UNPKG

1.46 MBJavaScriptView Raw
1/*! OpenPGP.js v5.3.1 - 2022-06-29 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
2const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3
4const doneWritingPromise = Symbol('doneWritingPromise');
5const doneWritingResolve = Symbol('doneWritingResolve');
6const doneWritingReject = Symbol('doneWritingReject');
7
8const readingIndex = Symbol('readingIndex');
9
10class ArrayStream extends Array {
11 constructor() {
12 super();
13 this[doneWritingPromise] = new Promise((resolve, reject) => {
14 this[doneWritingResolve] = resolve;
15 this[doneWritingReject] = reject;
16 });
17 this[doneWritingPromise].catch(() => {});
18 }
19}
20
21ArrayStream.prototype.getReader = function() {
22 if (this[readingIndex] === undefined) {
23 this[readingIndex] = 0;
24 }
25 return {
26 read: async () => {
27 await this[doneWritingPromise];
28 if (this[readingIndex] === this.length) {
29 return { value: undefined, done: true };
30 }
31 return { value: this[this[readingIndex]++], done: false };
32 }
33 };
34};
35
36ArrayStream.prototype.readToEnd = async function(join) {
37 await this[doneWritingPromise];
38 const result = join(this.slice(this[readingIndex]));
39 this.length = 0;
40 return result;
41};
42
43ArrayStream.prototype.clone = function() {
44 const clone = new ArrayStream();
45 clone[doneWritingPromise] = this[doneWritingPromise].then(() => {
46 clone.push(...this);
47 });
48 return clone;
49};
50
51/**
52 * Check whether data is an ArrayStream
53 * @param {Any} input data to check
54 * @returns {boolean}
55 */
56function isArrayStream(input) {
57 return input && input.getReader && Array.isArray(input);
58}
59
60/**
61 * A wrapper class over the native WritableStreamDefaultWriter.
62 * It also lets you "write data to" array streams instead of streams.
63 * @class
64 */
65function Writer(input) {
66 if (!isArrayStream(input)) {
67 const writer = input.getWriter();
68 const releaseLock = writer.releaseLock;
69 writer.releaseLock = () => {
70 writer.closed.catch(function() {});
71 releaseLock.call(writer);
72 };
73 return writer;
74 }
75 this.stream = input;
76}
77
78/**
79 * Write a chunk of data.
80 * @returns {Promise<undefined>}
81 * @async
82 */
83Writer.prototype.write = async function(chunk) {
84 this.stream.push(chunk);
85};
86
87/**
88 * Close the stream.
89 * @returns {Promise<undefined>}
90 * @async
91 */
92Writer.prototype.close = async function() {
93 this.stream[doneWritingResolve]();
94};
95
96/**
97 * Error the stream.
98 * @returns {Promise<Object>}
99 * @async
100 */
101Writer.prototype.abort = async function(reason) {
102 this.stream[doneWritingReject](reason);
103 return reason;
104};
105
106/**
107 * Release the writer's lock.
108 * @returns {undefined}
109 * @async
110 */
111Writer.prototype.releaseLock = function() {};
112
113const isNode = typeof globalThis.process === 'object' &&
114 typeof globalThis.process.versions === 'object';
115
116const NodeReadableStream = isNode && void('stream').Readable;
117
118/**
119 * Check whether data is a Stream, and if so of which type
120 * @param {Any} input data to check
121 * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}
122 */
123function isStream(input) {
124 if (isArrayStream(input)) {
125 return 'array';
126 }
127 if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
128 return 'web';
129 }
130 if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) {
131 return 'ponyfill';
132 }
133 if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
134 return 'node';
135 }
136 if (input && input.getReader) {
137 return 'web-like';
138 }
139 return false;
140}
141
142/**
143 * Check whether data is a Uint8Array
144 * @param {Any} input data to check
145 * @returns {Boolean}
146 */
147function isUint8Array(input) {
148 return Uint8Array.prototype.isPrototypeOf(input);
149}
150
151/**
152 * Concat Uint8Arrays
153 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
154 * @returns {Uint8array} Concatenated array
155 */
156function concatUint8Array(arrays) {
157 if (arrays.length === 1) return arrays[0];
158
159 let totalLength = 0;
160 for (let i = 0; i < arrays.length; i++) {
161 if (!isUint8Array(arrays[i])) {
162 throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
163 }
164
165 totalLength += arrays[i].length;
166 }
167
168 const result = new Uint8Array(totalLength);
169 let pos = 0;
170 arrays.forEach(function (element) {
171 result.set(element, pos);
172 pos += element.length;
173 });
174
175 return result;
176}
177
178const NodeBuffer = isNode && void('buffer').Buffer;
179const NodeReadableStream$1 = isNode && void('stream').Readable;
180
181/**
182 * Web / node stream conversion functions
183 * From https://github.com/gwicke/node-web-streams
184 */
185
186let nodeToWeb;
187let webToNode;
188
189if (NodeReadableStream$1) {
190
191 /**
192 * Convert a Node Readable Stream to a Web ReadableStream
193 * @param {Readable} nodeStream
194 * @returns {ReadableStream}
195 */
196 nodeToWeb = function(nodeStream) {
197 let canceled = false;
198 return new ReadableStream({
199 start(controller) {
200 nodeStream.pause();
201 nodeStream.on('data', chunk => {
202 if (canceled) {
203 return;
204 }
205 if (NodeBuffer.isBuffer(chunk)) {
206 chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
207 }
208 controller.enqueue(chunk);
209 nodeStream.pause();
210 });
211 nodeStream.on('end', () => {
212 if (canceled) {
213 return;
214 }
215 controller.close();
216 });
217 nodeStream.on('error', e => controller.error(e));
218 },
219 pull() {
220 nodeStream.resume();
221 },
222 cancel(reason) {
223 canceled = true;
224 nodeStream.destroy(reason);
225 }
226 });
227 };
228
229
230 class NodeReadable extends NodeReadableStream$1 {
231 constructor(webStream, options) {
232 super(options);
233 this._reader = getReader(webStream);
234 }
235
236 async _read(size) {
237 try {
238 while (true) {
239 const { done, value } = await this._reader.read();
240 if (done) {
241 this.push(null);
242 break;
243 }
244 if (!this.push(value) || this._cancelling) {
245 this._reading = false;
246 break;
247 }
248 }
249 } catch(e) {
250 this.emit('error', e);
251 }
252 }
253
254 _destroy(reason) {
255 this._reader.cancel(reason);
256 }
257 }
258
259 /**
260 * Convert a Web ReadableStream to a Node Readable Stream
261 * @param {ReadableStream} webStream
262 * @param {Object} options
263 * @returns {Readable}
264 */
265 webToNode = function(webStream, options) {
266 return new NodeReadable(webStream, options);
267 };
268
269}
270
271const doneReadingSet = new WeakSet();
272const externalBuffer = Symbol('externalBuffer');
273
274/**
275 * A wrapper class over the native ReadableStreamDefaultReader.
276 * This additionally implements pushing back data on the stream, which
277 * lets us implement peeking and a host of convenience functions.
278 * It also lets you read data other than streams, such as a Uint8Array.
279 * @class
280 */
281function Reader(input) {
282 this.stream = input;
283 if (input[externalBuffer]) {
284 this[externalBuffer] = input[externalBuffer].slice();
285 }
286 if (isArrayStream(input)) {
287 const reader = input.getReader();
288 this._read = reader.read.bind(reader);
289 this._releaseLock = () => {};
290 this._cancel = () => {};
291 return;
292 }
293 let streamType = isStream(input);
294 if (streamType === 'node') {
295 input = nodeToWeb(input);
296 }
297 if (streamType) {
298 const reader = input.getReader();
299 this._read = reader.read.bind(reader);
300 this._releaseLock = () => {
301 reader.closed.catch(function() {});
302 reader.releaseLock();
303 };
304 this._cancel = reader.cancel.bind(reader);
305 return;
306 }
307 let doneReading = false;
308 this._read = async () => {
309 if (doneReading || doneReadingSet.has(input)) {
310 return { value: undefined, done: true };
311 }
312 doneReading = true;
313 return { value: input, done: false };
314 };
315 this._releaseLock = () => {
316 if (doneReading) {
317 try {
318 doneReadingSet.add(input);
319 } catch(e) {}
320 }
321 };
322}
323
324/**
325 * Read a chunk of data.
326 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
327 * @async
328 */
329Reader.prototype.read = async function() {
330 if (this[externalBuffer] && this[externalBuffer].length) {
331 const value = this[externalBuffer].shift();
332 return { done: false, value };
333 }
334 return this._read();
335};
336
337/**
338 * Allow others to read the stream.
339 */
340Reader.prototype.releaseLock = function() {
341 if (this[externalBuffer]) {
342 this.stream[externalBuffer] = this[externalBuffer];
343 }
344 this._releaseLock();
345};
346
347/**
348 * Cancel the stream.
349 */
350Reader.prototype.cancel = function(reason) {
351 return this._cancel(reason);
352};
353
354/**
355 * Read up to and including the first \n character.
356 * @returns {Promise<String|Undefined>}
357 * @async
358 */
359Reader.prototype.readLine = async function() {
360 let buffer = [];
361 let returnVal;
362 while (!returnVal) {
363 let { done, value } = await this.read();
364 value += '';
365 if (done) {
366 if (buffer.length) return concat(buffer);
367 return;
368 }
369 const lineEndIndex = value.indexOf('\n') + 1;
370 if (lineEndIndex) {
371 returnVal = concat(buffer.concat(value.substr(0, lineEndIndex)));
372 buffer = [];
373 }
374 if (lineEndIndex !== value.length) {
375 buffer.push(value.substr(lineEndIndex));
376 }
377 }
378 this.unshift(...buffer);
379 return returnVal;
380};
381
382/**
383 * Read a single byte/character.
384 * @returns {Promise<Number|String|Undefined>}
385 * @async
386 */
387Reader.prototype.readByte = async function() {
388 const { done, value } = await this.read();
389 if (done) return;
390 const byte = value[0];
391 this.unshift(slice(value, 1));
392 return byte;
393};
394
395/**
396 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
397 * @returns {Promise<Uint8Array|String|Undefined>}
398 * @async
399 */
400Reader.prototype.readBytes = async function(length) {
401 const buffer = [];
402 let bufferLength = 0;
403 while (true) {
404 const { done, value } = await this.read();
405 if (done) {
406 if (buffer.length) return concat(buffer);
407 return;
408 }
409 buffer.push(value);
410 bufferLength += value.length;
411 if (bufferLength >= length) {
412 const bufferConcat = concat(buffer);
413 this.unshift(slice(bufferConcat, length));
414 return slice(bufferConcat, 0, length);
415 }
416 }
417};
418
419/**
420 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
421 * @returns {Promise<Uint8Array|String|Undefined>}
422 * @async
423 */
424Reader.prototype.peekBytes = async function(length) {
425 const bytes = await this.readBytes(length);
426 this.unshift(bytes);
427 return bytes;
428};
429
430/**
431 * Push data to the front of the stream.
432 * Data must have been read in the last call to read*.
433 * @param {...(Uint8Array|String|Undefined)} values
434 */
435Reader.prototype.unshift = function(...values) {
436 if (!this[externalBuffer]) {
437 this[externalBuffer] = [];
438 }
439 if (
440 values.length === 1 && isUint8Array(values[0]) &&
441 this[externalBuffer].length && values[0].length &&
442 this[externalBuffer][0].byteOffset >= values[0].length
443 ) {
444 this[externalBuffer][0] = new Uint8Array(
445 this[externalBuffer][0].buffer,
446 this[externalBuffer][0].byteOffset - values[0].length,
447 this[externalBuffer][0].byteLength + values[0].length
448 );
449 return;
450 }
451 this[externalBuffer].unshift(...values.filter(value => value && value.length));
452};
453
454/**
455 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
456 * @param {Function} join
457 * @returns {Promise<Uint8array|String|Any>} the return value of join()
458 * @async
459 */
460Reader.prototype.readToEnd = async function(join=concat) {
461 const result = [];
462 while (true) {
463 const { done, value } = await this.read();
464 if (done) break;
465 result.push(value);
466 }
467 return join(result);
468};
469
470let { ReadableStream, WritableStream, TransformStream } = globalThis;
471
472let toPonyfillReadable, toNativeReadable;
473
474async function loadStreamsPonyfill() {
475 if (TransformStream) {
476 return;
477 }
478
479 const [ponyfill, adapter] = await Promise.all([
480 Promise.resolve().then(function () { return ponyfill_es6; }),
481 Promise.resolve().then(function () { return webStreamsAdapter; })
482 ]);
483
484 ({ ReadableStream, WritableStream, TransformStream } = ponyfill);
485
486 const { createReadableStreamWrapper } = adapter;
487
488 if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {
489 toPonyfillReadable = createReadableStreamWrapper(ReadableStream);
490 toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);
491 }
492}
493
494const NodeBuffer$1 = isNode && void('buffer').Buffer;
495
496/**
497 * Convert data to Stream
498 * @param {ReadableStream|Uint8array|String} input data to convert
499 * @returns {ReadableStream} Converted data
500 */
501function toStream(input) {
502 let streamType = isStream(input);
503 if (streamType === 'node') {
504 return nodeToWeb(input);
505 }
506 if (streamType === 'web' && toPonyfillReadable) {
507 return toPonyfillReadable(input);
508 }
509 if (streamType) {
510 return input;
511 }
512 return new ReadableStream({
513 start(controller) {
514 controller.enqueue(input);
515 controller.close();
516 }
517 });
518}
519
520/**
521 * Convert data to ArrayStream
522 * @param {Object} input data to convert
523 * @returns {ArrayStream} Converted data
524 */
525function toArrayStream(input) {
526 if (isStream(input)) {
527 return input;
528 }
529 const stream = new ArrayStream();
530 (async () => {
531 const writer = getWriter(stream);
532 await writer.write(input);
533 await writer.close();
534 })();
535 return stream;
536}
537
538/**
539 * Concat a list of Uint8Arrays, Strings or Streams
540 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
541 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
542 * @returns {Uint8array|String|ReadableStream} Concatenated array
543 */
544function concat(list) {
545 if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {
546 return concatStream(list);
547 }
548 if (list.some(stream => isArrayStream(stream))) {
549 return concatArrayStream(list);
550 }
551 if (typeof list[0] === 'string') {
552 return list.join('');
553 }
554 if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) {
555 return NodeBuffer$1.concat(list);
556 }
557 return concatUint8Array(list);
558}
559
560/**
561 * Concat a list of Streams
562 * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
563 * @returns {ReadableStream} Concatenated list
564 */
565function concatStream(list) {
566 list = list.map(toStream);
567 const transform = transformWithCancel(async function(reason) {
568 await Promise.all(transforms.map(stream => cancel(stream, reason)));
569 });
570 let prev = Promise.resolve();
571 const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
572 prev = prev.then(() => pipe(readable, transform.writable, {
573 preventClose: i !== list.length - 1
574 }));
575 return prev;
576 }));
577 return transform.readable;
578}
579
580/**
581 * Concat a list of ArrayStreams
582 * @param {Array<ArrayStream|Uint8array|String>} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate
583 * @returns {ArrayStream} Concatenated streams
584 */
585function concatArrayStream(list) {
586 const result = new ArrayStream();
587 let prev = Promise.resolve();
588 list.forEach((stream, i) => {
589 prev = prev.then(() => pipe(stream, result, {
590 preventClose: i !== list.length - 1
591 }));
592 return prev;
593 });
594 return result;
595}
596
597/**
598 * Get a Reader
599 * @param {ReadableStream|Uint8array|String} input
600 * @returns {Reader}
601 */
602function getReader(input) {
603 return new Reader(input);
604}
605
606/**
607 * Get a Writer
608 * @param {WritableStream} input
609 * @returns {Writer}
610 */
611function getWriter(input) {
612 return new Writer(input);
613}
614
615/**
616 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
617 * @param {ReadableStream|Uint8array|String} input
618 * @param {WritableStream} target
619 * @param {Object} (optional) options
620 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
621 * @async
622 */
623async function pipe(input, target, {
624 preventClose = false,
625 preventAbort = false,
626 preventCancel = false
627} = {}) {
628 if (isStream(input) && !isArrayStream(input)) {
629 input = toStream(input);
630 try {
631 if (input[externalBuffer]) {
632 const writer = getWriter(target);
633 for (let i = 0; i < input[externalBuffer].length; i++) {
634 await writer.ready;
635 await writer.write(input[externalBuffer][i]);
636 }
637 writer.releaseLock();
638 }
639 await input.pipeTo(target, {
640 preventClose,
641 preventAbort,
642 preventCancel
643 });
644 } catch(e) {}
645 return;
646 }
647 input = toArrayStream(input);
648 const reader = getReader(input);
649 const writer = getWriter(target);
650 try {
651 while (true) {
652 await writer.ready;
653 const { done, value } = await reader.read();
654 if (done) {
655 if (!preventClose) await writer.close();
656 break;
657 }
658 await writer.write(value);
659 }
660 } catch (e) {
661 if (!preventAbort) await writer.abort(e);
662 } finally {
663 reader.releaseLock();
664 writer.releaseLock();
665 }
666}
667
668/**
669 * Pipe a readable stream through a transform stream.
670 * @param {ReadableStream|Uint8array|String} input
671 * @param {Object} (optional) options
672 * @returns {ReadableStream} transformed stream
673 */
674function transformRaw(input, options) {
675 const transformStream = new TransformStream(options);
676 pipe(input, transformStream.writable);
677 return transformStream.readable;
678}
679
680/**
681 * Create a cancelable TransformStream.
682 * @param {Function} cancel
683 * @returns {TransformStream}
684 */
685function transformWithCancel(cancel) {
686 let pulled = false;
687 let backpressureChangePromiseResolve;
688 let outputController;
689 return {
690 readable: new ReadableStream({
691 start(controller) {
692 outputController = controller;
693 },
694 pull() {
695 if (backpressureChangePromiseResolve) {
696 backpressureChangePromiseResolve();
697 } else {
698 pulled = true;
699 }
700 },
701 cancel
702 }, {highWaterMark: 0}),
703 writable: new WritableStream({
704 write: async function(chunk) {
705 outputController.enqueue(chunk);
706 if (!pulled) {
707 await new Promise(resolve => {
708 backpressureChangePromiseResolve = resolve;
709 });
710 backpressureChangePromiseResolve = null;
711 } else {
712 pulled = false;
713 }
714 },
715 close: outputController.close.bind(outputController),
716 abort: outputController.error.bind(outputController)
717 })
718 };
719}
720
721/**
722 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
723 * @param {ReadableStream|Uint8array|String} input
724 * @param {Function} process
725 * @param {Function} finish
726 * @returns {ReadableStream|Uint8array|String}
727 */
728function transform(input, process = () => undefined, finish = () => undefined) {
729 if (isArrayStream(input)) {
730 const output = new ArrayStream();
731 (async () => {
732 const writer = getWriter(output);
733 try {
734 const data = await readToEnd(input);
735 const result1 = process(data);
736 const result2 = finish();
737 let result;
738 if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);
739 else result = result1 !== undefined ? result1 : result2;
740 await writer.write(result);
741 await writer.close();
742 } catch (e) {
743 await writer.abort(e);
744 }
745 })();
746 return output;
747 }
748 if (isStream(input)) {
749 return transformRaw(input, {
750 async transform(value, controller) {
751 try {
752 const result = await process(value);
753 if (result !== undefined) controller.enqueue(result);
754 } catch(e) {
755 controller.error(e);
756 }
757 },
758 async flush(controller) {
759 try {
760 const result = await finish();
761 if (result !== undefined) controller.enqueue(result);
762 } catch(e) {
763 controller.error(e);
764 }
765 }
766 });
767 }
768 const result1 = process(input);
769 const result2 = finish();
770 if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
771 return result1 !== undefined ? result1 : result2;
772}
773
774/**
775 * Transform a stream using a helper function which is passed a readable and a writable stream.
776 * This function also maintains the possibility to cancel the input stream,
777 * and does so on cancelation of the output stream, despite cancelation
778 * normally being impossible when the input stream is being read from.
779 * @param {ReadableStream|Uint8array|String} input
780 * @param {Function} fn
781 * @returns {ReadableStream}
782 */
783function transformPair(input, fn) {
784 if (isStream(input) && !isArrayStream(input)) {
785 let incomingTransformController;
786 const incoming = new TransformStream({
787 start(controller) {
788 incomingTransformController = controller;
789 }
790 });
791
792 const pipeDonePromise = pipe(input, incoming.writable);
793
794 const outgoing = transformWithCancel(async function(reason) {
795 incomingTransformController.error(reason);
796 await pipeDonePromise;
797 await new Promise(setTimeout);
798 });
799 fn(incoming.readable, outgoing.writable);
800 return outgoing.readable;
801 }
802 input = toArrayStream(input);
803 const output = new ArrayStream();
804 fn(input, output);
805 return output;
806}
807
808/**
809 * Parse a stream using a helper function which is passed a Reader.
810 * The reader additionally has a remainder() method which returns a
811 * stream pointing to the remainder of input, and is linked to input
812 * for cancelation.
813 * @param {ReadableStream|Uint8array|String} input
814 * @param {Function} fn
815 * @returns {Any} the return value of fn()
816 */
817function parse(input, fn) {
818 let returnValue;
819 const transformed = transformPair(input, (readable, writable) => {
820 const reader = getReader(readable);
821 reader.remainder = () => {
822 reader.releaseLock();
823 pipe(readable, writable);
824 return transformed;
825 };
826 returnValue = fn(reader);
827 });
828 return returnValue;
829}
830
831/**
832 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
833 * Reading either of the two returned streams will pull from the input stream.
834 * The input stream will only be canceled if both of the returned streams are canceled.
835 * @param {ReadableStream|Uint8array|String} input
836 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
837 */
838function tee(input) {
839 if (isArrayStream(input)) {
840 throw new Error('ArrayStream cannot be tee()d, use clone() instead');
841 }
842 if (isStream(input)) {
843 const teed = toStream(input).tee();
844 teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
845 return teed;
846 }
847 return [slice(input), slice(input)];
848}
849
850/**
851 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
852 * Reading from the clone will pull from the input stream.
853 * The input stream will only be canceled if both the clone and the input stream are canceled.
854 * @param {ReadableStream|Uint8array|String} input
855 * @returns {ReadableStream|Uint8array|String} cloned input
856 */
857function clone(input) {
858 if (isArrayStream(input)) {
859 return input.clone();
860 }
861 if (isStream(input)) {
862 const teed = tee(input);
863 overwrite(input, teed[0]);
864 return teed[1];
865 }
866 return slice(input);
867}
868
869/**
870 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
871 * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
872 * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
873 * If the input stream is canceled, the clone will be errored.
874 * @param {ReadableStream|Uint8array|String} input
875 * @returns {ReadableStream|Uint8array|String} cloned input
876 */
877function passiveClone(input) {
878 if (isArrayStream(input)) {
879 return clone(input);
880 }
881 if (isStream(input)) {
882 return new ReadableStream({
883 start(controller) {
884 const transformed = transformPair(input, async (readable, writable) => {
885 const reader = getReader(readable);
886 const writer = getWriter(writable);
887 try {
888 while (true) {
889 await writer.ready;
890 const { done, value } = await reader.read();
891 if (done) {
892 try { controller.close(); } catch(e) {}
893 await writer.close();
894 return;
895 }
896 try { controller.enqueue(value); } catch(e) {}
897 await writer.write(value);
898 }
899 } catch(e) {
900 controller.error(e);
901 await writer.abort(e);
902 }
903 });
904 overwrite(input, transformed);
905 }
906 });
907 }
908 return slice(input);
909}
910
911/**
912 * Modify a stream object to point to a different stream object.
913 * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
914 * @param {ReadableStream} input
915 * @param {ReadableStream} clone
916 */
917function overwrite(input, clone) {
918 // Overwrite input.getReader, input.locked, etc to point to clone
919 Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {
920 if (name === 'constructor') {
921 return;
922 }
923 if (descriptor.value) {
924 descriptor.value = descriptor.value.bind(clone);
925 } else {
926 descriptor.get = descriptor.get.bind(clone);
927 }
928 Object.defineProperty(input, name, descriptor);
929 });
930}
931
932/**
933 * Return a stream pointing to a part of the input stream.
934 * @param {ReadableStream|Uint8array|String} input
935 * @returns {ReadableStream|Uint8array|String} clone
936 */
937function slice(input, begin=0, end=Infinity) {
938 if (isArrayStream(input)) {
939 throw new Error('Not implemented');
940 }
941 if (isStream(input)) {
942 if (begin >= 0 && end >= 0) {
943 let bytesRead = 0;
944 return transformRaw(input, {
945 transform(value, controller) {
946 if (bytesRead < end) {
947 if (bytesRead + value.length >= begin) {
948 controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
949 }
950 bytesRead += value.length;
951 } else {
952 controller.terminate();
953 }
954 }
955 });
956 }
957 if (begin < 0 && (end < 0 || end === Infinity)) {
958 let lastBytes = [];
959 return transform(input, value => {
960 if (value.length >= -begin) lastBytes = [value];
961 else lastBytes.push(value);
962 }, () => slice(concat(lastBytes), begin, end));
963 }
964 if (begin === 0 && end < 0) {
965 let lastBytes;
966 return transform(input, value => {
967 const returnValue = lastBytes ? concat([lastBytes, value]) : value;
968 if (returnValue.length >= -end) {
969 lastBytes = slice(returnValue, end);
970 return slice(returnValue, begin, end);
971 } else {
972 lastBytes = returnValue;
973 }
974 });
975 }
976 console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
977 return fromAsync(async () => slice(await readToEnd(input), begin, end));
978 }
979 if (input[externalBuffer]) {
980 input = concat(input[externalBuffer].concat([input]));
981 }
982 if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) {
983 if (end === Infinity) end = input.length;
984 return input.subarray(begin, end);
985 }
986 return input.slice(begin, end);
987}
988
989/**
990 * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).
991 * @param {ReadableStream|Uint8array|String} input
992 * @param {Function} join
993 * @returns {Promise<Uint8array|String|Any>} the return value of join()
994 * @async
995 */
996async function readToEnd(input, join=concat) {
997 if (isArrayStream(input)) {
998 return input.readToEnd(join);
999 }
1000 if (isStream(input)) {
1001 return getReader(input).readToEnd(join);
1002 }
1003 return input;
1004}
1005
1006/**
1007 * Cancel a stream.
1008 * @param {ReadableStream|Uint8array|String} input
1009 * @param {Any} reason
1010 * @returns {Promise<Any>} indicates when the stream has been canceled
1011 * @async
1012 */
1013async function cancel(input, reason) {
1014 if (isStream(input)) {
1015 if (input.cancel) {
1016 return input.cancel(reason);
1017 }
1018 if (input.destroy) {
1019 input.destroy(reason);
1020 await new Promise(setTimeout);
1021 return reason;
1022 }
1023 }
1024}
1025
1026/**
1027 * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.
1028 * @param {Function} fn
1029 * @returns {ArrayStream}
1030 */
1031function fromAsync(fn) {
1032 const arrayStream = new ArrayStream();
1033 (async () => {
1034 const writer = getWriter(arrayStream);
1035 try {
1036 await writer.write(await fn());
1037 await writer.close();
1038 } catch (e) {
1039 await writer.abort(e);
1040 }
1041 })();
1042 return arrayStream;
1043}
1044
1045/* eslint-disable new-cap */
1046
1047/**
1048 * @fileoverview
1049 * BigInteger implementation of basic operations
1050 * that wraps the native BigInt library.
1051 * Operations are not constant time,
1052 * but we try and limit timing leakage where we can
1053 * @module biginteger/native
1054 * @private
1055 */
1056
1057/**
1058 * @private
1059 */
1060class BigInteger {
1061 /**
1062 * Get a BigInteger (input must be big endian for strings and arrays)
1063 * @param {Number|String|Uint8Array} n - Value to convert
1064 * @throws {Error} on null or undefined input
1065 */
1066 constructor(n) {
1067 if (n === undefined) {
1068 throw new Error('Invalid BigInteger input');
1069 }
1070
1071 if (n instanceof Uint8Array) {
1072 const bytes = n;
1073 const hex = new Array(bytes.length);
1074 for (let i = 0; i < bytes.length; i++) {
1075 const hexByte = bytes[i].toString(16);
1076 hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
1077 }
1078 this.value = BigInt('0x0' + hex.join(''));
1079 } else {
1080 this.value = BigInt(n);
1081 }
1082 }
1083
1084 clone() {
1085 return new BigInteger(this.value);
1086 }
1087
1088 /**
1089 * BigInteger increment in place
1090 */
1091 iinc() {
1092 this.value++;
1093 return this;
1094 }
1095
1096 /**
1097 * BigInteger increment
1098 * @returns {BigInteger} this + 1.
1099 */
1100 inc() {
1101 return this.clone().iinc();
1102 }
1103
1104 /**
1105 * BigInteger decrement in place
1106 */
1107 idec() {
1108 this.value--;
1109 return this;
1110 }
1111
1112 /**
1113 * BigInteger decrement
1114 * @returns {BigInteger} this - 1.
1115 */
1116 dec() {
1117 return this.clone().idec();
1118 }
1119
1120 /**
1121 * BigInteger addition in place
1122 * @param {BigInteger} x - Value to add
1123 */
1124 iadd(x) {
1125 this.value += x.value;
1126 return this;
1127 }
1128
1129 /**
1130 * BigInteger addition
1131 * @param {BigInteger} x - Value to add
1132 * @returns {BigInteger} this + x.
1133 */
1134 add(x) {
1135 return this.clone().iadd(x);
1136 }
1137
1138 /**
1139 * BigInteger subtraction in place
1140 * @param {BigInteger} x - Value to subtract
1141 */
1142 isub(x) {
1143 this.value -= x.value;
1144 return this;
1145 }
1146
1147 /**
1148 * BigInteger subtraction
1149 * @param {BigInteger} x - Value to subtract
1150 * @returns {BigInteger} this - x.
1151 */
1152 sub(x) {
1153 return this.clone().isub(x);
1154 }
1155
1156 /**
1157 * BigInteger multiplication in place
1158 * @param {BigInteger} x - Value to multiply
1159 */
1160 imul(x) {
1161 this.value *= x.value;
1162 return this;
1163 }
1164
1165 /**
1166 * BigInteger multiplication
1167 * @param {BigInteger} x - Value to multiply
1168 * @returns {BigInteger} this * x.
1169 */
1170 mul(x) {
1171 return this.clone().imul(x);
1172 }
1173
1174 /**
1175 * Compute value modulo m, in place
1176 * @param {BigInteger} m - Modulo
1177 */
1178 imod(m) {
1179 this.value %= m.value;
1180 if (this.isNegative()) {
1181 this.iadd(m);
1182 }
1183 return this;
1184 }
1185
1186 /**
1187 * Compute value modulo m
1188 * @param {BigInteger} m - Modulo
1189 * @returns {BigInteger} this mod m.
1190 */
1191 mod(m) {
1192 return this.clone().imod(m);
1193 }
1194
1195 /**
1196 * Compute modular exponentiation using square and multiply
1197 * @param {BigInteger} e - Exponent
1198 * @param {BigInteger} n - Modulo
1199 * @returns {BigInteger} this ** e mod n.
1200 */
1201 modExp(e, n) {
1202 if (n.isZero()) throw Error('Modulo cannot be zero');
1203 if (n.isOne()) return new BigInteger(0);
1204 if (e.isNegative()) throw Error('Unsopported negative exponent');
1205
1206 let exp = e.value;
1207 let x = this.value;
1208
1209 x %= n.value;
1210 let r = BigInt(1);
1211 while (exp > BigInt(0)) {
1212 const lsb = exp & BigInt(1);
1213 exp >>= BigInt(1); // e / 2
1214 // Always compute multiplication step, to reduce timing leakage
1215 const rx = (r * x) % n.value;
1216 // Update r only if lsb is 1 (odd exponent)
1217 r = lsb ? rx : r;
1218 x = (x * x) % n.value; // Square
1219 }
1220 return new BigInteger(r);
1221 }
1222
1223
1224 /**
1225 * Compute the inverse of this value modulo n
1226 * Note: this and and n must be relatively prime
1227 * @param {BigInteger} n - Modulo
1228 * @returns {BigInteger} x such that this*x = 1 mod n
1229 * @throws {Error} if the inverse does not exist
1230 */
1231 modInv(n) {
1232 const { gcd, x } = this._egcd(n);
1233 if (!gcd.isOne()) {
1234 throw new Error('Inverse does not exist');
1235 }
1236 return x.add(n).mod(n);
1237 }
1238
1239 /**
1240 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
1241 * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
1242 * @param {BigInteger} b - Second operand
1243 * @returns {{ gcd, x, y: BigInteger }}
1244 */
1245 _egcd(b) {
1246 let x = BigInt(0);
1247 let y = BigInt(1);
1248 let xPrev = BigInt(1);
1249 let yPrev = BigInt(0);
1250
1251 let a = this.value;
1252 b = b.value;
1253
1254 while (b !== BigInt(0)) {
1255 const q = a / b;
1256 let tmp = x;
1257 x = xPrev - q * x;
1258 xPrev = tmp;
1259
1260 tmp = y;
1261 y = yPrev - q * y;
1262 yPrev = tmp;
1263
1264 tmp = b;
1265 b = a % b;
1266 a = tmp;
1267 }
1268
1269 return {
1270 x: new BigInteger(xPrev),
1271 y: new BigInteger(yPrev),
1272 gcd: new BigInteger(a)
1273 };
1274 }
1275
1276 /**
1277 * Compute greatest common divisor between this and n
1278 * @param {BigInteger} b - Operand
1279 * @returns {BigInteger} gcd
1280 */
1281 gcd(b) {
1282 let a = this.value;
1283 b = b.value;
1284 while (b !== BigInt(0)) {
1285 const tmp = b;
1286 b = a % b;
1287 a = tmp;
1288 }
1289 return new BigInteger(a);
1290 }
1291
1292 /**
1293 * Shift this to the left by x, in place
1294 * @param {BigInteger} x - Shift value
1295 */
1296 ileftShift(x) {
1297 this.value <<= x.value;
1298 return this;
1299 }
1300
1301 /**
1302 * Shift this to the left by x
1303 * @param {BigInteger} x - Shift value
1304 * @returns {BigInteger} this << x.
1305 */
1306 leftShift(x) {
1307 return this.clone().ileftShift(x);
1308 }
1309
1310 /**
1311 * Shift this to the right by x, in place
1312 * @param {BigInteger} x - Shift value
1313 */
1314 irightShift(x) {
1315 this.value >>= x.value;
1316 return this;
1317 }
1318
1319 /**
1320 * Shift this to the right by x
1321 * @param {BigInteger} x - Shift value
1322 * @returns {BigInteger} this >> x.
1323 */
1324 rightShift(x) {
1325 return this.clone().irightShift(x);
1326 }
1327
1328 /**
1329 * Whether this value is equal to x
1330 * @param {BigInteger} x
1331 * @returns {Boolean}
1332 */
1333 equal(x) {
1334 return this.value === x.value;
1335 }
1336
1337 /**
1338 * Whether this value is less than x
1339 * @param {BigInteger} x
1340 * @returns {Boolean}
1341 */
1342 lt(x) {
1343 return this.value < x.value;
1344 }
1345
1346 /**
1347 * Whether this value is less than or equal to x
1348 * @param {BigInteger} x
1349 * @returns {Boolean}
1350 */
1351 lte(x) {
1352 return this.value <= x.value;
1353 }
1354
1355 /**
1356 * Whether this value is greater than x
1357 * @param {BigInteger} x
1358 * @returns {Boolean}
1359 */
1360 gt(x) {
1361 return this.value > x.value;
1362 }
1363
1364 /**
1365 * Whether this value is greater than or equal to x
1366 * @param {BigInteger} x
1367 * @returns {Boolean}
1368 */
1369 gte(x) {
1370 return this.value >= x.value;
1371 }
1372
1373 isZero() {
1374 return this.value === BigInt(0);
1375 }
1376
1377 isOne() {
1378 return this.value === BigInt(1);
1379 }
1380
1381 isNegative() {
1382 return this.value < BigInt(0);
1383 }
1384
1385 isEven() {
1386 return !(this.value & BigInt(1));
1387 }
1388
1389 abs() {
1390 const res = this.clone();
1391 if (this.isNegative()) {
1392 res.value = -res.value;
1393 }
1394 return res;
1395 }
1396
1397 /**
1398 * Get this value as a string
1399 * @returns {String} this value.
1400 */
1401 toString() {
1402 return this.value.toString();
1403 }
1404
1405 /**
1406 * Get this value as an exact Number (max 53 bits)
1407 * Fails if this value is too large
1408 * @returns {Number}
1409 */
1410 toNumber() {
1411 const number = Number(this.value);
1412 if (number > Number.MAX_SAFE_INTEGER) {
1413 // We throw and error to conform with the bn.js implementation
1414 throw new Error('Number can only safely store up to 53 bits');
1415 }
1416 return number;
1417 }
1418
1419 /**
1420 * Get value of i-th bit
1421 * @param {Number} i - Bit index
1422 * @returns {Number} Bit value.
1423 */
1424 getBit(i) {
1425 const bit = (this.value >> BigInt(i)) & BigInt(1);
1426 return (bit === BigInt(0)) ? 0 : 1;
1427 }
1428
1429 /**
1430 * Compute bit length
1431 * @returns {Number} Bit length.
1432 */
1433 bitLength() {
1434 const zero = new BigInteger(0);
1435 const one = new BigInteger(1);
1436 const negOne = new BigInteger(-1);
1437
1438 // -1n >> -1n is -1n
1439 // 1n >> 1n is 0n
1440 const target = this.isNegative() ? negOne : zero;
1441 let bitlen = 1;
1442 const tmp = this.clone();
1443 while (!tmp.irightShift(one).equal(target)) {
1444 bitlen++;
1445 }
1446 return bitlen;
1447 }
1448
1449 /**
1450 * Compute byte length
1451 * @returns {Number} Byte length.
1452 */
1453 byteLength() {
1454 const zero = new BigInteger(0);
1455 const negOne = new BigInteger(-1);
1456
1457 const target = this.isNegative() ? negOne : zero;
1458 const eight = new BigInteger(8);
1459 let len = 1;
1460 const tmp = this.clone();
1461 while (!tmp.irightShift(eight).equal(target)) {
1462 len++;
1463 }
1464 return len;
1465 }
1466
1467 /**
1468 * Get Uint8Array representation of this number
1469 * @param {String} endian - Endianess of output array (defaults to 'be')
1470 * @param {Number} length - Of output array
1471 * @returns {Uint8Array}
1472 */
1473 toUint8Array(endian = 'be', length) {
1474 // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
1475 // this is faster than shift+mod iterations
1476 let hex = this.value.toString(16);
1477 if (hex.length % 2 === 1) {
1478 hex = '0' + hex;
1479 }
1480
1481 const rawLength = hex.length / 2;
1482 const bytes = new Uint8Array(length || rawLength);
1483 // parse hex
1484 const offset = length ? (length - rawLength) : 0;
1485 let i = 0;
1486 while (i < rawLength) {
1487 bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
1488 i++;
1489 }
1490
1491 if (endian !== 'be') {
1492 bytes.reverse();
1493 }
1494
1495 return bytes;
1496 }
1497}
1498
1499async function getBigInteger() {
1500 if (util.detectBigInt()) {
1501 return BigInteger;
1502 } else {
1503 const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; });
1504 return BigInteger;
1505 }
1506}
1507
1508// GPG4Browsers - An OpenPGP implementation in javascript
1509
1510const debugMode = (() => {
1511 try {
1512 return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env
1513 } catch (e) {}
1514 return false;
1515})();
1516
1517const util = {
1518 isString: function(data) {
1519 return typeof data === 'string' || String.prototype.isPrototypeOf(data);
1520 },
1521
1522 isArray: function(data) {
1523 return Array.prototype.isPrototypeOf(data);
1524 },
1525
1526 isUint8Array: isUint8Array,
1527
1528 isStream: isStream,
1529
1530 readNumber: function (bytes) {
1531 let n = 0;
1532 for (let i = 0; i < bytes.length; i++) {
1533 n += (256 ** i) * bytes[bytes.length - 1 - i];
1534 }
1535 return n;
1536 },
1537
1538 writeNumber: function (n, bytes) {
1539 const b = new Uint8Array(bytes);
1540 for (let i = 0; i < bytes; i++) {
1541 b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
1542 }
1543
1544 return b;
1545 },
1546
1547 readDate: function (bytes) {
1548 const n = util.readNumber(bytes);
1549 const d = new Date(n * 1000);
1550 return d;
1551 },
1552
1553 writeDate: function (time) {
1554 const numeric = Math.floor(time.getTime() / 1000);
1555
1556 return util.writeNumber(numeric, 4);
1557 },
1558
1559 normalizeDate: function (time = Date.now()) {
1560 return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
1561 },
1562
1563 /**
1564 * Read one MPI from bytes in input
1565 * @param {Uint8Array} bytes - Input data to parse
1566 * @returns {Uint8Array} Parsed MPI.
1567 */
1568 readMPI: function (bytes) {
1569 const bits = (bytes[0] << 8) | bytes[1];
1570 const bytelen = (bits + 7) >>> 3;
1571 return bytes.subarray(2, 2 + bytelen);
1572 },
1573
1574 /**
1575 * Left-pad Uint8Array to length by adding 0x0 bytes
1576 * @param {Uint8Array} bytes - Data to pad
1577 * @param {Number} length - Padded length
1578 * @returns {Uint8Array} Padded bytes.
1579 */
1580 leftPad(bytes, length) {
1581 const padded = new Uint8Array(length);
1582 const offset = length - bytes.length;
1583 padded.set(bytes, offset);
1584 return padded;
1585 },
1586
1587 /**
1588 * Convert a Uint8Array to an MPI-formatted Uint8Array.
1589 * @param {Uint8Array} bin - An array of 8-bit integers to convert
1590 * @returns {Uint8Array} MPI-formatted Uint8Array.
1591 */
1592 uint8ArrayToMPI: function (bin) {
1593 const bitSize = util.uint8ArrayBitLength(bin);
1594 if (bitSize === 0) {
1595 throw new Error('Zero MPI');
1596 }
1597 const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));
1598 const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);
1599 return util.concatUint8Array([prefix, stripped]);
1600 },
1601
1602 /**
1603 * Return bit length of the input data
1604 * @param {Uint8Array} bin input data (big endian)
1605 * @returns bit length
1606 */
1607 uint8ArrayBitLength: function (bin) {
1608 let i; // index of leading non-zero byte
1609 for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;
1610 if (i === bin.length) {
1611 return 0;
1612 }
1613 const stripped = bin.subarray(i);
1614 return (stripped.length - 1) * 8 + util.nbits(stripped[0]);
1615 },
1616
1617 /**
1618 * Convert a hex string to an array of 8-bit integers
1619 * @param {String} hex - A hex string to convert
1620 * @returns {Uint8Array} An array of 8-bit integers.
1621 */
1622 hexToUint8Array: function (hex) {
1623 const result = new Uint8Array(hex.length >> 1);
1624 for (let k = 0; k < hex.length >> 1; k++) {
1625 result[k] = parseInt(hex.substr(k << 1, 2), 16);
1626 }
1627 return result;
1628 },
1629
1630 /**
1631 * Convert an array of 8-bit integers to a hex string
1632 * @param {Uint8Array} bytes - Array of 8-bit integers to convert
1633 * @returns {String} Hexadecimal representation of the array.
1634 */
1635 uint8ArrayToHex: function (bytes) {
1636 const r = [];
1637 const e = bytes.length;
1638 let c = 0;
1639 let h;
1640 while (c < e) {
1641 h = bytes[c++].toString(16);
1642 while (h.length < 2) {
1643 h = '0' + h;
1644 }
1645 r.push('' + h);
1646 }
1647 return r.join('');
1648 },
1649
1650 /**
1651 * Convert a string to an array of 8-bit integers
1652 * @param {String} str - String to convert
1653 * @returns {Uint8Array} An array of 8-bit integers.
1654 */
1655 stringToUint8Array: function (str) {
1656 return transform(str, str => {
1657 if (!util.isString(str)) {
1658 throw new Error('stringToUint8Array: Data must be in the form of a string');
1659 }
1660
1661 const result = new Uint8Array(str.length);
1662 for (let i = 0; i < str.length; i++) {
1663 result[i] = str.charCodeAt(i);
1664 }
1665 return result;
1666 });
1667 },
1668
1669 /**
1670 * Convert an array of 8-bit integers to a string
1671 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
1672 * @returns {String} String representation of the array.
1673 */
1674 uint8ArrayToString: function (bytes) {
1675 bytes = new Uint8Array(bytes);
1676 const result = [];
1677 const bs = 1 << 14;
1678 const j = bytes.length;
1679
1680 for (let i = 0; i < j; i += bs) {
1681 result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
1682 }
1683 return result.join('');
1684 },
1685
1686 /**
1687 * Convert a native javascript string to a Uint8Array of utf8 bytes
1688 * @param {String|ReadableStream} str - The string to convert
1689 * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
1690 */
1691 encodeUTF8: function (str) {
1692 const encoder = new TextEncoder('utf-8');
1693 // eslint-disable-next-line no-inner-declarations
1694 function process(value, lastChunk = false) {
1695 return encoder.encode(value, { stream: !lastChunk });
1696 }
1697 return transform(str, process, () => process('', true));
1698 },
1699
1700 /**
1701 * Convert a Uint8Array of utf8 bytes to a native javascript string
1702 * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
1703 * @returns {String|ReadableStream} A native javascript string.
1704 */
1705 decodeUTF8: function (utf8) {
1706 const decoder = new TextDecoder('utf-8');
1707 // eslint-disable-next-line no-inner-declarations
1708 function process(value, lastChunk = false) {
1709 return decoder.decode(value, { stream: !lastChunk });
1710 }
1711 return transform(utf8, process, () => process(new Uint8Array(), true));
1712 },
1713
1714 /**
1715 * Concat a list of Uint8Arrays, Strings or Streams
1716 * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
1717 * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
1718 * @returns {Uint8Array|String|ReadableStream} Concatenated array.
1719 */
1720 concat: concat,
1721
1722 /**
1723 * Concat Uint8Arrays
1724 * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
1725 * @returns {Uint8Array} Concatenated array.
1726 */
1727 concatUint8Array: concatUint8Array,
1728
1729 /**
1730 * Check Uint8Array equality
1731 * @param {Uint8Array} array1 - First array
1732 * @param {Uint8Array} array2 - Second array
1733 * @returns {Boolean} Equality.
1734 */
1735 equalsUint8Array: function (array1, array2) {
1736 if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
1737 throw new Error('Data must be in the form of a Uint8Array');
1738 }
1739
1740 if (array1.length !== array2.length) {
1741 return false;
1742 }
1743
1744 for (let i = 0; i < array1.length; i++) {
1745 if (array1[i] !== array2[i]) {
1746 return false;
1747 }
1748 }
1749 return true;
1750 },
1751
1752 /**
1753 * Calculates a 16bit sum of a Uint8Array by adding each character
1754 * codes modulus 65535
1755 * @param {Uint8Array} Uint8Array - To create a sum of
1756 * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
1757 */
1758 writeChecksum: function (text) {
1759 let s = 0;
1760 for (let i = 0; i < text.length; i++) {
1761 s = (s + text[i]) & 0xFFFF;
1762 }
1763 return util.writeNumber(s, 2);
1764 },
1765
1766 /**
1767 * Helper function to print a debug message. Debug
1768 * messages are only printed if
1769 * @param {String} str - String of the debug message
1770 */
1771 printDebug: function (str) {
1772 if (debugMode) {
1773 console.log(str);
1774 }
1775 },
1776
1777 /**
1778 * Helper function to print a debug error. Debug
1779 * messages are only printed if
1780 * @param {String} str - String of the debug message
1781 */
1782 printDebugError: function (error) {
1783 if (debugMode) {
1784 console.error(error);
1785 }
1786 },
1787
1788 // returns bit length of the integer x
1789 nbits: function (x) {
1790 let r = 1;
1791 let t = x >>> 16;
1792 if (t !== 0) {
1793 x = t;
1794 r += 16;
1795 }
1796 t = x >> 8;
1797 if (t !== 0) {
1798 x = t;
1799 r += 8;
1800 }
1801 t = x >> 4;
1802 if (t !== 0) {
1803 x = t;
1804 r += 4;
1805 }
1806 t = x >> 2;
1807 if (t !== 0) {
1808 x = t;
1809 r += 2;
1810 }
1811 t = x >> 1;
1812 if (t !== 0) {
1813 x = t;
1814 r += 1;
1815 }
1816 return r;
1817 },
1818
1819 /**
1820 * If S[1] == 0, then double(S) == (S[2..128] || 0);
1821 * otherwise, double(S) == (S[2..128] || 0) xor
1822 * (zeros(120) || 10000111).
1823 *
1824 * Both OCB and EAX (through CMAC) require this function to be constant-time.
1825 *
1826 * @param {Uint8Array} data
1827 */
1828 double: function(data) {
1829 const doubleVar = new Uint8Array(data.length);
1830 const last = data.length - 1;
1831 for (let i = 0; i < last; i++) {
1832 doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
1833 }
1834 doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
1835 return doubleVar;
1836 },
1837
1838 /**
1839 * Shift a Uint8Array to the right by n bits
1840 * @param {Uint8Array} array - The array to shift
1841 * @param {Integer} bits - Amount of bits to shift (MUST be smaller
1842 * than 8)
1843 * @returns {String} Resulting array.
1844 */
1845 shiftRight: function (array, bits) {
1846 if (bits) {
1847 for (let i = array.length - 1; i >= 0; i--) {
1848 array[i] >>= bits;
1849 if (i > 0) {
1850 array[i] |= (array[i - 1] << (8 - bits));
1851 }
1852 }
1853 }
1854 return array;
1855 },
1856
1857 /**
1858 * Get native Web Cryptography api, only the current version of the spec.
1859 * @returns {Object} The SubtleCrypto api or 'undefined'.
1860 */
1861 getWebCrypto: function() {
1862 return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
1863 },
1864
1865 /**
1866 * Detect native BigInt support
1867 */
1868 detectBigInt: () => typeof BigInt !== 'undefined',
1869
1870 /**
1871 * Get BigInteger class
1872 * It wraps the native BigInt type if it's available
1873 * Otherwise it relies on bn.js
1874 * @returns {BigInteger}
1875 * @async
1876 */
1877 getBigInteger,
1878
1879 /**
1880 * Get native Node.js crypto api.
1881 * @returns {Object} The crypto module or 'undefined'.
1882 */
1883 getNodeCrypto: function() {
1884 return void('crypto');
1885 },
1886
1887 getNodeZlib: function() {
1888 return void('zlib');
1889 },
1890
1891 /**
1892 * Get native Node.js Buffer constructor. This should be used since
1893 * Buffer is not available under browserify.
1894 * @returns {Function} The Buffer constructor or 'undefined'.
1895 */
1896 getNodeBuffer: function() {
1897 return ({}).Buffer;
1898 },
1899
1900 getHardwareConcurrency: function() {
1901 if (typeof navigator !== 'undefined') {
1902 return navigator.hardwareConcurrency || 1;
1903 }
1904
1905 const os = void('os'); // Assume we're on Node.js.
1906 return os.cpus().length;
1907 },
1908
1909 isEmailAddress: function(data) {
1910 if (!util.isString(data)) {
1911 return false;
1912 }
1913 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]+)))$/;
1914 return re.test(data);
1915 },
1916
1917 /**
1918 * Normalize line endings to <CR><LF>
1919 * Support any encoding where CR=0x0D, LF=0x0A
1920 */
1921 canonicalizeEOL: function(data) {
1922 const CR = 13;
1923 const LF = 10;
1924 let carryOverCR = false;
1925
1926 return transform(data, bytes => {
1927 if (carryOverCR) {
1928 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1929 }
1930
1931 if (bytes[bytes.length - 1] === CR) {
1932 carryOverCR = true;
1933 bytes = bytes.subarray(0, -1);
1934 } else {
1935 carryOverCR = false;
1936 }
1937
1938 let index;
1939 const indices = [];
1940 for (let i = 0; ; i = index) {
1941 index = bytes.indexOf(LF, i) + 1;
1942 if (index) {
1943 if (bytes[index - 2] !== CR) indices.push(index);
1944 } else {
1945 break;
1946 }
1947 }
1948 if (!indices.length) {
1949 return bytes;
1950 }
1951
1952 const normalized = new Uint8Array(bytes.length + indices.length);
1953 let j = 0;
1954 for (let i = 0; i < indices.length; i++) {
1955 const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
1956 normalized.set(sub, j);
1957 j += sub.length;
1958 normalized[j - 1] = CR;
1959 normalized[j] = LF;
1960 j++;
1961 }
1962 normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
1963 return normalized;
1964 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
1965 },
1966
1967 /**
1968 * Convert line endings from canonicalized <CR><LF> to native <LF>
1969 * Support any encoding where CR=0x0D, LF=0x0A
1970 */
1971 nativeEOL: function(data) {
1972 const CR = 13;
1973 const LF = 10;
1974 let carryOverCR = false;
1975
1976 return transform(data, bytes => {
1977 if (carryOverCR && bytes[0] !== LF) {
1978 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1979 } else {
1980 bytes = new Uint8Array(bytes); // Don't mutate passed bytes
1981 }
1982
1983 if (bytes[bytes.length - 1] === CR) {
1984 carryOverCR = true;
1985 bytes = bytes.subarray(0, -1);
1986 } else {
1987 carryOverCR = false;
1988 }
1989
1990 let index;
1991 let j = 0;
1992 for (let i = 0; i !== bytes.length; i = index) {
1993 index = bytes.indexOf(CR, i) + 1;
1994 if (!index) index = bytes.length;
1995 const last = index - (bytes[index] === LF ? 1 : 0);
1996 if (i) bytes.copyWithin(j, i, last);
1997 j += last - i;
1998 }
1999 return bytes.subarray(0, j);
2000 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
2001 },
2002
2003 /**
2004 * Remove trailing spaces and tabs from each line
2005 */
2006 removeTrailingSpaces: function(text) {
2007 return text.split('\n').map(line => {
2008 let i = line.length - 1;
2009 for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--);
2010 return line.substr(0, i + 1);
2011 }).join('\n');
2012 },
2013
2014 wrapError: function(message, error) {
2015 if (!error) {
2016 return new Error(message);
2017 }
2018
2019 // update error message
2020 try {
2021 error.message = message + ': ' + error.message;
2022 } catch (e) {}
2023
2024 return error;
2025 },
2026
2027 /**
2028 * Map allowed packet tags to corresponding classes
2029 * Meant to be used to format `allowedPacket` for Packetlist.read
2030 * @param {Array<Object>} allowedClasses
2031 * @returns {Object} map from enum.packet to corresponding *Packet class
2032 */
2033 constructAllowedPackets: function(allowedClasses) {
2034 const map = {};
2035 allowedClasses.forEach(PacketClass => {
2036 if (!PacketClass.tag) {
2037 throw new Error('Invalid input: expected a packet class');
2038 }
2039 map[PacketClass.tag] = PacketClass;
2040 });
2041 return map;
2042 },
2043
2044 /**
2045 * Return a Promise that will resolve as soon as one of the promises in input resolves
2046 * or will reject if all input promises all rejected
2047 * (similar to Promise.any, but with slightly different error handling)
2048 * @param {Array<Promise>} promises
2049 * @return {Promise<Any>} Promise resolving to the result of the fastest fulfilled promise
2050 * or rejected with the Error of the last resolved Promise (if all promises are rejected)
2051 */
2052 anyPromise: function(promises) {
2053 return new Promise(async (resolve, reject) => {
2054 let exception;
2055 await Promise.all(promises.map(async promise => {
2056 try {
2057 resolve(await promise);
2058 } catch (e) {
2059 exception = e;
2060 }
2061 }));
2062 reject(exception);
2063 });
2064 },
2065
2066 /**
2067 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2068 * @param {Boolean} cond
2069 * @param {Uint8Array} a
2070 * @param {Uint8Array} b
2071 * @returns `a` if `cond` is true, `b` otherwise
2072 */
2073 selectUint8Array: function(cond, a, b) {
2074 const length = Math.max(a.length, b.length);
2075 const result = new Uint8Array(length);
2076 let end = 0;
2077 for (let i = 0; i < result.length; i++) {
2078 result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));
2079 end += (cond & i < a.length) | ((1 - cond) & i < b.length);
2080 }
2081 return result.subarray(0, end);
2082 },
2083 /**
2084 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2085 * NB: it only supports `a, b` with values between 0-255.
2086 * @param {Boolean} cond
2087 * @param {Uint8} a
2088 * @param {Uint8} b
2089 * @returns `a` if `cond` is true, `b` otherwise
2090 */
2091 selectUint8: function(cond, a, b) {
2092 return (a & (256 - cond)) | (b & (255 + cond));
2093 }
2094};
2095
2096/* OpenPGP radix-64/base64 string encoding/decoding
2097 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
2098 * version 1.0, check www.haneWIN.de for the latest version
2099 *
2100 * This software is provided as-is, without express or implied warranty.
2101 * Permission to use, copy, modify, distribute or sell this software, with or
2102 * without fee, for any purpose and by any individual or organization, is hereby
2103 * granted, provided that the above copyright notice and this paragraph appear
2104 * in all copies. Distribution as a part of an application or binary must
2105 * include the above copyright notice in the documentation and/or other materials
2106 * provided with the application or distribution.
2107 */
2108
2109const Buffer = util.getNodeBuffer();
2110
2111let encodeChunk;
2112let decodeChunk;
2113if (Buffer) {
2114 encodeChunk = buf => Buffer.from(buf).toString('base64');
2115 decodeChunk = str => {
2116 const b = Buffer.from(str, 'base64');
2117 return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
2118 };
2119} else {
2120 encodeChunk = buf => btoa(util.uint8ArrayToString(buf));
2121 decodeChunk = str => util.stringToUint8Array(atob(str));
2122}
2123
2124/**
2125 * Convert binary array to radix-64
2126 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
2127 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
2128 * @static
2129 */
2130function encode(data) {
2131 let buf = new Uint8Array();
2132 return transform(data, value => {
2133 buf = util.concatUint8Array([buf, value]);
2134 const r = [];
2135 const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
2136 const lines = Math.floor(buf.length / bytesPerLine);
2137 const bytes = lines * bytesPerLine;
2138 const encoded = encodeChunk(buf.subarray(0, bytes));
2139 for (let i = 0; i < lines; i++) {
2140 r.push(encoded.substr(i * 60, 60));
2141 r.push('\n');
2142 }
2143 buf = buf.subarray(bytes);
2144 return r.join('');
2145 }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
2146}
2147
2148/**
2149 * Convert radix-64 to binary array
2150 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
2151 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
2152 * @static
2153 */
2154function decode(data) {
2155 let buf = '';
2156 return transform(data, value => {
2157 buf += value;
2158
2159 // Count how many whitespace characters there are in buf
2160 let spaces = 0;
2161 const spacechars = [' ', '\t', '\r', '\n'];
2162 for (let i = 0; i < spacechars.length; i++) {
2163 const spacechar = spacechars[i];
2164 for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
2165 spaces++;
2166 }
2167 }
2168
2169 // Backtrack until we have 4n non-whitespace characters
2170 // that we can safely base64-decode
2171 let length = buf.length;
2172 for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
2173 if (spacechars.includes(buf[length])) spaces--;
2174 }
2175
2176 const decoded = decodeChunk(buf.substr(0, length));
2177 buf = buf.substr(length);
2178 return decoded;
2179 }, () => decodeChunk(buf));
2180}
2181
2182/**
2183 * Convert a Base-64 encoded string an array of 8-bit integer
2184 *
2185 * Note: accepts both Radix-64 and URL-safe strings
2186 * @param {String} base64 - Base-64 encoded string to convert
2187 * @returns {Uint8Array} An array of 8-bit integers.
2188 */
2189function b64ToUint8Array(base64) {
2190 return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
2191}
2192
2193/**
2194 * Convert an array of 8-bit integer to a Base-64 encoded string
2195 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
2196 * @param {bool} url - If true, output is URL-safe
2197 * @returns {String} Base-64 encoded string.
2198 */
2199function uint8ArrayToB64(bytes, url) {
2200 let encoded = encode(bytes).replace(/[\r\n]/g, '');
2201 if (url) {
2202 encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
2203 }
2204 return encoded;
2205}
2206
2207/**
2208 * @module enums
2209 */
2210
2211const byValue = Symbol('byValue');
2212
2213var enums = {
2214
2215 /** Maps curve names under various standards to one
2216 * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
2217 * @enum {String}
2218 * @readonly
2219 */
2220 curve: {
2221 /** NIST P-256 Curve */
2222 'p256': 'p256',
2223 'P-256': 'p256',
2224 'secp256r1': 'p256',
2225 'prime256v1': 'p256',
2226 '1.2.840.10045.3.1.7': 'p256',
2227 '2a8648ce3d030107': 'p256',
2228 '2A8648CE3D030107': 'p256',
2229
2230 /** NIST P-384 Curve */
2231 'p384': 'p384',
2232 'P-384': 'p384',
2233 'secp384r1': 'p384',
2234 '1.3.132.0.34': 'p384',
2235 '2b81040022': 'p384',
2236 '2B81040022': 'p384',
2237
2238 /** NIST P-521 Curve */
2239 'p521': 'p521',
2240 'P-521': 'p521',
2241 'secp521r1': 'p521',
2242 '1.3.132.0.35': 'p521',
2243 '2b81040023': 'p521',
2244 '2B81040023': 'p521',
2245
2246 /** SECG SECP256k1 Curve */
2247 'secp256k1': 'secp256k1',
2248 '1.3.132.0.10': 'secp256k1',
2249 '2b8104000a': 'secp256k1',
2250 '2B8104000A': 'secp256k1',
2251
2252 /** Ed25519 */
2253 'ED25519': 'ed25519',
2254 'ed25519': 'ed25519',
2255 'Ed25519': 'ed25519',
2256 '1.3.6.1.4.1.11591.15.1': 'ed25519',
2257 '2b06010401da470f01': 'ed25519',
2258 '2B06010401DA470F01': 'ed25519',
2259
2260 /** Curve25519 */
2261 'X25519': 'curve25519',
2262 'cv25519': 'curve25519',
2263 'curve25519': 'curve25519',
2264 'Curve25519': 'curve25519',
2265 '1.3.6.1.4.1.3029.1.5.1': 'curve25519',
2266 '2b060104019755010501': 'curve25519',
2267 '2B060104019755010501': 'curve25519',
2268
2269 /** BrainpoolP256r1 Curve */
2270 'brainpoolP256r1': 'brainpoolP256r1',
2271 '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',
2272 '2b2403030208010107': 'brainpoolP256r1',
2273 '2B2403030208010107': 'brainpoolP256r1',
2274
2275 /** BrainpoolP384r1 Curve */
2276 'brainpoolP384r1': 'brainpoolP384r1',
2277 '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',
2278 '2b240303020801010b': 'brainpoolP384r1',
2279 '2B240303020801010B': 'brainpoolP384r1',
2280
2281 /** BrainpoolP512r1 Curve */
2282 'brainpoolP512r1': 'brainpoolP512r1',
2283 '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',
2284 '2b240303020801010d': 'brainpoolP512r1',
2285 '2B240303020801010D': 'brainpoolP512r1'
2286 },
2287
2288 /** A string to key specifier type
2289 * @enum {Integer}
2290 * @readonly
2291 */
2292 s2k: {
2293 simple: 0,
2294 salted: 1,
2295 iterated: 3,
2296 gnu: 101
2297 },
2298
2299 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
2300 * @enum {Integer}
2301 * @readonly
2302 */
2303 publicKey: {
2304 /** RSA (Encrypt or Sign) [HAC] */
2305 rsaEncryptSign: 1,
2306 /** RSA (Encrypt only) [HAC] */
2307 rsaEncrypt: 2,
2308 /** RSA (Sign only) [HAC] */
2309 rsaSign: 3,
2310 /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
2311 elgamal: 16,
2312 /** DSA (Sign only) [FIPS186] [HAC] */
2313 dsa: 17,
2314 /** ECDH (Encrypt only) [RFC6637] */
2315 ecdh: 18,
2316 /** ECDSA (Sign only) [RFC6637] */
2317 ecdsa: 19,
2318 /** EdDSA (Sign only)
2319 * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
2320 eddsa: 22,
2321 /** Reserved for AEDH */
2322 aedh: 23,
2323 /** Reserved for AEDSA */
2324 aedsa: 24
2325 },
2326
2327 /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
2328 * @enum {Integer}
2329 * @readonly
2330 */
2331 symmetric: {
2332 plaintext: 0,
2333 /** Not implemented! */
2334 idea: 1,
2335 tripledes: 2,
2336 cast5: 3,
2337 blowfish: 4,
2338 aes128: 7,
2339 aes192: 8,
2340 aes256: 9,
2341 twofish: 10
2342 },
2343
2344 /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
2345 * @enum {Integer}
2346 * @readonly
2347 */
2348 compression: {
2349 uncompressed: 0,
2350 /** RFC1951 */
2351 zip: 1,
2352 /** RFC1950 */
2353 zlib: 2,
2354 bzip2: 3
2355 },
2356
2357 /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
2358 * @enum {Integer}
2359 * @readonly
2360 */
2361 hash: {
2362 md5: 1,
2363 sha1: 2,
2364 ripemd: 3,
2365 sha256: 8,
2366 sha384: 9,
2367 sha512: 10,
2368 sha224: 11
2369 },
2370
2371 /** A list of hash names as accepted by webCrypto functions.
2372 * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
2373 * @enum {String}
2374 */
2375 webHash: {
2376 'SHA-1': 2,
2377 'SHA-256': 8,
2378 'SHA-384': 9,
2379 'SHA-512': 10
2380 },
2381
2382 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
2383 * @enum {Integer}
2384 * @readonly
2385 */
2386 aead: {
2387 eax: 1,
2388 ocb: 2,
2389 experimentalGCM: 100 // Private algorithm
2390 },
2391
2392 /** A list of packet types and numeric tags associated with them.
2393 * @enum {Integer}
2394 * @readonly
2395 */
2396 packet: {
2397 publicKeyEncryptedSessionKey: 1,
2398 signature: 2,
2399 symEncryptedSessionKey: 3,
2400 onePassSignature: 4,
2401 secretKey: 5,
2402 publicKey: 6,
2403 secretSubkey: 7,
2404 compressedData: 8,
2405 symmetricallyEncryptedData: 9,
2406 marker: 10,
2407 literalData: 11,
2408 trust: 12,
2409 userID: 13,
2410 publicSubkey: 14,
2411 userAttribute: 17,
2412 symEncryptedIntegrityProtectedData: 18,
2413 modificationDetectionCode: 19,
2414 aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
2415 },
2416
2417 /** Data types in the literal packet
2418 * @enum {Integer}
2419 * @readonly
2420 */
2421 literal: {
2422 /** Binary data 'b' */
2423 binary: 'b'.charCodeAt(),
2424 /** Text data 't' */
2425 text: 't'.charCodeAt(),
2426 /** Utf8 data 'u' */
2427 utf8: 'u'.charCodeAt(),
2428 /** MIME message body part 'm' */
2429 mime: 'm'.charCodeAt()
2430 },
2431
2432
2433 /** One pass signature packet type
2434 * @enum {Integer}
2435 * @readonly
2436 */
2437 signature: {
2438 /** 0x00: Signature of a binary document. */
2439 binary: 0,
2440 /** 0x01: Signature of a canonical text document.
2441 *
2442 * Canonicalyzing the document by converting line endings. */
2443 text: 1,
2444 /** 0x02: Standalone signature.
2445 *
2446 * This signature is a signature of only its own subpacket contents.
2447 * It is calculated identically to a signature over a zero-lengh
2448 * binary document. Note that it doesn't make sense to have a V3
2449 * standalone signature. */
2450 standalone: 2,
2451 /** 0x10: Generic certification of a User ID and Public-Key packet.
2452 *
2453 * The issuer of this certification does not make any particular
2454 * assertion as to how well the certifier has checked that the owner
2455 * of the key is in fact the person described by the User ID. */
2456 certGeneric: 16,
2457 /** 0x11: Persona certification of a User ID and Public-Key packet.
2458 *
2459 * The issuer of this certification has not done any verification of
2460 * the claim that the owner of this key is the User ID specified. */
2461 certPersona: 17,
2462 /** 0x12: Casual certification of a User ID and Public-Key packet.
2463 *
2464 * The issuer of this certification has done some casual
2465 * verification of the claim of identity. */
2466 certCasual: 18,
2467 /** 0x13: Positive certification of a User ID and Public-Key packet.
2468 *
2469 * The issuer of this certification has done substantial
2470 * verification of the claim of identity.
2471 *
2472 * Most OpenPGP implementations make their "key signatures" as 0x10
2473 * certifications. Some implementations can issue 0x11-0x13
2474 * certifications, but few differentiate between the types. */
2475 certPositive: 19,
2476 /** 0x30: Certification revocation signature
2477 *
2478 * This signature revokes an earlier User ID certification signature
2479 * (signature class 0x10 through 0x13) or direct-key signature
2480 * (0x1F). It should be issued by the same key that issued the
2481 * revoked signature or an authorized revocation key. The signature
2482 * is computed over the same data as the certificate that it
2483 * revokes, and should have a later creation date than that
2484 * certificate. */
2485 certRevocation: 48,
2486 /** 0x18: Subkey Binding Signature
2487 *
2488 * This signature is a statement by the top-level signing key that
2489 * indicates that it owns the subkey. This signature is calculated
2490 * directly on the primary key and subkey, and not on any User ID or
2491 * other packets. A signature that binds a signing subkey MUST have
2492 * an Embedded Signature subpacket in this binding signature that
2493 * contains a 0x19 signature made by the signing subkey on the
2494 * primary key and subkey. */
2495 subkeyBinding: 24,
2496 /** 0x19: Primary Key Binding Signature
2497 *
2498 * This signature is a statement by a signing subkey, indicating
2499 * that it is owned by the primary key and subkey. This signature
2500 * is calculated the same way as a 0x18 signature: directly on the
2501 * primary key and subkey, and not on any User ID or other packets.
2502 *
2503 * When a signature is made over a key, the hash data starts with the
2504 * octet 0x99, followed by a two-octet length of the key, and then body
2505 * of the key packet. (Note that this is an old-style packet header for
2506 * a key packet with two-octet length.) A subkey binding signature
2507 * (type 0x18) or primary key binding signature (type 0x19) then hashes
2508 * the subkey using the same format as the main key (also using 0x99 as
2509 * the first octet). */
2510 keyBinding: 25,
2511 /** 0x1F: Signature directly on a key
2512 *
2513 * This signature is calculated directly on a key. It binds the
2514 * information in the Signature subpackets to the key, and is
2515 * appropriate to be used for subpackets that provide information
2516 * about the key, such as the Revocation Key subpacket. It is also
2517 * appropriate for statements that non-self certifiers want to make
2518 * about the key itself, rather than the binding between a key and a
2519 * name. */
2520 key: 31,
2521 /** 0x20: Key revocation signature
2522 *
2523 * The signature is calculated directly on the key being revoked. A
2524 * revoked key is not to be used. Only revocation signatures by the
2525 * key being revoked, or by an authorized revocation key, should be
2526 * considered valid revocation signatures.a */
2527 keyRevocation: 32,
2528 /** 0x28: Subkey revocation signature
2529 *
2530 * The signature is calculated directly on the subkey being revoked.
2531 * A revoked subkey is not to be used. Only revocation signatures
2532 * by the top-level signature key that is bound to this subkey, or
2533 * by an authorized revocation key, should be considered valid
2534 * revocation signatures.
2535 *
2536 * Key revocation signatures (types 0x20 and 0x28)
2537 * hash only the key being revoked. */
2538 subkeyRevocation: 40,
2539 /** 0x40: Timestamp signature.
2540 * This signature is only meaningful for the timestamp contained in
2541 * it. */
2542 timestamp: 64,
2543 /** 0x50: Third-Party Confirmation signature.
2544 *
2545 * This signature is a signature over some other OpenPGP Signature
2546 * packet(s). It is analogous to a notary seal on the signed data.
2547 * A third-party signature SHOULD include Signature Target
2548 * subpacket(s) to give easy identification. Note that we really do
2549 * mean SHOULD. There are plausible uses for this (such as a blind
2550 * party that only sees the signature, not the key or source
2551 * document) that cannot include a target subpacket. */
2552 thirdParty: 80
2553 },
2554
2555 /** Signature subpacket type
2556 * @enum {Integer}
2557 * @readonly
2558 */
2559 signatureSubpacket: {
2560 signatureCreationTime: 2,
2561 signatureExpirationTime: 3,
2562 exportableCertification: 4,
2563 trustSignature: 5,
2564 regularExpression: 6,
2565 revocable: 7,
2566 keyExpirationTime: 9,
2567 placeholderBackwardsCompatibility: 10,
2568 preferredSymmetricAlgorithms: 11,
2569 revocationKey: 12,
2570 issuer: 16,
2571 notationData: 20,
2572 preferredHashAlgorithms: 21,
2573 preferredCompressionAlgorithms: 22,
2574 keyServerPreferences: 23,
2575 preferredKeyServer: 24,
2576 primaryUserID: 25,
2577 policyURI: 26,
2578 keyFlags: 27,
2579 signersUserID: 28,
2580 reasonForRevocation: 29,
2581 features: 30,
2582 signatureTarget: 31,
2583 embeddedSignature: 32,
2584 issuerFingerprint: 33,
2585 preferredAEADAlgorithms: 34
2586 },
2587
2588 /** Key flags
2589 * @enum {Integer}
2590 * @readonly
2591 */
2592 keyFlags: {
2593 /** 0x01 - This key may be used to certify other keys. */
2594 certifyKeys: 1,
2595 /** 0x02 - This key may be used to sign data. */
2596 signData: 2,
2597 /** 0x04 - This key may be used to encrypt communications. */
2598 encryptCommunication: 4,
2599 /** 0x08 - This key may be used to encrypt storage. */
2600 encryptStorage: 8,
2601 /** 0x10 - The private component of this key may have been split
2602 * by a secret-sharing mechanism. */
2603 splitPrivateKey: 16,
2604 /** 0x20 - This key may be used for authentication. */
2605 authentication: 32,
2606 /** 0x80 - The private component of this key may be in the
2607 * possession of more than one person. */
2608 sharedPrivateKey: 128
2609 },
2610
2611 /** Armor type
2612 * @enum {Integer}
2613 * @readonly
2614 */
2615 armor: {
2616 multipartSection: 0,
2617 multipartLast: 1,
2618 signed: 2,
2619 message: 3,
2620 publicKey: 4,
2621 privateKey: 5,
2622 signature: 6
2623 },
2624
2625 /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
2626 * @enum {Integer}
2627 * @readonly
2628 */
2629 reasonForRevocation: {
2630 /** No reason specified (key revocations or cert revocations) */
2631 noReason: 0,
2632 /** Key is superseded (key revocations) */
2633 keySuperseded: 1,
2634 /** Key material has been compromised (key revocations) */
2635 keyCompromised: 2,
2636 /** Key is retired and no longer used (key revocations) */
2637 keyRetired: 3,
2638 /** User ID information is no longer valid (cert revocations) */
2639 userIDInvalid: 32
2640 },
2641
2642 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
2643 * @enum {Integer}
2644 * @readonly
2645 */
2646 features: {
2647 /** 0x01 - Modification Detection (packets 18 and 19) */
2648 modificationDetection: 1,
2649 /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
2650 * Symmetric-Key Encrypted Session Key Packets (packet 3) */
2651 aead: 2,
2652 /** 0x04 - Version 5 Public-Key Packet format and corresponding new
2653 * fingerprint format */
2654 v5Keys: 4
2655 },
2656
2657 /**
2658 * Asserts validity of given value and converts from string/integer to integer.
2659 * @param {Object} type target enum type
2660 * @param {String|Integer} e value to check and/or convert
2661 * @returns {Integer} enum value if it exists
2662 * @throws {Error} if the value is invalid
2663 */
2664 write: function(type, e) {
2665 if (typeof e === 'number') {
2666 e = this.read(type, e);
2667 }
2668
2669 if (type[e] !== undefined) {
2670 return type[e];
2671 }
2672
2673 throw new Error('Invalid enum value.');
2674 },
2675
2676 /**
2677 * Converts enum integer value to the corresponding string, if it exists.
2678 * @param {Object} type target enum type
2679 * @param {Integer} e value to convert
2680 * @returns {String} name of enum value if it exists
2681 * @throws {Error} if the value is invalid
2682 */
2683 read: function(type, e) {
2684 if (!type[byValue]) {
2685 type[byValue] = [];
2686 Object.entries(type).forEach(([key, value]) => {
2687 type[byValue][value] = key;
2688 });
2689 }
2690
2691 if (type[byValue][e] !== undefined) {
2692 return type[byValue][e];
2693 }
2694
2695 throw new Error('Invalid enum value.');
2696 }
2697};
2698
2699// GPG4Browsers - An OpenPGP implementation in javascript
2700
2701var defaultConfig = {
2702 /**
2703 * @memberof module:config
2704 * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
2705 */
2706 preferredHashAlgorithm: enums.hash.sha256,
2707 /**
2708 * @memberof module:config
2709 * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
2710 */
2711 preferredSymmetricAlgorithm: enums.symmetric.aes256,
2712 /**
2713 * @memberof module:config
2714 * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
2715 */
2716 preferredCompressionAlgorithm: enums.compression.uncompressed,
2717 /**
2718 * @memberof module:config
2719 * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
2720 */
2721 deflateLevel: 6,
2722
2723 /**
2724 * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
2725 * Note: not all OpenPGP implementations are compatible with this option.
2726 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2727 * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
2728 * @memberof module:config
2729 * @property {Boolean} aeadProtect
2730 */
2731 aeadProtect: false,
2732 /**
2733 * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
2734 * Only has an effect when aeadProtect is set to true.
2735 * @memberof module:config
2736 * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
2737 */
2738 preferredAEADAlgorithm: enums.aead.eax,
2739 /**
2740 * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
2741 * Only has an effect when aeadProtect is set to true.
2742 * Must be an integer value from 0 to 56.
2743 * @memberof module:config
2744 * @property {Integer} aeadChunkSizeByte
2745 */
2746 aeadChunkSizeByte: 12,
2747 /**
2748 * Use V5 keys.
2749 * Note: not all OpenPGP implementations are compatible with this option.
2750 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2751 * @memberof module:config
2752 * @property {Boolean} v5Keys
2753 */
2754 v5Keys: false,
2755 /**
2756 * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
2757 * Iteration Count Byte for S2K (String to Key)
2758 * @memberof module:config
2759 * @property {Integer} s2kIterationCountByte
2760 */
2761 s2kIterationCountByte: 224,
2762 /**
2763 * Allow decryption of messages without integrity protection.
2764 * This is an **insecure** setting:
2765 * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
2766 * - it enables downgrade attacks against integrity-protected messages.
2767 * @memberof module:config
2768 * @property {Boolean} allowUnauthenticatedMessages
2769 */
2770 allowUnauthenticatedMessages: false,
2771 /**
2772 * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to
2773 * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible
2774 * and deferring checking their integrity until the decrypted stream has been read in full.
2775 *
2776 * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.
2777 * @memberof module:config
2778 * @property {Boolean} allowUnauthenticatedStream
2779 */
2780 allowUnauthenticatedStream: false,
2781 /**
2782 * @memberof module:config
2783 * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
2784 */
2785 checksumRequired: false,
2786 /**
2787 * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
2788 * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
2789 * @memberof module:config
2790 * @property {Number} minRSABits
2791 */
2792 minRSABits: 2047,
2793 /**
2794 * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
2795 * **Slower and slightly less secure**
2796 * @memberof module:config
2797 * @property {Boolean} passwordCollisionCheck
2798 */
2799 passwordCollisionCheck: false,
2800 /**
2801 * @memberof module:config
2802 * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
2803 */
2804 revocationsExpire: false,
2805 /**
2806 * Allow decryption using RSA keys without `encrypt` flag.
2807 * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
2808 * where key flags were ignored when selecting a key for encryption.
2809 * @memberof module:config
2810 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2811 */
2812 allowInsecureDecryptionWithSigningKeys: false,
2813 /**
2814 * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.
2815 * Instead, a verification key will also be consider valid as long as it is valid at the current time.
2816 * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,
2817 * and have self-signature's creation date that does not match the primary key creation date.
2818 * @memberof module:config
2819 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2820 */
2821 allowInsecureVerificationWithReformattedKeys: false,
2822
2823 /**
2824 * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).
2825 * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:
2826 * - new/incoming messages are automatically decrypted (without user interaction);
2827 * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).
2828 * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.
2829 * @memberof module:config
2830 * @property {Boolean} constantTimePKCS1Decryption
2831 */
2832 constantTimePKCS1Decryption: false,
2833 /**
2834 * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.
2835 * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.
2836 * However, the more algorithms are added, the slower the decryption procedure becomes.
2837 * @memberof module:config
2838 * @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}
2839 */
2840 constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),
2841
2842 /**
2843 * @memberof module:config
2844 * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
2845 */
2846 minBytesForWebCrypto: 1000,
2847 /**
2848 * @memberof module:config
2849 * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
2850 */
2851 ignoreUnsupportedPackets: true,
2852 /**
2853 * @memberof module:config
2854 * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error
2855 */
2856 ignoreMalformedPackets: false,
2857 /**
2858 * @memberof module:config
2859 * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
2860 */
2861 showVersion: false,
2862 /**
2863 * @memberof module:config
2864 * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
2865 */
2866 showComment: false,
2867 /**
2868 * @memberof module:config
2869 * @property {String} versionString A version string to be included in armored messages
2870 */
2871 versionString: 'OpenPGP.js 5.3.1',
2872 /**
2873 * @memberof module:config
2874 * @property {String} commentString A comment string to be included in armored messages
2875 */
2876 commentString: 'https://openpgpjs.org',
2877
2878 /**
2879 * Max userID string length (used for parsing)
2880 * @memberof module:config
2881 * @property {Integer} maxUserIDLength
2882 */
2883 maxUserIDLength: 1024 * 5,
2884 /**
2885 * Contains notatations that are considered "known". Known notations do not trigger
2886 * validation error when the notation is marked as critical.
2887 * @memberof module:config
2888 * @property {Array} knownNotations
2889 */
2890 knownNotations: ['preferred-email-encoding@pgp.com', 'pka-address@gnupg.org'],
2891 /**
2892 * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.
2893 * When false, certain standard curves will not be supported (depending on the platform).
2894 * Note: the indutny/elliptic curve library is not designed to be constant time.
2895 * @memberof module:config
2896 * @property {Boolean} useIndutnyElliptic
2897 */
2898 useIndutnyElliptic: true,
2899 /**
2900 * Reject insecure hash algorithms
2901 * @memberof module:config
2902 * @property {Set<Integer>} rejectHashAlgorithms {@link module:enums.hash}
2903 */
2904 rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),
2905 /**
2906 * Reject insecure message hash algorithms
2907 * @memberof module:config
2908 * @property {Set<Integer>} rejectMessageHashAlgorithms {@link module:enums.hash}
2909 */
2910 rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),
2911 /**
2912 * Reject insecure public key algorithms for key generation and message encryption, signing or verification
2913 * @memberof module:config
2914 * @property {Set<Integer>} rejectPublicKeyAlgorithms {@link module:enums.publicKey}
2915 */
2916 rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),
2917 /**
2918 * Reject non-standard curves for key generation, message encryption, signing or verification
2919 * @memberof module:config
2920 * @property {Set<String>} rejectCurves {@link module:enums.curve}
2921 */
2922 rejectCurves: new Set([enums.curve.brainpoolP256r1, enums.curve.brainpoolP384r1, enums.curve.brainpoolP512r1, enums.curve.secp256k1])
2923};
2924
2925// GPG4Browsers - An OpenPGP implementation in javascript
2926
2927/**
2928 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
2929 * @param {String} text - ascii armored text
2930 * @returns {Integer} 0 = MESSAGE PART n of m.
2931 * 1 = MESSAGE PART n
2932 * 2 = SIGNED MESSAGE
2933 * 3 = PGP MESSAGE
2934 * 4 = PUBLIC KEY BLOCK
2935 * 5 = PRIVATE KEY BLOCK
2936 * 6 = SIGNATURE
2937 * @private
2938 */
2939function getType(text) {
2940 const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
2941
2942 const header = text.match(reHeader);
2943
2944 if (!header) {
2945 throw new Error('Unknown ASCII armor type');
2946 }
2947
2948 // BEGIN PGP MESSAGE, PART X/Y
2949 // Used for multi-part messages, where the armor is split amongst Y
2950 // parts, and this is the Xth part out of Y.
2951 if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
2952 return enums.armor.multipartSection;
2953 } else
2954 // BEGIN PGP MESSAGE, PART X
2955 // Used for multi-part messages, where this is the Xth part of an
2956 // unspecified number of parts. Requires the MESSAGE-ID Armor
2957 // Header to be used.
2958 if (/MESSAGE, PART \d+/.test(header[1])) {
2959 return enums.armor.multipartLast;
2960 } else
2961 // BEGIN PGP SIGNED MESSAGE
2962 if (/SIGNED MESSAGE/.test(header[1])) {
2963 return enums.armor.signed;
2964 } else
2965 // BEGIN PGP MESSAGE
2966 // Used for signed, encrypted, or compressed files.
2967 if (/MESSAGE/.test(header[1])) {
2968 return enums.armor.message;
2969 } else
2970 // BEGIN PGP PUBLIC KEY BLOCK
2971 // Used for armoring public keys.
2972 if (/PUBLIC KEY BLOCK/.test(header[1])) {
2973 return enums.armor.publicKey;
2974 } else
2975 // BEGIN PGP PRIVATE KEY BLOCK
2976 // Used for armoring private keys.
2977 if (/PRIVATE KEY BLOCK/.test(header[1])) {
2978 return enums.armor.privateKey;
2979 } else
2980 // BEGIN PGP SIGNATURE
2981 // Used for detached signatures, OpenPGP/MIME signatures, and
2982 // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
2983 // for detached signatures.
2984 if (/SIGNATURE/.test(header[1])) {
2985 return enums.armor.signature;
2986 }
2987}
2988
2989/**
2990 * Add additional information to the armor version of an OpenPGP binary
2991 * packet block.
2992 * @author Alex
2993 * @version 2011-12-16
2994 * @param {String} [customComment] - Additional comment to add to the armored string
2995 * @returns {String} The header information.
2996 * @private
2997 */
2998function addheader(customComment, config) {
2999 let result = '';
3000 if (config.showVersion) {
3001 result += 'Version: ' + config.versionString + '\n';
3002 }
3003 if (config.showComment) {
3004 result += 'Comment: ' + config.commentString + '\n';
3005 }
3006 if (customComment) {
3007 result += 'Comment: ' + customComment + '\n';
3008 }
3009 result += '\n';
3010 return result;
3011}
3012
3013
3014/**
3015 * Calculates a checksum over the given data and returns it base64 encoded
3016 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
3017 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
3018 * @private
3019 */
3020function getCheckSum(data) {
3021 const crc = createcrc24(data);
3022 return encode(crc);
3023}
3024
3025// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
3026
3027const crc_table = [
3028 new Array(0xFF),
3029 new Array(0xFF),
3030 new Array(0xFF),
3031 new Array(0xFF)
3032];
3033
3034for (let i = 0; i <= 0xFF; i++) {
3035 let crc = i << 16;
3036 for (let j = 0; j < 8; j++) {
3037 crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
3038 }
3039 crc_table[0][i] =
3040 ((crc & 0xFF0000) >> 16) |
3041 (crc & 0x00FF00) |
3042 ((crc & 0x0000FF) << 16);
3043}
3044for (let i = 0; i <= 0xFF; i++) {
3045 crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
3046}
3047for (let i = 0; i <= 0xFF; i++) {
3048 crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
3049}
3050for (let i = 0; i <= 0xFF; i++) {
3051 crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
3052}
3053
3054// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
3055const isLittleEndian = (function() {
3056 const buffer = new ArrayBuffer(2);
3057 new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
3058 // Int16Array uses the platform's endianness.
3059 return new Int16Array(buffer)[0] === 0xFF;
3060}());
3061
3062/**
3063 * Internal function to calculate a CRC-24 checksum over a given string (data)
3064 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
3065 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
3066 * @private
3067 */
3068function createcrc24(input) {
3069 let crc = 0xCE04B7;
3070 return transform(input, value => {
3071 const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;
3072 const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
3073 for (let i = 0; i < len32; i++) {
3074 crc ^= arr32[i];
3075 crc =
3076 crc_table[0][(crc >> 24) & 0xFF] ^
3077 crc_table[1][(crc >> 16) & 0xFF] ^
3078 crc_table[2][(crc >> 8) & 0xFF] ^
3079 crc_table[3][(crc >> 0) & 0xFF];
3080 }
3081 for (let i = len32 * 4; i < value.length; i++) {
3082 crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
3083 }
3084 }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
3085}
3086
3087/**
3088 * Verify armored headers. RFC4880, section 6.3: "OpenPGP should consider improperly formatted
3089 * Armor Headers to be corruption of the ASCII Armor."
3090 * @private
3091 * @param {Array<String>} headers - Armor headers
3092 */
3093function verifyHeaders(headers) {
3094 for (let i = 0; i < headers.length; i++) {
3095 if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
3096 throw new Error('Improperly formatted armor header: ' + headers[i]);
3097 }
3098 if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
3099 util.printDebugError(new Error('Unknown header: ' + headers[i]));
3100 }
3101 }
3102}
3103
3104/**
3105 * Splits a message into two parts, the body and the checksum. This is an internal function
3106 * @param {String} text - OpenPGP armored message part
3107 * @returns {Object} An object with attribute "body" containing the body.
3108 * and an attribute "checksum" containing the checksum.
3109 * @private
3110 */
3111function splitChecksum(text) {
3112 let body = text;
3113 let checksum = '';
3114
3115 const lastEquals = text.lastIndexOf('=');
3116
3117 if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
3118 body = text.slice(0, lastEquals);
3119 checksum = text.slice(lastEquals + 1).substr(0, 4);
3120 }
3121
3122 return { body: body, checksum: checksum };
3123}
3124
3125/**
3126 * Dearmor an OpenPGP armored message; verify the checksum and return
3127 * the encoded bytes
3128 * @param {String} input - OpenPGP armored message
3129 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
3130 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
3131 * @async
3132 * @static
3133 */
3134function unarmor(input, config = defaultConfig) {
3135 return new Promise(async (resolve, reject) => {
3136 try {
3137 const reSplit = /^-----[^-]+-----$/m;
3138 const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
3139
3140 let type;
3141 const headers = [];
3142 let lastHeaders = headers;
3143 let headersDone;
3144 let text = [];
3145 let textDone;
3146 let checksum;
3147 let data = decode(transformPair(input, async (readable, writable) => {
3148 const reader = getReader(readable);
3149 try {
3150 while (true) {
3151 let line = await reader.readLine();
3152 if (line === undefined) {
3153 throw new Error('Misformed armored text');
3154 }
3155 // remove trailing whitespace at end of lines
3156 line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
3157 if (!type) {
3158 if (reSplit.test(line)) {
3159 type = getType(line);
3160 }
3161 } else if (!headersDone) {
3162 if (reSplit.test(line)) {
3163 reject(new Error('Mandatory blank line missing between armor headers and armor data'));
3164 }
3165 if (!reEmptyLine.test(line)) {
3166 lastHeaders.push(line);
3167 } else {
3168 verifyHeaders(lastHeaders);
3169 headersDone = true;
3170 if (textDone || type !== 2) {
3171 resolve({ text, data, headers, type });
3172 break;
3173 }
3174 }
3175 } else if (!textDone && type === 2) {
3176 if (!reSplit.test(line)) {
3177 // Reverse dash-escaping for msg
3178 text.push(line.replace(/^- /, ''));
3179 } else {
3180 text = text.join('\r\n');
3181 textDone = true;
3182 verifyHeaders(lastHeaders);
3183 lastHeaders = [];
3184 headersDone = false;
3185 }
3186 }
3187 }
3188 } catch (e) {
3189 reject(e);
3190 return;
3191 }
3192 const writer = getWriter(writable);
3193 try {
3194 while (true) {
3195 await writer.ready;
3196 const { done, value } = await reader.read();
3197 if (done) {
3198 throw new Error('Misformed armored text');
3199 }
3200 const line = value + '';
3201 if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
3202 await writer.write(line);
3203 } else {
3204 let remainder = await reader.readToEnd();
3205 if (!remainder.length) remainder = '';
3206 remainder = line + remainder;
3207 remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
3208 const parts = remainder.split(reSplit);
3209 if (parts.length === 1) {
3210 throw new Error('Misformed armored text');
3211 }
3212 const split = splitChecksum(parts[0].slice(0, -1));
3213 checksum = split.checksum;
3214 await writer.write(split.body);
3215 break;
3216 }
3217 }
3218 await writer.ready;
3219 await writer.close();
3220 } catch (e) {
3221 await writer.abort(e);
3222 }
3223 }));
3224 data = transformPair(data, async (readable, writable) => {
3225 const checksumVerified = readToEnd(getCheckSum(passiveClone(readable)));
3226 checksumVerified.catch(() => {});
3227 await pipe(readable, writable, {
3228 preventClose: true
3229 });
3230 const writer = getWriter(writable);
3231 try {
3232 const checksumVerifiedString = (await checksumVerified).replace('\n', '');
3233 if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {
3234 throw new Error('Ascii armor integrity check failed');
3235 }
3236 await writer.ready;
3237 await writer.close();
3238 } catch (e) {
3239 await writer.abort(e);
3240 }
3241 });
3242 } catch (e) {
3243 reject(e);
3244 }
3245 }).then(async result => {
3246 if (isArrayStream(result.data)) {
3247 result.data = await readToEnd(result.data);
3248 }
3249 return result;
3250 });
3251}
3252
3253
3254/**
3255 * Armor an OpenPGP binary packet block
3256 * @param {module:enums.armor} messageType - Type of the message
3257 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
3258 * @param {Integer} [partIndex]
3259 * @param {Integer} [partTotal]
3260 * @param {String} [customComment] - Additional comment to add to the armored string
3261 * @returns {String | ReadableStream<String>} Armored text.
3262 * @static
3263 */
3264function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {
3265 let text;
3266 let hash;
3267 if (messageType === enums.armor.signed) {
3268 text = body.text;
3269 hash = body.hash;
3270 body = body.data;
3271 }
3272 const bodyClone = passiveClone(body);
3273 const result = [];
3274 switch (messageType) {
3275 case enums.armor.multipartSection:
3276 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3277 result.push(addheader(customComment, config));
3278 result.push(encode(body));
3279 result.push('=', getCheckSum(bodyClone));
3280 result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3281 break;
3282 case enums.armor.multipartLast:
3283 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n');
3284 result.push(addheader(customComment, config));
3285 result.push(encode(body));
3286 result.push('=', getCheckSum(bodyClone));
3287 result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n');
3288 break;
3289 case enums.armor.signed:
3290 result.push('\n-----BEGIN PGP SIGNED MESSAGE-----\n');
3291 result.push('Hash: ' + hash + '\n\n');
3292 result.push(text.replace(/^-/mg, '- -'));
3293 result.push('\n-----BEGIN PGP SIGNATURE-----\n');
3294 result.push(addheader(customComment, config));
3295 result.push(encode(body));
3296 result.push('=', getCheckSum(bodyClone));
3297 result.push('-----END PGP SIGNATURE-----\n');
3298 break;
3299 case enums.armor.message:
3300 result.push('-----BEGIN PGP MESSAGE-----\n');
3301 result.push(addheader(customComment, config));
3302 result.push(encode(body));
3303 result.push('=', getCheckSum(bodyClone));
3304 result.push('-----END PGP MESSAGE-----\n');
3305 break;
3306 case enums.armor.publicKey:
3307 result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n');
3308 result.push(addheader(customComment, config));
3309 result.push(encode(body));
3310 result.push('=', getCheckSum(bodyClone));
3311 result.push('-----END PGP PUBLIC KEY BLOCK-----\n');
3312 break;
3313 case enums.armor.privateKey:
3314 result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n');
3315 result.push(addheader(customComment, config));
3316 result.push(encode(body));
3317 result.push('=', getCheckSum(bodyClone));
3318 result.push('-----END PGP PRIVATE KEY BLOCK-----\n');
3319 break;
3320 case enums.armor.signature:
3321 result.push('-----BEGIN PGP SIGNATURE-----\n');
3322 result.push(addheader(customComment, config));
3323 result.push(encode(body));
3324 result.push('=', getCheckSum(bodyClone));
3325 result.push('-----END PGP SIGNATURE-----\n');
3326 break;
3327 }
3328
3329 return util.concat(result);
3330}
3331
3332// GPG4Browsers - An OpenPGP implementation in javascript
3333
3334/**
3335 * Implementation of type key id
3336 *
3337 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
3338 * A Key ID is an eight-octet scalar that identifies a key.
3339 * Implementations SHOULD NOT assume that Key IDs are unique. The
3340 * section "Enhanced Key Formats" below describes how Key IDs are
3341 * formed.
3342 */
3343class KeyID {
3344 constructor() {
3345 this.bytes = '';
3346 }
3347
3348 /**
3349 * Parsing method for a key id
3350 * @param {Uint8Array} bytes - Input to read the key id from
3351 */
3352 read(bytes) {
3353 this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));
3354 }
3355
3356 /**
3357 * Serializes the Key ID
3358 * @returns {Uint8Array} Key ID as a Uint8Array.
3359 */
3360 write() {
3361 return util.stringToUint8Array(this.bytes);
3362 }
3363
3364 /**
3365 * Returns the Key ID represented as a hexadecimal string
3366 * @returns {String} Key ID as a hexadecimal string.
3367 */
3368 toHex() {
3369 return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));
3370 }
3371
3372 /**
3373 * Checks equality of Key ID's
3374 * @param {KeyID} keyID
3375 * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard
3376 */
3377 equals(keyID, matchWildcard = false) {
3378 return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;
3379 }
3380
3381 /**
3382 * Checks to see if the Key ID is unset
3383 * @returns {Boolean} True if the Key ID is null.
3384 */
3385 isNull() {
3386 return this.bytes === '';
3387 }
3388
3389 /**
3390 * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
3391 * @returns {Boolean} True if this is a wildcard Key ID.
3392 */
3393 isWildcard() {
3394 return /^0+$/.test(this.toHex());
3395 }
3396
3397 static mapToHex(keyID) {
3398 return keyID.toHex();
3399 }
3400
3401 static fromID(hex) {
3402 const keyID = new KeyID();
3403 keyID.read(util.hexToUint8Array(hex));
3404 return keyID;
3405 }
3406
3407 static wildcard() {
3408 const keyID = new KeyID();
3409 keyID.read(new Uint8Array(8));
3410 return keyID;
3411 }
3412}
3413
3414/**
3415 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
3416 * @author Artem S Vybornov <vybornov@gmail.com>
3417 * @license MIT
3418 */
3419var AES_asm = function () {
3420
3421 /**
3422 * Galois Field stuff init flag
3423 */
3424 var ginit_done = false;
3425
3426 /**
3427 * Galois Field exponentiation and logarithm tables for 3 (the generator)
3428 */
3429 var gexp3, glog3;
3430
3431 /**
3432 * Init Galois Field tables
3433 */
3434 function ginit() {
3435 gexp3 = [],
3436 glog3 = [];
3437
3438 var a = 1, c, d;
3439 for (c = 0; c < 255; c++) {
3440 gexp3[c] = a;
3441
3442 // Multiply by three
3443 d = a & 0x80, a <<= 1, a &= 255;
3444 if (d === 0x80) a ^= 0x1b;
3445 a ^= gexp3[c];
3446
3447 // Set the log table value
3448 glog3[gexp3[c]] = c;
3449 }
3450 gexp3[255] = gexp3[0];
3451 glog3[0] = 0;
3452
3453 ginit_done = true;
3454 }
3455
3456 /**
3457 * Galois Field multiplication
3458 * @param {number} a
3459 * @param {number} b
3460 * @return {number}
3461 */
3462 function gmul(a, b) {
3463 var c = gexp3[(glog3[a] + glog3[b]) % 255];
3464 if (a === 0 || b === 0) c = 0;
3465 return c;
3466 }
3467
3468 /**
3469 * Galois Field reciprocal
3470 * @param {number} a
3471 * @return {number}
3472 */
3473 function ginv(a) {
3474 var i = gexp3[255 - glog3[a]];
3475 if (a === 0) i = 0;
3476 return i;
3477 }
3478
3479 /**
3480 * AES stuff init flag
3481 */
3482 var aes_init_done = false;
3483
3484 /**
3485 * Encryption, Decryption, S-Box and KeyTransform tables
3486 *
3487 * @type {number[]}
3488 */
3489 var aes_sbox;
3490
3491 /**
3492 * @type {number[]}
3493 */
3494 var aes_sinv;
3495
3496 /**
3497 * @type {number[][]}
3498 */
3499 var aes_enc;
3500
3501 /**
3502 * @type {number[][]}
3503 */
3504 var aes_dec;
3505
3506 /**
3507 * Init AES tables
3508 */
3509 function aes_init() {
3510 if (!ginit_done) ginit();
3511
3512 // Calculates AES S-Box value
3513 function _s(a) {
3514 var c, s, x;
3515 s = x = ginv(a);
3516 for (c = 0; c < 4; c++) {
3517 s = ((s << 1) | (s >>> 7)) & 255;
3518 x ^= s;
3519 }
3520 x ^= 99;
3521 return x;
3522 }
3523
3524 // Tables
3525 aes_sbox = [],
3526 aes_sinv = [],
3527 aes_enc = [[], [], [], []],
3528 aes_dec = [[], [], [], []];
3529
3530 for (var i = 0; i < 256; i++) {
3531 var s = _s(i);
3532
3533 // S-Box and its inverse
3534 aes_sbox[i] = s;
3535 aes_sinv[s] = i;
3536
3537 // Ecryption and Decryption tables
3538 aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);
3539 aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);
3540 // Rotate tables
3541 for (var t = 1; t < 4; t++) {
3542 aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);
3543 aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);
3544 }
3545 }
3546
3547 aes_init_done = true;
3548 }
3549
3550 /**
3551 * Asm.js module constructor.
3552 *
3553 * <p>
3554 * Heap buffer layout by offset:
3555 * <pre>
3556 * 0x0000 encryption key schedule
3557 * 0x0400 decryption key schedule
3558 * 0x0800 sbox
3559 * 0x0c00 inv sbox
3560 * 0x1000 encryption tables
3561 * 0x2000 decryption tables
3562 * 0x3000 reserved (future GCM multiplication lookup table)
3563 * 0x4000 data
3564 * </pre>
3565 * Don't touch anything before <code>0x400</code>.
3566 * </p>
3567 *
3568 * @alias AES_asm
3569 * @class
3570 * @param foreign - <i>ignored</i>
3571 * @param buffer - heap buffer to link with
3572 */
3573 var wrapper = function (foreign, buffer) {
3574 // Init AES stuff for the first time
3575 if (!aes_init_done) aes_init();
3576
3577 // Fill up AES tables
3578 var heap = new Uint32Array(buffer);
3579 heap.set(aes_sbox, 0x0800 >> 2);
3580 heap.set(aes_sinv, 0x0c00 >> 2);
3581 for (var i = 0; i < 4; i++) {
3582 heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);
3583 heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);
3584 }
3585
3586 /**
3587 * Calculate AES key schedules.
3588 * @instance
3589 * @memberof AES_asm
3590 * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
3591 * @param {number} k0 - key vector components
3592 * @param {number} k1 - key vector components
3593 * @param {number} k2 - key vector components
3594 * @param {number} k3 - key vector components
3595 * @param {number} k4 - key vector components
3596 * @param {number} k5 - key vector components
3597 * @param {number} k6 - key vector components
3598 * @param {number} k7 - key vector components
3599 */
3600 function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
3601 var ekeys = heap.subarray(0x000, 60),
3602 dkeys = heap.subarray(0x100, 0x100 + 60);
3603
3604 // Encryption key schedule
3605 ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
3606 for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
3607 var k = ekeys[i - 1];
3608 if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {
3609 k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
3610 }
3611 if (i % ks === 0) {
3612 k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
3613 rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);
3614 }
3615 ekeys[i] = ekeys[i - ks] ^ k;
3616 }
3617
3618 // Decryption key schedule
3619 for (var j = 0; j < i; j += 4) {
3620 for (var jj = 0; jj < 4; jj++) {
3621 var k = ekeys[i - (4 + j) + (4 - jj) % 4];
3622 if (j < 4 || j >= i - 4) {
3623 dkeys[j + jj] = k;
3624 } else {
3625 dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]
3626 ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]
3627 ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]
3628 ^ aes_dec[3][aes_sbox[k & 255]];
3629 }
3630 }
3631 }
3632
3633 // Set rounds number
3634 asm.set_rounds(ks + 5);
3635 }
3636
3637 // create library object with necessary properties
3638 var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};
3639
3640 var asm = function (stdlib, foreign, buffer) {
3641 "use asm";
3642
3643 var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
3644 I0 = 0, I1 = 0, I2 = 0, I3 = 0,
3645 N0 = 0, N1 = 0, N2 = 0, N3 = 0,
3646 M0 = 0, M1 = 0, M2 = 0, M3 = 0,
3647 H0 = 0, H1 = 0, H2 = 0, H3 = 0,
3648 R = 0;
3649
3650 var HEAP = new stdlib.Uint32Array(buffer),
3651 DATA = new stdlib.Uint8Array(buffer);
3652
3653 /**
3654 * AES core
3655 * @param {number} k - precomputed key schedule offset
3656 * @param {number} s - precomputed sbox table offset
3657 * @param {number} t - precomputed round table offset
3658 * @param {number} r - number of inner rounds to perform
3659 * @param {number} x0 - 128-bit input block vector
3660 * @param {number} x1 - 128-bit input block vector
3661 * @param {number} x2 - 128-bit input block vector
3662 * @param {number} x3 - 128-bit input block vector
3663 */
3664 function _core(k, s, t, r, x0, x1, x2, x3) {
3665 k = k | 0;
3666 s = s | 0;
3667 t = t | 0;
3668 r = r | 0;
3669 x0 = x0 | 0;
3670 x1 = x1 | 0;
3671 x2 = x2 | 0;
3672 x3 = x3 | 0;
3673
3674 var t1 = 0, t2 = 0, t3 = 0,
3675 y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3676 i = 0;
3677
3678 t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
3679
3680 // round 0
3681 x0 = x0 ^ HEAP[(k | 0) >> 2],
3682 x1 = x1 ^ HEAP[(k | 4) >> 2],
3683 x2 = x2 ^ HEAP[(k | 8) >> 2],
3684 x3 = x3 ^ HEAP[(k | 12) >> 2];
3685
3686 // round 1..r
3687 for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {
3688 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],
3689 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],
3690 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],
3691 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];
3692 x0 = y0, x1 = y1, x2 = y2, x3 = y3;
3693 }
3694
3695 // final round
3696 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],
3697 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],
3698 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],
3699 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];
3700 }
3701
3702 /**
3703 * ECB mode encryption
3704 * @param {number} x0 - 128-bit input block vector
3705 * @param {number} x1 - 128-bit input block vector
3706 * @param {number} x2 - 128-bit input block vector
3707 * @param {number} x3 - 128-bit input block vector
3708 */
3709 function _ecb_enc(x0, x1, x2, x3) {
3710 x0 = x0 | 0;
3711 x1 = x1 | 0;
3712 x2 = x2 | 0;
3713 x3 = x3 | 0;
3714
3715 _core(
3716 0x0000, 0x0800, 0x1000,
3717 R,
3718 x0,
3719 x1,
3720 x2,
3721 x3
3722 );
3723 }
3724
3725 /**
3726 * ECB mode decryption
3727 * @param {number} x0 - 128-bit input block vector
3728 * @param {number} x1 - 128-bit input block vector
3729 * @param {number} x2 - 128-bit input block vector
3730 * @param {number} x3 - 128-bit input block vector
3731 */
3732 function _ecb_dec(x0, x1, x2, x3) {
3733 x0 = x0 | 0;
3734 x1 = x1 | 0;
3735 x2 = x2 | 0;
3736 x3 = x3 | 0;
3737
3738 var t = 0;
3739
3740 _core(
3741 0x0400, 0x0c00, 0x2000,
3742 R,
3743 x0,
3744 x3,
3745 x2,
3746 x1
3747 );
3748
3749 t = S1, S1 = S3, S3 = t;
3750 }
3751
3752
3753 /**
3754 * CBC mode encryption
3755 * @param {number} x0 - 128-bit input block vector
3756 * @param {number} x1 - 128-bit input block vector
3757 * @param {number} x2 - 128-bit input block vector
3758 * @param {number} x3 - 128-bit input block vector
3759 */
3760 function _cbc_enc(x0, x1, x2, x3) {
3761 x0 = x0 | 0;
3762 x1 = x1 | 0;
3763 x2 = x2 | 0;
3764 x3 = x3 | 0;
3765
3766 _core(
3767 0x0000, 0x0800, 0x1000,
3768 R,
3769 I0 ^ x0,
3770 I1 ^ x1,
3771 I2 ^ x2,
3772 I3 ^ x3
3773 );
3774
3775 I0 = S0,
3776 I1 = S1,
3777 I2 = S2,
3778 I3 = S3;
3779 }
3780
3781 /**
3782 * CBC 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 _cbc_dec(x0, x1, x2, x3) {
3789 x0 = x0 | 0;
3790 x1 = x1 | 0;
3791 x2 = x2 | 0;
3792 x3 = x3 | 0;
3793
3794 var t = 0;
3795
3796 _core(
3797 0x0400, 0x0c00, 0x2000,
3798 R,
3799 x0,
3800 x3,
3801 x2,
3802 x1
3803 );
3804
3805 t = S1, S1 = S3, S3 = t;
3806
3807 S0 = S0 ^ I0,
3808 S1 = S1 ^ I1,
3809 S2 = S2 ^ I2,
3810 S3 = S3 ^ I3;
3811
3812 I0 = x0,
3813 I1 = x1,
3814 I2 = x2,
3815 I3 = x3;
3816 }
3817
3818 /**
3819 * CFB mode encryption
3820 * @param {number} x0 - 128-bit input block vector
3821 * @param {number} x1 - 128-bit input block vector
3822 * @param {number} x2 - 128-bit input block vector
3823 * @param {number} x3 - 128-bit input block vector
3824 */
3825 function _cfb_enc(x0, x1, x2, x3) {
3826 x0 = x0 | 0;
3827 x1 = x1 | 0;
3828 x2 = x2 | 0;
3829 x3 = x3 | 0;
3830
3831 _core(
3832 0x0000, 0x0800, 0x1000,
3833 R,
3834 I0,
3835 I1,
3836 I2,
3837 I3
3838 );
3839
3840 I0 = S0 = S0 ^ x0,
3841 I1 = S1 = S1 ^ x1,
3842 I2 = S2 = S2 ^ x2,
3843 I3 = S3 = S3 ^ x3;
3844 }
3845
3846
3847 /**
3848 * CFB mode 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 _cfb_dec(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 I0,
3864 I1,
3865 I2,
3866 I3
3867 );
3868
3869 S0 = S0 ^ x0,
3870 S1 = S1 ^ x1,
3871 S2 = S2 ^ x2,
3872 S3 = S3 ^ x3;
3873
3874 I0 = x0,
3875 I1 = x1,
3876 I2 = x2,
3877 I3 = x3;
3878 }
3879
3880 /**
3881 * OFB mode encryption / decryption
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 _ofb(x0, x1, x2, x3) {
3888 x0 = x0 | 0;
3889 x1 = x1 | 0;
3890 x2 = x2 | 0;
3891 x3 = x3 | 0;
3892
3893 _core(
3894 0x0000, 0x0800, 0x1000,
3895 R,
3896 I0,
3897 I1,
3898 I2,
3899 I3
3900 );
3901
3902 I0 = S0,
3903 I1 = S1,
3904 I2 = S2,
3905 I3 = S3;
3906
3907 S0 = S0 ^ x0,
3908 S1 = S1 ^ x1,
3909 S2 = S2 ^ x2,
3910 S3 = S3 ^ x3;
3911 }
3912
3913 /**
3914 * CTR mode encryption / decryption
3915 * @param {number} x0 - 128-bit input block vector
3916 * @param {number} x1 - 128-bit input block vector
3917 * @param {number} x2 - 128-bit input block vector
3918 * @param {number} x3 - 128-bit input block vector
3919 */
3920 function _ctr(x0, x1, x2, x3) {
3921 x0 = x0 | 0;
3922 x1 = x1 | 0;
3923 x2 = x2 | 0;
3924 x3 = x3 | 0;
3925
3926 _core(
3927 0x0000, 0x0800, 0x1000,
3928 R,
3929 N0,
3930 N1,
3931 N2,
3932 N3
3933 );
3934
3935 N3 = (~M3 & N3) | M3 & (N3 + 1);
3936 N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));
3937 N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));
3938 N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));
3939
3940 S0 = S0 ^ x0;
3941 S1 = S1 ^ x1;
3942 S2 = S2 ^ x2;
3943 S3 = S3 ^ x3;
3944 }
3945
3946 /**
3947 * GCM mode MAC calculation
3948 * @param {number} x0 - 128-bit input block vector
3949 * @param {number} x1 - 128-bit input block vector
3950 * @param {number} x2 - 128-bit input block vector
3951 * @param {number} x3 - 128-bit input block vector
3952 */
3953 function _gcm_mac(x0, x1, x2, x3) {
3954 x0 = x0 | 0;
3955 x1 = x1 | 0;
3956 x2 = x2 | 0;
3957 x3 = x3 | 0;
3958
3959 var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3960 z0 = 0, z1 = 0, z2 = 0, z3 = 0,
3961 i = 0, c = 0;
3962
3963 x0 = x0 ^ I0,
3964 x1 = x1 ^ I1,
3965 x2 = x2 ^ I2,
3966 x3 = x3 ^ I3;
3967
3968 y0 = H0 | 0,
3969 y1 = H1 | 0,
3970 y2 = H2 | 0,
3971 y3 = H3 | 0;
3972
3973 for (; (i | 0) < 128; i = (i + 1) | 0) {
3974 if (y0 >>> 31) {
3975 z0 = z0 ^ x0,
3976 z1 = z1 ^ x1,
3977 z2 = z2 ^ x2,
3978 z3 = z3 ^ x3;
3979 }
3980
3981 y0 = (y0 << 1) | (y1 >>> 31),
3982 y1 = (y1 << 1) | (y2 >>> 31),
3983 y2 = (y2 << 1) | (y3 >>> 31),
3984 y3 = (y3 << 1);
3985
3986 c = x3 & 1;
3987
3988 x3 = (x3 >>> 1) | (x2 << 31),
3989 x2 = (x2 >>> 1) | (x1 << 31),
3990 x1 = (x1 >>> 1) | (x0 << 31),
3991 x0 = (x0 >>> 1);
3992
3993 if (c) x0 = x0 ^ 0xe1000000;
3994 }
3995
3996 I0 = z0,
3997 I1 = z1,
3998 I2 = z2,
3999 I3 = z3;
4000 }
4001
4002 /**
4003 * Set the internal rounds number.
4004 * @instance
4005 * @memberof AES_asm
4006 * @param {number} r - number if inner AES rounds
4007 */
4008 function set_rounds(r) {
4009 r = r | 0;
4010 R = r;
4011 }
4012
4013 /**
4014 * Populate the internal state of the module.
4015 * @instance
4016 * @memberof AES_asm
4017 * @param {number} s0 - state vector
4018 * @param {number} s1 - state vector
4019 * @param {number} s2 - state vector
4020 * @param {number} s3 - state vector
4021 */
4022 function set_state(s0, s1, s2, s3) {
4023 s0 = s0 | 0;
4024 s1 = s1 | 0;
4025 s2 = s2 | 0;
4026 s3 = s3 | 0;
4027
4028 S0 = s0,
4029 S1 = s1,
4030 S2 = s2,
4031 S3 = s3;
4032 }
4033
4034 /**
4035 * Populate the internal iv of the module.
4036 * @instance
4037 * @memberof AES_asm
4038 * @param {number} i0 - iv vector
4039 * @param {number} i1 - iv vector
4040 * @param {number} i2 - iv vector
4041 * @param {number} i3 - iv vector
4042 */
4043 function set_iv(i0, i1, i2, i3) {
4044 i0 = i0 | 0;
4045 i1 = i1 | 0;
4046 i2 = i2 | 0;
4047 i3 = i3 | 0;
4048
4049 I0 = i0,
4050 I1 = i1,
4051 I2 = i2,
4052 I3 = i3;
4053 }
4054
4055 /**
4056 * Set nonce for CTR-family modes.
4057 * @instance
4058 * @memberof AES_asm
4059 * @param {number} n0 - nonce vector
4060 * @param {number} n1 - nonce vector
4061 * @param {number} n2 - nonce vector
4062 * @param {number} n3 - nonce vector
4063 */
4064 function set_nonce(n0, n1, n2, n3) {
4065 n0 = n0 | 0;
4066 n1 = n1 | 0;
4067 n2 = n2 | 0;
4068 n3 = n3 | 0;
4069
4070 N0 = n0,
4071 N1 = n1,
4072 N2 = n2,
4073 N3 = n3;
4074 }
4075
4076 /**
4077 * Set counter mask for CTR-family modes.
4078 * @instance
4079 * @memberof AES_asm
4080 * @param {number} m0 - counter mask vector
4081 * @param {number} m1 - counter mask vector
4082 * @param {number} m2 - counter mask vector
4083 * @param {number} m3 - counter mask vector
4084 */
4085 function set_mask(m0, m1, m2, m3) {
4086 m0 = m0 | 0;
4087 m1 = m1 | 0;
4088 m2 = m2 | 0;
4089 m3 = m3 | 0;
4090
4091 M0 = m0,
4092 M1 = m1,
4093 M2 = m2,
4094 M3 = m3;
4095 }
4096
4097 /**
4098 * Set counter for CTR-family modes.
4099 * @instance
4100 * @memberof AES_asm
4101 * @param {number} c0 - counter vector
4102 * @param {number} c1 - counter vector
4103 * @param {number} c2 - counter vector
4104 * @param {number} c3 - counter vector
4105 */
4106 function set_counter(c0, c1, c2, c3) {
4107 c0 = c0 | 0;
4108 c1 = c1 | 0;
4109 c2 = c2 | 0;
4110 c3 = c3 | 0;
4111
4112 N3 = (~M3 & N3) | M3 & c3,
4113 N2 = (~M2 & N2) | M2 & c2,
4114 N1 = (~M1 & N1) | M1 & c1,
4115 N0 = (~M0 & N0) | M0 & c0;
4116 }
4117
4118 /**
4119 * Store the internal state vector into the heap.
4120 * @instance
4121 * @memberof AES_asm
4122 * @param {number} pos - offset where to put the data
4123 * @return {number} The number of bytes have been written into the heap, always 16.
4124 */
4125 function get_state(pos) {
4126 pos = pos | 0;
4127
4128 if (pos & 15) return -1;
4129
4130 DATA[pos | 0] = S0 >>> 24,
4131 DATA[pos | 1] = S0 >>> 16 & 255,
4132 DATA[pos | 2] = S0 >>> 8 & 255,
4133 DATA[pos | 3] = S0 & 255,
4134 DATA[pos | 4] = S1 >>> 24,
4135 DATA[pos | 5] = S1 >>> 16 & 255,
4136 DATA[pos | 6] = S1 >>> 8 & 255,
4137 DATA[pos | 7] = S1 & 255,
4138 DATA[pos | 8] = S2 >>> 24,
4139 DATA[pos | 9] = S2 >>> 16 & 255,
4140 DATA[pos | 10] = S2 >>> 8 & 255,
4141 DATA[pos | 11] = S2 & 255,
4142 DATA[pos | 12] = S3 >>> 24,
4143 DATA[pos | 13] = S3 >>> 16 & 255,
4144 DATA[pos | 14] = S3 >>> 8 & 255,
4145 DATA[pos | 15] = S3 & 255;
4146
4147 return 16;
4148 }
4149
4150 /**
4151 * Store the internal iv vector into the heap.
4152 * @instance
4153 * @memberof AES_asm
4154 * @param {number} pos - offset where to put the data
4155 * @return {number} The number of bytes have been written into the heap, always 16.
4156 */
4157 function get_iv(pos) {
4158 pos = pos | 0;
4159
4160 if (pos & 15) return -1;
4161
4162 DATA[pos | 0] = I0 >>> 24,
4163 DATA[pos | 1] = I0 >>> 16 & 255,
4164 DATA[pos | 2] = I0 >>> 8 & 255,
4165 DATA[pos | 3] = I0 & 255,
4166 DATA[pos | 4] = I1 >>> 24,
4167 DATA[pos | 5] = I1 >>> 16 & 255,
4168 DATA[pos | 6] = I1 >>> 8 & 255,
4169 DATA[pos | 7] = I1 & 255,
4170 DATA[pos | 8] = I2 >>> 24,
4171 DATA[pos | 9] = I2 >>> 16 & 255,
4172 DATA[pos | 10] = I2 >>> 8 & 255,
4173 DATA[pos | 11] = I2 & 255,
4174 DATA[pos | 12] = I3 >>> 24,
4175 DATA[pos | 13] = I3 >>> 16 & 255,
4176 DATA[pos | 14] = I3 >>> 8 & 255,
4177 DATA[pos | 15] = I3 & 255;
4178
4179 return 16;
4180 }
4181
4182 /**
4183 * GCM initialization.
4184 * @instance
4185 * @memberof AES_asm
4186 */
4187 function gcm_init() {
4188 _ecb_enc(0, 0, 0, 0);
4189 H0 = S0,
4190 H1 = S1,
4191 H2 = S2,
4192 H3 = S3;
4193 }
4194
4195 /**
4196 * Perform ciphering operation on the supplied data.
4197 * @instance
4198 * @memberof AES_asm
4199 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4200 * @param {number} pos - offset of the data being processed
4201 * @param {number} len - length of the data being processed
4202 * @return {number} Actual amount of data have been processed.
4203 */
4204 function cipher(mode, pos, len) {
4205 mode = mode | 0;
4206 pos = pos | 0;
4207 len = len | 0;
4208
4209 var ret = 0;
4210
4211 if (pos & 15) return -1;
4212
4213 while ((len | 0) >= 16) {
4214 _cipher_modes[mode & 7](
4215 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4216 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4217 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4218 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4219 );
4220
4221 DATA[pos | 0] = S0 >>> 24,
4222 DATA[pos | 1] = S0 >>> 16 & 255,
4223 DATA[pos | 2] = S0 >>> 8 & 255,
4224 DATA[pos | 3] = S0 & 255,
4225 DATA[pos | 4] = S1 >>> 24,
4226 DATA[pos | 5] = S1 >>> 16 & 255,
4227 DATA[pos | 6] = S1 >>> 8 & 255,
4228 DATA[pos | 7] = S1 & 255,
4229 DATA[pos | 8] = S2 >>> 24,
4230 DATA[pos | 9] = S2 >>> 16 & 255,
4231 DATA[pos | 10] = S2 >>> 8 & 255,
4232 DATA[pos | 11] = S2 & 255,
4233 DATA[pos | 12] = S3 >>> 24,
4234 DATA[pos | 13] = S3 >>> 16 & 255,
4235 DATA[pos | 14] = S3 >>> 8 & 255,
4236 DATA[pos | 15] = S3 & 255;
4237
4238 ret = (ret + 16) | 0,
4239 pos = (pos + 16) | 0,
4240 len = (len - 16) | 0;
4241 }
4242
4243 return ret | 0;
4244 }
4245
4246 /**
4247 * Calculates MAC of the supplied data.
4248 * @instance
4249 * @memberof AES_asm
4250 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4251 * @param {number} pos - offset of the data being processed
4252 * @param {number} len - length of the data being processed
4253 * @return {number} Actual amount of data have been processed.
4254 */
4255 function mac(mode, pos, len) {
4256 mode = mode | 0;
4257 pos = pos | 0;
4258 len = len | 0;
4259
4260 var ret = 0;
4261
4262 if (pos & 15) return -1;
4263
4264 while ((len | 0) >= 16) {
4265 _mac_modes[mode & 1](
4266 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4267 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4268 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4269 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4270 );
4271
4272 ret = (ret + 16) | 0,
4273 pos = (pos + 16) | 0,
4274 len = (len - 16) | 0;
4275 }
4276
4277 return ret | 0;
4278 }
4279
4280 /**
4281 * AES cipher modes table (virual methods)
4282 */
4283 var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
4284
4285 /**
4286 * AES MAC modes table (virual methods)
4287 */
4288 var _mac_modes = [_cbc_enc, _gcm_mac];
4289
4290 /**
4291 * Asm.js module exports
4292 */
4293 return {
4294 set_rounds: set_rounds,
4295 set_state: set_state,
4296 set_iv: set_iv,
4297 set_nonce: set_nonce,
4298 set_mask: set_mask,
4299 set_counter: set_counter,
4300 get_state: get_state,
4301 get_iv: get_iv,
4302 gcm_init: gcm_init,
4303 cipher: cipher,
4304 mac: mac,
4305 };
4306 }(stdlib, foreign, buffer);
4307
4308 asm.set_key = set_key;
4309
4310 return asm;
4311 };
4312
4313 /**
4314 * AES enciphering mode constants
4315 * @enum {number}
4316 * @const
4317 */
4318 wrapper.ENC = {
4319 ECB: 0,
4320 CBC: 2,
4321 CFB: 4,
4322 OFB: 6,
4323 CTR: 7,
4324 },
4325
4326 /**
4327 * AES deciphering mode constants
4328 * @enum {number}
4329 * @const
4330 */
4331 wrapper.DEC = {
4332 ECB: 1,
4333 CBC: 3,
4334 CFB: 5,
4335 OFB: 6,
4336 CTR: 7,
4337 },
4338
4339 /**
4340 * AES MAC mode constants
4341 * @enum {number}
4342 * @const
4343 */
4344 wrapper.MAC = {
4345 CBC: 0,
4346 GCM: 1,
4347 };
4348
4349 /**
4350 * Heap data offset
4351 * @type {number}
4352 * @const
4353 */
4354 wrapper.HEAP_DATA = 0x4000;
4355
4356 return wrapper;
4357}();
4358
4359function is_bytes(a) {
4360 return a instanceof Uint8Array;
4361}
4362function _heap_init(heap, heapSize) {
4363 const size = heap ? heap.byteLength : heapSize || 65536;
4364 if (size & 0xfff || size <= 0)
4365 throw new Error('heap size must be a positive integer and a multiple of 4096');
4366 heap = heap || new Uint8Array(new ArrayBuffer(size));
4367 return heap;
4368}
4369function _heap_write(heap, hpos, data, dpos, dlen) {
4370 const hlen = heap.length - hpos;
4371 const wlen = hlen < dlen ? hlen : dlen;
4372 heap.set(data.subarray(dpos, dpos + wlen), hpos);
4373 return wlen;
4374}
4375function joinBytes(...arg) {
4376 const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);
4377 const ret = new Uint8Array(totalLenght);
4378 let cursor = 0;
4379 for (let i = 0; i < arg.length; i++) {
4380 ret.set(arg[i], cursor);
4381 cursor += arg[i].length;
4382 }
4383 return ret;
4384}
4385
4386class IllegalStateError extends Error {
4387 constructor(...args) {
4388 super(...args);
4389 }
4390}
4391class IllegalArgumentError extends Error {
4392 constructor(...args) {
4393 super(...args);
4394 }
4395}
4396class SecurityError extends Error {
4397 constructor(...args) {
4398 super(...args);
4399 }
4400}
4401
4402const heap_pool = [];
4403const asm_pool = [];
4404class AES {
4405 constructor(key, iv, padding = true, mode, heap, asm) {
4406 this.pos = 0;
4407 this.len = 0;
4408 this.mode = mode;
4409 // The AES object state
4410 this.pos = 0;
4411 this.len = 0;
4412 this.key = key;
4413 this.iv = iv;
4414 this.padding = padding;
4415 // The AES "worker"
4416 this.acquire_asm(heap, asm);
4417 }
4418 acquire_asm(heap, asm) {
4419 if (this.heap === undefined || this.asm === undefined) {
4420 this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);
4421 this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);
4422 this.reset(this.key, this.iv);
4423 }
4424 return { heap: this.heap, asm: this.asm };
4425 }
4426 release_asm() {
4427 if (this.heap !== undefined && this.asm !== undefined) {
4428 heap_pool.push(this.heap);
4429 asm_pool.push(this.asm);
4430 }
4431 this.heap = undefined;
4432 this.asm = undefined;
4433 }
4434 reset(key, iv) {
4435 const { asm } = this.acquire_asm();
4436 // Key
4437 const keylen = key.length;
4438 if (keylen !== 16 && keylen !== 24 && keylen !== 32)
4439 throw new IllegalArgumentError('illegal key size');
4440 const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
4441 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);
4442 // IV
4443 if (iv !== undefined) {
4444 if (iv.length !== 16)
4445 throw new IllegalArgumentError('illegal iv size');
4446 let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
4447 asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
4448 }
4449 else {
4450 asm.set_iv(0, 0, 0, 0);
4451 }
4452 }
4453 AES_Encrypt_process(data) {
4454 if (!is_bytes(data))
4455 throw new TypeError("data isn't of expected type");
4456 let { heap, asm } = this.acquire_asm();
4457 let amode = AES_asm.ENC[this.mode];
4458 let hpos = AES_asm.HEAP_DATA;
4459 let pos = this.pos;
4460 let len = this.len;
4461 let dpos = 0;
4462 let dlen = data.length || 0;
4463 let rpos = 0;
4464 let rlen = (len + dlen) & -16;
4465 let wlen = 0;
4466 let result = new Uint8Array(rlen);
4467 while (dlen > 0) {
4468 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4469 len += wlen;
4470 dpos += wlen;
4471 dlen -= wlen;
4472 wlen = asm.cipher(amode, hpos + pos, len);
4473 if (wlen)
4474 result.set(heap.subarray(pos, pos + wlen), rpos);
4475 rpos += wlen;
4476 if (wlen < len) {
4477 pos += wlen;
4478 len -= wlen;
4479 }
4480 else {
4481 pos = 0;
4482 len = 0;
4483 }
4484 }
4485 this.pos = pos;
4486 this.len = len;
4487 return result;
4488 }
4489 AES_Encrypt_finish() {
4490 let { heap, asm } = this.acquire_asm();
4491 let amode = AES_asm.ENC[this.mode];
4492 let hpos = AES_asm.HEAP_DATA;
4493 let pos = this.pos;
4494 let len = this.len;
4495 let plen = 16 - (len % 16);
4496 let rlen = len;
4497 if (this.hasOwnProperty('padding')) {
4498 if (this.padding) {
4499 for (let p = 0; p < plen; ++p) {
4500 heap[pos + len + p] = plen;
4501 }
4502 len += plen;
4503 rlen = len;
4504 }
4505 else if (len % 16) {
4506 throw new IllegalArgumentError('data length must be a multiple of the block size');
4507 }
4508 }
4509 else {
4510 len += plen;
4511 }
4512 const result = new Uint8Array(rlen);
4513 if (len)
4514 asm.cipher(amode, hpos + pos, len);
4515 if (rlen)
4516 result.set(heap.subarray(pos, pos + rlen));
4517 this.pos = 0;
4518 this.len = 0;
4519 this.release_asm();
4520 return result;
4521 }
4522 AES_Decrypt_process(data) {
4523 if (!is_bytes(data))
4524 throw new TypeError("data isn't of expected type");
4525 let { heap, asm } = this.acquire_asm();
4526 let amode = AES_asm.DEC[this.mode];
4527 let hpos = AES_asm.HEAP_DATA;
4528 let pos = this.pos;
4529 let len = this.len;
4530 let dpos = 0;
4531 let dlen = data.length || 0;
4532 let rpos = 0;
4533 let rlen = (len + dlen) & -16;
4534 let plen = 0;
4535 let wlen = 0;
4536 if (this.padding) {
4537 plen = len + dlen - rlen || 16;
4538 rlen -= plen;
4539 }
4540 const result = new Uint8Array(rlen);
4541 while (dlen > 0) {
4542 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4543 len += wlen;
4544 dpos += wlen;
4545 dlen -= wlen;
4546 wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
4547 if (wlen)
4548 result.set(heap.subarray(pos, pos + wlen), rpos);
4549 rpos += wlen;
4550 if (wlen < len) {
4551 pos += wlen;
4552 len -= wlen;
4553 }
4554 else {
4555 pos = 0;
4556 len = 0;
4557 }
4558 }
4559 this.pos = pos;
4560 this.len = len;
4561 return result;
4562 }
4563 AES_Decrypt_finish() {
4564 let { heap, asm } = this.acquire_asm();
4565 let amode = AES_asm.DEC[this.mode];
4566 let hpos = AES_asm.HEAP_DATA;
4567 let pos = this.pos;
4568 let len = this.len;
4569 let rlen = len;
4570 if (len > 0) {
4571 if (len % 16) {
4572 if (this.hasOwnProperty('padding')) {
4573 throw new IllegalArgumentError('data length must be a multiple of the block size');
4574 }
4575 else {
4576 len += 16 - (len % 16);
4577 }
4578 }
4579 asm.cipher(amode, hpos + pos, len);
4580 if (this.hasOwnProperty('padding') && this.padding) {
4581 let pad = heap[pos + rlen - 1];
4582 if (pad < 1 || pad > 16 || pad > rlen)
4583 throw new SecurityError('bad padding');
4584 let pcheck = 0;
4585 for (let i = pad; i > 1; i--)
4586 pcheck |= pad ^ heap[pos + rlen - i];
4587 if (pcheck)
4588 throw new SecurityError('bad padding');
4589 rlen -= pad;
4590 }
4591 }
4592 const result = new Uint8Array(rlen);
4593 if (rlen > 0) {
4594 result.set(heap.subarray(pos, pos + rlen));
4595 }
4596 this.pos = 0;
4597 this.len = 0;
4598 this.release_asm();
4599 return result;
4600 }
4601}
4602
4603class AES_ECB {
4604 static encrypt(data, key, padding = false) {
4605 return new AES_ECB(key, padding).encrypt(data);
4606 }
4607 static decrypt(data, key, padding = false) {
4608 return new AES_ECB(key, padding).decrypt(data);
4609 }
4610 constructor(key, padding = false, aes) {
4611 this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');
4612 }
4613 encrypt(data) {
4614 const r1 = this.aes.AES_Encrypt_process(data);
4615 const r2 = this.aes.AES_Encrypt_finish();
4616 return joinBytes(r1, r2);
4617 }
4618 decrypt(data) {
4619 const r1 = this.aes.AES_Decrypt_process(data);
4620 const r2 = this.aes.AES_Decrypt_finish();
4621 return joinBytes(r1, r2);
4622 }
4623}
4624
4625/**
4626 * Javascript AES implementation.
4627 * This is used as fallback if the native Crypto APIs are not available.
4628 */
4629function aes(length) {
4630 const C = function(key) {
4631 const aesECB = new AES_ECB(key);
4632
4633 this.encrypt = function(block) {
4634 return aesECB.encrypt(block);
4635 };
4636
4637 this.decrypt = function(block) {
4638 return aesECB.decrypt(block);
4639 };
4640 };
4641
4642 C.blockSize = C.prototype.blockSize = 16;
4643 C.keySize = C.prototype.keySize = length / 8;
4644
4645 return C;
4646}
4647
4648//Paul Tero, July 2001
4649//http://www.tero.co.uk/des/
4650//
4651//Optimised for performance with large blocks by Michael Hayworth, November 2001
4652//http://www.netdealing.com
4653//
4654// Modified by Recurity Labs GmbH
4655
4656//THIS SOFTWARE IS PROVIDED "AS IS" AND
4657//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4658//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4659//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4660//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4661//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4662//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4663//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4664//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4665//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4666//SUCH DAMAGE.
4667
4668//des
4669//this takes the key, the message, and whether to encrypt or decrypt
4670
4671function des(keys, message, encrypt, mode, iv, padding) {
4672 //declaring this locally speeds things up a bit
4673 const spfunction1 = [
4674 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
4675 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
4676 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
4677 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
4678 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
4679 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
4680 ];
4681 const spfunction2 = [
4682 -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,
4683 -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,
4684 -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,
4685 -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,
4686 -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,
4687 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,
4688 -0x7fef7fe0, 0x108000
4689 ];
4690 const spfunction3 = [
4691 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
4692 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
4693 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
4694 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
4695 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
4696 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
4697 ];
4698 const spfunction4 = [
4699 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
4700 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
4701 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
4702 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
4703 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
4704 ];
4705 const spfunction5 = [
4706 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
4707 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
4708 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
4709 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
4710 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
4711 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
4712 0x40080000, 0x2080100, 0x40000100
4713 ];
4714 const spfunction6 = [
4715 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
4716 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
4717 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
4718 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
4719 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
4720 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
4721 ];
4722 const spfunction7 = [
4723 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
4724 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
4725 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
4726 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
4727 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
4728 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
4729 ];
4730 const spfunction8 = [
4731 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
4732 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
4733 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
4734 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
4735 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
4736 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
4737 ];
4738
4739 //create the 16 or 48 subkeys we will need
4740 let m = 0;
4741 let i;
4742 let j;
4743 let temp;
4744 let right1;
4745 let right2;
4746 let left;
4747 let right;
4748 let looping;
4749 let cbcleft;
4750 let cbcleft2;
4751 let cbcright;
4752 let cbcright2;
4753 let endloop;
4754 let loopinc;
4755 let len = message.length;
4756
4757 //set up the loops for single and triple des
4758 const iterations = keys.length === 32 ? 3 : 9; //single or triple des
4759 if (iterations === 3) {
4760 looping = encrypt ? [0, 32, 2] : [30, -2, -2];
4761 } else {
4762 looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
4763 }
4764
4765 //pad the message depending on the padding parameter
4766 //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
4767 if (encrypt) {
4768 message = desAddPadding(message, padding);
4769 len = message.length;
4770 }
4771
4772 //store the result here
4773 let result = new Uint8Array(len);
4774 let k = 0;
4775
4776 if (mode === 1) { //CBC mode
4777 cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4778 cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4779 m = 0;
4780 }
4781
4782 //loop through each 64 bit chunk of the message
4783 while (m < len) {
4784 left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4785 right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4786
4787 //for Cipher Block Chaining mode, xor the message with the previous result
4788 if (mode === 1) {
4789 if (encrypt) {
4790 left ^= cbcleft;
4791 right ^= cbcright;
4792 } else {
4793 cbcleft2 = cbcleft;
4794 cbcright2 = cbcright;
4795 cbcleft = left;
4796 cbcright = right;
4797 }
4798 }
4799
4800 //first each 64 but chunk of the message must be permuted according to IP
4801 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4802 right ^= temp;
4803 left ^= (temp << 4);
4804 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4805 right ^= temp;
4806 left ^= (temp << 16);
4807 temp = ((right >>> 2) ^ left) & 0x33333333;
4808 left ^= temp;
4809 right ^= (temp << 2);
4810 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4811 left ^= temp;
4812 right ^= (temp << 8);
4813 temp = ((left >>> 1) ^ right) & 0x55555555;
4814 right ^= temp;
4815 left ^= (temp << 1);
4816
4817 left = ((left << 1) | (left >>> 31));
4818 right = ((right << 1) | (right >>> 31));
4819
4820 //do this either 1 or 3 times for each chunk of the message
4821 for (j = 0; j < iterations; j += 3) {
4822 endloop = looping[j + 1];
4823 loopinc = looping[j + 2];
4824 //now go through and perform the encryption or decryption
4825 for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
4826 right1 = right ^ keys[i];
4827 right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
4828 //the result is attained by passing these bytes through the S selection functions
4829 temp = left;
4830 left = right;
4831 right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
4832 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
4833 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
4834 }
4835 temp = left;
4836 left = right;
4837 right = temp; //unreverse left and right
4838 } //for either 1 or 3 iterations
4839
4840 //move then each one bit to the right
4841 left = ((left >>> 1) | (left << 31));
4842 right = ((right >>> 1) | (right << 31));
4843
4844 //now perform IP-1, which is IP in the opposite direction
4845 temp = ((left >>> 1) ^ right) & 0x55555555;
4846 right ^= temp;
4847 left ^= (temp << 1);
4848 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4849 left ^= temp;
4850 right ^= (temp << 8);
4851 temp = ((right >>> 2) ^ left) & 0x33333333;
4852 left ^= temp;
4853 right ^= (temp << 2);
4854 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4855 right ^= temp;
4856 left ^= (temp << 16);
4857 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4858 right ^= temp;
4859 left ^= (temp << 4);
4860
4861 //for Cipher Block Chaining mode, xor the message with the previous result
4862 if (mode === 1) {
4863 if (encrypt) {
4864 cbcleft = left;
4865 cbcright = right;
4866 } else {
4867 left ^= cbcleft2;
4868 right ^= cbcright2;
4869 }
4870 }
4871
4872 result[k++] = (left >>> 24);
4873 result[k++] = ((left >>> 16) & 0xff);
4874 result[k++] = ((left >>> 8) & 0xff);
4875 result[k++] = (left & 0xff);
4876 result[k++] = (right >>> 24);
4877 result[k++] = ((right >>> 16) & 0xff);
4878 result[k++] = ((right >>> 8) & 0xff);
4879 result[k++] = (right & 0xff);
4880 } //for every 8 characters, or 64 bits in the message
4881
4882 //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
4883 if (!encrypt) {
4884 result = desRemovePadding(result, padding);
4885 }
4886
4887 return result;
4888} //end of des
4889
4890
4891//desCreateKeys
4892//this takes as input a 64 bit key (even though only 56 bits are used)
4893//as an array of 2 integers, and returns 16 48 bit keys
4894
4895function desCreateKeys(key) {
4896 //declaring this locally speeds things up a bit
4897 const pc2bytes0 = [
4898 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
4899 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
4900 ];
4901 const pc2bytes1 = [
4902 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
4903 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
4904 ];
4905 const pc2bytes2 = [
4906 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
4907 0x1000000, 0x1000008, 0x1000800, 0x1000808
4908 ];
4909 const pc2bytes3 = [
4910 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
4911 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
4912 ];
4913 const pc2bytes4 = [
4914 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
4915 0x41000, 0x1010, 0x41010
4916 ];
4917 const pc2bytes5 = [
4918 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
4919 0x2000000, 0x2000400, 0x2000020, 0x2000420
4920 ];
4921 const pc2bytes6 = [
4922 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
4923 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
4924 ];
4925 const pc2bytes7 = [
4926 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
4927 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
4928 ];
4929 const pc2bytes8 = [
4930 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
4931 0x2000002, 0x2040002, 0x2000002, 0x2040002
4932 ];
4933 const pc2bytes9 = [
4934 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
4935 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
4936 ];
4937 const pc2bytes10 = [
4938 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
4939 0x102000, 0x102020, 0x102000, 0x102020
4940 ];
4941 const pc2bytes11 = [
4942 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
4943 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
4944 ];
4945 const pc2bytes12 = [
4946 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
4947 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
4948 ];
4949 const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
4950
4951 //how many iterations (1 for des, 3 for triple des)
4952 const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
4953 //stores the return keys
4954 const keys = new Array(32 * iterations);
4955 //now define the left shifts which need to be done
4956 const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
4957 //other variables
4958 let lefttemp;
4959 let righttemp;
4960 let m = 0;
4961 let n = 0;
4962 let temp;
4963
4964 for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
4965 let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4966 let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4967
4968 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4969 right ^= temp;
4970 left ^= (temp << 4);
4971 temp = ((right >>> -16) ^ left) & 0x0000ffff;
4972 left ^= temp;
4973 right ^= (temp << -16);
4974 temp = ((left >>> 2) ^ right) & 0x33333333;
4975 right ^= temp;
4976 left ^= (temp << 2);
4977 temp = ((right >>> -16) ^ left) & 0x0000ffff;
4978 left ^= temp;
4979 right ^= (temp << -16);
4980 temp = ((left >>> 1) ^ right) & 0x55555555;
4981 right ^= temp;
4982 left ^= (temp << 1);
4983 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4984 left ^= temp;
4985 right ^= (temp << 8);
4986 temp = ((left >>> 1) ^ right) & 0x55555555;
4987 right ^= temp;
4988 left ^= (temp << 1);
4989
4990 //the right side needs to be shifted and to get the last four bits of the left side
4991 temp = (left << 8) | ((right >>> 20) & 0x000000f0);
4992 //left needs to be put upside down
4993 left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
4994 right = temp;
4995
4996 //now go through and perform these shifts on the left and right keys
4997 for (let i = 0; i < shifts.length; i++) {
4998 //shift the keys either one or two bits to the left
4999 if (shifts[i]) {
5000 left = (left << 2) | (left >>> 26);
5001 right = (right << 2) | (right >>> 26);
5002 } else {
5003 left = (left << 1) | (left >>> 27);
5004 right = (right << 1) | (right >>> 27);
5005 }
5006 left &= -0xf;
5007 right &= -0xf;
5008
5009 //now apply PC-2, in such a way that E is easier when encrypting or decrypting
5010 //this conversion will look like PC-2 except only the last 6 bits of each byte are used
5011 //rather than 48 consecutive bits and the order of lines will be according to
5012 //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
5013 lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(
5014 left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
5015 0xf];
5016 righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
5017 pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
5018 pc2bytes13[(right >>> 4) & 0xf];
5019 temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
5020 keys[n++] = lefttemp ^ temp;
5021 keys[n++] = righttemp ^ (temp << 16);
5022 }
5023 } //for each iterations
5024 //return the keys we've created
5025 return keys;
5026} //end of desCreateKeys
5027
5028
5029function desAddPadding(message, padding) {
5030 const padLength = 8 - (message.length % 8);
5031
5032 let pad;
5033 if (padding === 2 && (padLength < 8)) { //pad the message with spaces
5034 pad = ' '.charCodeAt(0);
5035 } else if (padding === 1) { //PKCS7 padding
5036 pad = padLength;
5037 } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
5038 pad = 0;
5039 } else if (padLength === 8) {
5040 return message;
5041 } else {
5042 throw new Error('des: invalid padding');
5043 }
5044
5045 const paddedMessage = new Uint8Array(message.length + padLength);
5046 for (let i = 0; i < message.length; i++) {
5047 paddedMessage[i] = message[i];
5048 }
5049 for (let j = 0; j < padLength; j++) {
5050 paddedMessage[message.length + j] = pad;
5051 }
5052
5053 return paddedMessage;
5054}
5055
5056function desRemovePadding(message, padding) {
5057 let padLength = null;
5058 let pad;
5059 if (padding === 2) { // space padded
5060 pad = ' '.charCodeAt(0);
5061 } else if (padding === 1) { // PKCS7
5062 padLength = message[message.length - 1];
5063 } else if (!padding) { // null padding
5064 pad = 0;
5065 } else {
5066 throw new Error('des: invalid padding');
5067 }
5068
5069 if (!padLength) {
5070 padLength = 1;
5071 while (message[message.length - padLength] === pad) {
5072 padLength++;
5073 }
5074 padLength--;
5075 }
5076
5077 return message.subarray(0, message.length - padLength);
5078}
5079
5080// added by Recurity Labs
5081
5082function TripleDES(key) {
5083 this.key = [];
5084
5085 for (let i = 0; i < 3; i++) {
5086 this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
5087 }
5088
5089 this.encrypt = function(block) {
5090 return des(
5091 desCreateKeys(this.key[2]),
5092 des(
5093 desCreateKeys(this.key[1]),
5094 des(
5095 desCreateKeys(this.key[0]),
5096 block, true, 0, null, null
5097 ),
5098 false, 0, null, null
5099 ), true, 0, null, null
5100 );
5101 };
5102}
5103
5104TripleDES.keySize = TripleDES.prototype.keySize = 24;
5105TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
5106
5107// This is "original" DES
5108
5109function DES(key) {
5110 this.key = key;
5111
5112 this.encrypt = function(block, padding) {
5113 const keys = desCreateKeys(this.key);
5114 return des(keys, block, true, 0, null, padding);
5115 };
5116
5117 this.decrypt = function(block, padding) {
5118 const keys = desCreateKeys(this.key);
5119 return des(keys, block, false, 0, null, padding);
5120 };
5121}
5122
5123// Use of this source code is governed by a BSD-style
5124// license that can be found in the LICENSE file.
5125
5126// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
5127
5128// Modified by Recurity Labs GmbH
5129
5130// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
5131// check www.haneWIN.de for the latest version
5132
5133// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
5134// CAST-128 is a common OpenPGP cipher.
5135
5136
5137// CAST5 constructor
5138
5139function OpenPGPSymEncCAST5() {
5140 this.BlockSize = 8;
5141 this.KeySize = 16;
5142
5143 this.setKey = function(key) {
5144 this.masking = new Array(16);
5145 this.rotate = new Array(16);
5146
5147 this.reset();
5148
5149 if (key.length === this.KeySize) {
5150 this.keySchedule(key);
5151 } else {
5152 throw new Error('CAST-128: keys must be 16 bytes');
5153 }
5154 return true;
5155 };
5156
5157 this.reset = function() {
5158 for (let i = 0; i < 16; i++) {
5159 this.masking[i] = 0;
5160 this.rotate[i] = 0;
5161 }
5162 };
5163
5164 this.getBlockSize = function() {
5165 return this.BlockSize;
5166 };
5167
5168 this.encrypt = function(src) {
5169 const dst = new Array(src.length);
5170
5171 for (let i = 0; i < src.length; i += 8) {
5172 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5173 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5174 let t;
5175
5176 t = r;
5177 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5178 l = t;
5179 t = r;
5180 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5181 l = t;
5182 t = r;
5183 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5184 l = t;
5185 t = r;
5186 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5187 l = t;
5188
5189 t = r;
5190 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5191 l = t;
5192 t = r;
5193 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5194 l = t;
5195 t = r;
5196 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5197 l = t;
5198 t = r;
5199 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5200 l = t;
5201
5202 t = r;
5203 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5204 l = t;
5205 t = r;
5206 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5207 l = t;
5208 t = r;
5209 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5210 l = t;
5211 t = r;
5212 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5213 l = t;
5214
5215 t = r;
5216 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5217 l = t;
5218 t = r;
5219 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5220 l = t;
5221 t = r;
5222 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5223 l = t;
5224 t = r;
5225 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5226 l = t;
5227
5228 dst[i] = (r >>> 24) & 255;
5229 dst[i + 1] = (r >>> 16) & 255;
5230 dst[i + 2] = (r >>> 8) & 255;
5231 dst[i + 3] = r & 255;
5232 dst[i + 4] = (l >>> 24) & 255;
5233 dst[i + 5] = (l >>> 16) & 255;
5234 dst[i + 6] = (l >>> 8) & 255;
5235 dst[i + 7] = l & 255;
5236 }
5237
5238 return dst;
5239 };
5240
5241 this.decrypt = function(src) {
5242 const dst = new Array(src.length);
5243
5244 for (let i = 0; i < src.length; i += 8) {
5245 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5246 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5247 let t;
5248
5249 t = r;
5250 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5251 l = t;
5252 t = r;
5253 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5254 l = t;
5255 t = r;
5256 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5257 l = t;
5258 t = r;
5259 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5260 l = t;
5261
5262 t = r;
5263 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5264 l = t;
5265 t = r;
5266 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5267 l = t;
5268 t = r;
5269 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5270 l = t;
5271 t = r;
5272 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5273 l = t;
5274
5275 t = r;
5276 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5277 l = t;
5278 t = r;
5279 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5280 l = t;
5281 t = r;
5282 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5283 l = t;
5284 t = r;
5285 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5286 l = t;
5287
5288 t = r;
5289 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5290 l = t;
5291 t = r;
5292 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5293 l = t;
5294 t = r;
5295 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5296 l = t;
5297 t = r;
5298 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5299 l = t;
5300
5301 dst[i] = (r >>> 24) & 255;
5302 dst[i + 1] = (r >>> 16) & 255;
5303 dst[i + 2] = (r >>> 8) & 255;
5304 dst[i + 3] = r & 255;
5305 dst[i + 4] = (l >>> 24) & 255;
5306 dst[i + 5] = (l >> 16) & 255;
5307 dst[i + 6] = (l >> 8) & 255;
5308 dst[i + 7] = l & 255;
5309 }
5310
5311 return dst;
5312 };
5313 const scheduleA = new Array(4);
5314
5315 scheduleA[0] = new Array(4);
5316 scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
5317 scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5318 scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5319 scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5320
5321 scheduleA[1] = new Array(4);
5322 scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5323 scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5324 scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5325 scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5326
5327 scheduleA[2] = new Array(4);
5328 scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
5329 scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5330 scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5331 scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5332
5333
5334 scheduleA[3] = new Array(4);
5335 scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5336 scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5337 scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5338 scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5339
5340 const scheduleB = new Array(4);
5341
5342 scheduleB[0] = new Array(4);
5343 scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
5344 scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
5345 scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
5346 scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
5347
5348 scheduleB[1] = new Array(4);
5349 scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
5350 scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
5351 scheduleB[1][2] = [7, 6, 8, 9, 3];
5352 scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
5353
5354
5355 scheduleB[2] = new Array(4);
5356 scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
5357 scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
5358 scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
5359 scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
5360
5361
5362 scheduleB[3] = new Array(4);
5363 scheduleB[3][0] = [8, 9, 7, 6, 3];
5364 scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
5365 scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
5366 scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
5367
5368 // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
5369 this.keySchedule = function(inn) {
5370 const t = new Array(8);
5371 const k = new Array(32);
5372
5373 let j;
5374
5375 for (let i = 0; i < 4; i++) {
5376 j = i * 4;
5377 t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
5378 }
5379
5380 const x = [6, 7, 4, 5];
5381 let ki = 0;
5382 let w;
5383
5384 for (let half = 0; half < 2; half++) {
5385 for (let round = 0; round < 4; round++) {
5386 for (j = 0; j < 4; j++) {
5387 const a = scheduleA[round][j];
5388 w = t[a[1]];
5389
5390 w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
5391 w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
5392 w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
5393 w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
5394 w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
5395 t[a[0]] = w;
5396 }
5397
5398 for (j = 0; j < 4; j++) {
5399 const b = scheduleB[round][j];
5400 w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
5401
5402 w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
5403 w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
5404 w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
5405 w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
5406 k[ki] = w;
5407 ki++;
5408 }
5409 }
5410 }
5411
5412 for (let i = 0; i < 16; i++) {
5413 this.masking[i] = k[i];
5414 this.rotate[i] = k[16 + i] & 0x1f;
5415 }
5416 };
5417
5418 // These are the three 'f' functions. See RFC 2144, section 2.2.
5419
5420 function f1(d, m, r) {
5421 const t = m + d;
5422 const I = (t << r) | (t >>> (32 - r));
5423 return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
5424 }
5425
5426 function f2(d, m, r) {
5427 const t = m ^ d;
5428 const I = (t << r) | (t >>> (32 - r));
5429 return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
5430 }
5431
5432 function f3(d, m, r) {
5433 const t = m - d;
5434 const I = (t << r) | (t >>> (32 - r));
5435 return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
5436 }
5437
5438 const sBox = new Array(8);
5439 sBox[0] = [
5440 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
5441 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
5442 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
5443 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
5444 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
5445 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
5446 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
5447 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
5448 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
5449 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
5450 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
5451 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
5452 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
5453 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
5454 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
5455 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
5456 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
5457 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
5458 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
5459 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
5460 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
5461 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
5462 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
5463 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
5464 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
5465 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
5466 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
5467 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
5468 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
5469 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
5470 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
5471 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
5472 ];
5473
5474 sBox[1] = [
5475 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
5476 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
5477 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
5478 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
5479 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
5480 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
5481 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
5482 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
5483 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
5484 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
5485 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
5486 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
5487 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
5488 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
5489 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
5490 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
5491 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
5492 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
5493 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
5494 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
5495 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
5496 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
5497 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
5498 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
5499 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
5500 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
5501 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
5502 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
5503 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
5504 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
5505 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
5506 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
5507 ];
5508
5509 sBox[2] = [
5510 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
5511 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
5512 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
5513 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
5514 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
5515 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
5516 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
5517 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
5518 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
5519 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
5520 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
5521 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
5522 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
5523 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
5524 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
5525 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
5526 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
5527 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
5528 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
5529 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
5530 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
5531 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
5532 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
5533 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
5534 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
5535 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
5536 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
5537 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
5538 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
5539 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
5540 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
5541 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
5542 ];
5543
5544 sBox[3] = [
5545 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
5546 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
5547 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
5548 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
5549 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
5550 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
5551 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
5552 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
5553 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
5554 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
5555 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
5556 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
5557 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
5558 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
5559 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
5560 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
5561 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
5562 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
5563 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
5564 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
5565 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
5566 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
5567 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
5568 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
5569 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
5570 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
5571 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
5572 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
5573 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
5574 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
5575 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
5576 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
5577 ];
5578
5579 sBox[4] = [
5580 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
5581 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
5582 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
5583 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
5584 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
5585 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
5586 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
5587 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
5588 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
5589 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
5590 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
5591 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
5592 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
5593 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
5594 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
5595 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
5596 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
5597 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
5598 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
5599 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
5600 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
5601 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
5602 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
5603 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
5604 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
5605 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
5606 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
5607 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
5608 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
5609 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
5610 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
5611 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
5612 ];
5613
5614 sBox[5] = [
5615 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
5616 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
5617 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
5618 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
5619 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
5620 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
5621 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
5622 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
5623 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
5624 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
5625 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
5626 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
5627 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
5628 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
5629 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
5630 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
5631 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
5632 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
5633 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
5634 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
5635 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
5636 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
5637 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
5638 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
5639 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
5640 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
5641 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
5642 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
5643 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
5644 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
5645 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
5646 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
5647 ];
5648
5649 sBox[6] = [
5650 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
5651 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
5652 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
5653 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
5654 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
5655 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
5656 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
5657 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
5658 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
5659 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
5660 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
5661 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
5662 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
5663 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
5664 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
5665 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
5666 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
5667 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
5668 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
5669 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
5670 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
5671 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
5672 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
5673 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
5674 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
5675 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
5676 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
5677 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
5678 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
5679 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
5680 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
5681 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
5682 ];
5683
5684 sBox[7] = [
5685 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
5686 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
5687 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
5688 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
5689 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
5690 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
5691 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
5692 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
5693 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
5694 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
5695 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
5696 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
5697 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
5698 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
5699 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
5700 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
5701 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
5702 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
5703 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
5704 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
5705 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
5706 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
5707 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
5708 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
5709 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
5710 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
5711 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
5712 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
5713 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
5714 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
5715 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
5716 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
5717 ];
5718}
5719
5720function CAST5(key) {
5721 this.cast5 = new OpenPGPSymEncCAST5();
5722 this.cast5.setKey(key);
5723
5724 this.encrypt = function(block) {
5725 return this.cast5.encrypt(block);
5726 };
5727}
5728
5729CAST5.blockSize = CAST5.prototype.blockSize = 8;
5730CAST5.keySize = CAST5.prototype.keySize = 16;
5731
5732/* eslint-disable no-mixed-operators, no-fallthrough */
5733
5734
5735/* Modified by Recurity Labs GmbH
5736 *
5737 * Cipher.js
5738 * A block-cipher algorithm implementation on JavaScript
5739 * See Cipher.readme.txt for further information.
5740 *
5741 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
5742 * This script file is distributed under the LGPL
5743 *
5744 * ACKNOWLEDGMENT
5745 *
5746 * The main subroutines are written by Michiel van Everdingen.
5747 *
5748 * Michiel van Everdingen
5749 * http://home.versatel.nl/MAvanEverdingen/index.html
5750 *
5751 * All rights for these routines are reserved to Michiel van Everdingen.
5752 *
5753 */
5754
5755////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5756//Math
5757////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5758
5759const MAXINT = 0xFFFFFFFF;
5760
5761function rotw(w, n) {
5762 return (w << n | w >>> (32 - n)) & MAXINT;
5763}
5764
5765function getW(a, i) {
5766 return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
5767}
5768
5769function setW(a, i, w) {
5770 a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
5771}
5772
5773function getB(x, n) {
5774 return (x >>> (n * 8)) & 0xFF;
5775}
5776
5777// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5778// Twofish
5779// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5780
5781function createTwofish() {
5782 //
5783 let keyBytes = null;
5784 let dataBytes = null;
5785 let dataOffset = -1;
5786 // var dataLength = -1;
5787 // var idx2 = -1;
5788 //
5789
5790 let tfsKey = [];
5791 let tfsM = [
5792 [],
5793 [],
5794 [],
5795 []
5796 ];
5797
5798 function tfsInit(key) {
5799 keyBytes = key;
5800 let i;
5801 let a;
5802 let b;
5803 let c;
5804 let d;
5805 const meKey = [];
5806 const moKey = [];
5807 const inKey = [];
5808 let kLen;
5809 const sKey = [];
5810 let f01;
5811 let f5b;
5812 let fef;
5813
5814 const q0 = [
5815 [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
5816 [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
5817 ];
5818 const q1 = [
5819 [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
5820 [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
5821 ];
5822 const q2 = [
5823 [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
5824 [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
5825 ];
5826 const q3 = [
5827 [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
5828 [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
5829 ];
5830 const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
5831 const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
5832 const q = [
5833 [],
5834 []
5835 ];
5836 const m = [
5837 [],
5838 [],
5839 [],
5840 []
5841 ];
5842
5843 function ffm5b(x) {
5844 return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
5845 }
5846
5847 function ffmEf(x) {
5848 return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
5849 }
5850
5851 function mdsRem(p, q) {
5852 let i;
5853 let t;
5854 let u;
5855 for (i = 0; i < 8; i++) {
5856 t = q >>> 24;
5857 q = ((q << 8) & MAXINT) | p >>> 24;
5858 p = (p << 8) & MAXINT;
5859 u = t << 1;
5860 if (t & 128) {
5861 u ^= 333;
5862 }
5863 q ^= t ^ (u << 16);
5864 u ^= t >>> 1;
5865 if (t & 1) {
5866 u ^= 166;
5867 }
5868 q ^= u << 24 | u << 8;
5869 }
5870 return q;
5871 }
5872
5873 function qp(n, x) {
5874 const a = x >> 4;
5875 const b = x & 15;
5876 const c = q0[n][a ^ b];
5877 const d = q1[n][ror4[b] ^ ashx[a]];
5878 return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
5879 }
5880
5881 function hFun(x, key) {
5882 let a = getB(x, 0);
5883 let b = getB(x, 1);
5884 let c = getB(x, 2);
5885 let d = getB(x, 3);
5886 switch (kLen) {
5887 case 4:
5888 a = q[1][a] ^ getB(key[3], 0);
5889 b = q[0][b] ^ getB(key[3], 1);
5890 c = q[0][c] ^ getB(key[3], 2);
5891 d = q[1][d] ^ getB(key[3], 3);
5892 case 3:
5893 a = q[1][a] ^ getB(key[2], 0);
5894 b = q[1][b] ^ getB(key[2], 1);
5895 c = q[0][c] ^ getB(key[2], 2);
5896 d = q[0][d] ^ getB(key[2], 3);
5897 case 2:
5898 a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
5899 b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
5900 c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
5901 d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
5902 }
5903 return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
5904 }
5905
5906 keyBytes = keyBytes.slice(0, 32);
5907 i = keyBytes.length;
5908 while (i !== 16 && i !== 24 && i !== 32) {
5909 keyBytes[i++] = 0;
5910 }
5911
5912 for (i = 0; i < keyBytes.length; i += 4) {
5913 inKey[i >> 2] = getW(keyBytes, i);
5914 }
5915 for (i = 0; i < 256; i++) {
5916 q[0][i] = qp(0, i);
5917 q[1][i] = qp(1, i);
5918 }
5919 for (i = 0; i < 256; i++) {
5920 f01 = q[1][i];
5921 f5b = ffm5b(f01);
5922 fef = ffmEf(f01);
5923 m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
5924 m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
5925 f01 = q[0][i];
5926 f5b = ffm5b(f01);
5927 fef = ffmEf(f01);
5928 m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
5929 m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
5930 }
5931
5932 kLen = inKey.length / 2;
5933 for (i = 0; i < kLen; i++) {
5934 a = inKey[i + i];
5935 meKey[i] = a;
5936 b = inKey[i + i + 1];
5937 moKey[i] = b;
5938 sKey[kLen - i - 1] = mdsRem(a, b);
5939 }
5940 for (i = 0; i < 40; i += 2) {
5941 a = 0x1010101 * i;
5942 b = a + 0x1010101;
5943 a = hFun(a, meKey);
5944 b = rotw(hFun(b, moKey), 8);
5945 tfsKey[i] = (a + b) & MAXINT;
5946 tfsKey[i + 1] = rotw(a + 2 * b, 9);
5947 }
5948 for (i = 0; i < 256; i++) {
5949 a = b = c = d = i;
5950 switch (kLen) {
5951 case 4:
5952 a = q[1][a] ^ getB(sKey[3], 0);
5953 b = q[0][b] ^ getB(sKey[3], 1);
5954 c = q[0][c] ^ getB(sKey[3], 2);
5955 d = q[1][d] ^ getB(sKey[3], 3);
5956 case 3:
5957 a = q[1][a] ^ getB(sKey[2], 0);
5958 b = q[1][b] ^ getB(sKey[2], 1);
5959 c = q[0][c] ^ getB(sKey[2], 2);
5960 d = q[0][d] ^ getB(sKey[2], 3);
5961 case 2:
5962 tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
5963 tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
5964 tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
5965 tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
5966 }
5967 }
5968 }
5969
5970 function tfsG0(x) {
5971 return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
5972 }
5973
5974 function tfsG1(x) {
5975 return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
5976 }
5977
5978 function tfsFrnd(r, blk) {
5979 let a = tfsG0(blk[0]);
5980 let b = tfsG1(blk[1]);
5981 blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
5982 blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
5983 a = tfsG0(blk[2]);
5984 b = tfsG1(blk[3]);
5985 blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
5986 blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
5987 }
5988
5989 function tfsIrnd(i, blk) {
5990 let a = tfsG0(blk[0]);
5991 let b = tfsG1(blk[1]);
5992 blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
5993 blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
5994 a = tfsG0(blk[2]);
5995 b = tfsG1(blk[3]);
5996 blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
5997 blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
5998 }
5999
6000 function tfsClose() {
6001 tfsKey = [];
6002 tfsM = [
6003 [],
6004 [],
6005 [],
6006 []
6007 ];
6008 }
6009
6010 function tfsEncrypt(data, offset) {
6011 dataBytes = data;
6012 dataOffset = offset;
6013 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
6014 getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
6015 getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
6016 getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
6017 for (let j = 0; j < 8; j++) {
6018 tfsFrnd(j, blk);
6019 }
6020 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
6021 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
6022 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
6023 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
6024 dataOffset += 16;
6025 return dataBytes;
6026 }
6027
6028 function tfsDecrypt(data, offset) {
6029 dataBytes = data;
6030 dataOffset = offset;
6031 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
6032 getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
6033 getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
6034 getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
6035 for (let j = 7; j >= 0; j--) {
6036 tfsIrnd(j, blk);
6037 }
6038 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
6039 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
6040 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
6041 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
6042 dataOffset += 16;
6043 }
6044
6045 // added by Recurity Labs
6046
6047 function tfsFinal() {
6048 return dataBytes;
6049 }
6050
6051 return {
6052 name: 'twofish',
6053 blocksize: 128 / 8,
6054 open: tfsInit,
6055 close: tfsClose,
6056 encrypt: tfsEncrypt,
6057 decrypt: tfsDecrypt,
6058 // added by Recurity Labs
6059 finalize: tfsFinal
6060 };
6061}
6062
6063// added by Recurity Labs
6064
6065function TF(key) {
6066 this.tf = createTwofish();
6067 this.tf.open(Array.from(key), 0);
6068
6069 this.encrypt = function(block) {
6070 return this.tf.encrypt(Array.from(block), 0);
6071 };
6072}
6073
6074TF.keySize = TF.prototype.keySize = 32;
6075TF.blockSize = TF.prototype.blockSize = 16;
6076
6077/* Modified by Recurity Labs GmbH
6078 *
6079 * Originally written by nklein software (nklein.com)
6080 */
6081
6082/*
6083 * Javascript implementation based on Bruce Schneier's reference implementation.
6084 *
6085 *
6086 * The constructor doesn't do much of anything. It's just here
6087 * so we can start defining properties and methods and such.
6088 */
6089function Blowfish() {}
6090
6091/*
6092 * Declare the block size so that protocols know what size
6093 * Initialization Vector (IV) they will need.
6094 */
6095Blowfish.prototype.BLOCKSIZE = 8;
6096
6097/*
6098 * These are the default SBOXES.
6099 */
6100Blowfish.prototype.SBOXES = [
6101 [
6102 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
6103 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
6104 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
6105 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
6106 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
6107 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
6108 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
6109 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
6110 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
6111 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
6112 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
6113 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
6114 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
6115 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
6116 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
6117 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
6118 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
6119 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
6120 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
6121 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
6122 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
6123 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
6124 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
6125 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
6126 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
6127 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
6128 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
6129 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
6130 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
6131 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
6132 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
6133 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
6134 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
6135 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
6136 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
6137 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
6138 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
6139 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
6140 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
6141 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
6142 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
6143 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
6144 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
6145 ],
6146 [
6147 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
6148 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
6149 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
6150 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
6151 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
6152 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
6153 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
6154 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
6155 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
6156 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
6157 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
6158 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
6159 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
6160 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
6161 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
6162 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
6163 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
6164 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
6165 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
6166 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
6167 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
6168 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
6169 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
6170 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
6171 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
6172 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
6173 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
6174 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
6175 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
6176 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
6177 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
6178 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
6179 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
6180 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
6181 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
6182 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
6183 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
6184 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
6185 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
6186 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
6187 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
6188 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
6189 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
6190 ],
6191 [
6192 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
6193 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
6194 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
6195 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
6196 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
6197 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
6198 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
6199 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
6200 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
6201 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
6202 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
6203 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
6204 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
6205 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
6206 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
6207 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
6208 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
6209 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
6210 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
6211 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
6212 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
6213 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
6214 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
6215 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
6216 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
6217 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
6218 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
6219 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
6220 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
6221 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
6222 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
6223 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
6224 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
6225 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
6226 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
6227 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
6228 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
6229 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
6230 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
6231 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
6232 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
6233 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
6234 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
6235 ],
6236 [
6237 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
6238 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
6239 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
6240 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
6241 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
6242 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
6243 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
6244 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
6245 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
6246 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
6247 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
6248 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
6249 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
6250 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
6251 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
6252 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
6253 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
6254 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
6255 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
6256 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
6257 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
6258 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
6259 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
6260 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
6261 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
6262 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
6263 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
6264 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
6265 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
6266 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
6267 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
6268 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
6269 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
6270 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
6271 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
6272 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
6273 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
6274 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
6275 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
6276 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
6277 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
6278 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
6279 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
6280 ]
6281];
6282
6283//*
6284//* This is the default PARRAY
6285//*
6286Blowfish.prototype.PARRAY = [
6287 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
6288 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
6289 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
6290];
6291
6292//*
6293//* This is the number of rounds the cipher will go
6294//*
6295Blowfish.prototype.NN = 16;
6296
6297//*
6298//* This function is needed to get rid of problems
6299//* with the high-bit getting set. If we don't do
6300//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
6301//* equal to ( bb & 0x00FFFFFFFF ) even when they
6302//* agree bit-for-bit for the first 32 bits.
6303//*
6304Blowfish.prototype._clean = function(xx) {
6305 if (xx < 0) {
6306 const yy = xx & 0x7FFFFFFF;
6307 xx = yy + 0x80000000;
6308 }
6309 return xx;
6310};
6311
6312//*
6313//* This is the mixing function that uses the sboxes
6314//*
6315Blowfish.prototype._F = function(xx) {
6316 let yy;
6317
6318 const dd = xx & 0x00FF;
6319 xx >>>= 8;
6320 const cc = xx & 0x00FF;
6321 xx >>>= 8;
6322 const bb = xx & 0x00FF;
6323 xx >>>= 8;
6324 const aa = xx & 0x00FF;
6325
6326 yy = this.sboxes[0][aa] + this.sboxes[1][bb];
6327 yy ^= this.sboxes[2][cc];
6328 yy += this.sboxes[3][dd];
6329
6330 return yy;
6331};
6332
6333//*
6334//* This method takes an array with two values, left and right
6335//* and does NN rounds of Blowfish on them.
6336//*
6337Blowfish.prototype._encryptBlock = function(vals) {
6338 let dataL = vals[0];
6339 let dataR = vals[1];
6340
6341 let ii;
6342
6343 for (ii = 0; ii < this.NN; ++ii) {
6344 dataL ^= this.parray[ii];
6345 dataR = this._F(dataL) ^ dataR;
6346
6347 const tmp = dataL;
6348 dataL = dataR;
6349 dataR = tmp;
6350 }
6351
6352 dataL ^= this.parray[this.NN + 0];
6353 dataR ^= this.parray[this.NN + 1];
6354
6355 vals[0] = this._clean(dataR);
6356 vals[1] = this._clean(dataL);
6357};
6358
6359//*
6360//* This method takes a vector of numbers and turns them
6361//* into long words so that they can be processed by the
6362//* real algorithm.
6363//*
6364//* Maybe I should make the real algorithm above take a vector
6365//* instead. That will involve more looping, but it won't require
6366//* the F() method to deconstruct the vector.
6367//*
6368Blowfish.prototype.encryptBlock = function(vector) {
6369 let ii;
6370 const vals = [0, 0];
6371 const off = this.BLOCKSIZE / 2;
6372 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6373 vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
6374 vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
6375 }
6376
6377 this._encryptBlock(vals);
6378
6379 const ret = [];
6380 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6381 ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
6382 ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
6383 // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
6384 // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
6385 }
6386
6387 return ret;
6388};
6389
6390//*
6391//* This method takes an array with two values, left and right
6392//* and undoes NN rounds of Blowfish on them.
6393//*
6394Blowfish.prototype._decryptBlock = function(vals) {
6395 let dataL = vals[0];
6396 let dataR = vals[1];
6397
6398 let ii;
6399
6400 for (ii = this.NN + 1; ii > 1; --ii) {
6401 dataL ^= this.parray[ii];
6402 dataR = this._F(dataL) ^ dataR;
6403
6404 const tmp = dataL;
6405 dataL = dataR;
6406 dataR = tmp;
6407 }
6408
6409 dataL ^= this.parray[1];
6410 dataR ^= this.parray[0];
6411
6412 vals[0] = this._clean(dataR);
6413 vals[1] = this._clean(dataL);
6414};
6415
6416//*
6417//* This method takes a key array and initializes the
6418//* sboxes and parray for this encryption.
6419//*
6420Blowfish.prototype.init = function(key) {
6421 let ii;
6422 let jj = 0;
6423
6424 this.parray = [];
6425 for (ii = 0; ii < this.NN + 2; ++ii) {
6426 let data = 0x00000000;
6427 for (let kk = 0; kk < 4; ++kk) {
6428 data = (data << 8) | (key[jj] & 0x00FF);
6429 if (++jj >= key.length) {
6430 jj = 0;
6431 }
6432 }
6433 this.parray[ii] = this.PARRAY[ii] ^ data;
6434 }
6435
6436 this.sboxes = [];
6437 for (ii = 0; ii < 4; ++ii) {
6438 this.sboxes[ii] = [];
6439 for (jj = 0; jj < 256; ++jj) {
6440 this.sboxes[ii][jj] = this.SBOXES[ii][jj];
6441 }
6442 }
6443
6444 const vals = [0x00000000, 0x00000000];
6445
6446 for (ii = 0; ii < this.NN + 2; ii += 2) {
6447 this._encryptBlock(vals);
6448 this.parray[ii + 0] = vals[0];
6449 this.parray[ii + 1] = vals[1];
6450 }
6451
6452 for (ii = 0; ii < 4; ++ii) {
6453 for (jj = 0; jj < 256; jj += 2) {
6454 this._encryptBlock(vals);
6455 this.sboxes[ii][jj + 0] = vals[0];
6456 this.sboxes[ii][jj + 1] = vals[1];
6457 }
6458 }
6459};
6460
6461// added by Recurity Labs
6462function BF(key) {
6463 this.bf = new Blowfish();
6464 this.bf.init(key);
6465
6466 this.encrypt = function(block) {
6467 return this.bf.encryptBlock(block);
6468 };
6469}
6470
6471BF.keySize = BF.prototype.keySize = 16;
6472BF.blockSize = BF.prototype.blockSize = 8;
6473
6474/**
6475 * @fileoverview Symmetric cryptography functions
6476 * @module crypto/cipher
6477 * @private
6478 */
6479
6480/**
6481 * AES-128 encryption and decryption (ID 7)
6482 * @function
6483 * @param {String} key - 128-bit key
6484 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6485 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6486 * @returns {Object}
6487 */
6488const aes128 = aes(128);
6489/**
6490 * AES-128 Block Cipher (ID 8)
6491 * @function
6492 * @param {String} key - 192-bit key
6493 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6494 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6495 * @returns {Object}
6496 */
6497const aes192 = aes(192);
6498/**
6499 * AES-128 Block Cipher (ID 9)
6500 * @function
6501 * @param {String} key - 256-bit key
6502 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6503 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6504 * @returns {Object}
6505 */
6506const aes256 = aes(256);
6507// Not in OpenPGP specifications
6508const des$1 = DES;
6509/**
6510 * Triple DES Block Cipher (ID 2)
6511 * @function
6512 * @param {String} key - 192-bit key
6513 * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
6514 * @returns {Object}
6515 */
6516const tripledes = TripleDES;
6517/**
6518 * CAST-128 Block Cipher (ID 3)
6519 * @function
6520 * @param {String} key - 128-bit key
6521 * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
6522 * @returns {Object}
6523 */
6524const cast5 = CAST5;
6525/**
6526 * Twofish Block Cipher (ID 10)
6527 * @function
6528 * @param {String} key - 256-bit key
6529 * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
6530 * @returns {Object}
6531 */
6532const twofish = TF;
6533/**
6534 * Blowfish Block Cipher (ID 4)
6535 * @function
6536 * @param {String} key - 128-bit key
6537 * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
6538 * @returns {Object}
6539 */
6540const blowfish = BF;
6541/**
6542 * Not implemented
6543 * @function
6544 * @throws {Error}
6545 */
6546const idea = function() {
6547 throw new Error('IDEA symmetric-key algorithm not implemented');
6548};
6549
6550var cipher = /*#__PURE__*/Object.freeze({
6551 __proto__: null,
6552 aes128: aes128,
6553 aes192: aes192,
6554 aes256: aes256,
6555 des: des$1,
6556 tripledes: tripledes,
6557 cast5: cast5,
6558 twofish: twofish,
6559 blowfish: blowfish,
6560 idea: idea
6561});
6562
6563var sha1_asm = function ( stdlib, foreign, buffer ) {
6564 "use asm";
6565
6566 // SHA256 state
6567 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
6568 TOTAL0 = 0, TOTAL1 = 0;
6569
6570 // HMAC state
6571 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
6572 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
6573
6574 // I/O buffer
6575 var HEAP = new stdlib.Uint8Array(buffer);
6576
6577 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
6578 w0 = w0|0;
6579 w1 = w1|0;
6580 w2 = w2|0;
6581 w3 = w3|0;
6582 w4 = w4|0;
6583 w5 = w5|0;
6584 w6 = w6|0;
6585 w7 = w7|0;
6586 w8 = w8|0;
6587 w9 = w9|0;
6588 w10 = w10|0;
6589 w11 = w11|0;
6590 w12 = w12|0;
6591 w13 = w13|0;
6592 w14 = w14|0;
6593 w15 = w15|0;
6594
6595 var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
6596 w16 = 0, w17 = 0, w18 = 0, w19 = 0,
6597 w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
6598 w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
6599 w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
6600 w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
6601 w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
6602 w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
6603
6604 a = H0;
6605 b = H1;
6606 c = H2;
6607 d = H3;
6608 e = H4;
6609
6610 // 0
6611 t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6612 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6613
6614 // 1
6615 t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6616 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6617
6618 // 2
6619 t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6620 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6621
6622 // 3
6623 t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6624 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6625
6626 // 4
6627 t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6628 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6629
6630 // 5
6631 t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6632 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6633
6634 // 6
6635 t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6636 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6637
6638 // 7
6639 t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6640 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6641
6642 // 8
6643 t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6644 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6645
6646 // 9
6647 t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6648 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6649
6650 // 10
6651 t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6652 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6653
6654 // 11
6655 t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6656 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6657
6658 // 12
6659 t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6660 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6661
6662 // 13
6663 t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6664 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6665
6666 // 14
6667 t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6668 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6669
6670 // 15
6671 t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6672 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6673
6674 // 16
6675 n = w13 ^ w8 ^ w2 ^ w0;
6676 w16 = (n << 1) | (n >>> 31);
6677 t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6678 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6679
6680 // 17
6681 n = w14 ^ w9 ^ w3 ^ w1;
6682 w17 = (n << 1) | (n >>> 31);
6683 t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6684 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6685
6686 // 18
6687 n = w15 ^ w10 ^ w4 ^ w2;
6688 w18 = (n << 1) | (n >>> 31);
6689 t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6690 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6691
6692 // 19
6693 n = w16 ^ w11 ^ w5 ^ w3;
6694 w19 = (n << 1) | (n >>> 31);
6695 t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6696 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6697
6698 // 20
6699 n = w17 ^ w12 ^ w6 ^ w4;
6700 w20 = (n << 1) | (n >>> 31);
6701 t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6702 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6703
6704 // 21
6705 n = w18 ^ w13 ^ w7 ^ w5;
6706 w21 = (n << 1) | (n >>> 31);
6707 t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6708 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6709
6710 // 22
6711 n = w19 ^ w14 ^ w8 ^ w6;
6712 w22 = (n << 1) | (n >>> 31);
6713 t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6714 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6715
6716 // 23
6717 n = w20 ^ w15 ^ w9 ^ w7;
6718 w23 = (n << 1) | (n >>> 31);
6719 t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6720 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6721
6722 // 24
6723 n = w21 ^ w16 ^ w10 ^ w8;
6724 w24 = (n << 1) | (n >>> 31);
6725 t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6726 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6727
6728 // 25
6729 n = w22 ^ w17 ^ w11 ^ w9;
6730 w25 = (n << 1) | (n >>> 31);
6731 t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6732 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6733
6734 // 26
6735 n = w23 ^ w18 ^ w12 ^ w10;
6736 w26 = (n << 1) | (n >>> 31);
6737 t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6738 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6739
6740 // 27
6741 n = w24 ^ w19 ^ w13 ^ w11;
6742 w27 = (n << 1) | (n >>> 31);
6743 t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6744 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6745
6746 // 28
6747 n = w25 ^ w20 ^ w14 ^ w12;
6748 w28 = (n << 1) | (n >>> 31);
6749 t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6750 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6751
6752 // 29
6753 n = w26 ^ w21 ^ w15 ^ w13;
6754 w29 = (n << 1) | (n >>> 31);
6755 t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6756 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6757
6758 // 30
6759 n = w27 ^ w22 ^ w16 ^ w14;
6760 w30 = (n << 1) | (n >>> 31);
6761 t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6762 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6763
6764 // 31
6765 n = w28 ^ w23 ^ w17 ^ w15;
6766 w31 = (n << 1) | (n >>> 31);
6767 t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6768 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6769
6770 // 32
6771 n = w29 ^ w24 ^ w18 ^ w16;
6772 w32 = (n << 1) | (n >>> 31);
6773 t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6774 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6775
6776 // 33
6777 n = w30 ^ w25 ^ w19 ^ w17;
6778 w33 = (n << 1) | (n >>> 31);
6779 t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6780 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6781
6782 // 34
6783 n = w31 ^ w26 ^ w20 ^ w18;
6784 w34 = (n << 1) | (n >>> 31);
6785 t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6786 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6787
6788 // 35
6789 n = w32 ^ w27 ^ w21 ^ w19;
6790 w35 = (n << 1) | (n >>> 31);
6791 t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6792 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6793
6794 // 36
6795 n = w33 ^ w28 ^ w22 ^ w20;
6796 w36 = (n << 1) | (n >>> 31);
6797 t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6798 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6799
6800 // 37
6801 n = w34 ^ w29 ^ w23 ^ w21;
6802 w37 = (n << 1) | (n >>> 31);
6803 t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6804 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6805
6806 // 38
6807 n = w35 ^ w30 ^ w24 ^ w22;
6808 w38 = (n << 1) | (n >>> 31);
6809 t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6810 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6811
6812 // 39
6813 n = w36 ^ w31 ^ w25 ^ w23;
6814 w39 = (n << 1) | (n >>> 31);
6815 t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6816 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6817
6818 // 40
6819 n = w37 ^ w32 ^ w26 ^ w24;
6820 w40 = (n << 1) | (n >>> 31);
6821 t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6822 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6823
6824 // 41
6825 n = w38 ^ w33 ^ w27 ^ w25;
6826 w41 = (n << 1) | (n >>> 31);
6827 t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6828 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6829
6830 // 42
6831 n = w39 ^ w34 ^ w28 ^ w26;
6832 w42 = (n << 1) | (n >>> 31);
6833 t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6834 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6835
6836 // 43
6837 n = w40 ^ w35 ^ w29 ^ w27;
6838 w43 = (n << 1) | (n >>> 31);
6839 t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6840 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6841
6842 // 44
6843 n = w41 ^ w36 ^ w30 ^ w28;
6844 w44 = (n << 1) | (n >>> 31);
6845 t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6846 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6847
6848 // 45
6849 n = w42 ^ w37 ^ w31 ^ w29;
6850 w45 = (n << 1) | (n >>> 31);
6851 t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6852 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6853
6854 // 46
6855 n = w43 ^ w38 ^ w32 ^ w30;
6856 w46 = (n << 1) | (n >>> 31);
6857 t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6858 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6859
6860 // 47
6861 n = w44 ^ w39 ^ w33 ^ w31;
6862 w47 = (n << 1) | (n >>> 31);
6863 t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6864 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6865
6866 // 48
6867 n = w45 ^ w40 ^ w34 ^ w32;
6868 w48 = (n << 1) | (n >>> 31);
6869 t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6870 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6871
6872 // 49
6873 n = w46 ^ w41 ^ w35 ^ w33;
6874 w49 = (n << 1) | (n >>> 31);
6875 t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6876 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6877
6878 // 50
6879 n = w47 ^ w42 ^ w36 ^ w34;
6880 w50 = (n << 1) | (n >>> 31);
6881 t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6882 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6883
6884 // 51
6885 n = w48 ^ w43 ^ w37 ^ w35;
6886 w51 = (n << 1) | (n >>> 31);
6887 t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6888 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6889
6890 // 52
6891 n = w49 ^ w44 ^ w38 ^ w36;
6892 w52 = (n << 1) | (n >>> 31);
6893 t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6894 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6895
6896 // 53
6897 n = w50 ^ w45 ^ w39 ^ w37;
6898 w53 = (n << 1) | (n >>> 31);
6899 t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6900 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6901
6902 // 54
6903 n = w51 ^ w46 ^ w40 ^ w38;
6904 w54 = (n << 1) | (n >>> 31);
6905 t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6906 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6907
6908 // 55
6909 n = w52 ^ w47 ^ w41 ^ w39;
6910 w55 = (n << 1) | (n >>> 31);
6911 t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6912 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6913
6914 // 56
6915 n = w53 ^ w48 ^ w42 ^ w40;
6916 w56 = (n << 1) | (n >>> 31);
6917 t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6918 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6919
6920 // 57
6921 n = w54 ^ w49 ^ w43 ^ w41;
6922 w57 = (n << 1) | (n >>> 31);
6923 t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6924 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6925
6926 // 58
6927 n = w55 ^ w50 ^ w44 ^ w42;
6928 w58 = (n << 1) | (n >>> 31);
6929 t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6930 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6931
6932 // 59
6933 n = w56 ^ w51 ^ w45 ^ w43;
6934 w59 = (n << 1) | (n >>> 31);
6935 t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6936 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6937
6938 // 60
6939 n = w57 ^ w52 ^ w46 ^ w44;
6940 w60 = (n << 1) | (n >>> 31);
6941 t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6942 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6943
6944 // 61
6945 n = w58 ^ w53 ^ w47 ^ w45;
6946 w61 = (n << 1) | (n >>> 31);
6947 t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6948 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6949
6950 // 62
6951 n = w59 ^ w54 ^ w48 ^ w46;
6952 w62 = (n << 1) | (n >>> 31);
6953 t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6954 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6955
6956 // 63
6957 n = w60 ^ w55 ^ w49 ^ w47;
6958 w63 = (n << 1) | (n >>> 31);
6959 t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6960 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6961
6962 // 64
6963 n = w61 ^ w56 ^ w50 ^ w48;
6964 w64 = (n << 1) | (n >>> 31);
6965 t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6966 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6967
6968 // 65
6969 n = w62 ^ w57 ^ w51 ^ w49;
6970 w65 = (n << 1) | (n >>> 31);
6971 t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6972 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6973
6974 // 66
6975 n = w63 ^ w58 ^ w52 ^ w50;
6976 w66 = (n << 1) | (n >>> 31);
6977 t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6978 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6979
6980 // 67
6981 n = w64 ^ w59 ^ w53 ^ w51;
6982 w67 = (n << 1) | (n >>> 31);
6983 t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6984 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6985
6986 // 68
6987 n = w65 ^ w60 ^ w54 ^ w52;
6988 w68 = (n << 1) | (n >>> 31);
6989 t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6990 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6991
6992 // 69
6993 n = w66 ^ w61 ^ w55 ^ w53;
6994 w69 = (n << 1) | (n >>> 31);
6995 t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6996 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6997
6998 // 70
6999 n = w67 ^ w62 ^ w56 ^ w54;
7000 w70 = (n << 1) | (n >>> 31);
7001 t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7002 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7003
7004 // 71
7005 n = w68 ^ w63 ^ w57 ^ w55;
7006 w71 = (n << 1) | (n >>> 31);
7007 t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7008 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7009
7010 // 72
7011 n = w69 ^ w64 ^ w58 ^ w56;
7012 w72 = (n << 1) | (n >>> 31);
7013 t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7014 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7015
7016 // 73
7017 n = w70 ^ w65 ^ w59 ^ w57;
7018 w73 = (n << 1) | (n >>> 31);
7019 t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7020 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7021
7022 // 74
7023 n = w71 ^ w66 ^ w60 ^ w58;
7024 w74 = (n << 1) | (n >>> 31);
7025 t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7026 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7027
7028 // 75
7029 n = w72 ^ w67 ^ w61 ^ w59;
7030 w75 = (n << 1) | (n >>> 31);
7031 t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7032 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7033
7034 // 76
7035 n = w73 ^ w68 ^ w62 ^ w60;
7036 w76 = (n << 1) | (n >>> 31);
7037 t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7038 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7039
7040 // 77
7041 n = w74 ^ w69 ^ w63 ^ w61;
7042 w77 = (n << 1) | (n >>> 31);
7043 t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7044 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7045
7046 // 78
7047 n = w75 ^ w70 ^ w64 ^ w62;
7048 w78 = (n << 1) | (n >>> 31);
7049 t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7050 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7051
7052 // 79
7053 n = w76 ^ w71 ^ w65 ^ w63;
7054 w79 = (n << 1) | (n >>> 31);
7055 t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7056 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7057
7058 H0 = ( H0 + a )|0;
7059 H1 = ( H1 + b )|0;
7060 H2 = ( H2 + c )|0;
7061 H3 = ( H3 + d )|0;
7062 H4 = ( H4 + e )|0;
7063
7064 }
7065
7066 function _core_heap ( offset ) {
7067 offset = offset|0;
7068
7069 _core(
7070 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7071 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7072 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7073 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7074 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7075 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7076 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7077 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7078 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7079 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7080 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7081 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7082 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7083 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7084 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7085 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7086 );
7087 }
7088
7089 // offset — multiple of 32
7090 function _state_to_heap ( output ) {
7091 output = output|0;
7092
7093 HEAP[output|0] = H0>>>24;
7094 HEAP[output|1] = H0>>>16&255;
7095 HEAP[output|2] = H0>>>8&255;
7096 HEAP[output|3] = H0&255;
7097 HEAP[output|4] = H1>>>24;
7098 HEAP[output|5] = H1>>>16&255;
7099 HEAP[output|6] = H1>>>8&255;
7100 HEAP[output|7] = H1&255;
7101 HEAP[output|8] = H2>>>24;
7102 HEAP[output|9] = H2>>>16&255;
7103 HEAP[output|10] = H2>>>8&255;
7104 HEAP[output|11] = H2&255;
7105 HEAP[output|12] = H3>>>24;
7106 HEAP[output|13] = H3>>>16&255;
7107 HEAP[output|14] = H3>>>8&255;
7108 HEAP[output|15] = H3&255;
7109 HEAP[output|16] = H4>>>24;
7110 HEAP[output|17] = H4>>>16&255;
7111 HEAP[output|18] = H4>>>8&255;
7112 HEAP[output|19] = H4&255;
7113 }
7114
7115 function reset () {
7116 H0 = 0x67452301;
7117 H1 = 0xefcdab89;
7118 H2 = 0x98badcfe;
7119 H3 = 0x10325476;
7120 H4 = 0xc3d2e1f0;
7121 TOTAL0 = TOTAL1 = 0;
7122 }
7123
7124 function init ( h0, h1, h2, h3, h4, total0, total1 ) {
7125 h0 = h0|0;
7126 h1 = h1|0;
7127 h2 = h2|0;
7128 h3 = h3|0;
7129 h4 = h4|0;
7130 total0 = total0|0;
7131 total1 = total1|0;
7132
7133 H0 = h0;
7134 H1 = h1;
7135 H2 = h2;
7136 H3 = h3;
7137 H4 = h4;
7138 TOTAL0 = total0;
7139 TOTAL1 = total1;
7140 }
7141
7142 // offset — multiple of 64
7143 function process ( offset, length ) {
7144 offset = offset|0;
7145 length = length|0;
7146
7147 var hashed = 0;
7148
7149 if ( offset & 63 )
7150 return -1;
7151
7152 while ( (length|0) >= 64 ) {
7153 _core_heap(offset);
7154
7155 offset = ( offset + 64 )|0;
7156 length = ( length - 64 )|0;
7157
7158 hashed = ( hashed + 64 )|0;
7159 }
7160
7161 TOTAL0 = ( TOTAL0 + hashed )|0;
7162 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
7163
7164 return hashed|0;
7165 }
7166
7167 // offset — multiple of 64
7168 // output — multiple of 32
7169 function finish ( offset, length, output ) {
7170 offset = offset|0;
7171 length = length|0;
7172 output = output|0;
7173
7174 var hashed = 0,
7175 i = 0;
7176
7177 if ( offset & 63 )
7178 return -1;
7179
7180 if ( ~output )
7181 if ( output & 31 )
7182 return -1;
7183
7184 if ( (length|0) >= 64 ) {
7185 hashed = process( offset, length )|0;
7186 if ( (hashed|0) == -1 )
7187 return -1;
7188
7189 offset = ( offset + hashed )|0;
7190 length = ( length - hashed )|0;
7191 }
7192
7193 hashed = ( hashed + length )|0;
7194 TOTAL0 = ( TOTAL0 + length )|0;
7195 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
7196
7197 HEAP[offset|length] = 0x80;
7198
7199 if ( (length|0) >= 56 ) {
7200 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
7201 HEAP[offset|i] = 0x00;
7202 _core_heap(offset);
7203
7204 length = 0;
7205
7206 HEAP[offset|0] = 0;
7207 }
7208
7209 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
7210 HEAP[offset|i] = 0;
7211
7212 HEAP[offset|56] = TOTAL1>>>21&255;
7213 HEAP[offset|57] = TOTAL1>>>13&255;
7214 HEAP[offset|58] = TOTAL1>>>5&255;
7215 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
7216 HEAP[offset|60] = TOTAL0>>>21&255;
7217 HEAP[offset|61] = TOTAL0>>>13&255;
7218 HEAP[offset|62] = TOTAL0>>>5&255;
7219 HEAP[offset|63] = TOTAL0<<3&255;
7220 _core_heap(offset);
7221
7222 if ( ~output )
7223 _state_to_heap(output);
7224
7225 return hashed|0;
7226 }
7227
7228 function hmac_reset () {
7229 H0 = I0;
7230 H1 = I1;
7231 H2 = I2;
7232 H3 = I3;
7233 H4 = I4;
7234 TOTAL0 = 64;
7235 TOTAL1 = 0;
7236 }
7237
7238 function _hmac_opad () {
7239 H0 = O0;
7240 H1 = O1;
7241 H2 = O2;
7242 H3 = O3;
7243 H4 = O4;
7244 TOTAL0 = 64;
7245 TOTAL1 = 0;
7246 }
7247
7248 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
7249 p0 = p0|0;
7250 p1 = p1|0;
7251 p2 = p2|0;
7252 p3 = p3|0;
7253 p4 = p4|0;
7254 p5 = p5|0;
7255 p6 = p6|0;
7256 p7 = p7|0;
7257 p8 = p8|0;
7258 p9 = p9|0;
7259 p10 = p10|0;
7260 p11 = p11|0;
7261 p12 = p12|0;
7262 p13 = p13|0;
7263 p14 = p14|0;
7264 p15 = p15|0;
7265
7266 // opad
7267 reset();
7268 _core(
7269 p0 ^ 0x5c5c5c5c,
7270 p1 ^ 0x5c5c5c5c,
7271 p2 ^ 0x5c5c5c5c,
7272 p3 ^ 0x5c5c5c5c,
7273 p4 ^ 0x5c5c5c5c,
7274 p5 ^ 0x5c5c5c5c,
7275 p6 ^ 0x5c5c5c5c,
7276 p7 ^ 0x5c5c5c5c,
7277 p8 ^ 0x5c5c5c5c,
7278 p9 ^ 0x5c5c5c5c,
7279 p10 ^ 0x5c5c5c5c,
7280 p11 ^ 0x5c5c5c5c,
7281 p12 ^ 0x5c5c5c5c,
7282 p13 ^ 0x5c5c5c5c,
7283 p14 ^ 0x5c5c5c5c,
7284 p15 ^ 0x5c5c5c5c
7285 );
7286 O0 = H0;
7287 O1 = H1;
7288 O2 = H2;
7289 O3 = H3;
7290 O4 = H4;
7291
7292 // ipad
7293 reset();
7294 _core(
7295 p0 ^ 0x36363636,
7296 p1 ^ 0x36363636,
7297 p2 ^ 0x36363636,
7298 p3 ^ 0x36363636,
7299 p4 ^ 0x36363636,
7300 p5 ^ 0x36363636,
7301 p6 ^ 0x36363636,
7302 p7 ^ 0x36363636,
7303 p8 ^ 0x36363636,
7304 p9 ^ 0x36363636,
7305 p10 ^ 0x36363636,
7306 p11 ^ 0x36363636,
7307 p12 ^ 0x36363636,
7308 p13 ^ 0x36363636,
7309 p14 ^ 0x36363636,
7310 p15 ^ 0x36363636
7311 );
7312 I0 = H0;
7313 I1 = H1;
7314 I2 = H2;
7315 I3 = H3;
7316 I4 = H4;
7317
7318 TOTAL0 = 64;
7319 TOTAL1 = 0;
7320 }
7321
7322 // offset — multiple of 64
7323 // output — multiple of 32
7324 function hmac_finish ( offset, length, output ) {
7325 offset = offset|0;
7326 length = length|0;
7327 output = output|0;
7328
7329 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
7330
7331 if ( offset & 63 )
7332 return -1;
7333
7334 if ( ~output )
7335 if ( output & 31 )
7336 return -1;
7337
7338 hashed = finish( offset, length, -1 )|0;
7339 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7340
7341 _hmac_opad();
7342 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7343
7344 if ( ~output )
7345 _state_to_heap(output);
7346
7347 return hashed|0;
7348 }
7349
7350 // salt is assumed to be already processed
7351 // offset — multiple of 64
7352 // output — multiple of 32
7353 function pbkdf2_generate_block ( offset, length, block, count, output ) {
7354 offset = offset|0;
7355 length = length|0;
7356 block = block|0;
7357 count = count|0;
7358 output = output|0;
7359
7360 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
7361 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
7362
7363 if ( offset & 63 )
7364 return -1;
7365
7366 if ( ~output )
7367 if ( output & 31 )
7368 return -1;
7369
7370 // pad block number into heap
7371 // FIXME probable OOB write
7372 HEAP[(offset+length)|0] = block>>>24;
7373 HEAP[(offset+length+1)|0] = block>>>16&255;
7374 HEAP[(offset+length+2)|0] = block>>>8&255;
7375 HEAP[(offset+length+3)|0] = block&255;
7376
7377 // finish first iteration
7378 hmac_finish( offset, (length+4)|0, -1 )|0;
7379 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
7380 count = (count-1)|0;
7381
7382 // perform the rest iterations
7383 while ( (count|0) > 0 ) {
7384 hmac_reset();
7385 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7386 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7387
7388 _hmac_opad();
7389 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7390 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7391
7392 h0 = h0 ^ H0;
7393 h1 = h1 ^ H1;
7394 h2 = h2 ^ H2;
7395 h3 = h3 ^ H3;
7396 h4 = h4 ^ H4;
7397
7398 count = (count-1)|0;
7399 }
7400
7401 H0 = h0;
7402 H1 = h1;
7403 H2 = h2;
7404 H3 = h3;
7405 H4 = h4;
7406
7407 if ( ~output )
7408 _state_to_heap(output);
7409
7410 return 0;
7411 }
7412
7413 return {
7414 // SHA1
7415 reset: reset,
7416 init: init,
7417 process: process,
7418 finish: finish,
7419
7420 // HMAC-SHA1
7421 hmac_reset: hmac_reset,
7422 hmac_init: hmac_init,
7423 hmac_finish: hmac_finish,
7424
7425 // PBKDF2-HMAC-SHA1
7426 pbkdf2_generate_block: pbkdf2_generate_block
7427 }
7428};
7429
7430class Hash {
7431 constructor() {
7432 this.pos = 0;
7433 this.len = 0;
7434 }
7435 reset() {
7436 const { asm } = this.acquire_asm();
7437 this.result = null;
7438 this.pos = 0;
7439 this.len = 0;
7440 asm.reset();
7441 return this;
7442 }
7443 process(data) {
7444 if (this.result !== null)
7445 throw new IllegalStateError('state must be reset before processing new data');
7446 const { asm, heap } = this.acquire_asm();
7447 let hpos = this.pos;
7448 let hlen = this.len;
7449 let dpos = 0;
7450 let dlen = data.length;
7451 let wlen = 0;
7452 while (dlen > 0) {
7453 wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
7454 hlen += wlen;
7455 dpos += wlen;
7456 dlen -= wlen;
7457 wlen = asm.process(hpos, hlen);
7458 hpos += wlen;
7459 hlen -= wlen;
7460 if (!hlen)
7461 hpos = 0;
7462 }
7463 this.pos = hpos;
7464 this.len = hlen;
7465 return this;
7466 }
7467 finish() {
7468 if (this.result !== null)
7469 throw new IllegalStateError('state must be reset before processing new data');
7470 const { asm, heap } = this.acquire_asm();
7471 asm.finish(this.pos, this.len, 0);
7472 this.result = new Uint8Array(this.HASH_SIZE);
7473 this.result.set(heap.subarray(0, this.HASH_SIZE));
7474 this.pos = 0;
7475 this.len = 0;
7476 this.release_asm();
7477 return this;
7478 }
7479}
7480
7481const _sha1_block_size = 64;
7482const _sha1_hash_size = 20;
7483const heap_pool$1 = [];
7484const asm_pool$1 = [];
7485class Sha1 extends Hash {
7486 constructor() {
7487 super();
7488 this.NAME = 'sha1';
7489 this.BLOCK_SIZE = _sha1_block_size;
7490 this.HASH_SIZE = _sha1_hash_size;
7491 this.acquire_asm();
7492 }
7493 acquire_asm() {
7494 if (this.heap === undefined || this.asm === undefined) {
7495 this.heap = heap_pool$1.pop() || _heap_init();
7496 this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
7497 this.reset();
7498 }
7499 return { heap: this.heap, asm: this.asm };
7500 }
7501 release_asm() {
7502 if (this.heap !== undefined && this.asm !== undefined) {
7503 heap_pool$1.push(this.heap);
7504 asm_pool$1.push(this.asm);
7505 }
7506 this.heap = undefined;
7507 this.asm = undefined;
7508 }
7509 static bytes(data) {
7510 return new Sha1().process(data).finish().result;
7511 }
7512}
7513Sha1.NAME = 'sha1';
7514Sha1.heap_pool = [];
7515Sha1.asm_pool = [];
7516Sha1.asm_function = sha1_asm;
7517
7518var sha256_asm = function ( stdlib, foreign, buffer ) {
7519 "use asm";
7520
7521 // SHA256 state
7522 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
7523 TOTAL0 = 0, TOTAL1 = 0;
7524
7525 // HMAC state
7526 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
7527 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
7528
7529 // I/O buffer
7530 var HEAP = new stdlib.Uint8Array(buffer);
7531
7532 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
7533 w0 = w0|0;
7534 w1 = w1|0;
7535 w2 = w2|0;
7536 w3 = w3|0;
7537 w4 = w4|0;
7538 w5 = w5|0;
7539 w6 = w6|0;
7540 w7 = w7|0;
7541 w8 = w8|0;
7542 w9 = w9|0;
7543 w10 = w10|0;
7544 w11 = w11|0;
7545 w12 = w12|0;
7546 w13 = w13|0;
7547 w14 = w14|0;
7548 w15 = w15|0;
7549
7550 var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
7551
7552 a = H0;
7553 b = H1;
7554 c = H2;
7555 d = H3;
7556 e = H4;
7557 f = H5;
7558 g = H6;
7559 h = H7;
7560
7561 // 0
7562 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
7563 d = ( d + h )|0;
7564 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7565
7566 // 1
7567 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
7568 c = ( c + g )|0;
7569 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7570
7571 // 2
7572 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
7573 b = ( b + f )|0;
7574 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7575
7576 // 3
7577 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
7578 a = ( a + e )|0;
7579 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7580
7581 // 4
7582 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
7583 h = ( h + d )|0;
7584 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7585
7586 // 5
7587 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
7588 g = ( g + c )|0;
7589 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7590
7591 // 6
7592 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
7593 f = ( f + b )|0;
7594 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7595
7596 // 7
7597 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
7598 e = ( e + a )|0;
7599 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7600
7601 // 8
7602 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
7603 d = ( d + h )|0;
7604 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7605
7606 // 9
7607 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
7608 c = ( c + g )|0;
7609 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7610
7611 // 10
7612 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
7613 b = ( b + f )|0;
7614 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7615
7616 // 11
7617 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
7618 a = ( a + e )|0;
7619 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7620
7621 // 12
7622 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
7623 h = ( h + d )|0;
7624 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7625
7626 // 13
7627 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
7628 g = ( g + c )|0;
7629 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7630
7631 // 14
7632 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
7633 f = ( f + b )|0;
7634 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7635
7636 // 15
7637 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
7638 e = ( e + a )|0;
7639 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7640
7641 // 16
7642 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7643 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
7644 d = ( d + h )|0;
7645 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7646
7647 // 17
7648 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7649 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
7650 c = ( c + g )|0;
7651 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7652
7653 // 18
7654 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7655 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
7656 b = ( b + f )|0;
7657 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7658
7659 // 19
7660 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7661 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
7662 a = ( a + e )|0;
7663 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7664
7665 // 20
7666 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7667 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
7668 h = ( h + d )|0;
7669 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7670
7671 // 21
7672 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7673 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
7674 g = ( g + c )|0;
7675 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7676
7677 // 22
7678 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7679 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
7680 f = ( f + b )|0;
7681 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7682
7683 // 23
7684 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7685 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
7686 e = ( e + a )|0;
7687 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7688
7689 // 24
7690 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7691 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
7692 d = ( d + h )|0;
7693 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7694
7695 // 25
7696 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7697 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
7698 c = ( c + g )|0;
7699 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7700
7701 // 26
7702 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7703 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
7704 b = ( b + f )|0;
7705 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7706
7707 // 27
7708 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7709 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
7710 a = ( a + e )|0;
7711 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7712
7713 // 28
7714 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7715 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
7716 h = ( h + d )|0;
7717 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7718
7719 // 29
7720 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7721 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
7722 g = ( g + c )|0;
7723 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7724
7725 // 30
7726 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7727 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
7728 f = ( f + b )|0;
7729 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7730
7731 // 31
7732 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7733 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
7734 e = ( e + a )|0;
7735 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7736
7737 // 32
7738 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7739 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
7740 d = ( d + h )|0;
7741 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7742
7743 // 33
7744 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7745 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
7746 c = ( c + g )|0;
7747 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7748
7749 // 34
7750 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7751 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
7752 b = ( b + f )|0;
7753 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7754
7755 // 35
7756 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7757 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
7758 a = ( a + e )|0;
7759 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7760
7761 // 36
7762 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7763 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
7764 h = ( h + d )|0;
7765 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7766
7767 // 37
7768 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7769 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
7770 g = ( g + c )|0;
7771 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7772
7773 // 38
7774 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7775 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
7776 f = ( f + b )|0;
7777 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7778
7779 // 39
7780 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7781 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
7782 e = ( e + a )|0;
7783 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7784
7785 // 40
7786 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7787 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
7788 d = ( d + h )|0;
7789 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7790
7791 // 41
7792 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7793 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
7794 c = ( c + g )|0;
7795 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7796
7797 // 42
7798 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7799 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
7800 b = ( b + f )|0;
7801 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7802
7803 // 43
7804 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7805 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
7806 a = ( a + e )|0;
7807 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7808
7809 // 44
7810 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7811 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
7812 h = ( h + d )|0;
7813 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7814
7815 // 45
7816 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7817 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
7818 g = ( g + c )|0;
7819 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7820
7821 // 46
7822 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7823 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
7824 f = ( f + b )|0;
7825 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7826
7827 // 47
7828 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7829 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
7830 e = ( e + a )|0;
7831 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7832
7833 // 48
7834 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7835 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
7836 d = ( d + h )|0;
7837 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7838
7839 // 49
7840 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7841 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
7842 c = ( c + g )|0;
7843 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7844
7845 // 50
7846 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7847 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
7848 b = ( b + f )|0;
7849 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7850
7851 // 51
7852 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7853 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
7854 a = ( a + e )|0;
7855 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7856
7857 // 52
7858 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7859 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
7860 h = ( h + d )|0;
7861 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7862
7863 // 53
7864 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7865 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
7866 g = ( g + c )|0;
7867 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7868
7869 // 54
7870 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7871 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
7872 f = ( f + b )|0;
7873 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7874
7875 // 55
7876 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7877 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
7878 e = ( e + a )|0;
7879 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7880
7881 // 56
7882 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7883 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
7884 d = ( d + h )|0;
7885 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7886
7887 // 57
7888 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7889 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
7890 c = ( c + g )|0;
7891 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7892
7893 // 58
7894 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7895 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
7896 b = ( b + f )|0;
7897 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7898
7899 // 59
7900 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7901 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
7902 a = ( a + e )|0;
7903 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7904
7905 // 60
7906 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7907 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
7908 h = ( h + d )|0;
7909 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7910
7911 // 61
7912 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7913 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
7914 g = ( g + c )|0;
7915 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7916
7917 // 62
7918 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7919 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
7920 f = ( f + b )|0;
7921 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7922
7923 // 63
7924 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7925 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
7926 e = ( e + a )|0;
7927 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7928
7929 H0 = ( H0 + a )|0;
7930 H1 = ( H1 + b )|0;
7931 H2 = ( H2 + c )|0;
7932 H3 = ( H3 + d )|0;
7933 H4 = ( H4 + e )|0;
7934 H5 = ( H5 + f )|0;
7935 H6 = ( H6 + g )|0;
7936 H7 = ( H7 + h )|0;
7937 }
7938
7939 function _core_heap ( offset ) {
7940 offset = offset|0;
7941
7942 _core(
7943 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7944 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7945 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7946 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7947 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7948 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7949 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7950 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7951 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7952 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7953 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7954 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7955 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7956 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7957 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7958 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7959 );
7960 }
7961
7962 // offset — multiple of 32
7963 function _state_to_heap ( output ) {
7964 output = output|0;
7965
7966 HEAP[output|0] = H0>>>24;
7967 HEAP[output|1] = H0>>>16&255;
7968 HEAP[output|2] = H0>>>8&255;
7969 HEAP[output|3] = H0&255;
7970 HEAP[output|4] = H1>>>24;
7971 HEAP[output|5] = H1>>>16&255;
7972 HEAP[output|6] = H1>>>8&255;
7973 HEAP[output|7] = H1&255;
7974 HEAP[output|8] = H2>>>24;
7975 HEAP[output|9] = H2>>>16&255;
7976 HEAP[output|10] = H2>>>8&255;
7977 HEAP[output|11] = H2&255;
7978 HEAP[output|12] = H3>>>24;
7979 HEAP[output|13] = H3>>>16&255;
7980 HEAP[output|14] = H3>>>8&255;
7981 HEAP[output|15] = H3&255;
7982 HEAP[output|16] = H4>>>24;
7983 HEAP[output|17] = H4>>>16&255;
7984 HEAP[output|18] = H4>>>8&255;
7985 HEAP[output|19] = H4&255;
7986 HEAP[output|20] = H5>>>24;
7987 HEAP[output|21] = H5>>>16&255;
7988 HEAP[output|22] = H5>>>8&255;
7989 HEAP[output|23] = H5&255;
7990 HEAP[output|24] = H6>>>24;
7991 HEAP[output|25] = H6>>>16&255;
7992 HEAP[output|26] = H6>>>8&255;
7993 HEAP[output|27] = H6&255;
7994 HEAP[output|28] = H7>>>24;
7995 HEAP[output|29] = H7>>>16&255;
7996 HEAP[output|30] = H7>>>8&255;
7997 HEAP[output|31] = H7&255;
7998 }
7999
8000 function reset () {
8001 H0 = 0x6a09e667;
8002 H1 = 0xbb67ae85;
8003 H2 = 0x3c6ef372;
8004 H3 = 0xa54ff53a;
8005 H4 = 0x510e527f;
8006 H5 = 0x9b05688c;
8007 H6 = 0x1f83d9ab;
8008 H7 = 0x5be0cd19;
8009 TOTAL0 = TOTAL1 = 0;
8010 }
8011
8012 function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
8013 h0 = h0|0;
8014 h1 = h1|0;
8015 h2 = h2|0;
8016 h3 = h3|0;
8017 h4 = h4|0;
8018 h5 = h5|0;
8019 h6 = h6|0;
8020 h7 = h7|0;
8021 total0 = total0|0;
8022 total1 = total1|0;
8023
8024 H0 = h0;
8025 H1 = h1;
8026 H2 = h2;
8027 H3 = h3;
8028 H4 = h4;
8029 H5 = h5;
8030 H6 = h6;
8031 H7 = h7;
8032 TOTAL0 = total0;
8033 TOTAL1 = total1;
8034 }
8035
8036 // offset — multiple of 64
8037 function process ( offset, length ) {
8038 offset = offset|0;
8039 length = length|0;
8040
8041 var hashed = 0;
8042
8043 if ( offset & 63 )
8044 return -1;
8045
8046 while ( (length|0) >= 64 ) {
8047 _core_heap(offset);
8048
8049 offset = ( offset + 64 )|0;
8050 length = ( length - 64 )|0;
8051
8052 hashed = ( hashed + 64 )|0;
8053 }
8054
8055 TOTAL0 = ( TOTAL0 + hashed )|0;
8056 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8057
8058 return hashed|0;
8059 }
8060
8061 // offset — multiple of 64
8062 // output — multiple of 32
8063 function finish ( offset, length, output ) {
8064 offset = offset|0;
8065 length = length|0;
8066 output = output|0;
8067
8068 var hashed = 0,
8069 i = 0;
8070
8071 if ( offset & 63 )
8072 return -1;
8073
8074 if ( ~output )
8075 if ( output & 31 )
8076 return -1;
8077
8078 if ( (length|0) >= 64 ) {
8079 hashed = process( offset, length )|0;
8080 if ( (hashed|0) == -1 )
8081 return -1;
8082
8083 offset = ( offset + hashed )|0;
8084 length = ( length - hashed )|0;
8085 }
8086
8087 hashed = ( hashed + length )|0;
8088 TOTAL0 = ( TOTAL0 + length )|0;
8089 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8090
8091 HEAP[offset|length] = 0x80;
8092
8093 if ( (length|0) >= 56 ) {
8094 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
8095 HEAP[offset|i] = 0x00;
8096
8097 _core_heap(offset);
8098
8099 length = 0;
8100
8101 HEAP[offset|0] = 0;
8102 }
8103
8104 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
8105 HEAP[offset|i] = 0;
8106
8107 HEAP[offset|56] = TOTAL1>>>21&255;
8108 HEAP[offset|57] = TOTAL1>>>13&255;
8109 HEAP[offset|58] = TOTAL1>>>5&255;
8110 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
8111 HEAP[offset|60] = TOTAL0>>>21&255;
8112 HEAP[offset|61] = TOTAL0>>>13&255;
8113 HEAP[offset|62] = TOTAL0>>>5&255;
8114 HEAP[offset|63] = TOTAL0<<3&255;
8115 _core_heap(offset);
8116
8117 if ( ~output )
8118 _state_to_heap(output);
8119
8120 return hashed|0;
8121 }
8122
8123 function hmac_reset () {
8124 H0 = I0;
8125 H1 = I1;
8126 H2 = I2;
8127 H3 = I3;
8128 H4 = I4;
8129 H5 = I5;
8130 H6 = I6;
8131 H7 = I7;
8132 TOTAL0 = 64;
8133 TOTAL1 = 0;
8134 }
8135
8136 function _hmac_opad () {
8137 H0 = O0;
8138 H1 = O1;
8139 H2 = O2;
8140 H3 = O3;
8141 H4 = O4;
8142 H5 = O5;
8143 H6 = O6;
8144 H7 = O7;
8145 TOTAL0 = 64;
8146 TOTAL1 = 0;
8147 }
8148
8149 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
8150 p0 = p0|0;
8151 p1 = p1|0;
8152 p2 = p2|0;
8153 p3 = p3|0;
8154 p4 = p4|0;
8155 p5 = p5|0;
8156 p6 = p6|0;
8157 p7 = p7|0;
8158 p8 = p8|0;
8159 p9 = p9|0;
8160 p10 = p10|0;
8161 p11 = p11|0;
8162 p12 = p12|0;
8163 p13 = p13|0;
8164 p14 = p14|0;
8165 p15 = p15|0;
8166
8167 // opad
8168 reset();
8169 _core(
8170 p0 ^ 0x5c5c5c5c,
8171 p1 ^ 0x5c5c5c5c,
8172 p2 ^ 0x5c5c5c5c,
8173 p3 ^ 0x5c5c5c5c,
8174 p4 ^ 0x5c5c5c5c,
8175 p5 ^ 0x5c5c5c5c,
8176 p6 ^ 0x5c5c5c5c,
8177 p7 ^ 0x5c5c5c5c,
8178 p8 ^ 0x5c5c5c5c,
8179 p9 ^ 0x5c5c5c5c,
8180 p10 ^ 0x5c5c5c5c,
8181 p11 ^ 0x5c5c5c5c,
8182 p12 ^ 0x5c5c5c5c,
8183 p13 ^ 0x5c5c5c5c,
8184 p14 ^ 0x5c5c5c5c,
8185 p15 ^ 0x5c5c5c5c
8186 );
8187 O0 = H0;
8188 O1 = H1;
8189 O2 = H2;
8190 O3 = H3;
8191 O4 = H4;
8192 O5 = H5;
8193 O6 = H6;
8194 O7 = H7;
8195
8196 // ipad
8197 reset();
8198 _core(
8199 p0 ^ 0x36363636,
8200 p1 ^ 0x36363636,
8201 p2 ^ 0x36363636,
8202 p3 ^ 0x36363636,
8203 p4 ^ 0x36363636,
8204 p5 ^ 0x36363636,
8205 p6 ^ 0x36363636,
8206 p7 ^ 0x36363636,
8207 p8 ^ 0x36363636,
8208 p9 ^ 0x36363636,
8209 p10 ^ 0x36363636,
8210 p11 ^ 0x36363636,
8211 p12 ^ 0x36363636,
8212 p13 ^ 0x36363636,
8213 p14 ^ 0x36363636,
8214 p15 ^ 0x36363636
8215 );
8216 I0 = H0;
8217 I1 = H1;
8218 I2 = H2;
8219 I3 = H3;
8220 I4 = H4;
8221 I5 = H5;
8222 I6 = H6;
8223 I7 = H7;
8224
8225 TOTAL0 = 64;
8226 TOTAL1 = 0;
8227 }
8228
8229 // offset — multiple of 64
8230 // output — multiple of 32
8231 function hmac_finish ( offset, length, output ) {
8232 offset = offset|0;
8233 length = length|0;
8234 output = output|0;
8235
8236 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
8237 hashed = 0;
8238
8239 if ( offset & 63 )
8240 return -1;
8241
8242 if ( ~output )
8243 if ( output & 31 )
8244 return -1;
8245
8246 hashed = finish( offset, length, -1 )|0;
8247 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8248
8249 _hmac_opad();
8250 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8251
8252 if ( ~output )
8253 _state_to_heap(output);
8254
8255 return hashed|0;
8256 }
8257
8258 // salt is assumed to be already processed
8259 // offset — multiple of 64
8260 // output — multiple of 32
8261 function pbkdf2_generate_block ( offset, length, block, count, output ) {
8262 offset = offset|0;
8263 length = length|0;
8264 block = block|0;
8265 count = count|0;
8266 output = output|0;
8267
8268 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
8269 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
8270
8271 if ( offset & 63 )
8272 return -1;
8273
8274 if ( ~output )
8275 if ( output & 31 )
8276 return -1;
8277
8278 // pad block number into heap
8279 // FIXME probable OOB write
8280 HEAP[(offset+length)|0] = block>>>24;
8281 HEAP[(offset+length+1)|0] = block>>>16&255;
8282 HEAP[(offset+length+2)|0] = block>>>8&255;
8283 HEAP[(offset+length+3)|0] = block&255;
8284
8285 // finish first iteration
8286 hmac_finish( offset, (length+4)|0, -1 )|0;
8287 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
8288 count = (count-1)|0;
8289
8290 // perform the rest iterations
8291 while ( (count|0) > 0 ) {
8292 hmac_reset();
8293 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8294 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8295
8296 _hmac_opad();
8297 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8298 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8299
8300 h0 = h0 ^ H0;
8301 h1 = h1 ^ H1;
8302 h2 = h2 ^ H2;
8303 h3 = h3 ^ H3;
8304 h4 = h4 ^ H4;
8305 h5 = h5 ^ H5;
8306 h6 = h6 ^ H6;
8307 h7 = h7 ^ H7;
8308
8309 count = (count-1)|0;
8310 }
8311
8312 H0 = h0;
8313 H1 = h1;
8314 H2 = h2;
8315 H3 = h3;
8316 H4 = h4;
8317 H5 = h5;
8318 H6 = h6;
8319 H7 = h7;
8320
8321 if ( ~output )
8322 _state_to_heap(output);
8323
8324 return 0;
8325 }
8326
8327 return {
8328 // SHA256
8329 reset: reset,
8330 init: init,
8331 process: process,
8332 finish: finish,
8333
8334 // HMAC-SHA256
8335 hmac_reset: hmac_reset,
8336 hmac_init: hmac_init,
8337 hmac_finish: hmac_finish,
8338
8339 // PBKDF2-HMAC-SHA256
8340 pbkdf2_generate_block: pbkdf2_generate_block
8341 }
8342};
8343
8344const _sha256_block_size = 64;
8345const _sha256_hash_size = 32;
8346const heap_pool$2 = [];
8347const asm_pool$2 = [];
8348class Sha256 extends Hash {
8349 constructor() {
8350 super();
8351 this.NAME = 'sha256';
8352 this.BLOCK_SIZE = _sha256_block_size;
8353 this.HASH_SIZE = _sha256_hash_size;
8354 this.acquire_asm();
8355 }
8356 acquire_asm() {
8357 if (this.heap === undefined || this.asm === undefined) {
8358 this.heap = heap_pool$2.pop() || _heap_init();
8359 this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
8360 this.reset();
8361 }
8362 return { heap: this.heap, asm: this.asm };
8363 }
8364 release_asm() {
8365 if (this.heap !== undefined && this.asm !== undefined) {
8366 heap_pool$2.push(this.heap);
8367 asm_pool$2.push(this.asm);
8368 }
8369 this.heap = undefined;
8370 this.asm = undefined;
8371 }
8372 static bytes(data) {
8373 return new Sha256().process(data).finish().result;
8374 }
8375}
8376Sha256.NAME = 'sha256';
8377
8378var minimalisticAssert = assert;
8379
8380function assert(val, msg) {
8381 if (!val)
8382 throw new Error(msg || 'Assertion failed');
8383}
8384
8385assert.equal = function assertEqual(l, r, msg) {
8386 if (l != r)
8387 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
8388};
8389
8390var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8391
8392function createCommonjsModule(fn, module) {
8393 return module = { exports: {} }, fn(module, module.exports), module.exports;
8394}
8395
8396function commonjsRequire () {
8397 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
8398}
8399
8400var inherits_browser = createCommonjsModule(function (module) {
8401if (typeof Object.create === 'function') {
8402 // implementation from standard node.js 'util' module
8403 module.exports = function inherits(ctor, superCtor) {
8404 ctor.super_ = superCtor;
8405 ctor.prototype = Object.create(superCtor.prototype, {
8406 constructor: {
8407 value: ctor,
8408 enumerable: false,
8409 writable: true,
8410 configurable: true
8411 }
8412 });
8413 };
8414} else {
8415 // old school shim for old browsers
8416 module.exports = function inherits(ctor, superCtor) {
8417 ctor.super_ = superCtor;
8418 var TempCtor = function () {};
8419 TempCtor.prototype = superCtor.prototype;
8420 ctor.prototype = new TempCtor();
8421 ctor.prototype.constructor = ctor;
8422 };
8423}
8424});
8425
8426var inherits_1 = inherits_browser;
8427
8428function toArray(msg, enc) {
8429 if (Array.isArray(msg))
8430 return msg.slice();
8431 if (!msg)
8432 return [];
8433 var res = [];
8434 if (typeof msg === 'string') {
8435 if (!enc) {
8436 for (var i = 0; i < msg.length; i++) {
8437 var c = msg.charCodeAt(i);
8438 var hi = c >> 8;
8439 var lo = c & 0xff;
8440 if (hi)
8441 res.push(hi, lo);
8442 else
8443 res.push(lo);
8444 }
8445 } else if (enc === 'hex') {
8446 msg = msg.replace(/[^a-z0-9]+/ig, '');
8447 if (msg.length % 2 !== 0)
8448 msg = '0' + msg;
8449 for (i = 0; i < msg.length; i += 2)
8450 res.push(parseInt(msg[i] + msg[i + 1], 16));
8451 }
8452 } else {
8453 for (i = 0; i < msg.length; i++)
8454 res[i] = msg[i] | 0;
8455 }
8456 return res;
8457}
8458var toArray_1 = toArray;
8459
8460function toHex(msg) {
8461 var res = '';
8462 for (var i = 0; i < msg.length; i++)
8463 res += zero2(msg[i].toString(16));
8464 return res;
8465}
8466var toHex_1 = toHex;
8467
8468function htonl(w) {
8469 var res = (w >>> 24) |
8470 ((w >>> 8) & 0xff00) |
8471 ((w << 8) & 0xff0000) |
8472 ((w & 0xff) << 24);
8473 return res >>> 0;
8474}
8475var htonl_1 = htonl;
8476
8477function toHex32(msg, endian) {
8478 var res = '';
8479 for (var i = 0; i < msg.length; i++) {
8480 var w = msg[i];
8481 if (endian === 'little')
8482 w = htonl(w);
8483 res += zero8(w.toString(16));
8484 }
8485 return res;
8486}
8487var toHex32_1 = toHex32;
8488
8489function zero2(word) {
8490 if (word.length === 1)
8491 return '0' + word;
8492 else
8493 return word;
8494}
8495var zero2_1 = zero2;
8496
8497function zero8(word) {
8498 if (word.length === 7)
8499 return '0' + word;
8500 else if (word.length === 6)
8501 return '00' + word;
8502 else if (word.length === 5)
8503 return '000' + word;
8504 else if (word.length === 4)
8505 return '0000' + word;
8506 else if (word.length === 3)
8507 return '00000' + word;
8508 else if (word.length === 2)
8509 return '000000' + word;
8510 else if (word.length === 1)
8511 return '0000000' + word;
8512 else
8513 return word;
8514}
8515var zero8_1 = zero8;
8516
8517function join32(msg, start, end, endian) {
8518 var len = end - start;
8519 minimalisticAssert(len % 4 === 0);
8520 var res = new Array(len / 4);
8521 for (var i = 0, k = start; i < res.length; i++, k += 4) {
8522 var w;
8523 if (endian === 'big')
8524 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
8525 else
8526 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
8527 res[i] = w >>> 0;
8528 }
8529 return res;
8530}
8531var join32_1 = join32;
8532
8533function split32(msg, endian) {
8534 var res = new Array(msg.length * 4);
8535 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
8536 var m = msg[i];
8537 if (endian === 'big') {
8538 res[k] = m >>> 24;
8539 res[k + 1] = (m >>> 16) & 0xff;
8540 res[k + 2] = (m >>> 8) & 0xff;
8541 res[k + 3] = m & 0xff;
8542 } else {
8543 res[k + 3] = m >>> 24;
8544 res[k + 2] = (m >>> 16) & 0xff;
8545 res[k + 1] = (m >>> 8) & 0xff;
8546 res[k] = m & 0xff;
8547 }
8548 }
8549 return res;
8550}
8551var split32_1 = split32;
8552
8553function rotr32(w, b) {
8554 return (w >>> b) | (w << (32 - b));
8555}
8556var rotr32_1 = rotr32;
8557
8558function rotl32(w, b) {
8559 return (w << b) | (w >>> (32 - b));
8560}
8561var rotl32_1 = rotl32;
8562
8563function sum32(a, b) {
8564 return (a + b) >>> 0;
8565}
8566var sum32_1 = sum32;
8567
8568function sum32_3(a, b, c) {
8569 return (a + b + c) >>> 0;
8570}
8571var sum32_3_1 = sum32_3;
8572
8573function sum32_4(a, b, c, d) {
8574 return (a + b + c + d) >>> 0;
8575}
8576var sum32_4_1 = sum32_4;
8577
8578function sum32_5(a, b, c, d, e) {
8579 return (a + b + c + d + e) >>> 0;
8580}
8581var sum32_5_1 = sum32_5;
8582
8583function sum64(buf, pos, ah, al) {
8584 var bh = buf[pos];
8585 var bl = buf[pos + 1];
8586
8587 var lo = (al + bl) >>> 0;
8588 var hi = (lo < al ? 1 : 0) + ah + bh;
8589 buf[pos] = hi >>> 0;
8590 buf[pos + 1] = lo;
8591}
8592var sum64_1 = sum64;
8593
8594function sum64_hi(ah, al, bh, bl) {
8595 var lo = (al + bl) >>> 0;
8596 var hi = (lo < al ? 1 : 0) + ah + bh;
8597 return hi >>> 0;
8598}
8599var sum64_hi_1 = sum64_hi;
8600
8601function sum64_lo(ah, al, bh, bl) {
8602 var lo = al + bl;
8603 return lo >>> 0;
8604}
8605var sum64_lo_1 = sum64_lo;
8606
8607function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
8608 var carry = 0;
8609 var lo = al;
8610 lo = (lo + bl) >>> 0;
8611 carry += lo < al ? 1 : 0;
8612 lo = (lo + cl) >>> 0;
8613 carry += lo < cl ? 1 : 0;
8614 lo = (lo + dl) >>> 0;
8615 carry += lo < dl ? 1 : 0;
8616
8617 var hi = ah + bh + ch + dh + carry;
8618 return hi >>> 0;
8619}
8620var sum64_4_hi_1 = sum64_4_hi;
8621
8622function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
8623 var lo = al + bl + cl + dl;
8624 return lo >>> 0;
8625}
8626var sum64_4_lo_1 = sum64_4_lo;
8627
8628function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8629 var carry = 0;
8630 var lo = al;
8631 lo = (lo + bl) >>> 0;
8632 carry += lo < al ? 1 : 0;
8633 lo = (lo + cl) >>> 0;
8634 carry += lo < cl ? 1 : 0;
8635 lo = (lo + dl) >>> 0;
8636 carry += lo < dl ? 1 : 0;
8637 lo = (lo + el) >>> 0;
8638 carry += lo < el ? 1 : 0;
8639
8640 var hi = ah + bh + ch + dh + eh + carry;
8641 return hi >>> 0;
8642}
8643var sum64_5_hi_1 = sum64_5_hi;
8644
8645function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8646 var lo = al + bl + cl + dl + el;
8647
8648 return lo >>> 0;
8649}
8650var sum64_5_lo_1 = sum64_5_lo;
8651
8652function rotr64_hi(ah, al, num) {
8653 var r = (al << (32 - num)) | (ah >>> num);
8654 return r >>> 0;
8655}
8656var rotr64_hi_1 = rotr64_hi;
8657
8658function rotr64_lo(ah, al, num) {
8659 var r = (ah << (32 - num)) | (al >>> num);
8660 return r >>> 0;
8661}
8662var rotr64_lo_1 = rotr64_lo;
8663
8664function shr64_hi(ah, al, num) {
8665 return ah >>> num;
8666}
8667var shr64_hi_1 = shr64_hi;
8668
8669function shr64_lo(ah, al, num) {
8670 var r = (ah << (32 - num)) | (al >>> num);
8671 return r >>> 0;
8672}
8673var shr64_lo_1 = shr64_lo;
8674
8675var utils = {
8676 inherits: inherits_1,
8677 toArray: toArray_1,
8678 toHex: toHex_1,
8679 htonl: htonl_1,
8680 toHex32: toHex32_1,
8681 zero2: zero2_1,
8682 zero8: zero8_1,
8683 join32: join32_1,
8684 split32: split32_1,
8685 rotr32: rotr32_1,
8686 rotl32: rotl32_1,
8687 sum32: sum32_1,
8688 sum32_3: sum32_3_1,
8689 sum32_4: sum32_4_1,
8690 sum32_5: sum32_5_1,
8691 sum64: sum64_1,
8692 sum64_hi: sum64_hi_1,
8693 sum64_lo: sum64_lo_1,
8694 sum64_4_hi: sum64_4_hi_1,
8695 sum64_4_lo: sum64_4_lo_1,
8696 sum64_5_hi: sum64_5_hi_1,
8697 sum64_5_lo: sum64_5_lo_1,
8698 rotr64_hi: rotr64_hi_1,
8699 rotr64_lo: rotr64_lo_1,
8700 shr64_hi: shr64_hi_1,
8701 shr64_lo: shr64_lo_1
8702};
8703
8704function BlockHash() {
8705 this.pending = null;
8706 this.pendingTotal = 0;
8707 this.blockSize = this.constructor.blockSize;
8708 this.outSize = this.constructor.outSize;
8709 this.hmacStrength = this.constructor.hmacStrength;
8710 this.padLength = this.constructor.padLength / 8;
8711 this.endian = 'big';
8712
8713 this._delta8 = this.blockSize / 8;
8714 this._delta32 = this.blockSize / 32;
8715}
8716var BlockHash_1 = BlockHash;
8717
8718BlockHash.prototype.update = function update(msg, enc) {
8719 // Convert message to array, pad it, and join into 32bit blocks
8720 msg = utils.toArray(msg, enc);
8721 if (!this.pending)
8722 this.pending = msg;
8723 else
8724 this.pending = this.pending.concat(msg);
8725 this.pendingTotal += msg.length;
8726
8727 // Enough data, try updating
8728 if (this.pending.length >= this._delta8) {
8729 msg = this.pending;
8730
8731 // Process pending data in blocks
8732 var r = msg.length % this._delta8;
8733 this.pending = msg.slice(msg.length - r, msg.length);
8734 if (this.pending.length === 0)
8735 this.pending = null;
8736
8737 msg = utils.join32(msg, 0, msg.length - r, this.endian);
8738 for (var i = 0; i < msg.length; i += this._delta32)
8739 this._update(msg, i, i + this._delta32);
8740 }
8741
8742 return this;
8743};
8744
8745BlockHash.prototype.digest = function digest(enc) {
8746 this.update(this._pad());
8747 minimalisticAssert(this.pending === null);
8748
8749 return this._digest(enc);
8750};
8751
8752BlockHash.prototype._pad = function pad() {
8753 var len = this.pendingTotal;
8754 var bytes = this._delta8;
8755 var k = bytes - ((len + this.padLength) % bytes);
8756 var res = new Array(k + this.padLength);
8757 res[0] = 0x80;
8758 for (var i = 1; i < k; i++)
8759 res[i] = 0;
8760
8761 // Append length
8762 len <<= 3;
8763 if (this.endian === 'big') {
8764 for (var t = 8; t < this.padLength; t++)
8765 res[i++] = 0;
8766
8767 res[i++] = 0;
8768 res[i++] = 0;
8769 res[i++] = 0;
8770 res[i++] = 0;
8771 res[i++] = (len >>> 24) & 0xff;
8772 res[i++] = (len >>> 16) & 0xff;
8773 res[i++] = (len >>> 8) & 0xff;
8774 res[i++] = len & 0xff;
8775 } else {
8776 res[i++] = len & 0xff;
8777 res[i++] = (len >>> 8) & 0xff;
8778 res[i++] = (len >>> 16) & 0xff;
8779 res[i++] = (len >>> 24) & 0xff;
8780 res[i++] = 0;
8781 res[i++] = 0;
8782 res[i++] = 0;
8783 res[i++] = 0;
8784
8785 for (t = 8; t < this.padLength; t++)
8786 res[i++] = 0;
8787 }
8788
8789 return res;
8790};
8791
8792var common = {
8793 BlockHash: BlockHash_1
8794};
8795
8796var rotr32$1 = utils.rotr32;
8797
8798function ft_1(s, x, y, z) {
8799 if (s === 0)
8800 return ch32(x, y, z);
8801 if (s === 1 || s === 3)
8802 return p32(x, y, z);
8803 if (s === 2)
8804 return maj32(x, y, z);
8805}
8806var ft_1_1 = ft_1;
8807
8808function ch32(x, y, z) {
8809 return (x & y) ^ ((~x) & z);
8810}
8811var ch32_1 = ch32;
8812
8813function maj32(x, y, z) {
8814 return (x & y) ^ (x & z) ^ (y & z);
8815}
8816var maj32_1 = maj32;
8817
8818function p32(x, y, z) {
8819 return x ^ y ^ z;
8820}
8821var p32_1 = p32;
8822
8823function s0_256(x) {
8824 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
8825}
8826var s0_256_1 = s0_256;
8827
8828function s1_256(x) {
8829 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
8830}
8831var s1_256_1 = s1_256;
8832
8833function g0_256(x) {
8834 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
8835}
8836var g0_256_1 = g0_256;
8837
8838function g1_256(x) {
8839 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
8840}
8841var g1_256_1 = g1_256;
8842
8843var common$1 = {
8844 ft_1: ft_1_1,
8845 ch32: ch32_1,
8846 maj32: maj32_1,
8847 p32: p32_1,
8848 s0_256: s0_256_1,
8849 s1_256: s1_256_1,
8850 g0_256: g0_256_1,
8851 g1_256: g1_256_1
8852};
8853
8854var sum32$1 = utils.sum32;
8855var sum32_4$1 = utils.sum32_4;
8856var sum32_5$1 = utils.sum32_5;
8857var ch32$1 = common$1.ch32;
8858var maj32$1 = common$1.maj32;
8859var s0_256$1 = common$1.s0_256;
8860var s1_256$1 = common$1.s1_256;
8861var g0_256$1 = common$1.g0_256;
8862var g1_256$1 = common$1.g1_256;
8863
8864var BlockHash$1 = common.BlockHash;
8865
8866var sha256_K = [
8867 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
8868 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8869 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
8870 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8871 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
8872 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
8873 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
8874 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8875 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
8876 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
8877 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
8878 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8879 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
8880 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
8881 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
8882 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
8883];
8884
8885function SHA256() {
8886 if (!(this instanceof SHA256))
8887 return new SHA256();
8888
8889 BlockHash$1.call(this);
8890 this.h = [
8891 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
8892 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
8893 ];
8894 this.k = sha256_K;
8895 this.W = new Array(64);
8896}
8897utils.inherits(SHA256, BlockHash$1);
8898var _256 = SHA256;
8899
8900SHA256.blockSize = 512;
8901SHA256.outSize = 256;
8902SHA256.hmacStrength = 192;
8903SHA256.padLength = 64;
8904
8905SHA256.prototype._update = function _update(msg, start) {
8906 var W = this.W;
8907
8908 for (var i = 0; i < 16; i++)
8909 W[i] = msg[start + i];
8910 for (; i < W.length; i++)
8911 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
8912
8913 var a = this.h[0];
8914 var b = this.h[1];
8915 var c = this.h[2];
8916 var d = this.h[3];
8917 var e = this.h[4];
8918 var f = this.h[5];
8919 var g = this.h[6];
8920 var h = this.h[7];
8921
8922 minimalisticAssert(this.k.length === W.length);
8923 for (i = 0; i < W.length; i++) {
8924 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
8925 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
8926 h = g;
8927 g = f;
8928 f = e;
8929 e = sum32$1(d, T1);
8930 d = c;
8931 c = b;
8932 b = a;
8933 a = sum32$1(T1, T2);
8934 }
8935
8936 this.h[0] = sum32$1(this.h[0], a);
8937 this.h[1] = sum32$1(this.h[1], b);
8938 this.h[2] = sum32$1(this.h[2], c);
8939 this.h[3] = sum32$1(this.h[3], d);
8940 this.h[4] = sum32$1(this.h[4], e);
8941 this.h[5] = sum32$1(this.h[5], f);
8942 this.h[6] = sum32$1(this.h[6], g);
8943 this.h[7] = sum32$1(this.h[7], h);
8944};
8945
8946SHA256.prototype._digest = function digest(enc) {
8947 if (enc === 'hex')
8948 return utils.toHex32(this.h, 'big');
8949 else
8950 return utils.split32(this.h, 'big');
8951};
8952
8953function SHA224() {
8954 if (!(this instanceof SHA224))
8955 return new SHA224();
8956
8957 _256.call(this);
8958 this.h = [
8959 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
8960 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
8961}
8962utils.inherits(SHA224, _256);
8963var _224 = SHA224;
8964
8965SHA224.blockSize = 512;
8966SHA224.outSize = 224;
8967SHA224.hmacStrength = 192;
8968SHA224.padLength = 64;
8969
8970SHA224.prototype._digest = function digest(enc) {
8971 // Just truncate output
8972 if (enc === 'hex')
8973 return utils.toHex32(this.h.slice(0, 7), 'big');
8974 else
8975 return utils.split32(this.h.slice(0, 7), 'big');
8976};
8977
8978var rotr64_hi$1 = utils.rotr64_hi;
8979var rotr64_lo$1 = utils.rotr64_lo;
8980var shr64_hi$1 = utils.shr64_hi;
8981var shr64_lo$1 = utils.shr64_lo;
8982var sum64$1 = utils.sum64;
8983var sum64_hi$1 = utils.sum64_hi;
8984var sum64_lo$1 = utils.sum64_lo;
8985var sum64_4_hi$1 = utils.sum64_4_hi;
8986var sum64_4_lo$1 = utils.sum64_4_lo;
8987var sum64_5_hi$1 = utils.sum64_5_hi;
8988var sum64_5_lo$1 = utils.sum64_5_lo;
8989
8990var BlockHash$2 = common.BlockHash;
8991
8992var sha512_K = [
8993 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
8994 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
8995 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
8996 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
8997 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
8998 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
8999 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
9000 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
9001 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
9002 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
9003 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
9004 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
9005 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
9006 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
9007 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
9008 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
9009 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
9010 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
9011 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
9012 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
9013 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
9014 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
9015 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
9016 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
9017 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
9018 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
9019 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
9020 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
9021 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
9022 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
9023 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
9024 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
9025 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
9026 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
9027 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
9028 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
9029 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
9030 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
9031 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
9032 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
9033];
9034
9035function SHA512() {
9036 if (!(this instanceof SHA512))
9037 return new SHA512();
9038
9039 BlockHash$2.call(this);
9040 this.h = [
9041 0x6a09e667, 0xf3bcc908,
9042 0xbb67ae85, 0x84caa73b,
9043 0x3c6ef372, 0xfe94f82b,
9044 0xa54ff53a, 0x5f1d36f1,
9045 0x510e527f, 0xade682d1,
9046 0x9b05688c, 0x2b3e6c1f,
9047 0x1f83d9ab, 0xfb41bd6b,
9048 0x5be0cd19, 0x137e2179 ];
9049 this.k = sha512_K;
9050 this.W = new Array(160);
9051}
9052utils.inherits(SHA512, BlockHash$2);
9053var _512 = SHA512;
9054
9055SHA512.blockSize = 1024;
9056SHA512.outSize = 512;
9057SHA512.hmacStrength = 192;
9058SHA512.padLength = 128;
9059
9060SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
9061 var W = this.W;
9062
9063 // 32 x 32bit words
9064 for (var i = 0; i < 32; i++)
9065 W[i] = msg[start + i];
9066 for (; i < W.length; i += 2) {
9067 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
9068 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
9069 var c1_hi = W[i - 14]; // i - 7
9070 var c1_lo = W[i - 13];
9071 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
9072 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
9073 var c3_hi = W[i - 32]; // i - 16
9074 var c3_lo = W[i - 31];
9075
9076 W[i] = sum64_4_hi$1(
9077 c0_hi, c0_lo,
9078 c1_hi, c1_lo,
9079 c2_hi, c2_lo,
9080 c3_hi, c3_lo);
9081 W[i + 1] = sum64_4_lo$1(
9082 c0_hi, c0_lo,
9083 c1_hi, c1_lo,
9084 c2_hi, c2_lo,
9085 c3_hi, c3_lo);
9086 }
9087};
9088
9089SHA512.prototype._update = function _update(msg, start) {
9090 this._prepareBlock(msg, start);
9091
9092 var W = this.W;
9093
9094 var ah = this.h[0];
9095 var al = this.h[1];
9096 var bh = this.h[2];
9097 var bl = this.h[3];
9098 var ch = this.h[4];
9099 var cl = this.h[5];
9100 var dh = this.h[6];
9101 var dl = this.h[7];
9102 var eh = this.h[8];
9103 var el = this.h[9];
9104 var fh = this.h[10];
9105 var fl = this.h[11];
9106 var gh = this.h[12];
9107 var gl = this.h[13];
9108 var hh = this.h[14];
9109 var hl = this.h[15];
9110
9111 minimalisticAssert(this.k.length === W.length);
9112 for (var i = 0; i < W.length; i += 2) {
9113 var c0_hi = hh;
9114 var c0_lo = hl;
9115 var c1_hi = s1_512_hi(eh, el);
9116 var c1_lo = s1_512_lo(eh, el);
9117 var c2_hi = ch64_hi(eh, el, fh, fl, gh);
9118 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
9119 var c3_hi = this.k[i];
9120 var c3_lo = this.k[i + 1];
9121 var c4_hi = W[i];
9122 var c4_lo = W[i + 1];
9123
9124 var T1_hi = sum64_5_hi$1(
9125 c0_hi, c0_lo,
9126 c1_hi, c1_lo,
9127 c2_hi, c2_lo,
9128 c3_hi, c3_lo,
9129 c4_hi, c4_lo);
9130 var T1_lo = sum64_5_lo$1(
9131 c0_hi, c0_lo,
9132 c1_hi, c1_lo,
9133 c2_hi, c2_lo,
9134 c3_hi, c3_lo,
9135 c4_hi, c4_lo);
9136
9137 c0_hi = s0_512_hi(ah, al);
9138 c0_lo = s0_512_lo(ah, al);
9139 c1_hi = maj64_hi(ah, al, bh, bl, ch);
9140 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
9141
9142 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
9143 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
9144
9145 hh = gh;
9146 hl = gl;
9147
9148 gh = fh;
9149 gl = fl;
9150
9151 fh = eh;
9152 fl = el;
9153
9154 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
9155 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
9156
9157 dh = ch;
9158 dl = cl;
9159
9160 ch = bh;
9161 cl = bl;
9162
9163 bh = ah;
9164 bl = al;
9165
9166 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
9167 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
9168 }
9169
9170 sum64$1(this.h, 0, ah, al);
9171 sum64$1(this.h, 2, bh, bl);
9172 sum64$1(this.h, 4, ch, cl);
9173 sum64$1(this.h, 6, dh, dl);
9174 sum64$1(this.h, 8, eh, el);
9175 sum64$1(this.h, 10, fh, fl);
9176 sum64$1(this.h, 12, gh, gl);
9177 sum64$1(this.h, 14, hh, hl);
9178};
9179
9180SHA512.prototype._digest = function digest(enc) {
9181 if (enc === 'hex')
9182 return utils.toHex32(this.h, 'big');
9183 else
9184 return utils.split32(this.h, 'big');
9185};
9186
9187function ch64_hi(xh, xl, yh, yl, zh) {
9188 var r = (xh & yh) ^ ((~xh) & zh);
9189 if (r < 0)
9190 r += 0x100000000;
9191 return r;
9192}
9193
9194function ch64_lo(xh, xl, yh, yl, zh, zl) {
9195 var r = (xl & yl) ^ ((~xl) & zl);
9196 if (r < 0)
9197 r += 0x100000000;
9198 return r;
9199}
9200
9201function maj64_hi(xh, xl, yh, yl, zh) {
9202 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
9203 if (r < 0)
9204 r += 0x100000000;
9205 return r;
9206}
9207
9208function maj64_lo(xh, xl, yh, yl, zh, zl) {
9209 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
9210 if (r < 0)
9211 r += 0x100000000;
9212 return r;
9213}
9214
9215function s0_512_hi(xh, xl) {
9216 var c0_hi = rotr64_hi$1(xh, xl, 28);
9217 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
9218 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
9219
9220 var r = c0_hi ^ c1_hi ^ c2_hi;
9221 if (r < 0)
9222 r += 0x100000000;
9223 return r;
9224}
9225
9226function s0_512_lo(xh, xl) {
9227 var c0_lo = rotr64_lo$1(xh, xl, 28);
9228 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
9229 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
9230
9231 var r = c0_lo ^ c1_lo ^ c2_lo;
9232 if (r < 0)
9233 r += 0x100000000;
9234 return r;
9235}
9236
9237function s1_512_hi(xh, xl) {
9238 var c0_hi = rotr64_hi$1(xh, xl, 14);
9239 var c1_hi = rotr64_hi$1(xh, xl, 18);
9240 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
9241
9242 var r = c0_hi ^ c1_hi ^ c2_hi;
9243 if (r < 0)
9244 r += 0x100000000;
9245 return r;
9246}
9247
9248function s1_512_lo(xh, xl) {
9249 var c0_lo = rotr64_lo$1(xh, xl, 14);
9250 var c1_lo = rotr64_lo$1(xh, xl, 18);
9251 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
9252
9253 var r = c0_lo ^ c1_lo ^ c2_lo;
9254 if (r < 0)
9255 r += 0x100000000;
9256 return r;
9257}
9258
9259function g0_512_hi(xh, xl) {
9260 var c0_hi = rotr64_hi$1(xh, xl, 1);
9261 var c1_hi = rotr64_hi$1(xh, xl, 8);
9262 var c2_hi = shr64_hi$1(xh, xl, 7);
9263
9264 var r = c0_hi ^ c1_hi ^ c2_hi;
9265 if (r < 0)
9266 r += 0x100000000;
9267 return r;
9268}
9269
9270function g0_512_lo(xh, xl) {
9271 var c0_lo = rotr64_lo$1(xh, xl, 1);
9272 var c1_lo = rotr64_lo$1(xh, xl, 8);
9273 var c2_lo = shr64_lo$1(xh, xl, 7);
9274
9275 var r = c0_lo ^ c1_lo ^ c2_lo;
9276 if (r < 0)
9277 r += 0x100000000;
9278 return r;
9279}
9280
9281function g1_512_hi(xh, xl) {
9282 var c0_hi = rotr64_hi$1(xh, xl, 19);
9283 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
9284 var c2_hi = shr64_hi$1(xh, xl, 6);
9285
9286 var r = c0_hi ^ c1_hi ^ c2_hi;
9287 if (r < 0)
9288 r += 0x100000000;
9289 return r;
9290}
9291
9292function g1_512_lo(xh, xl) {
9293 var c0_lo = rotr64_lo$1(xh, xl, 19);
9294 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
9295 var c2_lo = shr64_lo$1(xh, xl, 6);
9296
9297 var r = c0_lo ^ c1_lo ^ c2_lo;
9298 if (r < 0)
9299 r += 0x100000000;
9300 return r;
9301}
9302
9303function SHA384() {
9304 if (!(this instanceof SHA384))
9305 return new SHA384();
9306
9307 _512.call(this);
9308 this.h = [
9309 0xcbbb9d5d, 0xc1059ed8,
9310 0x629a292a, 0x367cd507,
9311 0x9159015a, 0x3070dd17,
9312 0x152fecd8, 0xf70e5939,
9313 0x67332667, 0xffc00b31,
9314 0x8eb44a87, 0x68581511,
9315 0xdb0c2e0d, 0x64f98fa7,
9316 0x47b5481d, 0xbefa4fa4 ];
9317}
9318utils.inherits(SHA384, _512);
9319var _384 = SHA384;
9320
9321SHA384.blockSize = 1024;
9322SHA384.outSize = 384;
9323SHA384.hmacStrength = 192;
9324SHA384.padLength = 128;
9325
9326SHA384.prototype._digest = function digest(enc) {
9327 if (enc === 'hex')
9328 return utils.toHex32(this.h.slice(0, 12), 'big');
9329 else
9330 return utils.split32(this.h.slice(0, 12), 'big');
9331};
9332
9333var rotl32$1 = utils.rotl32;
9334var sum32$2 = utils.sum32;
9335var sum32_3$1 = utils.sum32_3;
9336var sum32_4$2 = utils.sum32_4;
9337var BlockHash$3 = common.BlockHash;
9338
9339function RIPEMD160() {
9340 if (!(this instanceof RIPEMD160))
9341 return new RIPEMD160();
9342
9343 BlockHash$3.call(this);
9344
9345 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
9346 this.endian = 'little';
9347}
9348utils.inherits(RIPEMD160, BlockHash$3);
9349var ripemd160 = RIPEMD160;
9350
9351RIPEMD160.blockSize = 512;
9352RIPEMD160.outSize = 160;
9353RIPEMD160.hmacStrength = 192;
9354RIPEMD160.padLength = 64;
9355
9356RIPEMD160.prototype._update = function update(msg, start) {
9357 var A = this.h[0];
9358 var B = this.h[1];
9359 var C = this.h[2];
9360 var D = this.h[3];
9361 var E = this.h[4];
9362 var Ah = A;
9363 var Bh = B;
9364 var Ch = C;
9365 var Dh = D;
9366 var Eh = E;
9367 for (var j = 0; j < 80; j++) {
9368 var T = sum32$2(
9369 rotl32$1(
9370 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
9371 s[j]),
9372 E);
9373 A = E;
9374 E = D;
9375 D = rotl32$1(C, 10);
9376 C = B;
9377 B = T;
9378 T = sum32$2(
9379 rotl32$1(
9380 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
9381 sh[j]),
9382 Eh);
9383 Ah = Eh;
9384 Eh = Dh;
9385 Dh = rotl32$1(Ch, 10);
9386 Ch = Bh;
9387 Bh = T;
9388 }
9389 T = sum32_3$1(this.h[1], C, Dh);
9390 this.h[1] = sum32_3$1(this.h[2], D, Eh);
9391 this.h[2] = sum32_3$1(this.h[3], E, Ah);
9392 this.h[3] = sum32_3$1(this.h[4], A, Bh);
9393 this.h[4] = sum32_3$1(this.h[0], B, Ch);
9394 this.h[0] = T;
9395};
9396
9397RIPEMD160.prototype._digest = function digest(enc) {
9398 if (enc === 'hex')
9399 return utils.toHex32(this.h, 'little');
9400 else
9401 return utils.split32(this.h, 'little');
9402};
9403
9404function f(j, x, y, z) {
9405 if (j <= 15)
9406 return x ^ y ^ z;
9407 else if (j <= 31)
9408 return (x & y) | ((~x) & z);
9409 else if (j <= 47)
9410 return (x | (~y)) ^ z;
9411 else if (j <= 63)
9412 return (x & z) | (y & (~z));
9413 else
9414 return x ^ (y | (~z));
9415}
9416
9417function K(j) {
9418 if (j <= 15)
9419 return 0x00000000;
9420 else if (j <= 31)
9421 return 0x5a827999;
9422 else if (j <= 47)
9423 return 0x6ed9eba1;
9424 else if (j <= 63)
9425 return 0x8f1bbcdc;
9426 else
9427 return 0xa953fd4e;
9428}
9429
9430function Kh(j) {
9431 if (j <= 15)
9432 return 0x50a28be6;
9433 else if (j <= 31)
9434 return 0x5c4dd124;
9435 else if (j <= 47)
9436 return 0x6d703ef3;
9437 else if (j <= 63)
9438 return 0x7a6d76e9;
9439 else
9440 return 0x00000000;
9441}
9442
9443var r = [
9444 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
9445 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
9446 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
9447 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
9448 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
9449];
9450
9451var rh = [
9452 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
9453 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
9454 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
9455 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
9456 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
9457];
9458
9459var s = [
9460 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
9461 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
9462 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
9463 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9464 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
9465];
9466
9467var sh = [
9468 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9469 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9470 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
9471 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
9472 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
9473];
9474
9475var ripemd = {
9476 ripemd160: ripemd160
9477};
9478
9479/**
9480 * A fast MD5 JavaScript implementation
9481 * Copyright (c) 2012 Joseph Myers
9482 * http://www.myersdaily.org/joseph/javascript/md5-text.html
9483 *
9484 * Permission to use, copy, modify, and distribute this software
9485 * and its documentation for any purposes and without
9486 * fee is hereby granted provided that this copyright notice
9487 * appears in all copies.
9488 *
9489 * Of course, this soft is provided "as is" without express or implied
9490 * warranty of any kind.
9491 */
9492
9493// MD5 Digest
9494async function md5(entree) {
9495 const digest = md51(util.uint8ArrayToString(entree));
9496 return util.hexToUint8Array(hex(digest));
9497}
9498
9499function md5cycle(x, k) {
9500 let a = x[0];
9501 let b = x[1];
9502 let c = x[2];
9503 let d = x[3];
9504
9505 a = ff(a, b, c, d, k[0], 7, -680876936);
9506 d = ff(d, a, b, c, k[1], 12, -389564586);
9507 c = ff(c, d, a, b, k[2], 17, 606105819);
9508 b = ff(b, c, d, a, k[3], 22, -1044525330);
9509 a = ff(a, b, c, d, k[4], 7, -176418897);
9510 d = ff(d, a, b, c, k[5], 12, 1200080426);
9511 c = ff(c, d, a, b, k[6], 17, -1473231341);
9512 b = ff(b, c, d, a, k[7], 22, -45705983);
9513 a = ff(a, b, c, d, k[8], 7, 1770035416);
9514 d = ff(d, a, b, c, k[9], 12, -1958414417);
9515 c = ff(c, d, a, b, k[10], 17, -42063);
9516 b = ff(b, c, d, a, k[11], 22, -1990404162);
9517 a = ff(a, b, c, d, k[12], 7, 1804603682);
9518 d = ff(d, a, b, c, k[13], 12, -40341101);
9519 c = ff(c, d, a, b, k[14], 17, -1502002290);
9520 b = ff(b, c, d, a, k[15], 22, 1236535329);
9521
9522 a = gg(a, b, c, d, k[1], 5, -165796510);
9523 d = gg(d, a, b, c, k[6], 9, -1069501632);
9524 c = gg(c, d, a, b, k[11], 14, 643717713);
9525 b = gg(b, c, d, a, k[0], 20, -373897302);
9526 a = gg(a, b, c, d, k[5], 5, -701558691);
9527 d = gg(d, a, b, c, k[10], 9, 38016083);
9528 c = gg(c, d, a, b, k[15], 14, -660478335);
9529 b = gg(b, c, d, a, k[4], 20, -405537848);
9530 a = gg(a, b, c, d, k[9], 5, 568446438);
9531 d = gg(d, a, b, c, k[14], 9, -1019803690);
9532 c = gg(c, d, a, b, k[3], 14, -187363961);
9533 b = gg(b, c, d, a, k[8], 20, 1163531501);
9534 a = gg(a, b, c, d, k[13], 5, -1444681467);
9535 d = gg(d, a, b, c, k[2], 9, -51403784);
9536 c = gg(c, d, a, b, k[7], 14, 1735328473);
9537 b = gg(b, c, d, a, k[12], 20, -1926607734);
9538
9539 a = hh(a, b, c, d, k[5], 4, -378558);
9540 d = hh(d, a, b, c, k[8], 11, -2022574463);
9541 c = hh(c, d, a, b, k[11], 16, 1839030562);
9542 b = hh(b, c, d, a, k[14], 23, -35309556);
9543 a = hh(a, b, c, d, k[1], 4, -1530992060);
9544 d = hh(d, a, b, c, k[4], 11, 1272893353);
9545 c = hh(c, d, a, b, k[7], 16, -155497632);
9546 b = hh(b, c, d, a, k[10], 23, -1094730640);
9547 a = hh(a, b, c, d, k[13], 4, 681279174);
9548 d = hh(d, a, b, c, k[0], 11, -358537222);
9549 c = hh(c, d, a, b, k[3], 16, -722521979);
9550 b = hh(b, c, d, a, k[6], 23, 76029189);
9551 a = hh(a, b, c, d, k[9], 4, -640364487);
9552 d = hh(d, a, b, c, k[12], 11, -421815835);
9553 c = hh(c, d, a, b, k[15], 16, 530742520);
9554 b = hh(b, c, d, a, k[2], 23, -995338651);
9555
9556 a = ii(a, b, c, d, k[0], 6, -198630844);
9557 d = ii(d, a, b, c, k[7], 10, 1126891415);
9558 c = ii(c, d, a, b, k[14], 15, -1416354905);
9559 b = ii(b, c, d, a, k[5], 21, -57434055);
9560 a = ii(a, b, c, d, k[12], 6, 1700485571);
9561 d = ii(d, a, b, c, k[3], 10, -1894986606);
9562 c = ii(c, d, a, b, k[10], 15, -1051523);
9563 b = ii(b, c, d, a, k[1], 21, -2054922799);
9564 a = ii(a, b, c, d, k[8], 6, 1873313359);
9565 d = ii(d, a, b, c, k[15], 10, -30611744);
9566 c = ii(c, d, a, b, k[6], 15, -1560198380);
9567 b = ii(b, c, d, a, k[13], 21, 1309151649);
9568 a = ii(a, b, c, d, k[4], 6, -145523070);
9569 d = ii(d, a, b, c, k[11], 10, -1120210379);
9570 c = ii(c, d, a, b, k[2], 15, 718787259);
9571 b = ii(b, c, d, a, k[9], 21, -343485551);
9572
9573 x[0] = add32(a, x[0]);
9574 x[1] = add32(b, x[1]);
9575 x[2] = add32(c, x[2]);
9576 x[3] = add32(d, x[3]);
9577}
9578
9579function cmn(q, a, b, x, s, t) {
9580 a = add32(add32(a, q), add32(x, t));
9581 return add32((a << s) | (a >>> (32 - s)), b);
9582}
9583
9584function ff(a, b, c, d, x, s, t) {
9585 return cmn((b & c) | ((~b) & d), a, b, x, s, t);
9586}
9587
9588function gg(a, b, c, d, x, s, t) {
9589 return cmn((b & d) | (c & (~d)), a, b, x, s, t);
9590}
9591
9592function hh(a, b, c, d, x, s, t) {
9593 return cmn(b ^ c ^ d, a, b, x, s, t);
9594}
9595
9596function ii(a, b, c, d, x, s, t) {
9597 return cmn(c ^ (b | (~d)), a, b, x, s, t);
9598}
9599
9600function md51(s) {
9601 const n = s.length;
9602 const state = [1732584193, -271733879, -1732584194, 271733878];
9603 let i;
9604 for (i = 64; i <= s.length; i += 64) {
9605 md5cycle(state, md5blk(s.substring(i - 64, i)));
9606 }
9607 s = s.substring(i - 64);
9608 const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9609 for (i = 0; i < s.length; i++) {
9610 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
9611 }
9612 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
9613 if (i > 55) {
9614 md5cycle(state, tail);
9615 for (i = 0; i < 16; i++) {
9616 tail[i] = 0;
9617 }
9618 }
9619 tail[14] = n * 8;
9620 md5cycle(state, tail);
9621 return state;
9622}
9623
9624/* there needs to be support for Unicode here,
9625 * unless we pretend that we can redefine the MD-5
9626 * algorithm for multi-byte characters (perhaps
9627 * by adding every four 16-bit characters and
9628 * shortening the sum to 32 bits). Otherwise
9629 * I suggest performing MD-5 as if every character
9630 * was two bytes--e.g., 0040 0025 = @%--but then
9631 * how will an ordinary MD-5 sum be matched?
9632 * There is no way to standardize text to something
9633 * like UTF-8 before transformation; speed cost is
9634 * utterly prohibitive. The JavaScript standard
9635 * itself needs to look at this: it should start
9636 * providing access to strings as preformed UTF-8
9637 * 8-bit unsigned value arrays.
9638 */
9639function md5blk(s) { /* I figured global was faster. */
9640 const md5blks = [];
9641 let i; /* Andy King said do it this way. */
9642 for (i = 0; i < 64; i += 4) {
9643 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<
9644 24);
9645 }
9646 return md5blks;
9647}
9648
9649const hex_chr = '0123456789abcdef'.split('');
9650
9651function rhex(n) {
9652 let s = '';
9653 let j = 0;
9654 for (; j < 4; j++) {
9655 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
9656 }
9657 return s;
9658}
9659
9660function hex(x) {
9661 for (let i = 0; i < x.length; i++) {
9662 x[i] = rhex(x[i]);
9663 }
9664 return x.join('');
9665}
9666
9667/* this function is much faster,
9668so if possible we use it. Some IEs
9669are the only ones I know of that
9670need the idiotic second function,
9671generated by an if clause. */
9672
9673function add32(a, b) {
9674 return (a + b) & 0xFFFFFFFF;
9675}
9676
9677/**
9678 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
9679 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9680 * @see {@link https://github.com/indutny/hash.js|hash.js}
9681 * @module crypto/hash
9682 * @private
9683 */
9684
9685const webCrypto = util.getWebCrypto();
9686const nodeCrypto = util.getNodeCrypto();
9687const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();
9688
9689function nodeHash(type) {
9690 if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {
9691 return;
9692 }
9693 return async function (data) {
9694 const shasum = nodeCrypto.createHash(type);
9695 return transform(data, value => {
9696 shasum.update(value);
9697 }, () => new Uint8Array(shasum.digest()));
9698 };
9699}
9700
9701function hashjsHash(hash, webCryptoHash) {
9702 return async function(data, config = defaultConfig) {
9703 if (isArrayStream(data)) {
9704 data = await readToEnd(data);
9705 }
9706 if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9707 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9708 }
9709 const hashInstance = hash();
9710 return transform(data, value => {
9711 hashInstance.update(value);
9712 }, () => new Uint8Array(hashInstance.digest()));
9713 };
9714}
9715
9716function asmcryptoHash(hash, webCryptoHash) {
9717 return async function(data, config = defaultConfig) {
9718 if (isArrayStream(data)) {
9719 data = await readToEnd(data);
9720 }
9721 if (util.isStream(data)) {
9722 const hashInstance = new hash();
9723 return transform(data, value => {
9724 hashInstance.process(value);
9725 }, () => hashInstance.finish().result);
9726 } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9727 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9728 } else {
9729 return hash.bytes(data);
9730 }
9731 };
9732}
9733
9734const hashFunctions = {
9735 md5: nodeHash('md5') || md5,
9736 sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),
9737 sha224: nodeHash('sha224') || hashjsHash(_224),
9738 sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),
9739 sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'),
9740 sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge.
9741 ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)
9742};
9743
9744var hash = {
9745
9746 /** @see module:md5 */
9747 md5: hashFunctions.md5,
9748 /** @see asmCrypto */
9749 sha1: hashFunctions.sha1,
9750 /** @see hash.js */
9751 sha224: hashFunctions.sha224,
9752 /** @see asmCrypto */
9753 sha256: hashFunctions.sha256,
9754 /** @see hash.js */
9755 sha384: hashFunctions.sha384,
9756 /** @see asmCrypto */
9757 sha512: hashFunctions.sha512,
9758 /** @see hash.js */
9759 ripemd: hashFunctions.ripemd,
9760
9761 /**
9762 * Create a hash on the specified data using the specified algorithm
9763 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9764 * @param {Uint8Array} data - Data to be hashed
9765 * @returns {Promise<Uint8Array>} Hash value.
9766 */
9767 digest: function(algo, data) {
9768 switch (algo) {
9769 case enums.hash.md5:
9770 return this.md5(data);
9771 case enums.hash.sha1:
9772 return this.sha1(data);
9773 case enums.hash.ripemd:
9774 return this.ripemd(data);
9775 case enums.hash.sha256:
9776 return this.sha256(data);
9777 case enums.hash.sha384:
9778 return this.sha384(data);
9779 case enums.hash.sha512:
9780 return this.sha512(data);
9781 case enums.hash.sha224:
9782 return this.sha224(data);
9783 default:
9784 throw new Error('Invalid hash function.');
9785 }
9786 },
9787
9788 /**
9789 * Returns the hash size in bytes of the specified hash algorithm type
9790 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9791 * @returns {Integer} Size in bytes of the resulting hash.
9792 */
9793 getHashByteLength: function(algo) {
9794 switch (algo) {
9795 case enums.hash.md5:
9796 return 16;
9797 case enums.hash.sha1:
9798 case enums.hash.ripemd:
9799 return 20;
9800 case enums.hash.sha256:
9801 return 32;
9802 case enums.hash.sha384:
9803 return 48;
9804 case enums.hash.sha512:
9805 return 64;
9806 case enums.hash.sha224:
9807 return 28;
9808 default:
9809 throw new Error('Invalid hash algorithm.');
9810 }
9811 }
9812};
9813
9814class AES_CFB {
9815 static encrypt(data, key, iv) {
9816 return new AES_CFB(key, iv).encrypt(data);
9817 }
9818 static decrypt(data, key, iv) {
9819 return new AES_CFB(key, iv).decrypt(data);
9820 }
9821 constructor(key, iv, aes) {
9822 this.aes = aes ? aes : new AES(key, iv, true, 'CFB');
9823 delete this.aes.padding;
9824 }
9825 encrypt(data) {
9826 const r1 = this.aes.AES_Encrypt_process(data);
9827 const r2 = this.aes.AES_Encrypt_finish();
9828 return joinBytes(r1, r2);
9829 }
9830 decrypt(data) {
9831 const r1 = this.aes.AES_Decrypt_process(data);
9832 const r2 = this.aes.AES_Decrypt_finish();
9833 return joinBytes(r1, r2);
9834 }
9835}
9836
9837var naclFastLight = createCommonjsModule(function (module) {
9838/*jshint bitwise: false*/
9839
9840(function(nacl) {
9841
9842// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
9843// Public domain.
9844//
9845// Implementation derived from TweetNaCl version 20140427.
9846// See for details: http://tweetnacl.cr.yp.to/
9847
9848var gf = function(init) {
9849 var i, r = new Float64Array(16);
9850 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
9851 return r;
9852};
9853
9854// Pluggable, initialized in high-level API below.
9855var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
9856
9857var _9 = new Uint8Array(32); _9[0] = 9;
9858
9859var gf0 = gf(),
9860 gf1 = gf([1]),
9861 _121665 = gf([0xdb41, 1]),
9862 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
9863 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
9864 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
9865 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
9866 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
9867
9868function vn(x, xi, y, yi, n) {
9869 var i,d = 0;
9870 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
9871 return (1 & ((d - 1) >>> 8)) - 1;
9872}
9873
9874function crypto_verify_32(x, xi, y, yi) {
9875 return vn(x,xi,y,yi,32);
9876}
9877
9878function set25519(r, a) {
9879 var i;
9880 for (i = 0; i < 16; i++) r[i] = a[i]|0;
9881}
9882
9883function car25519(o) {
9884 var i, v, c = 1;
9885 for (i = 0; i < 16; i++) {
9886 v = o[i] + c + 65535;
9887 c = Math.floor(v / 65536);
9888 o[i] = v - c * 65536;
9889 }
9890 o[0] += c-1 + 37 * (c-1);
9891}
9892
9893function sel25519(p, q, b) {
9894 var t, c = ~(b-1);
9895 for (var i = 0; i < 16; i++) {
9896 t = c & (p[i] ^ q[i]);
9897 p[i] ^= t;
9898 q[i] ^= t;
9899 }
9900}
9901
9902function pack25519(o, n) {
9903 var i, j, b;
9904 var m = gf(), t = gf();
9905 for (i = 0; i < 16; i++) t[i] = n[i];
9906 car25519(t);
9907 car25519(t);
9908 car25519(t);
9909 for (j = 0; j < 2; j++) {
9910 m[0] = t[0] - 0xffed;
9911 for (i = 1; i < 15; i++) {
9912 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
9913 m[i-1] &= 0xffff;
9914 }
9915 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
9916 b = (m[15]>>16) & 1;
9917 m[14] &= 0xffff;
9918 sel25519(t, m, 1-b);
9919 }
9920 for (i = 0; i < 16; i++) {
9921 o[2*i] = t[i] & 0xff;
9922 o[2*i+1] = t[i]>>8;
9923 }
9924}
9925
9926function neq25519(a, b) {
9927 var c = new Uint8Array(32), d = new Uint8Array(32);
9928 pack25519(c, a);
9929 pack25519(d, b);
9930 return crypto_verify_32(c, 0, d, 0);
9931}
9932
9933function par25519(a) {
9934 var d = new Uint8Array(32);
9935 pack25519(d, a);
9936 return d[0] & 1;
9937}
9938
9939function unpack25519(o, n) {
9940 var i;
9941 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
9942 o[15] &= 0x7fff;
9943}
9944
9945function A(o, a, b) {
9946 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
9947}
9948
9949function Z(o, a, b) {
9950 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
9951}
9952
9953function M(o, a, b) {
9954 var v, c,
9955 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
9956 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
9957 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
9958 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
9959 b0 = b[0],
9960 b1 = b[1],
9961 b2 = b[2],
9962 b3 = b[3],
9963 b4 = b[4],
9964 b5 = b[5],
9965 b6 = b[6],
9966 b7 = b[7],
9967 b8 = b[8],
9968 b9 = b[9],
9969 b10 = b[10],
9970 b11 = b[11],
9971 b12 = b[12],
9972 b13 = b[13],
9973 b14 = b[14],
9974 b15 = b[15];
9975
9976 v = a[0];
9977 t0 += v * b0;
9978 t1 += v * b1;
9979 t2 += v * b2;
9980 t3 += v * b3;
9981 t4 += v * b4;
9982 t5 += v * b5;
9983 t6 += v * b6;
9984 t7 += v * b7;
9985 t8 += v * b8;
9986 t9 += v * b9;
9987 t10 += v * b10;
9988 t11 += v * b11;
9989 t12 += v * b12;
9990 t13 += v * b13;
9991 t14 += v * b14;
9992 t15 += v * b15;
9993 v = a[1];
9994 t1 += v * b0;
9995 t2 += v * b1;
9996 t3 += v * b2;
9997 t4 += v * b3;
9998 t5 += v * b4;
9999 t6 += v * b5;
10000 t7 += v * b6;
10001 t8 += v * b7;
10002 t9 += v * b8;
10003 t10 += v * b9;
10004 t11 += v * b10;
10005 t12 += v * b11;
10006 t13 += v * b12;
10007 t14 += v * b13;
10008 t15 += v * b14;
10009 t16 += v * b15;
10010 v = a[2];
10011 t2 += v * b0;
10012 t3 += v * b1;
10013 t4 += v * b2;
10014 t5 += v * b3;
10015 t6 += v * b4;
10016 t7 += v * b5;
10017 t8 += v * b6;
10018 t9 += v * b7;
10019 t10 += v * b8;
10020 t11 += v * b9;
10021 t12 += v * b10;
10022 t13 += v * b11;
10023 t14 += v * b12;
10024 t15 += v * b13;
10025 t16 += v * b14;
10026 t17 += v * b15;
10027 v = a[3];
10028 t3 += v * b0;
10029 t4 += v * b1;
10030 t5 += v * b2;
10031 t6 += v * b3;
10032 t7 += v * b4;
10033 t8 += v * b5;
10034 t9 += v * b6;
10035 t10 += v * b7;
10036 t11 += v * b8;
10037 t12 += v * b9;
10038 t13 += v * b10;
10039 t14 += v * b11;
10040 t15 += v * b12;
10041 t16 += v * b13;
10042 t17 += v * b14;
10043 t18 += v * b15;
10044 v = a[4];
10045 t4 += v * b0;
10046 t5 += v * b1;
10047 t6 += v * b2;
10048 t7 += v * b3;
10049 t8 += v * b4;
10050 t9 += v * b5;
10051 t10 += v * b6;
10052 t11 += v * b7;
10053 t12 += v * b8;
10054 t13 += v * b9;
10055 t14 += v * b10;
10056 t15 += v * b11;
10057 t16 += v * b12;
10058 t17 += v * b13;
10059 t18 += v * b14;
10060 t19 += v * b15;
10061 v = a[5];
10062 t5 += v * b0;
10063 t6 += v * b1;
10064 t7 += v * b2;
10065 t8 += v * b3;
10066 t9 += v * b4;
10067 t10 += v * b5;
10068 t11 += v * b6;
10069 t12 += v * b7;
10070 t13 += v * b8;
10071 t14 += v * b9;
10072 t15 += v * b10;
10073 t16 += v * b11;
10074 t17 += v * b12;
10075 t18 += v * b13;
10076 t19 += v * b14;
10077 t20 += v * b15;
10078 v = a[6];
10079 t6 += v * b0;
10080 t7 += v * b1;
10081 t8 += v * b2;
10082 t9 += v * b3;
10083 t10 += v * b4;
10084 t11 += v * b5;
10085 t12 += v * b6;
10086 t13 += v * b7;
10087 t14 += v * b8;
10088 t15 += v * b9;
10089 t16 += v * b10;
10090 t17 += v * b11;
10091 t18 += v * b12;
10092 t19 += v * b13;
10093 t20 += v * b14;
10094 t21 += v * b15;
10095 v = a[7];
10096 t7 += v * b0;
10097 t8 += v * b1;
10098 t9 += v * b2;
10099 t10 += v * b3;
10100 t11 += v * b4;
10101 t12 += v * b5;
10102 t13 += v * b6;
10103 t14 += v * b7;
10104 t15 += v * b8;
10105 t16 += v * b9;
10106 t17 += v * b10;
10107 t18 += v * b11;
10108 t19 += v * b12;
10109 t20 += v * b13;
10110 t21 += v * b14;
10111 t22 += v * b15;
10112 v = a[8];
10113 t8 += v * b0;
10114 t9 += v * b1;
10115 t10 += v * b2;
10116 t11 += v * b3;
10117 t12 += v * b4;
10118 t13 += v * b5;
10119 t14 += v * b6;
10120 t15 += v * b7;
10121 t16 += v * b8;
10122 t17 += v * b9;
10123 t18 += v * b10;
10124 t19 += v * b11;
10125 t20 += v * b12;
10126 t21 += v * b13;
10127 t22 += v * b14;
10128 t23 += v * b15;
10129 v = a[9];
10130 t9 += v * b0;
10131 t10 += v * b1;
10132 t11 += v * b2;
10133 t12 += v * b3;
10134 t13 += v * b4;
10135 t14 += v * b5;
10136 t15 += v * b6;
10137 t16 += v * b7;
10138 t17 += v * b8;
10139 t18 += v * b9;
10140 t19 += v * b10;
10141 t20 += v * b11;
10142 t21 += v * b12;
10143 t22 += v * b13;
10144 t23 += v * b14;
10145 t24 += v * b15;
10146 v = a[10];
10147 t10 += v * b0;
10148 t11 += v * b1;
10149 t12 += v * b2;
10150 t13 += v * b3;
10151 t14 += v * b4;
10152 t15 += v * b5;
10153 t16 += v * b6;
10154 t17 += v * b7;
10155 t18 += v * b8;
10156 t19 += v * b9;
10157 t20 += v * b10;
10158 t21 += v * b11;
10159 t22 += v * b12;
10160 t23 += v * b13;
10161 t24 += v * b14;
10162 t25 += v * b15;
10163 v = a[11];
10164 t11 += v * b0;
10165 t12 += v * b1;
10166 t13 += v * b2;
10167 t14 += v * b3;
10168 t15 += v * b4;
10169 t16 += v * b5;
10170 t17 += v * b6;
10171 t18 += v * b7;
10172 t19 += v * b8;
10173 t20 += v * b9;
10174 t21 += v * b10;
10175 t22 += v * b11;
10176 t23 += v * b12;
10177 t24 += v * b13;
10178 t25 += v * b14;
10179 t26 += v * b15;
10180 v = a[12];
10181 t12 += v * b0;
10182 t13 += v * b1;
10183 t14 += v * b2;
10184 t15 += v * b3;
10185 t16 += v * b4;
10186 t17 += v * b5;
10187 t18 += v * b6;
10188 t19 += v * b7;
10189 t20 += v * b8;
10190 t21 += v * b9;
10191 t22 += v * b10;
10192 t23 += v * b11;
10193 t24 += v * b12;
10194 t25 += v * b13;
10195 t26 += v * b14;
10196 t27 += v * b15;
10197 v = a[13];
10198 t13 += v * b0;
10199 t14 += v * b1;
10200 t15 += v * b2;
10201 t16 += v * b3;
10202 t17 += v * b4;
10203 t18 += v * b5;
10204 t19 += v * b6;
10205 t20 += v * b7;
10206 t21 += v * b8;
10207 t22 += v * b9;
10208 t23 += v * b10;
10209 t24 += v * b11;
10210 t25 += v * b12;
10211 t26 += v * b13;
10212 t27 += v * b14;
10213 t28 += v * b15;
10214 v = a[14];
10215 t14 += v * b0;
10216 t15 += v * b1;
10217 t16 += v * b2;
10218 t17 += v * b3;
10219 t18 += v * b4;
10220 t19 += v * b5;
10221 t20 += v * b6;
10222 t21 += v * b7;
10223 t22 += v * b8;
10224 t23 += v * b9;
10225 t24 += v * b10;
10226 t25 += v * b11;
10227 t26 += v * b12;
10228 t27 += v * b13;
10229 t28 += v * b14;
10230 t29 += v * b15;
10231 v = a[15];
10232 t15 += v * b0;
10233 t16 += v * b1;
10234 t17 += v * b2;
10235 t18 += v * b3;
10236 t19 += v * b4;
10237 t20 += v * b5;
10238 t21 += v * b6;
10239 t22 += v * b7;
10240 t23 += v * b8;
10241 t24 += v * b9;
10242 t25 += v * b10;
10243 t26 += v * b11;
10244 t27 += v * b12;
10245 t28 += v * b13;
10246 t29 += v * b14;
10247 t30 += v * b15;
10248
10249 t0 += 38 * t16;
10250 t1 += 38 * t17;
10251 t2 += 38 * t18;
10252 t3 += 38 * t19;
10253 t4 += 38 * t20;
10254 t5 += 38 * t21;
10255 t6 += 38 * t22;
10256 t7 += 38 * t23;
10257 t8 += 38 * t24;
10258 t9 += 38 * t25;
10259 t10 += 38 * t26;
10260 t11 += 38 * t27;
10261 t12 += 38 * t28;
10262 t13 += 38 * t29;
10263 t14 += 38 * t30;
10264 // t15 left as is
10265
10266 // first car
10267 c = 1;
10268 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
10269 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
10270 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
10271 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
10272 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
10273 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
10274 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
10275 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
10276 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
10277 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
10278 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
10279 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
10280 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
10281 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
10282 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
10283 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
10284 t0 += c-1 + 37 * (c-1);
10285
10286 // second car
10287 c = 1;
10288 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
10289 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
10290 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
10291 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
10292 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
10293 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
10294 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
10295 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
10296 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
10297 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
10298 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
10299 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
10300 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
10301 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
10302 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
10303 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
10304 t0 += c-1 + 37 * (c-1);
10305
10306 o[ 0] = t0;
10307 o[ 1] = t1;
10308 o[ 2] = t2;
10309 o[ 3] = t3;
10310 o[ 4] = t4;
10311 o[ 5] = t5;
10312 o[ 6] = t6;
10313 o[ 7] = t7;
10314 o[ 8] = t8;
10315 o[ 9] = t9;
10316 o[10] = t10;
10317 o[11] = t11;
10318 o[12] = t12;
10319 o[13] = t13;
10320 o[14] = t14;
10321 o[15] = t15;
10322}
10323
10324function S(o, a) {
10325 M(o, a, a);
10326}
10327
10328function inv25519(o, i) {
10329 var c = gf();
10330 var a;
10331 for (a = 0; a < 16; a++) c[a] = i[a];
10332 for (a = 253; a >= 0; a--) {
10333 S(c, c);
10334 if(a !== 2 && a !== 4) M(c, c, i);
10335 }
10336 for (a = 0; a < 16; a++) o[a] = c[a];
10337}
10338
10339function pow2523(o, i) {
10340 var c = gf();
10341 var a;
10342 for (a = 0; a < 16; a++) c[a] = i[a];
10343 for (a = 250; a >= 0; a--) {
10344 S(c, c);
10345 if(a !== 1) M(c, c, i);
10346 }
10347 for (a = 0; a < 16; a++) o[a] = c[a];
10348}
10349
10350function crypto_scalarmult(q, n, p) {
10351 var z = new Uint8Array(32);
10352 var x = new Float64Array(80), r, i;
10353 var a = gf(), b = gf(), c = gf(),
10354 d = gf(), e = gf(), f = gf();
10355 for (i = 0; i < 31; i++) z[i] = n[i];
10356 z[31]=(n[31]&127)|64;
10357 z[0]&=248;
10358 unpack25519(x,p);
10359 for (i = 0; i < 16; i++) {
10360 b[i]=x[i];
10361 d[i]=a[i]=c[i]=0;
10362 }
10363 a[0]=d[0]=1;
10364 for (i=254; i>=0; --i) {
10365 r=(z[i>>>3]>>>(i&7))&1;
10366 sel25519(a,b,r);
10367 sel25519(c,d,r);
10368 A(e,a,c);
10369 Z(a,a,c);
10370 A(c,b,d);
10371 Z(b,b,d);
10372 S(d,e);
10373 S(f,a);
10374 M(a,c,a);
10375 M(c,b,e);
10376 A(e,a,c);
10377 Z(a,a,c);
10378 S(b,a);
10379 Z(c,d,f);
10380 M(a,c,_121665);
10381 A(a,a,d);
10382 M(c,c,a);
10383 M(a,d,f);
10384 M(d,b,x);
10385 S(b,e);
10386 sel25519(a,b,r);
10387 sel25519(c,d,r);
10388 }
10389 for (i = 0; i < 16; i++) {
10390 x[i+16]=a[i];
10391 x[i+32]=c[i];
10392 x[i+48]=b[i];
10393 x[i+64]=d[i];
10394 }
10395 var x32 = x.subarray(32);
10396 var x16 = x.subarray(16);
10397 inv25519(x32,x32);
10398 M(x16,x16,x32);
10399 pack25519(q,x16);
10400 return 0;
10401}
10402
10403function crypto_scalarmult_base(q, n) {
10404 return crypto_scalarmult(q, n, _9);
10405}
10406
10407function crypto_box_keypair(y, x) {
10408 randombytes(x, 32);
10409 return crypto_scalarmult_base(y, x);
10410}
10411
10412function add(p, q) {
10413 var a = gf(), b = gf(), c = gf(),
10414 d = gf(), e = gf(), f = gf(),
10415 g = gf(), h = gf(), t = gf();
10416
10417 Z(a, p[1], p[0]);
10418 Z(t, q[1], q[0]);
10419 M(a, a, t);
10420 A(b, p[0], p[1]);
10421 A(t, q[0], q[1]);
10422 M(b, b, t);
10423 M(c, p[3], q[3]);
10424 M(c, c, D2);
10425 M(d, p[2], q[2]);
10426 A(d, d, d);
10427 Z(e, b, a);
10428 Z(f, d, c);
10429 A(g, d, c);
10430 A(h, b, a);
10431
10432 M(p[0], e, f);
10433 M(p[1], h, g);
10434 M(p[2], g, f);
10435 M(p[3], e, h);
10436}
10437
10438function cswap(p, q, b) {
10439 var i;
10440 for (i = 0; i < 4; i++) {
10441 sel25519(p[i], q[i], b);
10442 }
10443}
10444
10445function pack(r, p) {
10446 var tx = gf(), ty = gf(), zi = gf();
10447 inv25519(zi, p[2]);
10448 M(tx, p[0], zi);
10449 M(ty, p[1], zi);
10450 pack25519(r, ty);
10451 r[31] ^= par25519(tx) << 7;
10452}
10453
10454function scalarmult(p, q, s) {
10455 var b, i;
10456 set25519(p[0], gf0);
10457 set25519(p[1], gf1);
10458 set25519(p[2], gf1);
10459 set25519(p[3], gf0);
10460 for (i = 255; i >= 0; --i) {
10461 b = (s[(i/8)|0] >> (i&7)) & 1;
10462 cswap(p, q, b);
10463 add(q, p);
10464 add(p, p);
10465 cswap(p, q, b);
10466 }
10467}
10468
10469function scalarbase(p, s) {
10470 var q = [gf(), gf(), gf(), gf()];
10471 set25519(q[0], X);
10472 set25519(q[1], Y);
10473 set25519(q[2], gf1);
10474 M(q[3], X, Y);
10475 scalarmult(p, q, s);
10476}
10477
10478function crypto_sign_keypair(pk, sk, seeded) {
10479 var d;
10480 var p = [gf(), gf(), gf(), gf()];
10481 var i;
10482
10483 if (!seeded) randombytes(sk, 32);
10484 d = nacl.hash(sk.subarray(0, 32));
10485 d[0] &= 248;
10486 d[31] &= 127;
10487 d[31] |= 64;
10488
10489 scalarbase(p, d);
10490 pack(pk, p);
10491
10492 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
10493 return 0;
10494}
10495
10496var 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]);
10497
10498function modL(r, x) {
10499 var carry, i, j, k;
10500 for (i = 63; i >= 32; --i) {
10501 carry = 0;
10502 for (j = i - 32, k = i - 12; j < k; ++j) {
10503 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
10504 carry = Math.floor((x[j] + 128) / 256);
10505 x[j] -= carry * 256;
10506 }
10507 x[j] += carry;
10508 x[i] = 0;
10509 }
10510 carry = 0;
10511 for (j = 0; j < 32; j++) {
10512 x[j] += carry - (x[31] >> 4) * L[j];
10513 carry = x[j] >> 8;
10514 x[j] &= 255;
10515 }
10516 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
10517 for (i = 0; i < 32; i++) {
10518 x[i+1] += x[i] >> 8;
10519 r[i] = x[i] & 255;
10520 }
10521}
10522
10523function reduce(r) {
10524 var x = new Float64Array(64), i;
10525 for (i = 0; i < 64; i++) x[i] = r[i];
10526 for (i = 0; i < 64; i++) r[i] = 0;
10527 modL(r, x);
10528}
10529
10530// Note: difference from C - smlen returned, not passed as argument.
10531function crypto_sign(sm, m, n, sk) {
10532 var d, h, r;
10533 var i, j, x = new Float64Array(64);
10534 var p = [gf(), gf(), gf(), gf()];
10535
10536 d = nacl.hash(sk.subarray(0, 32));
10537 d[0] &= 248;
10538 d[31] &= 127;
10539 d[31] |= 64;
10540
10541 var smlen = n + 64;
10542 for (i = 0; i < n; i++) sm[64 + i] = m[i];
10543 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
10544
10545 r = nacl.hash(sm.subarray(32, smlen));
10546 reduce(r);
10547 scalarbase(p, r);
10548 pack(sm, p);
10549
10550 for (i = 32; i < 64; i++) sm[i] = sk[i];
10551 h = nacl.hash(sm.subarray(0, smlen));
10552 reduce(h);
10553
10554 for (i = 0; i < 64; i++) x[i] = 0;
10555 for (i = 0; i < 32; i++) x[i] = r[i];
10556 for (i = 0; i < 32; i++) {
10557 for (j = 0; j < 32; j++) {
10558 x[i+j] += h[i] * d[j];
10559 }
10560 }
10561
10562 modL(sm.subarray(32), x);
10563 return smlen;
10564}
10565
10566function unpackneg(r, p) {
10567 var t = gf(), chk = gf(), num = gf(),
10568 den = gf(), den2 = gf(), den4 = gf(),
10569 den6 = gf();
10570
10571 set25519(r[2], gf1);
10572 unpack25519(r[1], p);
10573 S(num, r[1]);
10574 M(den, num, D);
10575 Z(num, num, r[2]);
10576 A(den, r[2], den);
10577
10578 S(den2, den);
10579 S(den4, den2);
10580 M(den6, den4, den2);
10581 M(t, den6, num);
10582 M(t, t, den);
10583
10584 pow2523(t, t);
10585 M(t, t, num);
10586 M(t, t, den);
10587 M(t, t, den);
10588 M(r[0], t, den);
10589
10590 S(chk, r[0]);
10591 M(chk, chk, den);
10592 if (neq25519(chk, num)) M(r[0], r[0], I);
10593
10594 S(chk, r[0]);
10595 M(chk, chk, den);
10596 if (neq25519(chk, num)) return -1;
10597
10598 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
10599
10600 M(r[3], r[0], r[1]);
10601 return 0;
10602}
10603
10604function crypto_sign_open(m, sm, n, pk) {
10605 var i;
10606 var t = new Uint8Array(32), h;
10607 var p = [gf(), gf(), gf(), gf()],
10608 q = [gf(), gf(), gf(), gf()];
10609
10610 if (n < 64) return -1;
10611
10612 if (unpackneg(q, pk)) return -1;
10613
10614 for (i = 0; i < n; i++) m[i] = sm[i];
10615 for (i = 0; i < 32; i++) m[i+32] = pk[i];
10616 h = nacl.hash(m.subarray(0, n));
10617 reduce(h);
10618 scalarmult(p, q, h);
10619
10620 scalarbase(q, sm.subarray(32));
10621 add(p, q);
10622 pack(t, p);
10623
10624 n -= 64;
10625 if (crypto_verify_32(sm, 0, t, 0)) {
10626 for (i = 0; i < n; i++) m[i] = 0;
10627 return -1;
10628 }
10629
10630 for (i = 0; i < n; i++) m[i] = sm[i + 64];
10631 return n;
10632}
10633
10634var crypto_scalarmult_BYTES = 32,
10635 crypto_scalarmult_SCALARBYTES = 32,
10636 crypto_box_PUBLICKEYBYTES = 32,
10637 crypto_box_SECRETKEYBYTES = 32,
10638 crypto_sign_BYTES = 64,
10639 crypto_sign_PUBLICKEYBYTES = 32,
10640 crypto_sign_SECRETKEYBYTES = 64,
10641 crypto_sign_SEEDBYTES = 32;
10642
10643function checkArrayTypes() {
10644 for (var i = 0; i < arguments.length; i++) {
10645 if (!(arguments[i] instanceof Uint8Array))
10646 throw new TypeError('unexpected type, use Uint8Array');
10647 }
10648}
10649
10650function cleanup(arr) {
10651 for (var i = 0; i < arr.length; i++) arr[i] = 0;
10652}
10653
10654nacl.scalarMult = function(n, p) {
10655 checkArrayTypes(n, p);
10656 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
10657 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
10658 var q = new Uint8Array(crypto_scalarmult_BYTES);
10659 crypto_scalarmult(q, n, p);
10660 return q;
10661};
10662
10663nacl.box = {};
10664
10665nacl.box.keyPair = function() {
10666 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
10667 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
10668 crypto_box_keypair(pk, sk);
10669 return {publicKey: pk, secretKey: sk};
10670};
10671
10672nacl.box.keyPair.fromSecretKey = function(secretKey) {
10673 checkArrayTypes(secretKey);
10674 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
10675 throw new Error('bad secret key size');
10676 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
10677 crypto_scalarmult_base(pk, secretKey);
10678 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
10679};
10680
10681nacl.sign = function(msg, secretKey) {
10682 checkArrayTypes(msg, secretKey);
10683 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
10684 throw new Error('bad secret key size');
10685 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
10686 crypto_sign(signedMsg, msg, msg.length, secretKey);
10687 return signedMsg;
10688};
10689
10690nacl.sign.detached = function(msg, secretKey) {
10691 var signedMsg = nacl.sign(msg, secretKey);
10692 var sig = new Uint8Array(crypto_sign_BYTES);
10693 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
10694 return sig;
10695};
10696
10697nacl.sign.detached.verify = function(msg, sig, publicKey) {
10698 checkArrayTypes(msg, sig, publicKey);
10699 if (sig.length !== crypto_sign_BYTES)
10700 throw new Error('bad signature size');
10701 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
10702 throw new Error('bad public key size');
10703 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
10704 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
10705 var i;
10706 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
10707 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
10708 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
10709};
10710
10711nacl.sign.keyPair = function() {
10712 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10713 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
10714 crypto_sign_keypair(pk, sk);
10715 return {publicKey: pk, secretKey: sk};
10716};
10717
10718nacl.sign.keyPair.fromSecretKey = function(secretKey) {
10719 checkArrayTypes(secretKey);
10720 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
10721 throw new Error('bad secret key size');
10722 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10723 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
10724 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
10725};
10726
10727nacl.sign.keyPair.fromSeed = function(seed) {
10728 checkArrayTypes(seed);
10729 if (seed.length !== crypto_sign_SEEDBYTES)
10730 throw new Error('bad seed size');
10731 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10732 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
10733 for (var i = 0; i < 32; i++) sk[i] = seed[i];
10734 crypto_sign_keypair(pk, sk, true);
10735 return {publicKey: pk, secretKey: sk};
10736};
10737
10738nacl.setPRNG = function(fn) {
10739 randombytes = fn;
10740};
10741
10742(function() {
10743 // Initialize PRNG if environment provides CSPRNG.
10744 // If not, methods calling randombytes will throw.
10745 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
10746 if (crypto && crypto.getRandomValues) {
10747 // Browsers.
10748 var QUOTA = 65536;
10749 nacl.setPRNG(function(x, n) {
10750 var i, v = new Uint8Array(n);
10751 for (i = 0; i < n; i += QUOTA) {
10752 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
10753 }
10754 for (i = 0; i < n; i++) x[i] = v[i];
10755 cleanup(v);
10756 });
10757 } else if (typeof commonjsRequire !== 'undefined') {
10758 // Node.js.
10759 crypto = void('crypto');
10760 if (crypto && crypto.randomBytes) {
10761 nacl.setPRNG(function(x, n) {
10762 var i, v = crypto.randomBytes(n);
10763 for (i = 0; i < n; i++) x[i] = v[i];
10764 cleanup(v);
10765 });
10766 }
10767 }
10768})();
10769
10770})(module.exports ? module.exports : (self.nacl = self.nacl || {}));
10771});
10772
10773// GPG4Browsers - An OpenPGP implementation in javascript
10774
10775const nodeCrypto$1 = util.getNodeCrypto();
10776
10777/**
10778 * Buffer for secure random numbers
10779 */
10780class RandomBuffer {
10781 constructor() {
10782 this.buffer = null;
10783 this.size = null;
10784 this.callback = null;
10785 }
10786
10787 /**
10788 * Initialize buffer
10789 * @param {Integer} size - size of buffer
10790 */
10791 init(size, callback) {
10792 this.buffer = new Uint8Array(size);
10793 this.size = 0;
10794 this.callback = callback;
10795 }
10796
10797 /**
10798 * Concat array of secure random numbers to buffer
10799 * @param {Uint8Array} buf
10800 */
10801 set(buf) {
10802 if (!this.buffer) {
10803 throw new Error('RandomBuffer is not initialized');
10804 }
10805 if (!(buf instanceof Uint8Array)) {
10806 throw new Error('Invalid type: buf not an Uint8Array');
10807 }
10808 const freeSpace = this.buffer.length - this.size;
10809 if (buf.length > freeSpace) {
10810 buf = buf.subarray(0, freeSpace);
10811 }
10812 // set buf with offset old size of buffer
10813 this.buffer.set(buf, this.size);
10814 this.size += buf.length;
10815 }
10816
10817 /**
10818 * Take numbers out of buffer and copy to array
10819 * @param {Uint8Array} buf - The destination array
10820 */
10821 async get(buf) {
10822 if (!this.buffer) {
10823 throw new Error('RandomBuffer is not initialized');
10824 }
10825 if (!(buf instanceof Uint8Array)) {
10826 throw new Error('Invalid type: buf not an Uint8Array');
10827 }
10828 if (this.size < buf.length) {
10829 if (!this.callback) {
10830 throw new Error('Random number buffer depleted');
10831 }
10832 // Wait for random bytes from main context, then try again
10833 await this.callback();
10834 return this.get(buf);
10835 }
10836 for (let i = 0; i < buf.length; i++) {
10837 buf[i] = this.buffer[--this.size];
10838 // clear buffer value
10839 this.buffer[this.size] = 0;
10840 }
10841 }
10842}
10843
10844/**
10845 * Retrieve secure random byte array of the specified length
10846 * @param {Integer} length - Length in bytes to generate
10847 * @returns {Promise<Uint8Array>} Random byte array.
10848 * @async
10849 */
10850async function getRandomBytes(length) {
10851 const buf = new Uint8Array(length);
10852 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
10853 crypto.getRandomValues(buf);
10854 } else if (nodeCrypto$1) {
10855 const bytes = nodeCrypto$1.randomBytes(buf.length);
10856 buf.set(bytes);
10857 } else if (randomBuffer.buffer) {
10858 await randomBuffer.get(buf);
10859 } else {
10860 throw new Error('No secure random number generator available.');
10861 }
10862 return buf;
10863}
10864
10865/**
10866 * Create a secure random BigInteger that is greater than or equal to min and less than max.
10867 * @param {module:BigInteger} min - Lower bound, included
10868 * @param {module:BigInteger} max - Upper bound, excluded
10869 * @returns {Promise<module:BigInteger>} Random BigInteger.
10870 * @async
10871 */
10872async function getRandomBigInteger(min, max) {
10873 const BigInteger = await util.getBigInteger();
10874
10875 if (max.lt(min)) {
10876 throw new Error('Illegal parameter value: max <= min');
10877 }
10878
10879 const modulus = max.sub(min);
10880 const bytes = modulus.byteLength();
10881
10882 // Using a while loop is necessary to avoid bias introduced by the mod operation.
10883 // However, we request 64 extra random bits so that the bias is negligible.
10884 // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
10885 const r = new BigInteger(await getRandomBytes(bytes + 8));
10886 return r.mod(modulus).add(min);
10887}
10888
10889const randomBuffer = new RandomBuffer();
10890
10891var random = /*#__PURE__*/Object.freeze({
10892 __proto__: null,
10893 getRandomBytes: getRandomBytes,
10894 getRandomBigInteger: getRandomBigInteger,
10895 randomBuffer: randomBuffer
10896});
10897
10898// OpenPGP.js - An OpenPGP implementation in javascript
10899
10900/**
10901 * Generate a probably prime random number
10902 * @param {Integer} bits - Bit length of the prime
10903 * @param {BigInteger} e - Optional RSA exponent to check against the prime
10904 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
10905 * @returns BigInteger
10906 * @async
10907 */
10908async function randomProbablePrime(bits, e, k) {
10909 const BigInteger = await util.getBigInteger();
10910 const one = new BigInteger(1);
10911 const min = one.leftShift(new BigInteger(bits - 1));
10912 const thirty = new BigInteger(30);
10913 /*
10914 * We can avoid any multiples of 3 and 5 by looking at n mod 30
10915 * 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
10916 * the next possible prime is mod 30:
10917 * 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
10918 */
10919 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];
10920
10921 const n = await getRandomBigInteger(min, min.leftShift(one));
10922 let i = n.mod(thirty).toNumber();
10923
10924 do {
10925 n.iadd(new BigInteger(adds[i]));
10926 i = (i + adds[i]) % adds.length;
10927 // If reached the maximum, go back to the minimum.
10928 if (n.bitLength() > bits) {
10929 n.imod(min.leftShift(one)).iadd(min);
10930 i = n.mod(thirty).toNumber();
10931 }
10932 } while (!await isProbablePrime(n, e, k));
10933 return n;
10934}
10935
10936/**
10937 * Probabilistic primality testing
10938 * @param {BigInteger} n - Number to test
10939 * @param {BigInteger} e - Optional RSA exponent to check against the prime
10940 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
10941 * @returns {boolean}
10942 * @async
10943 */
10944async function isProbablePrime(n, e, k) {
10945 if (e && !n.dec().gcd(e).isOne()) {
10946 return false;
10947 }
10948 if (!await divisionTest(n)) {
10949 return false;
10950 }
10951 if (!await fermat(n)) {
10952 return false;
10953 }
10954 if (!await millerRabin(n, k)) {
10955 return false;
10956 }
10957 // TODO implement the Lucas test
10958 // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
10959 return true;
10960}
10961
10962/**
10963 * Tests whether n is probably prime or not using Fermat's test with b = 2.
10964 * Fails if b^(n-1) mod n != 1.
10965 * @param {BigInteger} n - Number to test
10966 * @param {BigInteger} b - Optional Fermat test base
10967 * @returns {boolean}
10968 */
10969async function fermat(n, b) {
10970 const BigInteger = await util.getBigInteger();
10971 b = b || new BigInteger(2);
10972 return b.modExp(n.dec(), n).isOne();
10973}
10974
10975async function divisionTest(n) {
10976 const BigInteger = await util.getBigInteger();
10977 return smallPrimes.every(m => {
10978 return n.mod(new BigInteger(m)) !== 0;
10979 });
10980}
10981
10982// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
10983const smallPrimes = [
10984 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
10985 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
10986 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
10987 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
10988 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
10989 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
10990 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
10991 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
10992 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
10993 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
10994 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
10995 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
10996 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
10997 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
10998 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
10999 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
11000 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
11001 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
11002 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
11003 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
11004 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
11005 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
11006 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
11007 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
11008 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
11009 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
11010 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
11011 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
11012 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
11013 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
11014 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
11015 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
11016 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
11017 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
11018 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
11019 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
11020 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
11021 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
11022 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
11023 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
11024 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
11025 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
11026 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
11027 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
11028 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
11029 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
11030 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
11031 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
11032 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
11033 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
11034 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
11035 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
11036 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
11037 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
11038 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
11039 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
11040 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
11041 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
11042 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
11043 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
11044 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
11045 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
11046 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
11047 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
11048 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
11049 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
11050 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
11051 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
11052 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
11053 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
11054 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
11055 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
11056 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
11057 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
11058 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
11059 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
11060 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
11061 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
11062 4957, 4967, 4969, 4973, 4987, 4993, 4999
11063];
11064
11065
11066// Miller-Rabin - Miller Rabin algorithm for primality test
11067// Copyright Fedor Indutny, 2014.
11068//
11069// This software is licensed under the MIT License.
11070//
11071// Permission is hereby granted, free of charge, to any person obtaining a
11072// copy of this software and associated documentation files (the
11073// "Software"), to deal in the Software without restriction, including
11074// without limitation the rights to use, copy, modify, merge, publish,
11075// distribute, sublicense, and/or sell copies of the Software, and to permit
11076// persons to whom the Software is furnished to do so, subject to the
11077// following conditions:
11078//
11079// The above copyright notice and this permission notice shall be included
11080// in all copies or substantial portions of the Software.
11081//
11082// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11083// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11084// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11085// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11086// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11087// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11088// USE OR OTHER DEALINGS IN THE SOFTWARE.
11089
11090// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
11091
11092// Sample syntax for Fixed-Base Miller-Rabin:
11093// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
11094
11095/**
11096 * Tests whether n is probably prime or not using the Miller-Rabin test.
11097 * See HAC Remark 4.28.
11098 * @param {BigInteger} n - Number to test
11099 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
11100 * @param {Function} rand - Optional function to generate potential witnesses
11101 * @returns {boolean}
11102 * @async
11103 */
11104async function millerRabin(n, k, rand) {
11105 const BigInteger = await util.getBigInteger();
11106 const len = n.bitLength();
11107
11108 if (!k) {
11109 k = Math.max(1, (len / 48) | 0);
11110 }
11111
11112 const n1 = n.dec(); // n - 1
11113
11114 // Find d and s, (n - 1) = (2 ^ s) * d;
11115 let s = 0;
11116 while (!n1.getBit(s)) { s++; }
11117 const d = n.rightShift(new BigInteger(s));
11118
11119 for (; k > 0; k--) {
11120 const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);
11121
11122 let x = a.modExp(d, n);
11123 if (x.isOne() || x.equal(n1)) {
11124 continue;
11125 }
11126
11127 let i;
11128 for (i = 1; i < s; i++) {
11129 x = x.mul(x).mod(n);
11130
11131 if (x.isOne()) {
11132 return false;
11133 }
11134 if (x.equal(n1)) {
11135 break;
11136 }
11137 }
11138
11139 if (i === s) {
11140 return false;
11141 }
11142 }
11143
11144 return true;
11145}
11146
11147// GPG4Browsers - An OpenPGP implementation in javascript
11148
11149/**
11150 * ASN1 object identifiers for hashes
11151 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
11152 */
11153const hash_headers = [];
11154hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
11155 0x10];
11156hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
11157hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
11158hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
11159 0x04, 0x20];
11160hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
11161 0x04, 0x30];
11162hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
11163 0x00, 0x04, 0x40];
11164hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
11165 0x00, 0x04, 0x1C];
11166
11167/**
11168 * Create padding with secure random data
11169 * @private
11170 * @param {Integer} length - Length of the padding in bytes
11171 * @returns {Promise<Uint8Array>} Random padding.
11172 * @async
11173 */
11174async function getPKCS1Padding(length) {
11175 const result = new Uint8Array(length);
11176 let count = 0;
11177 while (count < length) {
11178 const randomBytes = await getRandomBytes(length - count);
11179 for (let i = 0; i < randomBytes.length; i++) {
11180 if (randomBytes[i] !== 0) {
11181 result[count++] = randomBytes[i];
11182 }
11183 }
11184 }
11185 return result;
11186}
11187
11188/**
11189 * Create a EME-PKCS1-v1_5 padded message
11190 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
11191 * @param {Uint8Array} message - Message to be encoded
11192 * @param {Integer} keyLength - The length in octets of the key modulus
11193 * @returns {Promise<Uint8Array>} EME-PKCS1 padded message.
11194 * @async
11195 */
11196async function emeEncode(message, keyLength) {
11197 const mLength = message.length;
11198 // length checking
11199 if (mLength > keyLength - 11) {
11200 throw new Error('Message too long');
11201 }
11202 // Generate an octet string PS of length k - mLen - 3 consisting of
11203 // pseudo-randomly generated nonzero octets
11204 const PS = await getPKCS1Padding(keyLength - mLength - 3);
11205 // Concatenate PS, the message M, and other padding to form an
11206 // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
11207 const encoded = new Uint8Array(keyLength);
11208 // 0x00 byte
11209 encoded[1] = 2;
11210 encoded.set(PS, 2);
11211 // 0x00 bytes
11212 encoded.set(message, keyLength - mLength);
11213 return encoded;
11214}
11215
11216/**
11217 * Decode a EME-PKCS1-v1_5 padded message
11218 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
11219 * @param {Uint8Array} encoded - Encoded message bytes
11220 * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)
11221 * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)
11222 * @throws {Error} on decoding failure, unless `randomPayload` is provided
11223 */
11224function emeDecode(encoded, randomPayload) {
11225 // encoded format: 0x00 0x02 <PS> 0x00 <payload>
11226 let offset = 2;
11227 let separatorNotFound = 1;
11228 for (let j = offset; j < encoded.length; j++) {
11229 separatorNotFound &= encoded[j] !== 0;
11230 offset += separatorNotFound;
11231 }
11232
11233 const psLen = offset - 2;
11234 const payload = encoded.subarray(offset + 1); // discard the 0x00 separator
11235 const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;
11236
11237 if (randomPayload) {
11238 return util.selectUint8Array(isValidPadding, payload, randomPayload);
11239 }
11240
11241 if (isValidPadding) {
11242 return payload;
11243 }
11244
11245 throw new Error('Decryption error');
11246}
11247
11248/**
11249 * Create a EMSA-PKCS1-v1_5 padded message
11250 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
11251 * @param {Integer} algo - Hash algorithm type used
11252 * @param {Uint8Array} hashed - Message to be encoded
11253 * @param {Integer} emLen - Intended length in octets of the encoded message
11254 * @returns {Uint8Array} Encoded message.
11255 */
11256async function emsaEncode(algo, hashed, emLen) {
11257 let i;
11258 if (hashed.length !== hash.getHashByteLength(algo)) {
11259 throw new Error('Invalid hash length');
11260 }
11261 // produce an ASN.1 DER value for the hash function used.
11262 // Let T be the full hash prefix
11263 const hashPrefix = new Uint8Array(hash_headers[algo].length);
11264 for (i = 0; i < hash_headers[algo].length; i++) {
11265 hashPrefix[i] = hash_headers[algo][i];
11266 }
11267 // and let tLen be the length in octets prefix and hashed data
11268 const tLen = hashPrefix.length + hashed.length;
11269 if (emLen < tLen + 11) {
11270 throw new Error('Intended encoded message length too short');
11271 }
11272 // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
11273 // The length of PS will be at least 8 octets
11274 const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
11275
11276 // Concatenate PS, the hash prefix, hashed data, and other padding to form the
11277 // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
11278 const EM = new Uint8Array(emLen);
11279 EM[1] = 0x01;
11280 EM.set(PS, 2);
11281 EM.set(hashPrefix, emLen - tLen);
11282 EM.set(hashed, emLen - hashed.length);
11283 return EM;
11284}
11285
11286var pkcs1 = /*#__PURE__*/Object.freeze({
11287 __proto__: null,
11288 emeEncode: emeEncode,
11289 emeDecode: emeDecode,
11290 emsaEncode: emsaEncode
11291});
11292
11293// GPG4Browsers - An OpenPGP implementation in javascript
11294
11295const webCrypto$1 = util.getWebCrypto();
11296const nodeCrypto$2 = util.getNodeCrypto();
11297const asn1 = nodeCrypto$2 ? void('asn1.js') : undefined;
11298
11299/* eslint-disable no-invalid-this */
11300const RSAPrivateKey = nodeCrypto$2 ? asn1.define('RSAPrivateKey', function () {
11301 this.seq().obj( // used for native NodeJS crypto
11302 this.key('version').int(), // 0
11303 this.key('modulus').int(), // n
11304 this.key('publicExponent').int(), // e
11305 this.key('privateExponent').int(), // d
11306 this.key('prime1').int(), // p
11307 this.key('prime2').int(), // q
11308 this.key('exponent1').int(), // dp
11309 this.key('exponent2').int(), // dq
11310 this.key('coefficient').int() // u
11311 );
11312}) : undefined;
11313
11314const RSAPublicKey = nodeCrypto$2 ? asn1.define('RSAPubliceKey', function () {
11315 this.seq().obj( // used for native NodeJS crypto
11316 this.key('modulus').int(), // n
11317 this.key('publicExponent').int(), // e
11318 );
11319}) : undefined;
11320/* eslint-enable no-invalid-this */
11321
11322/** Create signature
11323 * @param {module:enums.hash} hashAlgo - Hash algorithm
11324 * @param {Uint8Array} data - Message
11325 * @param {Uint8Array} n - RSA public modulus
11326 * @param {Uint8Array} e - RSA public exponent
11327 * @param {Uint8Array} d - RSA private exponent
11328 * @param {Uint8Array} p - RSA private prime p
11329 * @param {Uint8Array} q - RSA private prime q
11330 * @param {Uint8Array} u - RSA private coefficient
11331 * @param {Uint8Array} hashed - Hashed message
11332 * @returns {Promise<Uint8Array>} RSA Signature.
11333 * @async
11334 */
11335async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {
11336 if (data && !util.isStream(data)) {
11337 if (util.getWebCrypto()) {
11338 try {
11339 return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);
11340 } catch (err) {
11341 util.printDebugError(err);
11342 }
11343 } else if (util.getNodeCrypto()) {
11344 return nodeSign(hashAlgo, data, n, e, d, p, q, u);
11345 }
11346 }
11347 return bnSign(hashAlgo, n, d, hashed);
11348}
11349
11350/**
11351 * Verify signature
11352 * @param {module:enums.hash} hashAlgo - Hash algorithm
11353 * @param {Uint8Array} data - Message
11354 * @param {Uint8Array} s - Signature
11355 * @param {Uint8Array} n - RSA public modulus
11356 * @param {Uint8Array} e - RSA public exponent
11357 * @param {Uint8Array} hashed - Hashed message
11358 * @returns {Boolean}
11359 * @async
11360 */
11361async function verify(hashAlgo, data, s, n, e, hashed) {
11362 if (data && !util.isStream(data)) {
11363 if (util.getWebCrypto()) {
11364 try {
11365 return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);
11366 } catch (err) {
11367 util.printDebugError(err);
11368 }
11369 } else if (util.getNodeCrypto()) {
11370 return nodeVerify(hashAlgo, data, s, n, e);
11371 }
11372 }
11373 return bnVerify(hashAlgo, s, n, e, hashed);
11374}
11375
11376/**
11377 * Encrypt message
11378 * @param {Uint8Array} data - Message
11379 * @param {Uint8Array} n - RSA public modulus
11380 * @param {Uint8Array} e - RSA public exponent
11381 * @returns {Promise<Uint8Array>} RSA Ciphertext.
11382 * @async
11383 */
11384async function encrypt(data, n, e) {
11385 if (util.getNodeCrypto()) {
11386 return nodeEncrypt(data, n, e);
11387 }
11388 return bnEncrypt(data, n, e);
11389}
11390
11391/**
11392 * Decrypt RSA message
11393 * @param {Uint8Array} m - Message
11394 * @param {Uint8Array} n - RSA public modulus
11395 * @param {Uint8Array} e - RSA public exponent
11396 * @param {Uint8Array} d - RSA private exponent
11397 * @param {Uint8Array} p - RSA private prime p
11398 * @param {Uint8Array} q - RSA private prime q
11399 * @param {Uint8Array} u - RSA private coefficient
11400 * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing
11401 * (needed for constant-time processing)
11402 * @returns {Promise<String>} RSA Plaintext.
11403 * @throws {Error} on decryption error, unless `randomPayload` is given
11404 * @async
11405 */
11406async function decrypt(data, n, e, d, p, q, u, randomPayload) {
11407 if (util.getNodeCrypto()) {
11408 return nodeDecrypt(data, n, e, d, p, q, u, randomPayload);
11409 }
11410 return bnDecrypt(data, n, e, d, p, q, u, randomPayload);
11411}
11412
11413/**
11414 * Generate a new random private key B bits long with public exponent E.
11415 *
11416 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
11417 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
11418 * @see module:crypto/public_key/prime
11419 * @param {Integer} bits - RSA bit length
11420 * @param {Integer} e - RSA public exponent
11421 * @returns {{n, e, d,
11422 * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,
11423 * RSA private prime p, RSA private prime q, u = p ** -1 mod q
11424 * @async
11425 */
11426async function generate(bits, e) {
11427 const BigInteger = await util.getBigInteger();
11428
11429 e = new BigInteger(e);
11430
11431 // Native RSA keygen using Web Crypto
11432 if (util.getWebCrypto()) {
11433 const keyGenOpt = {
11434 name: 'RSASSA-PKCS1-v1_5',
11435 modulusLength: bits, // the specified keysize in bits
11436 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
11437 hash: {
11438 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
11439 }
11440 };
11441 const keyPair = await webCrypto$1.generateKey(keyGenOpt, true, ['sign', 'verify']);
11442
11443 // export the generated keys as JsonWebKey (JWK)
11444 // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
11445 const jwk = await webCrypto$1.exportKey('jwk', keyPair.privateKey);
11446 // map JWK parameters to corresponding OpenPGP names
11447 return {
11448 n: b64ToUint8Array(jwk.n),
11449 e: e.toUint8Array(),
11450 d: b64ToUint8Array(jwk.d),
11451 // switch p and q
11452 p: b64ToUint8Array(jwk.q),
11453 q: b64ToUint8Array(jwk.p),
11454 // Since p and q are switched in places, u is the inverse of jwk.q
11455 u: b64ToUint8Array(jwk.qi)
11456 };
11457 } else if (util.getNodeCrypto() && nodeCrypto$2.generateKeyPair && RSAPrivateKey) {
11458 const opts = {
11459 modulusLength: bits,
11460 publicExponent: e.toNumber(),
11461 publicKeyEncoding: { type: 'pkcs1', format: 'der' },
11462 privateKeyEncoding: { type: 'pkcs1', format: 'der' }
11463 };
11464 const prv = await new Promise((resolve, reject) => nodeCrypto$2.generateKeyPair('rsa', opts, (err, _, der) => {
11465 if (err) {
11466 reject(err);
11467 } else {
11468 resolve(RSAPrivateKey.decode(der, 'der'));
11469 }
11470 }));
11471 /**
11472 * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.
11473 * @link https://tools.ietf.org/html/rfc3447#section-3.2
11474 * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
11475 */
11476 return {
11477 n: prv.modulus.toArrayLike(Uint8Array),
11478 e: prv.publicExponent.toArrayLike(Uint8Array),
11479 d: prv.privateExponent.toArrayLike(Uint8Array),
11480 // switch p and q
11481 p: prv.prime2.toArrayLike(Uint8Array),
11482 q: prv.prime1.toArrayLike(Uint8Array),
11483 // Since p and q are switched in places, we can keep u as defined by DER
11484 u: prv.coefficient.toArrayLike(Uint8Array)
11485 };
11486 }
11487
11488 // RSA keygen fallback using 40 iterations of the Miller-Rabin test
11489 // See https://stackoverflow.com/a/6330138 for justification
11490 // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
11491 let p;
11492 let q;
11493 let n;
11494 do {
11495 q = await randomProbablePrime(bits - (bits >> 1), e, 40);
11496 p = await randomProbablePrime(bits >> 1, e, 40);
11497 n = p.mul(q);
11498 } while (n.bitLength() !== bits);
11499
11500 const phi = p.dec().imul(q.dec());
11501
11502 if (q.lt(p)) {
11503 [p, q] = [q, p];
11504 }
11505
11506 return {
11507 n: n.toUint8Array(),
11508 e: e.toUint8Array(),
11509 d: e.modInv(phi).toUint8Array(),
11510 p: p.toUint8Array(),
11511 q: q.toUint8Array(),
11512 // dp: d.mod(p.subn(1)),
11513 // dq: d.mod(q.subn(1)),
11514 u: p.modInv(q).toUint8Array()
11515 };
11516}
11517
11518/**
11519 * Validate RSA parameters
11520 * @param {Uint8Array} n - RSA public modulus
11521 * @param {Uint8Array} e - RSA public exponent
11522 * @param {Uint8Array} d - RSA private exponent
11523 * @param {Uint8Array} p - RSA private prime p
11524 * @param {Uint8Array} q - RSA private prime q
11525 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
11526 * @returns {Promise<Boolean>} Whether params are valid.
11527 * @async
11528 */
11529async function validateParams(n, e, d, p, q, u) {
11530 const BigInteger = await util.getBigInteger();
11531 n = new BigInteger(n);
11532 p = new BigInteger(p);
11533 q = new BigInteger(q);
11534
11535 // expect pq = n
11536 if (!p.mul(q).equal(n)) {
11537 return false;
11538 }
11539
11540 const two = new BigInteger(2);
11541 // expect p*u = 1 mod q
11542 u = new BigInteger(u);
11543 if (!p.mul(u).mod(q).isOne()) {
11544 return false;
11545 }
11546
11547 e = new BigInteger(e);
11548 d = new BigInteger(d);
11549 /**
11550 * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
11551 * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
11552 * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
11553 *
11554 * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
11555 */
11556 const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));
11557 const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q
11558 const rde = r.mul(d).mul(e);
11559
11560 const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);
11561 if (!areInverses) {
11562 return false;
11563 }
11564
11565 return true;
11566}
11567
11568async function bnSign(hashAlgo, n, d, hashed) {
11569 const BigInteger = await util.getBigInteger();
11570 n = new BigInteger(n);
11571 const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));
11572 d = new BigInteger(d);
11573 if (m.gte(n)) {
11574 throw new Error('Message size cannot exceed modulus size');
11575 }
11576 return m.modExp(d, n).toUint8Array('be', n.byteLength());
11577}
11578
11579async function webSign(hashName, data, n, e, d, p, q, u) {
11580 /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
11581 * We swap them in privateToJWK, so it usually works out, but nevertheless,
11582 * not all OpenPGP keys are compatible with this requirement.
11583 * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
11584 * does if the underlying Web Crypto does so (though the tested implementations
11585 * don't do so).
11586 */
11587 const jwk = await privateToJWK(n, e, d, p, q, u);
11588 const algo = {
11589 name: 'RSASSA-PKCS1-v1_5',
11590 hash: { name: hashName }
11591 };
11592 const key = await webCrypto$1.importKey('jwk', jwk, algo, false, ['sign']);
11593 return new Uint8Array(await webCrypto$1.sign('RSASSA-PKCS1-v1_5', key, data));
11594}
11595
11596async function nodeSign(hashAlgo, data, n, e, d, p, q, u) {
11597 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11598 const pBNum = new BN(p);
11599 const qBNum = new BN(q);
11600 const dBNum = new BN(d);
11601 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
11602 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
11603 const sign = nodeCrypto$2.createSign(enums.read(enums.hash, hashAlgo));
11604 sign.write(data);
11605 sign.end();
11606 const keyObject = {
11607 version: 0,
11608 modulus: new BN(n),
11609 publicExponent: new BN(e),
11610 privateExponent: new BN(d),
11611 // switch p and q
11612 prime1: new BN(q),
11613 prime2: new BN(p),
11614 // switch dp and dq
11615 exponent1: dq,
11616 exponent2: dp,
11617 coefficient: new BN(u)
11618 };
11619 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
11620 const der = RSAPrivateKey.encode(keyObject, 'der');
11621 return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
11622 }
11623 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
11624 label: 'RSA PRIVATE KEY'
11625 });
11626 return new Uint8Array(sign.sign(pem));
11627}
11628
11629async function bnVerify(hashAlgo, s, n, e, hashed) {
11630 const BigInteger = await util.getBigInteger();
11631 n = new BigInteger(n);
11632 s = new BigInteger(s);
11633 e = new BigInteger(e);
11634 if (s.gte(n)) {
11635 throw new Error('Signature size cannot exceed modulus size');
11636 }
11637 const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());
11638 const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());
11639 return util.equalsUint8Array(EM1, EM2);
11640}
11641
11642async function webVerify(hashName, data, s, n, e) {
11643 const jwk = publicToJWK(n, e);
11644 const key = await webCrypto$1.importKey('jwk', jwk, {
11645 name: 'RSASSA-PKCS1-v1_5',
11646 hash: { name: hashName }
11647 }, false, ['verify']);
11648 return webCrypto$1.verify('RSASSA-PKCS1-v1_5', key, s, data);
11649}
11650
11651async function nodeVerify(hashAlgo, data, s, n, e) {
11652 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11653
11654 const verify = nodeCrypto$2.createVerify(enums.read(enums.hash, hashAlgo));
11655 verify.write(data);
11656 verify.end();
11657 const keyObject = {
11658 modulus: new BN(n),
11659 publicExponent: new BN(e)
11660 };
11661 let key;
11662 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
11663 const der = RSAPublicKey.encode(keyObject, 'der');
11664 key = { key: der, format: 'der', type: 'pkcs1' };
11665 } else {
11666 key = RSAPublicKey.encode(keyObject, 'pem', {
11667 label: 'RSA PUBLIC KEY'
11668 });
11669 }
11670 try {
11671 return await verify.verify(key, s);
11672 } catch (err) {
11673 return false;
11674 }
11675}
11676
11677async function nodeEncrypt(data, n, e) {
11678 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11679
11680 const keyObject = {
11681 modulus: new BN(n),
11682 publicExponent: new BN(e)
11683 };
11684 let key;
11685 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') {
11686 const der = RSAPublicKey.encode(keyObject, 'der');
11687 key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11688 } else {
11689 const pem = RSAPublicKey.encode(keyObject, 'pem', {
11690 label: 'RSA PUBLIC KEY'
11691 });
11692 key = { key: pem, padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11693 }
11694 return new Uint8Array(nodeCrypto$2.publicEncrypt(key, data));
11695}
11696
11697async function bnEncrypt(data, n, e) {
11698 const BigInteger = await util.getBigInteger();
11699 n = new BigInteger(n);
11700 data = new BigInteger(await emeEncode(data, n.byteLength()));
11701 e = new BigInteger(e);
11702 if (data.gte(n)) {
11703 throw new Error('Message size cannot exceed modulus size');
11704 }
11705 return data.modExp(e, n).toUint8Array('be', n.byteLength());
11706}
11707
11708async function nodeDecrypt(data, n, e, d, p, q, u, randomPayload) {
11709 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11710
11711 const pBNum = new BN(p);
11712 const qBNum = new BN(q);
11713 const dBNum = new BN(d);
11714 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
11715 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
11716 const keyObject = {
11717 version: 0,
11718 modulus: new BN(n),
11719 publicExponent: new BN(e),
11720 privateExponent: new BN(d),
11721 // switch p and q
11722 prime1: new BN(q),
11723 prime2: new BN(p),
11724 // switch dp and dq
11725 exponent1: dq,
11726 exponent2: dp,
11727 coefficient: new BN(u)
11728 };
11729 let key;
11730 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') {
11731 const der = RSAPrivateKey.encode(keyObject, 'der');
11732 key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11733 } else {
11734 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
11735 label: 'RSA PRIVATE KEY'
11736 });
11737 key = { key: pem, padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11738 }
11739 try {
11740 return new Uint8Array(nodeCrypto$2.privateDecrypt(key, data));
11741 } catch (err) {
11742 if (randomPayload) {
11743 return randomPayload;
11744 }
11745 throw new Error('Decryption error');
11746 }
11747}
11748
11749async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {
11750 const BigInteger = await util.getBigInteger();
11751 data = new BigInteger(data);
11752 n = new BigInteger(n);
11753 e = new BigInteger(e);
11754 d = new BigInteger(d);
11755 p = new BigInteger(p);
11756 q = new BigInteger(q);
11757 u = new BigInteger(u);
11758 if (data.gte(n)) {
11759 throw new Error('Data too large.');
11760 }
11761 const dq = d.mod(q.dec()); // d mod (q-1)
11762 const dp = d.mod(p.dec()); // d mod (p-1)
11763
11764 const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);
11765 const blinder = unblinder.modInv(n).modExp(e, n);
11766 data = data.mul(blinder).mod(n);
11767
11768
11769 const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p
11770 const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q
11771 const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)
11772
11773 let result = h.mul(p).add(mp); // result < n due to relations above
11774
11775 result = result.mul(unblinder).mod(n);
11776
11777
11778 return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);
11779}
11780
11781/** Convert Openpgp private key params to jwk key according to
11782 * @link https://tools.ietf.org/html/rfc7517
11783 * @param {String} hashAlgo
11784 * @param {Uint8Array} n
11785 * @param {Uint8Array} e
11786 * @param {Uint8Array} d
11787 * @param {Uint8Array} p
11788 * @param {Uint8Array} q
11789 * @param {Uint8Array} u
11790 */
11791async function privateToJWK(n, e, d, p, q, u) {
11792 const BigInteger = await util.getBigInteger();
11793 const pNum = new BigInteger(p);
11794 const qNum = new BigInteger(q);
11795 const dNum = new BigInteger(d);
11796
11797 let dq = dNum.mod(qNum.dec()); // d mod (q-1)
11798 let dp = dNum.mod(pNum.dec()); // d mod (p-1)
11799 dp = dp.toUint8Array();
11800 dq = dq.toUint8Array();
11801 return {
11802 kty: 'RSA',
11803 n: uint8ArrayToB64(n, true),
11804 e: uint8ArrayToB64(e, true),
11805 d: uint8ArrayToB64(d, true),
11806 // switch p and q
11807 p: uint8ArrayToB64(q, true),
11808 q: uint8ArrayToB64(p, true),
11809 // switch dp and dq
11810 dp: uint8ArrayToB64(dq, true),
11811 dq: uint8ArrayToB64(dp, true),
11812 qi: uint8ArrayToB64(u, true),
11813 ext: true
11814 };
11815}
11816
11817/** Convert Openpgp key public params to jwk key according to
11818 * @link https://tools.ietf.org/html/rfc7517
11819 * @param {String} hashAlgo
11820 * @param {Uint8Array} n
11821 * @param {Uint8Array} e
11822 */
11823function publicToJWK(n, e) {
11824 return {
11825 kty: 'RSA',
11826 n: uint8ArrayToB64(n, true),
11827 e: uint8ArrayToB64(e, true),
11828 ext: true
11829 };
11830}
11831
11832var rsa = /*#__PURE__*/Object.freeze({
11833 __proto__: null,
11834 sign: sign,
11835 verify: verify,
11836 encrypt: encrypt,
11837 decrypt: decrypt,
11838 generate: generate,
11839 validateParams: validateParams
11840});
11841
11842// GPG4Browsers - An OpenPGP implementation in javascript
11843
11844/**
11845 * ElGamal Encryption function
11846 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
11847 * @param {Uint8Array} data - To be padded and encrypted
11848 * @param {Uint8Array} p
11849 * @param {Uint8Array} g
11850 * @param {Uint8Array} y
11851 * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}
11852 * @async
11853 */
11854async function encrypt$1(data, p, g, y) {
11855 const BigInteger = await util.getBigInteger();
11856 p = new BigInteger(p);
11857 g = new BigInteger(g);
11858 y = new BigInteger(y);
11859
11860 const padded = await emeEncode(data, p.byteLength());
11861 const m = new BigInteger(padded);
11862
11863 // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
11864 // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
11865 const k = await getRandomBigInteger(new BigInteger(1), p.dec());
11866 return {
11867 c1: g.modExp(k, p).toUint8Array(),
11868 c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()
11869 };
11870}
11871
11872/**
11873 * ElGamal Encryption function
11874 * @param {Uint8Array} c1
11875 * @param {Uint8Array} c2
11876 * @param {Uint8Array} p
11877 * @param {Uint8Array} x
11878 * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing
11879 * (needed for constant-time processing)
11880 * @returns {Promise<Uint8Array>} Unpadded message.
11881 * @throws {Error} on decryption error, unless `randomPayload` is given
11882 * @async
11883 */
11884async function decrypt$1(c1, c2, p, x, randomPayload) {
11885 const BigInteger = await util.getBigInteger();
11886 c1 = new BigInteger(c1);
11887 c2 = new BigInteger(c2);
11888 p = new BigInteger(p);
11889 x = new BigInteger(x);
11890
11891 const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);
11892 return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);
11893}
11894
11895/**
11896 * Validate ElGamal parameters
11897 * @param {Uint8Array} p - ElGamal prime
11898 * @param {Uint8Array} g - ElGamal group generator
11899 * @param {Uint8Array} y - ElGamal public key
11900 * @param {Uint8Array} x - ElGamal private exponent
11901 * @returns {Promise<Boolean>} Whether params are valid.
11902 * @async
11903 */
11904async function validateParams$1(p, g, y, x) {
11905 const BigInteger = await util.getBigInteger();
11906 p = new BigInteger(p);
11907 g = new BigInteger(g);
11908 y = new BigInteger(y);
11909
11910 const one = new BigInteger(1);
11911 // Check that 1 < g < p
11912 if (g.lte(one) || g.gte(p)) {
11913 return false;
11914 }
11915
11916 // Expect p-1 to be large
11917 const pSize = new BigInteger(p.bitLength());
11918 const n1023 = new BigInteger(1023);
11919 if (pSize.lt(n1023)) {
11920 return false;
11921 }
11922
11923 /**
11924 * g should have order p-1
11925 * Check that g ** (p-1) = 1 mod p
11926 */
11927 if (!g.modExp(p.dec(), p).isOne()) {
11928 return false;
11929 }
11930
11931 /**
11932 * Since p-1 is not prime, g might have a smaller order that divides p-1
11933 * We want to make sure that the order is large enough to hinder a small subgroup attack
11934 *
11935 * We just check g**i != 1 for all i up to a threshold
11936 */
11937 let res = g;
11938 const i = new BigInteger(1);
11939 const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold
11940 while (i.lt(threshold)) {
11941 res = res.mul(g).imod(p);
11942 if (res.isOne()) {
11943 return false;
11944 }
11945 i.iinc();
11946 }
11947
11948 /**
11949 * Re-derive public key y' = g ** x mod p
11950 * Expect y == y'
11951 *
11952 * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
11953 */
11954 x = new BigInteger(x);
11955 const two = new BigInteger(2);
11956 const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1
11957 const rqx = p.dec().imul(r).iadd(x);
11958 if (!y.equal(g.modExp(rqx, p))) {
11959 return false;
11960 }
11961
11962 return true;
11963}
11964
11965var elgamal = /*#__PURE__*/Object.freeze({
11966 __proto__: null,
11967 encrypt: encrypt$1,
11968 decrypt: decrypt$1,
11969 validateParams: validateParams$1
11970});
11971
11972// OpenPGP.js - An OpenPGP implementation in javascript
11973
11974class OID {
11975 constructor(oid) {
11976 if (oid instanceof OID) {
11977 this.oid = oid.oid;
11978 } else if (util.isArray(oid) ||
11979 util.isUint8Array(oid)) {
11980 oid = new Uint8Array(oid);
11981 if (oid[0] === 0x06) { // DER encoded oid byte array
11982 if (oid[1] !== oid.length - 2) {
11983 throw new Error('Length mismatch in DER encoded oid');
11984 }
11985 oid = oid.subarray(2);
11986 }
11987 this.oid = oid;
11988 } else {
11989 this.oid = '';
11990 }
11991 }
11992
11993 /**
11994 * Method to read an OID object
11995 * @param {Uint8Array} input - Where to read the OID from
11996 * @returns {Number} Number of read bytes.
11997 */
11998 read(input) {
11999 if (input.length >= 1) {
12000 const length = input[0];
12001 if (input.length >= 1 + length) {
12002 this.oid = input.subarray(1, 1 + length);
12003 return 1 + this.oid.length;
12004 }
12005 }
12006 throw new Error('Invalid oid');
12007 }
12008
12009 /**
12010 * Serialize an OID object
12011 * @returns {Uint8Array} Array with the serialized value the OID.
12012 */
12013 write() {
12014 return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
12015 }
12016
12017 /**
12018 * Serialize an OID object as a hex string
12019 * @returns {string} String with the hex value of the OID.
12020 */
12021 toHex() {
12022 return util.uint8ArrayToHex(this.oid);
12023 }
12024
12025 /**
12026 * If a known curve object identifier, return the canonical name of the curve
12027 * @returns {string} String with the canonical name of the curve.
12028 */
12029 getName() {
12030 const hex = this.toHex();
12031 if (enums.curve[hex]) {
12032 return enums.write(enums.curve, hex);
12033 } else {
12034 throw new Error('Unknown curve object identifier.');
12035 }
12036 }
12037}
12038
12039// OpenPGP.js - An OpenPGP implementation in javascript
12040
12041function keyFromPrivate(indutnyCurve, priv) {
12042 const keyPair = indutnyCurve.keyPair({ priv: priv });
12043 return keyPair;
12044}
12045
12046function keyFromPublic(indutnyCurve, pub) {
12047 const keyPair = indutnyCurve.keyPair({ pub: pub });
12048 if (keyPair.validate().result !== true) {
12049 throw new Error('Invalid elliptic public key');
12050 }
12051 return keyPair;
12052}
12053
12054async function getIndutnyCurve(name) {
12055 if (!defaultConfig.useIndutnyElliptic) {
12056 throw new Error('This curve is only supported in the full build of OpenPGP.js');
12057 }
12058 const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; });
12059 return new elliptic.ec(name);
12060}
12061
12062// GPG4Browsers - An OpenPGP implementation in javascript
12063
12064function readSimpleLength(bytes) {
12065 let len = 0;
12066 let offset;
12067 const type = bytes[0];
12068
12069
12070 if (type < 192) {
12071 [len] = bytes;
12072 offset = 1;
12073 } else if (type < 255) {
12074 len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
12075 offset = 2;
12076 } else if (type === 255) {
12077 len = util.readNumber(bytes.subarray(1, 1 + 4));
12078 offset = 5;
12079 }
12080
12081 return {
12082 len: len,
12083 offset: offset
12084 };
12085}
12086
12087/**
12088 * Encodes a given integer of length to the openpgp length specifier to a
12089 * string
12090 *
12091 * @param {Integer} length - The length to encode
12092 * @returns {Uint8Array} String with openpgp length representation.
12093 */
12094function writeSimpleLength(length) {
12095 if (length < 192) {
12096 return new Uint8Array([length]);
12097 } else if (length > 191 && length < 8384) {
12098 /*
12099 * let a = (total data packet length) - 192 let bc = two octet
12100 * representation of a let d = b + 192
12101 */
12102 return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
12103 }
12104 return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
12105}
12106
12107function writePartialLength(power) {
12108 if (power < 0 || power > 30) {
12109 throw new Error('Partial Length power must be between 1 and 30');
12110 }
12111 return new Uint8Array([224 + power]);
12112}
12113
12114function writeTag(tag_type) {
12115 /* we're only generating v4 packet headers here */
12116 return new Uint8Array([0xC0 | tag_type]);
12117}
12118
12119/**
12120 * Writes a packet header version 4 with the given tag_type and length to a
12121 * string
12122 *
12123 * @param {Integer} tag_type - Tag type
12124 * @param {Integer} length - Length of the payload
12125 * @returns {String} String of the header.
12126 */
12127function writeHeader(tag_type, length) {
12128 /* we're only generating v4 packet headers here */
12129 return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
12130}
12131
12132/**
12133 * Whether the packet type supports partial lengths per RFC4880
12134 * @param {Integer} tag - Tag type
12135 * @returns {Boolean} String of the header.
12136 */
12137function supportsStreaming(tag) {
12138 return [
12139 enums.packet.literalData,
12140 enums.packet.compressedData,
12141 enums.packet.symmetricallyEncryptedData,
12142 enums.packet.symEncryptedIntegrityProtectedData,
12143 enums.packet.aeadEncryptedData
12144 ].includes(tag);
12145}
12146
12147/**
12148 * Generic static Packet Parser function
12149 *
12150 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
12151 * @param {Function} callback - Function to call with the parsed packet
12152 * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
12153 */
12154async function readPackets(input, callback) {
12155 const reader = getReader(input);
12156 let writer;
12157 let callbackReturned;
12158 try {
12159 const peekedBytes = await reader.peekBytes(2);
12160 // some sanity checks
12161 if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
12162 throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');
12163 }
12164 const headerByte = await reader.readByte();
12165 let tag = -1;
12166 let format = -1;
12167 let packetLength;
12168
12169 format = 0; // 0 = old format; 1 = new format
12170 if ((headerByte & 0x40) !== 0) {
12171 format = 1;
12172 }
12173
12174 let packetLengthType;
12175 if (format) {
12176 // new format header
12177 tag = headerByte & 0x3F; // bit 5-0
12178 } else {
12179 // old format header
12180 tag = (headerByte & 0x3F) >> 2; // bit 5-2
12181 packetLengthType = headerByte & 0x03; // bit 1-0
12182 }
12183
12184 const packetSupportsStreaming = supportsStreaming(tag);
12185 let packet = null;
12186 if (packetSupportsStreaming) {
12187 if (util.isStream(input) === 'array') {
12188 const arrayStream = new ArrayStream();
12189 writer = getWriter(arrayStream);
12190 packet = arrayStream;
12191 } else {
12192 const transform = new TransformStream();
12193 writer = getWriter(transform.writable);
12194 packet = transform.readable;
12195 }
12196 callbackReturned = callback({ tag, packet });
12197 } else {
12198 packet = [];
12199 }
12200
12201 let wasPartialLength;
12202 do {
12203 if (!format) {
12204 // 4.2.1. Old Format Packet Lengths
12205 switch (packetLengthType) {
12206 case 0:
12207 // The packet has a one-octet length. The header is 2 octets
12208 // long.
12209 packetLength = await reader.readByte();
12210 break;
12211 case 1:
12212 // The packet has a two-octet length. The header is 3 octets
12213 // long.
12214 packetLength = (await reader.readByte() << 8) | await reader.readByte();
12215 break;
12216 case 2:
12217 // The packet has a four-octet length. The header is 5
12218 // octets long.
12219 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
12220 8) | await reader.readByte();
12221 break;
12222 default:
12223 // 3 - The packet is of indeterminate length. The header is 1
12224 // octet long, and the implementation must determine how long
12225 // the packet is. If the packet is in a file, this means that
12226 // the packet extends until the end of the file. In general,
12227 // an implementation SHOULD NOT use indeterminate-length
12228 // packets except where the end of the data will be clear
12229 // from the context, and even then it is better to use a
12230 // definite length, or a new format header. The new format
12231 // headers described below have a mechanism for precisely
12232 // encoding data of indeterminate length.
12233 packetLength = Infinity;
12234 break;
12235 }
12236 } else { // 4.2.2. New Format Packet Lengths
12237 // 4.2.2.1. One-Octet Lengths
12238 const lengthByte = await reader.readByte();
12239 wasPartialLength = false;
12240 if (lengthByte < 192) {
12241 packetLength = lengthByte;
12242 // 4.2.2.2. Two-Octet Lengths
12243 } else if (lengthByte >= 192 && lengthByte < 224) {
12244 packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
12245 // 4.2.2.4. Partial Body Lengths
12246 } else if (lengthByte > 223 && lengthByte < 255) {
12247 packetLength = 1 << (lengthByte & 0x1F);
12248 wasPartialLength = true;
12249 if (!packetSupportsStreaming) {
12250 throw new TypeError('This packet type does not support partial lengths.');
12251 }
12252 // 4.2.2.3. Five-Octet Lengths
12253 } else {
12254 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
12255 8) | await reader.readByte();
12256 }
12257 }
12258 if (packetLength > 0) {
12259 let bytesRead = 0;
12260 while (true) {
12261 if (writer) await writer.ready;
12262 const { done, value } = await reader.read();
12263 if (done) {
12264 if (packetLength === Infinity) break;
12265 throw new Error('Unexpected end of packet');
12266 }
12267 const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);
12268 if (writer) await writer.write(chunk);
12269 else packet.push(chunk);
12270 bytesRead += value.length;
12271 if (bytesRead >= packetLength) {
12272 reader.unshift(value.subarray(packetLength - bytesRead + value.length));
12273 break;
12274 }
12275 }
12276 }
12277 } while (wasPartialLength);
12278
12279 // If this was not a packet that "supports streaming", we peek to check
12280 // whether it is the last packet in the message. We peek 2 bytes instead
12281 // of 1 because the beginning of this function also peeks 2 bytes, and we
12282 // want to cut a `subarray` of the correct length into `web-stream-tools`'
12283 // `externalBuffer` as a tiny optimization here.
12284 //
12285 // If it *was* a streaming packet (i.e. the data packets), we peek at the
12286 // entire remainder of the stream, in order to forward errors in the
12287 // remainder of the stream to the packet data. (Note that this means we
12288 // read/peek at all signature packets before closing the literal data
12289 // packet, for example.) This forwards MDC errors to the literal data
12290 // stream, for example, so that they don't get lost / forgotten on
12291 // decryptedMessage.packets.stream, which we never look at.
12292 //
12293 // An example of what we do when stream-parsing a message containing
12294 // [ one-pass signature packet, literal data packet, signature packet ]:
12295 // 1. Read the one-pass signature packet
12296 // 2. Peek 2 bytes of the literal data packet
12297 // 3. Parse the one-pass signature packet
12298 //
12299 // 4. Read the literal data packet, simultaneously stream-parsing it
12300 // 5. Peek until the end of the message
12301 // 6. Finish parsing the literal data packet
12302 //
12303 // 7. Read the signature packet again (we already peeked at it in step 5)
12304 // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
12305 // 9. Parse the signature packet
12306 //
12307 // Note that this means that if there's an error in the very end of the
12308 // stream, such as an MDC error, we throw in step 5 instead of in step 8
12309 // (or never), which is the point of this exercise.
12310 const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);
12311 if (writer) {
12312 await writer.ready;
12313 await writer.close();
12314 } else {
12315 packet = util.concatUint8Array(packet);
12316 await callback({ tag, packet });
12317 }
12318 return !nextPacket || !nextPacket.length;
12319 } catch (e) {
12320 if (writer) {
12321 await writer.abort(e);
12322 return true;
12323 } else {
12324 throw e;
12325 }
12326 } finally {
12327 if (writer) {
12328 await callbackReturned;
12329 }
12330 reader.releaseLock();
12331 }
12332}
12333
12334class UnsupportedError extends Error {
12335 constructor(...params) {
12336 super(...params);
12337
12338 if (Error.captureStackTrace) {
12339 Error.captureStackTrace(this, UnsupportedError);
12340 }
12341
12342 this.name = 'UnsupportedError';
12343 }
12344}
12345
12346class UnparseablePacket {
12347 constructor(tag, rawContent) {
12348 this.tag = tag;
12349 this.rawContent = rawContent;
12350 }
12351
12352 write() {
12353 return this.rawContent;
12354 }
12355}
12356
12357// OpenPGP.js - An OpenPGP implementation in javascript
12358
12359const webCrypto$2 = util.getWebCrypto();
12360const nodeCrypto$3 = util.getNodeCrypto();
12361
12362const webCurves = {
12363 'p256': 'P-256',
12364 'p384': 'P-384',
12365 'p521': 'P-521'
12366};
12367const knownCurves = nodeCrypto$3 ? nodeCrypto$3.getCurves() : [];
12368const nodeCurves = nodeCrypto$3 ? {
12369 secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
12370 p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
12371 p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
12372 p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
12373 ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
12374 curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
12375 brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
12376 brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
12377 brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
12378} : {};
12379
12380const curves = {
12381 p256: {
12382 oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
12383 keyType: enums.publicKey.ecdsa,
12384 hash: enums.hash.sha256,
12385 cipher: enums.symmetric.aes128,
12386 node: nodeCurves.p256,
12387 web: webCurves.p256,
12388 payloadSize: 32,
12389 sharedSize: 256
12390 },
12391 p384: {
12392 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
12393 keyType: enums.publicKey.ecdsa,
12394 hash: enums.hash.sha384,
12395 cipher: enums.symmetric.aes192,
12396 node: nodeCurves.p384,
12397 web: webCurves.p384,
12398 payloadSize: 48,
12399 sharedSize: 384
12400 },
12401 p521: {
12402 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
12403 keyType: enums.publicKey.ecdsa,
12404 hash: enums.hash.sha512,
12405 cipher: enums.symmetric.aes256,
12406 node: nodeCurves.p521,
12407 web: webCurves.p521,
12408 payloadSize: 66,
12409 sharedSize: 528
12410 },
12411 secp256k1: {
12412 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
12413 keyType: enums.publicKey.ecdsa,
12414 hash: enums.hash.sha256,
12415 cipher: enums.symmetric.aes128,
12416 node: nodeCurves.secp256k1,
12417 payloadSize: 32
12418 },
12419 ed25519: {
12420 oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
12421 keyType: enums.publicKey.eddsa,
12422 hash: enums.hash.sha512,
12423 node: false, // nodeCurves.ed25519 TODO
12424 payloadSize: 32
12425 },
12426 curve25519: {
12427 oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
12428 keyType: enums.publicKey.ecdh,
12429 hash: enums.hash.sha256,
12430 cipher: enums.symmetric.aes128,
12431 node: false, // nodeCurves.curve25519 TODO
12432 payloadSize: 32
12433 },
12434 brainpoolP256r1: {
12435 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
12436 keyType: enums.publicKey.ecdsa,
12437 hash: enums.hash.sha256,
12438 cipher: enums.symmetric.aes128,
12439 node: nodeCurves.brainpoolP256r1,
12440 payloadSize: 32
12441 },
12442 brainpoolP384r1: {
12443 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
12444 keyType: enums.publicKey.ecdsa,
12445 hash: enums.hash.sha384,
12446 cipher: enums.symmetric.aes192,
12447 node: nodeCurves.brainpoolP384r1,
12448 payloadSize: 48
12449 },
12450 brainpoolP512r1: {
12451 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
12452 keyType: enums.publicKey.ecdsa,
12453 hash: enums.hash.sha512,
12454 cipher: enums.symmetric.aes256,
12455 node: nodeCurves.brainpoolP512r1,
12456 payloadSize: 64
12457 }
12458};
12459
12460class Curve {
12461 constructor(oidOrName, params) {
12462 try {
12463 if (util.isArray(oidOrName) ||
12464 util.isUint8Array(oidOrName)) {
12465 // by oid byte array
12466 oidOrName = new OID(oidOrName);
12467 }
12468 if (oidOrName instanceof OID) {
12469 // by curve OID
12470 oidOrName = oidOrName.getName();
12471 }
12472 // by curve name or oid string
12473 this.name = enums.write(enums.curve, oidOrName);
12474 } catch (err) {
12475 throw new UnsupportedError('Unknown curve');
12476 }
12477 params = params || curves[this.name];
12478
12479 this.keyType = params.keyType;
12480
12481 this.oid = params.oid;
12482 this.hash = params.hash;
12483 this.cipher = params.cipher;
12484 this.node = params.node && curves[this.name];
12485 this.web = params.web && curves[this.name];
12486 this.payloadSize = params.payloadSize;
12487 if (this.web && util.getWebCrypto()) {
12488 this.type = 'web';
12489 } else if (this.node && util.getNodeCrypto()) {
12490 this.type = 'node';
12491 } else if (this.name === 'curve25519') {
12492 this.type = 'curve25519';
12493 } else if (this.name === 'ed25519') {
12494 this.type = 'ed25519';
12495 }
12496 }
12497
12498 async genKeyPair() {
12499 let keyPair;
12500 switch (this.type) {
12501 case 'web':
12502 try {
12503 return await webGenKeyPair(this.name);
12504 } catch (err) {
12505 util.printDebugError('Browser did not support generating ec key ' + err.message);
12506 break;
12507 }
12508 case 'node':
12509 return nodeGenKeyPair(this.name);
12510 case 'curve25519': {
12511 const privateKey = await getRandomBytes(32);
12512 privateKey[0] = (privateKey[0] & 127) | 64;
12513 privateKey[31] &= 248;
12514 const secretKey = privateKey.slice().reverse();
12515 keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey);
12516 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
12517 return { publicKey, privateKey };
12518 }
12519 case 'ed25519': {
12520 const privateKey = await getRandomBytes(32);
12521 const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey);
12522 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
12523 return { publicKey, privateKey };
12524 }
12525 }
12526 const indutnyCurve = await getIndutnyCurve(this.name);
12527 keyPair = await indutnyCurve.genKeyPair({
12528 entropy: util.uint8ArrayToString(await getRandomBytes(32))
12529 });
12530 return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
12531 }
12532}
12533
12534async function generate$1(curve) {
12535 const BigInteger = await util.getBigInteger();
12536
12537 curve = new Curve(curve);
12538 const keyPair = await curve.genKeyPair();
12539 const Q = new BigInteger(keyPair.publicKey).toUint8Array();
12540 const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);
12541 return {
12542 oid: curve.oid,
12543 Q,
12544 secret,
12545 hash: curve.hash,
12546 cipher: curve.cipher
12547 };
12548}
12549
12550/**
12551 * Get preferred hash algo to use with the given curve
12552 * @param {module:type/oid} oid - curve oid
12553 * @returns {enums.hash} hash algorithm
12554 */
12555function getPreferredHashAlgo(oid) {
12556 return curves[enums.write(enums.curve, oid.toHex())].hash;
12557}
12558
12559/**
12560 * Validate ECDH and ECDSA parameters
12561 * Not suitable for EdDSA (different secret key format)
12562 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
12563 * @param {module:type/oid} oid - EC object identifier
12564 * @param {Uint8Array} Q - EC public point
12565 * @param {Uint8Array} d - EC secret scalar
12566 * @returns {Promise<Boolean>} Whether params are valid.
12567 * @async
12568 */
12569async function validateStandardParams(algo, oid, Q, d) {
12570 const supportedCurves = {
12571 p256: true,
12572 p384: true,
12573 p521: true,
12574 secp256k1: true,
12575 curve25519: algo === enums.publicKey.ecdh,
12576 brainpoolP256r1: true,
12577 brainpoolP384r1: true,
12578 brainpoolP512r1: true
12579 };
12580
12581 // Check whether the given curve is supported
12582 const curveName = oid.getName();
12583 if (!supportedCurves[curveName]) {
12584 return false;
12585 }
12586
12587 if (curveName === 'curve25519') {
12588 d = d.slice().reverse();
12589 // Re-derive public point Q'
12590 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d);
12591
12592 Q = new Uint8Array(Q);
12593 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
12594 if (!util.equalsUint8Array(dG, Q)) {
12595 return false;
12596 }
12597
12598 return true;
12599 }
12600
12601 const curve = await getIndutnyCurve(curveName);
12602 try {
12603 // Parse Q and check that it is on the curve but not at infinity
12604 Q = keyFromPublic(curve, Q).getPublic();
12605 } catch (validationErrors) {
12606 return false;
12607 }
12608
12609 /**
12610 * Re-derive public point Q' = dG from private key
12611 * Expect Q == Q'
12612 */
12613 const dG = keyFromPrivate(curve, d).getPublic();
12614 if (!dG.eq(Q)) {
12615 return false;
12616 }
12617
12618 return true;
12619}
12620
12621//////////////////////////
12622// //
12623// Helper functions //
12624// //
12625//////////////////////////
12626
12627
12628async function webGenKeyPair(name) {
12629 // Note: keys generated with ECDSA and ECDH are structurally equivalent
12630 const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);
12631
12632 const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey);
12633 const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey);
12634
12635 return {
12636 publicKey: jwkToRawPublic(publicKey),
12637 privateKey: b64ToUint8Array(privateKey.d)
12638 };
12639}
12640
12641async function nodeGenKeyPair(name) {
12642 // Note: ECDSA and ECDH key generation is structurally equivalent
12643 const ecdh = nodeCrypto$3.createECDH(nodeCurves[name]);
12644 await ecdh.generateKeys();
12645 return {
12646 publicKey: new Uint8Array(ecdh.getPublicKey()),
12647 privateKey: new Uint8Array(ecdh.getPrivateKey())
12648 };
12649}
12650
12651//////////////////////////
12652// //
12653// Helper functions //
12654// //
12655//////////////////////////
12656
12657/**
12658 * @param {JsonWebKey} jwk - key for conversion
12659 *
12660 * @returns {Uint8Array} Raw public key.
12661 */
12662function jwkToRawPublic(jwk) {
12663 const bufX = b64ToUint8Array(jwk.x);
12664 const bufY = b64ToUint8Array(jwk.y);
12665 const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
12666 publicKey[0] = 0x04;
12667 publicKey.set(bufX, 1);
12668 publicKey.set(bufY, bufX.length + 1);
12669 return publicKey;
12670}
12671
12672/**
12673 * @param {Integer} payloadSize - ec payload size
12674 * @param {String} name - curve name
12675 * @param {Uint8Array} publicKey - public key
12676 *
12677 * @returns {JsonWebKey} Public key in jwk format.
12678 */
12679function rawPublicToJWK(payloadSize, name, publicKey) {
12680 const len = payloadSize;
12681 const bufX = publicKey.slice(1, len + 1);
12682 const bufY = publicKey.slice(len + 1, len * 2 + 1);
12683 // https://www.rfc-editor.org/rfc/rfc7518.txt
12684 const jwk = {
12685 kty: 'EC',
12686 crv: name,
12687 x: uint8ArrayToB64(bufX, true),
12688 y: uint8ArrayToB64(bufY, true),
12689 ext: true
12690 };
12691 return jwk;
12692}
12693
12694/**
12695 * @param {Integer} payloadSize - ec payload size
12696 * @param {String} name - curve name
12697 * @param {Uint8Array} publicKey - public key
12698 * @param {Uint8Array} privateKey - private key
12699 *
12700 * @returns {JsonWebKey} Private key in jwk format.
12701 */
12702function privateToJWK$1(payloadSize, name, publicKey, privateKey) {
12703 const jwk = rawPublicToJWK(payloadSize, name, publicKey);
12704 jwk.d = uint8ArrayToB64(privateKey, true);
12705 return jwk;
12706}
12707
12708// OpenPGP.js - An OpenPGP implementation in javascript
12709
12710const webCrypto$3 = util.getWebCrypto();
12711const nodeCrypto$4 = util.getNodeCrypto();
12712
12713/**
12714 * Sign a message using the provided key
12715 * @param {module:type/oid} oid - Elliptic curve object identifier
12716 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign
12717 * @param {Uint8Array} message - Message to sign
12718 * @param {Uint8Array} publicKey - Public key
12719 * @param {Uint8Array} privateKey - Private key used to sign the message
12720 * @param {Uint8Array} hashed - The hashed message
12721 * @returns {Promise<{
12722 * r: Uint8Array,
12723 * s: Uint8Array
12724 * }>} Signature of the message
12725 * @async
12726 */
12727async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) {
12728 const curve = new Curve(oid);
12729 if (message && !util.isStream(message)) {
12730 const keyPair = { publicKey, privateKey };
12731 switch (curve.type) {
12732 case 'web': {
12733 // If browser doesn't support a curve, we'll catch it
12734 try {
12735 // Need to await to make sure browser succeeds
12736 return await webSign$1(curve, hashAlgo, message, keyPair);
12737 } catch (err) {
12738 // We do not fallback if the error is related to key integrity
12739 // Unfortunaley Safari does not support p521 and throws a DataError when using it
12740 // So we need to always fallback for that curve
12741 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
12742 throw err;
12743 }
12744 util.printDebugError('Browser did not support signing: ' + err.message);
12745 }
12746 break;
12747 }
12748 case 'node': {
12749 const signature = await nodeSign$1(curve, hashAlgo, message, keyPair);
12750 return {
12751 r: signature.r.toArrayLike(Uint8Array),
12752 s: signature.s.toArrayLike(Uint8Array)
12753 };
12754 }
12755 }
12756 }
12757 return ellipticSign(curve, hashed, privateKey);
12758}
12759
12760/**
12761 * Verifies if a signature is valid for a message
12762 * @param {module:type/oid} oid - Elliptic curve object identifier
12763 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
12764 * @param {{r: Uint8Array,
12765 s: Uint8Array}} signature Signature to verify
12766 * @param {Uint8Array} message - Message to verify
12767 * @param {Uint8Array} publicKey - Public key used to verify the message
12768 * @param {Uint8Array} hashed - The hashed message
12769 * @returns {Boolean}
12770 * @async
12771 */
12772async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) {
12773 const curve = new Curve(oid);
12774 if (message && !util.isStream(message)) {
12775 switch (curve.type) {
12776 case 'web':
12777 try {
12778 // Need to await to make sure browser succeeds
12779 return await webVerify$1(curve, hashAlgo, signature, message, publicKey);
12780 } catch (err) {
12781 // We do not fallback if the error is related to key integrity
12782 // Unfortunately Safari does not support p521 and throws a DataError when using it
12783 // So we need to always fallback for that curve
12784 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
12785 throw err;
12786 }
12787 util.printDebugError('Browser did not support verifying: ' + err.message);
12788 }
12789 break;
12790 case 'node':
12791 return nodeVerify$1(curve, hashAlgo, signature, message, publicKey);
12792 }
12793 }
12794 const digest = (typeof hashAlgo === 'undefined') ? message : hashed;
12795 return ellipticVerify(curve, signature, digest, publicKey);
12796}
12797
12798/**
12799 * Validate ECDSA parameters
12800 * @param {module:type/oid} oid - Elliptic curve object identifier
12801 * @param {Uint8Array} Q - ECDSA public point
12802 * @param {Uint8Array} d - ECDSA secret scalar
12803 * @returns {Promise<Boolean>} Whether params are valid.
12804 * @async
12805 */
12806async function validateParams$2(oid, Q, d) {
12807 const curve = new Curve(oid);
12808 // Reject curves x25519 and ed25519
12809 if (curve.keyType !== enums.publicKey.ecdsa) {
12810 return false;
12811 }
12812
12813 // To speed up the validation, we try to use node- or webcrypto when available
12814 // and sign + verify a random message
12815 switch (curve.type) {
12816 case 'web':
12817 case 'node': {
12818 const message = await getRandomBytes(8);
12819 const hashAlgo = enums.hash.sha256;
12820 const hashed = await hash.digest(hashAlgo, message);
12821 try {
12822 const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed);
12823 return await verify$1(oid, hashAlgo, signature, message, Q, hashed);
12824 } catch (err) {
12825 return false;
12826 }
12827 }
12828 default:
12829 return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
12830 }
12831}
12832
12833
12834//////////////////////////
12835// //
12836// Helper functions //
12837// //
12838//////////////////////////
12839
12840async function ellipticSign(curve, hashed, privateKey) {
12841 const indutnyCurve = await getIndutnyCurve(curve.name);
12842 const key = keyFromPrivate(indutnyCurve, privateKey);
12843 const signature = key.sign(hashed);
12844 return {
12845 r: signature.r.toArrayLike(Uint8Array),
12846 s: signature.s.toArrayLike(Uint8Array)
12847 };
12848}
12849
12850async function ellipticVerify(curve, signature, digest, publicKey) {
12851 const indutnyCurve = await getIndutnyCurve(curve.name);
12852 const key = keyFromPublic(indutnyCurve, publicKey);
12853 return key.verify(digest, signature);
12854}
12855
12856async function webSign$1(curve, hashAlgo, message, keyPair) {
12857 const len = curve.payloadSize;
12858 const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
12859 const key = await webCrypto$3.importKey(
12860 'jwk',
12861 jwk,
12862 {
12863 'name': 'ECDSA',
12864 'namedCurve': webCurves[curve.name],
12865 'hash': { name: enums.read(enums.webHash, curve.hash) }
12866 },
12867 false,
12868 ['sign']
12869 );
12870
12871 const signature = new Uint8Array(await webCrypto$3.sign(
12872 {
12873 'name': 'ECDSA',
12874 'namedCurve': webCurves[curve.name],
12875 'hash': { name: enums.read(enums.webHash, hashAlgo) }
12876 },
12877 key,
12878 message
12879 ));
12880
12881 return {
12882 r: signature.slice(0, len),
12883 s: signature.slice(len, len << 1)
12884 };
12885}
12886
12887async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
12888 const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);
12889 const key = await webCrypto$3.importKey(
12890 'jwk',
12891 jwk,
12892 {
12893 'name': 'ECDSA',
12894 'namedCurve': webCurves[curve.name],
12895 'hash': { name: enums.read(enums.webHash, curve.hash) }
12896 },
12897 false,
12898 ['verify']
12899 );
12900
12901 const signature = util.concatUint8Array([r, s]).buffer;
12902
12903 return webCrypto$3.verify(
12904 {
12905 'name': 'ECDSA',
12906 'namedCurve': webCurves[curve.name],
12907 'hash': { name: enums.read(enums.webHash, hashAlgo) }
12908 },
12909 key,
12910 signature,
12911 message
12912 );
12913}
12914
12915async function nodeSign$1(curve, hashAlgo, message, keyPair) {
12916 const sign = nodeCrypto$4.createSign(enums.read(enums.hash, hashAlgo));
12917 sign.write(message);
12918 sign.end();
12919 const key = ECPrivateKey.encode({
12920 version: 1,
12921 parameters: curve.oid,
12922 privateKey: Array.from(keyPair.privateKey),
12923 publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
12924 }, 'pem', {
12925 label: 'EC PRIVATE KEY'
12926 });
12927
12928 return ECDSASignature.decode(sign.sign(key), 'der');
12929}
12930
12931async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
12932 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12933
12934 const verify = nodeCrypto$4.createVerify(enums.read(enums.hash, hashAlgo));
12935 verify.write(message);
12936 verify.end();
12937 const key = SubjectPublicKeyInfo.encode({
12938 algorithm: {
12939 algorithm: [1, 2, 840, 10045, 2, 1],
12940 parameters: curve.oid
12941 },
12942 subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
12943 }, 'pem', {
12944 label: 'PUBLIC KEY'
12945 });
12946 const signature = ECDSASignature.encode({
12947 r: new BN(r), s: new BN(s)
12948 }, 'der');
12949
12950 try {
12951 return verify.verify(key, signature);
12952 } catch (err) {
12953 return false;
12954 }
12955}
12956
12957// Originally written by Owen Smith https://github.com/omsmith
12958// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
12959
12960/* eslint-disable no-invalid-this */
12961
12962const asn1$1 = nodeCrypto$4 ? void('asn1.js') : undefined;
12963
12964const ECDSASignature = nodeCrypto$4 ?
12965 asn1$1.define('ECDSASignature', function() {
12966 this.seq().obj(
12967 this.key('r').int(),
12968 this.key('s').int()
12969 );
12970 }) : undefined;
12971
12972const ECPrivateKey = nodeCrypto$4 ?
12973 asn1$1.define('ECPrivateKey', function() {
12974 this.seq().obj(
12975 this.key('version').int(),
12976 this.key('privateKey').octstr(),
12977 this.key('parameters').explicit(0).optional().any(),
12978 this.key('publicKey').explicit(1).optional().bitstr()
12979 );
12980 }) : undefined;
12981
12982const AlgorithmIdentifier = nodeCrypto$4 ?
12983 asn1$1.define('AlgorithmIdentifier', function() {
12984 this.seq().obj(
12985 this.key('algorithm').objid(),
12986 this.key('parameters').optional().any()
12987 );
12988 }) : undefined;
12989
12990const SubjectPublicKeyInfo = nodeCrypto$4 ?
12991 asn1$1.define('SubjectPublicKeyInfo', function() {
12992 this.seq().obj(
12993 this.key('algorithm').use(AlgorithmIdentifier),
12994 this.key('subjectPublicKey').bitstr()
12995 );
12996 }) : undefined;
12997
12998var ecdsa = /*#__PURE__*/Object.freeze({
12999 __proto__: null,
13000 sign: sign$1,
13001 verify: verify$1,
13002 validateParams: validateParams$2
13003});
13004
13005// OpenPGP.js - An OpenPGP implementation in javascript
13006
13007naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
13008
13009/**
13010 * Sign a message using the provided key
13011 * @param {module:type/oid} oid - Elliptic curve object identifier
13012 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
13013 * @param {Uint8Array} message - Message to sign
13014 * @param {Uint8Array} publicKey - Public key
13015 * @param {Uint8Array} privateKey - Private key used to sign the message
13016 * @param {Uint8Array} hashed - The hashed message
13017 * @returns {Promise<{
13018 * r: Uint8Array,
13019 * s: Uint8Array
13020 * }>} Signature of the message
13021 * @async
13022 */
13023async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) {
13024 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {
13025 // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
13026 throw new Error('Hash algorithm too weak: sha256 or stronger is required for EdDSA.');
13027 }
13028 const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);
13029 const signature = naclFastLight.sign.detached(hashed, secretKey);
13030 // EdDSA signature params are returned in little-endian format
13031 return {
13032 r: signature.subarray(0, 32),
13033 s: signature.subarray(32)
13034 };
13035}
13036
13037/**
13038 * Verifies if a signature is valid for a message
13039 * @param {module:type/oid} oid - Elliptic curve object identifier
13040 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
13041 * @param {{r: Uint8Array,
13042 s: Uint8Array}} signature Signature to verify the message
13043 * @param {Uint8Array} m - Message to verify
13044 * @param {Uint8Array} publicKey - Public key used to verify the message
13045 * @param {Uint8Array} hashed - The hashed message
13046 * @returns {Boolean}
13047 * @async
13048 */
13049async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) {
13050 const signature = util.concatUint8Array([r, s]);
13051 return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1));
13052}
13053/**
13054 * Validate EdDSA parameters
13055 * @param {module:type/oid} oid - Elliptic curve object identifier
13056 * @param {Uint8Array} Q - EdDSA public point
13057 * @param {Uint8Array} k - EdDSA secret seed
13058 * @returns {Promise<Boolean>} Whether params are valid.
13059 * @async
13060 */
13061async function validateParams$3(oid, Q, k) {
13062 // Check whether the given curve is supported
13063 if (oid.getName() !== 'ed25519') {
13064 return false;
13065 }
13066
13067 /**
13068 * Derive public point Q' = dG from private key
13069 * and expect Q == Q'
13070 */
13071 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k);
13072 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
13073 return util.equalsUint8Array(Q, dG);
13074}
13075
13076var eddsa = /*#__PURE__*/Object.freeze({
13077 __proto__: null,
13078 sign: sign$2,
13079 verify: verify$2,
13080 validateParams: validateParams$3
13081});
13082
13083// OpenPGP.js - An OpenPGP implementation in javascript
13084
13085/**
13086 * AES key wrap
13087 * @function
13088 * @param {Uint8Array} key
13089 * @param {Uint8Array} data
13090 * @returns {Uint8Array}
13091 */
13092function wrap(key, data) {
13093 const aes = new cipher['aes' + (key.length * 8)](key);
13094 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13095 const P = unpack(data);
13096 let A = IV;
13097 const R = P;
13098 const n = P.length / 2;
13099 const t = new Uint32Array([0, 0]);
13100 let B = new Uint32Array(4);
13101 for (let j = 0; j <= 5; ++j) {
13102 for (let i = 0; i < n; ++i) {
13103 t[1] = n * j + (1 + i);
13104 // B = A
13105 B[0] = A[0];
13106 B[1] = A[1];
13107 // B = A || R[i]
13108 B[2] = R[2 * i];
13109 B[3] = R[2 * i + 1];
13110 // B = AES(K, B)
13111 B = unpack(aes.encrypt(pack(B)));
13112 // A = MSB(64, B) ^ t
13113 A = B.subarray(0, 2);
13114 A[0] ^= t[0];
13115 A[1] ^= t[1];
13116 // R[i] = LSB(64, B)
13117 R[2 * i] = B[2];
13118 R[2 * i + 1] = B[3];
13119 }
13120 }
13121 return pack(A, R);
13122}
13123
13124/**
13125 * AES key unwrap
13126 * @function
13127 * @param {String} key
13128 * @param {String} data
13129 * @returns {Uint8Array}
13130 * @throws {Error}
13131 */
13132function unwrap(key, data) {
13133 const aes = new cipher['aes' + (key.length * 8)](key);
13134 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13135 const C = unpack(data);
13136 let A = C.subarray(0, 2);
13137 const R = C.subarray(2);
13138 const n = C.length / 2 - 1;
13139 const t = new Uint32Array([0, 0]);
13140 let B = new Uint32Array(4);
13141 for (let j = 5; j >= 0; --j) {
13142 for (let i = n - 1; i >= 0; --i) {
13143 t[1] = n * j + (i + 1);
13144 // B = A ^ t
13145 B[0] = A[0] ^ t[0];
13146 B[1] = A[1] ^ t[1];
13147 // B = (A ^ t) || R[i]
13148 B[2] = R[2 * i];
13149 B[3] = R[2 * i + 1];
13150 // B = AES-1(B)
13151 B = unpack(aes.decrypt(pack(B)));
13152 // A = MSB(64, B)
13153 A = B.subarray(0, 2);
13154 // R[i] = LSB(64, B)
13155 R[2 * i] = B[2];
13156 R[2 * i + 1] = B[3];
13157 }
13158 }
13159 if (A[0] === IV[0] && A[1] === IV[1]) {
13160 return pack(R);
13161 }
13162 throw new Error('Key Data Integrity failed');
13163}
13164
13165function createArrayBuffer(data) {
13166 if (util.isString(data)) {
13167 const { length } = data;
13168 const buffer = new ArrayBuffer(length);
13169 const view = new Uint8Array(buffer);
13170 for (let j = 0; j < length; ++j) {
13171 view[j] = data.charCodeAt(j);
13172 }
13173 return buffer;
13174 }
13175 return new Uint8Array(data).buffer;
13176}
13177
13178function unpack(data) {
13179 const { length } = data;
13180 const buffer = createArrayBuffer(data);
13181 const view = new DataView(buffer);
13182 const arr = new Uint32Array(length / 4);
13183 for (let i = 0; i < length / 4; ++i) {
13184 arr[i] = view.getUint32(4 * i);
13185 }
13186 return arr;
13187}
13188
13189function pack() {
13190 let length = 0;
13191 for (let k = 0; k < arguments.length; ++k) {
13192 length += 4 * arguments[k].length;
13193 }
13194 const buffer = new ArrayBuffer(length);
13195 const view = new DataView(buffer);
13196 let offset = 0;
13197 for (let i = 0; i < arguments.length; ++i) {
13198 for (let j = 0; j < arguments[i].length; ++j) {
13199 view.setUint32(offset + 4 * j, arguments[i][j]);
13200 }
13201 offset += 4 * arguments[i].length;
13202 }
13203 return new Uint8Array(buffer);
13204}
13205
13206var aesKW = /*#__PURE__*/Object.freeze({
13207 __proto__: null,
13208 wrap: wrap,
13209 unwrap: unwrap
13210});
13211
13212// OpenPGP.js - An OpenPGP implementation in javascript
13213
13214/**
13215 * @fileoverview Functions to add and remove PKCS5 padding
13216 * @see PublicKeyEncryptedSessionKeyPacket
13217 * @module crypto/pkcs5
13218 * @private
13219 */
13220
13221/**
13222 * Add pkcs5 padding to a message
13223 * @param {Uint8Array} message - message to pad
13224 * @returns {Uint8Array} Padded message.
13225 */
13226function encode$1(message) {
13227 const c = 8 - (message.length % 8);
13228 const padded = new Uint8Array(message.length + c).fill(c);
13229 padded.set(message);
13230 return padded;
13231}
13232
13233/**
13234 * Remove pkcs5 padding from a message
13235 * @param {Uint8Array} message - message to remove padding from
13236 * @returns {Uint8Array} Message without padding.
13237 */
13238function decode$1(message) {
13239 const len = message.length;
13240 if (len > 0) {
13241 const c = message[len - 1];
13242 if (c >= 1) {
13243 const provided = message.subarray(len - c);
13244 const computed = new Uint8Array(c).fill(c);
13245 if (util.equalsUint8Array(provided, computed)) {
13246 return message.subarray(0, len - c);
13247 }
13248 }
13249 }
13250 throw new Error('Invalid padding');
13251}
13252
13253var pkcs5 = /*#__PURE__*/Object.freeze({
13254 __proto__: null,
13255 encode: encode$1,
13256 decode: decode$1
13257});
13258
13259// OpenPGP.js - An OpenPGP implementation in javascript
13260
13261const webCrypto$4 = util.getWebCrypto();
13262const nodeCrypto$5 = util.getNodeCrypto();
13263
13264/**
13265 * Validate ECDH parameters
13266 * @param {module:type/oid} oid - Elliptic curve object identifier
13267 * @param {Uint8Array} Q - ECDH public point
13268 * @param {Uint8Array} d - ECDH secret scalar
13269 * @returns {Promise<Boolean>} Whether params are valid.
13270 * @async
13271 */
13272async function validateParams$4(oid, Q, d) {
13273 return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
13274}
13275
13276// Build Param for ECDH algorithm (RFC 6637)
13277function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
13278 return util.concatUint8Array([
13279 oid.write(),
13280 new Uint8Array([public_algo]),
13281 kdfParams.write(),
13282 util.stringToUint8Array('Anonymous Sender '),
13283 fingerprint.subarray(0, 20)
13284 ]);
13285}
13286
13287// Key Derivation Function (RFC 6637)
13288async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {
13289 // Note: X is little endian for Curve25519, big-endian for all others.
13290 // This is not ideal, but the RFC's are unclear
13291 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
13292 let i;
13293 if (stripLeading) {
13294 // Work around old go crypto bug
13295 for (i = 0; i < X.length && X[i] === 0; i++);
13296 X = X.subarray(i);
13297 }
13298 if (stripTrailing) {
13299 // Work around old OpenPGP.js bug
13300 for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
13301 X = X.subarray(0, i + 1);
13302 }
13303 const digest = await hash.digest(hashAlgo, util.concatUint8Array([
13304 new Uint8Array([0, 0, 0, 1]),
13305 X,
13306 param
13307 ]));
13308 return digest.subarray(0, length);
13309}
13310
13311/**
13312 * Generate ECDHE ephemeral key and secret from public key
13313 *
13314 * @param {Curve} curve - Elliptic curve object
13315 * @param {Uint8Array} Q - Recipient public key
13316 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13317 * @async
13318 */
13319async function genPublicEphemeralKey(curve, Q) {
13320 switch (curve.type) {
13321 case 'curve25519': {
13322 const d = await getRandomBytes(32);
13323 const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);
13324 let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey);
13325 publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
13326 return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
13327 }
13328 case 'web':
13329 if (curve.web && util.getWebCrypto()) {
13330 try {
13331 return await webPublicEphemeralKey(curve, Q);
13332 } catch (err) {
13333 util.printDebugError(err);
13334 }
13335 }
13336 break;
13337 case 'node':
13338 return nodePublicEphemeralKey(curve, Q);
13339 }
13340 return ellipticPublicEphemeralKey(curve, Q);
13341}
13342
13343/**
13344 * Encrypt and wrap a session key
13345 *
13346 * @param {module:type/oid} oid - Elliptic curve object identifier
13347 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
13348 * @param {Uint8Array} data - Unpadded session key data
13349 * @param {Uint8Array} Q - Recipient public key
13350 * @param {Uint8Array} fingerprint - Recipient fingerprint
13351 * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
13352 * @async
13353 */
13354async function encrypt$2(oid, kdfParams, data, Q, fingerprint) {
13355 const m = encode$1(data);
13356
13357 const curve = new Curve(oid);
13358 const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
13359 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
13360 const { keySize } = getCipher(kdfParams.cipher);
13361 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);
13362 const wrappedKey = wrap(Z, m);
13363 return { publicKey, wrappedKey };
13364}
13365
13366/**
13367 * Generate ECDHE secret from private key and public part of ephemeral key
13368 *
13369 * @param {Curve} curve - Elliptic curve object
13370 * @param {Uint8Array} V - Public part of ephemeral key
13371 * @param {Uint8Array} Q - Recipient public key
13372 * @param {Uint8Array} d - Recipient private key
13373 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13374 * @async
13375 */
13376async function genPrivateEphemeralKey(curve, V, Q, d) {
13377 if (d.length !== curve.payloadSize) {
13378 const privateKey = new Uint8Array(curve.payloadSize);
13379 privateKey.set(d, curve.payloadSize - d.length);
13380 d = privateKey;
13381 }
13382 switch (curve.type) {
13383 case 'curve25519': {
13384 const secretKey = d.slice().reverse();
13385 const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1));
13386 return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
13387 }
13388 case 'web':
13389 if (curve.web && util.getWebCrypto()) {
13390 try {
13391 return await webPrivateEphemeralKey(curve, V, Q, d);
13392 } catch (err) {
13393 util.printDebugError(err);
13394 }
13395 }
13396 break;
13397 case 'node':
13398 return nodePrivateEphemeralKey(curve, V, d);
13399 }
13400 return ellipticPrivateEphemeralKey(curve, V, d);
13401}
13402
13403/**
13404 * Decrypt and unwrap the value derived from session key
13405 *
13406 * @param {module:type/oid} oid - Elliptic curve object identifier
13407 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
13408 * @param {Uint8Array} V - Public part of ephemeral key
13409 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
13410 * @param {Uint8Array} Q - Recipient public key
13411 * @param {Uint8Array} d - Recipient private key
13412 * @param {Uint8Array} fingerprint - Recipient fingerprint
13413 * @returns {Promise<Uint8Array>} Value derived from session key.
13414 * @async
13415 */
13416async function decrypt$2(oid, kdfParams, V, C, Q, d, fingerprint) {
13417 const curve = new Curve(oid);
13418 const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
13419 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
13420 const { keySize } = getCipher(kdfParams.cipher);
13421 let err;
13422 for (let i = 0; i < 3; i++) {
13423 try {
13424 // Work around old go crypto bug and old OpenPGP.js bug, respectively.
13425 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);
13426 return decode$1(unwrap(Z, C));
13427 } catch (e) {
13428 err = e;
13429 }
13430 }
13431 throw err;
13432}
13433
13434/**
13435 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
13436 *
13437 * @param {Curve} curve - Elliptic curve object
13438 * @param {Uint8Array} V - Public part of ephemeral key
13439 * @param {Uint8Array} Q - Recipient public key
13440 * @param {Uint8Array} d - Recipient private key
13441 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13442 * @async
13443 */
13444async function webPrivateEphemeralKey(curve, V, Q, d) {
13445 const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d);
13446 let privateKey = webCrypto$4.importKey(
13447 'jwk',
13448 recipient,
13449 {
13450 name: 'ECDH',
13451 namedCurve: curve.web.web
13452 },
13453 true,
13454 ['deriveKey', 'deriveBits']
13455 );
13456 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);
13457 let sender = webCrypto$4.importKey(
13458 'jwk',
13459 jwk,
13460 {
13461 name: 'ECDH',
13462 namedCurve: curve.web.web
13463 },
13464 true,
13465 []
13466 );
13467 [privateKey, sender] = await Promise.all([privateKey, sender]);
13468 let S = webCrypto$4.deriveBits(
13469 {
13470 name: 'ECDH',
13471 namedCurve: curve.web.web,
13472 public: sender
13473 },
13474 privateKey,
13475 curve.web.sharedSize
13476 );
13477 let secret = webCrypto$4.exportKey(
13478 'jwk',
13479 privateKey
13480 );
13481 [S, secret] = await Promise.all([S, secret]);
13482 const sharedKey = new Uint8Array(S);
13483 const secretKey = b64ToUint8Array(secret.d);
13484 return { secretKey, sharedKey };
13485}
13486
13487/**
13488 * Generate ECDHE ephemeral key and secret from public key using webCrypto
13489 *
13490 * @param {Curve} curve - Elliptic curve object
13491 * @param {Uint8Array} Q - Recipient public key
13492 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13493 * @async
13494 */
13495async function webPublicEphemeralKey(curve, Q) {
13496 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);
13497 let keyPair = webCrypto$4.generateKey(
13498 {
13499 name: 'ECDH',
13500 namedCurve: curve.web.web
13501 },
13502 true,
13503 ['deriveKey', 'deriveBits']
13504 );
13505 let recipient = webCrypto$4.importKey(
13506 'jwk',
13507 jwk,
13508 {
13509 name: 'ECDH',
13510 namedCurve: curve.web.web
13511 },
13512 false,
13513 []
13514 );
13515 [keyPair, recipient] = await Promise.all([keyPair, recipient]);
13516 let s = webCrypto$4.deriveBits(
13517 {
13518 name: 'ECDH',
13519 namedCurve: curve.web.web,
13520 public: recipient
13521 },
13522 keyPair.privateKey,
13523 curve.web.sharedSize
13524 );
13525 let p = webCrypto$4.exportKey(
13526 'jwk',
13527 keyPair.publicKey
13528 );
13529 [s, p] = await Promise.all([s, p]);
13530 const sharedKey = new Uint8Array(s);
13531 const publicKey = new Uint8Array(jwkToRawPublic(p));
13532 return { publicKey, sharedKey };
13533}
13534
13535/**
13536 * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
13537 *
13538 * @param {Curve} curve - Elliptic curve object
13539 * @param {Uint8Array} V - Public part of ephemeral key
13540 * @param {Uint8Array} d - Recipient private key
13541 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13542 * @async
13543 */
13544async function ellipticPrivateEphemeralKey(curve, V, d) {
13545 const indutnyCurve = await getIndutnyCurve(curve.name);
13546 V = keyFromPublic(indutnyCurve, V);
13547 d = keyFromPrivate(indutnyCurve, d);
13548 const secretKey = new Uint8Array(d.getPrivate());
13549 const S = d.derive(V.getPublic());
13550 const len = indutnyCurve.curve.p.byteLength();
13551 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
13552 return { secretKey, sharedKey };
13553}
13554
13555/**
13556 * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
13557 *
13558 * @param {Curve} curve - Elliptic curve object
13559 * @param {Uint8Array} Q - Recipient public key
13560 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13561 * @async
13562 */
13563async function ellipticPublicEphemeralKey(curve, Q) {
13564 const indutnyCurve = await getIndutnyCurve(curve.name);
13565 const v = await curve.genKeyPair();
13566 Q = keyFromPublic(indutnyCurve, Q);
13567 const V = keyFromPrivate(indutnyCurve, v.privateKey);
13568 const publicKey = v.publicKey;
13569 const S = V.derive(Q.getPublic());
13570 const len = indutnyCurve.curve.p.byteLength();
13571 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
13572 return { publicKey, sharedKey };
13573}
13574
13575/**
13576 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
13577 *
13578 * @param {Curve} curve - Elliptic curve object
13579 * @param {Uint8Array} V - Public part of ephemeral key
13580 * @param {Uint8Array} d - Recipient private key
13581 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13582 * @async
13583 */
13584async function nodePrivateEphemeralKey(curve, V, d) {
13585 const recipient = nodeCrypto$5.createECDH(curve.node.node);
13586 recipient.setPrivateKey(d);
13587 const sharedKey = new Uint8Array(recipient.computeSecret(V));
13588 const secretKey = new Uint8Array(recipient.getPrivateKey());
13589 return { secretKey, sharedKey };
13590}
13591
13592/**
13593 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
13594 *
13595 * @param {Curve} curve - Elliptic curve object
13596 * @param {Uint8Array} Q - Recipient public key
13597 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13598 * @async
13599 */
13600async function nodePublicEphemeralKey(curve, Q) {
13601 const sender = nodeCrypto$5.createECDH(curve.node.node);
13602 sender.generateKeys();
13603 const sharedKey = new Uint8Array(sender.computeSecret(Q));
13604 const publicKey = new Uint8Array(sender.getPublicKey());
13605 return { publicKey, sharedKey };
13606}
13607
13608var ecdh = /*#__PURE__*/Object.freeze({
13609 __proto__: null,
13610 validateParams: validateParams$4,
13611 encrypt: encrypt$2,
13612 decrypt: decrypt$2
13613});
13614
13615// OpenPGP.js - An OpenPGP implementation in javascript
13616
13617var elliptic = /*#__PURE__*/Object.freeze({
13618 __proto__: null,
13619 Curve: Curve,
13620 ecdh: ecdh,
13621 ecdsa: ecdsa,
13622 eddsa: eddsa,
13623 generate: generate$1,
13624 getPreferredHashAlgo: getPreferredHashAlgo
13625});
13626
13627// GPG4Browsers - An OpenPGP implementation in javascript
13628
13629/*
13630 TODO regarding the hash function, read:
13631 https://tools.ietf.org/html/rfc4880#section-13.6
13632 https://tools.ietf.org/html/rfc4880#section-14
13633*/
13634
13635/**
13636 * DSA Sign function
13637 * @param {Integer} hashAlgo
13638 * @param {Uint8Array} hashed
13639 * @param {Uint8Array} g
13640 * @param {Uint8Array} p
13641 * @param {Uint8Array} q
13642 * @param {Uint8Array} x
13643 * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}
13644 * @async
13645 */
13646async function sign$3(hashAlgo, hashed, g, p, q, x) {
13647 const BigInteger = await util.getBigInteger();
13648 const one = new BigInteger(1);
13649 p = new BigInteger(p);
13650 q = new BigInteger(q);
13651 g = new BigInteger(g);
13652 x = new BigInteger(x);
13653
13654 let k;
13655 let r;
13656 let s;
13657 let t;
13658 g = g.mod(p);
13659 x = x.mod(q);
13660 // If the output size of the chosen hash is larger than the number of
13661 // bits of q, the hash result is truncated to fit by taking the number
13662 // of leftmost bits equal to the number of bits of q. This (possibly
13663 // truncated) hash function result is treated as a number and used
13664 // directly in the DSA signature algorithm.
13665 const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);
13666 // FIPS-186-4, section 4.6:
13667 // The values of r and s shall be checked to determine if r = 0 or s = 0.
13668 // If either r = 0 or s = 0, a new value of k shall be generated, and the
13669 // signature shall be recalculated. It is extremely unlikely that r = 0
13670 // or s = 0 if signatures are generated properly.
13671 while (true) {
13672 // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
13673 k = await getRandomBigInteger(one, q); // returns in [1, q-1]
13674 r = g.modExp(k, p).imod(q); // (g**k mod p) mod q
13675 if (r.isZero()) {
13676 continue;
13677 }
13678 const xr = x.mul(r).imod(q);
13679 t = h.add(xr).imod(q); // H(m) + x*r mod q
13680 s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q
13681 if (s.isZero()) {
13682 continue;
13683 }
13684 break;
13685 }
13686 return {
13687 r: r.toUint8Array('be', q.byteLength()),
13688 s: s.toUint8Array('be', q.byteLength())
13689 };
13690}
13691
13692/**
13693 * DSA Verify function
13694 * @param {Integer} hashAlgo
13695 * @param {Uint8Array} r
13696 * @param {Uint8Array} s
13697 * @param {Uint8Array} hashed
13698 * @param {Uint8Array} g
13699 * @param {Uint8Array} p
13700 * @param {Uint8Array} q
13701 * @param {Uint8Array} y
13702 * @returns {boolean}
13703 * @async
13704 */
13705async function verify$3(hashAlgo, r, s, hashed, g, p, q, y) {
13706 const BigInteger = await util.getBigInteger();
13707 const zero = new BigInteger(0);
13708 r = new BigInteger(r);
13709 s = new BigInteger(s);
13710
13711 p = new BigInteger(p);
13712 q = new BigInteger(q);
13713 g = new BigInteger(g);
13714 y = new BigInteger(y);
13715
13716 if (r.lte(zero) || r.gte(q) ||
13717 s.lte(zero) || s.gte(q)) {
13718 util.printDebug('invalid DSA Signature');
13719 return false;
13720 }
13721 const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);
13722 const w = s.modInv(q); // s**-1 mod q
13723 if (w.isZero()) {
13724 util.printDebug('invalid DSA Signature');
13725 return false;
13726 }
13727
13728 g = g.mod(p);
13729 y = y.mod(p);
13730 const u1 = h.mul(w).imod(q); // H(m) * w mod q
13731 const u2 = r.mul(w).imod(q); // r * w mod q
13732 const t1 = g.modExp(u1, p); // g**u1 mod p
13733 const t2 = y.modExp(u2, p); // y**u2 mod p
13734 const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q
13735 return v.equal(r);
13736}
13737
13738/**
13739 * Validate DSA parameters
13740 * @param {Uint8Array} p - DSA prime
13741 * @param {Uint8Array} q - DSA group order
13742 * @param {Uint8Array} g - DSA sub-group generator
13743 * @param {Uint8Array} y - DSA public key
13744 * @param {Uint8Array} x - DSA private key
13745 * @returns {Promise<Boolean>} Whether params are valid.
13746 * @async
13747 */
13748async function validateParams$5(p, q, g, y, x) {
13749 const BigInteger = await util.getBigInteger();
13750 p = new BigInteger(p);
13751 q = new BigInteger(q);
13752 g = new BigInteger(g);
13753 y = new BigInteger(y);
13754 const one = new BigInteger(1);
13755 // Check that 1 < g < p
13756 if (g.lte(one) || g.gte(p)) {
13757 return false;
13758 }
13759
13760 /**
13761 * Check that subgroup order q divides p-1
13762 */
13763 if (!p.dec().mod(q).isZero()) {
13764 return false;
13765 }
13766
13767 /**
13768 * g has order q
13769 * Check that g ** q = 1 mod p
13770 */
13771 if (!g.modExp(q, p).isOne()) {
13772 return false;
13773 }
13774
13775 /**
13776 * Check q is large and probably prime (we mainly want to avoid small factors)
13777 */
13778 const qSize = new BigInteger(q.bitLength());
13779 const n150 = new BigInteger(150);
13780 if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {
13781 return false;
13782 }
13783
13784 /**
13785 * Re-derive public key y' = g ** x mod p
13786 * Expect y == y'
13787 *
13788 * Blinded exponentiation computes g**{rq + x} to compare to y
13789 */
13790 x = new BigInteger(x);
13791 const two = new BigInteger(2);
13792 const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q
13793 const rqx = q.mul(r).add(x);
13794 if (!y.equal(g.modExp(rqx, p))) {
13795 return false;
13796 }
13797
13798 return true;
13799}
13800
13801var dsa = /*#__PURE__*/Object.freeze({
13802 __proto__: null,
13803 sign: sign$3,
13804 verify: verify$3,
13805 validateParams: validateParams$5
13806});
13807
13808/**
13809 * @fileoverview Asymmetric cryptography functions
13810 * @module crypto/public_key
13811 * @private
13812 */
13813
13814var publicKey = {
13815 /** @see module:crypto/public_key/rsa */
13816 rsa: rsa,
13817 /** @see module:crypto/public_key/elgamal */
13818 elgamal: elgamal,
13819 /** @see module:crypto/public_key/elliptic */
13820 elliptic: elliptic,
13821 /** @see module:crypto/public_key/dsa */
13822 dsa: dsa,
13823 /** @see tweetnacl */
13824 nacl: naclFastLight
13825};
13826
13827// OpenPGP.js - An OpenPGP implementation in javascript
13828
13829class ECDHSymmetricKey {
13830 constructor(data) {
13831 if (typeof data === 'undefined') {
13832 data = new Uint8Array([]);
13833 } else if (util.isString(data)) {
13834 data = util.stringToUint8Array(data);
13835 } else {
13836 data = new Uint8Array(data);
13837 }
13838 this.data = data;
13839 }
13840
13841 /**
13842 * Read an ECDHSymmetricKey from an Uint8Array
13843 * @param {Uint8Array} input - Where to read the encoded symmetric key from
13844 * @returns {Number} Number of read bytes.
13845 */
13846 read(input) {
13847 if (input.length >= 1) {
13848 const length = input[0];
13849 if (input.length >= 1 + length) {
13850 this.data = input.subarray(1, 1 + length);
13851 return 1 + this.data.length;
13852 }
13853 }
13854 throw new Error('Invalid symmetric key');
13855 }
13856
13857 /**
13858 * Write an ECDHSymmetricKey as an Uint8Array
13859 * @returns {Uint8Array} An array containing the value
13860 */
13861 write() {
13862 return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
13863 }
13864}
13865
13866// OpenPGP.js - An OpenPGP implementation in javascript
13867// Copyright (C) 2015-2016 Decentral
13868//
13869// This library is free software; you can redistribute it and/or
13870// modify it under the terms of the GNU Lesser General Public
13871// License as published by the Free Software Foundation; either
13872// version 3.0 of the License, or (at your option) any later version.
13873//
13874// This library is distributed in the hope that it will be useful,
13875// but WITHOUT ANY WARRANTY; without even the implied warranty of
13876// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13877// Lesser General Public License for more details.
13878//
13879// You should have received a copy of the GNU Lesser General Public
13880// License along with this library; if not, write to the Free Software
13881// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
13882
13883/**
13884 * Implementation of type KDF parameters
13885 *
13886 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
13887 * A key derivation function (KDF) is necessary to implement the EC
13888 * encryption. The Concatenation Key Derivation Function (Approved
13889 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
13890 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
13891 * @module type/kdf_params
13892 * @private
13893 */
13894
13895class KDFParams {
13896 /**
13897 * @param {enums.hash} hash - Hash algorithm
13898 * @param {enums.symmetric} cipher - Symmetric algorithm
13899 */
13900 constructor(data) {
13901 if (data) {
13902 const { hash, cipher } = data;
13903 this.hash = hash;
13904 this.cipher = cipher;
13905 } else {
13906 this.hash = null;
13907 this.cipher = null;
13908 }
13909 }
13910
13911 /**
13912 * Read KDFParams from an Uint8Array
13913 * @param {Uint8Array} input - Where to read the KDFParams from
13914 * @returns {Number} Number of read bytes.
13915 */
13916 read(input) {
13917 if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
13918 throw new Error('Cannot read KDFParams');
13919 }
13920 this.hash = input[2];
13921 this.cipher = input[3];
13922 return 4;
13923 }
13924
13925 /**
13926 * Write KDFParams to an Uint8Array
13927 * @returns {Uint8Array} Array with the KDFParams value
13928 */
13929 write() {
13930 return new Uint8Array([3, 1, this.hash, this.cipher]);
13931 }
13932}
13933
13934// GPG4Browsers - An OpenPGP implementation in javascript
13935
13936/**
13937 * Encrypts data using specified algorithm and public key parameters.
13938 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
13939 * @param {module:enums.publicKey} algo - Public key algorithm
13940 * @param {Object} publicParams - Algorithm-specific public key parameters
13941 * @param {Uint8Array} data - Data to be encrypted
13942 * @param {Uint8Array} fingerprint - Recipient fingerprint
13943 * @returns {Promise<Object>} Encrypted session key parameters.
13944 * @async
13945 */
13946async function publicKeyEncrypt(algo, publicParams, data, fingerprint) {
13947 switch (algo) {
13948 case enums.publicKey.rsaEncrypt:
13949 case enums.publicKey.rsaEncryptSign: {
13950 const { n, e } = publicParams;
13951 const c = await publicKey.rsa.encrypt(data, n, e);
13952 return { c };
13953 }
13954 case enums.publicKey.elgamal: {
13955 const { p, g, y } = publicParams;
13956 return publicKey.elgamal.encrypt(data, p, g, y);
13957 }
13958 case enums.publicKey.ecdh: {
13959 const { oid, Q, kdfParams } = publicParams;
13960 const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(
13961 oid, kdfParams, data, Q, fingerprint);
13962 return { V, C: new ECDHSymmetricKey(C) };
13963 }
13964 default:
13965 return [];
13966 }
13967}
13968
13969/**
13970 * Decrypts data using specified algorithm and private key parameters.
13971 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
13972 * @param {module:enums.publicKey} algo - Public key algorithm
13973 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
13974 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
13975 * @param {Object} sessionKeyParams - Encrypted session key parameters
13976 * @param {Uint8Array} fingerprint - Recipient fingerprint
13977 * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing
13978 * (needed for constant-time processing in RSA and ElGamal)
13979 * @returns {Promise<Uint8Array>} Decrypted data.
13980 * @throws {Error} on sensitive decryption error, unless `randomPayload` is given
13981 * @async
13982 */
13983async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {
13984 switch (algo) {
13985 case enums.publicKey.rsaEncryptSign:
13986 case enums.publicKey.rsaEncrypt: {
13987 const { c } = sessionKeyParams;
13988 const { n, e } = publicKeyParams;
13989 const { d, p, q, u } = privateKeyParams;
13990 return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);
13991 }
13992 case enums.publicKey.elgamal: {
13993 const { c1, c2 } = sessionKeyParams;
13994 const p = publicKeyParams.p;
13995 const x = privateKeyParams.x;
13996 return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);
13997 }
13998 case enums.publicKey.ecdh: {
13999 const { oid, Q, kdfParams } = publicKeyParams;
14000 const { d } = privateKeyParams;
14001 const { V, C } = sessionKeyParams;
14002 return publicKey.elliptic.ecdh.decrypt(
14003 oid, kdfParams, V, C.data, Q, d, fingerprint);
14004 }
14005 default:
14006 throw new Error('Unknown public key encryption algorithm.');
14007 }
14008}
14009
14010/**
14011 * Parse public key material in binary form to get the key parameters
14012 * @param {module:enums.publicKey} algo - The key algorithm
14013 * @param {Uint8Array} bytes - The key material to parse
14014 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
14015 */
14016function parsePublicKeyParams(algo, bytes) {
14017 let read = 0;
14018 switch (algo) {
14019 case enums.publicKey.rsaEncrypt:
14020 case enums.publicKey.rsaEncryptSign:
14021 case enums.publicKey.rsaSign: {
14022 const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;
14023 const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;
14024 return { read, publicParams: { n, e } };
14025 }
14026 case enums.publicKey.dsa: {
14027 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14028 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14029 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14030 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14031 return { read, publicParams: { p, q, g, y } };
14032 }
14033 case enums.publicKey.elgamal: {
14034 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14035 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14036 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14037 return { read, publicParams: { p, g, y } };
14038 }
14039 case enums.publicKey.ecdsa: {
14040 const oid = new OID(); read += oid.read(bytes);
14041 checkSupportedCurve(oid);
14042 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14043 return { read: read, publicParams: { oid, Q } };
14044 }
14045 case enums.publicKey.eddsa: {
14046 const oid = new OID(); read += oid.read(bytes);
14047 checkSupportedCurve(oid);
14048 let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14049 Q = util.leftPad(Q, 33);
14050 return { read: read, publicParams: { oid, Q } };
14051 }
14052 case enums.publicKey.ecdh: {
14053 const oid = new OID(); read += oid.read(bytes);
14054 checkSupportedCurve(oid);
14055 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14056 const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));
14057 return { read: read, publicParams: { oid, Q, kdfParams } };
14058 }
14059 default:
14060 throw new UnsupportedError('Unknown public key encryption algorithm.');
14061 }
14062}
14063
14064/**
14065 * Parse private key material in binary form to get the key parameters
14066 * @param {module:enums.publicKey} algo - The key algorithm
14067 * @param {Uint8Array} bytes - The key material to parse
14068 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
14069 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
14070 */
14071function parsePrivateKeyParams(algo, bytes, publicParams) {
14072 let read = 0;
14073 switch (algo) {
14074 case enums.publicKey.rsaEncrypt:
14075 case enums.publicKey.rsaEncryptSign:
14076 case enums.publicKey.rsaSign: {
14077 const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14078 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14079 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14080 const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;
14081 return { read, privateParams: { d, p, q, u } };
14082 }
14083 case enums.publicKey.dsa:
14084 case enums.publicKey.elgamal: {
14085 const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;
14086 return { read, privateParams: { x } };
14087 }
14088 case enums.publicKey.ecdsa:
14089 case enums.publicKey.ecdh: {
14090 const curve = new Curve(publicParams.oid);
14091 let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14092 d = util.leftPad(d, curve.payloadSize);
14093 return { read, privateParams: { d } };
14094 }
14095 case enums.publicKey.eddsa: {
14096 const curve = new Curve(publicParams.oid);
14097 let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;
14098 seed = util.leftPad(seed, curve.payloadSize);
14099 return { read, privateParams: { seed } };
14100 }
14101 default:
14102 throw new UnsupportedError('Unknown public key encryption algorithm.');
14103 }
14104}
14105
14106/** Returns the types comprising the encrypted session key of an algorithm
14107 * @param {module:enums.publicKey} algo - The key algorithm
14108 * @param {Uint8Array} bytes - The key material to parse
14109 * @returns {Object} The session key parameters referenced by name.
14110 */
14111function parseEncSessionKeyParams(algo, bytes) {
14112 let read = 0;
14113 switch (algo) {
14114 // Algorithm-Specific Fields for RSA encrypted session keys:
14115 // - MPI of RSA encrypted value m**e mod n.
14116 case enums.publicKey.rsaEncrypt:
14117 case enums.publicKey.rsaEncryptSign: {
14118 const c = util.readMPI(bytes.subarray(read));
14119 return { c };
14120 }
14121
14122 // Algorithm-Specific Fields for Elgamal encrypted session keys:
14123 // - MPI of Elgamal value g**k mod p
14124 // - MPI of Elgamal value m * y**k mod p
14125 case enums.publicKey.elgamal: {
14126 const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;
14127 const c2 = util.readMPI(bytes.subarray(read));
14128 return { c1, c2 };
14129 }
14130 // Algorithm-Specific Fields for ECDH encrypted session keys:
14131 // - MPI containing the ephemeral key used to establish the shared secret
14132 // - ECDH Symmetric Key
14133 case enums.publicKey.ecdh: {
14134 const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;
14135 const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read));
14136 return { V, C };
14137 }
14138 default:
14139 throw new UnsupportedError('Unknown public key encryption algorithm.');
14140 }
14141}
14142
14143/**
14144 * Convert params to MPI and serializes them in the proper order
14145 * @param {module:enums.publicKey} algo - The public key algorithm
14146 * @param {Object} params - The key parameters indexed by name
14147 * @returns {Uint8Array} The array containing the MPIs.
14148 */
14149function serializeParams(algo, params) {
14150 const orderedParams = Object.keys(params).map(name => {
14151 const param = params[name];
14152 return util.isUint8Array(param) ? util.uint8ArrayToMPI(param) : param.write();
14153 });
14154 return util.concatUint8Array(orderedParams);
14155}
14156
14157/**
14158 * Generate algorithm-specific key parameters
14159 * @param {module:enums.publicKey} algo - The public key algorithm
14160 * @param {Integer} bits - Bit length for RSA keys
14161 * @param {module:type/oid} oid - Object identifier for ECC keys
14162 * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.
14163 * @async
14164 */
14165function generateParams(algo, bits, oid) {
14166 switch (algo) {
14167 case enums.publicKey.rsaEncrypt:
14168 case enums.publicKey.rsaEncryptSign:
14169 case enums.publicKey.rsaSign: {
14170 return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({
14171 privateParams: { d, p, q, u },
14172 publicParams: { n, e }
14173 }));
14174 }
14175 case enums.publicKey.ecdsa:
14176 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
14177 privateParams: { d: secret },
14178 publicParams: { oid: new OID(oid), Q }
14179 }));
14180 case enums.publicKey.eddsa:
14181 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
14182 privateParams: { seed: secret },
14183 publicParams: { oid: new OID(oid), Q }
14184 }));
14185 case enums.publicKey.ecdh:
14186 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({
14187 privateParams: { d: secret },
14188 publicParams: {
14189 oid: new OID(oid),
14190 Q,
14191 kdfParams: new KDFParams({ hash, cipher })
14192 }
14193 }));
14194 case enums.publicKey.dsa:
14195 case enums.publicKey.elgamal:
14196 throw new Error('Unsupported algorithm for key generation.');
14197 default:
14198 throw new Error('Unknown public key algorithm.');
14199 }
14200}
14201
14202/**
14203 * Validate algorithm-specific key parameters
14204 * @param {module:enums.publicKey} algo - The public key algorithm
14205 * @param {Object} publicParams - Algorithm-specific public key parameters
14206 * @param {Object} privateParams - Algorithm-specific private key parameters
14207 * @returns {Promise<Boolean>} Whether the parameters are valid.
14208 * @async
14209 */
14210async function validateParams$6(algo, publicParams, privateParams) {
14211 if (!publicParams || !privateParams) {
14212 throw new Error('Missing key parameters');
14213 }
14214 switch (algo) {
14215 case enums.publicKey.rsaEncrypt:
14216 case enums.publicKey.rsaEncryptSign:
14217 case enums.publicKey.rsaSign: {
14218 const { n, e } = publicParams;
14219 const { d, p, q, u } = privateParams;
14220 return publicKey.rsa.validateParams(n, e, d, p, q, u);
14221 }
14222 case enums.publicKey.dsa: {
14223 const { p, q, g, y } = publicParams;
14224 const { x } = privateParams;
14225 return publicKey.dsa.validateParams(p, q, g, y, x);
14226 }
14227 case enums.publicKey.elgamal: {
14228 const { p, g, y } = publicParams;
14229 const { x } = privateParams;
14230 return publicKey.elgamal.validateParams(p, g, y, x);
14231 }
14232 case enums.publicKey.ecdsa:
14233 case enums.publicKey.ecdh: {
14234 const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];
14235 const { oid, Q } = publicParams;
14236 const { d } = privateParams;
14237 return algoModule.validateParams(oid, Q, d);
14238 }
14239 case enums.publicKey.eddsa: {
14240 const { oid, Q } = publicParams;
14241 const { seed } = privateParams;
14242 return publicKey.elliptic.eddsa.validateParams(oid, Q, seed);
14243 }
14244 default:
14245 throw new Error('Unknown public key algorithm.');
14246 }
14247}
14248
14249/**
14250 * Generates a random byte prefix for the specified algorithm
14251 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
14252 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
14253 * @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
14254 * @async
14255 */
14256async function getPrefixRandom(algo) {
14257 const { blockSize } = getCipher(algo);
14258 const prefixrandom = await getRandomBytes(blockSize);
14259 const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
14260 return util.concat([prefixrandom, repeat]);
14261}
14262
14263/**
14264 * Generating a session key for the specified symmetric algorithm
14265 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
14266 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
14267 * @returns {Promise<Uint8Array>} Random bytes as a string to be used as a key.
14268 * @async
14269 */
14270function generateSessionKey(algo) {
14271 const { keySize } = getCipher(algo);
14272 return getRandomBytes(keySize);
14273}
14274
14275/**
14276 * Get implementation of the given AEAD mode
14277 * @param {enums.aead} algo
14278 * @returns {Object}
14279 * @throws {Error} on invalid algo
14280 */
14281function getAEADMode(algo) {
14282 const algoName = enums.read(enums.aead, algo);
14283 return mode[algoName];
14284}
14285
14286/**
14287 * Get implementation of the given cipher
14288 * @param {enums.symmetric} algo
14289 * @returns {Object}
14290 * @throws {Error} on invalid algo
14291 */
14292function getCipher(algo) {
14293 const algoName = enums.read(enums.symmetric, algo);
14294 return cipher[algoName];
14295}
14296
14297/**
14298 * Check whether the given curve OID is supported
14299 * @param {module:type/oid} oid - EC object identifier
14300 * @throws {UnsupportedError} if curve is not supported
14301 */
14302function checkSupportedCurve(oid) {
14303 try {
14304 oid.getName();
14305 } catch (e) {
14306 throw new UnsupportedError('Unknown curve OID');
14307 }
14308}
14309
14310var crypto$1 = /*#__PURE__*/Object.freeze({
14311 __proto__: null,
14312 publicKeyEncrypt: publicKeyEncrypt,
14313 publicKeyDecrypt: publicKeyDecrypt,
14314 parsePublicKeyParams: parsePublicKeyParams,
14315 parsePrivateKeyParams: parsePrivateKeyParams,
14316 parseEncSessionKeyParams: parseEncSessionKeyParams,
14317 serializeParams: serializeParams,
14318 generateParams: generateParams,
14319 validateParams: validateParams$6,
14320 getPrefixRandom: getPrefixRandom,
14321 generateSessionKey: generateSessionKey,
14322 getAEADMode: getAEADMode,
14323 getCipher: getCipher
14324});
14325
14326// Modified by ProtonTech AG
14327
14328const webCrypto$5 = util.getWebCrypto();
14329const nodeCrypto$6 = util.getNodeCrypto();
14330
14331const knownAlgos = nodeCrypto$6 ? nodeCrypto$6.getCiphers() : [];
14332const nodeAlgos = {
14333 idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
14334 tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
14335 cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
14336 blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
14337 aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
14338 aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
14339 aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
14340 /* twofish is not implemented in OpenSSL */
14341};
14342
14343/**
14344 * CFB encryption
14345 * @param {enums.symmetric} algo - block cipher algorithm
14346 * @param {Uint8Array} key
14347 * @param {MaybeStream<Uint8Array>} plaintext
14348 * @param {Uint8Array} iv
14349 * @param {Object} config - full configuration, defaults to openpgp.config
14350 * @returns MaybeStream<Uint8Array>
14351 */
14352async function encrypt$3(algo, key, plaintext, iv, config) {
14353 const algoName = enums.read(enums.symmetric, algo);
14354 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
14355 return nodeEncrypt$1(algo, key, plaintext, iv);
14356 }
14357 if (algoName.substr(0, 3) === 'aes') {
14358 return aesEncrypt(algo, key, plaintext, iv, config);
14359 }
14360
14361 const cipherfn = new cipher[algoName](key);
14362 const block_size = cipherfn.blockSize;
14363
14364 const blockc = iv.slice();
14365 let pt = new Uint8Array();
14366 const process = chunk => {
14367 if (chunk) {
14368 pt = util.concatUint8Array([pt, chunk]);
14369 }
14370 const ciphertext = new Uint8Array(pt.length);
14371 let i;
14372 let j = 0;
14373 while (chunk ? pt.length >= block_size : pt.length) {
14374 const encblock = cipherfn.encrypt(blockc);
14375 for (i = 0; i < block_size; i++) {
14376 blockc[i] = pt[i] ^ encblock[i];
14377 ciphertext[j++] = blockc[i];
14378 }
14379 pt = pt.subarray(block_size);
14380 }
14381 return ciphertext.subarray(0, j);
14382 };
14383 return transform(plaintext, process, process);
14384}
14385
14386/**
14387 * CFB decryption
14388 * @param {enums.symmetric} algo - block cipher algorithm
14389 * @param {Uint8Array} key
14390 * @param {MaybeStream<Uint8Array>} ciphertext
14391 * @param {Uint8Array} iv
14392 * @returns MaybeStream<Uint8Array>
14393 */
14394async function decrypt$3(algo, key, ciphertext, iv) {
14395 const algoName = enums.read(enums.symmetric, algo);
14396 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
14397 return nodeDecrypt$1(algo, key, ciphertext, iv);
14398 }
14399 if (algoName.substr(0, 3) === 'aes') {
14400 return aesDecrypt(algo, key, ciphertext, iv);
14401 }
14402
14403 const cipherfn = new cipher[algoName](key);
14404 const block_size = cipherfn.blockSize;
14405
14406 let blockp = iv;
14407 let ct = new Uint8Array();
14408 const process = chunk => {
14409 if (chunk) {
14410 ct = util.concatUint8Array([ct, chunk]);
14411 }
14412 const plaintext = new Uint8Array(ct.length);
14413 let i;
14414 let j = 0;
14415 while (chunk ? ct.length >= block_size : ct.length) {
14416 const decblock = cipherfn.encrypt(blockp);
14417 blockp = ct;
14418 for (i = 0; i < block_size; i++) {
14419 plaintext[j++] = blockp[i] ^ decblock[i];
14420 }
14421 ct = ct.subarray(block_size);
14422 }
14423 return plaintext.subarray(0, j);
14424 };
14425 return transform(ciphertext, process, process);
14426}
14427
14428function aesEncrypt(algo, key, pt, iv, config) {
14429 if (
14430 util.getWebCrypto() &&
14431 key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
14432 !util.isStream(pt) &&
14433 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
14434 ) { // Web Crypto
14435 return webEncrypt(algo, key, pt, iv);
14436 }
14437 // asm.js fallback
14438 const cfb = new AES_CFB(key, iv);
14439 return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
14440}
14441
14442function aesDecrypt(algo, key, ct, iv) {
14443 if (util.isStream(ct)) {
14444 const cfb = new AES_CFB(key, iv);
14445 return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
14446 }
14447 return AES_CFB.decrypt(ct, key, iv);
14448}
14449
14450function xorMut(a, b) {
14451 for (let i = 0; i < a.length; i++) {
14452 a[i] = a[i] ^ b[i];
14453 }
14454}
14455
14456async function webEncrypt(algo, key, pt, iv) {
14457 const ALGO = 'AES-CBC';
14458 const _key = await webCrypto$5.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
14459 const { blockSize } = getCipher(algo);
14460 const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);
14461 const ct = new Uint8Array(await webCrypto$5.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);
14462 xorMut(ct, pt);
14463 return ct;
14464}
14465
14466function nodeEncrypt$1(algo, key, pt, iv) {
14467 const algoName = enums.read(enums.symmetric, algo);
14468 const cipherObj = new nodeCrypto$6.createCipheriv(nodeAlgos[algoName], key, iv);
14469 return transform(pt, value => new Uint8Array(cipherObj.update(value)));
14470}
14471
14472function nodeDecrypt$1(algo, key, ct, iv) {
14473 const algoName = enums.read(enums.symmetric, algo);
14474 const decipherObj = new nodeCrypto$6.createDecipheriv(nodeAlgos[algoName], key, iv);
14475 return transform(ct, value => new Uint8Array(decipherObj.update(value)));
14476}
14477
14478var cfb = /*#__PURE__*/Object.freeze({
14479 __proto__: null,
14480 encrypt: encrypt$3,
14481 decrypt: decrypt$3
14482});
14483
14484class AES_CTR {
14485 static encrypt(data, key, nonce) {
14486 return new AES_CTR(key, nonce).encrypt(data);
14487 }
14488 static decrypt(data, key, nonce) {
14489 return new AES_CTR(key, nonce).encrypt(data);
14490 }
14491 constructor(key, nonce, aes) {
14492 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
14493 delete this.aes.padding;
14494 this.AES_CTR_set_options(nonce);
14495 }
14496 encrypt(data) {
14497 const r1 = this.aes.AES_Encrypt_process(data);
14498 const r2 = this.aes.AES_Encrypt_finish();
14499 return joinBytes(r1, r2);
14500 }
14501 decrypt(data) {
14502 const r1 = this.aes.AES_Encrypt_process(data);
14503 const r2 = this.aes.AES_Encrypt_finish();
14504 return joinBytes(r1, r2);
14505 }
14506 AES_CTR_set_options(nonce, counter, size) {
14507 let { asm } = this.aes.acquire_asm();
14508 if (size !== undefined) {
14509 if (size < 8 || size > 48)
14510 throw new IllegalArgumentError('illegal counter size');
14511 let mask = Math.pow(2, size) - 1;
14512 asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);
14513 }
14514 else {
14515 size = 48;
14516 asm.set_mask(0, 0, 0xffff, 0xffffffff);
14517 }
14518 if (nonce !== undefined) {
14519 let len = nonce.length;
14520 if (!len || len > 16)
14521 throw new IllegalArgumentError('illegal nonce size');
14522 let view = new DataView(new ArrayBuffer(16));
14523 new Uint8Array(view.buffer).set(nonce);
14524 asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
14525 }
14526 else {
14527 throw new Error('nonce is required');
14528 }
14529 if (counter !== undefined) {
14530 if (counter < 0 || counter >= Math.pow(2, size))
14531 throw new IllegalArgumentError('illegal counter value');
14532 asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);
14533 }
14534 }
14535}
14536
14537class AES_CBC {
14538 static encrypt(data, key, padding = true, iv) {
14539 return new AES_CBC(key, iv, padding).encrypt(data);
14540 }
14541 static decrypt(data, key, padding = true, iv) {
14542 return new AES_CBC(key, iv, padding).decrypt(data);
14543 }
14544 constructor(key, iv, padding = true, aes) {
14545 this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');
14546 }
14547 encrypt(data) {
14548 const r1 = this.aes.AES_Encrypt_process(data);
14549 const r2 = this.aes.AES_Encrypt_finish();
14550 return joinBytes(r1, r2);
14551 }
14552 decrypt(data) {
14553 const r1 = this.aes.AES_Decrypt_process(data);
14554 const r2 = this.aes.AES_Decrypt_finish();
14555 return joinBytes(r1, r2);
14556 }
14557}
14558
14559/**
14560 * @fileoverview This module implements AES-CMAC on top of
14561 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
14562 * @module crypto/cmac
14563 * @private
14564 */
14565
14566const webCrypto$6 = util.getWebCrypto();
14567const nodeCrypto$7 = util.getNodeCrypto();
14568
14569
14570/**
14571 * This implementation of CMAC is based on the description of OMAC in
14572 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
14573 * document:
14574 *
14575 * We have made a small modification to the OMAC algorithm as it was
14576 * originally presented, changing one of its two constants.
14577 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
14578 * multiplicative inverse of 2) in the original definition of OMAC [14].
14579 * The OMAC authors indicate that they will promulgate this modification
14580 * [15], which slightly simplifies implementations.
14581 */
14582
14583const blockLength = 16;
14584
14585
14586/**
14587 * xor `padding` into the end of `data`. This function implements "the
14588 * operation xor→ [which] xors the shorter string into the end of longer
14589 * one". Since data is always as least as long as padding, we can
14590 * simplify the implementation.
14591 * @param {Uint8Array} data
14592 * @param {Uint8Array} padding
14593 */
14594function rightXORMut(data, padding) {
14595 const offset = data.length - blockLength;
14596 for (let i = 0; i < blockLength; i++) {
14597 data[i + offset] ^= padding[i];
14598 }
14599 return data;
14600}
14601
14602function pad(data, padding, padding2) {
14603 // if |M| in {n, 2n, 3n, ...}
14604 if (data.length && data.length % blockLength === 0) {
14605 // then return M xor→ B,
14606 return rightXORMut(data, padding);
14607 }
14608 // else return (M || 10^(n−1−(|M| mod n))) xor→ P
14609 const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength));
14610 padded.set(data);
14611 padded[data.length] = 0b10000000;
14612 return rightXORMut(padded, padding2);
14613}
14614
14615const zeroBlock = new Uint8Array(blockLength);
14616
14617async function CMAC(key) {
14618 const cbc = await CBC(key);
14619
14620 // L ← E_K(0^n); B ← 2L; P ← 4L
14621 const padding = util.double(await cbc(zeroBlock));
14622 const padding2 = util.double(padding);
14623
14624 return async function(data) {
14625 // return CBC_K(pad(M; B, P))
14626 return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
14627 };
14628}
14629
14630async function CBC(key) {
14631 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
14632 key = await webCrypto$6.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
14633 return async function(pt) {
14634 const ct = await webCrypto$6.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
14635 return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
14636 };
14637 }
14638 if (util.getNodeCrypto()) { // Node crypto library
14639 return async function(pt) {
14640 const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
14641 const ct = en.update(pt);
14642 return new Uint8Array(ct);
14643 };
14644 }
14645 // asm.js fallback
14646 return async function(pt) {
14647 return AES_CBC.encrypt(pt, key, false, zeroBlock);
14648 };
14649}
14650
14651// OpenPGP.js - An OpenPGP implementation in javascript
14652
14653const webCrypto$7 = util.getWebCrypto();
14654const nodeCrypto$8 = util.getNodeCrypto();
14655const Buffer$1 = util.getNodeBuffer();
14656
14657
14658const blockLength$1 = 16;
14659const ivLength = blockLength$1;
14660const tagLength = blockLength$1;
14661
14662const zero = new Uint8Array(blockLength$1);
14663const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1;
14664const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2;
14665
14666async function OMAC(key) {
14667 const cmac = await CMAC(key);
14668 return function(t, message) {
14669 return cmac(util.concatUint8Array([t, message]));
14670 };
14671}
14672
14673async function CTR(key) {
14674 if (
14675 util.getWebCrypto() &&
14676 key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
14677 ) {
14678 key = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
14679 return async function(pt, iv) {
14680 const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt);
14681 return new Uint8Array(ct);
14682 };
14683 }
14684 if (util.getNodeCrypto()) { // Node crypto library
14685 return async function(pt, iv) {
14686 const en = new nodeCrypto$8.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
14687 const ct = Buffer$1.concat([en.update(pt), en.final()]);
14688 return new Uint8Array(ct);
14689 };
14690 }
14691 // asm.js fallback
14692 return async function(pt, iv) {
14693 return AES_CTR.encrypt(pt, key, iv);
14694 };
14695}
14696
14697
14698/**
14699 * Class to en/decrypt using EAX mode.
14700 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
14701 * @param {Uint8Array} key - The encryption key
14702 */
14703async function EAX(cipher, key) {
14704 if (cipher !== enums.symmetric.aes128 &&
14705 cipher !== enums.symmetric.aes192 &&
14706 cipher !== enums.symmetric.aes256) {
14707 throw new Error('EAX mode supports only AES cipher');
14708 }
14709
14710 const [
14711 omac,
14712 ctr
14713 ] = await Promise.all([
14714 OMAC(key),
14715 CTR(key)
14716 ]);
14717
14718 return {
14719 /**
14720 * Encrypt plaintext input.
14721 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
14722 * @param {Uint8Array} nonce - The nonce (16 bytes)
14723 * @param {Uint8Array} adata - Associated data to sign
14724 * @returns {Promise<Uint8Array>} The ciphertext output.
14725 */
14726 encrypt: async function(plaintext, nonce, adata) {
14727 const [
14728 omacNonce,
14729 omacAdata
14730 ] = await Promise.all([
14731 omac(zero, nonce),
14732 omac(one, adata)
14733 ]);
14734 const ciphered = await ctr(plaintext, omacNonce);
14735 const omacCiphered = await omac(two, ciphered);
14736 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
14737 for (let i = 0; i < tagLength; i++) {
14738 tag[i] ^= omacAdata[i] ^ omacNonce[i];
14739 }
14740 return util.concatUint8Array([ciphered, tag]);
14741 },
14742
14743 /**
14744 * Decrypt ciphertext input.
14745 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
14746 * @param {Uint8Array} nonce - The nonce (16 bytes)
14747 * @param {Uint8Array} adata - Associated data to verify
14748 * @returns {Promise<Uint8Array>} The plaintext output.
14749 */
14750 decrypt: async function(ciphertext, nonce, adata) {
14751 if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
14752 const ciphered = ciphertext.subarray(0, -tagLength);
14753 const ctTag = ciphertext.subarray(-tagLength);
14754 const [
14755 omacNonce,
14756 omacAdata,
14757 omacCiphered
14758 ] = await Promise.all([
14759 omac(zero, nonce),
14760 omac(one, adata),
14761 omac(two, ciphered)
14762 ]);
14763 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
14764 for (let i = 0; i < tagLength; i++) {
14765 tag[i] ^= omacAdata[i] ^ omacNonce[i];
14766 }
14767 if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
14768 const plaintext = await ctr(ciphered, omacNonce);
14769 return plaintext;
14770 }
14771 };
14772}
14773
14774
14775/**
14776 * 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}.
14777 * @param {Uint8Array} iv - The initialization vector (16 bytes)
14778 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
14779 */
14780EAX.getNonce = function(iv, chunkIndex) {
14781 const nonce = iv.slice();
14782 for (let i = 0; i < chunkIndex.length; i++) {
14783 nonce[8 + i] ^= chunkIndex[i];
14784 }
14785 return nonce;
14786};
14787
14788EAX.blockLength = blockLength$1;
14789EAX.ivLength = ivLength;
14790EAX.tagLength = tagLength;
14791
14792// OpenPGP.js - An OpenPGP implementation in javascript
14793
14794const blockLength$2 = 16;
14795const ivLength$1 = 15;
14796
14797// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
14798// While OCB [RFC7253] allows the authentication tag length to be of any
14799// number up to 128 bits long, this document requires a fixed
14800// authentication tag length of 128 bits (16 octets) for simplicity.
14801const tagLength$1 = 16;
14802
14803
14804function ntz(n) {
14805 let ntz = 0;
14806 for (let i = 1; (n & i) === 0; i <<= 1) {
14807 ntz++;
14808 }
14809 return ntz;
14810}
14811
14812function xorMut$1(S, T) {
14813 for (let i = 0; i < S.length; i++) {
14814 S[i] ^= T[i];
14815 }
14816 return S;
14817}
14818
14819function xor(S, T) {
14820 return xorMut$1(S.slice(), T);
14821}
14822
14823const zeroBlock$1 = new Uint8Array(blockLength$2);
14824const one$1 = new Uint8Array([1]);
14825
14826/**
14827 * Class to en/decrypt using OCB mode.
14828 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
14829 * @param {Uint8Array} key - The encryption key
14830 */
14831async function OCB(cipher$1, key) {
14832
14833 let maxNtz = 0;
14834 let encipher;
14835 let decipher;
14836 let mask;
14837
14838 constructKeyVariables(cipher$1, key);
14839
14840 function constructKeyVariables(cipher$1, key) {
14841 const cipherName = enums.read(enums.symmetric, cipher$1);
14842 const aes = new cipher[cipherName](key);
14843 encipher = aes.encrypt.bind(aes);
14844 decipher = aes.decrypt.bind(aes);
14845
14846 const mask_x = encipher(zeroBlock$1);
14847 const mask_$ = util.double(mask_x);
14848 mask = [];
14849 mask[0] = util.double(mask_$);
14850
14851
14852 mask.x = mask_x;
14853 mask.$ = mask_$;
14854 }
14855
14856 function extendKeyVariables(text, adata) {
14857 const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1;
14858 for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
14859 mask[i] = util.double(mask[i - 1]);
14860 }
14861 maxNtz = newMaxNtz;
14862 }
14863
14864 function hash(adata) {
14865 if (!adata.length) {
14866 // Fast path
14867 return zeroBlock$1;
14868 }
14869
14870 //
14871 // Consider A as a sequence of 128-bit blocks
14872 //
14873 const m = adata.length / blockLength$2 | 0;
14874
14875 const offset = new Uint8Array(blockLength$2);
14876 const sum = new Uint8Array(blockLength$2);
14877 for (let i = 0; i < m; i++) {
14878 xorMut$1(offset, mask[ntz(i + 1)]);
14879 xorMut$1(sum, encipher(xor(offset, adata)));
14880 adata = adata.subarray(blockLength$2);
14881 }
14882
14883 //
14884 // Process any final partial block; compute final hash value
14885 //
14886 if (adata.length) {
14887 xorMut$1(offset, mask.x);
14888
14889 const cipherInput = new Uint8Array(blockLength$2);
14890 cipherInput.set(adata, 0);
14891 cipherInput[adata.length] = 0b10000000;
14892 xorMut$1(cipherInput, offset);
14893
14894 xorMut$1(sum, encipher(cipherInput));
14895 }
14896
14897 return sum;
14898 }
14899
14900 /**
14901 * Encrypt/decrypt data.
14902 * @param {encipher|decipher} fn - Encryption/decryption block cipher function
14903 * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
14904 * @param {Uint8Array} nonce - The nonce (15 bytes)
14905 * @param {Uint8Array} adata - Associated data to sign
14906 * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases.
14907 */
14908 function crypt(fn, text, nonce, adata) {
14909 //
14910 // Consider P as a sequence of 128-bit blocks
14911 //
14912 const m = text.length / blockLength$2 | 0;
14913
14914 //
14915 // Key-dependent variables
14916 //
14917 extendKeyVariables(text, adata);
14918
14919 //
14920 // Nonce-dependent and per-encryption variables
14921 //
14922 // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
14923 // Note: We assume here that tagLength mod 16 == 0.
14924 const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]);
14925 // bottom = str2num(Nonce[123..128])
14926 const bottom = paddedNonce[blockLength$2 - 1] & 0b111111;
14927 // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
14928 paddedNonce[blockLength$2 - 1] &= 0b11000000;
14929 const kTop = encipher(paddedNonce);
14930 // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
14931 const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
14932 // Offset_0 = Stretch[1+bottom..128+bottom]
14933 const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
14934 // Checksum_0 = zeros(128)
14935 const checksum = new Uint8Array(blockLength$2);
14936
14937 const ct = new Uint8Array(text.length + tagLength$1);
14938
14939 //
14940 // Process any whole blocks
14941 //
14942 let i;
14943 let pos = 0;
14944 for (i = 0; i < m; i++) {
14945 // Offset_i = Offset_{i-1} xor L_{ntz(i)}
14946 xorMut$1(offset, mask[ntz(i + 1)]);
14947 // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
14948 // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
14949 ct.set(xorMut$1(fn(xor(offset, text)), offset), pos);
14950 // Checksum_i = Checksum_{i-1} xor P_i
14951 xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos));
14952
14953 text = text.subarray(blockLength$2);
14954 pos += blockLength$2;
14955 }
14956
14957 //
14958 // Process any final partial block and compute raw tag
14959 //
14960 if (text.length) {
14961 // Offset_* = Offset_m xor L_*
14962 xorMut$1(offset, mask.x);
14963 // Pad = ENCIPHER(K, Offset_*)
14964 const padding = encipher(offset);
14965 // C_* = P_* xor Pad[1..bitlen(P_*)]
14966 ct.set(xor(text, padding), pos);
14967
14968 // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
14969 const xorInput = new Uint8Array(blockLength$2);
14970 xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0);
14971 xorInput[text.length] = 0b10000000;
14972 xorMut$1(checksum, xorInput);
14973 pos += text.length;
14974 }
14975 // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
14976 const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata));
14977
14978 //
14979 // Assemble ciphertext
14980 //
14981 // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
14982 ct.set(tag, pos);
14983 return ct;
14984 }
14985
14986
14987 return {
14988 /**
14989 * Encrypt plaintext input.
14990 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
14991 * @param {Uint8Array} nonce - The nonce (15 bytes)
14992 * @param {Uint8Array} adata - Associated data to sign
14993 * @returns {Promise<Uint8Array>} The ciphertext output.
14994 */
14995 encrypt: async function(plaintext, nonce, adata) {
14996 return crypt(encipher, plaintext, nonce, adata);
14997 },
14998
14999 /**
15000 * Decrypt ciphertext input.
15001 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
15002 * @param {Uint8Array} nonce - The nonce (15 bytes)
15003 * @param {Uint8Array} adata - Associated data to sign
15004 * @returns {Promise<Uint8Array>} The ciphertext output.
15005 */
15006 decrypt: async function(ciphertext, nonce, adata) {
15007 if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext');
15008
15009 const tag = ciphertext.subarray(-tagLength$1);
15010 ciphertext = ciphertext.subarray(0, -tagLength$1);
15011
15012 const crypted = crypt(decipher, ciphertext, nonce, adata);
15013 // if (Tag[1..TAGLEN] == T)
15014 if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) {
15015 return crypted.subarray(0, -tagLength$1);
15016 }
15017 throw new Error('Authentication tag mismatch');
15018 }
15019 };
15020}
15021
15022
15023/**
15024 * 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}.
15025 * @param {Uint8Array} iv - The initialization vector (15 bytes)
15026 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
15027 */
15028OCB.getNonce = function(iv, chunkIndex) {
15029 const nonce = iv.slice();
15030 for (let i = 0; i < chunkIndex.length; i++) {
15031 nonce[7 + i] ^= chunkIndex[i];
15032 }
15033 return nonce;
15034};
15035
15036OCB.blockLength = blockLength$2;
15037OCB.ivLength = ivLength$1;
15038OCB.tagLength = tagLength$1;
15039
15040const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
15041class AES_GCM {
15042 constructor(key, nonce, adata, tagSize = 16, aes) {
15043 this.tagSize = tagSize;
15044 this.gamma0 = 0;
15045 this.counter = 1;
15046 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
15047 let { asm, heap } = this.aes.acquire_asm();
15048 // Init GCM
15049 asm.gcm_init();
15050 // Tag size
15051 if (this.tagSize < 4 || this.tagSize > 16)
15052 throw new IllegalArgumentError('illegal tagSize value');
15053 // Nonce
15054 const noncelen = nonce.length || 0;
15055 const noncebuf = new Uint8Array(16);
15056 if (noncelen !== 12) {
15057 this._gcm_mac_process(nonce);
15058 heap[0] = 0;
15059 heap[1] = 0;
15060 heap[2] = 0;
15061 heap[3] = 0;
15062 heap[4] = 0;
15063 heap[5] = 0;
15064 heap[6] = 0;
15065 heap[7] = 0;
15066 heap[8] = 0;
15067 heap[9] = 0;
15068 heap[10] = 0;
15069 heap[11] = noncelen >>> 29;
15070 heap[12] = (noncelen >>> 21) & 255;
15071 heap[13] = (noncelen >>> 13) & 255;
15072 heap[14] = (noncelen >>> 5) & 255;
15073 heap[15] = (noncelen << 3) & 255;
15074 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15075 asm.get_iv(AES_asm.HEAP_DATA);
15076 asm.set_iv(0, 0, 0, 0);
15077 noncebuf.set(heap.subarray(0, 16));
15078 }
15079 else {
15080 noncebuf.set(nonce);
15081 noncebuf[15] = 1;
15082 }
15083 const nonceview = new DataView(noncebuf.buffer);
15084 this.gamma0 = nonceview.getUint32(12);
15085 asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
15086 asm.set_mask(0, 0, 0, 0xffffffff);
15087 // Associated data
15088 if (adata !== undefined) {
15089 if (adata.length > _AES_GCM_data_maxLength)
15090 throw new IllegalArgumentError('illegal adata length');
15091 if (adata.length) {
15092 this.adata = adata;
15093 this._gcm_mac_process(adata);
15094 }
15095 else {
15096 this.adata = undefined;
15097 }
15098 }
15099 else {
15100 this.adata = undefined;
15101 }
15102 // Counter
15103 if (this.counter < 1 || this.counter > 0xffffffff)
15104 throw new RangeError('counter must be a positive 32-bit integer');
15105 asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);
15106 }
15107 static encrypt(cleartext, key, nonce, adata, tagsize) {
15108 return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
15109 }
15110 static decrypt(ciphertext, key, nonce, adata, tagsize) {
15111 return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
15112 }
15113 encrypt(data) {
15114 return this.AES_GCM_encrypt(data);
15115 }
15116 decrypt(data) {
15117 return this.AES_GCM_decrypt(data);
15118 }
15119 AES_GCM_Encrypt_process(data) {
15120 let dpos = 0;
15121 let dlen = data.length || 0;
15122 let { asm, heap } = this.aes.acquire_asm();
15123 let counter = this.counter;
15124 let pos = this.aes.pos;
15125 let len = this.aes.len;
15126 let rpos = 0;
15127 let rlen = (len + dlen) & -16;
15128 let wlen = 0;
15129 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
15130 throw new RangeError('counter overflow');
15131 const result = new Uint8Array(rlen);
15132 while (dlen > 0) {
15133 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
15134 len += wlen;
15135 dpos += wlen;
15136 dlen -= wlen;
15137 wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);
15138 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
15139 if (wlen)
15140 result.set(heap.subarray(pos, pos + wlen), rpos);
15141 counter += wlen >>> 4;
15142 rpos += wlen;
15143 if (wlen < len) {
15144 pos += wlen;
15145 len -= wlen;
15146 }
15147 else {
15148 pos = 0;
15149 len = 0;
15150 }
15151 }
15152 this.counter = counter;
15153 this.aes.pos = pos;
15154 this.aes.len = len;
15155 return result;
15156 }
15157 AES_GCM_Encrypt_finish() {
15158 let { asm, heap } = this.aes.acquire_asm();
15159 let counter = this.counter;
15160 let tagSize = this.tagSize;
15161 let adata = this.adata;
15162 let pos = this.aes.pos;
15163 let len = this.aes.len;
15164 const result = new Uint8Array(len + tagSize);
15165 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);
15166 if (len)
15167 result.set(heap.subarray(pos, pos + len));
15168 let i = len;
15169 for (; i & 15; i++)
15170 heap[pos + i] = 0;
15171 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
15172 const alen = adata !== undefined ? adata.length : 0;
15173 const clen = ((counter - 1) << 4) + len;
15174 heap[0] = 0;
15175 heap[1] = 0;
15176 heap[2] = 0;
15177 heap[3] = alen >>> 29;
15178 heap[4] = alen >>> 21;
15179 heap[5] = (alen >>> 13) & 255;
15180 heap[6] = (alen >>> 5) & 255;
15181 heap[7] = (alen << 3) & 255;
15182 heap[8] = heap[9] = heap[10] = 0;
15183 heap[11] = clen >>> 29;
15184 heap[12] = (clen >>> 21) & 255;
15185 heap[13] = (clen >>> 13) & 255;
15186 heap[14] = (clen >>> 5) & 255;
15187 heap[15] = (clen << 3) & 255;
15188 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15189 asm.get_iv(AES_asm.HEAP_DATA);
15190 asm.set_counter(0, 0, 0, this.gamma0);
15191 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
15192 result.set(heap.subarray(0, tagSize), len);
15193 this.counter = 1;
15194 this.aes.pos = 0;
15195 this.aes.len = 0;
15196 return result;
15197 }
15198 AES_GCM_Decrypt_process(data) {
15199 let dpos = 0;
15200 let dlen = data.length || 0;
15201 let { asm, heap } = this.aes.acquire_asm();
15202 let counter = this.counter;
15203 let tagSize = this.tagSize;
15204 let pos = this.aes.pos;
15205 let len = this.aes.len;
15206 let rpos = 0;
15207 let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;
15208 let tlen = len + dlen - rlen;
15209 let wlen = 0;
15210 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
15211 throw new RangeError('counter overflow');
15212 const result = new Uint8Array(rlen);
15213 while (dlen > tlen) {
15214 wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);
15215 len += wlen;
15216 dpos += wlen;
15217 dlen -= wlen;
15218 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
15219 wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);
15220 if (wlen)
15221 result.set(heap.subarray(pos, pos + wlen), rpos);
15222 counter += wlen >>> 4;
15223 rpos += wlen;
15224 pos = 0;
15225 len = 0;
15226 }
15227 if (dlen > 0) {
15228 len += _heap_write(heap, 0, data, dpos, dlen);
15229 }
15230 this.counter = counter;
15231 this.aes.pos = pos;
15232 this.aes.len = len;
15233 return result;
15234 }
15235 AES_GCM_Decrypt_finish() {
15236 let { asm, heap } = this.aes.acquire_asm();
15237 let tagSize = this.tagSize;
15238 let adata = this.adata;
15239 let counter = this.counter;
15240 let pos = this.aes.pos;
15241 let len = this.aes.len;
15242 let rlen = len - tagSize;
15243 if (len < tagSize)
15244 throw new IllegalStateError('authentication tag not found');
15245 const result = new Uint8Array(rlen);
15246 const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
15247 let i = rlen;
15248 for (; i & 15; i++)
15249 heap[pos + i] = 0;
15250 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
15251 asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);
15252 if (rlen)
15253 result.set(heap.subarray(pos, pos + rlen));
15254 const alen = adata !== undefined ? adata.length : 0;
15255 const clen = ((counter - 1) << 4) + len - tagSize;
15256 heap[0] = 0;
15257 heap[1] = 0;
15258 heap[2] = 0;
15259 heap[3] = alen >>> 29;
15260 heap[4] = alen >>> 21;
15261 heap[5] = (alen >>> 13) & 255;
15262 heap[6] = (alen >>> 5) & 255;
15263 heap[7] = (alen << 3) & 255;
15264 heap[8] = heap[9] = heap[10] = 0;
15265 heap[11] = clen >>> 29;
15266 heap[12] = (clen >>> 21) & 255;
15267 heap[13] = (clen >>> 13) & 255;
15268 heap[14] = (clen >>> 5) & 255;
15269 heap[15] = (clen << 3) & 255;
15270 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15271 asm.get_iv(AES_asm.HEAP_DATA);
15272 asm.set_counter(0, 0, 0, this.gamma0);
15273 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
15274 let acheck = 0;
15275 for (let i = 0; i < tagSize; ++i)
15276 acheck |= atag[i] ^ heap[i];
15277 if (acheck)
15278 throw new SecurityError('data integrity check failed');
15279 this.counter = 1;
15280 this.aes.pos = 0;
15281 this.aes.len = 0;
15282 return result;
15283 }
15284 AES_GCM_decrypt(data) {
15285 const result1 = this.AES_GCM_Decrypt_process(data);
15286 const result2 = this.AES_GCM_Decrypt_finish();
15287 const result = new Uint8Array(result1.length + result2.length);
15288 if (result1.length)
15289 result.set(result1);
15290 if (result2.length)
15291 result.set(result2, result1.length);
15292 return result;
15293 }
15294 AES_GCM_encrypt(data) {
15295 const result1 = this.AES_GCM_Encrypt_process(data);
15296 const result2 = this.AES_GCM_Encrypt_finish();
15297 const result = new Uint8Array(result1.length + result2.length);
15298 if (result1.length)
15299 result.set(result1);
15300 if (result2.length)
15301 result.set(result2, result1.length);
15302 return result;
15303 }
15304 _gcm_mac_process(data) {
15305 let { asm, heap } = this.aes.acquire_asm();
15306 let dpos = 0;
15307 let dlen = data.length || 0;
15308 let wlen = 0;
15309 while (dlen > 0) {
15310 wlen = _heap_write(heap, 0, data, dpos, dlen);
15311 dpos += wlen;
15312 dlen -= wlen;
15313 while (wlen & 15)
15314 heap[wlen++] = 0;
15315 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);
15316 }
15317 }
15318}
15319
15320// OpenPGP.js - An OpenPGP implementation in javascript
15321
15322const webCrypto$8 = util.getWebCrypto();
15323const nodeCrypto$9 = util.getNodeCrypto();
15324const Buffer$2 = util.getNodeBuffer();
15325
15326const blockLength$3 = 16;
15327const ivLength$2 = 12; // size of the IV in bytes
15328const tagLength$2 = 16; // size of the tag in bytes
15329const ALGO = 'AES-GCM';
15330
15331/**
15332 * Class to en/decrypt using GCM mode.
15333 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
15334 * @param {Uint8Array} key - The encryption key
15335 */
15336async function GCM(cipher, key) {
15337 if (cipher !== enums.symmetric.aes128 &&
15338 cipher !== enums.symmetric.aes192 &&
15339 cipher !== enums.symmetric.aes256) {
15340 throw new Error('GCM mode supports only AES cipher');
15341 }
15342
15343 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
15344 const _key = await webCrypto$8.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
15345
15346 return {
15347 encrypt: async function(pt, iv, adata = new Uint8Array()) {
15348 if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages
15349 return AES_GCM.encrypt(pt, key, iv, adata);
15350 }
15351 const ct = await webCrypto$8.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt);
15352 return new Uint8Array(ct);
15353 },
15354
15355 decrypt: async function(ct, iv, adata = new Uint8Array()) {
15356 if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages
15357 return AES_GCM.decrypt(ct, key, iv, adata);
15358 }
15359 const pt = await webCrypto$8.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct);
15360 return new Uint8Array(pt);
15361 }
15362 };
15363 }
15364
15365 if (util.getNodeCrypto()) { // Node crypto library
15366 return {
15367 encrypt: async function(pt, iv, adata = new Uint8Array()) {
15368 const en = new nodeCrypto$9.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
15369 en.setAAD(adata);
15370 const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
15371 return new Uint8Array(ct);
15372 },
15373
15374 decrypt: async function(ct, iv, adata = new Uint8Array()) {
15375 const de = new nodeCrypto$9.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
15376 de.setAAD(adata);
15377 de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext
15378 const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]);
15379 return new Uint8Array(pt);
15380 }
15381 };
15382 }
15383
15384 return {
15385 encrypt: async function(pt, iv, adata) {
15386 return AES_GCM.encrypt(pt, key, iv, adata);
15387 },
15388
15389 decrypt: async function(ct, iv, adata) {
15390 return AES_GCM.decrypt(ct, key, iv, adata);
15391 }
15392 };
15393}
15394
15395
15396/**
15397 * Get GCM nonce. Note: this operation is not defined by the standard.
15398 * A future version of the standard may define GCM mode differently,
15399 * hopefully under a different ID (we use Private/Experimental algorithm
15400 * ID 100) so that we can maintain backwards compatibility.
15401 * @param {Uint8Array} iv - The initialization vector (12 bytes)
15402 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
15403 */
15404GCM.getNonce = function(iv, chunkIndex) {
15405 const nonce = iv.slice();
15406 for (let i = 0; i < chunkIndex.length; i++) {
15407 nonce[4 + i] ^= chunkIndex[i];
15408 }
15409 return nonce;
15410};
15411
15412GCM.blockLength = blockLength$3;
15413GCM.ivLength = ivLength$2;
15414GCM.tagLength = tagLength$2;
15415
15416/**
15417 * @fileoverview Cipher modes
15418 * @module crypto/mode
15419 * @private
15420 */
15421
15422var mode = {
15423 /** @see module:crypto/mode/cfb */
15424 cfb: cfb,
15425 /** @see module:crypto/mode/gcm */
15426 gcm: GCM,
15427 experimentalGCM: GCM,
15428 /** @see module:crypto/mode/eax */
15429 eax: EAX,
15430 /** @see module:crypto/mode/ocb */
15431 ocb: OCB
15432};
15433
15434/**
15435 * @fileoverview Provides functions for asymmetric signing and signature verification
15436 * @module crypto/signature
15437 * @private
15438 */
15439
15440/**
15441 * Parse signature in binary form to get the parameters.
15442 * The returned values are only padded for EdDSA, since in the other cases their expected length
15443 * depends on the key params, hence we delegate the padding to the signature verification function.
15444 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15445 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
15446 * @param {module:enums.publicKey} algo - Public key algorithm
15447 * @param {Uint8Array} signature - Data for which the signature was created
15448 * @returns {Promise<Object>} True if signature is valid.
15449 * @async
15450 */
15451function parseSignatureParams(algo, signature) {
15452 let read = 0;
15453 switch (algo) {
15454 // Algorithm-Specific Fields for RSA signatures:
15455 // - MPI of RSA signature value m**d mod n.
15456 case enums.publicKey.rsaEncryptSign:
15457 case enums.publicKey.rsaEncrypt:
15458 case enums.publicKey.rsaSign: {
15459 const s = util.readMPI(signature.subarray(read));
15460 // The signature needs to be the same length as the public key modulo n.
15461 // We pad s on signature verification, where we have access to n.
15462 return { s };
15463 }
15464 // Algorithm-Specific Fields for DSA or ECDSA signatures:
15465 // - MPI of DSA or ECDSA value r.
15466 // - MPI of DSA or ECDSA value s.
15467 case enums.publicKey.dsa:
15468 case enums.publicKey.ecdsa:
15469 {
15470 const r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15471 const s = util.readMPI(signature.subarray(read));
15472 return { r, s };
15473 }
15474 // Algorithm-Specific Fields for EdDSA signatures:
15475 // - MPI of an EC point r.
15476 // - EdDSA value s, in MPI, in the little endian representation
15477 case enums.publicKey.eddsa: {
15478 // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
15479 // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
15480 let r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15481 r = util.leftPad(r, 32);
15482 let s = util.readMPI(signature.subarray(read));
15483 s = util.leftPad(s, 32);
15484 return { r, s };
15485 }
15486 default:
15487 throw new UnsupportedError('Unknown signature algorithm.');
15488 }
15489}
15490
15491/**
15492 * Verifies the signature provided for data using specified algorithms and public key parameters.
15493 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15494 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15495 * for public key and hash algorithms.
15496 * @param {module:enums.publicKey} algo - Public key algorithm
15497 * @param {module:enums.hash} hashAlgo - Hash algorithm
15498 * @param {Object} signature - Named algorithm-specific signature parameters
15499 * @param {Object} publicParams - Algorithm-specific public key parameters
15500 * @param {Uint8Array} data - Data for which the signature was created
15501 * @param {Uint8Array} hashed - The hashed data
15502 * @returns {Promise<Boolean>} True if signature is valid.
15503 * @async
15504 */
15505async function verify$4(algo, hashAlgo, signature, publicParams, data, hashed) {
15506 switch (algo) {
15507 case enums.publicKey.rsaEncryptSign:
15508 case enums.publicKey.rsaEncrypt:
15509 case enums.publicKey.rsaSign: {
15510 const { n, e } = publicParams;
15511 const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
15512 return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);
15513 }
15514 case enums.publicKey.dsa: {
15515 const { g, p, q, y } = publicParams;
15516 const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
15517 return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);
15518 }
15519 case enums.publicKey.ecdsa: {
15520 const { oid, Q } = publicParams;
15521 const curveSize = new publicKey.elliptic.Curve(oid).payloadSize;
15522 // padding needed for webcrypto
15523 const r = util.leftPad(signature.r, curveSize);
15524 const s = util.leftPad(signature.s, curveSize);
15525 return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);
15526 }
15527 case enums.publicKey.eddsa: {
15528 const { oid, Q } = publicParams;
15529 // signature already padded on parsing
15530 return publicKey.elliptic.eddsa.verify(oid, hashAlgo, signature, data, Q, hashed);
15531 }
15532 default:
15533 throw new Error('Unknown signature algorithm.');
15534 }
15535}
15536
15537/**
15538 * Creates a signature on data using specified algorithms and private key parameters.
15539 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15540 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15541 * for public key and hash algorithms.
15542 * @param {module:enums.publicKey} algo - Public key algorithm
15543 * @param {module:enums.hash} hashAlgo - Hash algorithm
15544 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
15545 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
15546 * @param {Uint8Array} data - Data to be signed
15547 * @param {Uint8Array} hashed - The hashed data
15548 * @returns {Promise<Object>} Signature Object containing named signature parameters.
15549 * @async
15550 */
15551async function sign$4(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
15552 if (!publicKeyParams || !privateKeyParams) {
15553 throw new Error('Missing key parameters');
15554 }
15555 switch (algo) {
15556 case enums.publicKey.rsaEncryptSign:
15557 case enums.publicKey.rsaEncrypt:
15558 case enums.publicKey.rsaSign: {
15559 const { n, e } = publicKeyParams;
15560 const { d, p, q, u } = privateKeyParams;
15561 const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);
15562 return { s };
15563 }
15564 case enums.publicKey.dsa: {
15565 const { g, p, q } = publicKeyParams;
15566 const { x } = privateKeyParams;
15567 return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);
15568 }
15569 case enums.publicKey.elgamal: {
15570 throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
15571 }
15572 case enums.publicKey.ecdsa: {
15573 const { oid, Q } = publicKeyParams;
15574 const { d } = privateKeyParams;
15575 return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);
15576 }
15577 case enums.publicKey.eddsa: {
15578 const { oid, Q } = publicKeyParams;
15579 const { seed } = privateKeyParams;
15580 return publicKey.elliptic.eddsa.sign(oid, hashAlgo, data, Q, seed, hashed);
15581 }
15582 default:
15583 throw new Error('Unknown signature algorithm.');
15584 }
15585}
15586
15587var signature = /*#__PURE__*/Object.freeze({
15588 __proto__: null,
15589 parseSignatureParams: parseSignatureParams,
15590 verify: verify$4,
15591 sign: sign$4
15592});
15593
15594/**
15595 * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
15596 * @see module:crypto/crypto
15597 * @see module:crypto/signature
15598 * @see module:crypto/public_key
15599 * @see module:crypto/cipher
15600 * @see module:crypto/random
15601 * @see module:crypto/hash
15602 * @module crypto
15603 * @private
15604 */
15605
15606// TODO move cfb and gcm to cipher
15607const mod = {
15608 /** @see module:crypto/cipher */
15609 cipher: cipher,
15610 /** @see module:crypto/hash */
15611 hash: hash,
15612 /** @see module:crypto/mode */
15613 mode: mode,
15614 /** @see module:crypto/public_key */
15615 publicKey: publicKey,
15616 /** @see module:crypto/signature */
15617 signature: signature,
15618 /** @see module:crypto/random */
15619 random: random,
15620 /** @see module:crypto/pkcs1 */
15621 pkcs1: pkcs1,
15622 /** @see module:crypto/pkcs5 */
15623 pkcs5: pkcs5,
15624 /** @see module:crypto/aes_kw */
15625 aesKW: aesKW
15626};
15627
15628Object.assign(mod, crypto$1);
15629
15630var TYPED_OK = typeof Uint8Array !== "undefined" &&
15631 typeof Uint16Array !== "undefined" &&
15632 typeof Int32Array !== "undefined";
15633
15634
15635// reduce buffer size, avoiding mem copy
15636function shrinkBuf(buf, size) {
15637 if (buf.length === size) {
15638 return buf;
15639 }
15640 if (buf.subarray) {
15641 return buf.subarray(0, size);
15642 }
15643 buf.length = size;
15644 return buf;
15645}
15646
15647
15648const fnTyped = {
15649 arraySet: function (dest, src, src_offs, len, dest_offs) {
15650 if (src.subarray && dest.subarray) {
15651 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
15652 return;
15653 }
15654 // Fallback to ordinary array
15655 for (let i = 0; i < len; i++) {
15656 dest[dest_offs + i] = src[src_offs + i];
15657 }
15658 },
15659 // Join array of chunks to single array.
15660 flattenChunks: function (chunks) {
15661 let i, l, len, pos, chunk;
15662
15663 // calculate data length
15664 len = 0;
15665 for (i = 0, l = chunks.length; i < l; i++) {
15666 len += chunks[i].length;
15667 }
15668
15669 // join chunks
15670 const result = new Uint8Array(len);
15671 pos = 0;
15672 for (i = 0, l = chunks.length; i < l; i++) {
15673 chunk = chunks[i];
15674 result.set(chunk, pos);
15675 pos += chunk.length;
15676 }
15677
15678 return result;
15679 }
15680};
15681
15682const fnUntyped = {
15683 arraySet: function (dest, src, src_offs, len, dest_offs) {
15684 for (let i = 0; i < len; i++) {
15685 dest[dest_offs + i] = src[src_offs + i];
15686 }
15687 },
15688 // Join array of chunks to single array.
15689 flattenChunks: function (chunks) {
15690 return [].concat.apply([], chunks);
15691 }
15692};
15693
15694
15695// Enable/Disable typed arrays use, for testing
15696//
15697
15698let Buf8 = TYPED_OK ? Uint8Array : Array;
15699let Buf16 = TYPED_OK ? Uint16Array : Array;
15700let Buf32 = TYPED_OK ? Int32Array : Array;
15701let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;
15702let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;
15703
15704// (C) 1995-2013 Jean-loup Gailly and Mark Adler
15705// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15706//
15707// This software is provided 'as-is', without any express or implied
15708// warranty. In no event will the authors be held liable for any damages
15709// arising from the use of this software.
15710//
15711// Permission is granted to anyone to use this software for any purpose,
15712// including commercial applications, and to alter it and redistribute it
15713// freely, subject to the following restrictions:
15714//
15715// 1. The origin of this software must not be misrepresented; you must not
15716// claim that you wrote the original software. If you use this software
15717// in a product, an acknowledgment in the product documentation would be
15718// appreciated but is not required.
15719// 2. Altered source versions must be plainly marked as such, and must not be
15720// misrepresented as being the original software.
15721// 3. This notice may not be removed or altered from any source distribution.
15722
15723/* Allowed flush values; see deflate() and inflate() below for details */
15724const Z_NO_FLUSH = 0;
15725const Z_PARTIAL_FLUSH = 1;
15726const Z_SYNC_FLUSH = 2;
15727const Z_FULL_FLUSH = 3;
15728const Z_FINISH = 4;
15729const Z_BLOCK = 5;
15730const Z_TREES = 6;
15731
15732/* Return codes for the compression/decompression functions. Negative values
15733 * are errors, positive values are used for special but normal events.
15734 */
15735const Z_OK = 0;
15736const Z_STREAM_END = 1;
15737const Z_NEED_DICT = 2;
15738const Z_STREAM_ERROR = -2;
15739const Z_DATA_ERROR = -3;
15740//export const Z_MEM_ERROR = -4;
15741const Z_BUF_ERROR = -5;
15742const Z_DEFAULT_COMPRESSION = -1;
15743
15744
15745const Z_FILTERED = 1;
15746const Z_HUFFMAN_ONLY = 2;
15747const Z_RLE = 3;
15748const Z_FIXED = 4;
15749const Z_DEFAULT_STRATEGY = 0;
15750
15751/* Possible values of the data_type field (though see inflate()) */
15752const Z_BINARY = 0;
15753const Z_TEXT = 1;
15754//export const Z_ASCII = 1; // = Z_TEXT (deprecated)
15755const Z_UNKNOWN = 2;
15756
15757/* The deflate compression method */
15758const Z_DEFLATED = 8;
15759//export const Z_NULL = null // Use -1 or null inline, depending on var type
15760
15761/*============================================================================*/
15762
15763
15764function zero$1(buf) {
15765 let len = buf.length; while (--len >= 0) {
15766 buf[len] = 0;
15767 }
15768}
15769
15770// From zutil.h
15771
15772const STORED_BLOCK = 0;
15773const STATIC_TREES = 1;
15774const DYN_TREES = 2;
15775/* The three kinds of block type */
15776
15777const MIN_MATCH = 3;
15778const MAX_MATCH = 258;
15779/* The minimum and maximum match lengths */
15780
15781// From deflate.h
15782/* ===========================================================================
15783 * Internal compression state.
15784 */
15785
15786const LENGTH_CODES = 29;
15787/* number of length codes, not counting the special END_BLOCK code */
15788
15789const LITERALS = 256;
15790/* number of literal bytes 0..255 */
15791
15792const L_CODES = LITERALS + 1 + LENGTH_CODES;
15793/* number of Literal or Length codes, including the END_BLOCK code */
15794
15795const D_CODES = 30;
15796/* number of distance codes */
15797
15798const BL_CODES = 19;
15799/* number of codes used to transfer the bit lengths */
15800
15801const HEAP_SIZE = 2 * L_CODES + 1;
15802/* maximum heap size */
15803
15804const MAX_BITS = 15;
15805/* All codes must not exceed MAX_BITS bits */
15806
15807const Buf_size = 16;
15808/* size of bit buffer in bi_buf */
15809
15810
15811/* ===========================================================================
15812 * Constants
15813 */
15814
15815const MAX_BL_BITS = 7;
15816/* Bit length codes must not exceed MAX_BL_BITS bits */
15817
15818const END_BLOCK = 256;
15819/* end of block literal code */
15820
15821const REP_3_6 = 16;
15822/* repeat previous bit length 3-6 times (2 bits of repeat count) */
15823
15824const REPZ_3_10 = 17;
15825/* repeat a zero length 3-10 times (3 bits of repeat count) */
15826
15827const REPZ_11_138 = 18;
15828/* repeat a zero length 11-138 times (7 bits of repeat count) */
15829
15830/* eslint-disable comma-spacing,array-bracket-spacing */
15831const extra_lbits = /* extra bits for each length code */
15832 [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];
15833
15834const extra_dbits = /* extra bits for each distance code */
15835 [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];
15836
15837const extra_blbits = /* extra bits for each bit length code */
15838 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
15839
15840const bl_order =
15841 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
15842/* eslint-enable comma-spacing,array-bracket-spacing */
15843
15844/* The lengths of the bit length codes are sent in order of decreasing
15845 * probability, to avoid transmitting the lengths for unused bit length codes.
15846 */
15847
15848/* ===========================================================================
15849 * Local data. These are initialized only once.
15850 */
15851
15852// We pre-fill arrays with 0 to avoid uninitialized gaps
15853
15854const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
15855
15856// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
15857const static_ltree = new Array((L_CODES + 2) * 2);
15858zero$1(static_ltree);
15859/* The static literal tree. Since the bit lengths are imposed, there is no
15860 * need for the L_CODES extra codes used during heap construction. However
15861 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
15862 * below).
15863 */
15864
15865const static_dtree = new Array(D_CODES * 2);
15866zero$1(static_dtree);
15867/* The static distance tree. (Actually a trivial tree since all codes use
15868 * 5 bits.)
15869 */
15870
15871const _dist_code = new Array(DIST_CODE_LEN);
15872zero$1(_dist_code);
15873/* Distance codes. The first 256 values correspond to the distances
15874 * 3 .. 258, the last 256 values correspond to the top 8 bits of
15875 * the 15 bit distances.
15876 */
15877
15878const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
15879zero$1(_length_code);
15880/* length code for each normalized match length (0 == MIN_MATCH) */
15881
15882const base_length = new Array(LENGTH_CODES);
15883zero$1(base_length);
15884/* First normalized length for each code (0 = MIN_MATCH) */
15885
15886const base_dist = new Array(D_CODES);
15887zero$1(base_dist);
15888/* First normalized distance for each code (0 = distance of 1) */
15889
15890
15891function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
15892
15893 this.static_tree = static_tree; /* static tree or NULL */
15894 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
15895 this.extra_base = extra_base; /* base index for extra_bits */
15896 this.elems = elems; /* max number of elements in the tree */
15897 this.max_length = max_length; /* max bit length for the codes */
15898
15899 // show if `static_tree` has data or dummy - needed for monomorphic objects
15900 this.has_stree = static_tree && static_tree.length;
15901}
15902
15903
15904let static_l_desc;
15905let static_d_desc;
15906let static_bl_desc;
15907
15908
15909function TreeDesc(dyn_tree, stat_desc) {
15910 this.dyn_tree = dyn_tree; /* the dynamic tree */
15911 this.max_code = 0; /* largest code with non zero frequency */
15912 this.stat_desc = stat_desc; /* the corresponding static tree */
15913}
15914
15915
15916
15917function d_code(dist) {
15918 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
15919}
15920
15921
15922/* ===========================================================================
15923 * Output a short LSB first on the stream.
15924 * IN assertion: there is enough room in pendingBuf.
15925 */
15926function put_short(s, w) {
15927// put_byte(s, (uch)((w) & 0xff));
15928// put_byte(s, (uch)((ush)(w) >> 8));
15929 s.pending_buf[s.pending++] = w & 0xff;
15930 s.pending_buf[s.pending++] = w >>> 8 & 0xff;
15931}
15932
15933
15934/* ===========================================================================
15935 * Send a value on a given number of bits.
15936 * IN assertion: length <= 16 and value fits in length bits.
15937 */
15938function send_bits(s, value, length) {
15939 if (s.bi_valid > Buf_size - length) {
15940 s.bi_buf |= value << s.bi_valid & 0xffff;
15941 put_short(s, s.bi_buf);
15942 s.bi_buf = value >> Buf_size - s.bi_valid;
15943 s.bi_valid += length - Buf_size;
15944 } else {
15945 s.bi_buf |= value << s.bi_valid & 0xffff;
15946 s.bi_valid += length;
15947 }
15948}
15949
15950
15951function send_code(s, c, tree) {
15952 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
15953}
15954
15955
15956/* ===========================================================================
15957 * Reverse the first len bits of a code, using straightforward code (a faster
15958 * method would use a table)
15959 * IN assertion: 1 <= len <= 15
15960 */
15961function bi_reverse(code, len) {
15962 let res = 0;
15963 do {
15964 res |= code & 1;
15965 code >>>= 1;
15966 res <<= 1;
15967 } while (--len > 0);
15968 return res >>> 1;
15969}
15970
15971
15972/* ===========================================================================
15973 * Flush the bit buffer, keeping at most 7 bits in it.
15974 */
15975function bi_flush(s) {
15976 if (s.bi_valid === 16) {
15977 put_short(s, s.bi_buf);
15978 s.bi_buf = 0;
15979 s.bi_valid = 0;
15980
15981 } else if (s.bi_valid >= 8) {
15982 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
15983 s.bi_buf >>= 8;
15984 s.bi_valid -= 8;
15985 }
15986}
15987
15988
15989/* ===========================================================================
15990 * Compute the optimal bit lengths for a tree and update the total bit length
15991 * for the current block.
15992 * IN assertion: the fields freq and dad are set, heap[heap_max] and
15993 * above are the tree nodes sorted by increasing frequency.
15994 * OUT assertions: the field len is set to the optimal bit length, the
15995 * array bl_count contains the frequencies for each bit length.
15996 * The length opt_len is updated; static_len is also updated if stree is
15997 * not null.
15998 */
15999function gen_bitlen(s, desc)
16000// deflate_state *s;
16001// tree_desc *desc; /* the tree descriptor */
16002{
16003 const tree = desc.dyn_tree;
16004 const max_code = desc.max_code;
16005 const stree = desc.stat_desc.static_tree;
16006 const has_stree = desc.stat_desc.has_stree;
16007 const extra = desc.stat_desc.extra_bits;
16008 const base = desc.stat_desc.extra_base;
16009 const max_length = desc.stat_desc.max_length;
16010 let h; /* heap index */
16011 let n, m; /* iterate over the tree elements */
16012 let bits; /* bit length */
16013 let xbits; /* extra bits */
16014 let f; /* frequency */
16015 let overflow = 0; /* number of elements with bit length too large */
16016
16017 for (bits = 0; bits <= MAX_BITS; bits++) {
16018 s.bl_count[bits] = 0;
16019 }
16020
16021 /* In a first pass, compute the optimal bit lengths (which may
16022 * overflow in the case of the bit length tree).
16023 */
16024 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
16025
16026 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
16027 n = s.heap[h];
16028 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
16029 if (bits > max_length) {
16030 bits = max_length;
16031 overflow++;
16032 }
16033 tree[n * 2 + 1]/*.Len*/ = bits;
16034 /* We overwrite tree[n].Dad which is no longer needed */
16035
16036 if (n > max_code) {
16037 continue;
16038 } /* not a leaf node */
16039
16040 s.bl_count[bits]++;
16041 xbits = 0;
16042 if (n >= base) {
16043 xbits = extra[n - base];
16044 }
16045 f = tree[n * 2]/*.Freq*/;
16046 s.opt_len += f * (bits + xbits);
16047 if (has_stree) {
16048 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
16049 }
16050 }
16051 if (overflow === 0) {
16052 return;
16053 }
16054
16055 // Trace((stderr,"\nbit length overflow\n"));
16056 /* This happens for example on obj2 and pic of the Calgary corpus */
16057
16058 /* Find the first bit length which could increase: */
16059 do {
16060 bits = max_length - 1;
16061 while (s.bl_count[bits] === 0) {
16062 bits--;
16063 }
16064 s.bl_count[bits]--; /* move one leaf down the tree */
16065 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
16066 s.bl_count[max_length]--;
16067 /* The brother of the overflow item also moves one step up,
16068 * but this does not affect bl_count[max_length]
16069 */
16070 overflow -= 2;
16071 } while (overflow > 0);
16072
16073 /* Now recompute all bit lengths, scanning in increasing frequency.
16074 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
16075 * lengths instead of fixing only the wrong ones. This idea is taken
16076 * from 'ar' written by Haruhiko Okumura.)
16077 */
16078 for (bits = max_length; bits !== 0; bits--) {
16079 n = s.bl_count[bits];
16080 while (n !== 0) {
16081 m = s.heap[--h];
16082 if (m > max_code) {
16083 continue;
16084 }
16085 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
16086 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
16087 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
16088 tree[m * 2 + 1]/*.Len*/ = bits;
16089 }
16090 n--;
16091 }
16092 }
16093}
16094
16095
16096/* ===========================================================================
16097 * Generate the codes for a given tree and bit counts (which need not be
16098 * optimal).
16099 * IN assertion: the array bl_count contains the bit length statistics for
16100 * the given tree and the field len is set for all tree elements.
16101 * OUT assertion: the field code is set for all tree elements of non
16102 * zero code length.
16103 */
16104function gen_codes(tree, max_code, bl_count)
16105// ct_data *tree; /* the tree to decorate */
16106// int max_code; /* largest code with non zero frequency */
16107// ushf *bl_count; /* number of codes at each bit length */
16108{
16109 const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
16110 let code = 0; /* running code value */
16111 let bits; /* bit index */
16112 let n; /* code index */
16113
16114 /* The distribution counts are first used to generate the code values
16115 * without bit reversal.
16116 */
16117 for (bits = 1; bits <= MAX_BITS; bits++) {
16118 next_code[bits] = code = code + bl_count[bits - 1] << 1;
16119 }
16120 /* Check that the bit counts in bl_count are consistent. The last code
16121 * must be all ones.
16122 */
16123 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
16124 // "inconsistent bit counts");
16125 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
16126
16127 for (n = 0; n <= max_code; n++) {
16128 const len = tree[n * 2 + 1]/*.Len*/;
16129 if (len === 0) {
16130 continue;
16131 }
16132 /* Now reverse the bits */
16133 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
16134
16135 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
16136 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
16137 }
16138}
16139
16140
16141/* ===========================================================================
16142 * Initialize the various 'constant' tables.
16143 */
16144function tr_static_init() {
16145 let n; /* iterates over tree elements */
16146 let bits; /* bit counter */
16147 let length; /* length value */
16148 let code; /* code value */
16149 let dist; /* distance index */
16150 const bl_count = new Array(MAX_BITS + 1);
16151 /* number of codes at each bit length for an optimal tree */
16152
16153 // do check in _tr_init()
16154 //if (static_init_done) return;
16155
16156 /* For some embedded targets, global variables are not initialized: */
16157 /*#ifdef NO_INIT_GLOBAL_POINTERS
16158 static_l_desc.static_tree = static_ltree;
16159 static_l_desc.extra_bits = extra_lbits;
16160 static_d_desc.static_tree = static_dtree;
16161 static_d_desc.extra_bits = extra_dbits;
16162 static_bl_desc.extra_bits = extra_blbits;
16163#endif*/
16164
16165 /* Initialize the mapping length (0..255) -> length code (0..28) */
16166 length = 0;
16167 for (code = 0; code < LENGTH_CODES - 1; code++) {
16168 base_length[code] = length;
16169 for (n = 0; n < 1 << extra_lbits[code]; n++) {
16170 _length_code[length++] = code;
16171 }
16172 }
16173 //Assert (length == 256, "tr_static_init: length != 256");
16174 /* Note that the length 255 (match length 258) can be represented
16175 * in two different ways: code 284 + 5 bits or code 285, so we
16176 * overwrite length_code[255] to use the best encoding:
16177 */
16178 _length_code[length - 1] = code;
16179
16180 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
16181 dist = 0;
16182 for (code = 0; code < 16; code++) {
16183 base_dist[code] = dist;
16184 for (n = 0; n < 1 << extra_dbits[code]; n++) {
16185 _dist_code[dist++] = code;
16186 }
16187 }
16188 //Assert (dist == 256, "tr_static_init: dist != 256");
16189 dist >>= 7; /* from now on, all distances are divided by 128 */
16190 for (; code < D_CODES; code++) {
16191 base_dist[code] = dist << 7;
16192 for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
16193 _dist_code[256 + dist++] = code;
16194 }
16195 }
16196 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
16197
16198 /* Construct the codes of the static literal tree */
16199 for (bits = 0; bits <= MAX_BITS; bits++) {
16200 bl_count[bits] = 0;
16201 }
16202
16203 n = 0;
16204 while (n <= 143) {
16205 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16206 n++;
16207 bl_count[8]++;
16208 }
16209 while (n <= 255) {
16210 static_ltree[n * 2 + 1]/*.Len*/ = 9;
16211 n++;
16212 bl_count[9]++;
16213 }
16214 while (n <= 279) {
16215 static_ltree[n * 2 + 1]/*.Len*/ = 7;
16216 n++;
16217 bl_count[7]++;
16218 }
16219 while (n <= 287) {
16220 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16221 n++;
16222 bl_count[8]++;
16223 }
16224 /* Codes 286 and 287 do not exist, but we must include them in the
16225 * tree construction to get a canonical Huffman tree (longest code
16226 * all ones)
16227 */
16228 gen_codes(static_ltree, L_CODES + 1, bl_count);
16229
16230 /* The static distance tree is trivial: */
16231 for (n = 0; n < D_CODES; n++) {
16232 static_dtree[n * 2 + 1]/*.Len*/ = 5;
16233 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
16234 }
16235
16236 // Now data ready and we can init static trees
16237 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
16238 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
16239 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
16240
16241 //static_init_done = true;
16242}
16243
16244
16245/* ===========================================================================
16246 * Initialize a new block.
16247 */
16248function init_block(s) {
16249 let n; /* iterates over tree elements */
16250
16251 /* Initialize the trees. */
16252 for (n = 0; n < L_CODES; n++) {
16253 s.dyn_ltree[n * 2]/*.Freq*/ = 0;
16254 }
16255 for (n = 0; n < D_CODES; n++) {
16256 s.dyn_dtree[n * 2]/*.Freq*/ = 0;
16257 }
16258 for (n = 0; n < BL_CODES; n++) {
16259 s.bl_tree[n * 2]/*.Freq*/ = 0;
16260 }
16261
16262 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
16263 s.opt_len = s.static_len = 0;
16264 s.last_lit = s.matches = 0;
16265}
16266
16267
16268/* ===========================================================================
16269 * Flush the bit buffer and align the output on a byte boundary
16270 */
16271function bi_windup(s) {
16272 if (s.bi_valid > 8) {
16273 put_short(s, s.bi_buf);
16274 } else if (s.bi_valid > 0) {
16275 //put_byte(s, (Byte)s->bi_buf);
16276 s.pending_buf[s.pending++] = s.bi_buf;
16277 }
16278 s.bi_buf = 0;
16279 s.bi_valid = 0;
16280}
16281
16282/* ===========================================================================
16283 * Copy a stored block, storing first the length and its
16284 * one's complement if requested.
16285 */
16286function copy_block(s, buf, len, header)
16287//DeflateState *s;
16288//charf *buf; /* the input data */
16289//unsigned len; /* its length */
16290//int header; /* true if block header must be written */
16291{
16292 bi_windup(s); /* align on byte boundary */
16293
16294 if (header) {
16295 put_short(s, len);
16296 put_short(s, ~len);
16297 }
16298 // while (len--) {
16299 // put_byte(s, *buf++);
16300 // }
16301 arraySet(s.pending_buf, s.window, buf, len, s.pending);
16302 s.pending += len;
16303}
16304
16305/* ===========================================================================
16306 * Compares to subtrees, using the tree depth as tie breaker when
16307 * the subtrees have equal frequency. This minimizes the worst case length.
16308 */
16309function smaller(tree, n, m, depth) {
16310 const _n2 = n * 2;
16311 const _m2 = m * 2;
16312 return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
16313 tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];
16314}
16315
16316/* ===========================================================================
16317 * Restore the heap property by moving down the tree starting at node k,
16318 * exchanging a node with the smallest of its two sons if necessary, stopping
16319 * when the heap property is re-established (each father smaller than its
16320 * two sons).
16321 */
16322function pqdownheap(s, tree, k)
16323// deflate_state *s;
16324// ct_data *tree; /* the tree to restore */
16325// int k; /* node to move down */
16326{
16327 const v = s.heap[k];
16328 let j = k << 1; /* left son of k */
16329 while (j <= s.heap_len) {
16330 /* Set j to the smallest of the two sons: */
16331 if (j < s.heap_len &&
16332 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
16333 j++;
16334 }
16335 /* Exit if v is smaller than both sons */
16336 if (smaller(tree, v, s.heap[j], s.depth)) {
16337 break;
16338 }
16339
16340 /* Exchange v with the smallest son */
16341 s.heap[k] = s.heap[j];
16342 k = j;
16343
16344 /* And continue down the tree, setting j to the left son of k */
16345 j <<= 1;
16346 }
16347 s.heap[k] = v;
16348}
16349
16350
16351// inlined manually
16352// var SMALLEST = 1;
16353
16354/* ===========================================================================
16355 * Send the block data compressed using the given Huffman trees
16356 */
16357function compress_block(s, ltree, dtree)
16358// deflate_state *s;
16359// const ct_data *ltree; /* literal tree */
16360// const ct_data *dtree; /* distance tree */
16361{
16362 let dist; /* distance of matched string */
16363 let lc; /* match length or unmatched char (if dist == 0) */
16364 let lx = 0; /* running index in l_buf */
16365 let code; /* the code to send */
16366 let extra; /* number of extra bits to send */
16367
16368 if (s.last_lit !== 0) {
16369 do {
16370 dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
16371 lc = s.pending_buf[s.l_buf + lx];
16372 lx++;
16373
16374 if (dist === 0) {
16375 send_code(s, lc, ltree); /* send a literal byte */
16376 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
16377 } else {
16378 /* Here, lc is the match length - MIN_MATCH */
16379 code = _length_code[lc];
16380 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
16381 extra = extra_lbits[code];
16382 if (extra !== 0) {
16383 lc -= base_length[code];
16384 send_bits(s, lc, extra); /* send the extra length bits */
16385 }
16386 dist--; /* dist is now the match distance - 1 */
16387 code = d_code(dist);
16388 //Assert (code < D_CODES, "bad d_code");
16389
16390 send_code(s, code, dtree); /* send the distance code */
16391 extra = extra_dbits[code];
16392 if (extra !== 0) {
16393 dist -= base_dist[code];
16394 send_bits(s, dist, extra); /* send the extra distance bits */
16395 }
16396 } /* literal or match pair ? */
16397
16398 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
16399 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
16400 // "pendingBuf overflow");
16401
16402 } while (lx < s.last_lit);
16403 }
16404
16405 send_code(s, END_BLOCK, ltree);
16406}
16407
16408
16409/* ===========================================================================
16410 * Construct one Huffman tree and assigns the code bit strings and lengths.
16411 * Update the total bit length for the current block.
16412 * IN assertion: the field freq is set for all tree elements.
16413 * OUT assertions: the fields len and code are set to the optimal bit length
16414 * and corresponding code. The length opt_len is updated; static_len is
16415 * also updated if stree is not null. The field max_code is set.
16416 */
16417function build_tree(s, desc)
16418// deflate_state *s;
16419// tree_desc *desc; /* the tree descriptor */
16420{
16421 const tree = desc.dyn_tree;
16422 const stree = desc.stat_desc.static_tree;
16423 const has_stree = desc.stat_desc.has_stree;
16424 const elems = desc.stat_desc.elems;
16425 let n, m; /* iterate over heap elements */
16426 let max_code = -1; /* largest code with non zero frequency */
16427 let node; /* new node being created */
16428
16429 /* Construct the initial heap, with least frequent element in
16430 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
16431 * heap[0] is not used.
16432 */
16433 s.heap_len = 0;
16434 s.heap_max = HEAP_SIZE;
16435
16436 for (n = 0; n < elems; n++) {
16437 if (tree[n * 2]/*.Freq*/ !== 0) {
16438 s.heap[++s.heap_len] = max_code = n;
16439 s.depth[n] = 0;
16440
16441 } else {
16442 tree[n * 2 + 1]/*.Len*/ = 0;
16443 }
16444 }
16445
16446 /* The pkzip format requires that at least one distance code exists,
16447 * and that at least one bit should be sent even if there is only one
16448 * possible code. So to avoid special checks later on we force at least
16449 * two codes of non zero frequency.
16450 */
16451 while (s.heap_len < 2) {
16452 node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
16453 tree[node * 2]/*.Freq*/ = 1;
16454 s.depth[node] = 0;
16455 s.opt_len--;
16456
16457 if (has_stree) {
16458 s.static_len -= stree[node * 2 + 1]/*.Len*/;
16459 }
16460 /* node is 0 or 1 so it does not have extra bits */
16461 }
16462 desc.max_code = max_code;
16463
16464 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
16465 * establish sub-heaps of increasing lengths:
16466 */
16467 for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {
16468 pqdownheap(s, tree, n);
16469 }
16470
16471 /* Construct the Huffman tree by repeatedly combining the least two
16472 * frequent nodes.
16473 */
16474 node = elems; /* next internal node of the tree */
16475 do {
16476 //pqremove(s, tree, n); /* n = node of least frequency */
16477 /*** pqremove ***/
16478 n = s.heap[1/*SMALLEST*/];
16479 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
16480 pqdownheap(s, tree, 1/*SMALLEST*/);
16481 /***/
16482
16483 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
16484
16485 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
16486 s.heap[--s.heap_max] = m;
16487
16488 /* Create a new node father of n and m */
16489 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
16490 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
16491 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
16492
16493 /* and insert the new node in the heap */
16494 s.heap[1/*SMALLEST*/] = node++;
16495 pqdownheap(s, tree, 1/*SMALLEST*/);
16496
16497 } while (s.heap_len >= 2);
16498
16499 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
16500
16501 /* At this point, the fields freq and dad are set. We can now
16502 * generate the bit lengths.
16503 */
16504 gen_bitlen(s, desc);
16505
16506 /* The field len is now set, we can generate the bit codes */
16507 gen_codes(tree, max_code, s.bl_count);
16508}
16509
16510
16511/* ===========================================================================
16512 * Scan a literal or distance tree to determine the frequencies of the codes
16513 * in the bit length tree.
16514 */
16515function scan_tree(s, tree, max_code)
16516// deflate_state *s;
16517// ct_data *tree; /* the tree to be scanned */
16518// int max_code; /* and its largest code of non zero frequency */
16519{
16520 let n; /* iterates over all tree elements */
16521 let prevlen = -1; /* last emitted length */
16522 let curlen; /* length of current code */
16523
16524 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16525
16526 let count = 0; /* repeat count of the current code */
16527 let max_count = 7; /* max repeat count */
16528 let min_count = 4; /* min repeat count */
16529
16530 if (nextlen === 0) {
16531 max_count = 138;
16532 min_count = 3;
16533 }
16534 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
16535
16536 for (n = 0; n <= max_code; n++) {
16537 curlen = nextlen;
16538 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16539
16540 if (++count < max_count && curlen === nextlen) {
16541 continue;
16542
16543 } else if (count < min_count) {
16544 s.bl_tree[curlen * 2]/*.Freq*/ += count;
16545
16546 } else if (curlen !== 0) {
16547
16548 if (curlen !== prevlen) {
16549 s.bl_tree[curlen * 2]/*.Freq*/++;
16550 }
16551 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
16552
16553 } else if (count <= 10) {
16554 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
16555
16556 } else {
16557 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
16558 }
16559
16560 count = 0;
16561 prevlen = curlen;
16562
16563 if (nextlen === 0) {
16564 max_count = 138;
16565 min_count = 3;
16566
16567 } else if (curlen === nextlen) {
16568 max_count = 6;
16569 min_count = 3;
16570
16571 } else {
16572 max_count = 7;
16573 min_count = 4;
16574 }
16575 }
16576}
16577
16578
16579/* ===========================================================================
16580 * Send a literal or distance tree in compressed form, using the codes in
16581 * bl_tree.
16582 */
16583function send_tree(s, tree, max_code)
16584// deflate_state *s;
16585// ct_data *tree; /* the tree to be scanned */
16586// int max_code; /* and its largest code of non zero frequency */
16587{
16588 let n; /* iterates over all tree elements */
16589 let prevlen = -1; /* last emitted length */
16590 let curlen; /* length of current code */
16591
16592 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16593
16594 let count = 0; /* repeat count of the current code */
16595 let max_count = 7; /* max repeat count */
16596 let min_count = 4; /* min repeat count */
16597
16598 /* tree[max_code+1].Len = -1; */ /* guard already set */
16599 if (nextlen === 0) {
16600 max_count = 138;
16601 min_count = 3;
16602 }
16603
16604 for (n = 0; n <= max_code; n++) {
16605 curlen = nextlen;
16606 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16607
16608 if (++count < max_count && curlen === nextlen) {
16609 continue;
16610
16611 } else if (count < min_count) {
16612 do {
16613 send_code(s, curlen, s.bl_tree);
16614 } while (--count !== 0);
16615
16616 } else if (curlen !== 0) {
16617 if (curlen !== prevlen) {
16618 send_code(s, curlen, s.bl_tree);
16619 count--;
16620 }
16621 //Assert(count >= 3 && count <= 6, " 3_6?");
16622 send_code(s, REP_3_6, s.bl_tree);
16623 send_bits(s, count - 3, 2);
16624
16625 } else if (count <= 10) {
16626 send_code(s, REPZ_3_10, s.bl_tree);
16627 send_bits(s, count - 3, 3);
16628
16629 } else {
16630 send_code(s, REPZ_11_138, s.bl_tree);
16631 send_bits(s, count - 11, 7);
16632 }
16633
16634 count = 0;
16635 prevlen = curlen;
16636 if (nextlen === 0) {
16637 max_count = 138;
16638 min_count = 3;
16639
16640 } else if (curlen === nextlen) {
16641 max_count = 6;
16642 min_count = 3;
16643
16644 } else {
16645 max_count = 7;
16646 min_count = 4;
16647 }
16648 }
16649}
16650
16651
16652/* ===========================================================================
16653 * Construct the Huffman tree for the bit lengths and return the index in
16654 * bl_order of the last bit length code to send.
16655 */
16656function build_bl_tree(s) {
16657 let max_blindex; /* index of last bit length code of non zero freq */
16658
16659 /* Determine the bit length frequencies for literal and distance trees */
16660 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
16661 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
16662
16663 /* Build the bit length tree: */
16664 build_tree(s, s.bl_desc);
16665 /* opt_len now includes the length of the tree representations, except
16666 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
16667 */
16668
16669 /* Determine the number of bit length codes to send. The pkzip format
16670 * requires that at least 4 bit length codes be sent. (appnote.txt says
16671 * 3 but the actual value used is 4.)
16672 */
16673 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
16674 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
16675 break;
16676 }
16677 }
16678 /* Update opt_len to include the bit length tree and counts */
16679 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
16680 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
16681 // s->opt_len, s->static_len));
16682
16683 return max_blindex;
16684}
16685
16686
16687/* ===========================================================================
16688 * Send the header for a block using dynamic Huffman trees: the counts, the
16689 * lengths of the bit length codes, the literal tree and the distance tree.
16690 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
16691 */
16692function send_all_trees(s, lcodes, dcodes, blcodes)
16693// deflate_state *s;
16694// int lcodes, dcodes, blcodes; /* number of codes for each tree */
16695{
16696 let rank; /* index in bl_order */
16697
16698 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
16699 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
16700 // "too many codes");
16701 //Tracev((stderr, "\nbl counts: "));
16702 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
16703 send_bits(s, dcodes - 1, 5);
16704 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
16705 for (rank = 0; rank < blcodes; rank++) {
16706 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
16707 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
16708 }
16709 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
16710
16711 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
16712 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
16713
16714 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
16715 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
16716}
16717
16718
16719/* ===========================================================================
16720 * Check if the data type is TEXT or BINARY, using the following algorithm:
16721 * - TEXT if the two conditions below are satisfied:
16722 * a) There are no non-portable control characters belonging to the
16723 * "black list" (0..6, 14..25, 28..31).
16724 * b) There is at least one printable character belonging to the
16725 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
16726 * - BINARY otherwise.
16727 * - The following partially-portable control characters form a
16728 * "gray list" that is ignored in this detection algorithm:
16729 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
16730 * IN assertion: the fields Freq of dyn_ltree are set.
16731 */
16732function detect_data_type(s) {
16733 /* black_mask is the bit mask of black-listed bytes
16734 * set bits 0..6, 14..25, and 28..31
16735 * 0xf3ffc07f = binary 11110011111111111100000001111111
16736 */
16737 let black_mask = 0xf3ffc07f;
16738 let n;
16739
16740 /* Check for non-textual ("black-listed") bytes. */
16741 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
16742 if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16743 return Z_BINARY;
16744 }
16745 }
16746
16747 /* Check for textual ("white-listed") bytes. */
16748 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
16749 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
16750 return Z_TEXT;
16751 }
16752 for (n = 32; n < LITERALS; n++) {
16753 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16754 return Z_TEXT;
16755 }
16756 }
16757
16758 /* There are no "black-listed" or "white-listed" bytes:
16759 * this stream either is empty or has tolerated ("gray-listed") bytes only.
16760 */
16761 return Z_BINARY;
16762}
16763
16764
16765let static_init_done = false;
16766
16767/* ===========================================================================
16768 * Initialize the tree data structures for a new zlib stream.
16769 */
16770function _tr_init(s) {
16771
16772 if (!static_init_done) {
16773 tr_static_init();
16774 static_init_done = true;
16775 }
16776
16777 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
16778 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
16779 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
16780
16781 s.bi_buf = 0;
16782 s.bi_valid = 0;
16783
16784 /* Initialize the first block of the first file: */
16785 init_block(s);
16786}
16787
16788
16789/* ===========================================================================
16790 * Send a stored block
16791 */
16792function _tr_stored_block(s, buf, stored_len, last)
16793//DeflateState *s;
16794//charf *buf; /* input block */
16795//ulg stored_len; /* length of input block */
16796//int last; /* one if this is the last block for a file */
16797{
16798 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
16799 copy_block(s, buf, stored_len, true); /* with header */
16800}
16801
16802
16803/* ===========================================================================
16804 * Send one empty static block to give enough lookahead for inflate.
16805 * This takes 10 bits, of which 7 may remain in the bit buffer.
16806 */
16807function _tr_align(s) {
16808 send_bits(s, STATIC_TREES << 1, 3);
16809 send_code(s, END_BLOCK, static_ltree);
16810 bi_flush(s);
16811}
16812
16813
16814/* ===========================================================================
16815 * Determine the best encoding for the current block: dynamic trees, static
16816 * trees or store, and output the encoded block to the zip file.
16817 */
16818function _tr_flush_block(s, buf, stored_len, last)
16819//DeflateState *s;
16820//charf *buf; /* input block, or NULL if too old */
16821//ulg stored_len; /* length of input block */
16822//int last; /* one if this is the last block for a file */
16823{
16824 let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
16825 let max_blindex = 0; /* index of last bit length code of non zero freq */
16826
16827 /* Build the Huffman trees unless a stored block is forced */
16828 if (s.level > 0) {
16829
16830 /* Check if the file is binary or text */
16831 if (s.strm.data_type === Z_UNKNOWN) {
16832 s.strm.data_type = detect_data_type(s);
16833 }
16834
16835 /* Construct the literal and distance trees */
16836 build_tree(s, s.l_desc);
16837 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
16838 // s->static_len));
16839
16840 build_tree(s, s.d_desc);
16841 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
16842 // s->static_len));
16843 /* At this point, opt_len and static_len are the total bit lengths of
16844 * the compressed block data, excluding the tree representations.
16845 */
16846
16847 /* Build the bit length tree for the above two trees, and get the index
16848 * in bl_order of the last bit length code to send.
16849 */
16850 max_blindex = build_bl_tree(s);
16851
16852 /* Determine the best encoding. Compute the block lengths in bytes. */
16853 opt_lenb = s.opt_len + 3 + 7 >>> 3;
16854 static_lenb = s.static_len + 3 + 7 >>> 3;
16855
16856 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
16857 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
16858 // s->last_lit));
16859
16860 if (static_lenb <= opt_lenb) {
16861 opt_lenb = static_lenb;
16862 }
16863
16864 } else {
16865 // Assert(buf != (char*)0, "lost buf");
16866 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
16867 }
16868
16869 if (stored_len + 4 <= opt_lenb && buf !== -1) {
16870 /* 4: two words for the lengths */
16871
16872 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
16873 * Otherwise we can't have processed more than WSIZE input bytes since
16874 * the last block flush, because compression would have been
16875 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
16876 * transform a block into a stored block.
16877 */
16878 _tr_stored_block(s, buf, stored_len, last);
16879
16880 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
16881
16882 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
16883 compress_block(s, static_ltree, static_dtree);
16884
16885 } else {
16886 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
16887 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
16888 compress_block(s, s.dyn_ltree, s.dyn_dtree);
16889 }
16890 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
16891 /* The above check is made mod 2^32, for files larger than 512 MB
16892 * and uLong implemented on 32 bits.
16893 */
16894 init_block(s);
16895
16896 if (last) {
16897 bi_windup(s);
16898 }
16899 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
16900 // s->compressed_len-7*last));
16901}
16902
16903/* ===========================================================================
16904 * Save the match info and tally the frequency counts. Return true if
16905 * the current block must be flushed.
16906 */
16907function _tr_tally(s, dist, lc)
16908// deflate_state *s;
16909// unsigned dist; /* distance of matched string */
16910// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
16911{
16912 //var out_length, in_length, dcode;
16913
16914 s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
16915 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
16916
16917 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
16918 s.last_lit++;
16919
16920 if (dist === 0) {
16921 /* lc is the unmatched char */
16922 s.dyn_ltree[lc * 2]/*.Freq*/++;
16923 } else {
16924 s.matches++;
16925 /* Here, lc is the match length - MIN_MATCH */
16926 dist--; /* dist = match distance - 1 */
16927 //Assert((ush)dist < (ush)MAX_DIST(s) &&
16928 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
16929 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
16930
16931 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
16932 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
16933 }
16934
16935 // (!) This block is disabled in zlib defaults,
16936 // don't enable it for binary compatibility
16937
16938 //#ifdef TRUNCATE_BLOCK
16939 // /* Try to guess if it is profitable to stop the current block here */
16940 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
16941 // /* Compute an upper bound for the compressed length */
16942 // out_length = s.last_lit*8;
16943 // in_length = s.strstart - s.block_start;
16944 //
16945 // for (dcode = 0; dcode < D_CODES; dcode++) {
16946 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
16947 // }
16948 // out_length >>>= 3;
16949 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
16950 // // s->last_lit, in_length, out_length,
16951 // // 100L - out_length*100L/in_length));
16952 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
16953 // return true;
16954 // }
16955 // }
16956 //#endif
16957
16958 return s.last_lit === s.lit_bufsize - 1;
16959 /* We avoid equality with lit_bufsize because of wraparound at 64K
16960 * on 16 bit machines and because stored blocks are restricted to
16961 * 64K-1 bytes.
16962 */
16963}
16964
16965// Note: adler32 takes 12% for level 0 and 2% for level 6.
16966// It isn't worth it to make additional optimizations as in original.
16967// Small size is preferable.
16968
16969// (C) 1995-2013 Jean-loup Gailly and Mark Adler
16970// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16971//
16972// This software is provided 'as-is', without any express or implied
16973// warranty. In no event will the authors be held liable for any damages
16974// arising from the use of this software.
16975//
16976// Permission is granted to anyone to use this software for any purpose,
16977// including commercial applications, and to alter it and redistribute it
16978// freely, subject to the following restrictions:
16979//
16980// 1. The origin of this software must not be misrepresented; you must not
16981// claim that you wrote the original software. If you use this software
16982// in a product, an acknowledgment in the product documentation would be
16983// appreciated but is not required.
16984// 2. Altered source versions must be plainly marked as such, and must not be
16985// misrepresented as being the original software.
16986// 3. This notice may not be removed or altered from any source distribution.
16987
16988function adler32(adler, buf, len, pos) {
16989 let s1 = adler & 0xffff |0,
16990 s2 = adler >>> 16 & 0xffff |0,
16991 n = 0;
16992
16993 while (len !== 0) {
16994 // Set limit ~ twice less than 5552, to keep
16995 // s2 in 31-bits, because we force signed ints.
16996 // in other case %= will fail.
16997 n = len > 2000 ? 2000 : len;
16998 len -= n;
16999
17000 do {
17001 s1 = s1 + buf[pos++] |0;
17002 s2 = s2 + s1 |0;
17003 } while (--n);
17004
17005 s1 %= 65521;
17006 s2 %= 65521;
17007 }
17008
17009 return s1 | s2 << 16 |0;
17010}
17011
17012// Note: we can't get significant speed boost here.
17013// So write code to minimize size - no pregenerated tables
17014// and array tools dependencies.
17015
17016// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17017// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17018//
17019// This software is provided 'as-is', without any express or implied
17020// warranty. In no event will the authors be held liable for any damages
17021// arising from the use of this software.
17022//
17023// Permission is granted to anyone to use this software for any purpose,
17024// including commercial applications, and to alter it and redistribute it
17025// freely, subject to the following restrictions:
17026//
17027// 1. The origin of this software must not be misrepresented; you must not
17028// claim that you wrote the original software. If you use this software
17029// in a product, an acknowledgment in the product documentation would be
17030// appreciated but is not required.
17031// 2. Altered source versions must be plainly marked as such, and must not be
17032// misrepresented as being the original software.
17033// 3. This notice may not be removed or altered from any source distribution.
17034
17035// Use ordinary array, since untyped makes no boost here
17036function makeTable() {
17037 let c;
17038 const table = [];
17039
17040 for (let n = 0; n < 256; n++) {
17041 c = n;
17042 for (let k = 0; k < 8; k++) {
17043 c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
17044 }
17045 table[n] = c;
17046 }
17047
17048 return table;
17049}
17050
17051// Create table on load. Just 255 signed longs. Not a problem.
17052const crcTable = makeTable();
17053
17054
17055function crc32(crc, buf, len, pos) {
17056 const t = crcTable,
17057 end = pos + len;
17058
17059 crc ^= -1;
17060
17061 for (let i = pos; i < end; i++) {
17062 crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
17063 }
17064
17065 return crc ^ -1; // >>> 0;
17066}
17067
17068// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17069// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17070//
17071// This software is provided 'as-is', without any express or implied
17072// warranty. In no event will the authors be held liable for any damages
17073// arising from the use of this software.
17074//
17075// Permission is granted to anyone to use this software for any purpose,
17076// including commercial applications, and to alter it and redistribute it
17077// freely, subject to the following restrictions:
17078//
17079// 1. The origin of this software must not be misrepresented; you must not
17080// claim that you wrote the original software. If you use this software
17081// in a product, an acknowledgment in the product documentation would be
17082// appreciated but is not required.
17083// 2. Altered source versions must be plainly marked as such, and must not be
17084// misrepresented as being the original software.
17085// 3. This notice may not be removed or altered from any source distribution.
17086
17087var msg = {
17088 2: "need dictionary", /* Z_NEED_DICT 2 */
17089 1: "stream end", /* Z_STREAM_END 1 */
17090 0: "", /* Z_OK 0 */
17091 "-1": "file error", /* Z_ERRNO (-1) */
17092 "-2": "stream error", /* Z_STREAM_ERROR (-2) */
17093 "-3": "data error", /* Z_DATA_ERROR (-3) */
17094 "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */
17095 "-5": "buffer error", /* Z_BUF_ERROR (-5) */
17096 "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */
17097};
17098
17099/*============================================================================*/
17100
17101
17102const MAX_MEM_LEVEL = 9;
17103
17104
17105const LENGTH_CODES$1 = 29;
17106/* number of length codes, not counting the special END_BLOCK code */
17107const LITERALS$1 = 256;
17108/* number of literal bytes 0..255 */
17109const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
17110/* number of Literal or Length codes, including the END_BLOCK code */
17111const D_CODES$1 = 30;
17112/* number of distance codes */
17113const BL_CODES$1 = 19;
17114/* number of codes used to transfer the bit lengths */
17115const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
17116/* maximum heap size */
17117const MAX_BITS$1 = 15;
17118/* All codes must not exceed MAX_BITS bits */
17119
17120const MIN_MATCH$1 = 3;
17121const MAX_MATCH$1 = 258;
17122const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
17123
17124const PRESET_DICT = 0x20;
17125
17126const INIT_STATE = 42;
17127const EXTRA_STATE = 69;
17128const NAME_STATE = 73;
17129const COMMENT_STATE = 91;
17130const HCRC_STATE = 103;
17131const BUSY_STATE = 113;
17132const FINISH_STATE = 666;
17133
17134const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
17135const BS_BLOCK_DONE = 2; /* block flush performed */
17136const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
17137const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
17138
17139const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
17140
17141function err(strm, errorCode) {
17142 strm.msg = msg[errorCode];
17143 return errorCode;
17144}
17145
17146function rank(f) {
17147 return ((f) << 1) - ((f) > 4 ? 9 : 0);
17148}
17149
17150function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
17151
17152
17153/* =========================================================================
17154 * Flush as much pending output as possible. All deflate() output goes
17155 * through this function so some applications may wish to modify it
17156 * to avoid allocating a large strm->output buffer and copying into it.
17157 * (See also read_buf()).
17158 */
17159function flush_pending(strm) {
17160 const s = strm.state;
17161
17162 //_tr_flush_bits(s);
17163 let len = s.pending;
17164 if (len > strm.avail_out) {
17165 len = strm.avail_out;
17166 }
17167 if (len === 0) { return; }
17168
17169 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
17170 strm.next_out += len;
17171 s.pending_out += len;
17172 strm.total_out += len;
17173 strm.avail_out -= len;
17174 s.pending -= len;
17175 if (s.pending === 0) {
17176 s.pending_out = 0;
17177 }
17178}
17179
17180
17181function flush_block_only(s, last) {
17182 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
17183 s.block_start = s.strstart;
17184 flush_pending(s.strm);
17185}
17186
17187
17188function put_byte(s, b) {
17189 s.pending_buf[s.pending++] = b;
17190}
17191
17192
17193/* =========================================================================
17194 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
17195 * IN assertion: the stream state is correct and there is enough room in
17196 * pending_buf.
17197 */
17198function putShortMSB(s, b) {
17199 // put_byte(s, (Byte)(b >> 8));
17200 // put_byte(s, (Byte)(b & 0xff));
17201 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
17202 s.pending_buf[s.pending++] = b & 0xff;
17203}
17204
17205
17206/* ===========================================================================
17207 * Read a new buffer from the current input stream, update the adler32
17208 * and total number of bytes read. All deflate() input goes through
17209 * this function so some applications may wish to modify it to avoid
17210 * allocating a large strm->input buffer and copying from it.
17211 * (See also flush_pending()).
17212 */
17213function read_buf(strm, buf, start, size) {
17214 let len = strm.avail_in;
17215
17216 if (len > size) { len = size; }
17217 if (len === 0) { return 0; }
17218
17219 strm.avail_in -= len;
17220
17221 // zmemcpy(buf, strm->next_in, len);
17222 arraySet(buf, strm.input, strm.next_in, len, start);
17223 if (strm.state.wrap === 1) {
17224 strm.adler = adler32(strm.adler, buf, len, start);
17225 }
17226
17227 else if (strm.state.wrap === 2) {
17228 strm.adler = crc32(strm.adler, buf, len, start);
17229 }
17230
17231 strm.next_in += len;
17232 strm.total_in += len;
17233
17234 return len;
17235}
17236
17237
17238/* ===========================================================================
17239 * Set match_start to the longest match starting at the given string and
17240 * return its length. Matches shorter or equal to prev_length are discarded,
17241 * in which case the result is equal to prev_length and match_start is
17242 * garbage.
17243 * IN assertions: cur_match is the head of the hash chain for the current
17244 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
17245 * OUT assertion: the match length is not greater than s->lookahead.
17246 */
17247function longest_match(s, cur_match) {
17248 let chain_length = s.max_chain_length; /* max hash chain length */
17249 let scan = s.strstart; /* current string */
17250 let match; /* matched string */
17251 let len; /* length of current match */
17252 let best_len = s.prev_length; /* best match length so far */
17253 let nice_match = s.nice_match; /* stop if match long enough */
17254 const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
17255 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
17256
17257 const _win = s.window; // shortcut
17258
17259 const wmask = s.w_mask;
17260 const prev = s.prev;
17261
17262 /* Stop when cur_match becomes <= limit. To simplify the code,
17263 * we prevent matches with the string of window index 0.
17264 */
17265
17266 const strend = s.strstart + MAX_MATCH$1;
17267 let scan_end1 = _win[scan + best_len - 1];
17268 let scan_end = _win[scan + best_len];
17269
17270 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
17271 * It is easy to get rid of this optimization if necessary.
17272 */
17273 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
17274
17275 /* Do not waste too much time if we already have a good match: */
17276 if (s.prev_length >= s.good_match) {
17277 chain_length >>= 2;
17278 }
17279 /* Do not look for matches beyond the end of the input. This is necessary
17280 * to make deflate deterministic.
17281 */
17282 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
17283
17284 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
17285
17286 do {
17287 // Assert(cur_match < s->strstart, "no future");
17288 match = cur_match;
17289
17290 /* Skip to next match if the match length cannot increase
17291 * or if the match length is less than 2. Note that the checks below
17292 * for insufficient lookahead only occur occasionally for performance
17293 * reasons. Therefore uninitialized memory will be accessed, and
17294 * conditional jumps will be made that depend on those values.
17295 * However the length of the match is limited to the lookahead, so
17296 * the output of deflate is not affected by the uninitialized values.
17297 */
17298
17299 if (_win[match + best_len] !== scan_end ||
17300 _win[match + best_len - 1] !== scan_end1 ||
17301 _win[match] !== _win[scan] ||
17302 _win[++match] !== _win[scan + 1]) {
17303 continue;
17304 }
17305
17306 /* The check at best_len-1 can be removed because it will be made
17307 * again later. (This heuristic is not always a win.)
17308 * It is not necessary to compare scan[2] and match[2] since they
17309 * are always equal when the other bytes match, given that
17310 * the hash keys are equal and that HASH_BITS >= 8.
17311 */
17312 scan += 2;
17313 match++;
17314 // Assert(*scan == *match, "match[2]?");
17315
17316 /* We check for insufficient lookahead only every 8th comparison;
17317 * the 256th check will be made at strstart+258.
17318 */
17319 do {
17320 /*jshint noempty:false*/
17321 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17322 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17323 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17324 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17325 scan < strend);
17326
17327 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
17328
17329 len = MAX_MATCH$1 - (strend - scan);
17330 scan = strend - MAX_MATCH$1;
17331
17332 if (len > best_len) {
17333 s.match_start = cur_match;
17334 best_len = len;
17335 if (len >= nice_match) {
17336 break;
17337 }
17338 scan_end1 = _win[scan + best_len - 1];
17339 scan_end = _win[scan + best_len];
17340 }
17341 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
17342
17343 if (best_len <= s.lookahead) {
17344 return best_len;
17345 }
17346 return s.lookahead;
17347}
17348
17349
17350/* ===========================================================================
17351 * Fill the window when the lookahead becomes insufficient.
17352 * Updates strstart and lookahead.
17353 *
17354 * IN assertion: lookahead < MIN_LOOKAHEAD
17355 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
17356 * At least one byte has been read, or avail_in == 0; reads are
17357 * performed for at least two bytes (required for the zip translate_eol
17358 * option -- not supported here).
17359 */
17360function fill_window(s) {
17361 const _w_size = s.w_size;
17362 let p, n, m, more, str;
17363
17364 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
17365
17366 do {
17367 more = s.window_size - s.lookahead - s.strstart;
17368
17369 // JS ints have 32 bit, block below not needed
17370 /* Deal with !@#$% 64K limit: */
17371 //if (sizeof(int) <= 2) {
17372 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
17373 // more = wsize;
17374 //
17375 // } else if (more == (unsigned)(-1)) {
17376 // /* Very unlikely, but possible on 16 bit machine if
17377 // * strstart == 0 && lookahead == 1 (input done a byte at time)
17378 // */
17379 // more--;
17380 // }
17381 //}
17382
17383
17384 /* If the window is almost full and there is insufficient lookahead,
17385 * move the upper half to the lower one to make room in the upper half.
17386 */
17387 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
17388
17389 arraySet(s.window, s.window, _w_size, _w_size, 0);
17390 s.match_start -= _w_size;
17391 s.strstart -= _w_size;
17392 /* we now have strstart >= MAX_DIST */
17393 s.block_start -= _w_size;
17394
17395 /* Slide the hash table (could be avoided with 32 bit values
17396 at the expense of memory usage). We slide even when level == 0
17397 to keep the hash table consistent if we switch back to level > 0
17398 later. (Using level 0 permanently is not an optimal usage of
17399 zlib, so we don't care about this pathological case.)
17400 */
17401
17402 n = s.hash_size;
17403 p = n;
17404 do {
17405 m = s.head[--p];
17406 s.head[p] = (m >= _w_size ? m - _w_size : 0);
17407 } while (--n);
17408
17409 n = _w_size;
17410 p = n;
17411 do {
17412 m = s.prev[--p];
17413 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
17414 /* If n is not on any hash chain, prev[n] is garbage but
17415 * its value will never be used.
17416 */
17417 } while (--n);
17418
17419 more += _w_size;
17420 }
17421 if (s.strm.avail_in === 0) {
17422 break;
17423 }
17424
17425 /* If there was no sliding:
17426 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
17427 * more == window_size - lookahead - strstart
17428 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
17429 * => more >= window_size - 2*WSIZE + 2
17430 * In the BIG_MEM or MMAP case (not yet supported),
17431 * window_size == input_size + MIN_LOOKAHEAD &&
17432 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
17433 * Otherwise, window_size == 2*WSIZE so more >= 2.
17434 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
17435 */
17436 //Assert(more >= 2, "more < 2");
17437 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
17438 s.lookahead += n;
17439
17440 /* Initialize the hash value now that we have some input: */
17441 if (s.lookahead + s.insert >= MIN_MATCH$1) {
17442 str = s.strstart - s.insert;
17443 s.ins_h = s.window[str];
17444
17445 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
17446 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
17447 //#if MIN_MATCH != 3
17448 // Call update_hash() MIN_MATCH-3 more times
17449 //#endif
17450 while (s.insert) {
17451 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
17452 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
17453
17454 s.prev[str & s.w_mask] = s.head[s.ins_h];
17455 s.head[s.ins_h] = str;
17456 str++;
17457 s.insert--;
17458 if (s.lookahead + s.insert < MIN_MATCH$1) {
17459 break;
17460 }
17461 }
17462 }
17463 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
17464 * but this is not important since only literal bytes will be emitted.
17465 */
17466
17467 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
17468
17469 /* If the WIN_INIT bytes after the end of the current data have never been
17470 * written, then zero those bytes in order to avoid memory check reports of
17471 * the use of uninitialized (or uninitialised as Julian writes) bytes by
17472 * the longest match routines. Update the high water mark for the next
17473 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
17474 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
17475 */
17476 // if (s.high_water < s.window_size) {
17477 // var curr = s.strstart + s.lookahead;
17478 // var init = 0;
17479 //
17480 // if (s.high_water < curr) {
17481 // /* Previous high water mark below current data -- zero WIN_INIT
17482 // * bytes or up to end of window, whichever is less.
17483 // */
17484 // init = s.window_size - curr;
17485 // if (init > WIN_INIT)
17486 // init = WIN_INIT;
17487 // zmemzero(s->window + curr, (unsigned)init);
17488 // s->high_water = curr + init;
17489 // }
17490 // else if (s->high_water < (ulg)curr + WIN_INIT) {
17491 // /* High water mark at or above current data, but below current data
17492 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
17493 // * to end of window, whichever is less.
17494 // */
17495 // init = (ulg)curr + WIN_INIT - s->high_water;
17496 // if (init > s->window_size - s->high_water)
17497 // init = s->window_size - s->high_water;
17498 // zmemzero(s->window + s->high_water, (unsigned)init);
17499 // s->high_water += init;
17500 // }
17501 // }
17502 //
17503 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
17504 // "not enough room for search");
17505}
17506
17507/* ===========================================================================
17508 * Copy without compression as much as possible from the input stream, return
17509 * the current block state.
17510 * This function does not insert new strings in the dictionary since
17511 * uncompressible data is probably not useful. This function is used
17512 * only for the level=0 compression option.
17513 * NOTE: this function should be optimized to avoid extra copying from
17514 * window to pending_buf.
17515 */
17516function deflate_stored(s, flush) {
17517 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
17518 * to pending_buf_size, and each stored block has a 5 byte header:
17519 */
17520 let max_block_size = 0xffff;
17521
17522 if (max_block_size > s.pending_buf_size - 5) {
17523 max_block_size = s.pending_buf_size - 5;
17524 }
17525
17526 /* Copy as much as possible from input to output: */
17527 for (; ;) {
17528 /* Fill the window as much as possible: */
17529 if (s.lookahead <= 1) {
17530
17531 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
17532 // s->block_start >= (long)s->w_size, "slide too late");
17533 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
17534 // s.block_start >= s.w_size)) {
17535 // throw new Error("slide too late");
17536 // }
17537
17538 fill_window(s);
17539 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
17540 return BS_NEED_MORE;
17541 }
17542
17543 if (s.lookahead === 0) {
17544 break;
17545 }
17546 /* flush the current block */
17547 }
17548 //Assert(s->block_start >= 0L, "block gone");
17549 // if (s.block_start < 0) throw new Error("block gone");
17550
17551 s.strstart += s.lookahead;
17552 s.lookahead = 0;
17553
17554 /* Emit a stored block if pending_buf will be full: */
17555 const max_start = s.block_start + max_block_size;
17556
17557 if (s.strstart === 0 || s.strstart >= max_start) {
17558 /* strstart == 0 is possible when wraparound on 16-bit machine */
17559 s.lookahead = s.strstart - max_start;
17560 s.strstart = max_start;
17561 /*** FLUSH_BLOCK(s, 0); ***/
17562 flush_block_only(s, false);
17563 if (s.strm.avail_out === 0) {
17564 return BS_NEED_MORE;
17565 }
17566 /***/
17567
17568
17569 }
17570 /* Flush if we may have to slide, otherwise block_start may become
17571 * negative and the data will be gone:
17572 */
17573 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
17574 /*** FLUSH_BLOCK(s, 0); ***/
17575 flush_block_only(s, false);
17576 if (s.strm.avail_out === 0) {
17577 return BS_NEED_MORE;
17578 }
17579 /***/
17580 }
17581 }
17582
17583 s.insert = 0;
17584
17585 if (flush === Z_FINISH) {
17586 /*** FLUSH_BLOCK(s, 1); ***/
17587 flush_block_only(s, true);
17588 if (s.strm.avail_out === 0) {
17589 return BS_FINISH_STARTED;
17590 }
17591 /***/
17592 return BS_FINISH_DONE;
17593 }
17594
17595 if (s.strstart > s.block_start) {
17596 /*** FLUSH_BLOCK(s, 0); ***/
17597 flush_block_only(s, false);
17598 if (s.strm.avail_out === 0) {
17599 return BS_NEED_MORE;
17600 }
17601 /***/
17602 }
17603
17604 return BS_NEED_MORE;
17605}
17606
17607/* ===========================================================================
17608 * Compress as much as possible from the input stream, return the current
17609 * block state.
17610 * This function does not perform lazy evaluation of matches and inserts
17611 * new strings in the dictionary only for unmatched strings or for short
17612 * matches. It is used only for the fast compression options.
17613 */
17614function deflate_fast(s, flush) {
17615 let hash_head; /* head of the hash chain */
17616 let bflush; /* set if current block must be flushed */
17617
17618 for (; ;) {
17619 /* Make sure that we always have enough lookahead, except
17620 * at the end of the input file. We need MAX_MATCH bytes
17621 * for the next match, plus MIN_MATCH bytes to insert the
17622 * string following the next match.
17623 */
17624 if (s.lookahead < MIN_LOOKAHEAD) {
17625 fill_window(s);
17626 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17627 return BS_NEED_MORE;
17628 }
17629 if (s.lookahead === 0) {
17630 break; /* flush the current block */
17631 }
17632 }
17633
17634 /* Insert the string window[strstart .. strstart+2] in the
17635 * dictionary, and set hash_head to the head of the hash chain:
17636 */
17637 hash_head = 0/*NIL*/;
17638 if (s.lookahead >= MIN_MATCH$1) {
17639 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17640 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17641 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17642 s.head[s.ins_h] = s.strstart;
17643 /***/
17644 }
17645
17646 /* Find the longest match, discarding those <= prev_length.
17647 * At this point we have always match_length < MIN_MATCH
17648 */
17649 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
17650 /* To simplify the code, we prevent matches with the string
17651 * of window index 0 (in particular we have to avoid a match
17652 * of the string with itself at the start of the input file).
17653 */
17654 s.match_length = longest_match(s, hash_head);
17655 /* longest_match() sets match_start */
17656 }
17657 if (s.match_length >= MIN_MATCH$1) {
17658 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
17659
17660 /*** _tr_tally_dist(s, s.strstart - s.match_start,
17661 s.match_length - MIN_MATCH, bflush); ***/
17662 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
17663
17664 s.lookahead -= s.match_length;
17665
17666 /* Insert new strings in the hash table only if the match length
17667 * is not too large. This saves time but degrades compression.
17668 */
17669 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
17670 s.match_length--; /* string at strstart already in table */
17671 do {
17672 s.strstart++;
17673 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17674 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17675 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17676 s.head[s.ins_h] = s.strstart;
17677 /***/
17678 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
17679 * always MIN_MATCH bytes ahead.
17680 */
17681 } while (--s.match_length !== 0);
17682 s.strstart++;
17683 } else {
17684 s.strstart += s.match_length;
17685 s.match_length = 0;
17686 s.ins_h = s.window[s.strstart];
17687 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
17688 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
17689
17690 //#if MIN_MATCH != 3
17691 // Call UPDATE_HASH() MIN_MATCH-3 more times
17692 //#endif
17693 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
17694 * matter since it will be recomputed at next deflate call.
17695 */
17696 }
17697 } else {
17698 /* No match, output a literal byte */
17699 //Tracevv((stderr,"%c", s.window[s.strstart]));
17700 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17701 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17702
17703 s.lookahead--;
17704 s.strstart++;
17705 }
17706 if (bflush) {
17707 /*** FLUSH_BLOCK(s, 0); ***/
17708 flush_block_only(s, false);
17709 if (s.strm.avail_out === 0) {
17710 return BS_NEED_MORE;
17711 }
17712 /***/
17713 }
17714 }
17715 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
17716 if (flush === Z_FINISH) {
17717 /*** FLUSH_BLOCK(s, 1); ***/
17718 flush_block_only(s, true);
17719 if (s.strm.avail_out === 0) {
17720 return BS_FINISH_STARTED;
17721 }
17722 /***/
17723 return BS_FINISH_DONE;
17724 }
17725 if (s.last_lit) {
17726 /*** FLUSH_BLOCK(s, 0); ***/
17727 flush_block_only(s, false);
17728 if (s.strm.avail_out === 0) {
17729 return BS_NEED_MORE;
17730 }
17731 /***/
17732 }
17733 return BS_BLOCK_DONE;
17734}
17735
17736/* ===========================================================================
17737 * Same as above, but achieves better compression. We use a lazy
17738 * evaluation for matches: a match is finally adopted only if there is
17739 * no better match at the next window position.
17740 */
17741function deflate_slow(s, flush) {
17742 let hash_head; /* head of hash chain */
17743 let bflush; /* set if current block must be flushed */
17744
17745 let max_insert;
17746
17747 /* Process the input block. */
17748 for (; ;) {
17749 /* Make sure that we always have enough lookahead, except
17750 * at the end of the input file. We need MAX_MATCH bytes
17751 * for the next match, plus MIN_MATCH bytes to insert the
17752 * string following the next match.
17753 */
17754 if (s.lookahead < MIN_LOOKAHEAD) {
17755 fill_window(s);
17756 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17757 return BS_NEED_MORE;
17758 }
17759 if (s.lookahead === 0) { break; } /* flush the current block */
17760 }
17761
17762 /* Insert the string window[strstart .. strstart+2] in the
17763 * dictionary, and set hash_head to the head of the hash chain:
17764 */
17765 hash_head = 0/*NIL*/;
17766 if (s.lookahead >= MIN_MATCH$1) {
17767 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17768 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17769 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17770 s.head[s.ins_h] = s.strstart;
17771 /***/
17772 }
17773
17774 /* Find the longest match, discarding those <= prev_length.
17775 */
17776 s.prev_length = s.match_length;
17777 s.prev_match = s.match_start;
17778 s.match_length = MIN_MATCH$1 - 1;
17779
17780 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
17781 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
17782 /* To simplify the code, we prevent matches with the string
17783 * of window index 0 (in particular we have to avoid a match
17784 * of the string with itself at the start of the input file).
17785 */
17786 s.match_length = longest_match(s, hash_head);
17787 /* longest_match() sets match_start */
17788
17789 if (s.match_length <= 5 &&
17790 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
17791
17792 /* If prev_match is also MIN_MATCH, match_start is garbage
17793 * but we will ignore the current match anyway.
17794 */
17795 s.match_length = MIN_MATCH$1 - 1;
17796 }
17797 }
17798 /* If there was a match at the previous step and the current
17799 * match is not better, output the previous match:
17800 */
17801 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
17802 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
17803 /* Do not insert strings in hash table beyond this. */
17804
17805 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
17806
17807 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
17808 s.prev_length - MIN_MATCH, bflush);***/
17809 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
17810 /* Insert in hash table all strings up to the end of the match.
17811 * strstart-1 and strstart are already inserted. If there is not
17812 * enough lookahead, the last two strings are not inserted in
17813 * the hash table.
17814 */
17815 s.lookahead -= s.prev_length - 1;
17816 s.prev_length -= 2;
17817 do {
17818 if (++s.strstart <= max_insert) {
17819 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17820 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17821 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17822 s.head[s.ins_h] = s.strstart;
17823 /***/
17824 }
17825 } while (--s.prev_length !== 0);
17826 s.match_available = 0;
17827 s.match_length = MIN_MATCH$1 - 1;
17828 s.strstart++;
17829
17830 if (bflush) {
17831 /*** FLUSH_BLOCK(s, 0); ***/
17832 flush_block_only(s, false);
17833 if (s.strm.avail_out === 0) {
17834 return BS_NEED_MORE;
17835 }
17836 /***/
17837 }
17838
17839 } else if (s.match_available) {
17840 /* If there was no match at the previous position, output a
17841 * single literal. If there was a match but the current match
17842 * is longer, truncate the previous match to a single literal.
17843 */
17844 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17845 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17846 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17847
17848 if (bflush) {
17849 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
17850 flush_block_only(s, false);
17851 /***/
17852 }
17853 s.strstart++;
17854 s.lookahead--;
17855 if (s.strm.avail_out === 0) {
17856 return BS_NEED_MORE;
17857 }
17858 } else {
17859 /* There is no previous match to compare with, wait for
17860 * the next step to decide.
17861 */
17862 s.match_available = 1;
17863 s.strstart++;
17864 s.lookahead--;
17865 }
17866 }
17867 //Assert (flush != Z_NO_FLUSH, "no flush?");
17868 if (s.match_available) {
17869 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17870 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17871 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17872
17873 s.match_available = 0;
17874 }
17875 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
17876 if (flush === Z_FINISH) {
17877 /*** FLUSH_BLOCK(s, 1); ***/
17878 flush_block_only(s, true);
17879 if (s.strm.avail_out === 0) {
17880 return BS_FINISH_STARTED;
17881 }
17882 /***/
17883 return BS_FINISH_DONE;
17884 }
17885 if (s.last_lit) {
17886 /*** FLUSH_BLOCK(s, 0); ***/
17887 flush_block_only(s, false);
17888 if (s.strm.avail_out === 0) {
17889 return BS_NEED_MORE;
17890 }
17891 /***/
17892 }
17893
17894 return BS_BLOCK_DONE;
17895}
17896
17897
17898/* ===========================================================================
17899 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
17900 * one. Do not maintain a hash table. (It will be regenerated if this run of
17901 * deflate switches away from Z_RLE.)
17902 */
17903function deflate_rle(s, flush) {
17904 let bflush; /* set if current block must be flushed */
17905 let prev; /* byte at distance one to match */
17906 let scan, strend; /* scan goes up to strend for length of run */
17907
17908 const _win = s.window;
17909
17910 for (; ;) {
17911 /* Make sure that we always have enough lookahead, except
17912 * at the end of the input file. We need MAX_MATCH bytes
17913 * for the longest run, plus one for the unrolled loop.
17914 */
17915 if (s.lookahead <= MAX_MATCH$1) {
17916 fill_window(s);
17917 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
17918 return BS_NEED_MORE;
17919 }
17920 if (s.lookahead === 0) { break; } /* flush the current block */
17921 }
17922
17923 /* See how many times the previous byte repeats */
17924 s.match_length = 0;
17925 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
17926 scan = s.strstart - 1;
17927 prev = _win[scan];
17928 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
17929 strend = s.strstart + MAX_MATCH$1;
17930 do {
17931 /*jshint noempty:false*/
17932 } while (prev === _win[++scan] && prev === _win[++scan] &&
17933 prev === _win[++scan] && prev === _win[++scan] &&
17934 prev === _win[++scan] && prev === _win[++scan] &&
17935 prev === _win[++scan] && prev === _win[++scan] &&
17936 scan < strend);
17937 s.match_length = MAX_MATCH$1 - (strend - scan);
17938 if (s.match_length > s.lookahead) {
17939 s.match_length = s.lookahead;
17940 }
17941 }
17942 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
17943 }
17944
17945 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
17946 if (s.match_length >= MIN_MATCH$1) {
17947 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
17948
17949 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
17950 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
17951
17952 s.lookahead -= s.match_length;
17953 s.strstart += s.match_length;
17954 s.match_length = 0;
17955 } else {
17956 /* No match, output a literal byte */
17957 //Tracevv((stderr,"%c", s->window[s->strstart]));
17958 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17959 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17960
17961 s.lookahead--;
17962 s.strstart++;
17963 }
17964 if (bflush) {
17965 /*** FLUSH_BLOCK(s, 0); ***/
17966 flush_block_only(s, false);
17967 if (s.strm.avail_out === 0) {
17968 return BS_NEED_MORE;
17969 }
17970 /***/
17971 }
17972 }
17973 s.insert = 0;
17974 if (flush === Z_FINISH) {
17975 /*** FLUSH_BLOCK(s, 1); ***/
17976 flush_block_only(s, true);
17977 if (s.strm.avail_out === 0) {
17978 return BS_FINISH_STARTED;
17979 }
17980 /***/
17981 return BS_FINISH_DONE;
17982 }
17983 if (s.last_lit) {
17984 /*** FLUSH_BLOCK(s, 0); ***/
17985 flush_block_only(s, false);
17986 if (s.strm.avail_out === 0) {
17987 return BS_NEED_MORE;
17988 }
17989 /***/
17990 }
17991 return BS_BLOCK_DONE;
17992}
17993
17994/* ===========================================================================
17995 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
17996 * (It will be regenerated if this run of deflate switches away from Huffman.)
17997 */
17998function deflate_huff(s, flush) {
17999 let bflush; /* set if current block must be flushed */
18000
18001 for (; ;) {
18002 /* Make sure that we have a literal to write. */
18003 if (s.lookahead === 0) {
18004 fill_window(s);
18005 if (s.lookahead === 0) {
18006 if (flush === Z_NO_FLUSH) {
18007 return BS_NEED_MORE;
18008 }
18009 break; /* flush the current block */
18010 }
18011 }
18012
18013 /* Output a literal byte */
18014 s.match_length = 0;
18015 //Tracevv((stderr,"%c", s->window[s->strstart]));
18016 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
18017 bflush = _tr_tally(s, 0, s.window[s.strstart]);
18018 s.lookahead--;
18019 s.strstart++;
18020 if (bflush) {
18021 /*** FLUSH_BLOCK(s, 0); ***/
18022 flush_block_only(s, false);
18023 if (s.strm.avail_out === 0) {
18024 return BS_NEED_MORE;
18025 }
18026 /***/
18027 }
18028 }
18029 s.insert = 0;
18030 if (flush === Z_FINISH) {
18031 /*** FLUSH_BLOCK(s, 1); ***/
18032 flush_block_only(s, true);
18033 if (s.strm.avail_out === 0) {
18034 return BS_FINISH_STARTED;
18035 }
18036 /***/
18037 return BS_FINISH_DONE;
18038 }
18039 if (s.last_lit) {
18040 /*** FLUSH_BLOCK(s, 0); ***/
18041 flush_block_only(s, false);
18042 if (s.strm.avail_out === 0) {
18043 return BS_NEED_MORE;
18044 }
18045 /***/
18046 }
18047 return BS_BLOCK_DONE;
18048}
18049
18050/* Values for max_lazy_match, good_match and max_chain_length, depending on
18051 * the desired pack level (0..9). The values given below have been tuned to
18052 * exclude worst case performance for pathological files. Better values may be
18053 * found for specific files.
18054 */
18055class Config {
18056 constructor(good_length, max_lazy, nice_length, max_chain, func) {
18057 this.good_length = good_length;
18058 this.max_lazy = max_lazy;
18059 this.nice_length = nice_length;
18060 this.max_chain = max_chain;
18061 this.func = func;
18062 }
18063}
18064const configuration_table = [
18065 /* good lazy nice chain */
18066 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
18067 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
18068 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
18069 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
18070
18071 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
18072 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
18073 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
18074 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
18075 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
18076 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
18077];
18078
18079
18080/* ===========================================================================
18081 * Initialize the "longest match" routines for a new zlib stream
18082 */
18083function lm_init(s) {
18084 s.window_size = 2 * s.w_size;
18085
18086 /*** CLEAR_HASH(s); ***/
18087 zero$2(s.head); // Fill with NIL (= 0);
18088
18089 /* Set the default configuration parameters:
18090 */
18091 s.max_lazy_match = configuration_table[s.level].max_lazy;
18092 s.good_match = configuration_table[s.level].good_length;
18093 s.nice_match = configuration_table[s.level].nice_length;
18094 s.max_chain_length = configuration_table[s.level].max_chain;
18095
18096 s.strstart = 0;
18097 s.block_start = 0;
18098 s.lookahead = 0;
18099 s.insert = 0;
18100 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18101 s.match_available = 0;
18102 s.ins_h = 0;
18103}
18104
18105class DeflateState {
18106 constructor() {
18107 this.strm = null; /* pointer back to this zlib stream */
18108 this.status = 0; /* as the name implies */
18109 this.pending_buf = null; /* output still pending */
18110 this.pending_buf_size = 0; /* size of pending_buf */
18111 this.pending_out = 0; /* next pending byte to output to the stream */
18112 this.pending = 0; /* nb of bytes in the pending buffer */
18113 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
18114 this.gzhead = null; /* gzip header information to write */
18115 this.gzindex = 0; /* where in extra, name, or comment */
18116 this.method = Z_DEFLATED; /* can only be DEFLATED */
18117 this.last_flush = -1; /* value of flush param for previous deflate call */
18118
18119 this.w_size = 0; /* LZ77 window size (32K by default) */
18120 this.w_bits = 0; /* log2(w_size) (8..16) */
18121 this.w_mask = 0; /* w_size - 1 */
18122
18123 this.window = null;
18124 /* Sliding window. Input bytes are read into the second half of the window,
18125 * and move to the first half later to keep a dictionary of at least wSize
18126 * bytes. With this organization, matches are limited to a distance of
18127 * wSize-MAX_MATCH bytes, but this ensures that IO is always
18128 * performed with a length multiple of the block size.
18129 */
18130
18131 this.window_size = 0;
18132 /* Actual size of window: 2*wSize, except when the user input buffer
18133 * is directly used as sliding window.
18134 */
18135
18136 this.prev = null;
18137 /* Link to older string with same hash index. To limit the size of this
18138 * array to 64K, this link is maintained only for the last 32K strings.
18139 * An index in this array is thus a window index modulo 32K.
18140 */
18141
18142 this.head = null; /* Heads of the hash chains or NIL. */
18143
18144 this.ins_h = 0; /* hash index of string to be inserted */
18145 this.hash_size = 0; /* number of elements in hash table */
18146 this.hash_bits = 0; /* log2(hash_size) */
18147 this.hash_mask = 0; /* hash_size-1 */
18148
18149 this.hash_shift = 0;
18150 /* Number of bits by which ins_h must be shifted at each input
18151 * step. It must be such that after MIN_MATCH steps, the oldest
18152 * byte no longer takes part in the hash key, that is:
18153 * hash_shift * MIN_MATCH >= hash_bits
18154 */
18155
18156 this.block_start = 0;
18157 /* Window position at the beginning of the current output block. Gets
18158 * negative when the window is moved backwards.
18159 */
18160
18161 this.match_length = 0; /* length of best match */
18162 this.prev_match = 0; /* previous match */
18163 this.match_available = 0; /* set if previous match exists */
18164 this.strstart = 0; /* start of string to insert */
18165 this.match_start = 0; /* start of matching string */
18166 this.lookahead = 0; /* number of valid bytes ahead in window */
18167
18168 this.prev_length = 0;
18169 /* Length of the best match at previous step. Matches not greater than this
18170 * are discarded. This is used in the lazy match evaluation.
18171 */
18172
18173 this.max_chain_length = 0;
18174 /* To speed up deflation, hash chains are never searched beyond this
18175 * length. A higher limit improves compression ratio but degrades the
18176 * speed.
18177 */
18178
18179 this.max_lazy_match = 0;
18180 /* Attempt to find a better match only when the current match is strictly
18181 * smaller than this value. This mechanism is used only for compression
18182 * levels >= 4.
18183 */
18184 // That's alias to max_lazy_match, don't use directly
18185 //this.max_insert_length = 0;
18186 /* Insert new strings in the hash table only if the match length is not
18187 * greater than this length. This saves time but degrades compression.
18188 * max_insert_length is used only for compression levels <= 3.
18189 */
18190
18191 this.level = 0; /* compression level (1..9) */
18192 this.strategy = 0; /* favor or force Huffman coding*/
18193
18194 this.good_match = 0;
18195 /* Use a faster search when the previous match is longer than this */
18196
18197 this.nice_match = 0; /* Stop searching when current match exceeds this */
18198
18199 /* used by trees.c: */
18200
18201 /* Didn't use ct_data typedef below to suppress compiler warning */
18202
18203 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
18204 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
18205 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
18206
18207 // Use flat array of DOUBLE size, with interleaved fata,
18208 // because JS does not support effective
18209 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
18210 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
18211 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
18212 zero$2(this.dyn_ltree);
18213 zero$2(this.dyn_dtree);
18214 zero$2(this.bl_tree);
18215
18216 this.l_desc = null; /* desc. for literal tree */
18217 this.d_desc = null; /* desc. for distance tree */
18218 this.bl_desc = null; /* desc. for bit length tree */
18219
18220 //ush bl_count[MAX_BITS+1];
18221 this.bl_count = new Buf16(MAX_BITS$1 + 1);
18222 /* number of codes at each bit length for an optimal tree */
18223
18224 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
18225 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
18226 zero$2(this.heap);
18227
18228 this.heap_len = 0; /* number of elements in the heap */
18229 this.heap_max = 0; /* element of largest frequency */
18230 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
18231 * The same heap array is used to build all trees.
18232 */
18233
18234 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
18235 zero$2(this.depth);
18236 /* Depth of each subtree used as tie breaker for trees of equal frequency
18237 */
18238
18239 this.l_buf = 0; /* buffer index for literals or lengths */
18240
18241 this.lit_bufsize = 0;
18242 /* Size of match buffer for literals/lengths. There are 4 reasons for
18243 * limiting lit_bufsize to 64K:
18244 * - frequencies can be kept in 16 bit counters
18245 * - if compression is not successful for the first block, all input
18246 * data is still in the window so we can still emit a stored block even
18247 * when input comes from standard input. (This can also be done for
18248 * all blocks if lit_bufsize is not greater than 32K.)
18249 * - if compression is not successful for a file smaller than 64K, we can
18250 * even emit a stored file instead of a stored block (saving 5 bytes).
18251 * This is applicable only for zip (not gzip or zlib).
18252 * - creating new Huffman trees less frequently may not provide fast
18253 * adaptation to changes in the input data statistics. (Take for
18254 * example a binary file with poorly compressible code followed by
18255 * a highly compressible string table.) Smaller buffer sizes give
18256 * fast adaptation but have of course the overhead of transmitting
18257 * trees more frequently.
18258 * - I can't count above 4
18259 */
18260
18261 this.last_lit = 0; /* running index in l_buf */
18262
18263 this.d_buf = 0;
18264 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
18265 * the same number of elements. To use different lengths, an extra flag
18266 * array would be necessary.
18267 */
18268
18269 this.opt_len = 0; /* bit length of current block with optimal trees */
18270 this.static_len = 0; /* bit length of current block with static trees */
18271 this.matches = 0; /* number of string matches in current block */
18272 this.insert = 0; /* bytes at end of window left to insert */
18273
18274
18275 this.bi_buf = 0;
18276 /* Output buffer. bits are inserted starting at the bottom (least
18277 * significant bits).
18278 */
18279 this.bi_valid = 0;
18280 /* Number of valid bits in bi_buf. All bits above the last valid bit
18281 * are always zero.
18282 */
18283
18284 // Used for window memory init. We safely ignore it for JS. That makes
18285 // sense only for pointers and memory check tools.
18286 //this.high_water = 0;
18287 /* High water mark offset in window for initialized bytes -- bytes above
18288 * this are set to zero in order to avoid memory check warnings when
18289 * longest match routines access bytes past the input. This is then
18290 * updated to the new high water mark.
18291 */
18292 }
18293}
18294
18295function deflateResetKeep(strm) {
18296 let s;
18297
18298 if (!strm || !strm.state) {
18299 return err(strm, Z_STREAM_ERROR);
18300 }
18301
18302 strm.total_in = strm.total_out = 0;
18303 strm.data_type = Z_UNKNOWN;
18304
18305 s = strm.state;
18306 s.pending = 0;
18307 s.pending_out = 0;
18308
18309 if (s.wrap < 0) {
18310 s.wrap = -s.wrap;
18311 /* was made negative by deflate(..., Z_FINISH); */
18312 }
18313 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
18314 strm.adler = (s.wrap === 2) ?
18315 0 // crc32(0, Z_NULL, 0)
18316 :
18317 1; // adler32(0, Z_NULL, 0)
18318 s.last_flush = Z_NO_FLUSH;
18319 _tr_init(s);
18320 return Z_OK;
18321}
18322
18323
18324function deflateReset(strm) {
18325 const ret = deflateResetKeep(strm);
18326 if (ret === Z_OK) {
18327 lm_init(strm.state);
18328 }
18329 return ret;
18330}
18331
18332
18333function deflateSetHeader(strm, head) {
18334 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18335 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
18336 strm.state.gzhead = head;
18337 return Z_OK;
18338}
18339
18340
18341function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
18342 if (!strm) { // === Z_NULL
18343 return Z_STREAM_ERROR;
18344 }
18345 let wrap = 1;
18346
18347 if (level === Z_DEFAULT_COMPRESSION) {
18348 level = 6;
18349 }
18350
18351 if (windowBits < 0) { /* suppress zlib wrapper */
18352 wrap = 0;
18353 windowBits = -windowBits;
18354 }
18355
18356 else if (windowBits > 15) {
18357 wrap = 2; /* write gzip wrapper instead */
18358 windowBits -= 16;
18359 }
18360
18361
18362 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
18363 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
18364 strategy < 0 || strategy > Z_FIXED) {
18365 return err(strm, Z_STREAM_ERROR);
18366 }
18367
18368
18369 if (windowBits === 8) {
18370 windowBits = 9;
18371 }
18372 /* until 256-byte window bug fixed */
18373
18374 const s = new DeflateState();
18375
18376 strm.state = s;
18377 s.strm = strm;
18378
18379 s.wrap = wrap;
18380 s.gzhead = null;
18381 s.w_bits = windowBits;
18382 s.w_size = 1 << s.w_bits;
18383 s.w_mask = s.w_size - 1;
18384
18385 s.hash_bits = memLevel + 7;
18386 s.hash_size = 1 << s.hash_bits;
18387 s.hash_mask = s.hash_size - 1;
18388 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
18389 s.window = new Buf8(s.w_size * 2);
18390 s.head = new Buf16(s.hash_size);
18391 s.prev = new Buf16(s.w_size);
18392
18393 // Don't need mem init magic for JS.
18394 //s.high_water = 0; /* nothing written to s->window yet */
18395
18396 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
18397
18398 s.pending_buf_size = s.lit_bufsize * 4;
18399
18400 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
18401 //s->pending_buf = (uchf *) overlay;
18402 s.pending_buf = new Buf8(s.pending_buf_size);
18403
18404 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
18405 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
18406 s.d_buf = 1 * s.lit_bufsize;
18407
18408 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
18409 s.l_buf = (1 + 2) * s.lit_bufsize;
18410
18411 s.level = level;
18412 s.strategy = strategy;
18413 s.method = method;
18414
18415 return deflateReset(strm);
18416}
18417
18418
18419function deflate(strm, flush) {
18420 let old_flush, s;
18421 let beg, val; // for gzip header write only
18422
18423 if (!strm || !strm.state ||
18424 flush > Z_BLOCK || flush < 0) {
18425 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
18426 }
18427
18428 s = strm.state;
18429
18430 if (!strm.output ||
18431 (!strm.input && strm.avail_in !== 0) ||
18432 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
18433 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
18434 }
18435
18436 s.strm = strm; /* just in case */
18437 old_flush = s.last_flush;
18438 s.last_flush = flush;
18439
18440 /* Write the header */
18441 if (s.status === INIT_STATE) {
18442
18443 if (s.wrap === 2) { // GZIP header
18444 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18445 put_byte(s, 31);
18446 put_byte(s, 139);
18447 put_byte(s, 8);
18448 if (!s.gzhead) { // s->gzhead == Z_NULL
18449 put_byte(s, 0);
18450 put_byte(s, 0);
18451 put_byte(s, 0);
18452 put_byte(s, 0);
18453 put_byte(s, 0);
18454 put_byte(s, s.level === 9 ? 2 :
18455 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18456 4 : 0));
18457 put_byte(s, OS_CODE);
18458 s.status = BUSY_STATE;
18459 }
18460 else {
18461 put_byte(s, (s.gzhead.text ? 1 : 0) +
18462 (s.gzhead.hcrc ? 2 : 0) +
18463 (!s.gzhead.extra ? 0 : 4) +
18464 (!s.gzhead.name ? 0 : 8) +
18465 (!s.gzhead.comment ? 0 : 16)
18466 );
18467 put_byte(s, s.gzhead.time & 0xff);
18468 put_byte(s, (s.gzhead.time >> 8) & 0xff);
18469 put_byte(s, (s.gzhead.time >> 16) & 0xff);
18470 put_byte(s, (s.gzhead.time >> 24) & 0xff);
18471 put_byte(s, s.level === 9 ? 2 :
18472 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18473 4 : 0));
18474 put_byte(s, s.gzhead.os & 0xff);
18475 if (s.gzhead.extra && s.gzhead.extra.length) {
18476 put_byte(s, s.gzhead.extra.length & 0xff);
18477 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
18478 }
18479 if (s.gzhead.hcrc) {
18480 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
18481 }
18482 s.gzindex = 0;
18483 s.status = EXTRA_STATE;
18484 }
18485 }
18486 else // DEFLATE header
18487 {
18488 let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
18489 let level_flags = -1;
18490
18491 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
18492 level_flags = 0;
18493 } else if (s.level < 6) {
18494 level_flags = 1;
18495 } else if (s.level === 6) {
18496 level_flags = 2;
18497 } else {
18498 level_flags = 3;
18499 }
18500 header |= (level_flags << 6);
18501 if (s.strstart !== 0) { header |= PRESET_DICT; }
18502 header += 31 - (header % 31);
18503
18504 s.status = BUSY_STATE;
18505 putShortMSB(s, header);
18506
18507 /* Save the adler32 of the preset dictionary: */
18508 if (s.strstart !== 0) {
18509 putShortMSB(s, strm.adler >>> 16);
18510 putShortMSB(s, strm.adler & 0xffff);
18511 }
18512 strm.adler = 1; // adler32(0L, Z_NULL, 0);
18513 }
18514 }
18515
18516 //#ifdef GZIP
18517 if (s.status === EXTRA_STATE) {
18518 if (s.gzhead.extra/* != Z_NULL*/) {
18519 beg = s.pending; /* start of bytes to update crc */
18520
18521 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
18522 if (s.pending === s.pending_buf_size) {
18523 if (s.gzhead.hcrc && s.pending > beg) {
18524 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18525 }
18526 flush_pending(strm);
18527 beg = s.pending;
18528 if (s.pending === s.pending_buf_size) {
18529 break;
18530 }
18531 }
18532 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
18533 s.gzindex++;
18534 }
18535 if (s.gzhead.hcrc && s.pending > beg) {
18536 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18537 }
18538 if (s.gzindex === s.gzhead.extra.length) {
18539 s.gzindex = 0;
18540 s.status = NAME_STATE;
18541 }
18542 }
18543 else {
18544 s.status = NAME_STATE;
18545 }
18546 }
18547 if (s.status === NAME_STATE) {
18548 if (s.gzhead.name/* != Z_NULL*/) {
18549 beg = s.pending; /* start of bytes to update crc */
18550 //int val;
18551
18552 do {
18553 if (s.pending === s.pending_buf_size) {
18554 if (s.gzhead.hcrc && s.pending > beg) {
18555 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18556 }
18557 flush_pending(strm);
18558 beg = s.pending;
18559 if (s.pending === s.pending_buf_size) {
18560 val = 1;
18561 break;
18562 }
18563 }
18564 // JS specific: little magic to add zero terminator to end of string
18565 if (s.gzindex < s.gzhead.name.length) {
18566 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
18567 } else {
18568 val = 0;
18569 }
18570 put_byte(s, val);
18571 } while (val !== 0);
18572
18573 if (s.gzhead.hcrc && s.pending > beg) {
18574 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18575 }
18576 if (val === 0) {
18577 s.gzindex = 0;
18578 s.status = COMMENT_STATE;
18579 }
18580 }
18581 else {
18582 s.status = COMMENT_STATE;
18583 }
18584 }
18585 if (s.status === COMMENT_STATE) {
18586 if (s.gzhead.comment/* != Z_NULL*/) {
18587 beg = s.pending; /* start of bytes to update crc */
18588 //int val;
18589
18590 do {
18591 if (s.pending === s.pending_buf_size) {
18592 if (s.gzhead.hcrc && s.pending > beg) {
18593 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18594 }
18595 flush_pending(strm);
18596 beg = s.pending;
18597 if (s.pending === s.pending_buf_size) {
18598 val = 1;
18599 break;
18600 }
18601 }
18602 // JS specific: little magic to add zero terminator to end of string
18603 if (s.gzindex < s.gzhead.comment.length) {
18604 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
18605 } else {
18606 val = 0;
18607 }
18608 put_byte(s, val);
18609 } while (val !== 0);
18610
18611 if (s.gzhead.hcrc && s.pending > beg) {
18612 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18613 }
18614 if (val === 0) {
18615 s.status = HCRC_STATE;
18616 }
18617 }
18618 else {
18619 s.status = HCRC_STATE;
18620 }
18621 }
18622 if (s.status === HCRC_STATE) {
18623 if (s.gzhead.hcrc) {
18624 if (s.pending + 2 > s.pending_buf_size) {
18625 flush_pending(strm);
18626 }
18627 if (s.pending + 2 <= s.pending_buf_size) {
18628 put_byte(s, strm.adler & 0xff);
18629 put_byte(s, (strm.adler >> 8) & 0xff);
18630 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18631 s.status = BUSY_STATE;
18632 }
18633 }
18634 else {
18635 s.status = BUSY_STATE;
18636 }
18637 }
18638 //#endif
18639
18640 /* Flush as much pending output as possible */
18641 if (s.pending !== 0) {
18642 flush_pending(strm);
18643 if (strm.avail_out === 0) {
18644 /* Since avail_out is 0, deflate will be called again with
18645 * more output space, but possibly with both pending and
18646 * avail_in equal to zero. There won't be anything to do,
18647 * but this is not an error situation so make sure we
18648 * return OK instead of BUF_ERROR at next call of deflate:
18649 */
18650 s.last_flush = -1;
18651 return Z_OK;
18652 }
18653
18654 /* Make sure there is something to do and avoid duplicate consecutive
18655 * flushes. For repeated and useless calls with Z_FINISH, we keep
18656 * returning Z_STREAM_END instead of Z_BUF_ERROR.
18657 */
18658 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
18659 flush !== Z_FINISH) {
18660 return err(strm, Z_BUF_ERROR);
18661 }
18662
18663 /* User must not provide more input after the first FINISH: */
18664 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
18665 return err(strm, Z_BUF_ERROR);
18666 }
18667
18668 /* Start a new block or continue the current one.
18669 */
18670 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
18671 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
18672 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
18673 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
18674 configuration_table[s.level].func(s, flush));
18675
18676 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
18677 s.status = FINISH_STATE;
18678 }
18679 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
18680 if (strm.avail_out === 0) {
18681 s.last_flush = -1;
18682 /* avoid BUF_ERROR next call, see above */
18683 }
18684 return Z_OK;
18685 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
18686 * of deflate should use the same flush parameter to make sure
18687 * that the flush is complete. So we don't have to output an
18688 * empty block here, this will be done at next call. This also
18689 * ensures that for a very small output buffer, we emit at most
18690 * one empty block.
18691 */
18692 }
18693 if (bstate === BS_BLOCK_DONE) {
18694 if (flush === Z_PARTIAL_FLUSH) {
18695 _tr_align(s);
18696 }
18697 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
18698
18699 _tr_stored_block(s, 0, 0, false);
18700 /* For a full flush, this empty block will be recognized
18701 * as a special marker by inflate_sync().
18702 */
18703 if (flush === Z_FULL_FLUSH) {
18704 /*** CLEAR_HASH(s); ***/ /* forget history */
18705 zero$2(s.head); // Fill with NIL (= 0);
18706
18707 if (s.lookahead === 0) {
18708 s.strstart = 0;
18709 s.block_start = 0;
18710 s.insert = 0;
18711 }
18712 }
18713 }
18714 flush_pending(strm);
18715 if (strm.avail_out === 0) {
18716 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
18717 return Z_OK;
18718 }
18719 }
18720 }
18721 //Assert(strm->avail_out > 0, "bug2");
18722 //if (strm.avail_out <= 0) { throw new Error("bug2");}
18723
18724 if (flush !== Z_FINISH) { return Z_OK; }
18725 if (s.wrap <= 0) { return Z_STREAM_END; }
18726
18727 /* Write the trailer */
18728 if (s.wrap === 2) {
18729 put_byte(s, strm.adler & 0xff);
18730 put_byte(s, (strm.adler >> 8) & 0xff);
18731 put_byte(s, (strm.adler >> 16) & 0xff);
18732 put_byte(s, (strm.adler >> 24) & 0xff);
18733 put_byte(s, strm.total_in & 0xff);
18734 put_byte(s, (strm.total_in >> 8) & 0xff);
18735 put_byte(s, (strm.total_in >> 16) & 0xff);
18736 put_byte(s, (strm.total_in >> 24) & 0xff);
18737 }
18738 else {
18739 putShortMSB(s, strm.adler >>> 16);
18740 putShortMSB(s, strm.adler & 0xffff);
18741 }
18742
18743 flush_pending(strm);
18744 /* If avail_out is zero, the application will call deflate again
18745 * to flush the rest.
18746 */
18747 if (s.wrap > 0) { s.wrap = -s.wrap; }
18748 /* write the trailer only once! */
18749 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
18750}
18751
18752function deflateEnd(strm) {
18753 let status;
18754
18755 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18756 return Z_STREAM_ERROR;
18757 }
18758
18759 status = strm.state.status;
18760 if (status !== INIT_STATE &&
18761 status !== EXTRA_STATE &&
18762 status !== NAME_STATE &&
18763 status !== COMMENT_STATE &&
18764 status !== HCRC_STATE &&
18765 status !== BUSY_STATE &&
18766 status !== FINISH_STATE
18767 ) {
18768 return err(strm, Z_STREAM_ERROR);
18769 }
18770
18771 strm.state = null;
18772
18773 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
18774}
18775
18776
18777/* =========================================================================
18778 * Initializes the compression dictionary from the given byte
18779 * sequence without producing any compressed output.
18780 */
18781function deflateSetDictionary(strm, dictionary) {
18782 let dictLength = dictionary.length;
18783
18784 let s;
18785 let str, n;
18786 let wrap;
18787 let avail;
18788 let next;
18789 let input;
18790 let tmpDict;
18791
18792 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18793 return Z_STREAM_ERROR;
18794 }
18795
18796 s = strm.state;
18797 wrap = s.wrap;
18798
18799 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
18800 return Z_STREAM_ERROR;
18801 }
18802
18803 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
18804 if (wrap === 1) {
18805 /* adler32(strm->adler, dictionary, dictLength); */
18806 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
18807 }
18808
18809 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
18810
18811 /* if dictionary would fill window, just replace the history */
18812 if (dictLength >= s.w_size) {
18813 if (wrap === 0) { /* already empty otherwise */
18814 /*** CLEAR_HASH(s); ***/
18815 zero$2(s.head); // Fill with NIL (= 0);
18816 s.strstart = 0;
18817 s.block_start = 0;
18818 s.insert = 0;
18819 }
18820 /* use the tail */
18821 // dictionary = dictionary.slice(dictLength - s.w_size);
18822 tmpDict = new Buf8(s.w_size);
18823 arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
18824 dictionary = tmpDict;
18825 dictLength = s.w_size;
18826 }
18827 /* insert dictionary into window and hash */
18828 avail = strm.avail_in;
18829 next = strm.next_in;
18830 input = strm.input;
18831 strm.avail_in = dictLength;
18832 strm.next_in = 0;
18833 strm.input = dictionary;
18834 fill_window(s);
18835 while (s.lookahead >= MIN_MATCH$1) {
18836 str = s.strstart;
18837 n = s.lookahead - (MIN_MATCH$1 - 1);
18838 do {
18839 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
18840 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
18841
18842 s.prev[str & s.w_mask] = s.head[s.ins_h];
18843
18844 s.head[s.ins_h] = str;
18845 str++;
18846 } while (--n);
18847 s.strstart = str;
18848 s.lookahead = MIN_MATCH$1 - 1;
18849 fill_window(s);
18850 }
18851 s.strstart += s.lookahead;
18852 s.block_start = s.strstart;
18853 s.insert = s.lookahead;
18854 s.lookahead = 0;
18855 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18856 s.match_available = 0;
18857 strm.next_in = next;
18858 strm.input = input;
18859 strm.avail_in = avail;
18860 s.wrap = wrap;
18861 return Z_OK;
18862}
18863
18864/* Not implemented
18865exports.deflateBound = deflateBound;
18866exports.deflateCopy = deflateCopy;
18867exports.deflateParams = deflateParams;
18868exports.deflatePending = deflatePending;
18869exports.deflatePrime = deflatePrime;
18870exports.deflateTune = deflateTune;
18871*/
18872
18873// String encode/decode helpers
18874
18875try {
18876 String.fromCharCode.apply(null, [ 0 ]);
18877} catch (__) {
18878}
18879try {
18880 String.fromCharCode.apply(null, new Uint8Array(1));
18881} catch (__) {
18882}
18883
18884
18885// Table with utf8 lengths (calculated by first byte of sequence)
18886// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
18887// because max possible codepoint is 0x10ffff
18888const _utf8len = new Buf8(256);
18889for (let q = 0; q < 256; q++) {
18890 _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
18891}
18892_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
18893
18894
18895// convert string to array (typed, when possible)
18896function string2buf (str) {
18897 let c, c2, m_pos, i, buf_len = 0;
18898 const str_len = str.length;
18899
18900 // count binary size
18901 for (m_pos = 0; m_pos < str_len; m_pos++) {
18902 c = str.charCodeAt(m_pos);
18903 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18904 c2 = str.charCodeAt(m_pos + 1);
18905 if ((c2 & 0xfc00) === 0xdc00) {
18906 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18907 m_pos++;
18908 }
18909 }
18910 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
18911 }
18912
18913 // allocate buffer
18914 const buf = new Buf8(buf_len);
18915
18916 // convert
18917 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
18918 c = str.charCodeAt(m_pos);
18919 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18920 c2 = str.charCodeAt(m_pos + 1);
18921 if ((c2 & 0xfc00) === 0xdc00) {
18922 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18923 m_pos++;
18924 }
18925 }
18926 if (c < 0x80) {
18927 /* one byte */
18928 buf[i++] = c;
18929 } else if (c < 0x800) {
18930 /* two bytes */
18931 buf[i++] = 0xC0 | c >>> 6;
18932 buf[i++] = 0x80 | c & 0x3f;
18933 } else if (c < 0x10000) {
18934 /* three bytes */
18935 buf[i++] = 0xE0 | c >>> 12;
18936 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18937 buf[i++] = 0x80 | c & 0x3f;
18938 } else {
18939 /* four bytes */
18940 buf[i++] = 0xf0 | c >>> 18;
18941 buf[i++] = 0x80 | c >>> 12 & 0x3f;
18942 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18943 buf[i++] = 0x80 | c & 0x3f;
18944 }
18945 }
18946
18947 return buf;
18948}
18949
18950
18951// Convert binary string (typed, when possible)
18952function binstring2buf (str) {
18953 const buf = new Buf8(str.length);
18954 for (let i = 0, len = buf.length; i < len; i++) {
18955 buf[i] = str.charCodeAt(i);
18956 }
18957 return buf;
18958}
18959
18960// (C) 1995-2013 Jean-loup Gailly and Mark Adler
18961// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18962//
18963// This software is provided 'as-is', without any express or implied
18964// warranty. In no event will the authors be held liable for any damages
18965// arising from the use of this software.
18966//
18967// Permission is granted to anyone to use this software for any purpose,
18968// including commercial applications, and to alter it and redistribute it
18969// freely, subject to the following restrictions:
18970//
18971// 1. The origin of this software must not be misrepresented; you must not
18972// claim that you wrote the original software. If you use this software
18973// in a product, an acknowledgment in the product documentation would be
18974// appreciated but is not required.
18975// 2. Altered source versions must be plainly marked as such, and must not be
18976// misrepresented as being the original software.
18977// 3. This notice may not be removed or altered from any source distribution.
18978
18979class ZStream {
18980 constructor() {
18981 /* next input byte */
18982 this.input = null; // JS specific, because we have no pointers
18983 this.next_in = 0;
18984 /* number of bytes available at input */
18985 this.avail_in = 0;
18986 /* total number of input bytes read so far */
18987 this.total_in = 0;
18988 /* next output byte should be put there */
18989 this.output = null; // JS specific, because we have no pointers
18990 this.next_out = 0;
18991 /* remaining free space at output */
18992 this.avail_out = 0;
18993 /* total number of bytes output so far */
18994 this.total_out = 0;
18995 /* last error message, NULL if no error */
18996 this.msg = ''/*Z_NULL*/;
18997 /* not visible by applications */
18998 this.state = null;
18999 /* best guess about the data type: binary or text */
19000 this.data_type = 2/*Z_UNKNOWN*/;
19001 /* adler32 value of the uncompressed data */
19002 this.adler = 0;
19003 }
19004}
19005
19006/* ===========================================================================*/
19007
19008
19009/**
19010 * class Deflate
19011 *
19012 * Generic JS-style wrapper for zlib calls. If you don't need
19013 * streaming behaviour - use more simple functions: [[deflate]],
19014 * [[deflateRaw]] and [[gzip]].
19015 **/
19016
19017/* internal
19018 * Deflate.chunks -> Array
19019 *
19020 * Chunks of output data, if [[Deflate#onData]] not overridden.
19021 **/
19022
19023/**
19024 * Deflate.result -> Uint8Array|Array
19025 *
19026 * Compressed result, generated by default [[Deflate#onData]]
19027 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
19028 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
19029 * push a chunk with explicit flush (call [[Deflate#push]] with
19030 * `Z_SYNC_FLUSH` param).
19031 **/
19032
19033/**
19034 * Deflate.err -> Number
19035 *
19036 * Error code after deflate finished. 0 (Z_OK) on success.
19037 * You will not need it in real life, because deflate errors
19038 * are possible only on wrong options or bad `onData` / `onEnd`
19039 * custom handlers.
19040 **/
19041
19042/**
19043 * Deflate.msg -> String
19044 *
19045 * Error message, if [[Deflate.err]] != 0
19046 **/
19047
19048
19049/**
19050 * new Deflate(options)
19051 * - options (Object): zlib deflate options.
19052 *
19053 * Creates new deflator instance with specified params. Throws exception
19054 * on bad params. Supported options:
19055 *
19056 * - `level`
19057 * - `windowBits`
19058 * - `memLevel`
19059 * - `strategy`
19060 * - `dictionary`
19061 *
19062 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
19063 * for more information on these.
19064 *
19065 * Additional options, for internal needs:
19066 *
19067 * - `chunkSize` - size of generated data chunks (16K by default)
19068 * - `raw` (Boolean) - do raw deflate
19069 * - `gzip` (Boolean) - create gzip wrapper
19070 * - `to` (String) - if equal to 'string', then result will be "binary string"
19071 * (each char code [0..255])
19072 * - `header` (Object) - custom header for gzip
19073 * - `text` (Boolean) - true if compressed data believed to be text
19074 * - `time` (Number) - modification time, unix timestamp
19075 * - `os` (Number) - operation system code
19076 * - `extra` (Array) - array of bytes with extra data (max 65536)
19077 * - `name` (String) - file name (binary string)
19078 * - `comment` (String) - comment (binary string)
19079 * - `hcrc` (Boolean) - true if header crc should be added
19080 *
19081 * ##### Example:
19082 *
19083 * ```javascript
19084 * var pako = void('pako')
19085 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
19086 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
19087 *
19088 * var deflate = new pako.Deflate({ level: 3});
19089 *
19090 * deflate.push(chunk1, false);
19091 * deflate.push(chunk2, true); // true -> last chunk
19092 *
19093 * if (deflate.err) { throw new Error(deflate.err); }
19094 *
19095 * console.log(deflate.result);
19096 * ```
19097 **/
19098
19099class Deflate {
19100 constructor(options) {
19101 this.options = {
19102 level: Z_DEFAULT_COMPRESSION,
19103 method: Z_DEFLATED,
19104 chunkSize: 16384,
19105 windowBits: 15,
19106 memLevel: 8,
19107 strategy: Z_DEFAULT_STRATEGY,
19108 ...(options || {})
19109 };
19110
19111 const opt = this.options;
19112
19113 if (opt.raw && (opt.windowBits > 0)) {
19114 opt.windowBits = -opt.windowBits;
19115 }
19116
19117 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
19118 opt.windowBits += 16;
19119 }
19120
19121 this.err = 0; // error code, if happens (0 = Z_OK)
19122 this.msg = ''; // error message
19123 this.ended = false; // used to avoid multiple onEnd() calls
19124 this.chunks = []; // chunks of compressed data
19125
19126 this.strm = new ZStream();
19127 this.strm.avail_out = 0;
19128
19129 var status = deflateInit2(
19130 this.strm,
19131 opt.level,
19132 opt.method,
19133 opt.windowBits,
19134 opt.memLevel,
19135 opt.strategy
19136 );
19137
19138 if (status !== Z_OK) {
19139 throw new Error(msg[status]);
19140 }
19141
19142 if (opt.header) {
19143 deflateSetHeader(this.strm, opt.header);
19144 }
19145
19146 if (opt.dictionary) {
19147 let dict;
19148 // Convert data if needed
19149 if (typeof opt.dictionary === 'string') {
19150 // If we need to compress text, change encoding to utf8.
19151 dict = string2buf(opt.dictionary);
19152 } else if (opt.dictionary instanceof ArrayBuffer) {
19153 dict = new Uint8Array(opt.dictionary);
19154 } else {
19155 dict = opt.dictionary;
19156 }
19157
19158 status = deflateSetDictionary(this.strm, dict);
19159
19160 if (status !== Z_OK) {
19161 throw new Error(msg[status]);
19162 }
19163
19164 this._dict_set = true;
19165 }
19166 }
19167
19168 /**
19169 * Deflate#push(data[, mode]) -> Boolean
19170 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
19171 * converted to utf8 byte sequence.
19172 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
19173 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
19174 *
19175 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
19176 * new compressed chunks. Returns `true` on success. The last data block must have
19177 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
19178 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
19179 * can use mode Z_SYNC_FLUSH, keeping the compression context.
19180 *
19181 * On fail call [[Deflate#onEnd]] with error code and return false.
19182 *
19183 * We strongly recommend to use `Uint8Array` on input for best speed (output
19184 * array format is detected automatically). Also, don't skip last param and always
19185 * use the same type in your code (boolean or number). That will improve JS speed.
19186 *
19187 * For regular `Array`-s make sure all elements are [0..255].
19188 *
19189 * ##### Example
19190 *
19191 * ```javascript
19192 * push(chunk, false); // push one of data chunks
19193 * ...
19194 * push(chunk, true); // push last chunk
19195 * ```
19196 **/
19197 push(data, mode) {
19198 const { strm, options: { chunkSize } } = this;
19199 var status, _mode;
19200
19201 if (this.ended) { return false; }
19202
19203 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
19204
19205 // Convert data if needed
19206 if (typeof data === 'string') {
19207 // If we need to compress text, change encoding to utf8.
19208 strm.input = string2buf(data);
19209 } else if (data instanceof ArrayBuffer) {
19210 strm.input = new Uint8Array(data);
19211 } else {
19212 strm.input = data;
19213 }
19214
19215 strm.next_in = 0;
19216 strm.avail_in = strm.input.length;
19217
19218 do {
19219 if (strm.avail_out === 0) {
19220 strm.output = new Buf8(chunkSize);
19221 strm.next_out = 0;
19222 strm.avail_out = chunkSize;
19223 }
19224 status = deflate(strm, _mode); /* no bad return value */
19225
19226 if (status !== Z_STREAM_END && status !== Z_OK) {
19227 this.onEnd(status);
19228 this.ended = true;
19229 return false;
19230 }
19231 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
19232 this.onData(shrinkBuf(strm.output, strm.next_out));
19233 }
19234 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
19235
19236 // Finalize on the last chunk.
19237 if (_mode === Z_FINISH) {
19238 status = deflateEnd(this.strm);
19239 this.onEnd(status);
19240 this.ended = true;
19241 return status === Z_OK;
19242 }
19243
19244 // callback interim results if Z_SYNC_FLUSH.
19245 if (_mode === Z_SYNC_FLUSH) {
19246 this.onEnd(Z_OK);
19247 strm.avail_out = 0;
19248 return true;
19249 }
19250
19251 return true;
19252 };
19253 /**
19254 * Deflate#onData(chunk) -> Void
19255 * - chunk (Uint8Array|Array|String): output data. Type of array depends
19256 * on js engine support. When string output requested, each chunk
19257 * will be string.
19258 *
19259 * By default, stores data blocks in `chunks[]` property and glue
19260 * those in `onEnd`. Override this handler, if you need another behaviour.
19261 **/
19262 onData(chunk) {
19263 this.chunks.push(chunk);
19264 };
19265
19266 /**
19267 * Deflate#onEnd(status) -> Void
19268 * - status (Number): deflate status. 0 (Z_OK) on success,
19269 * other if not.
19270 *
19271 * Called once after you tell deflate that the input stream is
19272 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
19273 * or if an error happened. By default - join collected chunks,
19274 * free memory and fill `results` / `err` properties.
19275 **/
19276 onEnd(status) {
19277 // On success - join
19278 if (status === Z_OK) {
19279 this.result = flattenChunks(this.chunks);
19280 }
19281 this.chunks = [];
19282 this.err = status;
19283 this.msg = this.strm.msg;
19284 };
19285}
19286
19287// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19288// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19289//
19290// This software is provided 'as-is', without any express or implied
19291// warranty. In no event will the authors be held liable for any damages
19292// arising from the use of this software.
19293//
19294// Permission is granted to anyone to use this software for any purpose,
19295// including commercial applications, and to alter it and redistribute it
19296// freely, subject to the following restrictions:
19297//
19298// 1. The origin of this software must not be misrepresented; you must not
19299// claim that you wrote the original software. If you use this software
19300// in a product, an acknowledgment in the product documentation would be
19301// appreciated but is not required.
19302// 2. Altered source versions must be plainly marked as such, and must not be
19303// misrepresented as being the original software.
19304// 3. This notice may not be removed or altered from any source distribution.
19305
19306// See state defs from inflate.js
19307const BAD = 30; /* got a data error -- remain here until reset */
19308const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
19309
19310/*
19311 Decode literal, length, and distance codes and write out the resulting
19312 literal and match bytes until either not enough input or output is
19313 available, an end-of-block is encountered, or a data error is encountered.
19314 When large enough input and output buffers are supplied to inflate(), for
19315 example, a 16K input buffer and a 64K output buffer, more than 95% of the
19316 inflate execution time is spent in this routine.
19317
19318 Entry assumptions:
19319
19320 state.mode === LEN
19321 strm.avail_in >= 6
19322 strm.avail_out >= 258
19323 start >= strm.avail_out
19324 state.bits < 8
19325
19326 On return, state.mode is one of:
19327
19328 LEN -- ran out of enough output space or enough available input
19329 TYPE -- reached end of block code, inflate() to interpret next block
19330 BAD -- error in block data
19331
19332 Notes:
19333
19334 - The maximum input bits used by a length/distance pair is 15 bits for the
19335 length code, 5 bits for the length extra, 15 bits for the distance code,
19336 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
19337 Therefore if strm.avail_in >= 6, then there is enough input to avoid
19338 checking for available input while decoding.
19339
19340 - The maximum bytes that a single length/distance pair can output is 258
19341 bytes, which is the maximum length that can be coded. inflate_fast()
19342 requires strm.avail_out >= 258 for each loop to avoid checking for
19343 output space.
19344 */
19345function inflate_fast(strm, start) {
19346 let _in; /* local strm.input */
19347 let _out; /* local strm.output */
19348 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
19349 let hold; /* local strm.hold */
19350 let bits; /* local strm.bits */
19351 let here; /* retrieved table entry */
19352 let op; /* code bits, operation, extra bits, or */
19353 /* window position, window bytes to copy */
19354 let len; /* match length, unused bytes */
19355 let dist; /* match distance */
19356 let from; /* where to copy match from */
19357 let from_source;
19358
19359
19360
19361 /* copy state to local variables */
19362 const state = strm.state;
19363 //here = state.here;
19364 _in = strm.next_in;
19365 const input = strm.input;
19366 const last = _in + (strm.avail_in - 5);
19367 _out = strm.next_out;
19368 const output = strm.output;
19369 const beg = _out - (start - strm.avail_out);
19370 const end = _out + (strm.avail_out - 257);
19371 //#ifdef INFLATE_STRICT
19372 const dmax = state.dmax;
19373 //#endif
19374 const wsize = state.wsize;
19375 const whave = state.whave;
19376 const wnext = state.wnext;
19377 const s_window = state.window;
19378 hold = state.hold;
19379 bits = state.bits;
19380 const lcode = state.lencode;
19381 const dcode = state.distcode;
19382 const lmask = (1 << state.lenbits) - 1;
19383 const dmask = (1 << state.distbits) - 1;
19384
19385
19386 /* decode literals and length/distances until end-of-block or not enough
19387 input data or output space */
19388
19389 top:
19390 do {
19391 if (bits < 15) {
19392 hold += input[_in++] << bits;
19393 bits += 8;
19394 hold += input[_in++] << bits;
19395 bits += 8;
19396 }
19397
19398 here = lcode[hold & lmask];
19399
19400 dolen:
19401 for (;;) { // Goto emulation
19402 op = here >>> 24/*here.bits*/;
19403 hold >>>= op;
19404 bits -= op;
19405 op = here >>> 16 & 0xff/*here.op*/;
19406 if (op === 0) { /* literal */
19407 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
19408 // "inflate: literal '%c'\n" :
19409 // "inflate: literal 0x%02x\n", here.val));
19410 output[_out++] = here & 0xffff/*here.val*/;
19411 } else if (op & 16) { /* length base */
19412 len = here & 0xffff/*here.val*/;
19413 op &= 15; /* number of extra bits */
19414 if (op) {
19415 if (bits < op) {
19416 hold += input[_in++] << bits;
19417 bits += 8;
19418 }
19419 len += hold & (1 << op) - 1;
19420 hold >>>= op;
19421 bits -= op;
19422 }
19423 //Tracevv((stderr, "inflate: length %u\n", len));
19424 if (bits < 15) {
19425 hold += input[_in++] << bits;
19426 bits += 8;
19427 hold += input[_in++] << bits;
19428 bits += 8;
19429 }
19430 here = dcode[hold & dmask];
19431
19432 dodist:
19433 for (;;) { // goto emulation
19434 op = here >>> 24/*here.bits*/;
19435 hold >>>= op;
19436 bits -= op;
19437 op = here >>> 16 & 0xff/*here.op*/;
19438
19439 if (op & 16) { /* distance base */
19440 dist = here & 0xffff/*here.val*/;
19441 op &= 15; /* number of extra bits */
19442 if (bits < op) {
19443 hold += input[_in++] << bits;
19444 bits += 8;
19445 if (bits < op) {
19446 hold += input[_in++] << bits;
19447 bits += 8;
19448 }
19449 }
19450 dist += hold & (1 << op) - 1;
19451 //#ifdef INFLATE_STRICT
19452 if (dist > dmax) {
19453 strm.msg = "invalid distance too far back";
19454 state.mode = BAD;
19455 break top;
19456 }
19457 //#endif
19458 hold >>>= op;
19459 bits -= op;
19460 //Tracevv((stderr, "inflate: distance %u\n", dist));
19461 op = _out - beg; /* max distance in output */
19462 if (dist > op) { /* see if copy from window */
19463 op = dist - op; /* distance back in window */
19464 if (op > whave) {
19465 if (state.sane) {
19466 strm.msg = "invalid distance too far back";
19467 state.mode = BAD;
19468 break top;
19469 }
19470
19471 // (!) This block is disabled in zlib defaults,
19472 // don't enable it for binary compatibility
19473 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
19474 // if (len <= op - whave) {
19475 // do {
19476 // output[_out++] = 0;
19477 // } while (--len);
19478 // continue top;
19479 // }
19480 // len -= op - whave;
19481 // do {
19482 // output[_out++] = 0;
19483 // } while (--op > whave);
19484 // if (op === 0) {
19485 // from = _out - dist;
19486 // do {
19487 // output[_out++] = output[from++];
19488 // } while (--len);
19489 // continue top;
19490 // }
19491 //#endif
19492 }
19493 from = 0; // window index
19494 from_source = s_window;
19495 if (wnext === 0) { /* very common case */
19496 from += wsize - op;
19497 if (op < len) { /* some from window */
19498 len -= op;
19499 do {
19500 output[_out++] = s_window[from++];
19501 } while (--op);
19502 from = _out - dist; /* rest from output */
19503 from_source = output;
19504 }
19505 } else if (wnext < op) { /* wrap around window */
19506 from += wsize + wnext - op;
19507 op -= wnext;
19508 if (op < len) { /* some from end of window */
19509 len -= op;
19510 do {
19511 output[_out++] = s_window[from++];
19512 } while (--op);
19513 from = 0;
19514 if (wnext < len) { /* some from start of window */
19515 op = wnext;
19516 len -= op;
19517 do {
19518 output[_out++] = s_window[from++];
19519 } while (--op);
19520 from = _out - dist; /* rest from output */
19521 from_source = output;
19522 }
19523 }
19524 } else { /* contiguous in window */
19525 from += wnext - op;
19526 if (op < len) { /* some from window */
19527 len -= op;
19528 do {
19529 output[_out++] = s_window[from++];
19530 } while (--op);
19531 from = _out - dist; /* rest from output */
19532 from_source = output;
19533 }
19534 }
19535 while (len > 2) {
19536 output[_out++] = from_source[from++];
19537 output[_out++] = from_source[from++];
19538 output[_out++] = from_source[from++];
19539 len -= 3;
19540 }
19541 if (len) {
19542 output[_out++] = from_source[from++];
19543 if (len > 1) {
19544 output[_out++] = from_source[from++];
19545 }
19546 }
19547 } else {
19548 from = _out - dist; /* copy direct from output */
19549 do { /* minimum length is three */
19550 output[_out++] = output[from++];
19551 output[_out++] = output[from++];
19552 output[_out++] = output[from++];
19553 len -= 3;
19554 } while (len > 2);
19555 if (len) {
19556 output[_out++] = output[from++];
19557 if (len > 1) {
19558 output[_out++] = output[from++];
19559 }
19560 }
19561 }
19562 } else if ((op & 64) === 0) { /* 2nd level distance code */
19563 here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19564 continue dodist;
19565 } else {
19566 strm.msg = "invalid distance code";
19567 state.mode = BAD;
19568 break top;
19569 }
19570
19571 break; // need to emulate goto via "continue"
19572 }
19573 } else if ((op & 64) === 0) { /* 2nd level length code */
19574 here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19575 continue dolen;
19576 } else if (op & 32) { /* end-of-block */
19577 //Tracevv((stderr, "inflate: end of block\n"));
19578 state.mode = TYPE;
19579 break top;
19580 } else {
19581 strm.msg = "invalid literal/length code";
19582 state.mode = BAD;
19583 break top;
19584 }
19585
19586 break; // need to emulate goto via "continue"
19587 }
19588 } while (_in < last && _out < end);
19589
19590 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
19591 len = bits >> 3;
19592 _in -= len;
19593 bits -= len << 3;
19594 hold &= (1 << bits) - 1;
19595
19596 /* update state and return */
19597 strm.next_in = _in;
19598 strm.next_out = _out;
19599 strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
19600 strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
19601 state.hold = hold;
19602 state.bits = bits;
19603 return;
19604}
19605
19606const MAXBITS = 15;
19607const ENOUGH_LENS = 852;
19608const ENOUGH_DISTS = 592;
19609//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
19610
19611const CODES = 0;
19612const LENS = 1;
19613const DISTS = 2;
19614
19615const lbase = [ /* Length codes 257..285 base */
19616 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
19617 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
19618];
19619
19620const lext = [ /* Length codes 257..285 extra */
19621 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19622 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
19623];
19624
19625const dbase = [ /* Distance codes 0..29 base */
19626 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
19627 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
19628 8193, 12289, 16385, 24577, 0, 0
19629];
19630
19631const dext = [ /* Distance codes 0..29 extra */
19632 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
19633 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
19634 28, 28, 29, 29, 64, 64
19635];
19636
19637function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
19638 const bits = opts.bits;
19639 //here = opts.here; /* table entry for duplication */
19640
19641 let len = 0; /* a code's length in bits */
19642 let sym = 0; /* index of code symbols */
19643 let min = 0, max = 0; /* minimum and maximum code lengths */
19644 let root = 0; /* number of index bits for root table */
19645 let curr = 0; /* number of index bits for current table */
19646 let drop = 0; /* code bits to drop for sub-table */
19647 let left = 0; /* number of prefix codes available */
19648 let used = 0; /* code entries in table used */
19649 let huff = 0; /* Huffman code */
19650 let incr; /* for incrementing code, index */
19651 let fill; /* index for replicating entries */
19652 let low; /* low bits for current root entry */
19653 let next; /* next available space in table */
19654 let base = null; /* base value table to use */
19655 let base_index = 0;
19656 // var shoextra; /* extra bits table to use */
19657 let end; /* use base and extra for symbol > end */
19658 const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
19659 const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
19660 let extra = null;
19661 let extra_index = 0;
19662
19663 let here_bits, here_op, here_val;
19664
19665 /*
19666 Process a set of code lengths to create a canonical Huffman code. The
19667 code lengths are lens[0..codes-1]. Each length corresponds to the
19668 symbols 0..codes-1. The Huffman code is generated by first sorting the
19669 symbols by length from short to long, and retaining the symbol order
19670 for codes with equal lengths. Then the code starts with all zero bits
19671 for the first code of the shortest length, and the codes are integer
19672 increments for the same length, and zeros are appended as the length
19673 increases. For the deflate format, these bits are stored backwards
19674 from their more natural integer increment ordering, and so when the
19675 decoding tables are built in the large loop below, the integer codes
19676 are incremented backwards.
19677
19678 This routine assumes, but does not check, that all of the entries in
19679 lens[] are in the range 0..MAXBITS. The caller must assure this.
19680 1..MAXBITS is interpreted as that code length. zero means that that
19681 symbol does not occur in this code.
19682
19683 The codes are sorted by computing a count of codes for each length,
19684 creating from that a table of starting indices for each length in the
19685 sorted table, and then entering the symbols in order in the sorted
19686 table. The sorted table is work[], with that space being provided by
19687 the caller.
19688
19689 The length counts are used for other purposes as well, i.e. finding
19690 the minimum and maximum length codes, determining if there are any
19691 codes at all, checking for a valid set of lengths, and looking ahead
19692 at length counts to determine sub-table sizes when building the
19693 decoding tables.
19694 */
19695
19696 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
19697 for (len = 0; len <= MAXBITS; len++) {
19698 count[len] = 0;
19699 }
19700 for (sym = 0; sym < codes; sym++) {
19701 count[lens[lens_index + sym]]++;
19702 }
19703
19704 /* bound code lengths, force root to be within code lengths */
19705 root = bits;
19706 for (max = MAXBITS; max >= 1; max--) {
19707 if (count[max] !== 0) {
19708 break;
19709 }
19710 }
19711 if (root > max) {
19712 root = max;
19713 }
19714 if (max === 0) { /* no symbols to code at all */
19715 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
19716 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
19717 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
19718 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19719
19720
19721 //table.op[opts.table_index] = 64;
19722 //table.bits[opts.table_index] = 1;
19723 //table.val[opts.table_index++] = 0;
19724 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19725
19726 opts.bits = 1;
19727 return 0; /* no symbols, but wait for decoding to report error */
19728 }
19729 for (min = 1; min < max; min++) {
19730 if (count[min] !== 0) {
19731 break;
19732 }
19733 }
19734 if (root < min) {
19735 root = min;
19736 }
19737
19738 /* check for an over-subscribed or incomplete set of lengths */
19739 left = 1;
19740 for (len = 1; len <= MAXBITS; len++) {
19741 left <<= 1;
19742 left -= count[len];
19743 if (left < 0) {
19744 return -1;
19745 } /* over-subscribed */
19746 }
19747 if (left > 0 && (type === CODES || max !== 1)) {
19748 return -1; /* incomplete set */
19749 }
19750
19751 /* generate offsets into symbol table for each length for sorting */
19752 offs[1] = 0;
19753 for (len = 1; len < MAXBITS; len++) {
19754 offs[len + 1] = offs[len] + count[len];
19755 }
19756
19757 /* sort symbols by length, by symbol order within each length */
19758 for (sym = 0; sym < codes; sym++) {
19759 if (lens[lens_index + sym] !== 0) {
19760 work[offs[lens[lens_index + sym]]++] = sym;
19761 }
19762 }
19763
19764 /*
19765 Create and fill in decoding tables. In this loop, the table being
19766 filled is at next and has curr index bits. The code being used is huff
19767 with length len. That code is converted to an index by dropping drop
19768 bits off of the bottom. For codes where len is less than drop + curr,
19769 those top drop + curr - len bits are incremented through all values to
19770 fill the table with replicated entries.
19771
19772 root is the number of index bits for the root table. When len exceeds
19773 root, sub-tables are created pointed to by the root entry with an index
19774 of the low root bits of huff. This is saved in low to check for when a
19775 new sub-table should be started. drop is zero when the root table is
19776 being filled, and drop is root when sub-tables are being filled.
19777
19778 When a new sub-table is needed, it is necessary to look ahead in the
19779 code lengths to determine what size sub-table is needed. The length
19780 counts are used for this, and so count[] is decremented as codes are
19781 entered in the tables.
19782
19783 used keeps track of how many table entries have been allocated from the
19784 provided *table space. It is checked for LENS and DIST tables against
19785 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
19786 the initial root table size constants. See the comments in inftrees.h
19787 for more information.
19788
19789 sym increments through all symbols, and the loop terminates when
19790 all codes of length max, i.e. all codes, have been processed. This
19791 routine permits incomplete codes, so another loop after this one fills
19792 in the rest of the decoding tables with invalid code markers.
19793 */
19794
19795 /* set up for code type */
19796 // poor man optimization - use if-else instead of switch,
19797 // to avoid deopts in old v8
19798 if (type === CODES) {
19799 base = extra = work; /* dummy value--not used */
19800 end = 19;
19801
19802 } else if (type === LENS) {
19803 base = lbase;
19804 base_index -= 257;
19805 extra = lext;
19806 extra_index -= 257;
19807 end = 256;
19808
19809 } else { /* DISTS */
19810 base = dbase;
19811 extra = dext;
19812 end = -1;
19813 }
19814
19815 /* initialize opts for loop */
19816 huff = 0; /* starting code */
19817 sym = 0; /* starting code symbol */
19818 len = min; /* starting code length */
19819 next = table_index; /* current table to fill in */
19820 curr = root; /* current table index bits */
19821 drop = 0; /* current bits to drop from code for index */
19822 low = -1; /* trigger new sub-table when len > root */
19823 used = 1 << root; /* use root table entries */
19824 const mask = used - 1; /* mask for comparing low */
19825
19826 /* check available table space */
19827 if (type === LENS && used > ENOUGH_LENS ||
19828 type === DISTS && used > ENOUGH_DISTS) {
19829 return 1;
19830 }
19831
19832 /* process all codes and make table entries */
19833 for (;;) {
19834 /* create table entry */
19835 here_bits = len - drop;
19836 if (work[sym] < end) {
19837 here_op = 0;
19838 here_val = work[sym];
19839 } else if (work[sym] > end) {
19840 here_op = extra[extra_index + work[sym]];
19841 here_val = base[base_index + work[sym]];
19842 } else {
19843 here_op = 32 + 64; /* end of block */
19844 here_val = 0;
19845 }
19846
19847 /* replicate for those indices with low len bits equal to huff */
19848 incr = 1 << len - drop;
19849 fill = 1 << curr;
19850 min = fill; /* save offset to next table */
19851 do {
19852 fill -= incr;
19853 table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;
19854 } while (fill !== 0);
19855
19856 /* backwards increment the len-bit code huff */
19857 incr = 1 << len - 1;
19858 while (huff & incr) {
19859 incr >>= 1;
19860 }
19861 if (incr !== 0) {
19862 huff &= incr - 1;
19863 huff += incr;
19864 } else {
19865 huff = 0;
19866 }
19867
19868 /* go to next symbol, update count, len */
19869 sym++;
19870 if (--count[len] === 0) {
19871 if (len === max) {
19872 break;
19873 }
19874 len = lens[lens_index + work[sym]];
19875 }
19876
19877 /* create new sub-table if needed */
19878 if (len > root && (huff & mask) !== low) {
19879 /* if first time, transition to sub-tables */
19880 if (drop === 0) {
19881 drop = root;
19882 }
19883
19884 /* increment past last table */
19885 next += min; /* here min is 1 << curr */
19886
19887 /* determine length of next table */
19888 curr = len - drop;
19889 left = 1 << curr;
19890 while (curr + drop < max) {
19891 left -= count[curr + drop];
19892 if (left <= 0) {
19893 break;
19894 }
19895 curr++;
19896 left <<= 1;
19897 }
19898
19899 /* check for enough space */
19900 used += 1 << curr;
19901 if (type === LENS && used > ENOUGH_LENS ||
19902 type === DISTS && used > ENOUGH_DISTS) {
19903 return 1;
19904 }
19905
19906 /* point entry in root table to sub-table */
19907 low = huff & mask;
19908 /*table.op[low] = curr;
19909 table.bits[low] = root;
19910 table.val[low] = next - opts.table_index;*/
19911 table[low] = root << 24 | curr << 16 | next - table_index |0;
19912 }
19913 }
19914
19915 /* fill in remaining table entry if code is incomplete (guaranteed to have
19916 at most one remaining entry, since if the code is incomplete, the
19917 maximum code length that was allowed to get this far is one bit) */
19918 if (huff !== 0) {
19919 //table.op[next + huff] = 64; /* invalid code marker */
19920 //table.bits[next + huff] = len - drop;
19921 //table.val[next + huff] = 0;
19922 table[next + huff] = len - drop << 24 | 64 << 16 |0;
19923 }
19924
19925 /* set return parameters */
19926 //opts.table_index += used;
19927 opts.bits = root;
19928 return 0;
19929}
19930
19931const CODES$1 = 0;
19932const LENS$1 = 1;
19933const DISTS$1 = 2;
19934
19935/* STATES ====================================================================*/
19936/* ===========================================================================*/
19937
19938
19939const HEAD = 1; /* i: waiting for magic header */
19940const FLAGS = 2; /* i: waiting for method and flags (gzip) */
19941const TIME = 3; /* i: waiting for modification time (gzip) */
19942const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
19943const EXLEN = 5; /* i: waiting for extra length (gzip) */
19944const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
19945const NAME = 7; /* i: waiting for end of file name (gzip) */
19946const COMMENT = 8; /* i: waiting for end of comment (gzip) */
19947const HCRC = 9; /* i: waiting for header crc (gzip) */
19948const DICTID = 10; /* i: waiting for dictionary check value */
19949const DICT = 11; /* waiting for inflateSetDictionary() call */
19950const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
19951const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
19952const STORED = 14; /* i: waiting for stored size (length and complement) */
19953const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
19954const COPY = 16; /* i/o: waiting for input or output to copy stored block */
19955const TABLE = 17; /* i: waiting for dynamic block table lengths */
19956const LENLENS = 18; /* i: waiting for code length code lengths */
19957const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
19958const LEN_ = 20; /* i: same as LEN below, but only first time in */
19959const LEN = 21; /* i: waiting for length/lit/eob code */
19960const LENEXT = 22; /* i: waiting for length extra bits */
19961const DIST = 23; /* i: waiting for distance code */
19962const DISTEXT = 24; /* i: waiting for distance extra bits */
19963const MATCH = 25; /* o: waiting for output space to copy string */
19964const LIT = 26; /* o: waiting for output space to write literal */
19965const CHECK = 27; /* i: waiting for 32-bit check value */
19966const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
19967const DONE = 29; /* finished check, done -- remain here until reset */
19968const BAD$1 = 30; /* got a data error -- remain here until reset */
19969//const MEM = 31; /* got an inflate() memory error -- remain here until reset */
19970const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
19971
19972/* ===========================================================================*/
19973
19974
19975
19976const ENOUGH_LENS$1 = 852;
19977const ENOUGH_DISTS$1 = 592;
19978
19979
19980function zswap32(q) {
19981 return (((q >>> 24) & 0xff) +
19982 ((q >>> 8) & 0xff00) +
19983 ((q & 0xff00) << 8) +
19984 ((q & 0xff) << 24));
19985}
19986
19987
19988class InflateState {
19989 constructor() {
19990 this.mode = 0; /* current inflate mode */
19991 this.last = false; /* true if processing last block */
19992 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
19993 this.havedict = false; /* true if dictionary provided */
19994 this.flags = 0; /* gzip header method and flags (0 if zlib) */
19995 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
19996 this.check = 0; /* protected copy of check value */
19997 this.total = 0; /* protected copy of output count */
19998 // TODO: may be {}
19999 this.head = null; /* where to save gzip header information */
20000
20001 /* sliding window */
20002 this.wbits = 0; /* log base 2 of requested window size */
20003 this.wsize = 0; /* window size or zero if not using window */
20004 this.whave = 0; /* valid bytes in the window */
20005 this.wnext = 0; /* window write index */
20006 this.window = null; /* allocated sliding window, if needed */
20007
20008 /* bit accumulator */
20009 this.hold = 0; /* input bit accumulator */
20010 this.bits = 0; /* number of bits in "in" */
20011
20012 /* for string and stored block copying */
20013 this.length = 0; /* literal or length of data to copy */
20014 this.offset = 0; /* distance back to copy string from */
20015
20016 /* for table and code decoding */
20017 this.extra = 0; /* extra bits needed */
20018
20019 /* fixed and dynamic code tables */
20020 this.lencode = null; /* starting table for length/literal codes */
20021 this.distcode = null; /* starting table for distance codes */
20022 this.lenbits = 0; /* index bits for lencode */
20023 this.distbits = 0; /* index bits for distcode */
20024
20025 /* dynamic table building */
20026 this.ncode = 0; /* number of code length code lengths */
20027 this.nlen = 0; /* number of length code lengths */
20028 this.ndist = 0; /* number of distance code lengths */
20029 this.have = 0; /* number of code lengths in lens[] */
20030 this.next = null; /* next available space in codes[] */
20031
20032 this.lens = new Buf16(320); /* temporary storage for code lengths */
20033 this.work = new Buf16(288); /* work area for code table building */
20034
20035 /*
20036 because we don't have pointers in js, we use lencode and distcode directly
20037 as buffers so we don't need codes
20038 */
20039 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
20040 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
20041 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
20042 this.sane = 0; /* if false, allow invalid distance too far */
20043 this.back = 0; /* bits back of last unprocessed length/lit */
20044 this.was = 0; /* initial length of match */
20045 }
20046}
20047
20048function inflateResetKeep(strm) {
20049 let state;
20050
20051 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20052 state = strm.state;
20053 strm.total_in = strm.total_out = state.total = 0;
20054 strm.msg = ''; /*Z_NULL*/
20055 if (state.wrap) { /* to support ill-conceived Java test suite */
20056 strm.adler = state.wrap & 1;
20057 }
20058 state.mode = HEAD;
20059 state.last = 0;
20060 state.havedict = 0;
20061 state.dmax = 32768;
20062 state.head = null/*Z_NULL*/;
20063 state.hold = 0;
20064 state.bits = 0;
20065 //state.lencode = state.distcode = state.next = state.codes;
20066 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
20067 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
20068
20069 state.sane = 1;
20070 state.back = -1;
20071 //Tracev((stderr, "inflate: reset\n"));
20072 return Z_OK;
20073}
20074
20075function inflateReset(strm) {
20076 let state;
20077
20078 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20079 state = strm.state;
20080 state.wsize = 0;
20081 state.whave = 0;
20082 state.wnext = 0;
20083 return inflateResetKeep(strm);
20084
20085}
20086
20087function inflateReset2(strm, windowBits) {
20088 let wrap;
20089 let state;
20090
20091 /* get the state */
20092 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20093 state = strm.state;
20094
20095 /* extract wrap request from windowBits parameter */
20096 if (windowBits < 0) {
20097 wrap = 0;
20098 windowBits = -windowBits;
20099 }
20100 else {
20101 wrap = (windowBits >> 4) + 1;
20102 if (windowBits < 48) {
20103 windowBits &= 15;
20104 }
20105 }
20106
20107 /* set number of window bits, free window if different */
20108 if (windowBits && (windowBits < 8 || windowBits > 15)) {
20109 return Z_STREAM_ERROR;
20110 }
20111 if (state.window !== null && state.wbits !== windowBits) {
20112 state.window = null;
20113 }
20114
20115 /* update state and reset the rest of it */
20116 state.wrap = wrap;
20117 state.wbits = windowBits;
20118 return inflateReset(strm);
20119}
20120
20121function inflateInit2(strm, windowBits) {
20122 let ret;
20123 let state;
20124
20125 if (!strm) { return Z_STREAM_ERROR; }
20126 //strm.msg = Z_NULL; /* in case we return an error */
20127
20128 state = new InflateState();
20129
20130 //if (state === Z_NULL) return Z_MEM_ERROR;
20131 //Tracev((stderr, "inflate: allocated\n"));
20132 strm.state = state;
20133 state.window = null/*Z_NULL*/;
20134 ret = inflateReset2(strm, windowBits);
20135 if (ret !== Z_OK) {
20136 strm.state = null/*Z_NULL*/;
20137 }
20138 return ret;
20139}
20140
20141
20142/*
20143 Return state with length and distance decoding tables and index sizes set to
20144 fixed code decoding. Normally this returns fixed tables from inffixed.h.
20145 If BUILDFIXED is defined, then instead this routine builds the tables the
20146 first time it's called, and returns those tables the first time and
20147 thereafter. This reduces the size of the code by about 2K bytes, in
20148 exchange for a little execution time. However, BUILDFIXED should not be
20149 used for threaded applications, since the rewriting of the tables and virgin
20150 may not be thread-safe.
20151 */
20152let virgin = true;
20153
20154let lenfix, distfix; // We have no pointers in JS, so keep tables separate
20155
20156function fixedtables(state) {
20157 /* build fixed huffman tables if first call (may not be thread safe) */
20158 if (virgin) {
20159 let sym;
20160
20161 lenfix = new Buf32(512);
20162 distfix = new Buf32(32);
20163
20164 /* literal/length table */
20165 sym = 0;
20166 while (sym < 144) { state.lens[sym++] = 8; }
20167 while (sym < 256) { state.lens[sym++] = 9; }
20168 while (sym < 280) { state.lens[sym++] = 7; }
20169 while (sym < 288) { state.lens[sym++] = 8; }
20170
20171 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
20172
20173 /* distance table */
20174 sym = 0;
20175 while (sym < 32) { state.lens[sym++] = 5; }
20176
20177 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
20178
20179 /* do this just once */
20180 virgin = false;
20181 }
20182
20183 state.lencode = lenfix;
20184 state.lenbits = 9;
20185 state.distcode = distfix;
20186 state.distbits = 5;
20187}
20188
20189
20190/*
20191 Update the window with the last wsize (normally 32K) bytes written before
20192 returning. If window does not exist yet, create it. This is only called
20193 when a window is already in use, or when output has been written during this
20194 inflate call, but the end of the deflate stream has not been reached yet.
20195 It is also called to create a window for dictionary data when a dictionary
20196 is loaded.
20197
20198 Providing output buffers larger than 32K to inflate() should provide a speed
20199 advantage, since only the last 32K of output is copied to the sliding window
20200 upon return from inflate(), and since all distances after the first 32K of
20201 output will fall in the output data, making match copies simpler and faster.
20202 The advantage may be dependent on the size of the processor's data caches.
20203 */
20204function updatewindow(strm, src, end, copy) {
20205 let dist;
20206 const state = strm.state;
20207
20208 /* if it hasn't been done already, allocate space for the window */
20209 if (state.window === null) {
20210 state.wsize = 1 << state.wbits;
20211 state.wnext = 0;
20212 state.whave = 0;
20213
20214 state.window = new Buf8(state.wsize);
20215 }
20216
20217 /* copy state->wsize or less output bytes into the circular window */
20218 if (copy >= state.wsize) {
20219 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
20220 state.wnext = 0;
20221 state.whave = state.wsize;
20222 }
20223 else {
20224 dist = state.wsize - state.wnext;
20225 if (dist > copy) {
20226 dist = copy;
20227 }
20228 //zmemcpy(state->window + state->wnext, end - copy, dist);
20229 arraySet(state.window, src, end - copy, dist, state.wnext);
20230 copy -= dist;
20231 if (copy) {
20232 //zmemcpy(state->window, end - copy, copy);
20233 arraySet(state.window, src, end - copy, copy, 0);
20234 state.wnext = copy;
20235 state.whave = state.wsize;
20236 }
20237 else {
20238 state.wnext += dist;
20239 if (state.wnext === state.wsize) { state.wnext = 0; }
20240 if (state.whave < state.wsize) { state.whave += dist; }
20241 }
20242 }
20243 return 0;
20244}
20245
20246function inflate(strm, flush) {
20247 let state;
20248 let input, output; // input/output buffers
20249 let next; /* next input INDEX */
20250 let put; /* next output INDEX */
20251 let have, left; /* available input and output */
20252 let hold; /* bit buffer */
20253 let bits; /* bits in bit buffer */
20254 let _in, _out; /* save starting available input and output */
20255 let copy; /* number of stored or match bytes to copy */
20256 let from; /* where to copy match bytes from */
20257 let from_source;
20258 let here = 0; /* current decoding table entry */
20259 let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
20260 //var last; /* parent table entry */
20261 let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
20262 let len; /* length to copy for repeats, bits to drop */
20263 let ret; /* return code */
20264 let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
20265 let opts;
20266
20267 let n; // temporary var for NEED_BITS
20268
20269 const order = /* permutation of code lengths */
20270 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
20271
20272
20273 if (!strm || !strm.state || !strm.output ||
20274 (!strm.input && strm.avail_in !== 0)) {
20275 return Z_STREAM_ERROR;
20276 }
20277
20278 state = strm.state;
20279 if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */
20280
20281
20282 //--- LOAD() ---
20283 put = strm.next_out;
20284 output = strm.output;
20285 left = strm.avail_out;
20286 next = strm.next_in;
20287 input = strm.input;
20288 have = strm.avail_in;
20289 hold = state.hold;
20290 bits = state.bits;
20291 //---
20292
20293 _in = have;
20294 _out = left;
20295 ret = Z_OK;
20296
20297 inf_leave: // goto emulation
20298 for (;;) {
20299 switch (state.mode) {
20300 case HEAD:
20301 if (state.wrap === 0) {
20302 state.mode = TYPEDO;
20303 break;
20304 }
20305 //=== NEEDBITS(16);
20306 while (bits < 16) {
20307 if (have === 0) { break inf_leave; }
20308 have--;
20309 hold += input[next++] << bits;
20310 bits += 8;
20311 }
20312 //===//
20313 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
20314 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
20315 //=== CRC2(state.check, hold);
20316 hbuf[0] = hold & 0xff;
20317 hbuf[1] = (hold >>> 8) & 0xff;
20318 state.check = crc32(state.check, hbuf, 2, 0);
20319 //===//
20320
20321 //=== INITBITS();
20322 hold = 0;
20323 bits = 0;
20324 //===//
20325 state.mode = FLAGS;
20326 break;
20327 }
20328 state.flags = 0; /* expect zlib header */
20329 if (state.head) {
20330 state.head.done = false;
20331 }
20332 if (!(state.wrap & 1) || /* check if zlib header allowed */
20333 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
20334 strm.msg = 'incorrect header check';
20335 state.mode = BAD$1;
20336 break;
20337 }
20338 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
20339 strm.msg = 'unknown compression method';
20340 state.mode = BAD$1;
20341 break;
20342 }
20343 //--- DROPBITS(4) ---//
20344 hold >>>= 4;
20345 bits -= 4;
20346 //---//
20347 len = (hold & 0x0f)/*BITS(4)*/ + 8;
20348 if (state.wbits === 0) {
20349 state.wbits = len;
20350 }
20351 else if (len > state.wbits) {
20352 strm.msg = 'invalid window size';
20353 state.mode = BAD$1;
20354 break;
20355 }
20356 state.dmax = 1 << len;
20357 //Tracev((stderr, "inflate: zlib header ok\n"));
20358 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20359 state.mode = hold & 0x200 ? DICTID : TYPE$1;
20360 //=== INITBITS();
20361 hold = 0;
20362 bits = 0;
20363 //===//
20364 break;
20365 case FLAGS:
20366 //=== NEEDBITS(16); */
20367 while (bits < 16) {
20368 if (have === 0) { break inf_leave; }
20369 have--;
20370 hold += input[next++] << bits;
20371 bits += 8;
20372 }
20373 //===//
20374 state.flags = hold;
20375 if ((state.flags & 0xff) !== Z_DEFLATED) {
20376 strm.msg = 'unknown compression method';
20377 state.mode = BAD$1;
20378 break;
20379 }
20380 if (state.flags & 0xe000) {
20381 strm.msg = 'unknown header flags set';
20382 state.mode = BAD$1;
20383 break;
20384 }
20385 if (state.head) {
20386 state.head.text = ((hold >> 8) & 1);
20387 }
20388 if (state.flags & 0x0200) {
20389 //=== CRC2(state.check, hold);
20390 hbuf[0] = hold & 0xff;
20391 hbuf[1] = (hold >>> 8) & 0xff;
20392 state.check = crc32(state.check, hbuf, 2, 0);
20393 //===//
20394 }
20395 //=== INITBITS();
20396 hold = 0;
20397 bits = 0;
20398 //===//
20399 state.mode = TIME;
20400 /* falls through */
20401 case TIME:
20402 //=== NEEDBITS(32); */
20403 while (bits < 32) {
20404 if (have === 0) { break inf_leave; }
20405 have--;
20406 hold += input[next++] << bits;
20407 bits += 8;
20408 }
20409 //===//
20410 if (state.head) {
20411 state.head.time = hold;
20412 }
20413 if (state.flags & 0x0200) {
20414 //=== CRC4(state.check, hold)
20415 hbuf[0] = hold & 0xff;
20416 hbuf[1] = (hold >>> 8) & 0xff;
20417 hbuf[2] = (hold >>> 16) & 0xff;
20418 hbuf[3] = (hold >>> 24) & 0xff;
20419 state.check = crc32(state.check, hbuf, 4, 0);
20420 //===
20421 }
20422 //=== INITBITS();
20423 hold = 0;
20424 bits = 0;
20425 //===//
20426 state.mode = OS;
20427 /* falls through */
20428 case OS:
20429 //=== NEEDBITS(16); */
20430 while (bits < 16) {
20431 if (have === 0) { break inf_leave; }
20432 have--;
20433 hold += input[next++] << bits;
20434 bits += 8;
20435 }
20436 //===//
20437 if (state.head) {
20438 state.head.xflags = (hold & 0xff);
20439 state.head.os = (hold >> 8);
20440 }
20441 if (state.flags & 0x0200) {
20442 //=== CRC2(state.check, hold);
20443 hbuf[0] = hold & 0xff;
20444 hbuf[1] = (hold >>> 8) & 0xff;
20445 state.check = crc32(state.check, hbuf, 2, 0);
20446 //===//
20447 }
20448 //=== INITBITS();
20449 hold = 0;
20450 bits = 0;
20451 //===//
20452 state.mode = EXLEN;
20453 /* falls through */
20454 case EXLEN:
20455 if (state.flags & 0x0400) {
20456 //=== NEEDBITS(16); */
20457 while (bits < 16) {
20458 if (have === 0) { break inf_leave; }
20459 have--;
20460 hold += input[next++] << bits;
20461 bits += 8;
20462 }
20463 //===//
20464 state.length = hold;
20465 if (state.head) {
20466 state.head.extra_len = hold;
20467 }
20468 if (state.flags & 0x0200) {
20469 //=== CRC2(state.check, hold);
20470 hbuf[0] = hold & 0xff;
20471 hbuf[1] = (hold >>> 8) & 0xff;
20472 state.check = crc32(state.check, hbuf, 2, 0);
20473 //===//
20474 }
20475 //=== INITBITS();
20476 hold = 0;
20477 bits = 0;
20478 //===//
20479 }
20480 else if (state.head) {
20481 state.head.extra = null/*Z_NULL*/;
20482 }
20483 state.mode = EXTRA;
20484 /* falls through */
20485 case EXTRA:
20486 if (state.flags & 0x0400) {
20487 copy = state.length;
20488 if (copy > have) { copy = have; }
20489 if (copy) {
20490 if (state.head) {
20491 len = state.head.extra_len - state.length;
20492 if (!state.head.extra) {
20493 // Use untyped array for more convenient processing later
20494 state.head.extra = new Array(state.head.extra_len);
20495 }
20496 arraySet(
20497 state.head.extra,
20498 input,
20499 next,
20500 // extra field is limited to 65536 bytes
20501 // - no need for additional size check
20502 copy,
20503 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
20504 len
20505 );
20506 //zmemcpy(state.head.extra + len, next,
20507 // len + copy > state.head.extra_max ?
20508 // state.head.extra_max - len : copy);
20509 }
20510 if (state.flags & 0x0200) {
20511 state.check = crc32(state.check, input, copy, next);
20512 }
20513 have -= copy;
20514 next += copy;
20515 state.length -= copy;
20516 }
20517 if (state.length) { break inf_leave; }
20518 }
20519 state.length = 0;
20520 state.mode = NAME;
20521 /* falls through */
20522 case NAME:
20523 if (state.flags & 0x0800) {
20524 if (have === 0) { break inf_leave; }
20525 copy = 0;
20526 do {
20527 // TODO: 2 or 1 bytes?
20528 len = input[next + copy++];
20529 /* use constant limit because in js we should not preallocate memory */
20530 if (state.head && len &&
20531 (state.length < 65536 /*state.head.name_max*/)) {
20532 state.head.name += String.fromCharCode(len);
20533 }
20534 } while (len && copy < have);
20535
20536 if (state.flags & 0x0200) {
20537 state.check = crc32(state.check, input, copy, next);
20538 }
20539 have -= copy;
20540 next += copy;
20541 if (len) { break inf_leave; }
20542 }
20543 else if (state.head) {
20544 state.head.name = null;
20545 }
20546 state.length = 0;
20547 state.mode = COMMENT;
20548 /* falls through */
20549 case COMMENT:
20550 if (state.flags & 0x1000) {
20551 if (have === 0) { break inf_leave; }
20552 copy = 0;
20553 do {
20554 len = input[next + copy++];
20555 /* use constant limit because in js we should not preallocate memory */
20556 if (state.head && len &&
20557 (state.length < 65536 /*state.head.comm_max*/)) {
20558 state.head.comment += String.fromCharCode(len);
20559 }
20560 } while (len && copy < have);
20561 if (state.flags & 0x0200) {
20562 state.check = crc32(state.check, input, copy, next);
20563 }
20564 have -= copy;
20565 next += copy;
20566 if (len) { break inf_leave; }
20567 }
20568 else if (state.head) {
20569 state.head.comment = null;
20570 }
20571 state.mode = HCRC;
20572 /* falls through */
20573 case HCRC:
20574 if (state.flags & 0x0200) {
20575 //=== NEEDBITS(16); */
20576 while (bits < 16) {
20577 if (have === 0) { break inf_leave; }
20578 have--;
20579 hold += input[next++] << bits;
20580 bits += 8;
20581 }
20582 //===//
20583 if (hold !== (state.check & 0xffff)) {
20584 strm.msg = 'header crc mismatch';
20585 state.mode = BAD$1;
20586 break;
20587 }
20588 //=== INITBITS();
20589 hold = 0;
20590 bits = 0;
20591 //===//
20592 }
20593 if (state.head) {
20594 state.head.hcrc = ((state.flags >> 9) & 1);
20595 state.head.done = true;
20596 }
20597 strm.adler = state.check = 0;
20598 state.mode = TYPE$1;
20599 break;
20600 case DICTID:
20601 //=== NEEDBITS(32); */
20602 while (bits < 32) {
20603 if (have === 0) { break inf_leave; }
20604 have--;
20605 hold += input[next++] << bits;
20606 bits += 8;
20607 }
20608 //===//
20609 strm.adler = state.check = zswap32(hold);
20610 //=== INITBITS();
20611 hold = 0;
20612 bits = 0;
20613 //===//
20614 state.mode = DICT;
20615 /* falls through */
20616 case DICT:
20617 if (state.havedict === 0) {
20618 //--- RESTORE() ---
20619 strm.next_out = put;
20620 strm.avail_out = left;
20621 strm.next_in = next;
20622 strm.avail_in = have;
20623 state.hold = hold;
20624 state.bits = bits;
20625 //---
20626 return Z_NEED_DICT;
20627 }
20628 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20629 state.mode = TYPE$1;
20630 /* falls through */
20631 case TYPE$1:
20632 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
20633 /* falls through */
20634 case TYPEDO:
20635 if (state.last) {
20636 //--- BYTEBITS() ---//
20637 hold >>>= bits & 7;
20638 bits -= bits & 7;
20639 //---//
20640 state.mode = CHECK;
20641 break;
20642 }
20643 //=== NEEDBITS(3); */
20644 while (bits < 3) {
20645 if (have === 0) { break inf_leave; }
20646 have--;
20647 hold += input[next++] << bits;
20648 bits += 8;
20649 }
20650 //===//
20651 state.last = (hold & 0x01)/*BITS(1)*/;
20652 //--- DROPBITS(1) ---//
20653 hold >>>= 1;
20654 bits -= 1;
20655 //---//
20656
20657 switch ((hold & 0x03)/*BITS(2)*/) {
20658 case 0: /* stored block */
20659 //Tracev((stderr, "inflate: stored block%s\n",
20660 // state.last ? " (last)" : ""));
20661 state.mode = STORED;
20662 break;
20663 case 1: /* fixed block */
20664 fixedtables(state);
20665 //Tracev((stderr, "inflate: fixed codes block%s\n",
20666 // state.last ? " (last)" : ""));
20667 state.mode = LEN_; /* decode codes */
20668 if (flush === Z_TREES) {
20669 //--- DROPBITS(2) ---//
20670 hold >>>= 2;
20671 bits -= 2;
20672 //---//
20673 break inf_leave;
20674 }
20675 break;
20676 case 2: /* dynamic block */
20677 //Tracev((stderr, "inflate: dynamic codes block%s\n",
20678 // state.last ? " (last)" : ""));
20679 state.mode = TABLE;
20680 break;
20681 case 3:
20682 strm.msg = 'invalid block type';
20683 state.mode = BAD$1;
20684 }
20685 //--- DROPBITS(2) ---//
20686 hold >>>= 2;
20687 bits -= 2;
20688 //---//
20689 break;
20690 case STORED:
20691 //--- BYTEBITS() ---// /* go to byte boundary */
20692 hold >>>= bits & 7;
20693 bits -= bits & 7;
20694 //---//
20695 //=== NEEDBITS(32); */
20696 while (bits < 32) {
20697 if (have === 0) { break inf_leave; }
20698 have--;
20699 hold += input[next++] << bits;
20700 bits += 8;
20701 }
20702 //===//
20703 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
20704 strm.msg = 'invalid stored block lengths';
20705 state.mode = BAD$1;
20706 break;
20707 }
20708 state.length = hold & 0xffff;
20709 //Tracev((stderr, "inflate: stored length %u\n",
20710 // state.length));
20711 //=== INITBITS();
20712 hold = 0;
20713 bits = 0;
20714 //===//
20715 state.mode = COPY_;
20716 if (flush === Z_TREES) { break inf_leave; }
20717 /* falls through */
20718 case COPY_:
20719 state.mode = COPY;
20720 /* falls through */
20721 case COPY:
20722 copy = state.length;
20723 if (copy) {
20724 if (copy > have) { copy = have; }
20725 if (copy > left) { copy = left; }
20726 if (copy === 0) { break inf_leave; }
20727 //--- zmemcpy(put, next, copy); ---
20728 arraySet(output, input, next, copy, put);
20729 //---//
20730 have -= copy;
20731 next += copy;
20732 left -= copy;
20733 put += copy;
20734 state.length -= copy;
20735 break;
20736 }
20737 //Tracev((stderr, "inflate: stored end\n"));
20738 state.mode = TYPE$1;
20739 break;
20740 case TABLE:
20741 //=== NEEDBITS(14); */
20742 while (bits < 14) {
20743 if (have === 0) { break inf_leave; }
20744 have--;
20745 hold += input[next++] << bits;
20746 bits += 8;
20747 }
20748 //===//
20749 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
20750 //--- DROPBITS(5) ---//
20751 hold >>>= 5;
20752 bits -= 5;
20753 //---//
20754 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
20755 //--- DROPBITS(5) ---//
20756 hold >>>= 5;
20757 bits -= 5;
20758 //---//
20759 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
20760 //--- DROPBITS(4) ---//
20761 hold >>>= 4;
20762 bits -= 4;
20763 //---//
20764//#ifndef PKZIP_BUG_WORKAROUND
20765 if (state.nlen > 286 || state.ndist > 30) {
20766 strm.msg = 'too many length or distance symbols';
20767 state.mode = BAD$1;
20768 break;
20769 }
20770//#endif
20771 //Tracev((stderr, "inflate: table sizes ok\n"));
20772 state.have = 0;
20773 state.mode = LENLENS;
20774 /* falls through */
20775 case LENLENS:
20776 while (state.have < state.ncode) {
20777 //=== NEEDBITS(3);
20778 while (bits < 3) {
20779 if (have === 0) { break inf_leave; }
20780 have--;
20781 hold += input[next++] << bits;
20782 bits += 8;
20783 }
20784 //===//
20785 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
20786 //--- DROPBITS(3) ---//
20787 hold >>>= 3;
20788 bits -= 3;
20789 //---//
20790 }
20791 while (state.have < 19) {
20792 state.lens[order[state.have++]] = 0;
20793 }
20794 // We have separate tables & no pointers. 2 commented lines below not needed.
20795 //state.next = state.codes;
20796 //state.lencode = state.next;
20797 // Switch to use dynamic table
20798 state.lencode = state.lendyn;
20799 state.lenbits = 7;
20800
20801 opts = { bits: state.lenbits };
20802 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
20803 state.lenbits = opts.bits;
20804
20805 if (ret) {
20806 strm.msg = 'invalid code lengths set';
20807 state.mode = BAD$1;
20808 break;
20809 }
20810 //Tracev((stderr, "inflate: code lengths ok\n"));
20811 state.have = 0;
20812 state.mode = CODELENS;
20813 /* falls through */
20814 case CODELENS:
20815 while (state.have < state.nlen + state.ndist) {
20816 for (;;) {
20817 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
20818 here_bits = here >>> 24;
20819 here_op = (here >>> 16) & 0xff;
20820 here_val = here & 0xffff;
20821
20822 if ((here_bits) <= bits) { break; }
20823 //--- PULLBYTE() ---//
20824 if (have === 0) { break inf_leave; }
20825 have--;
20826 hold += input[next++] << bits;
20827 bits += 8;
20828 //---//
20829 }
20830 if (here_val < 16) {
20831 //--- DROPBITS(here.bits) ---//
20832 hold >>>= here_bits;
20833 bits -= here_bits;
20834 //---//
20835 state.lens[state.have++] = here_val;
20836 }
20837 else {
20838 if (here_val === 16) {
20839 //=== NEEDBITS(here.bits + 2);
20840 n = here_bits + 2;
20841 while (bits < n) {
20842 if (have === 0) { break inf_leave; }
20843 have--;
20844 hold += input[next++] << bits;
20845 bits += 8;
20846 }
20847 //===//
20848 //--- DROPBITS(here.bits) ---//
20849 hold >>>= here_bits;
20850 bits -= here_bits;
20851 //---//
20852 if (state.have === 0) {
20853 strm.msg = 'invalid bit length repeat';
20854 state.mode = BAD$1;
20855 break;
20856 }
20857 len = state.lens[state.have - 1];
20858 copy = 3 + (hold & 0x03);//BITS(2);
20859 //--- DROPBITS(2) ---//
20860 hold >>>= 2;
20861 bits -= 2;
20862 //---//
20863 }
20864 else if (here_val === 17) {
20865 //=== NEEDBITS(here.bits + 3);
20866 n = here_bits + 3;
20867 while (bits < n) {
20868 if (have === 0) { break inf_leave; }
20869 have--;
20870 hold += input[next++] << bits;
20871 bits += 8;
20872 }
20873 //===//
20874 //--- DROPBITS(here.bits) ---//
20875 hold >>>= here_bits;
20876 bits -= here_bits;
20877 //---//
20878 len = 0;
20879 copy = 3 + (hold & 0x07);//BITS(3);
20880 //--- DROPBITS(3) ---//
20881 hold >>>= 3;
20882 bits -= 3;
20883 //---//
20884 }
20885 else {
20886 //=== NEEDBITS(here.bits + 7);
20887 n = here_bits + 7;
20888 while (bits < n) {
20889 if (have === 0) { break inf_leave; }
20890 have--;
20891 hold += input[next++] << bits;
20892 bits += 8;
20893 }
20894 //===//
20895 //--- DROPBITS(here.bits) ---//
20896 hold >>>= here_bits;
20897 bits -= here_bits;
20898 //---//
20899 len = 0;
20900 copy = 11 + (hold & 0x7f);//BITS(7);
20901 //--- DROPBITS(7) ---//
20902 hold >>>= 7;
20903 bits -= 7;
20904 //---//
20905 }
20906 if (state.have + copy > state.nlen + state.ndist) {
20907 strm.msg = 'invalid bit length repeat';
20908 state.mode = BAD$1;
20909 break;
20910 }
20911 while (copy--) {
20912 state.lens[state.have++] = len;
20913 }
20914 }
20915 }
20916
20917 /* handle error breaks in while */
20918 if (state.mode === BAD$1) { break; }
20919
20920 /* check for end-of-block code (better have one) */
20921 if (state.lens[256] === 0) {
20922 strm.msg = 'invalid code -- missing end-of-block';
20923 state.mode = BAD$1;
20924 break;
20925 }
20926
20927 /* build code tables -- note: do not change the lenbits or distbits
20928 values here (9 and 6) without reading the comments in inftrees.h
20929 concerning the ENOUGH constants, which depend on those values */
20930 state.lenbits = 9;
20931
20932 opts = { bits: state.lenbits };
20933 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
20934 // We have separate tables & no pointers. 2 commented lines below not needed.
20935 // state.next_index = opts.table_index;
20936 state.lenbits = opts.bits;
20937 // state.lencode = state.next;
20938
20939 if (ret) {
20940 strm.msg = 'invalid literal/lengths set';
20941 state.mode = BAD$1;
20942 break;
20943 }
20944
20945 state.distbits = 6;
20946 //state.distcode.copy(state.codes);
20947 // Switch to use dynamic table
20948 state.distcode = state.distdyn;
20949 opts = { bits: state.distbits };
20950 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
20951 // We have separate tables & no pointers. 2 commented lines below not needed.
20952 // state.next_index = opts.table_index;
20953 state.distbits = opts.bits;
20954 // state.distcode = state.next;
20955
20956 if (ret) {
20957 strm.msg = 'invalid distances set';
20958 state.mode = BAD$1;
20959 break;
20960 }
20961 //Tracev((stderr, 'inflate: codes ok\n'));
20962 state.mode = LEN_;
20963 if (flush === Z_TREES) { break inf_leave; }
20964 /* falls through */
20965 case LEN_:
20966 state.mode = LEN;
20967 /* falls through */
20968 case LEN:
20969 if (have >= 6 && left >= 258) {
20970 //--- RESTORE() ---
20971 strm.next_out = put;
20972 strm.avail_out = left;
20973 strm.next_in = next;
20974 strm.avail_in = have;
20975 state.hold = hold;
20976 state.bits = bits;
20977 //---
20978 inflate_fast(strm, _out);
20979 //--- LOAD() ---
20980 put = strm.next_out;
20981 output = strm.output;
20982 left = strm.avail_out;
20983 next = strm.next_in;
20984 input = strm.input;
20985 have = strm.avail_in;
20986 hold = state.hold;
20987 bits = state.bits;
20988 //---
20989
20990 if (state.mode === TYPE$1) {
20991 state.back = -1;
20992 }
20993 break;
20994 }
20995 state.back = 0;
20996 for (;;) {
20997 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
20998 here_bits = here >>> 24;
20999 here_op = (here >>> 16) & 0xff;
21000 here_val = here & 0xffff;
21001
21002 if (here_bits <= bits) { break; }
21003 //--- PULLBYTE() ---//
21004 if (have === 0) { break inf_leave; }
21005 have--;
21006 hold += input[next++] << bits;
21007 bits += 8;
21008 //---//
21009 }
21010 if (here_op && (here_op & 0xf0) === 0) {
21011 last_bits = here_bits;
21012 last_op = here_op;
21013 last_val = here_val;
21014 for (;;) {
21015 here = state.lencode[last_val +
21016 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21017 here_bits = here >>> 24;
21018 here_op = (here >>> 16) & 0xff;
21019 here_val = here & 0xffff;
21020
21021 if ((last_bits + here_bits) <= bits) { break; }
21022 //--- PULLBYTE() ---//
21023 if (have === 0) { break inf_leave; }
21024 have--;
21025 hold += input[next++] << bits;
21026 bits += 8;
21027 //---//
21028 }
21029 //--- DROPBITS(last.bits) ---//
21030 hold >>>= last_bits;
21031 bits -= last_bits;
21032 //---//
21033 state.back += last_bits;
21034 }
21035 //--- DROPBITS(here.bits) ---//
21036 hold >>>= here_bits;
21037 bits -= here_bits;
21038 //---//
21039 state.back += here_bits;
21040 state.length = here_val;
21041 if (here_op === 0) {
21042 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
21043 // "inflate: literal '%c'\n" :
21044 // "inflate: literal 0x%02x\n", here.val));
21045 state.mode = LIT;
21046 break;
21047 }
21048 if (here_op & 32) {
21049 //Tracevv((stderr, "inflate: end of block\n"));
21050 state.back = -1;
21051 state.mode = TYPE$1;
21052 break;
21053 }
21054 if (here_op & 64) {
21055 strm.msg = 'invalid literal/length code';
21056 state.mode = BAD$1;
21057 break;
21058 }
21059 state.extra = here_op & 15;
21060 state.mode = LENEXT;
21061 /* falls through */
21062 case LENEXT:
21063 if (state.extra) {
21064 //=== NEEDBITS(state.extra);
21065 n = state.extra;
21066 while (bits < n) {
21067 if (have === 0) { break inf_leave; }
21068 have--;
21069 hold += input[next++] << bits;
21070 bits += 8;
21071 }
21072 //===//
21073 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21074 //--- DROPBITS(state.extra) ---//
21075 hold >>>= state.extra;
21076 bits -= state.extra;
21077 //---//
21078 state.back += state.extra;
21079 }
21080 //Tracevv((stderr, "inflate: length %u\n", state.length));
21081 state.was = state.length;
21082 state.mode = DIST;
21083 /* falls through */
21084 case DIST:
21085 for (;;) {
21086 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
21087 here_bits = here >>> 24;
21088 here_op = (here >>> 16) & 0xff;
21089 here_val = here & 0xffff;
21090
21091 if ((here_bits) <= bits) { break; }
21092 //--- PULLBYTE() ---//
21093 if (have === 0) { break inf_leave; }
21094 have--;
21095 hold += input[next++] << bits;
21096 bits += 8;
21097 //---//
21098 }
21099 if ((here_op & 0xf0) === 0) {
21100 last_bits = here_bits;
21101 last_op = here_op;
21102 last_val = here_val;
21103 for (;;) {
21104 here = state.distcode[last_val +
21105 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21106 here_bits = here >>> 24;
21107 here_op = (here >>> 16) & 0xff;
21108 here_val = here & 0xffff;
21109
21110 if ((last_bits + here_bits) <= bits) { break; }
21111 //--- PULLBYTE() ---//
21112 if (have === 0) { break inf_leave; }
21113 have--;
21114 hold += input[next++] << bits;
21115 bits += 8;
21116 //---//
21117 }
21118 //--- DROPBITS(last.bits) ---//
21119 hold >>>= last_bits;
21120 bits -= last_bits;
21121 //---//
21122 state.back += last_bits;
21123 }
21124 //--- DROPBITS(here.bits) ---//
21125 hold >>>= here_bits;
21126 bits -= here_bits;
21127 //---//
21128 state.back += here_bits;
21129 if (here_op & 64) {
21130 strm.msg = 'invalid distance code';
21131 state.mode = BAD$1;
21132 break;
21133 }
21134 state.offset = here_val;
21135 state.extra = (here_op) & 15;
21136 state.mode = DISTEXT;
21137 /* falls through */
21138 case DISTEXT:
21139 if (state.extra) {
21140 //=== NEEDBITS(state.extra);
21141 n = state.extra;
21142 while (bits < n) {
21143 if (have === 0) { break inf_leave; }
21144 have--;
21145 hold += input[next++] << bits;
21146 bits += 8;
21147 }
21148 //===//
21149 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21150 //--- DROPBITS(state.extra) ---//
21151 hold >>>= state.extra;
21152 bits -= state.extra;
21153 //---//
21154 state.back += state.extra;
21155 }
21156//#ifdef INFLATE_STRICT
21157 if (state.offset > state.dmax) {
21158 strm.msg = 'invalid distance too far back';
21159 state.mode = BAD$1;
21160 break;
21161 }
21162//#endif
21163 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
21164 state.mode = MATCH;
21165 /* falls through */
21166 case MATCH:
21167 if (left === 0) { break inf_leave; }
21168 copy = _out - left;
21169 if (state.offset > copy) { /* copy from window */
21170 copy = state.offset - copy;
21171 if (copy > state.whave) {
21172 if (state.sane) {
21173 strm.msg = 'invalid distance too far back';
21174 state.mode = BAD$1;
21175 break;
21176 }
21177// (!) This block is disabled in zlib defaults,
21178// don't enable it for binary compatibility
21179//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
21180// Trace((stderr, "inflate.c too far\n"));
21181// copy -= state.whave;
21182// if (copy > state.length) { copy = state.length; }
21183// if (copy > left) { copy = left; }
21184// left -= copy;
21185// state.length -= copy;
21186// do {
21187// output[put++] = 0;
21188// } while (--copy);
21189// if (state.length === 0) { state.mode = LEN; }
21190// break;
21191//#endif
21192 }
21193 if (copy > state.wnext) {
21194 copy -= state.wnext;
21195 from = state.wsize - copy;
21196 }
21197 else {
21198 from = state.wnext - copy;
21199 }
21200 if (copy > state.length) { copy = state.length; }
21201 from_source = state.window;
21202 }
21203 else { /* copy from output */
21204 from_source = output;
21205 from = put - state.offset;
21206 copy = state.length;
21207 }
21208 if (copy > left) { copy = left; }
21209 left -= copy;
21210 state.length -= copy;
21211 do {
21212 output[put++] = from_source[from++];
21213 } while (--copy);
21214 if (state.length === 0) { state.mode = LEN; }
21215 break;
21216 case LIT:
21217 if (left === 0) { break inf_leave; }
21218 output[put++] = state.length;
21219 left--;
21220 state.mode = LEN;
21221 break;
21222 case CHECK:
21223 if (state.wrap) {
21224 //=== NEEDBITS(32);
21225 while (bits < 32) {
21226 if (have === 0) { break inf_leave; }
21227 have--;
21228 // Use '|' instead of '+' to make sure that result is signed
21229 hold |= input[next++] << bits;
21230 bits += 8;
21231 }
21232 //===//
21233 _out -= left;
21234 strm.total_out += _out;
21235 state.total += _out;
21236 if (_out) {
21237 strm.adler = state.check =
21238 /*UPDATE(state.check, put - _out, _out);*/
21239 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
21240
21241 }
21242 _out = left;
21243 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
21244 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
21245 strm.msg = 'incorrect data check';
21246 state.mode = BAD$1;
21247 break;
21248 }
21249 //=== INITBITS();
21250 hold = 0;
21251 bits = 0;
21252 //===//
21253 //Tracev((stderr, "inflate: check matches trailer\n"));
21254 }
21255 state.mode = LENGTH;
21256 /* falls through */
21257 case LENGTH:
21258 if (state.wrap && state.flags) {
21259 //=== NEEDBITS(32);
21260 while (bits < 32) {
21261 if (have === 0) { break inf_leave; }
21262 have--;
21263 hold += input[next++] << bits;
21264 bits += 8;
21265 }
21266 //===//
21267 if (hold !== (state.total & 0xffffffff)) {
21268 strm.msg = 'incorrect length check';
21269 state.mode = BAD$1;
21270 break;
21271 }
21272 //=== INITBITS();
21273 hold = 0;
21274 bits = 0;
21275 //===//
21276 //Tracev((stderr, "inflate: length matches trailer\n"));
21277 }
21278 state.mode = DONE;
21279 /* falls through */
21280 case DONE:
21281 ret = Z_STREAM_END;
21282 break inf_leave;
21283 case BAD$1:
21284 ret = Z_DATA_ERROR;
21285 break inf_leave;
21286 // case MEM:
21287 // return Z_MEM_ERROR;
21288 case SYNC:
21289 /* falls through */
21290 default:
21291 return Z_STREAM_ERROR;
21292 }
21293 }
21294
21295 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
21296
21297 /*
21298 Return from inflate(), updating the total counts and the check value.
21299 If there was no progress during the inflate() call, return a buffer
21300 error. Call updatewindow() to create and/or update the window state.
21301 Note: a memory error from inflate() is non-recoverable.
21302 */
21303
21304 //--- RESTORE() ---
21305 strm.next_out = put;
21306 strm.avail_out = left;
21307 strm.next_in = next;
21308 strm.avail_in = have;
21309 state.hold = hold;
21310 state.bits = bits;
21311 //---
21312
21313 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
21314 (state.mode < CHECK || flush !== Z_FINISH))) {
21315 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
21316 }
21317 _in -= strm.avail_in;
21318 _out -= strm.avail_out;
21319 strm.total_in += _in;
21320 strm.total_out += _out;
21321 state.total += _out;
21322 if (state.wrap && _out) {
21323 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
21324 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
21325 }
21326 strm.data_type = state.bits + (state.last ? 64 : 0) +
21327 (state.mode === TYPE$1 ? 128 : 0) +
21328 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
21329 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
21330 ret = Z_BUF_ERROR;
21331 }
21332 return ret;
21333}
21334
21335function inflateEnd(strm) {
21336
21337 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
21338 return Z_STREAM_ERROR;
21339 }
21340
21341 const state = strm.state;
21342 if (state.window) {
21343 state.window = null;
21344 }
21345 strm.state = null;
21346 return Z_OK;
21347}
21348
21349function inflateGetHeader(strm, head) {
21350 let state;
21351
21352 /* check state */
21353 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
21354 state = strm.state;
21355 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
21356
21357 /* save header structure */
21358 state.head = head;
21359 head.done = false;
21360 return Z_OK;
21361}
21362
21363function inflateSetDictionary(strm, dictionary) {
21364 const dictLength = dictionary.length;
21365
21366 let state;
21367 let dictid;
21368
21369 /* check state */
21370 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
21371 state = strm.state;
21372
21373 if (state.wrap !== 0 && state.mode !== DICT) {
21374 return Z_STREAM_ERROR;
21375 }
21376
21377 /* check for correct dictionary identifier */
21378 if (state.mode === DICT) {
21379 dictid = 1; /* adler32(0, null, 0)*/
21380 /* dictid = adler32(dictid, dictionary, dictLength); */
21381 dictid = adler32(dictid, dictionary, dictLength, 0);
21382 if (dictid !== state.check) {
21383 return Z_DATA_ERROR;
21384 }
21385 }
21386 /* copy dictionary to window using updatewindow(), which will amend the
21387 existing dictionary if appropriate */
21388 updatewindow(strm, dictionary, dictLength, dictLength);
21389 // if (ret) {
21390 // state.mode = MEM;
21391 // return Z_MEM_ERROR;
21392 // }
21393 state.havedict = 1;
21394 // Tracev((stderr, "inflate: dictionary set\n"));
21395 return Z_OK;
21396}
21397
21398/* Not implemented
21399exports.inflateCopy = inflateCopy;
21400exports.inflateGetDictionary = inflateGetDictionary;
21401exports.inflateMark = inflateMark;
21402exports.inflatePrime = inflatePrime;
21403exports.inflateSync = inflateSync;
21404exports.inflateSyncPoint = inflateSyncPoint;
21405exports.inflateUndermine = inflateUndermine;
21406*/
21407
21408// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21409// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21410//
21411// This software is provided 'as-is', without any express or implied
21412// warranty. In no event will the authors be held liable for any damages
21413// arising from the use of this software.
21414//
21415// Permission is granted to anyone to use this software for any purpose,
21416// including commercial applications, and to alter it and redistribute it
21417// freely, subject to the following restrictions:
21418//
21419// 1. The origin of this software must not be misrepresented; you must not
21420// claim that you wrote the original software. If you use this software
21421// in a product, an acknowledgment in the product documentation would be
21422// appreciated but is not required.
21423// 2. Altered source versions must be plainly marked as such, and must not be
21424// misrepresented as being the original software.
21425// 3. This notice may not be removed or altered from any source distribution.
21426
21427class GZheader {
21428 constructor() {
21429 /* true if compressed data believed to be text */
21430 this.text = 0;
21431 /* modification time */
21432 this.time = 0;
21433 /* extra flags (not used when writing a gzip file) */
21434 this.xflags = 0;
21435 /* operating system */
21436 this.os = 0;
21437 /* pointer to extra field or Z_NULL if none */
21438 this.extra = null;
21439 /* extra field length (valid if extra != Z_NULL) */
21440 this.extra_len = 0; // Actually, we don't need it in JS,
21441 // but leave for few code modifications
21442
21443 //
21444 // Setup limits is not necessary because in js we should not preallocate memory
21445 // for inflate use constant limit in 65536 bytes
21446 //
21447
21448 /* space at extra (only when reading header) */
21449 // this.extra_max = 0;
21450 /* pointer to zero-terminated file name or Z_NULL */
21451 this.name = '';
21452 /* space at name (only when reading header) */
21453 // this.name_max = 0;
21454 /* pointer to zero-terminated comment or Z_NULL */
21455 this.comment = '';
21456 /* space at comment (only when reading header) */
21457 // this.comm_max = 0;
21458 /* true if there was or will be a header crc */
21459 this.hcrc = 0;
21460 /* true when done reading gzip header (not used when writing a gzip file) */
21461 this.done = false;
21462 }
21463}
21464
21465/**
21466 * class Inflate
21467 *
21468 * Generic JS-style wrapper for zlib calls. If you don't need
21469 * streaming behaviour - use more simple functions: [[inflate]]
21470 * and [[inflateRaw]].
21471 **/
21472
21473/* internal
21474 * inflate.chunks -> Array
21475 *
21476 * Chunks of output data, if [[Inflate#onData]] not overridden.
21477 **/
21478
21479/**
21480 * Inflate.result -> Uint8Array|Array|String
21481 *
21482 * Uncompressed result, generated by default [[Inflate#onData]]
21483 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
21484 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
21485 * push a chunk with explicit flush (call [[Inflate#push]] with
21486 * `Z_SYNC_FLUSH` param).
21487 **/
21488
21489/**
21490 * Inflate.err -> Number
21491 *
21492 * Error code after inflate finished. 0 (Z_OK) on success.
21493 * Should be checked if broken data possible.
21494 **/
21495
21496/**
21497 * Inflate.msg -> String
21498 *
21499 * Error message, if [[Inflate.err]] != 0
21500 **/
21501
21502
21503/**
21504 * new Inflate(options)
21505 * - options (Object): zlib inflate options.
21506 *
21507 * Creates new inflator instance with specified params. Throws exception
21508 * on bad params. Supported options:
21509 *
21510 * - `windowBits`
21511 * - `dictionary`
21512 *
21513 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
21514 * for more information on these.
21515 *
21516 * Additional options, for internal needs:
21517 *
21518 * - `chunkSize` - size of generated data chunks (16K by default)
21519 * - `raw` (Boolean) - do raw inflate
21520 * - `to` (String) - if equal to 'string', then result will be converted
21521 * from utf8 to utf16 (javascript) string. When string output requested,
21522 * chunk length can differ from `chunkSize`, depending on content.
21523 *
21524 * By default, when no options set, autodetect deflate/gzip data format via
21525 * wrapper header.
21526 *
21527 * ##### Example:
21528 *
21529 * ```javascript
21530 * var pako = void('pako')
21531 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
21532 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
21533 *
21534 * var inflate = new pako.Inflate({ level: 3});
21535 *
21536 * inflate.push(chunk1, false);
21537 * inflate.push(chunk2, true); // true -> last chunk
21538 *
21539 * if (inflate.err) { throw new Error(inflate.err); }
21540 *
21541 * console.log(inflate.result);
21542 * ```
21543 **/
21544class Inflate {
21545 constructor(options) {
21546 this.options = {
21547 chunkSize: 16384,
21548 windowBits: 0,
21549 ...(options || {})
21550 };
21551
21552 const opt = this.options;
21553
21554 // Force window size for `raw` data, if not set directly,
21555 // because we have no header for autodetect.
21556 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
21557 opt.windowBits = -opt.windowBits;
21558 if (opt.windowBits === 0) { opt.windowBits = -15; }
21559 }
21560
21561 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
21562 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
21563 !(options && options.windowBits)) {
21564 opt.windowBits += 32;
21565 }
21566
21567 // Gzip header has no info about windows size, we can do autodetect only
21568 // for deflate. So, if window size not set, force it to max when gzip possible
21569 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
21570 // bit 3 (16) -> gzipped data
21571 // bit 4 (32) -> autodetect gzip/deflate
21572 if ((opt.windowBits & 15) === 0) {
21573 opt.windowBits |= 15;
21574 }
21575 }
21576
21577 this.err = 0; // error code, if happens (0 = Z_OK)
21578 this.msg = ''; // error message
21579 this.ended = false; // used to avoid multiple onEnd() calls
21580 this.chunks = []; // chunks of compressed data
21581
21582 this.strm = new ZStream();
21583 this.strm.avail_out = 0;
21584
21585 let status = inflateInit2(
21586 this.strm,
21587 opt.windowBits
21588 );
21589
21590 if (status !== Z_OK) {
21591 throw new Error(msg[status]);
21592 }
21593
21594 this.header = new GZheader();
21595
21596 inflateGetHeader(this.strm, this.header);
21597
21598 // Setup dictionary
21599 if (opt.dictionary) {
21600 // Convert data if needed
21601 if (typeof opt.dictionary === 'string') {
21602 opt.dictionary = string2buf(opt.dictionary);
21603 } else if (opt.dictionary instanceof ArrayBuffer) {
21604 opt.dictionary = new Uint8Array(opt.dictionary);
21605 }
21606 if (opt.raw) { //In raw mode we need to set the dictionary early
21607 status = inflateSetDictionary(this.strm, opt.dictionary);
21608 if (status !== Z_OK) {
21609 throw new Error(msg[status]);
21610 }
21611 }
21612 }
21613 }
21614 /**
21615 * Inflate#push(data[, mode]) -> Boolean
21616 * - data (Uint8Array|Array|ArrayBuffer|String): input data
21617 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
21618 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
21619 *
21620 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
21621 * new output chunks. Returns `true` on success. The last data block must have
21622 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
21623 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
21624 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
21625 *
21626 * On fail call [[Inflate#onEnd]] with error code and return false.
21627 *
21628 * We strongly recommend to use `Uint8Array` on input for best speed (output
21629 * format is detected automatically). Also, don't skip last param and always
21630 * use the same type in your code (boolean or number). That will improve JS speed.
21631 *
21632 * For regular `Array`-s make sure all elements are [0..255].
21633 *
21634 * ##### Example
21635 *
21636 * ```javascript
21637 * push(chunk, false); // push one of data chunks
21638 * ...
21639 * push(chunk, true); // push last chunk
21640 * ```
21641 **/
21642 push(data, mode) {
21643 const { strm, options: { chunkSize, dictionary } } = this;
21644 let status, _mode;
21645
21646 // Flag to properly process Z_BUF_ERROR on testing inflate call
21647 // when we check that all output data was flushed.
21648 let allowBufError = false;
21649
21650 if (this.ended) { return false; }
21651 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
21652
21653 // Convert data if needed
21654 if (typeof data === 'string') {
21655 // Only binary strings can be decompressed on practice
21656 strm.input = binstring2buf(data);
21657 } else if (data instanceof ArrayBuffer) {
21658 strm.input = new Uint8Array(data);
21659 } else {
21660 strm.input = data;
21661 }
21662
21663 strm.next_in = 0;
21664 strm.avail_in = strm.input.length;
21665
21666 do {
21667 if (strm.avail_out === 0) {
21668 strm.output = new Buf8(chunkSize);
21669 strm.next_out = 0;
21670 strm.avail_out = chunkSize;
21671 }
21672
21673 status = inflate(strm, Z_NO_FLUSH); /* no bad return value */
21674
21675 if (status === Z_NEED_DICT && dictionary) {
21676 status = inflateSetDictionary(this.strm, dictionary);
21677 }
21678
21679 if (status === Z_BUF_ERROR && allowBufError === true) {
21680 status = Z_OK;
21681 allowBufError = false;
21682 }
21683
21684 if (status !== Z_STREAM_END && status !== Z_OK) {
21685 this.onEnd(status);
21686 this.ended = true;
21687 return false;
21688 }
21689
21690 if (strm.next_out) {
21691 if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
21692 this.onData(shrinkBuf(strm.output, strm.next_out));
21693 }
21694 }
21695
21696 // When no more input data, we should check that internal inflate buffers
21697 // are flushed. The only way to do it when avail_out = 0 - run one more
21698 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
21699 // Here we set flag to process this error properly.
21700 //
21701 // NOTE. Deflate does not return error in this case and does not needs such
21702 // logic.
21703 if (strm.avail_in === 0 && strm.avail_out === 0) {
21704 allowBufError = true;
21705 }
21706
21707 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
21708
21709 if (status === Z_STREAM_END) {
21710 _mode = Z_FINISH;
21711 }
21712
21713 // Finalize on the last chunk.
21714 if (_mode === Z_FINISH) {
21715 status = inflateEnd(this.strm);
21716 this.onEnd(status);
21717 this.ended = true;
21718 return status === Z_OK;
21719 }
21720
21721 // callback interim results if Z_SYNC_FLUSH.
21722 if (_mode === Z_SYNC_FLUSH) {
21723 this.onEnd(Z_OK);
21724 strm.avail_out = 0;
21725 return true;
21726 }
21727
21728 return true;
21729 };
21730
21731 /**
21732 * Inflate#onData(chunk) -> Void
21733 * - chunk (Uint8Array|Array|String): output data. Type of array depends
21734 * on js engine support. When string output requested, each chunk
21735 * will be string.
21736 *
21737 * By default, stores data blocks in `chunks[]` property and glue
21738 * those in `onEnd`. Override this handler, if you need another behaviour.
21739 **/
21740 onData(chunk) {
21741 this.chunks.push(chunk);
21742 };
21743
21744
21745
21746 /**
21747 * Inflate#onEnd(status) -> Void
21748 * - status (Number): inflate status. 0 (Z_OK) on success,
21749 * other if not.
21750 *
21751 * Called either after you tell inflate that the input stream is
21752 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
21753 * or if an error happened. By default - join collected chunks,
21754 * free memory and fill `results` / `err` properties.
21755 **/
21756 onEnd(status) {
21757 // On success - join
21758 if (status === Z_OK) {
21759 this.result = flattenChunks(this.chunks);
21760 }
21761 this.chunks = [];
21762 this.err = status;
21763 this.msg = this.strm.msg;
21764 };
21765}
21766
21767/*
21768node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
21769
21770Copyright (C) 2012 Eli Skeggs
21771
21772This library is free software; you can redistribute it and/or
21773modify it under the terms of the GNU Lesser General Public
21774License as published by the Free Software Foundation; either
21775version 2.1 of the License, or (at your option) any later version.
21776
21777This library is distributed in the hope that it will be useful,
21778but WITHOUT ANY WARRANTY; without even the implied warranty of
21779MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21780Lesser General Public License for more details.
21781
21782You should have received a copy of the GNU Lesser General Public
21783License along with this library; if not, see
21784http://www.gnu.org/licenses/lgpl-2.1.html
21785
21786Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
21787
21788Based on micro-bunzip by Rob Landley (rob@landley.net).
21789
21790Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21791which also acknowledges contributions by Mike Burrows, David Wheeler,
21792Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21793Robert Sedgewick, and Jon L. Bentley.
21794*/
21795
21796var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
21797
21798// offset in bytes
21799var BitReader = function(stream) {
21800 this.stream = stream;
21801 this.bitOffset = 0;
21802 this.curByte = 0;
21803 this.hasByte = false;
21804};
21805
21806BitReader.prototype._ensureByte = function() {
21807 if (!this.hasByte) {
21808 this.curByte = this.stream.readByte();
21809 this.hasByte = true;
21810 }
21811};
21812
21813// reads bits from the buffer
21814BitReader.prototype.read = function(bits) {
21815 var result = 0;
21816 while (bits > 0) {
21817 this._ensureByte();
21818 var remaining = 8 - this.bitOffset;
21819 // if we're in a byte
21820 if (bits >= remaining) {
21821 result <<= remaining;
21822 result |= BITMASK[remaining] & this.curByte;
21823 this.hasByte = false;
21824 this.bitOffset = 0;
21825 bits -= remaining;
21826 } else {
21827 result <<= bits;
21828 var shift = remaining - bits;
21829 result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;
21830 this.bitOffset += bits;
21831 bits = 0;
21832 }
21833 }
21834 return result;
21835};
21836
21837// seek to an arbitrary point in the buffer (expressed in bits)
21838BitReader.prototype.seek = function(pos) {
21839 var n_bit = pos % 8;
21840 var n_byte = (pos - n_bit) / 8;
21841 this.bitOffset = n_bit;
21842 this.stream.seek(n_byte);
21843 this.hasByte = false;
21844};
21845
21846// reads 6 bytes worth of data using the read method
21847BitReader.prototype.pi = function() {
21848 var buf = new Uint8Array(6), i;
21849 for (i = 0; i < buf.length; i++) {
21850 buf[i] = this.read(8);
21851 }
21852 return bufToHex(buf);
21853};
21854
21855function bufToHex(buf) {
21856 return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
21857}
21858
21859var bitreader = BitReader;
21860
21861/* very simple input/output stream interface */
21862var Stream = function() {
21863};
21864
21865// input streams //////////////
21866/** Returns the next byte, or -1 for EOF. */
21867Stream.prototype.readByte = function() {
21868 throw new Error("abstract method readByte() not implemented");
21869};
21870/** Attempts to fill the buffer; returns number of bytes read, or
21871 * -1 for EOF. */
21872Stream.prototype.read = function(buffer, bufOffset, length) {
21873 var bytesRead = 0;
21874 while (bytesRead < length) {
21875 var c = this.readByte();
21876 if (c < 0) { // EOF
21877 return (bytesRead===0) ? -1 : bytesRead;
21878 }
21879 buffer[bufOffset++] = c;
21880 bytesRead++;
21881 }
21882 return bytesRead;
21883};
21884Stream.prototype.seek = function(new_pos) {
21885 throw new Error("abstract method seek() not implemented");
21886};
21887
21888// output streams ///////////
21889Stream.prototype.writeByte = function(_byte) {
21890 throw new Error("abstract method readByte() not implemented");
21891};
21892Stream.prototype.write = function(buffer, bufOffset, length) {
21893 var i;
21894 for (i=0; i<length; i++) {
21895 this.writeByte(buffer[bufOffset++]);
21896 }
21897 return length;
21898};
21899Stream.prototype.flush = function() {
21900};
21901
21902var stream = Stream;
21903
21904/* CRC32, used in Bzip2 implementation.
21905 * This is a port of CRC32.java from the jbzip2 implementation at
21906 * https://code.google.com/p/jbzip2
21907 * which is:
21908 * Copyright (c) 2011 Matthew Francis
21909 *
21910 * Permission is hereby granted, free of charge, to any person
21911 * obtaining a copy of this software and associated documentation
21912 * files (the "Software"), to deal in the Software without
21913 * restriction, including without limitation the rights to use,
21914 * copy, modify, merge, publish, distribute, sublicense, and/or sell
21915 * copies of the Software, and to permit persons to whom the
21916 * Software is furnished to do so, subject to the following
21917 * conditions:
21918 *
21919 * The above copyright notice and this permission notice shall be
21920 * included in all copies or substantial portions of the Software.
21921 *
21922 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21923 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21924 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21925 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21926 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21927 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21928 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21929 * OTHER DEALINGS IN THE SOFTWARE.
21930 * This JavaScript implementation is:
21931 * Copyright (c) 2013 C. Scott Ananian
21932 * with the same licensing terms as Matthew Francis' original implementation.
21933 */
21934var crc32$1 = (function() {
21935
21936 /**
21937 * A static CRC lookup table
21938 */
21939 var crc32Lookup = new Uint32Array([
21940 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
21941 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
21942 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
21943 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
21944 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
21945 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
21946 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
21947 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
21948 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
21949 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
21950 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
21951 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
21952 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
21953 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
21954 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
21955 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
21956 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
21957 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
21958 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
21959 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
21960 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
21961 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
21962 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
21963 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
21964 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
21965 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
21966 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
21967 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
21968 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
21969 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
21970 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
21971 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
21972 ]);
21973
21974 var CRC32 = function() {
21975 /**
21976 * The current CRC
21977 */
21978 var crc = 0xffffffff;
21979
21980 /**
21981 * @return The current CRC
21982 */
21983 this.getCRC = function() {
21984 return (~crc) >>> 0; // return an unsigned value
21985 };
21986
21987 /**
21988 * Update the CRC with a single byte
21989 * @param value The value to update the CRC with
21990 */
21991 this.updateCRC = function(value) {
21992 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
21993 };
21994
21995 /**
21996 * Update the CRC with a sequence of identical bytes
21997 * @param value The value to update the CRC with
21998 * @param count The number of bytes
21999 */
22000 this.updateCRCRun = function(value, count) {
22001 while (count-- > 0) {
22002 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
22003 }
22004 };
22005 };
22006 return CRC32;
22007})();
22008
22009/*
22010seek-bzip - a pure-javascript module for seeking within bzip2 data
22011
22012Copyright (C) 2013 C. Scott Ananian
22013Copyright (C) 2012 Eli Skeggs
22014Copyright (C) 2011 Kevin Kwok
22015
22016This library is free software; you can redistribute it and/or
22017modify it under the terms of the GNU Lesser General Public
22018License as published by the Free Software Foundation; either
22019version 2.1 of the License, or (at your option) any later version.
22020
22021This library is distributed in the hope that it will be useful,
22022but WITHOUT ANY WARRANTY; without even the implied warranty of
22023MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22024Lesser General Public License for more details.
22025
22026You should have received a copy of the GNU Lesser General Public
22027License along with this library; if not, see
22028http://www.gnu.org/licenses/lgpl-2.1.html
22029
22030Adapted from node-bzip, copyright 2012 Eli Skeggs.
22031Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
22032
22033Based on micro-bunzip by Rob Landley (rob@landley.net).
22034
22035Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
22036which also acknowledges contributions by Mike Burrows, David Wheeler,
22037Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
22038Robert Sedgewick, and Jon L. Bentley.
22039*/
22040
22041
22042
22043
22044
22045var MAX_HUFCODE_BITS = 20;
22046var MAX_SYMBOLS = 258;
22047var SYMBOL_RUNA = 0;
22048var SYMBOL_RUNB = 1;
22049var MIN_GROUPS = 2;
22050var MAX_GROUPS = 6;
22051var GROUP_SIZE = 50;
22052
22053var WHOLEPI = "314159265359";
22054var SQRTPI = "177245385090";
22055
22056var mtf = function(array, index) {
22057 var src = array[index], i;
22058 for (i = index; i > 0; i--) {
22059 array[i] = array[i-1];
22060 }
22061 array[0] = src;
22062 return src;
22063};
22064
22065var Err = {
22066 OK: 0,
22067 LAST_BLOCK: -1,
22068 NOT_BZIP_DATA: -2,
22069 UNEXPECTED_INPUT_EOF: -3,
22070 UNEXPECTED_OUTPUT_EOF: -4,
22071 DATA_ERROR: -5,
22072 OUT_OF_MEMORY: -6,
22073 OBSOLETE_INPUT: -7,
22074 END_OF_BLOCK: -8
22075};
22076var ErrorMessages = {};
22077ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
22078ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
22079ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
22080ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
22081ErrorMessages[Err.DATA_ERROR] = "Data error";
22082ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
22083ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
22084
22085var _throw = function(status, optDetail) {
22086 var msg = ErrorMessages[status] || 'unknown error';
22087 if (optDetail) { msg += ': '+optDetail; }
22088 var e = new TypeError(msg);
22089 e.errorCode = status;
22090 throw e;
22091};
22092
22093var Bunzip = function(inputStream, outputStream) {
22094 this.writePos = this.writeCurrent = this.writeCount = 0;
22095
22096 this._start_bunzip(inputStream, outputStream);
22097};
22098Bunzip.prototype._init_block = function() {
22099 var moreBlocks = this._get_next_block();
22100 if ( !moreBlocks ) {
22101 this.writeCount = -1;
22102 return false; /* no more blocks */
22103 }
22104 this.blockCRC = new crc32$1();
22105 return true;
22106};
22107/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
22108Bunzip.prototype._start_bunzip = function(inputStream, outputStream) {
22109 /* Ensure that file starts with "BZh['1'-'9']." */
22110 var buf = new Uint8Array(4);
22111 if (inputStream.read(buf, 0, 4) !== 4 ||
22112 String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')
22113 _throw(Err.NOT_BZIP_DATA, 'bad magic');
22114
22115 var level = buf[3] - 0x30;
22116 if (level < 1 || level > 9)
22117 _throw(Err.NOT_BZIP_DATA, 'level out of range');
22118
22119 this.reader = new bitreader(inputStream);
22120
22121 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
22122 uncompressed data. Allocate intermediate buffer for block. */
22123 this.dbufSize = 100000 * level;
22124 this.nextoutput = 0;
22125 this.outputStream = outputStream;
22126 this.streamCRC = 0;
22127};
22128Bunzip.prototype._get_next_block = function() {
22129 var i, j, k;
22130 var reader = this.reader;
22131 // this is get_next_block() function from micro-bunzip:
22132 /* Read in header signature and CRC, then validate signature.
22133 (last block signature means CRC is for whole file, return now) */
22134 var h = reader.pi();
22135 if (h === SQRTPI) { // last block
22136 return false; /* no more blocks */
22137 }
22138 if (h !== WHOLEPI)
22139 _throw(Err.NOT_BZIP_DATA);
22140 this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
22141 this.streamCRC = (this.targetBlockCRC ^
22142 ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;
22143 /* We can add support for blockRandomised if anybody complains. There was
22144 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
22145 it didn't actually work. */
22146 if (reader.read(1))
22147 _throw(Err.OBSOLETE_INPUT);
22148 var origPointer = reader.read(24);
22149 if (origPointer > this.dbufSize)
22150 _throw(Err.DATA_ERROR, 'initial position out of bounds');
22151 /* mapping table: if some byte values are never used (encoding things
22152 like ascii text), the compression code removes the gaps to have fewer
22153 symbols to deal with, and writes a sparse bitfield indicating which
22154 values were present. We make a translation table to convert the symbols
22155 back to the corresponding bytes. */
22156 var t = reader.read(16);
22157 var symToByte = new Uint8Array(256), symTotal = 0;
22158 for (i = 0; i < 16; i++) {
22159 if (t & (1 << (0xF - i))) {
22160 var o = i * 16;
22161 k = reader.read(16);
22162 for (j = 0; j < 16; j++)
22163 if (k & (1 << (0xF - j)))
22164 symToByte[symTotal++] = o + j;
22165 }
22166 }
22167
22168 /* How many different huffman coding groups does this block use? */
22169 var groupCount = reader.read(3);
22170 if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)
22171 _throw(Err.DATA_ERROR);
22172 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
22173 group. Read in the group selector list, which is stored as MTF encoded
22174 bit runs. (MTF=Move To Front, as each value is used it's moved to the
22175 start of the list.) */
22176 var nSelectors = reader.read(15);
22177 if (nSelectors === 0)
22178 _throw(Err.DATA_ERROR);
22179
22180 var mtfSymbol = new Uint8Array(256);
22181 for (i = 0; i < groupCount; i++)
22182 mtfSymbol[i] = i;
22183
22184 var selectors = new Uint8Array(nSelectors); // was 32768...
22185
22186 for (i = 0; i < nSelectors; i++) {
22187 /* Get next value */
22188 for (j = 0; reader.read(1); j++)
22189 if (j >= groupCount) _throw(Err.DATA_ERROR);
22190 /* Decode MTF to get the next selector */
22191 selectors[i] = mtf(mtfSymbol, j);
22192 }
22193
22194 /* Read the huffman coding tables for each group, which code for symTotal
22195 literal symbols, plus two run symbols (RUNA, RUNB) */
22196 var symCount = symTotal + 2;
22197 var groups = [], hufGroup;
22198 for (j = 0; j < groupCount; j++) {
22199 var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
22200 /* Read huffman code lengths for each symbol. They're stored in
22201 a way similar to mtf; record a starting value for the first symbol,
22202 and an offset from the previous value for everys symbol after that. */
22203 t = reader.read(5); // lengths
22204 for (i = 0; i < symCount; i++) {
22205 for (;;) {
22206 if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
22207 /* If first bit is 0, stop. Else second bit indicates whether
22208 to increment or decrement the value. */
22209 if(!reader.read(1))
22210 break;
22211 if(!reader.read(1))
22212 t++;
22213 else
22214 t--;
22215 }
22216 length[i] = t;
22217 }
22218
22219 /* Find largest and smallest lengths in this group */
22220 var minLen, maxLen;
22221 minLen = maxLen = length[0];
22222 for (i = 1; i < symCount; i++) {
22223 if (length[i] > maxLen)
22224 maxLen = length[i];
22225 else if (length[i] < minLen)
22226 minLen = length[i];
22227 }
22228
22229 /* Calculate permute[], base[], and limit[] tables from length[].
22230 *
22231 * permute[] is the lookup table for converting huffman coded symbols
22232 * into decoded symbols. base[] is the amount to subtract from the
22233 * value of a huffman symbol of a given length when using permute[].
22234 *
22235 * limit[] indicates the largest numerical value a symbol with a given
22236 * number of bits can have. This is how the huffman codes can vary in
22237 * length: each code with a value>limit[length] needs another bit.
22238 */
22239 hufGroup = {};
22240 groups.push(hufGroup);
22241 hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
22242 hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
22243 hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
22244 hufGroup.minLen = minLen;
22245 hufGroup.maxLen = maxLen;
22246 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
22247 var pp = 0;
22248 for (i = minLen; i <= maxLen; i++) {
22249 temp[i] = hufGroup.limit[i] = 0;
22250 for (t = 0; t < symCount; t++)
22251 if (length[t] === i)
22252 hufGroup.permute[pp++] = t;
22253 }
22254 /* Count symbols coded for at each bit length */
22255 for (i = 0; i < symCount; i++)
22256 temp[length[i]]++;
22257 /* Calculate limit[] (the largest symbol-coding value at each bit
22258 * length, which is (previous limit<<1)+symbols at this level), and
22259 * base[] (number of symbols to ignore at each bit length, which is
22260 * limit minus the cumulative count of symbols coded for already). */
22261 pp = t = 0;
22262 for (i = minLen; i < maxLen; i++) {
22263 pp += temp[i];
22264 /* We read the largest possible symbol size and then unget bits
22265 after determining how many we need, and those extra bits could
22266 be set to anything. (They're noise from future symbols.) At
22267 each level we're really only interested in the first few bits,
22268 so here we set all the trailing to-be-ignored bits to 1 so they
22269 don't affect the value>limit[length] comparison. */
22270 hufGroup.limit[i] = pp - 1;
22271 pp <<= 1;
22272 t += temp[i];
22273 hufGroup.base[i + 1] = pp - t;
22274 }
22275 hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
22276 hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
22277 hufGroup.base[minLen] = 0;
22278 }
22279 /* We've finished reading and digesting the block header. Now read this
22280 block's huffman coded symbols from the file and undo the huffman coding
22281 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
22282
22283 /* Initialize symbol occurrence counters and symbol Move To Front table */
22284 var byteCount = new Uint32Array(256);
22285 for (i = 0; i < 256; i++)
22286 mtfSymbol[i] = i;
22287 /* Loop through compressed symbols. */
22288 var runPos = 0, dbufCount = 0, selector = 0, uc;
22289 var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
22290 symCount = 0;
22291 for (;;) {
22292 /* Determine which huffman coding group to use. */
22293 if (!(symCount--)) {
22294 symCount = GROUP_SIZE - 1;
22295 if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }
22296 hufGroup = groups[selectors[selector++]];
22297 }
22298 /* Read next huffman-coded symbol. */
22299 i = hufGroup.minLen;
22300 j = reader.read(i);
22301 for (;;i++) {
22302 if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }
22303 if (j <= hufGroup.limit[i])
22304 break;
22305 j = (j << 1) | reader.read(1);
22306 }
22307 /* Huffman decode value to get nextSym (with bounds checking) */
22308 j -= hufGroup.base[i];
22309 if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }
22310 var nextSym = hufGroup.permute[j];
22311 /* We have now decoded the symbol, which indicates either a new literal
22312 byte, or a repeated run of the most recent literal byte. First,
22313 check if nextSym indicates a repeated run, and if so loop collecting
22314 how many times to repeat the last literal. */
22315 if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
22316 /* If this is the start of a new run, zero out counter */
22317 if (!runPos){
22318 runPos = 1;
22319 t = 0;
22320 }
22321 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
22322 each bit position, add 1 or 2 instead. For example,
22323 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
22324 You can make any bit pattern that way using 1 less symbol than
22325 the basic or 0/1 method (except all bits 0, which would use no
22326 symbols, but a run of length 0 doesn't mean anything in this
22327 context). Thus space is saved. */
22328 if (nextSym === SYMBOL_RUNA)
22329 t += runPos;
22330 else
22331 t += 2 * runPos;
22332 runPos <<= 1;
22333 continue;
22334 }
22335 /* When we hit the first non-run symbol after a run, we now know
22336 how many times to repeat the last literal, so append that many
22337 copies to our buffer of decoded symbols (dbuf) now. (The last
22338 literal used is the one at the head of the mtfSymbol array.) */
22339 if (runPos){
22340 runPos = 0;
22341 if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }
22342 uc = symToByte[mtfSymbol[0]];
22343 byteCount[uc] += t;
22344 while (t--)
22345 dbuf[dbufCount++] = uc;
22346 }
22347 /* Is this the terminating symbol? */
22348 if (nextSym > symTotal)
22349 break;
22350 /* At this point, nextSym indicates a new literal character. Subtract
22351 one to get the position in the MTF array at which this literal is
22352 currently to be found. (Note that the result can't be -1 or 0,
22353 because 0 and 1 are RUNA and RUNB. But another instance of the
22354 first symbol in the mtf array, position 0, would have been handled
22355 as part of a run above. Therefore 1 unused mtf position minus
22356 2 non-literal nextSym values equals -1.) */
22357 if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }
22358 i = nextSym - 1;
22359 uc = mtf(mtfSymbol, i);
22360 uc = symToByte[uc];
22361 /* We have our literal byte. Save it into dbuf. */
22362 byteCount[uc]++;
22363 dbuf[dbufCount++] = uc;
22364 }
22365 /* At this point, we've read all the huffman-coded symbols (and repeated
22366 runs) for this block from the input stream, and decoded them into the
22367 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
22368 Now undo the Burrows-Wheeler transform on dbuf.
22369 See http://dogma.net/markn/articles/bwt/bwt.htm
22370 */
22371 if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }
22372 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
22373 j = 0;
22374 for (i = 0; i < 256; i++) {
22375 k = j + byteCount[i];
22376 byteCount[i] = j;
22377 j = k;
22378 }
22379 /* Figure out what order dbuf would be in if we sorted it. */
22380 for (i = 0; i < dbufCount; i++) {
22381 uc = dbuf[i] & 0xff;
22382 dbuf[byteCount[uc]] |= (i << 8);
22383 byteCount[uc]++;
22384 }
22385 /* Decode first byte by hand to initialize "previous" byte. Note that it
22386 doesn't get output, and if the first three characters are identical
22387 it doesn't qualify as a run (hence writeRunCountdown=5). */
22388 var pos = 0, current = 0, run = 0;
22389 if (dbufCount) {
22390 pos = dbuf[origPointer];
22391 current = (pos & 0xff);
22392 pos >>= 8;
22393 run = -1;
22394 }
22395 this.writePos = pos;
22396 this.writeCurrent = current;
22397 this.writeCount = dbufCount;
22398 this.writeRun = run;
22399
22400 return true; /* more blocks to come */
22401};
22402/* Undo burrows-wheeler transform on intermediate buffer to produce output.
22403 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
22404 data are written to outbuf. Return value is number of bytes written or
22405 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
22406 are ignored, data is written to out_fd and return is RETVAL_OK or error.
22407*/
22408Bunzip.prototype._read_bunzip = function(outputBuffer, len) {
22409 var copies, previous, outbyte;
22410 /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
22411 decoded, which results in this returning RETVAL_LAST_BLOCK, also
22412 equal to -1... Confusing, I'm returning 0 here to indicate no
22413 bytes written into the buffer */
22414 if (this.writeCount < 0) { return 0; }
22415 var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;
22416 var dbufCount = this.writeCount; this.outputsize;
22417 var run = this.writeRun;
22418
22419 while (dbufCount) {
22420 dbufCount--;
22421 previous = current;
22422 pos = dbuf[pos];
22423 current = pos & 0xff;
22424 pos >>= 8;
22425 if (run++ === 3){
22426 copies = current;
22427 outbyte = previous;
22428 current = -1;
22429 } else {
22430 copies = 1;
22431 outbyte = current;
22432 }
22433 this.blockCRC.updateCRCRun(outbyte, copies);
22434 while (copies--) {
22435 this.outputStream.writeByte(outbyte);
22436 this.nextoutput++;
22437 }
22438 if (current != previous)
22439 run = 0;
22440 }
22441 this.writeCount = dbufCount;
22442 // check CRC
22443 if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
22444 _throw(Err.DATA_ERROR, "Bad block CRC "+
22445 "(got "+this.blockCRC.getCRC().toString(16)+
22446 " expected "+this.targetBlockCRC.toString(16)+")");
22447 }
22448 return this.nextoutput;
22449};
22450
22451var coerceInputStream = function(input) {
22452 if ('readByte' in input) { return input; }
22453 var inputStream = new stream();
22454 inputStream.pos = 0;
22455 inputStream.readByte = function() { return input[this.pos++]; };
22456 inputStream.seek = function(pos) { this.pos = pos; };
22457 inputStream.eof = function() { return this.pos >= input.length; };
22458 return inputStream;
22459};
22460var coerceOutputStream = function(output) {
22461 var outputStream = new stream();
22462 var resizeOk = true;
22463 if (output) {
22464 if (typeof(output)==='number') {
22465 outputStream.buffer = new Uint8Array(output);
22466 resizeOk = false;
22467 } else if ('writeByte' in output) {
22468 return output;
22469 } else {
22470 outputStream.buffer = output;
22471 resizeOk = false;
22472 }
22473 } else {
22474 outputStream.buffer = new Uint8Array(16384);
22475 }
22476 outputStream.pos = 0;
22477 outputStream.writeByte = function(_byte) {
22478 if (resizeOk && this.pos >= this.buffer.length) {
22479 var newBuffer = new Uint8Array(this.buffer.length*2);
22480 newBuffer.set(this.buffer);
22481 this.buffer = newBuffer;
22482 }
22483 this.buffer[this.pos++] = _byte;
22484 };
22485 outputStream.getBuffer = function() {
22486 // trim buffer
22487 if (this.pos !== this.buffer.length) {
22488 if (!resizeOk)
22489 throw new TypeError('outputsize does not match decoded input');
22490 var newBuffer = new Uint8Array(this.pos);
22491 newBuffer.set(this.buffer.subarray(0, this.pos));
22492 this.buffer = newBuffer;
22493 }
22494 return this.buffer;
22495 };
22496 outputStream._coerced = true;
22497 return outputStream;
22498};
22499
22500/* Static helper functions */
22501// 'input' can be a stream or a buffer
22502// 'output' can be a stream or a buffer or a number (buffer size)
22503const decode$2 = function(input, output, multistream) {
22504 // make a stream from a buffer, if necessary
22505 var inputStream = coerceInputStream(input);
22506 var outputStream = coerceOutputStream(output);
22507
22508 var bz = new Bunzip(inputStream, outputStream);
22509 while (true) {
22510 if ('eof' in inputStream && inputStream.eof()) break;
22511 if (bz._init_block()) {
22512 bz._read_bunzip();
22513 } else {
22514 var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
22515 if (targetStreamCRC !== bz.streamCRC) {
22516 _throw(Err.DATA_ERROR, "Bad stream CRC "+
22517 "(got "+bz.streamCRC.toString(16)+
22518 " expected "+targetStreamCRC.toString(16)+")");
22519 }
22520 if (multistream &&
22521 'eof' in inputStream &&
22522 !inputStream.eof()) {
22523 // note that start_bunzip will also resync the bit reader to next byte
22524 bz._start_bunzip(inputStream, outputStream);
22525 } else break;
22526 }
22527 }
22528 if ('getBuffer' in outputStream)
22529 return outputStream.getBuffer();
22530};
22531const decodeBlock = function(input, pos, output) {
22532 // make a stream from a buffer, if necessary
22533 var inputStream = coerceInputStream(input);
22534 var outputStream = coerceOutputStream(output);
22535 var bz = new Bunzip(inputStream, outputStream);
22536 bz.reader.seek(pos);
22537 /* Fill the decode buffer for the block */
22538 var moreBlocks = bz._get_next_block();
22539 if (moreBlocks) {
22540 /* Init the CRC for writing */
22541 bz.blockCRC = new crc32$1();
22542
22543 /* Zero this so the current byte from before the seek is not written */
22544 bz.writeCopies = 0;
22545
22546 /* Decompress the block and write to stdout */
22547 bz._read_bunzip();
22548 // XXX keep writing?
22549 }
22550 if ('getBuffer' in outputStream)
22551 return outputStream.getBuffer();
22552};
22553/* Reads bzip2 file from stream or buffer `input`, and invoke
22554 * `callback(position, size)` once for each bzip2 block,
22555 * where position gives the starting position (in *bits*)
22556 * and size gives uncompressed size of the block (in *bytes*). */
22557const table = function(input, callback, multistream) {
22558 // make a stream from a buffer, if necessary
22559 var inputStream = new stream();
22560 inputStream.delegate = coerceInputStream(input);
22561 inputStream.pos = 0;
22562 inputStream.readByte = function() {
22563 this.pos++;
22564 return this.delegate.readByte();
22565 };
22566 if (inputStream.delegate.eof) {
22567 inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
22568 }
22569 var outputStream = new stream();
22570 outputStream.pos = 0;
22571 outputStream.writeByte = function() { this.pos++; };
22572
22573 var bz = new Bunzip(inputStream, outputStream);
22574 var blockSize = bz.dbufSize;
22575 while (true) {
22576 if ('eof' in inputStream && inputStream.eof()) break;
22577
22578 var position = inputStream.pos*8 + bz.reader.bitOffset;
22579 if (bz.reader.hasByte) { position -= 8; }
22580
22581 if (bz._init_block()) {
22582 var start = outputStream.pos;
22583 bz._read_bunzip();
22584 callback(position, outputStream.pos - start);
22585 } else {
22586 bz.reader.read(32); // (but we ignore the crc)
22587 if (multistream &&
22588 'eof' in inputStream &&
22589 !inputStream.eof()) {
22590 // note that start_bunzip will also resync the bit reader to next byte
22591 bz._start_bunzip(inputStream, outputStream);
22592 console.assert(bz.dbufSize === blockSize,
22593 "shouldn't change block size within multistream file");
22594 } else break;
22595 }
22596 }
22597};
22598
22599var lib = {
22600 Bunzip,
22601 Stream: stream,
22602 Err,
22603 decode: decode$2,
22604 decodeBlock,
22605 table
22606};
22607var lib_4 = lib.decode;
22608
22609// GPG4Browsers - An OpenPGP implementation in javascript
22610
22611/**
22612 * Implementation of the Literal Data Packet (Tag 11)
22613 *
22614 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
22615 * A Literal Data packet contains the body of a message; data that is not to be
22616 * further interpreted.
22617 */
22618class LiteralDataPacket {
22619 static get tag() {
22620 return enums.packet.literalData;
22621 }
22622
22623 /**
22624 * @param {Date} date - The creation date of the literal package
22625 */
22626 constructor(date = new Date()) {
22627 this.format = enums.literal.utf8; // default format for literal data packets
22628 this.date = util.normalizeDate(date);
22629 this.text = null; // textual data representation
22630 this.data = null; // literal data representation
22631 this.filename = '';
22632 }
22633
22634 /**
22635 * Set the packet data to a javascript native string, end of line
22636 * will be normalized to \r\n and by default text is converted to UTF8
22637 * @param {String | ReadableStream<String>} text - Any native javascript string
22638 * @param {enums.literal} [format] - The format of the string of bytes
22639 */
22640 setText(text, format = enums.literal.utf8) {
22641 this.format = format;
22642 this.text = text;
22643 this.data = null;
22644 }
22645
22646 /**
22647 * Returns literal data packets as native JavaScript string
22648 * with normalized end of line to \n
22649 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22650 * @returns {String | ReadableStream<String>} Literal data as text.
22651 */
22652 getText(clone = false) {
22653 if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
22654 this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));
22655 }
22656 return this.text;
22657 }
22658
22659 /**
22660 * Set the packet data to value represented by the provided string of bytes.
22661 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
22662 * @param {enums.literal} format - The format of the string of bytes
22663 */
22664 setBytes(bytes, format) {
22665 this.format = format;
22666 this.data = bytes;
22667 this.text = null;
22668 }
22669
22670
22671 /**
22672 * Get the byte sequence representing the literal packet data
22673 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22674 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
22675 */
22676 getBytes(clone = false) {
22677 if (this.data === null) {
22678 // encode UTF8 and normalize EOL to \r\n
22679 this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));
22680 }
22681 if (clone) {
22682 return passiveClone(this.data);
22683 }
22684 return this.data;
22685 }
22686
22687
22688 /**
22689 * Sets the filename of the literal packet data
22690 * @param {String} filename - Any native javascript string
22691 */
22692 setFilename(filename) {
22693 this.filename = filename;
22694 }
22695
22696
22697 /**
22698 * Get the filename of the literal packet data
22699 * @returns {String} Filename.
22700 */
22701 getFilename() {
22702 return this.filename;
22703 }
22704
22705 /**
22706 * Parsing function for a literal data packet (tag 11).
22707 *
22708 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
22709 * @returns {Promise<LiteralDataPacket>} Object representation.
22710 * @async
22711 */
22712 async read(bytes) {
22713 await parse(bytes, async reader => {
22714 // - A one-octet field that describes how the data is formatted.
22715 const format = await reader.readByte(); // enums.literal
22716
22717 const filename_len = await reader.readByte();
22718 this.filename = util.decodeUTF8(await reader.readBytes(filename_len));
22719
22720 this.date = util.readDate(await reader.readBytes(4));
22721
22722 let data = reader.remainder();
22723 if (isArrayStream(data)) data = await readToEnd(data);
22724 this.setBytes(data, format);
22725 });
22726 }
22727
22728 /**
22729 * Creates a Uint8Array representation of the packet, excluding the data
22730 *
22731 * @returns {Uint8Array} Uint8Array representation of the packet.
22732 */
22733 writeHeader() {
22734 const filename = util.encodeUTF8(this.filename);
22735 const filename_length = new Uint8Array([filename.length]);
22736
22737 const format = new Uint8Array([this.format]);
22738 const date = util.writeDate(this.date);
22739
22740 return util.concatUint8Array([format, filename_length, filename, date]);
22741 }
22742
22743 /**
22744 * Creates a Uint8Array representation of the packet
22745 *
22746 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
22747 */
22748 write() {
22749 const header = this.writeHeader();
22750 const data = this.getBytes();
22751
22752 return util.concat([header, data]);
22753 }
22754}
22755
22756// GPG4Browsers - An OpenPGP implementation in javascript
22757
22758// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.
22759const verified = Symbol('verified');
22760
22761// GPG puts the Issuer and Signature subpackets in the unhashed area.
22762// Tampering with those invalidates the signature, so we still trust them and parse them.
22763// All other unhashed subpackets are ignored.
22764const allowedUnhashedSubpackets = new Set([
22765 enums.signatureSubpacket.issuer,
22766 enums.signatureSubpacket.issuerFingerprint,
22767 enums.signatureSubpacket.embeddedSignature
22768]);
22769
22770/**
22771 * Implementation of the Signature Packet (Tag 2)
22772 *
22773 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
22774 * A Signature packet describes a binding between some public key and
22775 * some data. The most common signatures are a signature of a file or a
22776 * block of text, and a signature that is a certification of a User ID.
22777 */
22778class SignaturePacket {
22779 static get tag() {
22780 return enums.packet.signature;
22781 }
22782
22783 constructor() {
22784 this.version = null;
22785 /** @type {enums.signature} */
22786 this.signatureType = null;
22787 /** @type {enums.hash} */
22788 this.hashAlgorithm = null;
22789 /** @type {enums.publicKey} */
22790 this.publicKeyAlgorithm = null;
22791
22792 this.signatureData = null;
22793 this.unhashedSubpackets = [];
22794 this.signedHashValue = null;
22795
22796 this.created = null;
22797 this.signatureExpirationTime = null;
22798 this.signatureNeverExpires = true;
22799 this.exportable = null;
22800 this.trustLevel = null;
22801 this.trustAmount = null;
22802 this.regularExpression = null;
22803 this.revocable = null;
22804 this.keyExpirationTime = null;
22805 this.keyNeverExpires = null;
22806 this.preferredSymmetricAlgorithms = null;
22807 this.revocationKeyClass = null;
22808 this.revocationKeyAlgorithm = null;
22809 this.revocationKeyFingerprint = null;
22810 this.issuerKeyID = new KeyID();
22811 this.rawNotations = [];
22812 this.notations = {};
22813 this.preferredHashAlgorithms = null;
22814 this.preferredCompressionAlgorithms = null;
22815 this.keyServerPreferences = null;
22816 this.preferredKeyServer = null;
22817 this.isPrimaryUserID = null;
22818 this.policyURI = null;
22819 this.keyFlags = null;
22820 this.signersUserID = null;
22821 this.reasonForRevocationFlag = null;
22822 this.reasonForRevocationString = null;
22823 this.features = null;
22824 this.signatureTargetPublicKeyAlgorithm = null;
22825 this.signatureTargetHashAlgorithm = null;
22826 this.signatureTargetHash = null;
22827 this.embeddedSignature = null;
22828 this.issuerKeyVersion = null;
22829 this.issuerFingerprint = null;
22830 this.preferredAEADAlgorithms = null;
22831
22832 this.revoked = null;
22833 this[verified] = null;
22834 }
22835
22836 /**
22837 * parsing function for a signature packet (tag 2).
22838 * @param {String} bytes - Payload of a tag 2 packet
22839 * @returns {SignaturePacket} Object representation.
22840 */
22841 read(bytes) {
22842 let i = 0;
22843 this.version = bytes[i++];
22844
22845 if (this.version !== 4 && this.version !== 5) {
22846 throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);
22847 }
22848
22849 this.signatureType = bytes[i++];
22850 this.publicKeyAlgorithm = bytes[i++];
22851 this.hashAlgorithm = bytes[i++];
22852
22853 // hashed subpackets
22854 i += this.readSubPackets(bytes.subarray(i, bytes.length), true);
22855 if (!this.created) {
22856 throw new Error('Missing signature creation time subpacket.');
22857 }
22858
22859 // A V4 signature hashes the packet body
22860 // starting from its first field, the version number, through the end
22861 // of the hashed subpacket data. Thus, the fields hashed are the
22862 // signature version, the signature type, the public-key algorithm, the
22863 // hash algorithm, the hashed subpacket length, and the hashed
22864 // subpacket body.
22865 this.signatureData = bytes.subarray(0, i);
22866
22867 // unhashed subpackets
22868 i += this.readSubPackets(bytes.subarray(i, bytes.length), false);
22869
22870 // Two-octet field holding left 16 bits of signed hash value.
22871 this.signedHashValue = bytes.subarray(i, i + 2);
22872 i += 2;
22873
22874 this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));
22875 }
22876
22877 /**
22878 * @returns {Uint8Array | ReadableStream<Uint8Array>}
22879 */
22880 writeParams() {
22881 if (this.params instanceof Promise) {
22882 return fromAsync(
22883 async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params)
22884 );
22885 }
22886 return mod.serializeParams(this.publicKeyAlgorithm, this.params);
22887 }
22888
22889 write() {
22890 const arr = [];
22891 arr.push(this.signatureData);
22892 arr.push(this.writeUnhashedSubPackets());
22893 arr.push(this.signedHashValue);
22894 arr.push(this.writeParams());
22895 return util.concat(arr);
22896 }
22897
22898 /**
22899 * Signs provided data. This needs to be done prior to serialization.
22900 * @param {SecretKeyPacket} key - Private key used to sign the message.
22901 * @param {Object} data - Contains packets to be signed.
22902 * @param {Date} [date] - The signature creation time.
22903 * @param {Boolean} [detached] - Whether to create a detached signature
22904 * @throws {Error} if signing failed
22905 * @async
22906 */
22907 async sign(key, data, date = new Date(), detached = false) {
22908 if (key.version === 5) {
22909 this.version = 5;
22910 } else {
22911 this.version = 4;
22912 }
22913 const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];
22914
22915 this.created = util.normalizeDate(date);
22916 this.issuerKeyVersion = key.version;
22917 this.issuerFingerprint = key.getFingerprintBytes();
22918 this.issuerKeyID = key.getKeyID();
22919
22920 // Add hashed subpackets
22921 arr.push(this.writeHashedSubPackets());
22922
22923 this.signatureData = util.concat(arr);
22924
22925 const toHash = this.toHash(this.signatureType, data, detached);
22926 const hash = await this.hash(this.signatureType, data, toHash, detached);
22927
22928 this.signedHashValue = slice(clone(hash), 0, 2);
22929 const signed = async () => mod.signature.sign(
22930 this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash)
22931 );
22932 if (util.isStream(hash)) {
22933 this.params = signed();
22934 } else {
22935 this.params = await signed();
22936
22937 // Store the fact that this signature is valid, e.g. for when we call `await
22938 // getLatestValidSignature(this.revocationSignatures, key, data)` later.
22939 // Note that this only holds up if the key and data passed to verify are the
22940 // same as the ones passed to sign.
22941 this[verified] = true;
22942 }
22943 }
22944
22945 /**
22946 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
22947 * @returns {Uint8Array} Subpacket data.
22948 */
22949 writeHashedSubPackets() {
22950 const sub = enums.signatureSubpacket;
22951 const arr = [];
22952 let bytes;
22953 if (this.created === null) {
22954 throw new Error('Missing signature creation time');
22955 }
22956 arr.push(writeSubPacket(sub.signatureCreationTime, util.writeDate(this.created)));
22957 if (this.signatureExpirationTime !== null) {
22958 arr.push(writeSubPacket(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4)));
22959 }
22960 if (this.exportable !== null) {
22961 arr.push(writeSubPacket(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0])));
22962 }
22963 if (this.trustLevel !== null) {
22964 bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
22965 arr.push(writeSubPacket(sub.trustSignature, bytes));
22966 }
22967 if (this.regularExpression !== null) {
22968 arr.push(writeSubPacket(sub.regularExpression, this.regularExpression));
22969 }
22970 if (this.revocable !== null) {
22971 arr.push(writeSubPacket(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
22972 }
22973 if (this.keyExpirationTime !== null) {
22974 arr.push(writeSubPacket(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4)));
22975 }
22976 if (this.preferredSymmetricAlgorithms !== null) {
22977 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));
22978 arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, bytes));
22979 }
22980 if (this.revocationKeyClass !== null) {
22981 bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
22982 bytes = util.concat([bytes, this.revocationKeyFingerprint]);
22983 arr.push(writeSubPacket(sub.revocationKey, bytes));
22984 }
22985 this.rawNotations.forEach(([{ name, value, humanReadable }]) => {
22986 bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
22987 // 2 octets of name length
22988 bytes.push(util.writeNumber(name.length, 2));
22989 // 2 octets of value length
22990 bytes.push(util.writeNumber(value.length, 2));
22991 bytes.push(util.stringToUint8Array(name));
22992 bytes.push(value);
22993 bytes = util.concat(bytes);
22994 arr.push(writeSubPacket(sub.notationData, bytes));
22995 });
22996 if (this.preferredHashAlgorithms !== null) {
22997 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));
22998 arr.push(writeSubPacket(sub.preferredHashAlgorithms, bytes));
22999 }
23000 if (this.preferredCompressionAlgorithms !== null) {
23001 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));
23002 arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, bytes));
23003 }
23004 if (this.keyServerPreferences !== null) {
23005 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));
23006 arr.push(writeSubPacket(sub.keyServerPreferences, bytes));
23007 }
23008 if (this.preferredKeyServer !== null) {
23009 arr.push(writeSubPacket(sub.preferredKeyServer, util.stringToUint8Array(this.preferredKeyServer)));
23010 }
23011 if (this.isPrimaryUserID !== null) {
23012 arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
23013 }
23014 if (this.policyURI !== null) {
23015 arr.push(writeSubPacket(sub.policyURI, util.stringToUint8Array(this.policyURI)));
23016 }
23017 if (this.keyFlags !== null) {
23018 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));
23019 arr.push(writeSubPacket(sub.keyFlags, bytes));
23020 }
23021 if (this.signersUserID !== null) {
23022 arr.push(writeSubPacket(sub.signersUserID, util.stringToUint8Array(this.signersUserID)));
23023 }
23024 if (this.reasonForRevocationFlag !== null) {
23025 bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
23026 arr.push(writeSubPacket(sub.reasonForRevocation, bytes));
23027 }
23028 if (this.features !== null) {
23029 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));
23030 arr.push(writeSubPacket(sub.features, bytes));
23031 }
23032 if (this.signatureTargetPublicKeyAlgorithm !== null) {
23033 bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
23034 bytes.push(util.stringToUint8Array(this.signatureTargetHash));
23035 bytes = util.concat(bytes);
23036 arr.push(writeSubPacket(sub.signatureTarget, bytes));
23037 }
23038 if (this.preferredAEADAlgorithms !== null) {
23039 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));
23040 arr.push(writeSubPacket(sub.preferredAEADAlgorithms, bytes));
23041 }
23042
23043 const result = util.concat(arr);
23044 const length = util.writeNumber(result.length, 2);
23045
23046 return util.concat([length, result]);
23047 }
23048
23049 /**
23050 * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets
23051 * @returns {Uint8Array} Subpacket data.
23052 */
23053 writeUnhashedSubPackets() {
23054 const sub = enums.signatureSubpacket;
23055 const arr = [];
23056 let bytes;
23057 if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {
23058 // If the version of [the] key is greater than 4, this subpacket
23059 // MUST NOT be included in the signature.
23060 arr.push(writeSubPacket(sub.issuer, this.issuerKeyID.write()));
23061 }
23062 if (this.embeddedSignature !== null) {
23063 arr.push(writeSubPacket(sub.embeddedSignature, this.embeddedSignature.write()));
23064 }
23065 if (this.issuerFingerprint !== null) {
23066 bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
23067 bytes = util.concat(bytes);
23068 arr.push(writeSubPacket(sub.issuerFingerprint, bytes));
23069 }
23070 this.unhashedSubpackets.forEach(data => {
23071 arr.push(writeSimpleLength(data.length));
23072 arr.push(data);
23073 });
23074
23075 const result = util.concat(arr);
23076 const length = util.writeNumber(result.length, 2);
23077
23078 return util.concat([length, result]);
23079 }
23080
23081 // V4 signature sub packets
23082 readSubPacket(bytes, hashed = true) {
23083 let mypos = 0;
23084
23085 // The leftmost bit denotes a "critical" packet
23086 const critical = bytes[mypos] & 0x80;
23087 const type = bytes[mypos] & 0x7F;
23088
23089 if (!hashed && !allowedUnhashedSubpackets.has(type)) {
23090 this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
23091 return;
23092 }
23093
23094 mypos++;
23095
23096 // subpacket type
23097 switch (type) {
23098 case enums.signatureSubpacket.signatureCreationTime:
23099 // Signature Creation Time
23100 this.created = util.readDate(bytes.subarray(mypos, bytes.length));
23101 break;
23102 case enums.signatureSubpacket.signatureExpirationTime: {
23103 // Signature Expiration Time in seconds
23104 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23105
23106 this.signatureNeverExpires = seconds === 0;
23107 this.signatureExpirationTime = seconds;
23108
23109 break;
23110 }
23111 case enums.signatureSubpacket.exportableCertification:
23112 // Exportable Certification
23113 this.exportable = bytes[mypos++] === 1;
23114 break;
23115 case enums.signatureSubpacket.trustSignature:
23116 // Trust Signature
23117 this.trustLevel = bytes[mypos++];
23118 this.trustAmount = bytes[mypos++];
23119 break;
23120 case enums.signatureSubpacket.regularExpression:
23121 // Regular Expression
23122 this.regularExpression = bytes[mypos];
23123 break;
23124 case enums.signatureSubpacket.revocable:
23125 // Revocable
23126 this.revocable = bytes[mypos++] === 1;
23127 break;
23128 case enums.signatureSubpacket.keyExpirationTime: {
23129 // Key Expiration Time in seconds
23130 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23131
23132 this.keyExpirationTime = seconds;
23133 this.keyNeverExpires = seconds === 0;
23134
23135 break;
23136 }
23137 case enums.signatureSubpacket.preferredSymmetricAlgorithms:
23138 // Preferred Symmetric Algorithms
23139 this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23140 break;
23141 case enums.signatureSubpacket.revocationKey:
23142 // Revocation Key
23143 // (1 octet of class, 1 octet of public-key algorithm ID, 20
23144 // octets of
23145 // fingerprint)
23146 this.revocationKeyClass = bytes[mypos++];
23147 this.revocationKeyAlgorithm = bytes[mypos++];
23148 this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
23149 break;
23150
23151 case enums.signatureSubpacket.issuer:
23152 // Issuer
23153 this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));
23154 break;
23155
23156 case enums.signatureSubpacket.notationData: {
23157 // Notation Data
23158 const humanReadable = !!(bytes[mypos] & 0x80);
23159
23160 // We extract key/value tuple from the byte stream.
23161 mypos += 4;
23162 const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
23163 mypos += 2;
23164 const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
23165 mypos += 2;
23166
23167 const name = util.uint8ArrayToString(bytes.subarray(mypos, mypos + m));
23168 const value = bytes.subarray(mypos + m, mypos + m + n);
23169
23170 this.rawNotations.push({ name, humanReadable, value, critical });
23171
23172 if (humanReadable) {
23173 this.notations[name] = util.uint8ArrayToString(value);
23174 }
23175 break;
23176 }
23177 case enums.signatureSubpacket.preferredHashAlgorithms:
23178 // Preferred Hash Algorithms
23179 this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23180 break;
23181 case enums.signatureSubpacket.preferredCompressionAlgorithms:
23182 // Preferred Compression Algorithms
23183 this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23184 break;
23185 case enums.signatureSubpacket.keyServerPreferences:
23186 // Key Server Preferences
23187 this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];
23188 break;
23189 case enums.signatureSubpacket.preferredKeyServer:
23190 // Preferred Key Server
23191 this.preferredKeyServer = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23192 break;
23193 case enums.signatureSubpacket.primaryUserID:
23194 // Primary User ID
23195 this.isPrimaryUserID = bytes[mypos++] !== 0;
23196 break;
23197 case enums.signatureSubpacket.policyURI:
23198 // Policy URI
23199 this.policyURI = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23200 break;
23201 case enums.signatureSubpacket.keyFlags:
23202 // Key Flags
23203 this.keyFlags = [...bytes.subarray(mypos, bytes.length)];
23204 break;
23205 case enums.signatureSubpacket.signersUserID:
23206 // Signer's User ID
23207 this.signersUserID = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23208 break;
23209 case enums.signatureSubpacket.reasonForRevocation:
23210 // Reason for Revocation
23211 this.reasonForRevocationFlag = bytes[mypos++];
23212 this.reasonForRevocationString = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23213 break;
23214 case enums.signatureSubpacket.features:
23215 // Features
23216 this.features = [...bytes.subarray(mypos, bytes.length)];
23217 break;
23218 case enums.signatureSubpacket.signatureTarget: {
23219 // Signature Target
23220 // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
23221 this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
23222 this.signatureTargetHashAlgorithm = bytes[mypos++];
23223
23224 const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm);
23225
23226 this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));
23227 break;
23228 }
23229 case enums.signatureSubpacket.embeddedSignature:
23230 // Embedded Signature
23231 this.embeddedSignature = new SignaturePacket();
23232 this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
23233 break;
23234 case enums.signatureSubpacket.issuerFingerprint:
23235 // Issuer Fingerprint
23236 this.issuerKeyVersion = bytes[mypos++];
23237 this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
23238 if (this.issuerKeyVersion === 5) {
23239 this.issuerKeyID.read(this.issuerFingerprint);
23240 } else {
23241 this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));
23242 }
23243 break;
23244 case enums.signatureSubpacket.preferredAEADAlgorithms:
23245 // Preferred AEAD Algorithms
23246 this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23247 break;
23248 default: {
23249 const err = new Error(`Unknown signature subpacket type ${type}`);
23250 if (critical) {
23251 throw err;
23252 } else {
23253 util.printDebug(err);
23254 }
23255 }
23256 }
23257 }
23258
23259 readSubPackets(bytes, trusted = true, config) {
23260 // Two-octet scalar octet count for following subpacket data.
23261 const subpacketLength = util.readNumber(bytes.subarray(0, 2));
23262
23263 let i = 2;
23264
23265 // subpacket data set (zero or more subpackets)
23266 while (i < 2 + subpacketLength) {
23267 const len = readSimpleLength(bytes.subarray(i, bytes.length));
23268 i += len.offset;
23269
23270 this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);
23271
23272 i += len.len;
23273 }
23274
23275 return i;
23276 }
23277
23278 // Produces data to produce signature on
23279 toSign(type, data) {
23280 const t = enums.signature;
23281
23282 switch (type) {
23283 case t.binary:
23284 if (data.text !== null) {
23285 return util.encodeUTF8(data.getText(true));
23286 }
23287 return data.getBytes(true);
23288
23289 case t.text: {
23290 const bytes = data.getBytes(true);
23291 // normalize EOL to \r\n
23292 return util.canonicalizeEOL(bytes);
23293 }
23294 case t.standalone:
23295 return new Uint8Array(0);
23296
23297 case t.certGeneric:
23298 case t.certPersona:
23299 case t.certCasual:
23300 case t.certPositive:
23301 case t.certRevocation: {
23302 let packet;
23303 let tag;
23304
23305 if (data.userID) {
23306 tag = 0xB4;
23307 packet = data.userID;
23308 } else if (data.userAttribute) {
23309 tag = 0xD1;
23310 packet = data.userAttribute;
23311 } else {
23312 throw new Error('Either a userID or userAttribute packet needs to be ' +
23313 'supplied for certification.');
23314 }
23315
23316 const bytes = packet.write();
23317
23318 return util.concat([this.toSign(t.key, data),
23319 new Uint8Array([tag]),
23320 util.writeNumber(bytes.length, 4),
23321 bytes]);
23322 }
23323 case t.subkeyBinding:
23324 case t.subkeyRevocation:
23325 case t.keyBinding:
23326 return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
23327 key: data.bind
23328 })]);
23329
23330 case t.key:
23331 if (data.key === undefined) {
23332 throw new Error('Key packet is required for this signature.');
23333 }
23334 return data.key.writeForHash(this.version);
23335
23336 case t.keyRevocation:
23337 return this.toSign(t.key, data);
23338 case t.timestamp:
23339 return new Uint8Array(0);
23340 case t.thirdParty:
23341 throw new Error('Not implemented');
23342 default:
23343 throw new Error('Unknown signature type.');
23344 }
23345 }
23346
23347 calculateTrailer(data, detached) {
23348 let length = 0;
23349 return transform(clone(this.signatureData), value => {
23350 length += value.length;
23351 }, () => {
23352 const arr = [];
23353 if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
23354 if (detached) {
23355 arr.push(new Uint8Array(6));
23356 } else {
23357 arr.push(data.writeHeader());
23358 }
23359 }
23360 arr.push(new Uint8Array([this.version, 0xFF]));
23361 if (this.version === 5) {
23362 arr.push(new Uint8Array(4));
23363 }
23364 arr.push(util.writeNumber(length, 4));
23365 // For v5, this should really be writeNumber(length, 8) rather than the
23366 // hardcoded 4 zero bytes above
23367 return util.concat(arr);
23368 });
23369 }
23370
23371 toHash(signatureType, data, detached = false) {
23372 const bytes = this.toSign(signatureType, data);
23373
23374 return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
23375 }
23376
23377 async hash(signatureType, data, toHash, detached = false) {
23378 if (!toHash) toHash = this.toHash(signatureType, data, detached);
23379 return mod.hash.digest(this.hashAlgorithm, toHash);
23380 }
23381
23382 /**
23383 * verifies the signature packet. Note: not all signature types are implemented
23384 * @param {PublicSubkeyPacket|PublicKeyPacket|
23385 * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature
23386 * @param {module:enums.signature} signatureType - Expected signature type
23387 * @param {Uint8Array|Object} data - Data which on the signature applies
23388 * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration
23389 * @param {Boolean} [detached] - Whether to verify a detached signature
23390 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23391 * @throws {Error} if signature validation failed
23392 * @async
23393 */
23394 async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {
23395 if (!this.issuerKeyID.equals(key.getKeyID())) {
23396 throw new Error('Signature was not issued by the given public key');
23397 }
23398 if (this.publicKeyAlgorithm !== key.algorithm) {
23399 throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
23400 }
23401
23402 const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;
23403 // Cryptographic validity is cached after one successful verification.
23404 // However, for message signatures, we always re-verify, since the passed `data` can change
23405 const skipVerify = this[verified] && !isMessageSignature;
23406 if (!skipVerify) {
23407 let toHash;
23408 let hash;
23409 if (this.hashed) {
23410 hash = await this.hashed;
23411 } else {
23412 toHash = this.toHash(signatureType, data, detached);
23413 hash = await this.hash(signatureType, data, toHash);
23414 }
23415 hash = await readToEnd(hash);
23416 if (this.signedHashValue[0] !== hash[0] ||
23417 this.signedHashValue[1] !== hash[1]) {
23418 throw new Error('Signed digest did not match');
23419 }
23420
23421 this.params = await this.params;
23422
23423 this[verified] = await mod.signature.verify(
23424 this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,
23425 toHash, hash
23426 );
23427
23428 if (!this[verified]) {
23429 throw new Error('Signature verification failed');
23430 }
23431 }
23432
23433 const normDate = util.normalizeDate(date);
23434 if (normDate && this.created > normDate) {
23435 throw new Error('Signature creation time is in the future');
23436 }
23437 if (normDate && normDate >= this.getExpirationTime()) {
23438 throw new Error('Signature is expired');
23439 }
23440 if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {
23441 throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23442 }
23443 if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&
23444 [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
23445 throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23446 }
23447 this.rawNotations.forEach(({ name, critical }) => {
23448 if (critical && (config.knownNotations.indexOf(name) < 0)) {
23449 throw new Error(`Unknown critical notation: ${name}`);
23450 }
23451 });
23452 if (this.revocationKeyClass !== null) {
23453 throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
23454 }
23455 }
23456
23457 /**
23458 * Verifies signature expiration date
23459 * @param {Date} [date] - Use the given date for verification instead of the current time
23460 * @returns {Boolean} True if expired.
23461 */
23462 isExpired(date = new Date()) {
23463 const normDate = util.normalizeDate(date);
23464 if (normDate !== null) {
23465 return !(this.created <= normDate && normDate < this.getExpirationTime());
23466 }
23467 return false;
23468 }
23469
23470 /**
23471 * Returns the expiration time of the signature or Infinity if signature does not expire
23472 * @returns {Date | Infinity} Expiration time.
23473 */
23474 getExpirationTime() {
23475 return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);
23476 }
23477}
23478
23479/**
23480 * Creates a string representation of a sub signature packet
23481 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
23482 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
23483 * @param {Integer} type - Subpacket signature type.
23484 * @param {String} data - Data to be included
23485 * @returns {String} A string-representation of a sub signature packet.
23486 * @private
23487 */
23488function writeSubPacket(type, data) {
23489 const arr = [];
23490 arr.push(writeSimpleLength(data.length + 1));
23491 arr.push(new Uint8Array([type]));
23492 arr.push(data);
23493 return util.concat(arr);
23494}
23495
23496// GPG4Browsers - An OpenPGP implementation in javascript
23497
23498const VERSION = 3;
23499
23500/**
23501 * Implementation of the One-Pass Signature Packets (Tag 4)
23502 *
23503 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
23504 * The One-Pass Signature packet precedes the signed data and contains
23505 * enough information to allow the receiver to begin calculating any
23506 * hashes needed to verify the signature. It allows the Signature
23507 * packet to be placed at the end of the message, so that the signer
23508 * can compute the entire signed message in one pass.
23509 */
23510class OnePassSignaturePacket {
23511 static get tag() {
23512 return enums.packet.onePassSignature;
23513 }
23514
23515 constructor() {
23516 /** A one-octet version number. The current version is 3. */
23517 this.version = null;
23518 /**
23519 * A one-octet signature type.
23520 * Signature types are described in
23521 * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
23522 * @type {enums.signature}
23523
23524 */
23525 this.signatureType = null;
23526 /**
23527 * A one-octet number describing the hash algorithm used.
23528 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
23529 * @type {enums.hash}
23530 */
23531 this.hashAlgorithm = null;
23532 /**
23533 * A one-octet number describing the public-key algorithm used.
23534 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
23535 * @type {enums.publicKey}
23536 */
23537 this.publicKeyAlgorithm = null;
23538 /** An eight-octet number holding the Key ID of the signing key. */
23539 this.issuerKeyID = null;
23540 /**
23541 * A one-octet number holding a flag showing whether the signature is nested.
23542 * A zero value indicates that the next packet is another One-Pass Signature packet
23543 * that describes another signature to be applied to the same message data.
23544 */
23545 this.flags = null;
23546 }
23547
23548 /**
23549 * parsing function for a one-pass signature packet (tag 4).
23550 * @param {Uint8Array} bytes - Payload of a tag 4 packet
23551 * @returns {OnePassSignaturePacket} Object representation.
23552 */
23553 read(bytes) {
23554 let mypos = 0;
23555 // A one-octet version number. The current version is 3.
23556 this.version = bytes[mypos++];
23557 if (this.version !== VERSION) {
23558 throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);
23559 }
23560
23561 // A one-octet signature type. Signature types are described in
23562 // Section 5.2.1.
23563 this.signatureType = bytes[mypos++];
23564
23565 // A one-octet number describing the hash algorithm used.
23566 this.hashAlgorithm = bytes[mypos++];
23567
23568 // A one-octet number describing the public-key algorithm used.
23569 this.publicKeyAlgorithm = bytes[mypos++];
23570
23571 // An eight-octet number holding the Key ID of the signing key.
23572 this.issuerKeyID = new KeyID();
23573 this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));
23574 mypos += 8;
23575
23576 // A one-octet number holding a flag showing whether the signature
23577 // is nested. A zero value indicates that the next packet is
23578 // another One-Pass Signature packet that describes another
23579 // signature to be applied to the same message data.
23580 this.flags = bytes[mypos++];
23581 return this;
23582 }
23583
23584 /**
23585 * creates a string representation of a one-pass signature packet
23586 * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
23587 */
23588 write() {
23589 const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);
23590
23591 const end = new Uint8Array([this.flags]);
23592
23593 return util.concatUint8Array([start, this.issuerKeyID.write(), end]);
23594 }
23595
23596 calculateTrailer(...args) {
23597 return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
23598 }
23599
23600 async verify() {
23601 const correspondingSig = await this.correspondingSig;
23602 if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {
23603 throw new Error('Corresponding signature packet missing');
23604 }
23605 if (
23606 correspondingSig.signatureType !== this.signatureType ||
23607 correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
23608 correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
23609 !correspondingSig.issuerKeyID.equals(this.issuerKeyID)
23610 ) {
23611 throw new Error('Corresponding signature packet does not match one-pass signature packet');
23612 }
23613 correspondingSig.hashed = this.hashed;
23614 return correspondingSig.verify.apply(correspondingSig, arguments);
23615 }
23616}
23617
23618OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
23619OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
23620OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;
23621
23622/**
23623 * Instantiate a new packet given its tag
23624 * @function newPacketFromTag
23625 * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}
23626 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23627 * @returns {Object} New packet object with type based on tag
23628 * @throws {Error|UnsupportedError} for disallowed or unknown packets
23629 */
23630function newPacketFromTag(tag, allowedPackets) {
23631 if (!allowedPackets[tag]) {
23632 // distinguish between disallowed packets and unknown ones
23633 let packetType;
23634 try {
23635 packetType = enums.read(enums.packet, tag);
23636 } catch (e) {
23637 throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);
23638 }
23639 throw new Error(`Packet not allowed in this context: ${packetType}`);
23640 }
23641 return new allowedPackets[tag]();
23642}
23643
23644/**
23645 * This class represents a list of openpgp packets.
23646 * Take care when iterating over it - the packets themselves
23647 * are stored as numerical indices.
23648 * @extends Array
23649 */
23650class PacketList extends Array {
23651 /**
23652 * Parses the given binary data and returns a list of packets.
23653 * Equivalent to calling `read` on an empty PacketList instance.
23654 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23655 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23656 * @param {Object} [config] - full configuration, defaults to openpgp.config
23657 * @returns {PacketList} parsed list of packets
23658 * @throws on parsing errors
23659 * @async
23660 */
23661 static async fromBinary(bytes, allowedPackets, config = defaultConfig) {
23662 const packets = new PacketList();
23663 await packets.read(bytes, allowedPackets, config);
23664 return packets;
23665 }
23666
23667 /**
23668 * Reads a stream of binary data and interprets it as a list of packets.
23669 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23670 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23671 * @param {Object} [config] - full configuration, defaults to openpgp.config
23672 * @throws on parsing errors
23673 * @async
23674 */
23675 async read(bytes, allowedPackets, config = defaultConfig) {
23676 this.stream = transformPair(bytes, async (readable, writable) => {
23677 const writer = getWriter(writable);
23678 try {
23679 while (true) {
23680 await writer.ready;
23681 const done = await readPackets(readable, async parsed => {
23682 try {
23683 if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {
23684 // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:
23685 // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145
23686 // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10
23687 return;
23688 }
23689 const packet = newPacketFromTag(parsed.tag, allowedPackets);
23690 packet.packets = new PacketList();
23691 packet.fromStream = util.isStream(parsed.packet);
23692 await packet.read(parsed.packet, config);
23693 await writer.write(packet);
23694 } catch (e) {
23695 const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;
23696 const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);
23697 if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {
23698 // The packets that support streaming are the ones that contain message data.
23699 // Those are also the ones we want to be more strict about and throw on parse errors
23700 // (since we likely cannot process the message without these packets anyway).
23701 await writer.abort(e);
23702 } else {
23703 const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);
23704 await writer.write(unparsedPacket);
23705 }
23706 util.printDebugError(e);
23707 }
23708 });
23709 if (done) {
23710 await writer.ready;
23711 await writer.close();
23712 return;
23713 }
23714 }
23715 } catch (e) {
23716 await writer.abort(e);
23717 }
23718 });
23719
23720 // Wait until first few packets have been read
23721 const reader = getReader(this.stream);
23722 while (true) {
23723 const { done, value } = await reader.read();
23724 if (!done) {
23725 this.push(value);
23726 } else {
23727 this.stream = null;
23728 }
23729 if (done || supportsStreaming(value.constructor.tag)) {
23730 break;
23731 }
23732 }
23733 reader.releaseLock();
23734 }
23735
23736 /**
23737 * Creates a binary representation of openpgp objects contained within the
23738 * class instance.
23739 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
23740 */
23741 write() {
23742 const arr = [];
23743
23744 for (let i = 0; i < this.length; i++) {
23745 const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;
23746 const packetbytes = this[i].write();
23747 if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {
23748 let buffer = [];
23749 let bufferLength = 0;
23750 const minLength = 512;
23751 arr.push(writeTag(tag));
23752 arr.push(transform(packetbytes, value => {
23753 buffer.push(value);
23754 bufferLength += value.length;
23755 if (bufferLength >= minLength) {
23756 const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
23757 const chunkSize = 2 ** powerOf2;
23758 const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
23759 buffer = [bufferConcat.subarray(1 + chunkSize)];
23760 bufferLength = buffer[0].length;
23761 return bufferConcat.subarray(0, 1 + chunkSize);
23762 }
23763 }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
23764 } else {
23765 if (util.isStream(packetbytes)) {
23766 let length = 0;
23767 arr.push(transform(clone(packetbytes), value => {
23768 length += value.length;
23769 }, () => writeHeader(tag, length)));
23770 } else {
23771 arr.push(writeHeader(tag, packetbytes.length));
23772 }
23773 arr.push(packetbytes);
23774 }
23775 }
23776
23777 return util.concat(arr);
23778 }
23779
23780 /**
23781 * Creates a new PacketList with all packets matching the given tag(s)
23782 * @param {...module:enums.packet} tags - packet tags to look for
23783 * @returns {PacketList}
23784 */
23785 filterByTag(...tags) {
23786 const filtered = new PacketList();
23787
23788 const handle = tag => packetType => tag === packetType;
23789
23790 for (let i = 0; i < this.length; i++) {
23791 if (tags.some(handle(this[i].constructor.tag))) {
23792 filtered.push(this[i]);
23793 }
23794 }
23795
23796 return filtered;
23797 }
23798
23799 /**
23800 * Traverses packet list and returns first packet with matching tag
23801 * @param {module:enums.packet} tag - The packet tag
23802 * @returns {Packet|undefined}
23803 */
23804 findPacket(tag) {
23805 return this.find(packet => packet.constructor.tag === tag);
23806 }
23807
23808 /**
23809 * Find indices of packets with the given tag(s)
23810 * @param {...module:enums.packet} tags - packet tags to look for
23811 * @returns {Integer[]} packet indices
23812 */
23813 indexOfTag(...tags) {
23814 const tagIndex = [];
23815 const that = this;
23816
23817 const handle = tag => packetType => tag === packetType;
23818
23819 for (let i = 0; i < this.length; i++) {
23820 if (tags.some(handle(that[i].constructor.tag))) {
23821 tagIndex.push(i);
23822 }
23823 }
23824 return tagIndex;
23825 }
23826}
23827
23828// GPG4Browsers - An OpenPGP implementation in javascript
23829
23830// A Compressed Data packet can contain the following packet types
23831const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([
23832 LiteralDataPacket,
23833 OnePassSignaturePacket,
23834 SignaturePacket
23835]);
23836
23837/**
23838 * Implementation of the Compressed Data Packet (Tag 8)
23839 *
23840 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
23841 * The Compressed Data packet contains compressed data. Typically,
23842 * this packet is found as the contents of an encrypted packet, or following
23843 * a Signature or One-Pass Signature packet, and contains a literal data packet.
23844 */
23845class CompressedDataPacket {
23846 static get tag() {
23847 return enums.packet.compressedData;
23848 }
23849
23850 /**
23851 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23852 */
23853 constructor(config = defaultConfig) {
23854 /**
23855 * List of packets
23856 * @type {PacketList}
23857 */
23858 this.packets = null;
23859 /**
23860 * Compression algorithm
23861 * @type {enums.compression}
23862 */
23863 this.algorithm = config.preferredCompressionAlgorithm;
23864
23865 /**
23866 * Compressed packet data
23867 * @type {Uint8Array | ReadableStream<Uint8Array>}
23868 */
23869 this.compressed = null;
23870
23871 /**
23872 * zip/zlib compression level, between 1 and 9
23873 */
23874 this.deflateLevel = config.deflateLevel;
23875 }
23876
23877 /**
23878 * Parsing function for the packet.
23879 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
23880 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23881 */
23882 async read(bytes, config = defaultConfig) {
23883 await parse(bytes, async reader => {
23884
23885 // One octet that gives the algorithm used to compress the packet.
23886 this.algorithm = await reader.readByte();
23887
23888 // Compressed data, which makes up the remainder of the packet.
23889 this.compressed = reader.remainder();
23890
23891 await this.decompress(config);
23892 });
23893 }
23894
23895
23896 /**
23897 * Return the compressed packet.
23898 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
23899 */
23900 write() {
23901 if (this.compressed === null) {
23902 this.compress();
23903 }
23904
23905 return util.concat([new Uint8Array([this.algorithm]), this.compressed]);
23906 }
23907
23908
23909 /**
23910 * Decompression method for decompressing the compressed data
23911 * read by read_packet
23912 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23913 */
23914 async decompress(config = defaultConfig) {
23915 const compressionName = enums.read(enums.compression, this.algorithm);
23916 const decompressionFn = decompress_fns[compressionName];
23917 if (!decompressionFn) {
23918 throw new Error(`${compressionName} decompression not supported`);
23919 }
23920
23921 this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);
23922 }
23923
23924 /**
23925 * Compress the packet data (member decompressedData)
23926 */
23927 compress() {
23928 const compressionName = enums.read(enums.compression, this.algorithm);
23929 const compressionFn = compress_fns[compressionName];
23930 if (!compressionFn) {
23931 throw new Error(`${compressionName} compression not supported`);
23932 }
23933
23934 this.compressed = compressionFn(this.packets.write(), this.deflateLevel);
23935 }
23936}
23937
23938//////////////////////////
23939// //
23940// Helper functions //
23941// //
23942//////////////////////////
23943
23944
23945const nodeZlib = util.getNodeZlib();
23946
23947function uncompressed(data) {
23948 return data;
23949}
23950
23951function node_zlib(func, create, options = {}) {
23952 return function (data) {
23953 if (!util.isStream(data) || isArrayStream(data)) {
23954 return fromAsync(() => readToEnd(data).then(data => {
23955 return new Promise((resolve, reject) => {
23956 func(data, options, (err, result) => {
23957 if (err) return reject(err);
23958 resolve(result);
23959 });
23960 });
23961 }));
23962 }
23963 return nodeToWeb(webToNode(data).pipe(create(options)));
23964 };
23965}
23966
23967function pako_zlib(constructor, options = {}) {
23968 return function(data) {
23969 const obj = new constructor(options);
23970 return transform(data, value => {
23971 if (value.length) {
23972 obj.push(value, Z_SYNC_FLUSH);
23973 return obj.result;
23974 }
23975 }, () => {
23976 if (constructor === Deflate) {
23977 obj.push([], Z_FINISH);
23978 return obj.result;
23979 }
23980 });
23981 };
23982}
23983
23984function bzip2(func) {
23985 return function(data) {
23986 return fromAsync(async () => func(await readToEnd(data)));
23987 };
23988}
23989
23990const compress_fns = nodeZlib ? {
23991 zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),
23992 zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)
23993} : {
23994 zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),
23995 zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)
23996};
23997
23998const decompress_fns = nodeZlib ? {
23999 uncompressed: uncompressed,
24000 zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),
24001 zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),
24002 bzip2: /*#__PURE__*/ bzip2(lib_4)
24003} : {
24004 uncompressed: uncompressed,
24005 zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),
24006 zlib: /*#__PURE__*/ pako_zlib(Inflate),
24007 bzip2: /*#__PURE__*/ bzip2(lib_4)
24008};
24009
24010// GPG4Browsers - An OpenPGP implementation in javascript
24011
24012// A SEIP packet can contain the following packet types
24013const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([
24014 LiteralDataPacket,
24015 CompressedDataPacket,
24016 OnePassSignaturePacket,
24017 SignaturePacket
24018]);
24019
24020const VERSION$1 = 1; // A one-octet version number of the data packet.
24021
24022/**
24023 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
24024 *
24025 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
24026 * The Symmetrically Encrypted Integrity Protected Data packet is
24027 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
24028 * created for OpenPGP that addresses the problem of detecting a modification to
24029 * encrypted data. It is used in combination with a Modification Detection Code
24030 * packet.
24031 */
24032class SymEncryptedIntegrityProtectedDataPacket {
24033 static get tag() {
24034 return enums.packet.symEncryptedIntegrityProtectedData;
24035 }
24036
24037 constructor() {
24038 this.version = VERSION$1;
24039 this.encrypted = null;
24040 this.packets = null;
24041 }
24042
24043 async read(bytes) {
24044 await parse(bytes, async reader => {
24045 const version = await reader.readByte();
24046 // - A one-octet version number. The only currently defined value is 1.
24047 if (version !== VERSION$1) {
24048 throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);
24049 }
24050
24051 // - Encrypted data, the output of the selected symmetric-key cipher
24052 // operating in Cipher Feedback mode with shift amount equal to the
24053 // block size of the cipher (CFB-n where n is the block size).
24054 this.encrypted = reader.remainder();
24055 });
24056 }
24057
24058 write() {
24059 return util.concat([new Uint8Array([VERSION$1]), this.encrypted]);
24060 }
24061
24062 /**
24063 * Encrypt the payload in the packet.
24064 * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use
24065 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24066 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24067 * @returns {Promise<Boolean>}
24068 * @throws {Error} on encryption failure
24069 * @async
24070 */
24071 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24072 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24073
24074 let bytes = this.packets.write();
24075 if (isArrayStream(bytes)) bytes = await readToEnd(bytes);
24076 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
24077 const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
24078
24079 const tohash = util.concat([prefix, bytes, mdc]);
24080 const hash = await mod.hash.sha1(passiveClone(tohash));
24081 const plaintext = util.concat([tohash, hash]);
24082
24083 this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);
24084 return true;
24085 }
24086
24087 /**
24088 * Decrypts the encrypted data contained in the packet.
24089 * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used
24090 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24091 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24092 * @returns {Promise<Boolean>}
24093 * @throws {Error} on decryption failure
24094 * @async
24095 */
24096 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24097 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24098 let encrypted = clone(this.encrypted);
24099 if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted);
24100 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));
24101
24102 // there must be a modification detection code packet as the
24103 // last packet and everything gets hashed except the hash itself
24104 const realHash = slice(passiveClone(decrypted), -20);
24105 const tohash = slice(decrypted, 0, -20);
24106 const verifyHash = Promise.all([
24107 readToEnd(await mod.hash.sha1(passiveClone(tohash))),
24108 readToEnd(realHash)
24109 ]).then(([hash, mdc]) => {
24110 if (!util.equalsUint8Array(hash, mdc)) {
24111 throw new Error('Modification detected.');
24112 }
24113 return new Uint8Array();
24114 });
24115 const bytes = slice(tohash, blockSize + 2); // Remove random prefix
24116 let packetbytes = slice(bytes, 0, -2); // Remove MDC packet
24117 packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]);
24118 if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {
24119 packetbytes = await readToEnd(packetbytes);
24120 }
24121 this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config);
24122 return true;
24123 }
24124}
24125
24126// OpenPGP.js - An OpenPGP implementation in javascript
24127
24128// An AEAD-encrypted Data packet can contain the following packet types
24129const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([
24130 LiteralDataPacket,
24131 CompressedDataPacket,
24132 OnePassSignaturePacket,
24133 SignaturePacket
24134]);
24135
24136const VERSION$2 = 1; // A one-octet version number of the data packet.
24137
24138/**
24139 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
24140 * Additional Data (AEAD) Protected Data Packet
24141 *
24142 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
24143 * AEAD Protected Data Packet
24144 */
24145class AEADEncryptedDataPacket {
24146 static get tag() {
24147 return enums.packet.aeadEncryptedData;
24148 }
24149
24150 constructor() {
24151 this.version = VERSION$2;
24152 /** @type {enums.symmetric} */
24153 this.cipherAlgorithm = null;
24154 /** @type {enums.aead} */
24155 this.aeadAlgorithm = enums.aead.eax;
24156 this.chunkSizeByte = null;
24157 this.iv = null;
24158 this.encrypted = null;
24159 this.packets = null;
24160 }
24161
24162 /**
24163 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24164 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
24165 * @throws {Error} on parsing failure
24166 */
24167 async read(bytes) {
24168 await parse(bytes, async reader => {
24169 const version = await reader.readByte();
24170 if (version !== VERSION$2) { // The only currently defined value is 1.
24171 throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);
24172 }
24173 this.cipherAlgorithm = await reader.readByte();
24174 this.aeadAlgorithm = await reader.readByte();
24175 this.chunkSizeByte = await reader.readByte();
24176
24177 const mode = mod.getAEADMode(this.aeadAlgorithm);
24178 this.iv = await reader.readBytes(mode.ivLength);
24179 this.encrypted = reader.remainder();
24180 });
24181 }
24182
24183 /**
24184 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24185 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
24186 */
24187 write() {
24188 return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);
24189 }
24190
24191 /**
24192 * Decrypt the encrypted payload.
24193 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24194 * @param {Uint8Array} key - The session key used to encrypt the payload
24195 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24196 * @throws {Error} if decryption was not successful
24197 * @async
24198 */
24199 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24200 this.packets = await PacketList.fromBinary(
24201 await this.crypt('decrypt', key, clone(this.encrypted)),
24202 allowedPackets$2,
24203 config
24204 );
24205 }
24206
24207 /**
24208 * Encrypt the packet payload.
24209 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24210 * @param {Uint8Array} key - The session key used to encrypt the payload
24211 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24212 * @throws {Error} if encryption was not successful
24213 * @async
24214 */
24215 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24216 this.cipherAlgorithm = sessionKeyAlgorithm;
24217
24218 const { ivLength } = mod.getAEADMode(this.aeadAlgorithm);
24219 this.iv = await mod.random.getRandomBytes(ivLength); // generate new random IV
24220 this.chunkSizeByte = config.aeadChunkSizeByte;
24221 const data = this.packets.write();
24222 this.encrypted = await this.crypt('encrypt', key, data);
24223 }
24224
24225 /**
24226 * En/decrypt the payload.
24227 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
24228 * @param {Uint8Array} key - The session key used to en/decrypt the payload
24229 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
24230 * @returns {Promise<Uint8Array | ReadableStream<Uint8Array>>}
24231 * @async
24232 */
24233 async crypt(fn, key, data) {
24234 const mode = mod.getAEADMode(this.aeadAlgorithm);
24235 const modeInstance = await mode(this.cipherAlgorithm, key);
24236 const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
24237 const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
24238 const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
24239 const adataBuffer = new ArrayBuffer(21);
24240 const adataArray = new Uint8Array(adataBuffer, 0, 13);
24241 const adataTagArray = new Uint8Array(adataBuffer);
24242 const adataView = new DataView(adataBuffer);
24243 const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
24244 adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);
24245 let chunkIndex = 0;
24246 let latestPromise = Promise.resolve();
24247 let cryptedBytes = 0;
24248 let queuedBytes = 0;
24249 const iv = this.iv;
24250 return transformPair(data, async (readable, writable) => {
24251 if (util.isStream(readable) !== 'array') {
24252 const buffer = new TransformStream({}, {
24253 highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),
24254 size: array => array.length
24255 });
24256 pipe(buffer.readable, writable);
24257 writable = buffer.writable;
24258 }
24259 const reader = getReader(readable);
24260 const writer = getWriter(writable);
24261 try {
24262 while (true) {
24263 let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
24264 const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
24265 chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
24266 let cryptedPromise;
24267 let done;
24268 if (!chunkIndex || chunk.length) {
24269 reader.unshift(finalChunk);
24270 cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
24271 queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
24272 } else {
24273 // After the last chunk, we either encrypt a final, empty
24274 // data chunk to get the final authentication tag or
24275 // validate that final authentication tag.
24276 adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
24277 cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
24278 queuedBytes += tagLengthIfEncrypting;
24279 done = true;
24280 }
24281 cryptedBytes += chunk.length - tagLengthIfDecrypting;
24282 // eslint-disable-next-line no-loop-func
24283 latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
24284 await writer.ready;
24285 await writer.write(crypted);
24286 queuedBytes -= crypted.length;
24287 }).catch(err => writer.abort(err));
24288 if (done || queuedBytes > writer.desiredSize) {
24289 await latestPromise; // Respect backpressure
24290 }
24291 if (!done) {
24292 adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
24293 } else {
24294 await writer.close();
24295 break;
24296 }
24297 }
24298 } catch (e) {
24299 await writer.abort(e);
24300 }
24301 });
24302 }
24303}
24304
24305// GPG4Browsers - An OpenPGP implementation in javascript
24306
24307const VERSION$3 = 3;
24308
24309/**
24310 * Public-Key Encrypted Session Key Packets (Tag 1)
24311 *
24312 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
24313 * A Public-Key Encrypted Session Key packet holds the session key
24314 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
24315 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
24316 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
24317 * message is encrypted with the session key, and the session key is itself
24318 * encrypted and stored in the Encrypted Session Key packet(s). The
24319 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
24320 * Session Key packet for each OpenPGP key to which the message is encrypted.
24321 * The recipient of the message finds a session key that is encrypted to their
24322 * public key, decrypts the session key, and then uses the session key to
24323 * decrypt the message.
24324 */
24325class PublicKeyEncryptedSessionKeyPacket {
24326 static get tag() {
24327 return enums.packet.publicKeyEncryptedSessionKey;
24328 }
24329
24330 constructor() {
24331 this.version = 3;
24332
24333 this.publicKeyID = new KeyID();
24334 this.publicKeyAlgorithm = null;
24335
24336 this.sessionKey = null;
24337 /**
24338 * Algorithm to encrypt the message with
24339 * @type {enums.symmetric}
24340 */
24341 this.sessionKeyAlgorithm = null;
24342
24343 /** @type {Object} */
24344 this.encrypted = {};
24345 }
24346
24347 /**
24348 * Parsing function for a publickey encrypted session key packet (tag 1).
24349 *
24350 * @param {Uint8Array} bytes - Payload of a tag 1 packet
24351 */
24352 read(bytes) {
24353 this.version = bytes[0];
24354 if (this.version !== VERSION$3) {
24355 throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);
24356 }
24357 this.publicKeyID.read(bytes.subarray(1, bytes.length));
24358 this.publicKeyAlgorithm = bytes[9];
24359 this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(10));
24360 }
24361
24362 /**
24363 * Create a binary representation of a tag 1 packet
24364 *
24365 * @returns {Uint8Array} The Uint8Array representation.
24366 */
24367 write() {
24368 const arr = [
24369 new Uint8Array([this.version]),
24370 this.publicKeyID.write(),
24371 new Uint8Array([this.publicKeyAlgorithm]),
24372 mod.serializeParams(this.publicKeyAlgorithm, this.encrypted)
24373 ];
24374
24375 return util.concatUint8Array(arr);
24376 }
24377
24378 /**
24379 * Encrypt session key packet
24380 * @param {PublicKeyPacket} key - Public key
24381 * @throws {Error} if encryption failed
24382 * @async
24383 */
24384 async encrypt(key) {
24385 const data = util.concatUint8Array([
24386 new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]),
24387 this.sessionKey,
24388 util.writeChecksum(this.sessionKey)
24389 ]);
24390 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24391 this.encrypted = await mod.publicKeyEncrypt(
24392 algo, key.publicParams, data, key.getFingerprintBytes());
24393 }
24394
24395 /**
24396 * Decrypts the session key (only for public key encrypted session key packets (tag 1)
24397 * @param {SecretKeyPacket} key - decrypted private key
24398 * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.
24399 * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }
24400 * @throws {Error} if decryption failed, unless `randomSessionKey` is given
24401 * @async
24402 */
24403 async decrypt(key, randomSessionKey) {
24404 // check that session key algo matches the secret key algo
24405 if (this.publicKeyAlgorithm !== key.algorithm) {
24406 throw new Error('Decryption error');
24407 }
24408
24409 const randomPayload = randomSessionKey ? util.concatUint8Array([
24410 new Uint8Array([randomSessionKey.sessionKeyAlgorithm]),
24411 randomSessionKey.sessionKey,
24412 util.writeChecksum(randomSessionKey.sessionKey)
24413 ]) : null;
24414 const decoded = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);
24415 const symmetricAlgoByte = decoded[0];
24416 const sessionKey = decoded.subarray(1, decoded.length - 2);
24417 const checksum = decoded.subarray(decoded.length - 2);
24418 const computedChecksum = util.writeChecksum(sessionKey);
24419 const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];
24420
24421 if (randomSessionKey) {
24422 // We must not leak info about the validity of the decrypted checksum or cipher algo.
24423 // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.
24424 const isValidPayload = isValidChecksum & symmetricAlgoByte === randomSessionKey.sessionKeyAlgorithm & sessionKey.length === randomSessionKey.sessionKey.length;
24425 this.sessionKeyAlgorithm = util.selectUint8(isValidPayload, symmetricAlgoByte, randomSessionKey.sessionKeyAlgorithm);
24426 this.sessionKey = util.selectUint8Array(isValidPayload, sessionKey, randomSessionKey.sessionKey);
24427
24428 } else {
24429 const isValidPayload = isValidChecksum && enums.read(enums.symmetric, symmetricAlgoByte);
24430 if (isValidPayload) {
24431 this.sessionKey = sessionKey;
24432 this.sessionKeyAlgorithm = symmetricAlgoByte;
24433 } else {
24434 throw new Error('Decryption error');
24435 }
24436 }
24437 }
24438}
24439
24440// GPG4Browsers - An OpenPGP implementation in javascript
24441
24442class S2K {
24443 /**
24444 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24445 */
24446 constructor(config = defaultConfig) {
24447 /**
24448 * Hash function identifier, or 0 for gnu-dummy keys
24449 * @type {module:enums.hash | 0}
24450 */
24451 this.algorithm = enums.hash.sha256;
24452 /**
24453 * enums.s2k identifier or 'gnu-dummy'
24454 * @type {String}
24455 */
24456 this.type = 'iterated';
24457 /** @type {Integer} */
24458 this.c = config.s2kIterationCountByte;
24459 /** Eight bytes of salt in a binary string.
24460 * @type {Uint8Array}
24461 */
24462 this.salt = null;
24463 }
24464
24465 getCount() {
24466 // Exponent bias, defined in RFC4880
24467 const expbias = 6;
24468
24469 return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
24470 }
24471
24472 /**
24473 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
24474 * @param {Uint8Array} bytes - Payload of string-to-key specifier
24475 * @returns {Integer} Actual length of the object.
24476 */
24477 read(bytes) {
24478 let i = 0;
24479 this.type = enums.read(enums.s2k, bytes[i++]);
24480 this.algorithm = bytes[i++];
24481
24482 switch (this.type) {
24483 case 'simple':
24484 break;
24485
24486 case 'salted':
24487 this.salt = bytes.subarray(i, i + 8);
24488 i += 8;
24489 break;
24490
24491 case 'iterated':
24492 this.salt = bytes.subarray(i, i + 8);
24493 i += 8;
24494
24495 // Octet 10: count, a one-octet, coded value
24496 this.c = bytes[i++];
24497 break;
24498
24499 case 'gnu':
24500 if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {
24501 i += 3; // GNU
24502 const gnuExtType = 1000 + bytes[i++];
24503 if (gnuExtType === 1001) {
24504 this.type = 'gnu-dummy';
24505 // GnuPG extension mode 1001 -- don't write secret key at all
24506 } else {
24507 throw new Error('Unknown s2k gnu protection mode.');
24508 }
24509 } else {
24510 throw new Error('Unknown s2k type.');
24511 }
24512 break;
24513
24514 default:
24515 throw new Error('Unknown s2k type.');
24516 }
24517
24518 return i;
24519 }
24520
24521 /**
24522 * Serializes s2k information
24523 * @returns {Uint8Array} Binary representation of s2k.
24524 */
24525 write() {
24526 if (this.type === 'gnu-dummy') {
24527 return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);
24528 }
24529 const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];
24530
24531 switch (this.type) {
24532 case 'simple':
24533 break;
24534 case 'salted':
24535 arr.push(this.salt);
24536 break;
24537 case 'iterated':
24538 arr.push(this.salt);
24539 arr.push(new Uint8Array([this.c]));
24540 break;
24541 case 'gnu':
24542 throw new Error('GNU s2k type not supported.');
24543 default:
24544 throw new Error('Unknown s2k type.');
24545 }
24546
24547 return util.concatUint8Array(arr);
24548 }
24549
24550 /**
24551 * Produces a key using the specified passphrase and the defined
24552 * hashAlgorithm
24553 * @param {String} passphrase - Passphrase containing user input
24554 * @returns {Promise<Uint8Array>} Produced key with a length corresponding to.
24555 * hashAlgorithm hash length
24556 * @async
24557 */
24558 async produceKey(passphrase, numBytes) {
24559 passphrase = util.encodeUTF8(passphrase);
24560
24561 const arr = [];
24562 let rlength = 0;
24563
24564 let prefixlen = 0;
24565 while (rlength < numBytes) {
24566 let toHash;
24567 switch (this.type) {
24568 case 'simple':
24569 toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
24570 break;
24571 case 'salted':
24572 toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
24573 break;
24574 case 'iterated': {
24575 const data = util.concatUint8Array([this.salt, passphrase]);
24576 let datalen = data.length;
24577 const count = Math.max(this.getCount(), datalen);
24578 toHash = new Uint8Array(prefixlen + count);
24579 toHash.set(data, prefixlen);
24580 for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
24581 toHash.copyWithin(pos, prefixlen, pos);
24582 }
24583 break;
24584 }
24585 case 'gnu':
24586 throw new Error('GNU s2k type not supported.');
24587 default:
24588 throw new Error('Unknown s2k type.');
24589 }
24590 const result = await mod.hash.digest(this.algorithm, toHash);
24591 arr.push(result);
24592 rlength += result.length;
24593 prefixlen++;
24594 }
24595
24596 return util.concatUint8Array(arr).subarray(0, numBytes);
24597 }
24598}
24599
24600// GPG4Browsers - An OpenPGP implementation in javascript
24601
24602/**
24603 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
24604 *
24605 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
24606 * The Symmetric-Key Encrypted Session Key packet holds the
24607 * symmetric-key encryption of a session key used to encrypt a message.
24608 * Zero or more Public-Key Encrypted Session Key packets and/or
24609 * Symmetric-Key Encrypted Session Key packets may precede a
24610 * Symmetrically Encrypted Data packet that holds an encrypted message.
24611 * The message is encrypted with a session key, and the session key is
24612 * itself encrypted and stored in the Encrypted Session Key packet or
24613 * the Symmetric-Key Encrypted Session Key packet.
24614 */
24615class SymEncryptedSessionKeyPacket {
24616 static get tag() {
24617 return enums.packet.symEncryptedSessionKey;
24618 }
24619
24620 /**
24621 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24622 */
24623 constructor(config = defaultConfig) {
24624 this.version = config.aeadProtect ? 5 : 4;
24625 this.sessionKey = null;
24626 /**
24627 * Algorithm to encrypt the session key with
24628 * @type {enums.symmetric}
24629 */
24630 this.sessionKeyEncryptionAlgorithm = null;
24631 /**
24632 * Algorithm to encrypt the message with
24633 * @type {enums.symmetric}
24634 */
24635 this.sessionKeyAlgorithm = enums.symmetric.aes256;
24636 /**
24637 * AEAD mode to encrypt the session key with (if AEAD protection is enabled)
24638 * @type {enums.aead}
24639 */
24640 this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);
24641 this.encrypted = null;
24642 this.s2k = null;
24643 this.iv = null;
24644 }
24645
24646 /**
24647 * Parsing function for a symmetric encrypted session key packet (tag 3).
24648 *
24649 * @param {Uint8Array} bytes - Payload of a tag 3 packet
24650 */
24651 read(bytes) {
24652 let offset = 0;
24653
24654 // A one-octet version number. The only currently defined version is 4.
24655 this.version = bytes[offset++];
24656 if (this.version !== 4 && this.version !== 5) {
24657 throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);
24658 }
24659
24660 // A one-octet number describing the symmetric algorithm used.
24661 const algo = bytes[offset++];
24662
24663 if (this.version === 5) {
24664 // A one-octet AEAD algorithm.
24665 this.aeadAlgorithm = bytes[offset++];
24666 }
24667
24668 // A string-to-key (S2K) specifier, length as defined above.
24669 this.s2k = new S2K();
24670 offset += this.s2k.read(bytes.subarray(offset, bytes.length));
24671
24672 if (this.version === 5) {
24673 const mode = mod.getAEADMode(this.aeadAlgorithm);
24674
24675 // A starting initialization vector of size specified by the AEAD
24676 // algorithm.
24677 this.iv = bytes.subarray(offset, offset += mode.ivLength);
24678 }
24679
24680 // The encrypted session key itself, which is decrypted with the
24681 // string-to-key object. This is optional in version 4.
24682 if (this.version === 5 || offset < bytes.length) {
24683 this.encrypted = bytes.subarray(offset, bytes.length);
24684 this.sessionKeyEncryptionAlgorithm = algo;
24685 } else {
24686 this.sessionKeyAlgorithm = algo;
24687 }
24688 }
24689
24690 /**
24691 * Create a binary representation of a tag 3 packet
24692 *
24693 * @returns {Uint8Array} The Uint8Array representation.
24694 */
24695 write() {
24696 const algo = this.encrypted === null ?
24697 this.sessionKeyAlgorithm :
24698 this.sessionKeyEncryptionAlgorithm;
24699
24700 let bytes;
24701
24702 if (this.version === 5) {
24703 bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);
24704 } else {
24705 bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);
24706
24707 if (this.encrypted !== null) {
24708 bytes = util.concatUint8Array([bytes, this.encrypted]);
24709 }
24710 }
24711
24712 return bytes;
24713 }
24714
24715 /**
24716 * Decrypts the session key with the given passphrase
24717 * @param {String} passphrase - The passphrase in string form
24718 * @throws {Error} if decryption was not successful
24719 * @async
24720 */
24721 async decrypt(passphrase) {
24722 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24723 this.sessionKeyEncryptionAlgorithm :
24724 this.sessionKeyAlgorithm;
24725
24726 const { blockSize, keySize } = mod.getCipher(algo);
24727 const key = await this.s2k.produceKey(passphrase, keySize);
24728
24729 if (this.version === 5) {
24730 const mode = mod.getAEADMode(this.aeadAlgorithm);
24731 const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
24732 const modeInstance = await mode(algo, key);
24733 this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
24734 } else if (this.encrypted !== null) {
24735 const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));
24736
24737 this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);
24738 this.sessionKey = decrypted.subarray(1, decrypted.length);
24739 } else {
24740 this.sessionKey = key;
24741 }
24742 }
24743
24744 /**
24745 * Encrypts the session key with the given passphrase
24746 * @param {String} passphrase - The passphrase in string form
24747 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24748 * @throws {Error} if encryption was not successful
24749 * @async
24750 */
24751 async encrypt(passphrase, config = defaultConfig) {
24752 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24753 this.sessionKeyEncryptionAlgorithm :
24754 this.sessionKeyAlgorithm;
24755
24756 this.sessionKeyEncryptionAlgorithm = algo;
24757
24758 this.s2k = new S2K(config);
24759 this.s2k.salt = await mod.random.getRandomBytes(8);
24760
24761 const { blockSize, keySize } = mod.getCipher(algo);
24762 const encryptionKey = await this.s2k.produceKey(passphrase, keySize);
24763
24764 if (this.sessionKey === null) {
24765 this.sessionKey = await mod.generateSessionKey(this.sessionKeyAlgorithm);
24766 }
24767
24768 if (this.version === 5) {
24769 const mode = mod.getAEADMode(this.aeadAlgorithm);
24770 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
24771 const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
24772 const modeInstance = await mode(algo, encryptionKey);
24773 this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);
24774 } else {
24775 const toEncrypt = util.concatUint8Array([
24776 new Uint8Array([this.sessionKeyAlgorithm]),
24777 this.sessionKey
24778 ]);
24779 this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);
24780 }
24781 }
24782}
24783
24784// GPG4Browsers - An OpenPGP implementation in javascript
24785
24786/**
24787 * Implementation of the Key Material Packet (Tag 5,6,7,14)
24788 *
24789 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
24790 * A key material packet contains all the information about a public or
24791 * private key. There are four variants of this packet type, and two
24792 * major versions.
24793 *
24794 * A Public-Key packet starts a series of packets that forms an OpenPGP
24795 * key (sometimes called an OpenPGP certificate).
24796 */
24797class PublicKeyPacket {
24798 static get tag() {
24799 return enums.packet.publicKey;
24800 }
24801
24802 /**
24803 * @param {Date} [date] - Creation date
24804 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24805 */
24806 constructor(date = new Date(), config = defaultConfig) {
24807 /**
24808 * Packet version
24809 * @type {Integer}
24810 */
24811 this.version = config.v5Keys ? 5 : 4;
24812 /**
24813 * Key creation date.
24814 * @type {Date}
24815 */
24816 this.created = util.normalizeDate(date);
24817 /**
24818 * Public key algorithm.
24819 * @type {enums.publicKey}
24820 */
24821 this.algorithm = null;
24822 /**
24823 * Algorithm specific public params
24824 * @type {Object}
24825 */
24826 this.publicParams = null;
24827 /**
24828 * Time until expiration in days (V3 only)
24829 * @type {Integer}
24830 */
24831 this.expirationTimeV3 = 0;
24832 /**
24833 * Fingerprint bytes
24834 * @type {Uint8Array}
24835 */
24836 this.fingerprint = null;
24837 /**
24838 * KeyID
24839 * @type {module:type/keyid~KeyID}
24840 */
24841 this.keyID = null;
24842 }
24843
24844 /**
24845 * Create a PublicKeyPacket from a SecretKeyPacket
24846 * @param {SecretKeyPacket} secretKeyPacket - key packet to convert
24847 * @returns {PublicKeyPacket} public key packet
24848 * @static
24849 */
24850 static fromSecretKeyPacket(secretKeyPacket) {
24851 const keyPacket = new PublicKeyPacket();
24852 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;
24853 keyPacket.version = version;
24854 keyPacket.created = created;
24855 keyPacket.algorithm = algorithm;
24856 keyPacket.publicParams = publicParams;
24857 keyPacket.keyID = keyID;
24858 keyPacket.fingerprint = fingerprint;
24859 return keyPacket;
24860 }
24861
24862 /**
24863 * 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}
24864 * @param {Uint8Array} bytes - Input array to read the packet from
24865 * @returns {Object} This object with attributes set by the parser
24866 * @async
24867 */
24868 async read(bytes) {
24869 let pos = 0;
24870 // A one-octet version number (3, 4 or 5).
24871 this.version = bytes[pos++];
24872
24873 if (this.version === 4 || this.version === 5) {
24874 // - A four-octet number denoting the time that the key was created.
24875 this.created = util.readDate(bytes.subarray(pos, pos + 4));
24876 pos += 4;
24877
24878 // - A one-octet number denoting the public-key algorithm of this key.
24879 this.algorithm = bytes[pos++];
24880
24881 if (this.version === 5) {
24882 // - A four-octet scalar octet count for the following key material.
24883 pos += 4;
24884 }
24885
24886 // - A series of values comprising the key material.
24887 const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));
24888 this.publicParams = publicParams;
24889 pos += read;
24890
24891 // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor
24892 await this.computeFingerprintAndKeyID();
24893 return pos;
24894 }
24895 throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);
24896 }
24897
24898 /**
24899 * Creates an OpenPGP public key packet for the given key.
24900 * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
24901 */
24902 write() {
24903 const arr = [];
24904 // Version
24905 arr.push(new Uint8Array([this.version]));
24906 arr.push(util.writeDate(this.created));
24907 // A one-octet number denoting the public-key algorithm of this key
24908 arr.push(new Uint8Array([this.algorithm]));
24909
24910 const params = mod.serializeParams(this.algorithm, this.publicParams);
24911 if (this.version === 5) {
24912 // A four-octet scalar octet count for the following key material
24913 arr.push(util.writeNumber(params.length, 4));
24914 }
24915 // Algorithm-specific params
24916 arr.push(params);
24917 return util.concatUint8Array(arr);
24918 }
24919
24920 /**
24921 * Write packet in order to be hashed; either for a signature or a fingerprint
24922 * @param {Integer} version - target version of signature or key
24923 */
24924 writeForHash(version) {
24925 const bytes = this.writePublicKey();
24926
24927 if (version === 5) {
24928 return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);
24929 }
24930 return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);
24931 }
24932
24933 /**
24934 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
24935 * @returns {Boolean|null}
24936 */
24937 isDecrypted() {
24938 return null;
24939 }
24940
24941 /**
24942 * Returns the creation time of the key
24943 * @returns {Date}
24944 */
24945 getCreationTime() {
24946 return this.created;
24947 }
24948
24949 /**
24950 * Return the key ID of the key
24951 * @returns {module:type/keyid~KeyID} The 8-byte key ID
24952 */
24953 getKeyID() {
24954 return this.keyID;
24955 }
24956
24957 /**
24958 * Computes and set the key ID and fingerprint of the key
24959 * @async
24960 */
24961 async computeFingerprintAndKeyID() {
24962 await this.computeFingerprint();
24963 this.keyID = new KeyID();
24964
24965 if (this.version === 5) {
24966 this.keyID.read(this.fingerprint.subarray(0, 8));
24967 } else if (this.version === 4) {
24968 this.keyID.read(this.fingerprint.subarray(12, 20));
24969 } else {
24970 throw new Error('Unsupported key version');
24971 }
24972 }
24973
24974 /**
24975 * Computes and set the fingerprint of the key
24976 */
24977 async computeFingerprint() {
24978 const toHash = this.writeForHash(this.version);
24979
24980 if (this.version === 5) {
24981 this.fingerprint = await mod.hash.sha256(toHash);
24982 } else if (this.version === 4) {
24983 this.fingerprint = await mod.hash.sha1(toHash);
24984 } else {
24985 throw new Error('Unsupported key version');
24986 }
24987 }
24988
24989 /**
24990 * Returns the fingerprint of the key, as an array of bytes
24991 * @returns {Uint8Array} A Uint8Array containing the fingerprint
24992 */
24993 getFingerprintBytes() {
24994 return this.fingerprint;
24995 }
24996
24997 /**
24998 * Calculates and returns the fingerprint of the key, as a string
24999 * @returns {String} A string containing the fingerprint in lowercase hex
25000 */
25001 getFingerprint() {
25002 return util.uint8ArrayToHex(this.getFingerprintBytes());
25003 }
25004
25005 /**
25006 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
25007 * @returns {Boolean} Whether the two keys have the same version and public key data.
25008 */
25009 hasSameFingerprintAs(other) {
25010 return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
25011 }
25012
25013 /**
25014 * Returns algorithm information
25015 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
25016 */
25017 getAlgorithmInfo() {
25018 const result = {};
25019 result.algorithm = enums.read(enums.publicKey, this.algorithm);
25020 // RSA, DSA or ElGamal public modulo
25021 const modulo = this.publicParams.n || this.publicParams.p;
25022 if (modulo) {
25023 result.bits = util.uint8ArrayBitLength(modulo);
25024 } else {
25025 result.curve = this.publicParams.oid.getName();
25026 }
25027 return result;
25028 }
25029}
25030
25031/**
25032 * Alias of read()
25033 * @see PublicKeyPacket#read
25034 */
25035PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
25036
25037/**
25038 * Alias of write()
25039 * @see PublicKeyPacket#write
25040 */
25041PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;
25042
25043// GPG4Browsers - An OpenPGP implementation in javascript
25044
25045// A SE packet can contain the following packet types
25046const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([
25047 LiteralDataPacket,
25048 CompressedDataPacket,
25049 OnePassSignaturePacket,
25050 SignaturePacket
25051]);
25052
25053/**
25054 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
25055 *
25056 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
25057 * The Symmetrically Encrypted Data packet contains data encrypted with a
25058 * symmetric-key algorithm. When it has been decrypted, it contains other
25059 * packets (usually a literal data packet or compressed data packet, but in
25060 * theory other Symmetrically Encrypted Data packets or sequences of packets
25061 * that form whole OpenPGP messages).
25062 */
25063class SymmetricallyEncryptedDataPacket {
25064 static get tag() {
25065 return enums.packet.symmetricallyEncryptedData;
25066 }
25067
25068 constructor() {
25069 /**
25070 * Encrypted secret-key data
25071 */
25072 this.encrypted = null;
25073 /**
25074 * Decrypted packets contained within.
25075 * @type {PacketList}
25076 */
25077 this.packets = null;
25078 }
25079
25080 read(bytes) {
25081 this.encrypted = bytes;
25082 }
25083
25084 write() {
25085 return this.encrypted;
25086 }
25087
25088 /**
25089 * Decrypt the symmetrically-encrypted packet data
25090 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25091 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25092 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25093 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25094
25095 * @throws {Error} if decryption was not successful
25096 * @async
25097 */
25098 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
25099 // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
25100 if (!config.allowUnauthenticatedMessages) {
25101 throw new Error('Message is not authenticated.');
25102 }
25103
25104 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25105 const encrypted = await readToEnd(clone(this.encrypted));
25106 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key,
25107 encrypted.subarray(blockSize + 2),
25108 encrypted.subarray(2, blockSize + 2)
25109 );
25110
25111 this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config);
25112 }
25113
25114 /**
25115 * Encrypt the symmetrically-encrypted packet data
25116 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25117 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25118 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25119 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25120 * @throws {Error} if encryption was not successful
25121 * @async
25122 */
25123 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
25124 const data = this.packets.write();
25125 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25126
25127 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
25128 const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);
25129 const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);
25130 this.encrypted = util.concat([FRE, ciphertext]);
25131 }
25132}
25133
25134// GPG4Browsers - An OpenPGP implementation in javascript
25135
25136/**
25137 * Implementation of the strange "Marker packet" (Tag 10)
25138 *
25139 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
25140 * An experimental version of PGP used this packet as the Literal
25141 * packet, but no released version of PGP generated Literal packets with this
25142 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
25143 * the Marker packet.
25144 *
25145 * The body of this packet consists of:
25146 * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8).
25147 *
25148 * Such a packet MUST be ignored when received. It may be placed at the
25149 * beginning of a message that uses features not available in PGP
25150 * version 2.6 in order to cause that version to report that newer
25151 * software is necessary to process the message.
25152 */
25153class MarkerPacket {
25154 static get tag() {
25155 return enums.packet.marker;
25156 }
25157
25158 /**
25159 * Parsing function for a marker data packet (tag 10).
25160 * @param {Uint8Array} bytes - Payload of a tag 10 packet
25161 * @returns {Boolean} whether the packet payload contains "PGP"
25162 */
25163 read(bytes) {
25164 if (bytes[0] === 0x50 && // P
25165 bytes[1] === 0x47 && // G
25166 bytes[2] === 0x50) { // P
25167 return true;
25168 }
25169 return false;
25170 }
25171
25172 write() {
25173 return new Uint8Array([0x50, 0x47, 0x50]);
25174 }
25175}
25176
25177// GPG4Browsers - An OpenPGP implementation in javascript
25178
25179/**
25180 * A Public-Subkey packet (tag 14) has exactly the same format as a
25181 * Public-Key packet, but denotes a subkey. One or more subkeys may be
25182 * associated with a top-level key. By convention, the top-level key
25183 * provides signature services, and the subkeys provide encryption
25184 * services.
25185 * @extends PublicKeyPacket
25186 */
25187class PublicSubkeyPacket extends PublicKeyPacket {
25188 static get tag() {
25189 return enums.packet.publicSubkey;
25190 }
25191
25192 /**
25193 * @param {Date} [date] - Creation date
25194 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25195 */
25196 // eslint-disable-next-line no-useless-constructor
25197 constructor(date, config) {
25198 super(date, config);
25199 }
25200
25201 /**
25202 * Create a PublicSubkeyPacket from a SecretSubkeyPacket
25203 * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert
25204 * @returns {SecretSubkeyPacket} public key packet
25205 * @static
25206 */
25207 static fromSecretSubkeyPacket(secretSubkeyPacket) {
25208 const keyPacket = new PublicSubkeyPacket();
25209 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;
25210 keyPacket.version = version;
25211 keyPacket.created = created;
25212 keyPacket.algorithm = algorithm;
25213 keyPacket.publicParams = publicParams;
25214 keyPacket.keyID = keyID;
25215 keyPacket.fingerprint = fingerprint;
25216 return keyPacket;
25217 }
25218}
25219
25220// GPG4Browsers - An OpenPGP implementation in javascript
25221
25222/**
25223 * Implementation of the User Attribute Packet (Tag 17)
25224 *
25225 * The User Attribute packet is a variation of the User ID packet. It
25226 * is capable of storing more types of data than the User ID packet,
25227 * which is limited to text. Like the User ID packet, a User Attribute
25228 * packet may be certified by the key owner ("self-signed") or any other
25229 * key owner who cares to certify it. Except as noted, a User Attribute
25230 * packet may be used anywhere that a User ID packet may be used.
25231 *
25232 * While User Attribute packets are not a required part of the OpenPGP
25233 * standard, implementations SHOULD provide at least enough
25234 * compatibility to properly handle a certification signature on the
25235 * User Attribute packet. A simple way to do this is by treating the
25236 * User Attribute packet as a User ID packet with opaque contents, but
25237 * an implementation may use any method desired.
25238 */
25239class UserAttributePacket {
25240 static get tag() {
25241 return enums.packet.userAttribute;
25242 }
25243
25244 constructor() {
25245 this.attributes = [];
25246 }
25247
25248 /**
25249 * parsing function for a user attribute packet (tag 17).
25250 * @param {Uint8Array} input - Payload of a tag 17 packet
25251 */
25252 read(bytes) {
25253 let i = 0;
25254 while (i < bytes.length) {
25255 const len = readSimpleLength(bytes.subarray(i, bytes.length));
25256 i += len.offset;
25257
25258 this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));
25259 i += len.len;
25260 }
25261 }
25262
25263 /**
25264 * Creates a binary representation of the user attribute packet
25265 * @returns {Uint8Array} String representation.
25266 */
25267 write() {
25268 const arr = [];
25269 for (let i = 0; i < this.attributes.length; i++) {
25270 arr.push(writeSimpleLength(this.attributes[i].length));
25271 arr.push(util.stringToUint8Array(this.attributes[i]));
25272 }
25273 return util.concatUint8Array(arr);
25274 }
25275
25276 /**
25277 * Compare for equality
25278 * @param {UserAttributePacket} usrAttr
25279 * @returns {Boolean} True if equal.
25280 */
25281 equals(usrAttr) {
25282 if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
25283 return false;
25284 }
25285 return this.attributes.every(function(attr, index) {
25286 return attr === usrAttr.attributes[index];
25287 });
25288 }
25289}
25290
25291// GPG4Browsers - An OpenPGP implementation in javascript
25292
25293/**
25294 * A Secret-Key packet contains all the information that is found in a
25295 * Public-Key packet, including the public-key material, but also
25296 * includes the secret-key material after all the public-key fields.
25297 * @extends PublicKeyPacket
25298 */
25299class SecretKeyPacket extends PublicKeyPacket {
25300 static get tag() {
25301 return enums.packet.secretKey;
25302 }
25303
25304 /**
25305 * @param {Date} [date] - Creation date
25306 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25307 */
25308 constructor(date = new Date(), config = defaultConfig) {
25309 super(date, config);
25310 /**
25311 * Secret-key data
25312 */
25313 this.keyMaterial = null;
25314 /**
25315 * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
25316 */
25317 this.isEncrypted = null;
25318 /**
25319 * S2K usage
25320 * @type {enums.symmetric}
25321 */
25322 this.s2kUsage = 0;
25323 /**
25324 * S2K object
25325 * @type {type/s2k}
25326 */
25327 this.s2k = null;
25328 /**
25329 * Symmetric algorithm to encrypt the key with
25330 * @type {enums.symmetric}
25331 */
25332 this.symmetric = null;
25333 /**
25334 * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)
25335 * @type {enums.aead}
25336 */
25337 this.aead = null;
25338 /**
25339 * Decrypted private parameters, referenced by name
25340 * @type {Object}
25341 */
25342 this.privateParams = null;
25343 }
25344
25345 // 5.5.3. Secret-Key Packet Formats
25346
25347 /**
25348 * Internal parser for private keys as specified in
25349 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
25350 * @param {Uint8Array} bytes - Input string to read the packet from
25351 * @async
25352 */
25353 async read(bytes) {
25354 // - A Public-Key or Public-Subkey packet, as described above.
25355 let i = await this.readPublicKey(bytes);
25356
25357 // - One octet indicating string-to-key usage conventions. Zero
25358 // indicates that the secret-key data is not encrypted. 255 or 254
25359 // indicates that a string-to-key specifier is being given. Any
25360 // other value is a symmetric-key encryption algorithm identifier.
25361 this.s2kUsage = bytes[i++];
25362
25363 // - Only for a version 5 packet, a one-octet scalar octet count of
25364 // the next 4 optional fields.
25365 if (this.version === 5) {
25366 i++;
25367 }
25368
25369 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25370 // one-octet symmetric encryption algorithm.
25371 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25372 this.symmetric = bytes[i++];
25373
25374 // - [Optional] If string-to-key usage octet was 253, a one-octet
25375 // AEAD algorithm.
25376 if (this.s2kUsage === 253) {
25377 this.aead = bytes[i++];
25378 }
25379
25380 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25381 // string-to-key specifier. The length of the string-to-key
25382 // specifier is implied by its type, as described above.
25383 this.s2k = new S2K();
25384 i += this.s2k.read(bytes.subarray(i, bytes.length));
25385
25386 if (this.s2k.type === 'gnu-dummy') {
25387 return;
25388 }
25389 } else if (this.s2kUsage) {
25390 this.symmetric = this.s2kUsage;
25391 }
25392
25393 // - [Optional] If secret data is encrypted (string-to-key usage octet
25394 // not zero), an Initial Vector (IV) of the same length as the
25395 // cipher's block size.
25396 if (this.s2kUsage) {
25397 this.iv = bytes.subarray(
25398 i,
25399 i + mod.getCipher(this.symmetric).blockSize
25400 );
25401
25402 i += this.iv.length;
25403 }
25404
25405 // - Only for a version 5 packet, a four-octet scalar octet count for
25406 // the following key material.
25407 if (this.version === 5) {
25408 i += 4;
25409 }
25410
25411 // - Plain or encrypted multiprecision integers comprising the secret
25412 // key data. These algorithm-specific fields are as described
25413 // below.
25414 this.keyMaterial = bytes.subarray(i);
25415 this.isEncrypted = !!this.s2kUsage;
25416
25417 if (!this.isEncrypted) {
25418 const cleartext = this.keyMaterial.subarray(0, -2);
25419 if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
25420 throw new Error('Key checksum mismatch');
25421 }
25422 try {
25423 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
25424 this.privateParams = privateParams;
25425 } catch (err) {
25426 if (err instanceof UnsupportedError) throw err;
25427 // avoid throwing potentially sensitive errors
25428 throw new Error('Error reading MPIs');
25429 }
25430 }
25431 }
25432
25433 /**
25434 * Creates an OpenPGP key packet for the given key.
25435 * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
25436 */
25437 write() {
25438 const arr = [this.writePublicKey()];
25439
25440 arr.push(new Uint8Array([this.s2kUsage]));
25441
25442 const optionalFieldsArr = [];
25443 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25444 // one- octet symmetric encryption algorithm.
25445 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25446 optionalFieldsArr.push(this.symmetric);
25447
25448 // - [Optional] If string-to-key usage octet was 253, a one-octet
25449 // AEAD algorithm.
25450 if (this.s2kUsage === 253) {
25451 optionalFieldsArr.push(this.aead);
25452 }
25453
25454 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25455 // string-to-key specifier. The length of the string-to-key
25456 // specifier is implied by its type, as described above.
25457 optionalFieldsArr.push(...this.s2k.write());
25458 }
25459
25460 // - [Optional] If secret data is encrypted (string-to-key usage octet
25461 // not zero), an Initial Vector (IV) of the same length as the
25462 // cipher's block size.
25463 if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {
25464 optionalFieldsArr.push(...this.iv);
25465 }
25466
25467 if (this.version === 5) {
25468 arr.push(new Uint8Array([optionalFieldsArr.length]));
25469 }
25470 arr.push(new Uint8Array(optionalFieldsArr));
25471
25472 if (!this.isDummy()) {
25473 if (!this.s2kUsage) {
25474 this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams);
25475 }
25476
25477 if (this.version === 5) {
25478 arr.push(util.writeNumber(this.keyMaterial.length, 4));
25479 }
25480 arr.push(this.keyMaterial);
25481
25482 if (!this.s2kUsage) {
25483 arr.push(util.writeChecksum(this.keyMaterial));
25484 }
25485 }
25486
25487 return util.concatUint8Array(arr);
25488 }
25489
25490 /**
25491 * Check whether secret-key data is available in decrypted form.
25492 * Returns false for gnu-dummy keys and null for public keys.
25493 * @returns {Boolean|null}
25494 */
25495 isDecrypted() {
25496 return this.isEncrypted === false;
25497 }
25498
25499 /**
25500 * Check whether this is a gnu-dummy key
25501 * @returns {Boolean}
25502 */
25503 isDummy() {
25504 return !!(this.s2k && this.s2k.type === 'gnu-dummy');
25505 }
25506
25507 /**
25508 * Remove private key material, converting the key to a dummy one.
25509 * The resulting key cannot be used for signing/decrypting but can still verify signatures.
25510 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25511 */
25512 makeDummy(config = defaultConfig) {
25513 if (this.isDummy()) {
25514 return;
25515 }
25516 if (this.isDecrypted()) {
25517 this.clearPrivateParams();
25518 }
25519 this.isEncrypted = null;
25520 this.keyMaterial = null;
25521 this.s2k = new S2K(config);
25522 this.s2k.algorithm = 0;
25523 this.s2k.c = 0;
25524 this.s2k.type = 'gnu-dummy';
25525 this.s2kUsage = 254;
25526 this.symmetric = enums.symmetric.aes256;
25527 }
25528
25529 /**
25530 * Encrypt the payload. By default, we use aes256 and iterated, salted string
25531 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
25532 * and the passphrase is empty or undefined, the key will be set as not encrypted.
25533 * This can be used to remove passphrase protection after calling decrypt().
25534 * @param {String} passphrase
25535 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25536 * @throws {Error} if encryption was not successful
25537 * @async
25538 */
25539 async encrypt(passphrase, config = defaultConfig) {
25540 if (this.isDummy()) {
25541 return;
25542 }
25543
25544 if (!this.isDecrypted()) {
25545 throw new Error('Key packet is already encrypted');
25546 }
25547
25548 if (!passphrase) {
25549 throw new Error('A non-empty passphrase is required for key encryption.');
25550 }
25551
25552 this.s2k = new S2K(config);
25553 this.s2k.salt = await mod.random.getRandomBytes(8);
25554 const cleartext = mod.serializeParams(this.algorithm, this.privateParams);
25555 this.symmetric = enums.symmetric.aes256;
25556 const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25557
25558 const { blockSize } = mod.getCipher(this.symmetric);
25559 this.iv = await mod.random.getRandomBytes(blockSize);
25560
25561 if (config.aeadProtect) {
25562 this.s2kUsage = 253;
25563 this.aead = enums.aead.eax;
25564 const mode = mod.getAEADMode(this.aead);
25565 const modeInstance = await mode(this.symmetric, key);
25566 this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25567 } else {
25568 this.s2kUsage = 254;
25569 this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([
25570 cleartext,
25571 await mod.hash.sha1(cleartext, config)
25572 ]), this.iv, config);
25573 }
25574 }
25575
25576 /**
25577 * Decrypts the private key params which are needed to use the key.
25578 * Successful decryption does not imply key integrity, call validate() to confirm that.
25579 * {@link SecretKeyPacket.isDecrypted} should be false, as
25580 * otherwise calls to this function will throw an error.
25581 * @param {String} passphrase - The passphrase for this private key as string
25582 * @throws {Error} if the key is already decrypted, or if decryption was not successful
25583 * @async
25584 */
25585 async decrypt(passphrase) {
25586 if (this.isDummy()) {
25587 return false;
25588 }
25589
25590 if (this.isDecrypted()) {
25591 throw new Error('Key packet is already decrypted.');
25592 }
25593
25594 let key;
25595 if (this.s2kUsage === 254 || this.s2kUsage === 253) {
25596 key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25597 } else if (this.s2kUsage === 255) {
25598 throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
25599 } else {
25600 throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
25601 }
25602
25603 let cleartext;
25604 if (this.s2kUsage === 253) {
25605 const mode = mod.getAEADMode(this.aead);
25606 const modeInstance = await mode(this.symmetric, key);
25607 try {
25608 cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25609 } catch (err) {
25610 if (err.message === 'Authentication tag mismatch') {
25611 throw new Error('Incorrect key passphrase: ' + err.message);
25612 }
25613 throw err;
25614 }
25615 } else {
25616 const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
25617
25618 cleartext = cleartextWithHash.subarray(0, -20);
25619 const hash = await mod.hash.sha1(cleartext);
25620
25621 if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
25622 throw new Error('Incorrect key passphrase');
25623 }
25624 }
25625
25626 try {
25627 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
25628 this.privateParams = privateParams;
25629 } catch (err) {
25630 throw new Error('Error reading MPIs');
25631 }
25632 this.isEncrypted = false;
25633 this.keyMaterial = null;
25634 this.s2kUsage = 0;
25635 }
25636
25637 /**
25638 * Checks that the key parameters are consistent
25639 * @throws {Error} if validation was not successful
25640 * @async
25641 */
25642 async validate() {
25643 if (this.isDummy()) {
25644 return;
25645 }
25646
25647 if (!this.isDecrypted()) {
25648 throw new Error('Key is not decrypted');
25649 }
25650
25651 let validParams;
25652 try {
25653 // this can throw if some parameters are undefined
25654 validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams);
25655 } catch (_) {
25656 validParams = false;
25657 }
25658 if (!validParams) {
25659 throw new Error('Key is invalid');
25660 }
25661 }
25662
25663 async generate(bits, curve) {
25664 const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve);
25665 this.privateParams = privateParams;
25666 this.publicParams = publicParams;
25667 this.isEncrypted = false;
25668 }
25669
25670 /**
25671 * Clear private key parameters
25672 */
25673 clearPrivateParams() {
25674 if (this.isDummy()) {
25675 return;
25676 }
25677
25678 Object.keys(this.privateParams).forEach(name => {
25679 const param = this.privateParams[name];
25680 param.fill(0);
25681 delete this.privateParams[name];
25682 });
25683 this.privateParams = null;
25684 this.isEncrypted = true;
25685 }
25686}
25687
25688async function produceEncryptionKey(s2k, passphrase, algorithm) {
25689 const { keySize } = mod.getCipher(algorithm);
25690 return s2k.produceKey(passphrase, keySize);
25691}
25692
25693var emailAddresses = createCommonjsModule(function (module) {
25694// email-addresses.js - RFC 5322 email address parser
25695// v 3.1.0
25696//
25697// http://tools.ietf.org/html/rfc5322
25698//
25699// This library does not validate email addresses.
25700// emailAddresses attempts to parse addresses using the (fairly liberal)
25701// grammar specified in RFC 5322.
25702//
25703// email-addresses returns {
25704// ast: <an abstract syntax tree based on rfc5322>,
25705// addresses: [{
25706// node: <node in ast for this address>,
25707// name: <display-name>,
25708// address: <addr-spec>,
25709// local: <local-part>,
25710// domain: <domain>
25711// }, ...]
25712// }
25713//
25714// emailAddresses.parseOneAddress and emailAddresses.parseAddressList
25715// work as you might expect. Try it out.
25716//
25717// Many thanks to Dominic Sayers and his documentation on the is_email function,
25718// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
25719
25720(function (global) {
25721
25722function parse5322(opts) {
25723
25724 // tokenizing functions
25725
25726 function inStr() { return pos < len; }
25727 function curTok() { return parseString[pos]; }
25728 function getPos() { return pos; }
25729 function setPos(i) { pos = i; }
25730 function nextTok() { pos += 1; }
25731 function initialize() {
25732 pos = 0;
25733 len = parseString.length;
25734 }
25735
25736 // parser helper functions
25737
25738 function o(name, value) {
25739 return {
25740 name: name,
25741 tokens: value || "",
25742 semantic: value || "",
25743 children: []
25744 };
25745 }
25746
25747 function wrap(name, ast) {
25748 var n;
25749 if (ast === null) { return null; }
25750 n = o(name);
25751 n.tokens = ast.tokens;
25752 n.semantic = ast.semantic;
25753 n.children.push(ast);
25754 return n;
25755 }
25756
25757 function add(parent, child) {
25758 if (child !== null) {
25759 parent.tokens += child.tokens;
25760 parent.semantic += child.semantic;
25761 }
25762 parent.children.push(child);
25763 return parent;
25764 }
25765
25766 function compareToken(fxnCompare) {
25767 var tok;
25768 if (!inStr()) { return null; }
25769 tok = curTok();
25770 if (fxnCompare(tok)) {
25771 nextTok();
25772 return o('token', tok);
25773 }
25774 return null;
25775 }
25776
25777 function literal(lit) {
25778 return function literalFunc() {
25779 return wrap('literal', compareToken(function (tok) {
25780 return tok === lit;
25781 }));
25782 };
25783 }
25784
25785 function and() {
25786 var args = arguments;
25787 return function andFunc() {
25788 var i, s, result, start;
25789 start = getPos();
25790 s = o('and');
25791 for (i = 0; i < args.length; i += 1) {
25792 result = args[i]();
25793 if (result === null) {
25794 setPos(start);
25795 return null;
25796 }
25797 add(s, result);
25798 }
25799 return s;
25800 };
25801 }
25802
25803 function or() {
25804 var args = arguments;
25805 return function orFunc() {
25806 var i, result, start;
25807 start = getPos();
25808 for (i = 0; i < args.length; i += 1) {
25809 result = args[i]();
25810 if (result !== null) {
25811 return result;
25812 }
25813 setPos(start);
25814 }
25815 return null;
25816 };
25817 }
25818
25819 function opt(prod) {
25820 return function optFunc() {
25821 var result, start;
25822 start = getPos();
25823 result = prod();
25824 if (result !== null) {
25825 return result;
25826 }
25827 else {
25828 setPos(start);
25829 return o('opt');
25830 }
25831 };
25832 }
25833
25834 function invis(prod) {
25835 return function invisFunc() {
25836 var result = prod();
25837 if (result !== null) {
25838 result.semantic = "";
25839 }
25840 return result;
25841 };
25842 }
25843
25844 function colwsp(prod) {
25845 return function collapseSemanticWhitespace() {
25846 var result = prod();
25847 if (result !== null && result.semantic.length > 0) {
25848 result.semantic = " ";
25849 }
25850 return result;
25851 };
25852 }
25853
25854 function star(prod, minimum) {
25855 return function starFunc() {
25856 var s, result, count, start, min;
25857 start = getPos();
25858 s = o('star');
25859 count = 0;
25860 min = minimum === undefined ? 0 : minimum;
25861 while ((result = prod()) !== null) {
25862 count = count + 1;
25863 add(s, result);
25864 }
25865 if (count >= min) {
25866 return s;
25867 }
25868 else {
25869 setPos(start);
25870 return null;
25871 }
25872 };
25873 }
25874
25875 // One expects names to get normalized like this:
25876 // " First Last " -> "First Last"
25877 // "First Last" -> "First Last"
25878 // "First Last" -> "First Last"
25879 function collapseWhitespace(s) {
25880 return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
25881 }
25882
25883 // UTF-8 pseudo-production (RFC 6532)
25884 // RFC 6532 extends RFC 5322 productions to include UTF-8
25885 // using the following productions:
25886 // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
25887 // UTF8-2 = <Defined in Section 4 of RFC3629>
25888 // UTF8-3 = <Defined in Section 4 of RFC3629>
25889 // UTF8-4 = <Defined in Section 4 of RFC3629>
25890 //
25891 // For reference, the extended RFC 5322 productions are:
25892 // VCHAR =/ UTF8-non-ascii
25893 // ctext =/ UTF8-non-ascii
25894 // atext =/ UTF8-non-ascii
25895 // qtext =/ UTF8-non-ascii
25896 // dtext =/ UTF8-non-ascii
25897 function isUTF8NonAscii(tok) {
25898 // In JavaScript, we just deal directly with Unicode code points,
25899 // so we aren't checking individual bytes for UTF-8 encoding.
25900 // Just check that the character is non-ascii.
25901 return tok.charCodeAt(0) >= 128;
25902 }
25903
25904
25905 // common productions (RFC 5234)
25906 // http://tools.ietf.org/html/rfc5234
25907 // B.1. Core Rules
25908
25909 // CR = %x0D
25910 // ; carriage return
25911 function cr() { return wrap('cr', literal('\r')()); }
25912
25913 // CRLF = CR LF
25914 // ; Internet standard newline
25915 function crlf() { return wrap('crlf', and(cr, lf)()); }
25916
25917 // DQUOTE = %x22
25918 // ; " (Double Quote)
25919 function dquote() { return wrap('dquote', literal('"')()); }
25920
25921 // HTAB = %x09
25922 // ; horizontal tab
25923 function htab() { return wrap('htab', literal('\t')()); }
25924
25925 // LF = %x0A
25926 // ; linefeed
25927 function lf() { return wrap('lf', literal('\n')()); }
25928
25929 // SP = %x20
25930 function sp() { return wrap('sp', literal(' ')()); }
25931
25932 // VCHAR = %x21-7E
25933 // ; visible (printing) characters
25934 function vchar() {
25935 return wrap('vchar', compareToken(function vcharFunc(tok) {
25936 var code = tok.charCodeAt(0);
25937 var accept = (0x21 <= code && code <= 0x7E);
25938 if (opts.rfc6532) {
25939 accept = accept || isUTF8NonAscii(tok);
25940 }
25941 return accept;
25942 }));
25943 }
25944
25945 // WSP = SP / HTAB
25946 // ; white space
25947 function wsp() { return wrap('wsp', or(sp, htab)()); }
25948
25949
25950 // email productions (RFC 5322)
25951 // http://tools.ietf.org/html/rfc5322
25952 // 3.2.1. Quoted characters
25953
25954 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
25955 function quotedPair() {
25956 var qp = wrap('quoted-pair',
25957 or(
25958 and(literal('\\'), or(vchar, wsp)),
25959 obsQP
25960 )());
25961 if (qp === null) { return null; }
25962 // a quoted pair will be two characters, and the "\" character
25963 // should be semantically "invisible" (RFC 5322 3.2.1)
25964 qp.semantic = qp.semantic[1];
25965 return qp;
25966 }
25967
25968 // 3.2.2. Folding White Space and Comments
25969
25970 // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
25971 function fws() {
25972 return wrap('fws', or(
25973 obsFws,
25974 and(
25975 opt(and(
25976 star(wsp),
25977 invis(crlf)
25978 )),
25979 star(wsp, 1)
25980 )
25981 )());
25982 }
25983
25984 // ctext = %d33-39 / ; Printable US-ASCII
25985 // %d42-91 / ; characters not including
25986 // %d93-126 / ; "(", ")", or "\"
25987 // obs-ctext
25988 function ctext() {
25989 return wrap('ctext', or(
25990 function ctextFunc1() {
25991 return compareToken(function ctextFunc2(tok) {
25992 var code = tok.charCodeAt(0);
25993 var accept =
25994 (33 <= code && code <= 39) ||
25995 (42 <= code && code <= 91) ||
25996 (93 <= code && code <= 126);
25997 if (opts.rfc6532) {
25998 accept = accept || isUTF8NonAscii(tok);
25999 }
26000 return accept;
26001 });
26002 },
26003 obsCtext
26004 )());
26005 }
26006
26007 // ccontent = ctext / quoted-pair / comment
26008 function ccontent() {
26009 return wrap('ccontent', or(ctext, quotedPair, comment)());
26010 }
26011
26012 // comment = "(" *([FWS] ccontent) [FWS] ")"
26013 function comment() {
26014 return wrap('comment', and(
26015 literal('('),
26016 star(and(opt(fws), ccontent)),
26017 opt(fws),
26018 literal(')')
26019 )());
26020 }
26021
26022 // CFWS = (1*([FWS] comment) [FWS]) / FWS
26023 function cfws() {
26024 return wrap('cfws', or(
26025 and(
26026 star(
26027 and(opt(fws), comment),
26028 1
26029 ),
26030 opt(fws)
26031 ),
26032 fws
26033 )());
26034 }
26035
26036 // 3.2.3. Atom
26037
26038 //atext = ALPHA / DIGIT / ; Printable US-ASCII
26039 // "!" / "#" / ; characters not including
26040 // "$" / "%" / ; specials. Used for atoms.
26041 // "&" / "'" /
26042 // "*" / "+" /
26043 // "-" / "/" /
26044 // "=" / "?" /
26045 // "^" / "_" /
26046 // "`" / "{" /
26047 // "|" / "}" /
26048 // "~"
26049 function atext() {
26050 return wrap('atext', compareToken(function atextFunc(tok) {
26051 var accept =
26052 ('a' <= tok && tok <= 'z') ||
26053 ('A' <= tok && tok <= 'Z') ||
26054 ('0' <= tok && tok <= '9') ||
26055 (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
26056 '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
26057 if (opts.rfc6532) {
26058 accept = accept || isUTF8NonAscii(tok);
26059 }
26060 return accept;
26061 }));
26062 }
26063
26064 // atom = [CFWS] 1*atext [CFWS]
26065 function atom() {
26066 return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
26067 }
26068
26069 // dot-atom-text = 1*atext *("." 1*atext)
26070 function dotAtomText() {
26071 var s, maybeText;
26072 s = wrap('dot-atom-text', star(atext, 1)());
26073 if (s === null) { return s; }
26074 maybeText = star(and(literal('.'), star(atext, 1)))();
26075 if (maybeText !== null) {
26076 add(s, maybeText);
26077 }
26078 return s;
26079 }
26080
26081 // dot-atom = [CFWS] dot-atom-text [CFWS]
26082 function dotAtom() {
26083 return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
26084 }
26085
26086 // 3.2.4. Quoted Strings
26087
26088 // qtext = %d33 / ; Printable US-ASCII
26089 // %d35-91 / ; characters not including
26090 // %d93-126 / ; "\" or the quote character
26091 // obs-qtext
26092 function qtext() {
26093 return wrap('qtext', or(
26094 function qtextFunc1() {
26095 return compareToken(function qtextFunc2(tok) {
26096 var code = tok.charCodeAt(0);
26097 var accept =
26098 (33 === code) ||
26099 (35 <= code && code <= 91) ||
26100 (93 <= code && code <= 126);
26101 if (opts.rfc6532) {
26102 accept = accept || isUTF8NonAscii(tok);
26103 }
26104 return accept;
26105 });
26106 },
26107 obsQtext
26108 )());
26109 }
26110
26111 // qcontent = qtext / quoted-pair
26112 function qcontent() {
26113 return wrap('qcontent', or(qtext, quotedPair)());
26114 }
26115
26116 // quoted-string = [CFWS]
26117 // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
26118 // [CFWS]
26119 function quotedString() {
26120 return wrap('quoted-string', and(
26121 invis(opt(cfws)),
26122 invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
26123 invis(opt(cfws))
26124 )());
26125 }
26126
26127 // 3.2.5 Miscellaneous Tokens
26128
26129 // word = atom / quoted-string
26130 function word() {
26131 return wrap('word', or(atom, quotedString)());
26132 }
26133
26134 // phrase = 1*word / obs-phrase
26135 function phrase() {
26136 return wrap('phrase', or(obsPhrase, star(word, 1))());
26137 }
26138
26139 // 3.4. Address Specification
26140 // address = mailbox / group
26141 function address() {
26142 return wrap('address', or(mailbox, group)());
26143 }
26144
26145 // mailbox = name-addr / addr-spec
26146 function mailbox() {
26147 return wrap('mailbox', or(nameAddr, addrSpec)());
26148 }
26149
26150 // name-addr = [display-name] angle-addr
26151 function nameAddr() {
26152 return wrap('name-addr', and(opt(displayName), angleAddr)());
26153 }
26154
26155 // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
26156 // obs-angle-addr
26157 function angleAddr() {
26158 return wrap('angle-addr', or(
26159 and(
26160 invis(opt(cfws)),
26161 literal('<'),
26162 addrSpec,
26163 literal('>'),
26164 invis(opt(cfws))
26165 ),
26166 obsAngleAddr
26167 )());
26168 }
26169
26170 // group = display-name ":" [group-list] ";" [CFWS]
26171 function group() {
26172 return wrap('group', and(
26173 displayName,
26174 literal(':'),
26175 opt(groupList),
26176 literal(';'),
26177 invis(opt(cfws))
26178 )());
26179 }
26180
26181 // display-name = phrase
26182 function displayName() {
26183 return wrap('display-name', function phraseFixedSemantic() {
26184 var result = phrase();
26185 if (result !== null) {
26186 result.semantic = collapseWhitespace(result.semantic);
26187 }
26188 return result;
26189 }());
26190 }
26191
26192 // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
26193 function mailboxList() {
26194 return wrap('mailbox-list', or(
26195 and(
26196 mailbox,
26197 star(and(literal(','), mailbox))
26198 ),
26199 obsMboxList
26200 )());
26201 }
26202
26203 // address-list = (address *("," address)) / obs-addr-list
26204 function addressList() {
26205 return wrap('address-list', or(
26206 and(
26207 address,
26208 star(and(literal(','), address))
26209 ),
26210 obsAddrList
26211 )());
26212 }
26213
26214 // group-list = mailbox-list / CFWS / obs-group-list
26215 function groupList() {
26216 return wrap('group-list', or(
26217 mailboxList,
26218 invis(cfws),
26219 obsGroupList
26220 )());
26221 }
26222
26223 // 3.4.1 Addr-Spec Specification
26224
26225 // local-part = dot-atom / quoted-string / obs-local-part
26226 function localPart() {
26227 // note: quoted-string, dotAtom are proper subsets of obs-local-part
26228 // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
26229 return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
26230 }
26231
26232 // dtext = %d33-90 / ; Printable US-ASCII
26233 // %d94-126 / ; characters not including
26234 // obs-dtext ; "[", "]", or "\"
26235 function dtext() {
26236 return wrap('dtext', or(
26237 function dtextFunc1() {
26238 return compareToken(function dtextFunc2(tok) {
26239 var code = tok.charCodeAt(0);
26240 var accept =
26241 (33 <= code && code <= 90) ||
26242 (94 <= code && code <= 126);
26243 if (opts.rfc6532) {
26244 accept = accept || isUTF8NonAscii(tok);
26245 }
26246 return accept;
26247 });
26248 },
26249 obsDtext
26250 )()
26251 );
26252 }
26253
26254 // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
26255 function domainLiteral() {
26256 return wrap('domain-literal', and(
26257 invis(opt(cfws)),
26258 literal('['),
26259 star(and(opt(fws), dtext)),
26260 opt(fws),
26261 literal(']'),
26262 invis(opt(cfws))
26263 )());
26264 }
26265
26266 // domain = dot-atom / domain-literal / obs-domain
26267 function domain() {
26268 return wrap('domain', function domainCheckTLD() {
26269 var result = or(obsDomain, dotAtom, domainLiteral)();
26270 if (opts.rejectTLD) {
26271 if (result && result.semantic && result.semantic.indexOf('.') < 0) {
26272 return null;
26273 }
26274 }
26275 // strip all whitespace from domains
26276 if (result) {
26277 result.semantic = result.semantic.replace(/\s+/g, '');
26278 }
26279 return result;
26280 }());
26281 }
26282
26283 // addr-spec = local-part "@" domain
26284 function addrSpec() {
26285 return wrap('addr-spec', and(
26286 localPart, literal('@'), domain
26287 )());
26288 }
26289
26290 // 3.6.2 Originator Fields
26291 // Below we only parse the field body, not the name of the field
26292 // like "From:", "Sender:", or "Reply-To:". Other libraries that
26293 // parse email headers can parse those and defer to these productions
26294 // for the "RFC 5322" part.
26295
26296 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26297 // from = "From:" (mailbox-list / address-list) CRLF
26298 function fromSpec() {
26299 return wrap('from', or(
26300 mailboxList,
26301 addressList
26302 )());
26303 }
26304
26305 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26306 // sender = "Sender:" (mailbox / address) CRLF
26307 function senderSpec() {
26308 return wrap('sender', or(
26309 mailbox,
26310 address
26311 )());
26312 }
26313
26314 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26315 // reply-to = "Reply-To:" address-list CRLF
26316 function replyToSpec() {
26317 return wrap('reply-to', addressList());
26318 }
26319
26320 // 4.1. Miscellaneous Obsolete Tokens
26321
26322 // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
26323 // %d11 / ; characters that do not
26324 // %d12 / ; include the carriage
26325 // %d14-31 / ; return, line feed, and
26326 // %d127 ; white space characters
26327 function obsNoWsCtl() {
26328 return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
26329 var code = tok.charCodeAt(0);
26330 return ((1 <= code && code <= 8) ||
26331 (11 === code || 12 === code) ||
26332 (14 <= code && code <= 31) ||
26333 (127 === code));
26334 }));
26335 }
26336
26337 // obs-ctext = obs-NO-WS-CTL
26338 function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
26339
26340 // obs-qtext = obs-NO-WS-CTL
26341 function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
26342
26343 // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
26344 function obsQP() {
26345 return opts.strict ? null : wrap('obs-qp', and(
26346 literal('\\'),
26347 or(literal('\0'), obsNoWsCtl, lf, cr)
26348 )());
26349 }
26350
26351 // obs-phrase = word *(word / "." / CFWS)
26352 function obsPhrase() {
26353 if (opts.strict ) return null;
26354 return opts.atInDisplayName ? wrap('obs-phrase', and(
26355 word,
26356 star(or(word, literal('.'), literal('@'), colwsp(cfws)))
26357 )()) :
26358 wrap('obs-phrase', and(
26359 word,
26360 star(or(word, literal('.'), colwsp(cfws)))
26361 )());
26362 }
26363
26364 // 4.2. Obsolete Folding White Space
26365
26366 // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
26367 // obs-FWS = 1*([CRLF] WSP)
26368 function obsFws() {
26369 return opts.strict ? null : wrap('obs-FWS', star(
26370 and(invis(opt(crlf)), wsp),
26371 1
26372 )());
26373 }
26374
26375 // 4.4. Obsolete Addressing
26376
26377 // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
26378 function obsAngleAddr() {
26379 return opts.strict ? null : wrap('obs-angle-addr', and(
26380 invis(opt(cfws)),
26381 literal('<'),
26382 obsRoute,
26383 addrSpec,
26384 literal('>'),
26385 invis(opt(cfws))
26386 )());
26387 }
26388
26389 // obs-route = obs-domain-list ":"
26390 function obsRoute() {
26391 return opts.strict ? null : wrap('obs-route', and(
26392 obsDomainList,
26393 literal(':')
26394 )());
26395 }
26396
26397 // obs-domain-list = *(CFWS / ",") "@" domain
26398 // *("," [CFWS] ["@" domain])
26399 function obsDomainList() {
26400 return opts.strict ? null : wrap('obs-domain-list', and(
26401 star(or(invis(cfws), literal(','))),
26402 literal('@'),
26403 domain,
26404 star(and(
26405 literal(','),
26406 invis(opt(cfws)),
26407 opt(and(literal('@'), domain))
26408 ))
26409 )());
26410 }
26411
26412 // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
26413 function obsMboxList() {
26414 return opts.strict ? null : wrap('obs-mbox-list', and(
26415 star(and(
26416 invis(opt(cfws)),
26417 literal(',')
26418 )),
26419 mailbox,
26420 star(and(
26421 literal(','),
26422 opt(and(
26423 mailbox,
26424 invis(cfws)
26425 ))
26426 ))
26427 )());
26428 }
26429
26430 // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
26431 function obsAddrList() {
26432 return opts.strict ? null : wrap('obs-addr-list', and(
26433 star(and(
26434 invis(opt(cfws)),
26435 literal(',')
26436 )),
26437 address,
26438 star(and(
26439 literal(','),
26440 opt(and(
26441 address,
26442 invis(cfws)
26443 ))
26444 ))
26445 )());
26446 }
26447
26448 // obs-group-list = 1*([CFWS] ",") [CFWS]
26449 function obsGroupList() {
26450 return opts.strict ? null : wrap('obs-group-list', and(
26451 star(and(
26452 invis(opt(cfws)),
26453 literal(',')
26454 ), 1),
26455 invis(opt(cfws))
26456 )());
26457 }
26458
26459 // obs-local-part = word *("." word)
26460 function obsLocalPart() {
26461 return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
26462 }
26463
26464 // obs-domain = atom *("." atom)
26465 function obsDomain() {
26466 return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
26467 }
26468
26469 // obs-dtext = obs-NO-WS-CTL / quoted-pair
26470 function obsDtext() {
26471 return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
26472 }
26473
26474 /////////////////////////////////////////////////////
26475
26476 // ast analysis
26477
26478 function findNode(name, root) {
26479 var i, stack, node;
26480 if (root === null || root === undefined) { return null; }
26481 stack = [root];
26482 while (stack.length > 0) {
26483 node = stack.pop();
26484 if (node.name === name) {
26485 return node;
26486 }
26487 for (i = node.children.length - 1; i >= 0; i -= 1) {
26488 stack.push(node.children[i]);
26489 }
26490 }
26491 return null;
26492 }
26493
26494 function findAllNodes(name, root) {
26495 var i, stack, node, result;
26496 if (root === null || root === undefined) { return null; }
26497 stack = [root];
26498 result = [];
26499 while (stack.length > 0) {
26500 node = stack.pop();
26501 if (node.name === name) {
26502 result.push(node);
26503 }
26504 for (i = node.children.length - 1; i >= 0; i -= 1) {
26505 stack.push(node.children[i]);
26506 }
26507 }
26508 return result;
26509 }
26510
26511 function findAllNodesNoChildren(names, root) {
26512 var i, stack, node, result, namesLookup;
26513 if (root === null || root === undefined) { return null; }
26514 stack = [root];
26515 result = [];
26516 namesLookup = {};
26517 for (i = 0; i < names.length; i += 1) {
26518 namesLookup[names[i]] = true;
26519 }
26520
26521 while (stack.length > 0) {
26522 node = stack.pop();
26523 if (node.name in namesLookup) {
26524 result.push(node);
26525 // don't look at children (hence findAllNodesNoChildren)
26526 } else {
26527 for (i = node.children.length - 1; i >= 0; i -= 1) {
26528 stack.push(node.children[i]);
26529 }
26530 }
26531 }
26532 return result;
26533 }
26534
26535 function giveResult(ast) {
26536 var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
26537 if (ast === null) {
26538 return null;
26539 }
26540 addresses = [];
26541
26542 // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
26543 groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
26544 for (i = 0; i < groupsAndMailboxes.length; i += 1) {
26545 groupOrMailbox = groupsAndMailboxes[i];
26546 if (groupOrMailbox.name === 'group') {
26547 addresses.push(giveResultGroup(groupOrMailbox));
26548 } else if (groupOrMailbox.name === 'mailbox') {
26549 addresses.push(giveResultMailbox(groupOrMailbox));
26550 }
26551 }
26552
26553 result = {
26554 ast: ast,
26555 addresses: addresses,
26556 };
26557 if (opts.simple) {
26558 result = simplifyResult(result);
26559 }
26560 if (opts.oneResult) {
26561 return oneResult(result);
26562 }
26563 if (opts.simple) {
26564 return result && result.addresses;
26565 } else {
26566 return result;
26567 }
26568 }
26569
26570 function giveResultGroup(group) {
26571 var i;
26572 var groupName = findNode('display-name', group);
26573 var groupResultMailboxes = [];
26574 var mailboxes = findAllNodesNoChildren(['mailbox'], group);
26575 for (i = 0; i < mailboxes.length; i += 1) {
26576 groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
26577 }
26578 return {
26579 node: group,
26580 parts: {
26581 name: groupName,
26582 },
26583 type: group.name, // 'group'
26584 name: grabSemantic(groupName),
26585 addresses: groupResultMailboxes,
26586 };
26587 }
26588
26589 function giveResultMailbox(mailbox) {
26590 var name = findNode('display-name', mailbox);
26591 var aspec = findNode('addr-spec', mailbox);
26592 var cfws = findAllNodes('cfws', mailbox);
26593 var comments = findAllNodesNoChildren(['comment'], mailbox);
26594
26595
26596 var local = findNode('local-part', aspec);
26597 var domain = findNode('domain', aspec);
26598 return {
26599 node: mailbox,
26600 parts: {
26601 name: name,
26602 address: aspec,
26603 local: local,
26604 domain: domain,
26605 comments: cfws
26606 },
26607 type: mailbox.name, // 'mailbox'
26608 name: grabSemantic(name),
26609 address: grabSemantic(aspec),
26610 local: grabSemantic(local),
26611 domain: grabSemantic(domain),
26612 comments: concatComments(comments),
26613 groupName: grabSemantic(mailbox.groupName),
26614 };
26615 }
26616
26617 function grabSemantic(n) {
26618 return n !== null && n !== undefined ? n.semantic : null;
26619 }
26620
26621 function simplifyResult(result) {
26622 var i;
26623 if (result && result.addresses) {
26624 for (i = 0; i < result.addresses.length; i += 1) {
26625 delete result.addresses[i].node;
26626 }
26627 }
26628 return result;
26629 }
26630
26631 function concatComments(comments) {
26632 var result = '';
26633 if (comments) {
26634 for (var i = 0; i < comments.length; i += 1) {
26635 result += grabSemantic(comments[i]);
26636 }
26637 }
26638 return result;
26639 }
26640
26641 function oneResult(result) {
26642 if (!result) { return null; }
26643 if (!opts.partial && result.addresses.length > 1) { return null; }
26644 return result.addresses && result.addresses[0];
26645 }
26646
26647 /////////////////////////////////////////////////////
26648
26649 var parseString, pos, len, parsed, startProduction;
26650
26651 opts = handleOpts(opts, {});
26652 if (opts === null) { return null; }
26653
26654 parseString = opts.input;
26655
26656 startProduction = {
26657 'address': address,
26658 'address-list': addressList,
26659 'angle-addr': angleAddr,
26660 'from': fromSpec,
26661 'group': group,
26662 'mailbox': mailbox,
26663 'mailbox-list': mailboxList,
26664 'reply-to': replyToSpec,
26665 'sender': senderSpec,
26666 }[opts.startAt] || addressList;
26667
26668 if (!opts.strict) {
26669 initialize();
26670 opts.strict = true;
26671 parsed = startProduction(parseString);
26672 if (opts.partial || !inStr()) {
26673 return giveResult(parsed);
26674 }
26675 opts.strict = false;
26676 }
26677
26678 initialize();
26679 parsed = startProduction(parseString);
26680 if (!opts.partial && inStr()) { return null; }
26681 return giveResult(parsed);
26682}
26683
26684function parseOneAddressSimple(opts) {
26685 return parse5322(handleOpts(opts, {
26686 oneResult: true,
26687 rfc6532: true,
26688 simple: true,
26689 startAt: 'address-list',
26690 }));
26691}
26692
26693function parseAddressListSimple(opts) {
26694 return parse5322(handleOpts(opts, {
26695 rfc6532: true,
26696 simple: true,
26697 startAt: 'address-list',
26698 }));
26699}
26700
26701function parseFromSimple(opts) {
26702 return parse5322(handleOpts(opts, {
26703 rfc6532: true,
26704 simple: true,
26705 startAt: 'from',
26706 }));
26707}
26708
26709function parseSenderSimple(opts) {
26710 return parse5322(handleOpts(opts, {
26711 oneResult: true,
26712 rfc6532: true,
26713 simple: true,
26714 startAt: 'sender',
26715 }));
26716}
26717
26718function parseReplyToSimple(opts) {
26719 return parse5322(handleOpts(opts, {
26720 rfc6532: true,
26721 simple: true,
26722 startAt: 'reply-to',
26723 }));
26724}
26725
26726function handleOpts(opts, defs) {
26727 function isString(str) {
26728 return Object.prototype.toString.call(str) === '[object String]';
26729 }
26730
26731 function isObject(o) {
26732 return o === Object(o);
26733 }
26734
26735 function isNullUndef(o) {
26736 return o === null || o === undefined;
26737 }
26738
26739 var defaults, o;
26740
26741 if (isString(opts)) {
26742 opts = { input: opts };
26743 } else if (!isObject(opts)) {
26744 return null;
26745 }
26746
26747 if (!isString(opts.input)) { return null; }
26748 if (!defs) { return null; }
26749
26750 defaults = {
26751 oneResult: false,
26752 partial: false,
26753 rejectTLD: false,
26754 rfc6532: false,
26755 simple: false,
26756 startAt: 'address-list',
26757 strict: false,
26758 atInDisplayName: false
26759 };
26760
26761 for (o in defaults) {
26762 if (isNullUndef(opts[o])) {
26763 opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
26764 }
26765 }
26766 return opts;
26767}
26768
26769parse5322.parseOneAddress = parseOneAddressSimple;
26770parse5322.parseAddressList = parseAddressListSimple;
26771parse5322.parseFrom = parseFromSimple;
26772parse5322.parseSender = parseSenderSimple;
26773parse5322.parseReplyTo = parseReplyToSimple;
26774
26775{
26776 module.exports = parse5322;
26777}
26778
26779}());
26780});
26781
26782// GPG4Browsers - An OpenPGP implementation in javascript
26783
26784/**
26785 * Implementation of the User ID Packet (Tag 13)
26786 *
26787 * A User ID packet consists of UTF-8 text that is intended to represent
26788 * the name and email address of the key holder. By convention, it
26789 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
26790 * restrictions on its content. The packet length in the header
26791 * specifies the length of the User ID.
26792 */
26793class UserIDPacket {
26794 static get tag() {
26795 return enums.packet.userID;
26796 }
26797
26798 constructor() {
26799 /** A string containing the user id. Usually in the form
26800 * John Doe <john@example.com>
26801 * @type {String}
26802 */
26803 this.userID = '';
26804
26805 this.name = '';
26806 this.email = '';
26807 this.comment = '';
26808 }
26809
26810 /**
26811 * Create UserIDPacket instance from object
26812 * @param {Object} userID - Object specifying userID name, email and comment
26813 * @returns {UserIDPacket}
26814 * @static
26815 */
26816 static fromObject(userID) {
26817 if (util.isString(userID) ||
26818 (userID.name && !util.isString(userID.name)) ||
26819 (userID.email && !util.isEmailAddress(userID.email)) ||
26820 (userID.comment && !util.isString(userID.comment))) {
26821 throw new Error('Invalid user ID format');
26822 }
26823 const packet = new UserIDPacket();
26824 Object.assign(packet, userID);
26825 const components = [];
26826 if (packet.name) components.push(packet.name);
26827 if (packet.comment) components.push(`(${packet.comment})`);
26828 if (packet.email) components.push(`<${packet.email}>`);
26829 packet.userID = components.join(' ');
26830 return packet;
26831 }
26832
26833 /**
26834 * Parsing function for a user id packet (tag 13).
26835 * @param {Uint8Array} input - Payload of a tag 13 packet
26836 */
26837 read(bytes, config = defaultConfig) {
26838 const userID = util.decodeUTF8(bytes);
26839 if (userID.length > config.maxUserIDLength) {
26840 throw new Error('User ID string is too long');
26841 }
26842 try {
26843 const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });
26844 this.comment = comments.replace(/^\(|\)$/g, '');
26845 this.name = name;
26846 this.email = email;
26847 } catch (e) {}
26848 this.userID = userID;
26849 }
26850
26851 /**
26852 * Creates a binary representation of the user id packet
26853 * @returns {Uint8Array} Binary representation.
26854 */
26855 write() {
26856 return util.encodeUTF8(this.userID);
26857 }
26858
26859 equals(otherUserID) {
26860 return otherUserID && otherUserID.userID === this.userID;
26861 }
26862}
26863
26864// GPG4Browsers - An OpenPGP implementation in javascript
26865
26866/**
26867 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
26868 * Key packet and has exactly the same format.
26869 * @extends SecretKeyPacket
26870 */
26871class SecretSubkeyPacket extends SecretKeyPacket {
26872 static get tag() {
26873 return enums.packet.secretSubkey;
26874 }
26875
26876 /**
26877 * @param {Date} [date] - Creation date
26878 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26879 */
26880 constructor(date = new Date(), config = defaultConfig) {
26881 super(date, config);
26882 }
26883}
26884
26885/**
26886 * Implementation of the Trust Packet (Tag 12)
26887 *
26888 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
26889 * The Trust packet is used only within keyrings and is not normally
26890 * exported. Trust packets contain data that record the user's
26891 * specifications of which key holders are trustworthy introducers,
26892 * along with other information that implementing software uses for
26893 * trust information. The format of Trust packets is defined by a given
26894 * implementation.
26895 *
26896 * Trust packets SHOULD NOT be emitted to output streams that are
26897 * transferred to other users, and they SHOULD be ignored on any input
26898 * other than local keyring files.
26899 */
26900class TrustPacket {
26901 static get tag() {
26902 return enums.packet.trust;
26903 }
26904
26905 /**
26906 * Parsing function for a trust packet (tag 12).
26907 * Currently not implemented as we ignore trust packets
26908 */
26909 read() {
26910 throw new UnsupportedError('Trust packets are not supported');
26911 }
26912
26913 write() {
26914 throw new UnsupportedError('Trust packets are not supported');
26915 }
26916}
26917
26918// GPG4Browsers - An OpenPGP implementation in javascript
26919
26920// A Signature can contain the following packets
26921const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
26922
26923/**
26924 * Class that represents an OpenPGP signature.
26925 */
26926class Signature {
26927 /**
26928 * @param {PacketList} packetlist - The signature packets
26929 */
26930 constructor(packetlist) {
26931 this.packets = packetlist || new PacketList();
26932 }
26933
26934 /**
26935 * Returns binary encoded signature
26936 * @returns {ReadableStream<Uint8Array>} Binary signature.
26937 */
26938 write() {
26939 return this.packets.write();
26940 }
26941
26942 /**
26943 * Returns ASCII armored text of signature
26944 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26945 * @returns {ReadableStream<String>} ASCII armor.
26946 */
26947 armor(config = defaultConfig) {
26948 return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);
26949 }
26950
26951 /**
26952 * Returns an array of KeyIDs of all of the issuers who created this signature
26953 * @returns {Array<KeyID>} The Key IDs of the signing keys
26954 */
26955 getSigningKeyIDs() {
26956 return this.packets.map(packet => packet.issuerKeyID);
26957 }
26958}
26959
26960/**
26961 * reads an (optionally armored) OpenPGP signature and returns a signature object
26962 * @param {Object} options
26963 * @param {String} [options.armoredSignature] - Armored signature to be parsed
26964 * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed
26965 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
26966 * @returns {Promise<Signature>} New signature object.
26967 * @async
26968 * @static
26969 */
26970async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {
26971 config = { ...defaultConfig, ...config };
26972 let input = armoredSignature || binarySignature;
26973 if (!input) {
26974 throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
26975 }
26976 if (armoredSignature && !util.isString(armoredSignature)) {
26977 throw new Error('readSignature: options.armoredSignature must be a string');
26978 }
26979 if (binarySignature && !util.isUint8Array(binarySignature)) {
26980 throw new Error('readSignature: options.binarySignature must be a Uint8Array');
26981 }
26982 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
26983
26984 if (armoredSignature) {
26985 const { type, data } = await unarmor(input, config);
26986 if (type !== enums.armor.signature) {
26987 throw new Error('Armored text not of type signature');
26988 }
26989 input = data;
26990 }
26991 const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config);
26992 return new Signature(packetlist);
26993}
26994
26995/**
26996 * @fileoverview Provides helpers methods for key module
26997 * @module key/helper
26998 * @private
26999 */
27000
27001async function generateSecretSubkey(options, config) {
27002 const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
27003 secretSubkeyPacket.packets = null;
27004 secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27005 await secretSubkeyPacket.generate(options.rsaBits, options.curve);
27006 await secretSubkeyPacket.computeFingerprintAndKeyID();
27007 return secretSubkeyPacket;
27008}
27009
27010async function generateSecretKey(options, config) {
27011 const secretKeyPacket = new SecretKeyPacket(options.date, config);
27012 secretKeyPacket.packets = null;
27013 secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27014 await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
27015 await secretKeyPacket.computeFingerprintAndKeyID();
27016 return secretKeyPacket;
27017}
27018
27019/**
27020 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
27021 * @param {Array<SignaturePacket>} signatures - List of signatures
27022 * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature
27023 * @param {Date} date - Use the given date instead of the current time
27024 * @param {Object} config - full configuration
27025 * @returns {Promise<SignaturePacket>} The latest valid signature.
27026 * @async
27027 */
27028async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {
27029 let latestValid;
27030 let exception;
27031 for (let i = signatures.length - 1; i >= 0; i--) {
27032 try {
27033 if (
27034 (!latestValid || signatures[i].created >= latestValid.created)
27035 ) {
27036 await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);
27037 latestValid = signatures[i];
27038 }
27039 } catch (e) {
27040 exception = e;
27041 }
27042 }
27043 if (!latestValid) {
27044 throw util.wrapError(
27045 `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`
27046 .replace('certGeneric ', 'self-')
27047 .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase())
27048 , exception);
27049 }
27050 return latestValid;
27051}
27052
27053function isDataExpired(keyPacket, signature, date = new Date()) {
27054 const normDate = util.normalizeDate(date);
27055 if (normDate !== null) {
27056 const expirationTime = getKeyExpirationTime(keyPacket, signature);
27057 return !(keyPacket.created <= normDate && normDate < expirationTime);
27058 }
27059 return false;
27060}
27061
27062/**
27063 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
27064 * @param {SecretSubkeyPacket} subkey - Subkey key packet
27065 * @param {SecretKeyPacket} primaryKey - Primary key packet
27066 * @param {Object} options
27067 * @param {Object} config - Full configuration
27068 */
27069async function createBindingSignature(subkey, primaryKey, options, config) {
27070 const dataToSign = {};
27071 dataToSign.key = primaryKey;
27072 dataToSign.bind = subkey;
27073 const subkeySignaturePacket = new SignaturePacket();
27074 subkeySignaturePacket.signatureType = enums.signature.subkeyBinding;
27075 subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm;
27076 subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, subkey, undefined, undefined, config);
27077 if (options.sign) {
27078 subkeySignaturePacket.keyFlags = [enums.keyFlags.signData];
27079 subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
27080 signatureType: enums.signature.keyBinding
27081 }, options.date, undefined, undefined, config);
27082 } else {
27083 subkeySignaturePacket.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
27084 }
27085 if (options.keyExpirationTime > 0) {
27086 subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime;
27087 subkeySignaturePacket.keyNeverExpires = false;
27088 }
27089 await subkeySignaturePacket.sign(primaryKey, dataToSign, options.date);
27090 return subkeySignaturePacket;
27091}
27092
27093/**
27094 * Returns the preferred signature hash algorithm of a key
27095 * @param {Key} [key] - The key to get preferences from
27096 * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing
27097 * @param {Date} [date] - Use the given date for verification instead of the current time
27098 * @param {Object} [userID] - User ID
27099 * @param {Object} config - full configuration
27100 * @returns {Promise<enums.hash>}
27101 * @async
27102 */
27103async function getPreferredHashAlgo$1(key, keyPacket, date = new Date(), userID = {}, config) {
27104 let hashAlgo = config.preferredHashAlgorithm;
27105 let prefAlgo = hashAlgo;
27106 if (key) {
27107 const primaryUser = await key.getPrimaryUser(date, userID, config);
27108 if (primaryUser.selfCertification.preferredHashAlgorithms) {
27109 [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;
27110 hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27111 prefAlgo : hashAlgo;
27112 }
27113 }
27114 switch (Object.getPrototypeOf(keyPacket)) {
27115 case SecretKeyPacket.prototype:
27116 case PublicKeyPacket.prototype:
27117 case SecretSubkeyPacket.prototype:
27118 case PublicSubkeyPacket.prototype:
27119 switch (keyPacket.algorithm) {
27120 case enums.publicKey.ecdh:
27121 case enums.publicKey.ecdsa:
27122 case enums.publicKey.eddsa:
27123 prefAlgo = mod.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid);
27124 }
27125 }
27126 return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27127 prefAlgo : hashAlgo;
27128}
27129
27130/**
27131 * Returns the preferred symmetric/aead/compression algorithm for a set of keys
27132 * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return
27133 * @param {Array<Key>} [keys] - Set of keys
27134 * @param {Date} [date] - Use the given date for verification instead of the current time
27135 * @param {Array} [userIDs] - User IDs
27136 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27137 * @returns {Promise<module:enums.symmetric|aead|compression>} Preferred algorithm
27138 * @async
27139 */
27140async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {
27141 const defaultAlgo = { // these are all must-implement in rfc4880bis
27142 'symmetric': enums.symmetric.aes128,
27143 'aead': enums.aead.eax,
27144 'compression': enums.compression.uncompressed
27145 }[type];
27146 const preferredSenderAlgo = {
27147 'symmetric': config.preferredSymmetricAlgorithm,
27148 'aead': config.preferredAEADAlgorithm,
27149 'compression': config.preferredCompressionAlgorithm
27150 }[type];
27151 const prefPropertyName = {
27152 'symmetric': 'preferredSymmetricAlgorithms',
27153 'aead': 'preferredAEADAlgorithms',
27154 'compression': 'preferredCompressionAlgorithms'
27155 }[type];
27156
27157 // if preferredSenderAlgo appears in the prefs of all recipients, we pick it
27158 // otherwise we use the default algo
27159 // if no keys are available, preferredSenderAlgo is returned
27160 const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {
27161 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
27162 const recipientPrefs = primaryUser.selfCertification[prefPropertyName];
27163 return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;
27164 }));
27165 return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;
27166}
27167
27168/**
27169 * Create signature packet
27170 * @param {Object} dataToSign - Contains packets to be signed
27171 * @param {PrivateKey} privateKey - key to get preferences from
27172 * @param {SecretKeyPacket|
27173 * SecretSubkeyPacket} signingKeyPacket secret key packet for signing
27174 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
27175 * @param {Date} [date] - Override the creationtime of the signature
27176 * @param {Object} [userID] - User ID
27177 * @param {Object} [detached] - Whether to create a detached signature packet
27178 * @param {Object} config - full configuration
27179 * @returns {Promise<SignaturePacket>} Signature packet.
27180 */
27181async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, detached = false, config) {
27182 if (signingKeyPacket.isDummy()) {
27183 throw new Error('Cannot sign with a gnu-dummy key.');
27184 }
27185 if (!signingKeyPacket.isDecrypted()) {
27186 throw new Error('Signing key is not decrypted.');
27187 }
27188 const signaturePacket = new SignaturePacket();
27189 Object.assign(signaturePacket, signatureProperties);
27190 signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
27191 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(privateKey, signingKeyPacket, date, userID, config);
27192 await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);
27193 return signaturePacket;
27194}
27195
27196/**
27197 * Merges signatures from source[attr] to dest[attr]
27198 * @param {Object} source
27199 * @param {Object} dest
27200 * @param {String} attr
27201 * @param {Date} [date] - date to use for signature expiration check, instead of the current time
27202 * @param {Function} [checkFn] - signature only merged if true
27203 */
27204async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {
27205 source = source[attr];
27206 if (source) {
27207 if (!dest[attr].length) {
27208 dest[attr] = source;
27209 } else {
27210 await Promise.all(source.map(async function(sourceSig) {
27211 if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&
27212 !dest[attr].some(function(destSig) {
27213 return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());
27214 })) {
27215 dest[attr].push(sourceSig);
27216 }
27217 }));
27218 }
27219 }
27220}
27221
27222/**
27223 * Checks if a given certificate or binding signature is revoked
27224 * @param {SecretKeyPacket|
27225 * PublicKeyPacket} primaryKey The primary key packet
27226 * @param {Object} dataToVerify - The data to check
27227 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
27228 * @param {SignaturePacket} signature - The certificate or signature to check
27229 * @param {PublicSubkeyPacket|
27230 * SecretSubkeyPacket|
27231 * PublicKeyPacket|
27232 * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key
27233 * @param {Date} date - Use the given date instead of the current time
27234 * @param {Object} config - Full configuration
27235 * @returns {Promise<Boolean>} True if the signature revokes the data.
27236 * @async
27237 */
27238async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
27239 key = key || primaryKey;
27240 const revocationKeyIDs = [];
27241 await Promise.all(revocations.map(async function(revocationSignature) {
27242 try {
27243 if (
27244 // Note: a third-party revocation signature could legitimately revoke a
27245 // self-signature if the signature has an authorized revocation key.
27246 // However, we don't support passing authorized revocation keys, nor
27247 // verifying such revocation signatures. Instead, we indicate an error
27248 // when parsing a key with an authorized revocation key, and ignore
27249 // third-party revocation signatures here. (It could also be revoking a
27250 // third-party key certification, which should only affect
27251 // `verifyAllCertifications`.)
27252 !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)
27253 ) {
27254 await revocationSignature.verify(
27255 key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config
27256 );
27257
27258 // TODO get an identifier of the revoked object instead
27259 revocationKeyIDs.push(revocationSignature.issuerKeyID);
27260 }
27261 } catch (e) {}
27262 }));
27263 // TODO further verify that this is the signature that should be revoked
27264 if (signature) {
27265 signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :
27266 signature.revoked || false;
27267 return signature.revoked;
27268 }
27269 return revocationKeyIDs.length > 0;
27270}
27271
27272/**
27273 * Returns key expiration time based on the given certification signature.
27274 * The expiration time of the signature is ignored.
27275 * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check
27276 * @param {SignaturePacket} signature - signature to process
27277 * @returns {Date|Infinity} expiration time or infinity if the key does not expire
27278 */
27279function getKeyExpirationTime(keyPacket, signature) {
27280 let expirationTime;
27281 // check V4 expiration time
27282 if (signature.keyNeverExpires === false) {
27283 expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
27284 }
27285 return expirationTime ? new Date(expirationTime) : Infinity;
27286}
27287
27288/**
27289 * Returns whether aead is supported by all keys in the set
27290 * @param {Array<Key>} keys - Set of keys
27291 * @param {Date} [date] - Use the given date for verification instead of the current time
27292 * @param {Array} [userIDs] - User IDs
27293 * @param {Object} config - full configuration
27294 * @returns {Promise<Boolean>}
27295 * @async
27296 */
27297async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {
27298 let supported = true;
27299 // TODO replace when Promise.some or Promise.any are implemented
27300 await Promise.all(keys.map(async function(key, i) {
27301 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
27302 if (!primaryUser.selfCertification.features ||
27303 !(primaryUser.selfCertification.features[0] & enums.features.aead)) {
27304 supported = false;
27305 }
27306 }));
27307 return supported;
27308}
27309
27310function sanitizeKeyOptions(options, subkeyDefaults = {}) {
27311 options.type = options.type || subkeyDefaults.type;
27312 options.curve = options.curve || subkeyDefaults.curve;
27313 options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
27314 options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
27315 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
27316 options.date = options.date || subkeyDefaults.date;
27317
27318 options.sign = options.sign || false;
27319
27320 switch (options.type) {
27321 case 'ecc':
27322 try {
27323 options.curve = enums.write(enums.curve, options.curve);
27324 } catch (e) {
27325 throw new Error('Unknown curve');
27326 }
27327 if (options.curve === enums.curve.ed25519 || options.curve === enums.curve.curve25519) {
27328 options.curve = options.sign ? enums.curve.ed25519 : enums.curve.curve25519;
27329 }
27330 if (options.sign) {
27331 options.algorithm = options.curve === enums.curve.ed25519 ? enums.publicKey.eddsa : enums.publicKey.ecdsa;
27332 } else {
27333 options.algorithm = enums.publicKey.ecdh;
27334 }
27335 break;
27336 case 'rsa':
27337 options.algorithm = enums.publicKey.rsaEncryptSign;
27338 break;
27339 default:
27340 throw new Error(`Unsupported key type ${options.type}`);
27341 }
27342 return options;
27343}
27344
27345function isValidSigningKeyPacket(keyPacket, signature) {
27346 const keyAlgo = keyPacket.algorithm;
27347 return keyAlgo !== enums.publicKey.rsaEncrypt &&
27348 keyAlgo !== enums.publicKey.elgamal &&
27349 keyAlgo !== enums.publicKey.ecdh &&
27350 (!signature.keyFlags ||
27351 (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);
27352}
27353
27354function isValidEncryptionKeyPacket(keyPacket, signature) {
27355 const keyAlgo = keyPacket.algorithm;
27356 return keyAlgo !== enums.publicKey.dsa &&
27357 keyAlgo !== enums.publicKey.rsaSign &&
27358 keyAlgo !== enums.publicKey.ecdsa &&
27359 keyAlgo !== enums.publicKey.eddsa &&
27360 (!signature.keyFlags ||
27361 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27362 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);
27363}
27364
27365function isValidDecryptionKeyPacket(signature, config) {
27366 if (config.allowInsecureDecryptionWithSigningKeys) {
27367 // This is only relevant for RSA keys, all other signing algorithms cannot decrypt
27368 return true;
27369 }
27370
27371 return !signature.keyFlags ||
27372 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27373 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
27374}
27375
27376/**
27377 * Check key against blacklisted algorithms and minimum strength requirements.
27378 * @param {SecretKeyPacket|PublicKeyPacket|
27379 * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket
27380 * @param {Config} config
27381 * @throws {Error} if the key packet does not meet the requirements
27382 */
27383function checkKeyRequirements(keyPacket, config) {
27384 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27385 const algoInfo = keyPacket.getAlgorithmInfo();
27386 if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {
27387 throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);
27388 }
27389 switch (keyAlgo) {
27390 case enums.publicKey.rsaEncryptSign:
27391 case enums.publicKey.rsaSign:
27392 case enums.publicKey.rsaEncrypt:
27393 if (algoInfo.bits < config.minRSABits) {
27394 throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);
27395 }
27396 break;
27397 case enums.publicKey.ecdsa:
27398 case enums.publicKey.eddsa:
27399 case enums.publicKey.ecdh:
27400 if (config.rejectCurves.has(algoInfo.curve)) {
27401 throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);
27402 }
27403 break;
27404 }
27405}
27406
27407/**
27408 * @module key/User
27409 * @private
27410 */
27411
27412/**
27413 * Class that represents an user ID or attribute packet and the relevant signatures.
27414 * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info
27415 * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with
27416 */
27417class User {
27418 constructor(userPacket, mainKey) {
27419 this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;
27420 this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;
27421 this.selfCertifications = [];
27422 this.otherCertifications = [];
27423 this.revocationSignatures = [];
27424 this.mainKey = mainKey;
27425 }
27426
27427 /**
27428 * Transforms structured user data to packetlist
27429 * @returns {PacketList}
27430 */
27431 toPacketList() {
27432 const packetlist = new PacketList();
27433 packetlist.push(this.userID || this.userAttribute);
27434 packetlist.push(...this.revocationSignatures);
27435 packetlist.push(...this.selfCertifications);
27436 packetlist.push(...this.otherCertifications);
27437 return packetlist;
27438 }
27439
27440 /**
27441 * Shallow clone
27442 * @returns {User}
27443 */
27444 clone() {
27445 const user = new User(this.userID || this.userAttribute, this.mainKey);
27446 user.selfCertifications = [...this.selfCertifications];
27447 user.otherCertifications = [...this.otherCertifications];
27448 user.revocationSignatures = [...this.revocationSignatures];
27449 return user;
27450 }
27451
27452 /**
27453 * Generate third-party certifications over this user and its primary key
27454 * @param {Array<PrivateKey>} signingKeys - Decrypted private keys for signing
27455 * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time
27456 * @param {Object} config - Full configuration
27457 * @returns {Promise<User>} New user with new certifications.
27458 * @async
27459 */
27460 async certify(signingKeys, date, config) {
27461 const primaryKey = this.mainKey.keyPacket;
27462 const dataToSign = {
27463 userID: this.userID,
27464 userAttribute: this.userAttribute,
27465 key: primaryKey
27466 };
27467 const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
27468 user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {
27469 if (!privateKey.isPrivate()) {
27470 throw new Error('Need private key for signing');
27471 }
27472 if (privateKey.hasSameFingerprintAs(primaryKey)) {
27473 throw new Error("The user's own key can only be used for self-certifications");
27474 }
27475 const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);
27476 return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
27477 // Most OpenPGP implementations use generic certification (0x10)
27478 signatureType: enums.signature.certGeneric,
27479 keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
27480 }, date, undefined, undefined, config);
27481 }));
27482 await user.update(this, date, config);
27483 return user;
27484 }
27485
27486 /**
27487 * Checks if a given certificate of the user is revoked
27488 * @param {SignaturePacket} certificate - The certificate to verify
27489 * @param {PublicSubkeyPacket|
27490 * SecretSubkeyPacket|
27491 * PublicKeyPacket|
27492 * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key
27493 * @param {Date} [date] - Use the given date for verification instead of the current time
27494 * @param {Object} config - Full configuration
27495 * @returns {Promise<Boolean>} True if the certificate is revoked.
27496 * @async
27497 */
27498 async isRevoked(certificate, keyPacket, date = new Date(), config) {
27499 const primaryKey = this.mainKey.keyPacket;
27500 return isDataRevoked(primaryKey, enums.signature.certRevocation, {
27501 key: primaryKey,
27502 userID: this.userID,
27503 userAttribute: this.userAttribute
27504 }, this.revocationSignatures, certificate, keyPacket, date, config);
27505 }
27506
27507 /**
27508 * Verifies the user certificate.
27509 * @param {SignaturePacket} certificate - A certificate of this user
27510 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27511 * @param {Date} [date] - Use the given date instead of the current time
27512 * @param {Object} config - Full configuration
27513 * @returns {Promise<true|null>} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate
27514 * @throws if the user certificate is invalid.
27515 * @async
27516 */
27517 async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {
27518 const that = this;
27519 const primaryKey = this.mainKey.keyPacket;
27520 const dataToVerify = {
27521 userID: this.userID,
27522 userAttribute: this.userAttribute,
27523 key: primaryKey
27524 };
27525 const { issuerKeyID } = certificate;
27526 const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);
27527 if (issuerKeys.length === 0) {
27528 return null;
27529 }
27530 await Promise.all(issuerKeys.map(async key => {
27531 const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);
27532 if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {
27533 throw new Error('User certificate is revoked');
27534 }
27535 try {
27536 await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27537 } catch (e) {
27538 throw util.wrapError('User certificate is invalid', e);
27539 }
27540 }));
27541 return true;
27542 }
27543
27544 /**
27545 * Verifies all user certificates
27546 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27547 * @param {Date} [date] - Use the given date instead of the current time
27548 * @param {Object} config - Full configuration
27549 * @returns {Promise<Array<{
27550 * keyID: module:type/keyid~KeyID,
27551 * valid: Boolean | null
27552 * }>>} List of signer's keyID and validity of signature.
27553 * Signature validity is null if the verification keys do not correspond to the certificate.
27554 * @async
27555 */
27556 async verifyAllCertifications(verificationKeys, date = new Date(), config) {
27557 const that = this;
27558 const certifications = this.selfCertifications.concat(this.otherCertifications);
27559 return Promise.all(certifications.map(async certification => ({
27560 keyID: certification.issuerKeyID,
27561 valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)
27562 })));
27563 }
27564
27565 /**
27566 * Verify User. Checks for existence of self signatures, revocation signatures
27567 * and validity of self signature.
27568 * @param {Date} date - Use the given date instead of the current time
27569 * @param {Object} config - Full configuration
27570 * @returns {Promise<true>} Status of user.
27571 * @throws {Error} if there are no valid self signatures.
27572 * @async
27573 */
27574 async verify(date = new Date(), config) {
27575 if (!this.selfCertifications.length) {
27576 throw new Error('No self-certifications found');
27577 }
27578 const that = this;
27579 const primaryKey = this.mainKey.keyPacket;
27580 const dataToVerify = {
27581 userID: this.userID,
27582 userAttribute: this.userAttribute,
27583 key: primaryKey
27584 };
27585 // TODO replace when Promise.some or Promise.any are implemented
27586 let exception;
27587 for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
27588 try {
27589 const selfCertification = this.selfCertifications[i];
27590 if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {
27591 throw new Error('Self-certification is revoked');
27592 }
27593 try {
27594 await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27595 } catch (e) {
27596 throw util.wrapError('Self-certification is invalid', e);
27597 }
27598 return true;
27599 } catch (e) {
27600 exception = e;
27601 }
27602 }
27603 throw exception;
27604 }
27605
27606 /**
27607 * Update user with new components from specified user
27608 * @param {User} sourceUser - Source user to merge
27609 * @param {Date} date - Date to verify the validity of signatures
27610 * @param {Object} config - Full configuration
27611 * @returns {Promise<undefined>}
27612 * @async
27613 */
27614 async update(sourceUser, date, config) {
27615 const primaryKey = this.mainKey.keyPacket;
27616 const dataToVerify = {
27617 userID: this.userID,
27618 userAttribute: this.userAttribute,
27619 key: primaryKey
27620 };
27621 // self signatures
27622 await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {
27623 try {
27624 await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);
27625 return true;
27626 } catch (e) {
27627 return false;
27628 }
27629 });
27630 // other signatures
27631 await mergeSignatures(sourceUser, this, 'otherCertifications', date);
27632 // revocation signatures
27633 await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {
27634 return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27635 });
27636 }
27637}
27638
27639/**
27640 * @module key/Subkey
27641 * @private
27642 */
27643
27644/**
27645 * Class that represents a subkey packet and the relevant signatures.
27646 * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID
27647 * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint
27648 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs
27649 * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo
27650 * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime
27651 * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted
27652 */
27653class Subkey {
27654 /**
27655 * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey
27656 * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey
27657 */
27658 constructor(subkeyPacket, mainKey) {
27659 this.keyPacket = subkeyPacket;
27660 this.bindingSignatures = [];
27661 this.revocationSignatures = [];
27662 this.mainKey = mainKey;
27663 }
27664
27665 /**
27666 * Transforms structured subkey data to packetlist
27667 * @returns {PacketList}
27668 */
27669 toPacketList() {
27670 const packetlist = new PacketList();
27671 packetlist.push(this.keyPacket);
27672 packetlist.push(...this.revocationSignatures);
27673 packetlist.push(...this.bindingSignatures);
27674 return packetlist;
27675 }
27676
27677 /**
27678 * Shallow clone
27679 * @return {Subkey}
27680 */
27681 clone() {
27682 const subkey = new Subkey(this.keyPacket, this.mainKey);
27683 subkey.bindingSignatures = [...this.bindingSignatures];
27684 subkey.revocationSignatures = [...this.revocationSignatures];
27685 return subkey;
27686 }
27687
27688 /**
27689 * Checks if a binding signature of a subkey is revoked
27690 * @param {SignaturePacket} signature - The binding signature to verify
27691 * @param {PublicSubkeyPacket|
27692 * SecretSubkeyPacket|
27693 * PublicKeyPacket|
27694 * SecretKeyPacket} key, optional The key to verify the signature
27695 * @param {Date} [date] - Use the given date for verification instead of the current time
27696 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27697 * @returns {Promise<Boolean>} True if the binding signature is revoked.
27698 * @async
27699 */
27700 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
27701 const primaryKey = this.mainKey.keyPacket;
27702 return isDataRevoked(
27703 primaryKey, enums.signature.subkeyRevocation, {
27704 key: primaryKey,
27705 bind: this.keyPacket
27706 }, this.revocationSignatures, signature, key, date, config
27707 );
27708 }
27709
27710 /**
27711 * Verify subkey. Checks for revocation signatures, expiration time
27712 * and valid binding signature.
27713 * @param {Date} date - Use the given date instead of the current time
27714 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27715 * @returns {Promise<SignaturePacket>}
27716 * @throws {Error} if the subkey is invalid.
27717 * @async
27718 */
27719 async verify(date = new Date(), config = defaultConfig) {
27720 const primaryKey = this.mainKey.keyPacket;
27721 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27722 // check subkey binding signatures
27723 const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27724 // check binding signature is not revoked
27725 if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {
27726 throw new Error('Subkey is revoked');
27727 }
27728 // check for expiration time
27729 if (isDataExpired(this.keyPacket, bindingSignature, date)) {
27730 throw new Error('Subkey is expired');
27731 }
27732 return bindingSignature;
27733 }
27734
27735 /**
27736 * Returns the expiration time of the subkey or Infinity if key does not expire.
27737 * Returns null if the subkey is invalid.
27738 * @param {Date} date - Use the given date instead of the current time
27739 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27740 * @returns {Promise<Date | Infinity | null>}
27741 * @async
27742 */
27743 async getExpirationTime(date = new Date(), config = defaultConfig) {
27744 const primaryKey = this.mainKey.keyPacket;
27745 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27746 let bindingSignature;
27747 try {
27748 bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27749 } catch (e) {
27750 return null;
27751 }
27752 const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature);
27753 const sigExpiry = bindingSignature.getExpirationTime();
27754 return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
27755 }
27756
27757 /**
27758 * Update subkey with new components from specified subkey
27759 * @param {Subkey} subkey - Source subkey to merge
27760 * @param {Date} [date] - Date to verify validity of signatures
27761 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27762 * @throws {Error} if update failed
27763 * @async
27764 */
27765 async update(subkey, date = new Date(), config = defaultConfig) {
27766 const primaryKey = this.mainKey.keyPacket;
27767 if (!this.hasSameFingerprintAs(subkey)) {
27768 throw new Error('Subkey update method: fingerprints of subkeys not equal');
27769 }
27770 // key packet
27771 if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&
27772 subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {
27773 this.keyPacket = subkey.keyPacket;
27774 }
27775 // update missing binding signatures
27776 const that = this;
27777 const dataToVerify = { key: primaryKey, bind: that.keyPacket };
27778 await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {
27779 for (let i = 0; i < that.bindingSignatures.length; i++) {
27780 if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {
27781 if (srcBindSig.created > that.bindingSignatures[i].created) {
27782 that.bindingSignatures[i] = srcBindSig;
27783 }
27784 return false;
27785 }
27786 }
27787 try {
27788 await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);
27789 return true;
27790 } catch (e) {
27791 return false;
27792 }
27793 });
27794 // revocation signatures
27795 await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {
27796 return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27797 });
27798 }
27799
27800 /**
27801 * Revokes the subkey
27802 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
27803 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
27804 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
27805 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
27806 * @param {Date} date - optional, override the creationtime of the revocation signature
27807 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27808 * @returns {Promise<Subkey>} New subkey with revocation signature.
27809 * @async
27810 */
27811 async revoke(
27812 primaryKey,
27813 {
27814 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
27815 string: reasonForRevocationString = ''
27816 } = {},
27817 date = new Date(),
27818 config = defaultConfig
27819 ) {
27820 const dataToSign = { key: primaryKey, bind: this.keyPacket };
27821 const subkey = new Subkey(this.keyPacket, this.mainKey);
27822 subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
27823 signatureType: enums.signature.subkeyRevocation,
27824 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
27825 reasonForRevocationString
27826 }, date, undefined, false, config));
27827 await subkey.update(this);
27828 return subkey;
27829 }
27830
27831 hasSameFingerprintAs(other) {
27832 return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
27833 }
27834}
27835
27836['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
27837 Subkey.prototype[name] =
27838 function() {
27839 return this.keyPacket[name]();
27840 };
27841});
27842
27843// GPG4Browsers - An OpenPGP implementation in javascript
27844
27845// A key revocation certificate can contain the following packets
27846const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
27847const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);
27848const keyPacketTags = new Set([
27849 enums.packet.publicKey, enums.packet.privateKey,
27850 enums.packet.publicSubkey, enums.packet.privateSubkey
27851]);
27852
27853/**
27854 * Abstract class that represents an OpenPGP key. Must contain a primary key.
27855 * Can contain additional subkeys, signatures, user ids, user attributes.
27856 * @borrows PublicKeyPacket#getKeyID as Key#getKeyID
27857 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
27858 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
27859 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
27860 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
27861 */
27862class Key {
27863 /**
27864 * Transforms packetlist to structured key data
27865 * @param {PacketList} packetlist - The packets that form a key
27866 * @param {Set<enums.packet>} disallowedPackets - disallowed packet tags
27867 */
27868 packetListToStructure(packetlist, disallowedPackets = new Set()) {
27869 let user;
27870 let primaryKeyID;
27871 let subkey;
27872 let ignoreUntil;
27873
27874 for (const packet of packetlist) {
27875
27876 if (packet instanceof UnparseablePacket) {
27877 const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);
27878 if (isUnparseableKeyPacket && !ignoreUntil){
27879 // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must
27880 // discard all non-key packets that follow, until another (sub)key packet is found.
27881 if (mainKeyPacketTags.has(packet.tag)) {
27882 ignoreUntil = mainKeyPacketTags;
27883 } else {
27884 ignoreUntil = keyPacketTags;
27885 }
27886 }
27887 continue;
27888 }
27889
27890 const tag = packet.constructor.tag;
27891 if (ignoreUntil) {
27892 if (!ignoreUntil.has(tag)) continue;
27893 ignoreUntil = null;
27894 }
27895 if (disallowedPackets.has(tag)) {
27896 throw new Error(`Unexpected packet type: ${tag}`);
27897 }
27898 switch (tag) {
27899 case enums.packet.publicKey:
27900 case enums.packet.secretKey:
27901 if (this.keyPacket) {
27902 throw new Error('Key block contains multiple keys');
27903 }
27904 this.keyPacket = packet;
27905 primaryKeyID = this.getKeyID();
27906 if (!primaryKeyID) {
27907 throw new Error('Missing Key ID');
27908 }
27909 break;
27910 case enums.packet.userID:
27911 case enums.packet.userAttribute:
27912 user = new User(packet, this);
27913 this.users.push(user);
27914 break;
27915 case enums.packet.publicSubkey:
27916 case enums.packet.secretSubkey:
27917 user = null;
27918 subkey = new Subkey(packet, this);
27919 this.subkeys.push(subkey);
27920 break;
27921 case enums.packet.signature:
27922 switch (packet.signatureType) {
27923 case enums.signature.certGeneric:
27924 case enums.signature.certPersona:
27925 case enums.signature.certCasual:
27926 case enums.signature.certPositive:
27927 if (!user) {
27928 util.printDebug('Dropping certification signatures without preceding user packet');
27929 continue;
27930 }
27931 if (packet.issuerKeyID.equals(primaryKeyID)) {
27932 user.selfCertifications.push(packet);
27933 } else {
27934 user.otherCertifications.push(packet);
27935 }
27936 break;
27937 case enums.signature.certRevocation:
27938 if (user) {
27939 user.revocationSignatures.push(packet);
27940 } else {
27941 this.directSignatures.push(packet);
27942 }
27943 break;
27944 case enums.signature.key:
27945 this.directSignatures.push(packet);
27946 break;
27947 case enums.signature.subkeyBinding:
27948 if (!subkey) {
27949 util.printDebug('Dropping subkey binding signature without preceding subkey packet');
27950 continue;
27951 }
27952 subkey.bindingSignatures.push(packet);
27953 break;
27954 case enums.signature.keyRevocation:
27955 this.revocationSignatures.push(packet);
27956 break;
27957 case enums.signature.subkeyRevocation:
27958 if (!subkey) {
27959 util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
27960 continue;
27961 }
27962 subkey.revocationSignatures.push(packet);
27963 break;
27964 }
27965 break;
27966 }
27967 }
27968 }
27969
27970 /**
27971 * Transforms structured key data to packetlist
27972 * @returns {PacketList} The packets that form a key.
27973 */
27974 toPacketList() {
27975 const packetlist = new PacketList();
27976 packetlist.push(this.keyPacket);
27977 packetlist.push(...this.revocationSignatures);
27978 packetlist.push(...this.directSignatures);
27979 this.users.map(user => packetlist.push(...user.toPacketList()));
27980 this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));
27981 return packetlist;
27982 }
27983
27984 /**
27985 * Clones the key object
27986 * @param {Boolean} [deep=false] Whether to return a deep clone
27987 * @returns {Promise<Key>} Clone of the key.
27988 */
27989 clone(deep = false) {
27990 const key = new this.constructor(this.toPacketList());
27991 if (deep) {
27992 key.getKeys().forEach(k => {
27993 // shallow clone the key packets
27994 k.keyPacket = Object.create(
27995 Object.getPrototypeOf(k.keyPacket),
27996 Object.getOwnPropertyDescriptors(k.keyPacket)
27997 );
27998 if (!k.keyPacket.isDecrypted()) return;
27999 // deep clone the private params, which are cleared during encryption
28000 const privateParams = {};
28001 Object.keys(k.keyPacket.privateParams).forEach(name => {
28002 privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
28003 });
28004 k.keyPacket.privateParams = privateParams;
28005 });
28006 }
28007 return key;
28008 }
28009
28010 /**
28011 * Returns an array containing all public or private subkeys matching keyID;
28012 * If no keyID is given, returns all subkeys.
28013 * @param {type/keyID} [keyID] - key ID to look for
28014 * @returns {Array<Subkey>} array of subkeys
28015 */
28016 getSubkeys(keyID = null) {
28017 const subkeys = this.subkeys.filter(subkey => (
28018 !keyID || subkey.getKeyID().equals(keyID, true)
28019 ));
28020 return subkeys;
28021 }
28022
28023 /**
28024 * Returns an array containing all public or private keys matching keyID.
28025 * If no keyID is given, returns all keys, starting with the primary key.
28026 * @param {type/keyid~KeyID} [keyID] - key ID to look for
28027 * @returns {Array<Key|Subkey>} array of keys
28028 */
28029 getKeys(keyID = null) {
28030 const keys = [];
28031 if (!keyID || this.getKeyID().equals(keyID, true)) {
28032 keys.push(this);
28033 }
28034 return keys.concat(this.getSubkeys(keyID));
28035 }
28036
28037 /**
28038 * Returns key IDs of all keys
28039 * @returns {Array<module:type/keyid~KeyID>}
28040 */
28041 getKeyIDs() {
28042 return this.getKeys().map(key => key.getKeyID());
28043 }
28044
28045 /**
28046 * Returns userIDs
28047 * @returns {Array<string>} Array of userIDs.
28048 */
28049 getUserIDs() {
28050 return this.users.map(user => {
28051 return user.userID ? user.userID.userID : null;
28052 }).filter(userID => userID !== null);
28053 }
28054
28055 /**
28056 * Returns binary encoded key
28057 * @returns {Uint8Array} Binary key.
28058 */
28059 write() {
28060 return this.toPacketList().write();
28061 }
28062
28063 /**
28064 * Returns last created key or key by given keyID that is available for signing and verification
28065 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28066 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28067 * @param {Object} [userID] - filter keys for the given user ID
28068 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28069 * @returns {Promise<Key|Subkey>} signing key
28070 * @throws if no valid signing key was found
28071 * @async
28072 */
28073 async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {
28074 await this.verifyPrimaryKey(date, userID, config);
28075 const primaryKey = this.keyPacket;
28076 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28077 let exception;
28078 for (const subkey of subkeys) {
28079 if (!keyID || subkey.getKeyID().equals(keyID)) {
28080 try {
28081 await subkey.verify(date, config);
28082 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28083 const bindingSignature = await getLatestValidSignature(
28084 subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config
28085 );
28086 if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {
28087 continue;
28088 }
28089 if (!bindingSignature.embeddedSignature) {
28090 throw new Error('Missing embedded signature');
28091 }
28092 // verify embedded signature
28093 await getLatestValidSignature(
28094 [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config
28095 );
28096 checkKeyRequirements(subkey.keyPacket, config);
28097 return subkey;
28098 } catch (e) {
28099 exception = e;
28100 }
28101 }
28102 }
28103
28104 try {
28105 const primaryUser = await this.getPrimaryUser(date, userID, config);
28106 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28107 isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {
28108 checkKeyRequirements(primaryKey, config);
28109 return this;
28110 }
28111 } catch (e) {
28112 exception = e;
28113 }
28114 throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);
28115 }
28116
28117 /**
28118 * Returns last created key or key by given keyID that is available for encryption or decryption
28119 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28120 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28121 * @param {Object} [userID] - filter keys for the given user ID
28122 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28123 * @returns {Promise<Key|Subkey>} encryption key
28124 * @throws if no valid encryption key was found
28125 * @async
28126 */
28127 async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {
28128 await this.verifyPrimaryKey(date, userID, config);
28129 const primaryKey = this.keyPacket;
28130 // V4: by convention subkeys are preferred for encryption service
28131 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28132 let exception;
28133 for (const subkey of subkeys) {
28134 if (!keyID || subkey.getKeyID().equals(keyID)) {
28135 try {
28136 await subkey.verify(date, config);
28137 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28138 const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
28139 if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {
28140 checkKeyRequirements(subkey.keyPacket, config);
28141 return subkey;
28142 }
28143 } catch (e) {
28144 exception = e;
28145 }
28146 }
28147 }
28148
28149 try {
28150 // if no valid subkey for encryption, evaluate primary key
28151 const primaryUser = await this.getPrimaryUser(date, userID, config);
28152 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28153 isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
28154 checkKeyRequirements(primaryKey, config);
28155 return this;
28156 }
28157 } catch (e) {
28158 exception = e;
28159 }
28160 throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);
28161 }
28162
28163 /**
28164 * Checks if a signature on a key is revoked
28165 * @param {SignaturePacket} signature - The signature to verify
28166 * @param {PublicSubkeyPacket|
28167 * SecretSubkeyPacket|
28168 * PublicKeyPacket|
28169 * SecretKeyPacket} key, optional The key to verify the signature
28170 * @param {Date} [date] - Use the given date for verification, instead of the current time
28171 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28172 * @returns {Promise<Boolean>} True if the certificate is revoked.
28173 * @async
28174 */
28175 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
28176 return isDataRevoked(
28177 this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config
28178 );
28179 }
28180
28181 /**
28182 * Verify primary key. Checks for revocation signatures, expiration time
28183 * and valid self signature. Throws if the primary key is invalid.
28184 * @param {Date} [date] - Use the given date for verification instead of the current time
28185 * @param {Object} [userID] - User ID
28186 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28187 * @throws {Error} If key verification failed
28188 * @async
28189 */
28190 async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {
28191 const primaryKey = this.keyPacket;
28192 // check for key revocation signatures
28193 if (await this.isRevoked(null, null, date, config)) {
28194 throw new Error('Primary key is revoked');
28195 }
28196 // check for valid, unrevoked, unexpired self signature
28197 const { selfCertification } = await this.getPrimaryUser(date, userID, config);
28198 // check for expiration time in binding signatures
28199 if (isDataExpired(primaryKey, selfCertification, date)) {
28200 throw new Error('Primary key is expired');
28201 }
28202 // check for expiration time in direct signatures
28203 const directSignature = await getLatestValidSignature(
28204 this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config
28205 ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key
28206
28207 if (directSignature && isDataExpired(primaryKey, directSignature, date)) {
28208 throw new Error('Primary key is expired');
28209 }
28210 }
28211
28212 /**
28213 * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.
28214 * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.
28215 * @param {Object} [userID] - User ID to consider instead of the primary user
28216 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28217 * @returns {Promise<Date | Infinity | null>}
28218 * @async
28219 */
28220 async getExpirationTime(userID, config = defaultConfig) {
28221 let primaryKeyExpiry;
28222 try {
28223 const { selfCertification } = await this.getPrimaryUser(null, userID, config);
28224 const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification);
28225 const selfSigExpiry = selfCertification.getExpirationTime();
28226 const directSignature = await getLatestValidSignature(
28227 this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config
28228 ).catch(() => {});
28229 if (directSignature) {
28230 const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature);
28231 // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,
28232 // causing a discountinous validy period for the key
28233 primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);
28234 } else {
28235 primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;
28236 }
28237 } catch (e) {
28238 primaryKeyExpiry = null;
28239 }
28240
28241 return util.normalizeDate(primaryKeyExpiry);
28242 }
28243
28244
28245 /**
28246 * Returns primary user and most significant (latest valid) self signature
28247 * - if multiple primary users exist, returns the one with the latest self signature
28248 * - otherwise, returns the user with the latest self signature
28249 * @param {Date} [date] - Use the given date for verification instead of the current time
28250 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28251 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28252 * @returns {Promise<{
28253 * user: User,
28254 * selfCertification: SignaturePacket
28255 * }>} The primary user and the self signature
28256 * @async
28257 */
28258 async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {
28259 const primaryKey = this.keyPacket;
28260 const users = [];
28261 let exception;
28262 for (let i = 0; i < this.users.length; i++) {
28263 try {
28264 const user = this.users[i];
28265 if (!user.userID) {
28266 continue;
28267 }
28268 if (
28269 (userID.name !== undefined && user.userID.name !== userID.name) ||
28270 (userID.email !== undefined && user.userID.email !== userID.email) ||
28271 (userID.comment !== undefined && user.userID.comment !== userID.comment)
28272 ) {
28273 throw new Error('Could not find user that matches that user ID');
28274 }
28275 const dataToVerify = { userID: user.userID, key: primaryKey };
28276 const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);
28277 users.push({ index: i, user, selfCertification });
28278 } catch (e) {
28279 exception = e;
28280 }
28281 }
28282 if (!users.length) {
28283 throw exception || new Error('Could not find primary user');
28284 }
28285 await Promise.all(users.map(async function (a) {
28286 return a.user.revoked || a.user.isRevoked(a.selfCertification, null, date, config);
28287 }));
28288 // sort by primary user flag and signature creation time
28289 const primaryUser = users.sort(function(a, b) {
28290 const A = a.selfCertification;
28291 const B = b.selfCertification;
28292 return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
28293 }).pop();
28294 const { user, selfCertification: cert } = primaryUser;
28295 if (cert.revoked || await user.isRevoked(cert, null, date, config)) {
28296 throw new Error('Primary user is revoked');
28297 }
28298 return primaryUser;
28299 }
28300
28301 /**
28302 * Update key with new components from specified key with same key ID:
28303 * users, subkeys, certificates are merged into the destination key,
28304 * duplicates and expired signatures are ignored.
28305 *
28306 * If the source key is a private key and the destination key is public,
28307 * a private key is returned.
28308 * @param {Key} sourceKey - Source key to merge
28309 * @param {Date} [date] - Date to verify validity of signatures and keys
28310 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28311 * @returns {Promise<Key>} updated key
28312 * @async
28313 */
28314 async update(sourceKey, date = new Date(), config = defaultConfig) {
28315 if (!this.hasSameFingerprintAs(sourceKey)) {
28316 throw new Error('Primary key fingerprints must be equal to update the key');
28317 }
28318 if (!this.isPrivate() && sourceKey.isPrivate()) {
28319 // check for equal subkey packets
28320 const equal = (this.subkeys.length === sourceKey.subkeys.length) &&
28321 (this.subkeys.every(destSubkey => {
28322 return sourceKey.subkeys.some(srcSubkey => {
28323 return destSubkey.hasSameFingerprintAs(srcSubkey);
28324 });
28325 }));
28326 if (!equal) {
28327 throw new Error('Cannot update public key with private key if subkeys mismatch');
28328 }
28329
28330 return sourceKey.update(this, config);
28331 }
28332 // from here on, either:
28333 // - destination key is private, source key is public
28334 // - the keys are of the same type
28335 // hence we don't need to convert the destination key type
28336 const updatedKey = this.clone();
28337 // revocation signatures
28338 await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {
28339 return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);
28340 });
28341 // direct signatures
28342 await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);
28343 // update users
28344 await Promise.all(sourceKey.users.map(async srcUser => {
28345 // multiple users with the same ID/attribute are not explicitly disallowed by the spec
28346 // hence we support them, just in case
28347 const usersToUpdate = updatedKey.users.filter(dstUser => (
28348 (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||
28349 (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))
28350 ));
28351 if (usersToUpdate.length > 0) {
28352 await Promise.all(
28353 usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))
28354 );
28355 } else {
28356 const newUser = srcUser.clone();
28357 newUser.mainKey = updatedKey;
28358 updatedKey.users.push(newUser);
28359 }
28360 }));
28361 // update subkeys
28362 await Promise.all(sourceKey.subkeys.map(async srcSubkey => {
28363 // multiple subkeys with same fingerprint might be preset
28364 const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (
28365 dstSubkey.hasSameFingerprintAs(srcSubkey)
28366 ));
28367 if (subkeysToUpdate.length > 0) {
28368 await Promise.all(
28369 subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))
28370 );
28371 } else {
28372 const newSubkey = srcSubkey.clone();
28373 newSubkey.mainKey = updatedKey;
28374 updatedKey.subkeys.push(newSubkey);
28375 }
28376 }));
28377
28378 return updatedKey;
28379 }
28380
28381 /**
28382 * Get revocation certificate from a revoked key.
28383 * (To get a revocation certificate for an unrevoked key, call revoke() first.)
28384 * @param {Date} date - Use the given date instead of the current time
28385 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28386 * @returns {Promise<String>} Armored revocation certificate.
28387 * @async
28388 */
28389 async getRevocationCertificate(date = new Date(), config = defaultConfig) {
28390 const dataToVerify = { key: this.keyPacket };
28391 const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);
28392 const packetlist = new PacketList();
28393 packetlist.push(revocationSignature);
28394 return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');
28395 }
28396
28397 /**
28398 * Applies a revocation certificate to a key
28399 * This adds the first signature packet in the armored text to the key,
28400 * if it is a valid revocation signature.
28401 * @param {String} revocationCertificate - armored revocation certificate
28402 * @param {Date} [date] - Date to verify the certificate
28403 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28404 * @returns {Promise<Key>} Revoked key.
28405 * @async
28406 */
28407 async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {
28408 const input = await unarmor(revocationCertificate, config);
28409 const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);
28410 const revocationSignature = packetlist.findPacket(enums.packet.signature);
28411 if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
28412 throw new Error('Could not find revocation signature packet');
28413 }
28414 if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {
28415 throw new Error('Revocation signature does not match key');
28416 }
28417 try {
28418 await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);
28419 } catch (e) {
28420 throw util.wrapError('Could not verify revocation signature', e);
28421 }
28422 const key = this.clone();
28423 key.revocationSignatures.push(revocationSignature);
28424 return key;
28425 }
28426
28427 /**
28428 * Signs primary user of key
28429 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28430 * @param {Date} [date] - Use the given date for verification instead of the current time
28431 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28432 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28433 * @returns {Promise<Key>} Key with new certificate signature.
28434 * @async
28435 */
28436 async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {
28437 const { index, user } = await this.getPrimaryUser(date, userID, config);
28438 const userSign = await user.certify(privateKeys, date, config);
28439 const key = this.clone();
28440 key.users[index] = userSign;
28441 return key;
28442 }
28443
28444 /**
28445 * Signs all users of key
28446 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28447 * @param {Date} [date] - Use the given date for signing, instead of the current time
28448 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28449 * @returns {Promise<Key>} Key with new certificate signature.
28450 * @async
28451 */
28452 async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {
28453 const key = this.clone();
28454 key.users = await Promise.all(this.users.map(function(user) {
28455 return user.certify(privateKeys, date, config);
28456 }));
28457 return key;
28458 }
28459
28460 /**
28461 * Verifies primary user of key
28462 * - if no arguments are given, verifies the self certificates;
28463 * - otherwise, verifies all certificates signed with given keys.
28464 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key
28465 * @param {Date} [date] - Use the given date for verification instead of the current time
28466 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28467 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28468 * @returns {Promise<Array<{
28469 * keyID: module:type/keyid~KeyID,
28470 * valid: Boolean|null
28471 * }>>} List of signer's keyID and validity of signature.
28472 * Signature validity is null if the verification keys do not correspond to the certificate.
28473 * @async
28474 */
28475 async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {
28476 const primaryKey = this.keyPacket;
28477 const { user } = await this.getPrimaryUser(date, userID, config);
28478 const results = verificationKeys ?
28479 await user.verifyAllCertifications(verificationKeys, date, config) :
28480 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28481 return results;
28482 }
28483
28484 /**
28485 * Verifies all users of key
28486 * - if no arguments are given, verifies the self certificates;
28487 * - otherwise, verifies all certificates signed with given keys.
28488 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures
28489 * @param {Date} [date] - Use the given date for verification instead of the current time
28490 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28491 * @returns {Promise<Array<{
28492 * userID: String,
28493 * keyID: module:type/keyid~KeyID,
28494 * valid: Boolean|null
28495 * }>>} List of userID, signer's keyID and validity of signature.
28496 * Signature validity is null if the verification keys do not correspond to the certificate.
28497 * @async
28498 */
28499 async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {
28500 const primaryKey = this.keyPacket;
28501 const results = [];
28502 await Promise.all(this.users.map(async user => {
28503 const signatures = verificationKeys ?
28504 await user.verifyAllCertifications(verificationKeys, date, config) :
28505 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28506
28507 results.push(...signatures.map(
28508 signature => ({
28509 userID: user.userID.userID,
28510 keyID: signature.keyID,
28511 valid: signature.valid
28512 }))
28513 );
28514 }));
28515 return results;
28516 }
28517}
28518
28519['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
28520 Key.prototype[name] =
28521 Subkey.prototype[name];
28522});
28523
28524/**
28525 * Creates a PublicKey or PrivateKey depending on the packetlist in input
28526 * @param {PacketList} - packets to parse
28527 * @return {Key} parsed key
28528 * @throws if no key packet was found
28529 */
28530function createKey(packetlist) {
28531 for (const packet of packetlist) {
28532 switch (packet.constructor.tag) {
28533 case enums.packet.secretKey:
28534 return new PrivateKey(packetlist);
28535 case enums.packet.publicKey:
28536 return new PublicKey(packetlist);
28537 }
28538 }
28539 throw new Error('No key packet found');
28540}
28541
28542// This library is free software; you can redistribute it and/or
28543
28544/**
28545 * Class that represents an OpenPGP Public Key
28546 */
28547class PublicKey extends Key {
28548 /**
28549 * @param {PacketList} packetlist - The packets that form this key
28550 */
28551 constructor(packetlist) {
28552 super();
28553 this.keyPacket = null;
28554 this.revocationSignatures = [];
28555 this.directSignatures = [];
28556 this.users = [];
28557 this.subkeys = [];
28558 if (packetlist) {
28559 this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));
28560 if (!this.keyPacket) {
28561 throw new Error('Invalid key: missing public-key packet');
28562 }
28563 }
28564 }
28565
28566 /**
28567 * Returns true if this is a private key
28568 * @returns {false}
28569 */
28570 isPrivate() {
28571 return false;
28572 }
28573
28574 /**
28575 * Returns key as public key (shallow copy)
28576 * @returns {PublicKey} New public Key
28577 */
28578 toPublic() {
28579 return this;
28580 }
28581
28582 /**
28583 * Returns ASCII armored text of key
28584 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28585 * @returns {ReadableStream<String>} ASCII armor.
28586 */
28587 armor(config = defaultConfig) {
28588 return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28589 }
28590}
28591
28592/**
28593 * Class that represents an OpenPGP Private key
28594 */
28595class PrivateKey extends PublicKey {
28596 /**
28597 * @param {PacketList} packetlist - The packets that form this key
28598 */
28599 constructor(packetlist) {
28600 super();
28601 this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));
28602 if (!this.keyPacket) {
28603 throw new Error('Invalid key: missing private-key packet');
28604 }
28605 }
28606
28607 /**
28608 * Returns true if this is a private key
28609 * @returns {Boolean}
28610 */
28611 isPrivate() {
28612 return true;
28613 }
28614
28615 /**
28616 * Returns key as public key (shallow copy)
28617 * @returns {PublicKey} New public Key
28618 */
28619 toPublic() {
28620 const packetlist = new PacketList();
28621 const keyPackets = this.toPacketList();
28622 for (const keyPacket of keyPackets) {
28623 switch (keyPacket.constructor.tag) {
28624 case enums.packet.secretKey: {
28625 const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);
28626 packetlist.push(pubKeyPacket);
28627 break;
28628 }
28629 case enums.packet.secretSubkey: {
28630 const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);
28631 packetlist.push(pubSubkeyPacket);
28632 break;
28633 }
28634 default:
28635 packetlist.push(keyPacket);
28636 }
28637 }
28638 return new PublicKey(packetlist);
28639 }
28640
28641 /**
28642 * Returns ASCII armored text of key
28643 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28644 * @returns {ReadableStream<String>} ASCII armor.
28645 */
28646 armor(config = defaultConfig) {
28647 return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28648 }
28649
28650 /**
28651 * Returns all keys that are available for decryption, matching the keyID when given
28652 * This is useful to retrieve keys for session key decryption
28653 * @param {module:type/keyid~KeyID} keyID, optional
28654 * @param {Date} date, optional
28655 * @param {String} userID, optional
28656 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28657 * @returns {Promise<Array<Key|Subkey>>} Array of decryption keys.
28658 * @async
28659 */
28660 async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {
28661 const primaryKey = this.keyPacket;
28662 const keys = [];
28663 for (let i = 0; i < this.subkeys.length; i++) {
28664 if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {
28665 try {
28666 const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };
28667 const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
28668 if (isValidDecryptionKeyPacket(bindingSignature, config)) {
28669 keys.push(this.subkeys[i]);
28670 }
28671 } catch (e) {}
28672 }
28673 }
28674
28675 // evaluate primary key
28676 const primaryUser = await this.getPrimaryUser(date, userID, config);
28677 if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&
28678 isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {
28679 keys.push(this);
28680 }
28681
28682 return keys;
28683 }
28684
28685 /**
28686 * Returns true if the primary key or any subkey is decrypted.
28687 * A dummy key is considered encrypted.
28688 */
28689 isDecrypted() {
28690 return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
28691 }
28692
28693 /**
28694 * Check whether the private and public primary key parameters correspond
28695 * Together with verification of binding signatures, this guarantees key integrity
28696 * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
28697 * otherwise all encryption subkeys are validated
28698 * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
28699 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28700 * @throws {Error} if validation was not successful and the key cannot be trusted
28701 * @async
28702 */
28703 async validate(config = defaultConfig) {
28704 if (!this.isPrivate()) {
28705 throw new Error('Cannot validate a public key');
28706 }
28707
28708 let signingKeyPacket;
28709 if (!this.keyPacket.isDummy()) {
28710 signingKeyPacket = this.keyPacket;
28711 } else {
28712 /**
28713 * It is enough to validate any signing keys
28714 * since its binding signatures are also checked
28715 */
28716 const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });
28717 // This could again be a dummy key
28718 if (signingKey && !signingKey.keyPacket.isDummy()) {
28719 signingKeyPacket = signingKey.keyPacket;
28720 }
28721 }
28722
28723 if (signingKeyPacket) {
28724 return signingKeyPacket.validate();
28725 } else {
28726 const keys = this.getKeys();
28727 const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
28728 if (allDummies) {
28729 throw new Error('Cannot validate an all-gnu-dummy key');
28730 }
28731
28732 return Promise.all(keys.map(async key => key.keyPacket.validate()));
28733 }
28734 }
28735
28736 /**
28737 * Clear private key parameters
28738 */
28739 clearPrivateParams() {
28740 this.getKeys().forEach(({ keyPacket }) => {
28741 if (keyPacket.isDecrypted()) {
28742 keyPacket.clearPrivateParams();
28743 }
28744 });
28745 }
28746
28747 /**
28748 * Revokes the key
28749 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
28750 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
28751 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
28752 * @param {Date} date - optional, override the creationtime of the revocation signature
28753 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28754 * @returns {Promise<PrivateKey>} New key with revocation signature.
28755 * @async
28756 */
28757 async revoke(
28758 {
28759 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
28760 string: reasonForRevocationString = ''
28761 } = {},
28762 date = new Date(),
28763 config = defaultConfig
28764 ) {
28765 if (!this.isPrivate()) {
28766 throw new Error('Need private key for revoking');
28767 }
28768 const dataToSign = { key: this.keyPacket };
28769 const key = this.clone();
28770 key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, {
28771 signatureType: enums.signature.keyRevocation,
28772 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
28773 reasonForRevocationString
28774 }, date, undefined, undefined, config));
28775 return key;
28776 }
28777
28778
28779 /**
28780 * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
28781 * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
28782 * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA
28783 * @param {String} options.curve (optional) Elliptic curve for ECC keys
28784 * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys
28785 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28786 * @param {Date} options.date (optional) Override the creation date of the key and the key signatures
28787 * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
28788 * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}
28789 * @returns {Promise<PrivateKey>}
28790 * @async
28791 */
28792 async addSubkey(options = {}) {
28793 const config = { ...defaultConfig, ...options.config };
28794 if (options.passphrase) {
28795 throw new Error('Subkey could not be encrypted here, please encrypt whole key');
28796 }
28797 if (options.rsaBits < config.minRSABits) {
28798 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);
28799 }
28800 const secretKeyPacket = this.keyPacket;
28801 if (secretKeyPacket.isDummy()) {
28802 throw new Error('Cannot add subkey to gnu-dummy primary key');
28803 }
28804 if (!secretKeyPacket.isDecrypted()) {
28805 throw new Error('Key is not decrypted');
28806 }
28807 const defaultOptions = secretKeyPacket.getAlgorithmInfo();
28808 defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA
28809 defaultOptions.rsaBits = defaultOptions.bits || 4096;
28810 defaultOptions.curve = defaultOptions.curve || 'curve25519';
28811 options = sanitizeKeyOptions(options, defaultOptions);
28812 const keyPacket = await generateSecretSubkey(options);
28813 checkKeyRequirements(keyPacket, config);
28814 const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config);
28815 const packetList = this.toPacketList();
28816 packetList.push(keyPacket, bindingSignature);
28817 return new PrivateKey(packetList);
28818 }
28819}
28820
28821// OpenPGP.js - An OpenPGP implementation in javascript
28822
28823// A Key can contain the following packets
28824const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([
28825 PublicKeyPacket,
28826 PublicSubkeyPacket,
28827 SecretKeyPacket,
28828 SecretSubkeyPacket,
28829 UserIDPacket,
28830 UserAttributePacket,
28831 SignaturePacket
28832]);
28833
28834/**
28835 * Generates a new OpenPGP key. Supports RSA and ECC keys.
28836 * By default, primary and subkeys will be of same type.
28837 * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA
28838 * @param {String} options.curve Elliptic curve for ECC keys
28839 * @param {Integer} options.rsaBits Number of bits for RSA keys
28840 * @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' }
28841 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28842 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28843 * @param {Date} options.date Creation date of the key and the key signatures
28844 * @param {Object} config - Full configuration
28845 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28846 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
28847 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28848 * @async
28849 * @static
28850 * @private
28851 */
28852async function generate$2(options, config) {
28853 options.sign = true; // primary key is always a signing key
28854 options = sanitizeKeyOptions(options);
28855 options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
28856 let promises = [generateSecretKey(options, config)];
28857 promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
28858 const packets = await Promise.all(promises);
28859
28860 const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);
28861 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28862 key.revocationSignatures = [];
28863 return { key, revocationCertificate };
28864}
28865
28866/**
28867 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
28868 * @param {PrivateKey} options.privateKey The private key to reformat
28869 * @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' }
28870 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28871 * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires
28872 * @param {Date} options.date Override the creation date of the key signatures
28873 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28874 * @param {Object} config - Full configuration
28875 *
28876 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28877 * @async
28878 * @static
28879 * @private
28880 */
28881async function reformat(options, config) {
28882 options = sanitize(options);
28883 const { privateKey } = options;
28884
28885 if (!privateKey.isPrivate()) {
28886 throw new Error('Cannot reformat a public key');
28887 }
28888
28889 if (privateKey.keyPacket.isDummy()) {
28890 throw new Error('Cannot reformat a gnu-dummy primary key');
28891 }
28892
28893 const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
28894 if (!isDecrypted) {
28895 throw new Error('Key is not decrypted');
28896 }
28897
28898 const secretKeyPacket = privateKey.keyPacket;
28899
28900 if (!options.subkeys) {
28901 options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {
28902 const secretSubkeyPacket = subkey.keyPacket;
28903 const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };
28904 const bindingSignature = await (
28905 getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)
28906 ).catch(() => ({}));
28907 return {
28908 sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)
28909 };
28910 }));
28911 }
28912
28913 const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);
28914 if (options.subkeys.length !== secretSubkeyPackets.length) {
28915 throw new Error('Number of subkey options does not match number of subkeys');
28916 }
28917
28918 options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));
28919
28920 const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
28921 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28922 key.revocationSignatures = [];
28923 return { key, revocationCertificate };
28924
28925 function sanitize(options, subkeyDefaults = {}) {
28926 options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
28927 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
28928 options.date = options.date || subkeyDefaults.date;
28929
28930 return options;
28931 }
28932}
28933
28934/**
28935 * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection
28936 * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.
28937 * @param {SecretKeyPacket} secretKeyPacket
28938 * @param {SecretSubkeyPacket} secretSubkeyPackets
28939 * @param {Object} options
28940 * @param {Object} config - Full configuration
28941 * @returns {PrivateKey}
28942 */
28943async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
28944 // set passphrase protection
28945 if (options.passphrase) {
28946 await secretKeyPacket.encrypt(options.passphrase, config);
28947 }
28948
28949 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
28950 const subkeyPassphrase = options.subkeys[index].passphrase;
28951 if (subkeyPassphrase) {
28952 await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
28953 }
28954 }));
28955
28956 const packetlist = new PacketList();
28957 packetlist.push(secretKeyPacket);
28958
28959 await Promise.all(options.userIDs.map(async function(userID, index) {
28960 function createPreferredAlgos(algos, preferredAlgo) {
28961 return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];
28962 }
28963
28964 const userIDPacket = UserIDPacket.fromObject(userID);
28965 const dataToSign = {};
28966 dataToSign.userID = userIDPacket;
28967 dataToSign.key = secretKeyPacket;
28968 const signaturePacket = new SignaturePacket();
28969 signaturePacket.signatureType = enums.signature.certGeneric;
28970 signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
28971 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, secretKeyPacket, undefined, undefined, config);
28972 signaturePacket.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
28973 signaturePacket.preferredSymmetricAlgorithms = createPreferredAlgos([
28974 // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
28975 enums.symmetric.aes256,
28976 enums.symmetric.aes128,
28977 enums.symmetric.aes192
28978 ], config.preferredSymmetricAlgorithm);
28979 if (config.aeadProtect) {
28980 signaturePacket.preferredAEADAlgorithms = createPreferredAlgos([
28981 enums.aead.eax,
28982 enums.aead.ocb
28983 ], config.preferredAEADAlgorithm);
28984 }
28985 signaturePacket.preferredHashAlgorithms = createPreferredAlgos([
28986 // prefer fast asm.js implementations (SHA-256)
28987 enums.hash.sha256,
28988 enums.hash.sha512
28989 ], config.preferredHashAlgorithm);
28990 signaturePacket.preferredCompressionAlgorithms = createPreferredAlgos([
28991 enums.compression.zlib,
28992 enums.compression.zip,
28993 enums.compression.uncompressed
28994 ], config.preferredCompressionAlgorithm);
28995 if (index === 0) {
28996 signaturePacket.isPrimaryUserID = true;
28997 }
28998 // integrity protection always enabled
28999 signaturePacket.features = [0];
29000 signaturePacket.features[0] |= enums.features.modificationDetection;
29001 if (config.aeadProtect) {
29002 signaturePacket.features[0] |= enums.features.aead;
29003 }
29004 if (config.v5Keys) {
29005 signaturePacket.features[0] |= enums.features.v5Keys;
29006 }
29007 if (options.keyExpirationTime > 0) {
29008 signaturePacket.keyExpirationTime = options.keyExpirationTime;
29009 signaturePacket.keyNeverExpires = false;
29010 }
29011 await signaturePacket.sign(secretKeyPacket, dataToSign, options.date);
29012
29013 return { userIDPacket, signaturePacket };
29014 })).then(list => {
29015 list.forEach(({ userIDPacket, signaturePacket }) => {
29016 packetlist.push(userIDPacket);
29017 packetlist.push(signaturePacket);
29018 });
29019 });
29020
29021 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29022 const subkeyOptions = options.subkeys[index];
29023 const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
29024 return { secretSubkeyPacket, subkeySignaturePacket };
29025 })).then(packets => {
29026 packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
29027 packetlist.push(secretSubkeyPacket);
29028 packetlist.push(subkeySignaturePacket);
29029 });
29030 });
29031
29032 // Add revocation signature packet for creating a revocation certificate.
29033 // This packet should be removed before returning the key.
29034 const dataToSign = { key: secretKeyPacket };
29035 packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, {
29036 signatureType: enums.signature.keyRevocation,
29037 reasonForRevocationFlag: enums.reasonForRevocation.noReason,
29038 reasonForRevocationString: ''
29039 }, options.date, undefined, undefined, config));
29040
29041 if (options.passphrase) {
29042 secretKeyPacket.clearPrivateParams();
29043 }
29044
29045 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29046 const subkeyPassphrase = options.subkeys[index].passphrase;
29047 if (subkeyPassphrase) {
29048 secretSubkeyPacket.clearPrivateParams();
29049 }
29050 }));
29051
29052 return new PrivateKey(packetlist);
29053}
29054
29055/**
29056 * Reads an (optionally armored) OpenPGP key and returns a key object
29057 * @param {Object} options
29058 * @param {String} [options.armoredKey] - Armored key to be parsed
29059 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29060 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29061 * @returns {Promise<Key>} Key object.
29062 * @async
29063 * @static
29064 */
29065async function readKey({ armoredKey, binaryKey, config, ...rest }) {
29066 config = { ...defaultConfig, ...config };
29067 if (!armoredKey && !binaryKey) {
29068 throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
29069 }
29070 if (armoredKey && !util.isString(armoredKey)) {
29071 throw new Error('readKey: options.armoredKey must be a string');
29072 }
29073 if (binaryKey && !util.isUint8Array(binaryKey)) {
29074 throw new Error('readKey: options.binaryKey must be a Uint8Array');
29075 }
29076 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29077
29078 let input;
29079 if (armoredKey) {
29080 const { type, data } = await unarmor(armoredKey, config);
29081 if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
29082 throw new Error('Armored text not of type key');
29083 }
29084 input = data;
29085 } else {
29086 input = binaryKey;
29087 }
29088 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29089 return createKey(packetlist);
29090}
29091
29092/**
29093 * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object
29094 * @param {Object} options
29095 * @param {String} [options.armoredKey] - Armored key to be parsed
29096 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29097 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29098 * @returns {Promise<PrivateKey>} Key object.
29099 * @async
29100 * @static
29101 */
29102async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {
29103 config = { ...defaultConfig, ...config };
29104 if (!armoredKey && !binaryKey) {
29105 throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');
29106 }
29107 if (armoredKey && !util.isString(armoredKey)) {
29108 throw new Error('readPrivateKey: options.armoredKey must be a string');
29109 }
29110 if (binaryKey && !util.isUint8Array(binaryKey)) {
29111 throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');
29112 }
29113 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29114
29115 let input;
29116 if (armoredKey) {
29117 const { type, data } = await unarmor(armoredKey, config);
29118 if (!(type === enums.armor.privateKey)) {
29119 throw new Error('Armored text not of type private key');
29120 }
29121 input = data;
29122 } else {
29123 input = binaryKey;
29124 }
29125 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29126 return new PrivateKey(packetlist);
29127}
29128
29129/**
29130 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
29131 * @param {Object} options
29132 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29133 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29134 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29135 * @returns {Promise<Array<Key>>} Key objects.
29136 * @async
29137 * @static
29138 */
29139async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {
29140 config = { ...defaultConfig, ...config };
29141 let input = armoredKeys || binaryKeys;
29142 if (!input) {
29143 throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29144 }
29145 if (armoredKeys && !util.isString(armoredKeys)) {
29146 throw new Error('readKeys: options.armoredKeys must be a string');
29147 }
29148 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29149 throw new Error('readKeys: options.binaryKeys must be a Uint8Array');
29150 }
29151 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29152
29153 if (armoredKeys) {
29154 const { type, data } = await unarmor(armoredKeys, config);
29155 if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
29156 throw new Error('Armored text not of type key');
29157 }
29158 input = data;
29159 }
29160 const keys = [];
29161 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29162 const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
29163 if (keyIndex.length === 0) {
29164 throw new Error('No key packet found');
29165 }
29166 for (let i = 0; i < keyIndex.length; i++) {
29167 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29168 const newKey = createKey(oneKeyList);
29169 keys.push(newKey);
29170 }
29171 return keys;
29172}
29173
29174/**
29175 * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects
29176 * @param {Object} options
29177 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29178 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29179 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29180 * @returns {Promise<Array<PrivateKey>>} Key objects.
29181 * @async
29182 * @static
29183 */
29184async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {
29185 config = { ...defaultConfig, ...config };
29186 let input = armoredKeys || binaryKeys;
29187 if (!input) {
29188 throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29189 }
29190 if (armoredKeys && !util.isString(armoredKeys)) {
29191 throw new Error('readPrivateKeys: options.armoredKeys must be a string');
29192 }
29193 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29194 throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');
29195 }
29196 if (armoredKeys) {
29197 const { type, data } = await unarmor(armoredKeys, config);
29198 if (type !== enums.armor.privateKey) {
29199 throw new Error('Armored text not of type private key');
29200 }
29201 input = data;
29202 }
29203 const keys = [];
29204 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29205 const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);
29206 if (keyIndex.length === 0) {
29207 throw new Error('No secret key packet found');
29208 }
29209 for (let i = 0; i < keyIndex.length; i++) {
29210 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29211 const newKey = new PrivateKey(oneKeyList);
29212 keys.push(newKey);
29213 }
29214 return keys;
29215}
29216
29217// GPG4Browsers - An OpenPGP implementation in javascript
29218
29219// A Message can contain the following packets
29220const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([
29221 LiteralDataPacket,
29222 CompressedDataPacket,
29223 AEADEncryptedDataPacket,
29224 SymEncryptedIntegrityProtectedDataPacket,
29225 SymmetricallyEncryptedDataPacket,
29226 PublicKeyEncryptedSessionKeyPacket,
29227 SymEncryptedSessionKeyPacket,
29228 OnePassSignaturePacket,
29229 SignaturePacket
29230]);
29231// A SKESK packet can contain the following packets
29232const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);
29233// A detached signature can contain the following packets
29234const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
29235
29236/**
29237 * Class that represents an OpenPGP message.
29238 * Can be an encrypted message, signed message, compressed message or literal message
29239 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
29240 */
29241class Message {
29242 /**
29243 * @param {PacketList} packetlist - The packets that form this message
29244 */
29245 constructor(packetlist) {
29246 this.packets = packetlist || new PacketList();
29247 }
29248
29249 /**
29250 * Returns the key IDs of the keys to which the session key is encrypted
29251 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29252 */
29253 getEncryptionKeyIDs() {
29254 const keyIDs = [];
29255 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29256 pkESKeyPacketlist.forEach(function(packet) {
29257 keyIDs.push(packet.publicKeyID);
29258 });
29259 return keyIDs;
29260 }
29261
29262 /**
29263 * Returns the key IDs of the keys that signed the message
29264 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29265 */
29266 getSigningKeyIDs() {
29267 const msg = this.unwrapCompressed();
29268 // search for one pass signatures
29269 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
29270 if (onePassSigList.length > 0) {
29271 return onePassSigList.map(packet => packet.issuerKeyID);
29272 }
29273 // if nothing found look for signature packets
29274 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29275 return signatureList.map(packet => packet.issuerKeyID);
29276 }
29277
29278 /**
29279 * Decrypt the message. Either a private key, a session key, or a password must be specified.
29280 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29281 * @param {Array<String>} [passwords] - Passwords used to decrypt
29282 * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29283 * @param {Date} [date] - Use the given date for key verification instead of the current time
29284 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29285 * @returns {Promise<Message>} New message with decrypted content.
29286 * @async
29287 */
29288 async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {
29289 const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);
29290
29291 const symEncryptedPacketlist = this.packets.filterByTag(
29292 enums.packet.symmetricallyEncryptedData,
29293 enums.packet.symEncryptedIntegrityProtectedData,
29294 enums.packet.aeadEncryptedData
29295 );
29296
29297 if (symEncryptedPacketlist.length === 0) {
29298 throw new Error('No encrypted data found');
29299 }
29300
29301 const symEncryptedPacket = symEncryptedPacketlist[0];
29302 let exception = null;
29303 const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {
29304 if (!util.isUint8Array(data) || !util.isString(algorithmName)) {
29305 throw new Error('Invalid session key for decryption.');
29306 }
29307
29308 try {
29309 const algo = enums.write(enums.symmetric, algorithmName);
29310 await symEncryptedPacket.decrypt(algo, data, config);
29311 } catch (e) {
29312 util.printDebugError(e);
29313 exception = e;
29314 }
29315 }));
29316 // We don't await stream.cancel here because it only returns when the other copy is canceled too.
29317 cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
29318 symEncryptedPacket.encrypted = null;
29319 await decryptedPromise;
29320
29321 if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
29322 throw exception || new Error('Decryption failed.');
29323 }
29324
29325 const resultMsg = new Message(symEncryptedPacket.packets);
29326 symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
29327
29328 return resultMsg;
29329 }
29330
29331 /**
29332 * Decrypt encrypted session keys either with private keys or passwords.
29333 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29334 * @param {Array<String>} [passwords] - Passwords used to decrypt
29335 * @param {Date} [date] - Use the given date for key verification, instead of current time
29336 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29337 * @returns {Promise<Array<{
29338 * data: Uint8Array,
29339 * algorithm: String
29340 * }>>} array of object with potential sessionKey, algorithm pairs
29341 * @async
29342 */
29343 async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {
29344 let decryptedSessionKeyPackets = [];
29345
29346 let exception;
29347 if (passwords) {
29348 const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
29349 if (skeskPackets.length === 0) {
29350 throw new Error('No symmetrically encrypted session key packet found.');
29351 }
29352 await Promise.all(passwords.map(async function(password, i) {
29353 let packets;
29354 if (i) {
29355 packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);
29356 } else {
29357 packets = skeskPackets;
29358 }
29359 await Promise.all(packets.map(async function(skeskPacket) {
29360 try {
29361 await skeskPacket.decrypt(password);
29362 decryptedSessionKeyPackets.push(skeskPacket);
29363 } catch (err) {
29364 util.printDebugError(err);
29365 }
29366 }));
29367 }));
29368 } else if (decryptionKeys) {
29369 const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29370 if (pkeskPackets.length === 0) {
29371 throw new Error('No public key encrypted session key packet found.');
29372 }
29373 await Promise.all(pkeskPackets.map(async function(pkeskPacket) {
29374 await Promise.all(decryptionKeys.map(async function(decryptionKey) {
29375 let algos = [
29376 enums.symmetric.aes256, // Old OpenPGP.js default fallback
29377 enums.symmetric.aes128, // RFC4880bis fallback
29378 enums.symmetric.tripledes, // RFC4880 fallback
29379 enums.symmetric.cast5 // Golang OpenPGP fallback
29380 ];
29381 try {
29382 const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.
29383 if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
29384 algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
29385 }
29386 } catch (e) {}
29387
29388 // do not check key expiration to allow decryption of old messages
29389 const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);
29390 await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {
29391 if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {
29392 return;
29393 }
29394 if (!decryptionKeyPacket.isDecrypted()) {
29395 throw new Error('Decryption key is not decrypted.');
29396 }
29397
29398 // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.
29399 const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (
29400 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||
29401 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||
29402 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||
29403 pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal
29404 );
29405
29406 if (doConstantTimeDecryption) {
29407 // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,
29408 // either with the successfully decrypted session key, or with a randomly generated one.
29409 // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on
29410 // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:
29411 // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the
29412 // randomly generated keys of the remaining key types.
29413 // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly
29414 // generated session keys.
29415 // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.
29416
29417 const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times
29418 await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {
29419 const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();
29420 pkeskPacketCopy.read(serialisedPKESK);
29421 const randomSessionKey = {
29422 sessionKeyAlgorithm,
29423 sessionKey: await mod.generateSessionKey(sessionKeyAlgorithm)
29424 };
29425 try {
29426 await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);
29427 decryptedSessionKeyPackets.push(pkeskPacketCopy);
29428 } catch (err) {
29429 // `decrypt` can still throw some non-security-sensitive errors
29430 util.printDebugError(err);
29431 exception = err;
29432 }
29433 }));
29434
29435 } else {
29436 try {
29437 await pkeskPacket.decrypt(decryptionKeyPacket);
29438 if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {
29439 throw new Error('A non-preferred symmetric algorithm was used.');
29440 }
29441 decryptedSessionKeyPackets.push(pkeskPacket);
29442 } catch (err) {
29443 util.printDebugError(err);
29444 exception = err;
29445 }
29446 }
29447 }));
29448 }));
29449 cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.
29450 pkeskPacket.encrypted = null;
29451 }));
29452 } else {
29453 throw new Error('No key or password specified.');
29454 }
29455
29456 if (decryptedSessionKeyPackets.length > 0) {
29457 // Return only unique session keys
29458 if (decryptedSessionKeyPackets.length > 1) {
29459 const seen = new Set();
29460 decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {
29461 const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);
29462 if (seen.has(k)) {
29463 return false;
29464 }
29465 seen.add(k);
29466 return true;
29467 });
29468 }
29469
29470 return decryptedSessionKeyPackets.map(packet => ({
29471 data: packet.sessionKey,
29472 algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)
29473 }));
29474 }
29475 throw exception || new Error('Session key decryption failed.');
29476 }
29477
29478 /**
29479 * Get literal data that is the body of the message
29480 * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
29481 */
29482 getLiteralData() {
29483 const msg = this.unwrapCompressed();
29484 const literal = msg.packets.findPacket(enums.packet.literalData);
29485 return (literal && literal.getBytes()) || null;
29486 }
29487
29488 /**
29489 * Get filename from literal data packet
29490 * @returns {(String|null)} Filename of literal data packet as string.
29491 */
29492 getFilename() {
29493 const msg = this.unwrapCompressed();
29494 const literal = msg.packets.findPacket(enums.packet.literalData);
29495 return (literal && literal.getFilename()) || null;
29496 }
29497
29498 /**
29499 * Get literal data as text
29500 * @returns {(String|null)} Literal body of the message interpreted as text.
29501 */
29502 getText() {
29503 const msg = this.unwrapCompressed();
29504 const literal = msg.packets.findPacket(enums.packet.literalData);
29505 if (literal) {
29506 return literal.getText();
29507 }
29508 return null;
29509 }
29510
29511 /**
29512 * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.
29513 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) to select algorithm preferences for
29514 * @param {Date} [date] - Date to select algorithm preferences at
29515 * @param {Array<Object>} [userIDs] - User IDs to select algorithm preferences for
29516 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29517 * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.
29518 * @async
29519 */
29520 static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {
29521 const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);
29522 const algorithmName = enums.read(enums.symmetric, algo);
29523 const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?
29524 enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :
29525 undefined;
29526
29527 const sessionKeyData = await mod.generateSessionKey(algo);
29528 return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };
29529 }
29530
29531 /**
29532 * Encrypt the message either with public keys, passwords, or both at once.
29533 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29534 * @param {Array<String>} [passwords] - Password(s) for message encryption
29535 * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29536 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29537 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]
29538 * @param {Date} [date] - Override the creation date of the literal package
29539 * @param {Array<Object>} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29540 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29541 * @returns {Promise<Message>} New message with encrypted content.
29542 * @async
29543 */
29544 async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29545 if (sessionKey) {
29546 if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
29547 throw new Error('Invalid session key for encryption.');
29548 }
29549 } else if (encryptionKeys && encryptionKeys.length) {
29550 sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);
29551 } else if (passwords && passwords.length) {
29552 sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);
29553 } else {
29554 throw new Error('No keys, passwords, or session key provided.');
29555 }
29556
29557 const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;
29558
29559 const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);
29560
29561 let symEncryptedPacket;
29562 if (aeadAlgorithmName) {
29563 symEncryptedPacket = new AEADEncryptedDataPacket();
29564 symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);
29565 } else {
29566 symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();
29567 }
29568 symEncryptedPacket.packets = this.packets;
29569
29570 const algorithm = enums.write(enums.symmetric, algorithmName);
29571 await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);
29572
29573 msg.packets.push(symEncryptedPacket);
29574 symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
29575 return msg;
29576 }
29577
29578 /**
29579 * Encrypt a session key either with public keys, passwords, or both at once.
29580 * @param {Uint8Array} sessionKey - session key for encryption
29581 * @param {String} algorithmName - session key algorithm
29582 * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'
29583 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29584 * @param {Array<String>} [passwords] - For message encryption
29585 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29586 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
29587 * @param {Date} [date] - Override the date
29588 * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29589 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29590 * @returns {Promise<Message>} New message with encrypted content.
29591 * @async
29592 */
29593 static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29594 const packetlist = new PacketList();
29595 const algorithm = enums.write(enums.symmetric, algorithmName);
29596 const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);
29597
29598 if (encryptionKeys) {
29599 const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {
29600 const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);
29601 const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();
29602 pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();
29603 pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
29604 pkESKeyPacket.sessionKey = sessionKey;
29605 pkESKeyPacket.sessionKeyAlgorithm = algorithm;
29606 await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
29607 delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
29608 return pkESKeyPacket;
29609 }));
29610 packetlist.push(...results);
29611 }
29612 if (passwords) {
29613 const testDecrypt = async function(keyPacket, password) {
29614 try {
29615 await keyPacket.decrypt(password);
29616 return 1;
29617 } catch (e) {
29618 return 0;
29619 }
29620 };
29621
29622 const sum = (accumulator, currentValue) => accumulator + currentValue;
29623
29624 const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {
29625 const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);
29626 symEncryptedSessionKeyPacket.sessionKey = sessionKey;
29627 symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
29628 if (aeadAlgorithm) {
29629 symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
29630 }
29631 await symEncryptedSessionKeyPacket.encrypt(password, config);
29632
29633 if (config.passwordCollisionCheck) {
29634 const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
29635 if (results.reduce(sum) !== 1) {
29636 return encryptPassword(sessionKey, algorithm, password);
29637 }
29638 }
29639
29640 delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
29641 return symEncryptedSessionKeyPacket;
29642 };
29643
29644 const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));
29645 packetlist.push(...results);
29646 }
29647
29648 return new Message(packetlist);
29649 }
29650
29651 /**
29652 * Sign the message (the literal data packet of the message)
29653 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29654 * @param {Signature} [signature] - Any existing detached signature to add to the message
29655 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29656 * @param {Date} [date] - Override the creation time of the signature
29657 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29658 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29659 * @returns {Promise<Message>} New message with signed content.
29660 * @async
29661 */
29662 async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29663 const packetlist = new PacketList();
29664
29665 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29666 if (!literalDataPacket) {
29667 throw new Error('No literal data packet to sign.');
29668 }
29669
29670 let i;
29671 let existingSigPacketlist;
29672 // If data packet was created from Uint8Array, use binary, otherwise use text
29673 const signatureType = literalDataPacket.text === null ?
29674 enums.signature.binary : enums.signature.text;
29675
29676 if (signature) {
29677 existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29678 for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
29679 const signaturePacket = existingSigPacketlist[i];
29680 const onePassSig = new OnePassSignaturePacket();
29681 onePassSig.signatureType = signaturePacket.signatureType;
29682 onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
29683 onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
29684 onePassSig.issuerKeyID = signaturePacket.issuerKeyID;
29685 if (!signingKeys.length && i === 0) {
29686 onePassSig.flags = 1;
29687 }
29688 packetlist.push(onePassSig);
29689 }
29690 }
29691
29692 await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {
29693 if (!primaryKey.isPrivate()) {
29694 throw new Error('Need private key for signing');
29695 }
29696 const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];
29697 const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);
29698 const onePassSig = new OnePassSignaturePacket();
29699 onePassSig.signatureType = signatureType;
29700 onePassSig.hashAlgorithm = await getPreferredHashAlgo$1(primaryKey, signingKey.keyPacket, date, userIDs, config);
29701 onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
29702 onePassSig.issuerKeyID = signingKey.getKeyID();
29703 if (i === signingKeys.length - 1) {
29704 onePassSig.flags = 1;
29705 }
29706 return onePassSig;
29707 })).then(onePassSignatureList => {
29708 onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
29709 });
29710
29711 packetlist.push(literalDataPacket);
29712 packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, false, config)));
29713
29714 return new Message(packetlist);
29715 }
29716
29717 /**
29718 * Compresses the message (the literal and -if signed- signature data packets of the message)
29719 * @param {module:enums.compression} algo - compression algorithm
29720 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29721 * @returns {Message} New message with compressed content.
29722 */
29723 compress(algo, config = defaultConfig) {
29724 if (algo === enums.compression.uncompressed) {
29725 return this;
29726 }
29727
29728 const compressed = new CompressedDataPacket(config);
29729 compressed.algorithm = algo;
29730 compressed.packets = this.packets;
29731
29732 const packetList = new PacketList();
29733 packetList.push(compressed);
29734
29735 return new Message(packetList);
29736 }
29737
29738 /**
29739 * Create a detached signature for the message (the literal data packet of the message)
29740 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29741 * @param {Signature} [signature] - Any existing detached signature
29742 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29743 * @param {Date} [date] - Override the creation time of the signature
29744 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29745 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29746 * @returns {Promise<Signature>} New detached signature of message content.
29747 * @async
29748 */
29749 async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29750 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29751 if (!literalDataPacket) {
29752 throw new Error('No literal data packet to sign.');
29753 }
29754 return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, true, config));
29755 }
29756
29757 /**
29758 * Verify message signatures
29759 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29760 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29761 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29762 * @returns {Promise<Array<{
29763 * keyID: module:type/keyid~KeyID,
29764 * signature: Promise<Signature>,
29765 * verified: Promise<true>
29766 * }>>} List of signer's keyID and validity of signatures.
29767 * @async
29768 */
29769 async verify(verificationKeys, date = new Date(), config = defaultConfig) {
29770 const msg = this.unwrapCompressed();
29771 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29772 if (literalDataList.length !== 1) {
29773 throw new Error('Can only verify message with one literal data packet.');
29774 }
29775 if (isArrayStream(msg.packets.stream)) {
29776 msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || []));
29777 }
29778 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
29779 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29780 if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) {
29781 await Promise.all(onePassSigList.map(async onePassSig => {
29782 onePassSig.correspondingSig = new Promise((resolve, reject) => {
29783 onePassSig.correspondingSigResolve = resolve;
29784 onePassSig.correspondingSigReject = reject;
29785 });
29786 onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
29787 onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));
29788 onePassSig.hashed.catch(() => {});
29789 }));
29790 msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => {
29791 const reader = getReader(readable);
29792 const writer = getWriter(writable);
29793 try {
29794 for (let i = 0; i < onePassSigList.length; i++) {
29795 const { value: signature } = await reader.read();
29796 onePassSigList[i].correspondingSigResolve(signature);
29797 }
29798 await reader.readToEnd();
29799 await writer.ready;
29800 await writer.close();
29801 } catch (e) {
29802 onePassSigList.forEach(onePassSig => {
29803 onePassSig.correspondingSigReject(e);
29804 });
29805 await writer.abort(e);
29806 }
29807 });
29808 return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);
29809 }
29810 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);
29811 }
29812
29813 /**
29814 * Verify detached message signature
29815 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29816 * @param {Signature} signature
29817 * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29818 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29819 * @returns {Promise<Array<{
29820 * keyID: module:type/keyid~KeyID,
29821 * signature: Promise<Signature>,
29822 * verified: Promise<true>
29823 * }>>} List of signer's keyID and validity of signature.
29824 * @async
29825 */
29826 verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {
29827 const msg = this.unwrapCompressed();
29828 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29829 if (literalDataList.length !== 1) {
29830 throw new Error('Can only verify message with one literal data packet.');
29831 }
29832 const signatureList = signature.packets;
29833 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);
29834 }
29835
29836 /**
29837 * Unwrap compressed message
29838 * @returns {Message} Message Content of compressed message.
29839 */
29840 unwrapCompressed() {
29841 const compressed = this.packets.filterByTag(enums.packet.compressedData);
29842 if (compressed.length) {
29843 return new Message(compressed[0].packets);
29844 }
29845 return this;
29846 }
29847
29848 /**
29849 * Append signature to unencrypted message object
29850 * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
29851 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29852 */
29853 async appendSignature(detachedSignature, config = defaultConfig) {
29854 await this.packets.read(
29855 util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,
29856 allowedDetachedSignaturePackets,
29857 config
29858 );
29859 }
29860
29861 /**
29862 * Returns binary encoded message
29863 * @returns {ReadableStream<Uint8Array>} Binary message.
29864 */
29865 write() {
29866 return this.packets.write();
29867 }
29868
29869 /**
29870 * Returns ASCII armored text of message
29871 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29872 * @returns {ReadableStream<String>} ASCII armor.
29873 */
29874 armor(config = defaultConfig) {
29875 return armor(enums.armor.message, this.write(), null, null, null, config);
29876 }
29877}
29878
29879/**
29880 * Create signature packets for the message
29881 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
29882 * @param {Array<PrivateKey>} [signingKeys] - private keys with decrypted secret key data for signing
29883 * @param {Signature} [signature] - Any existing detached signature to append
29884 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29885 * @param {Date} [date] - Override the creationtime of the signature
29886 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29887 * @param {Boolean} [detached] - Whether to create detached signature packets
29888 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29889 * @returns {Promise<PacketList>} List of signature packets.
29890 * @async
29891 * @private
29892 */
29893async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], detached = false, config = defaultConfig) {
29894 const packetlist = new PacketList();
29895
29896 // If data packet was created from Uint8Array, use binary, otherwise use text
29897 const signatureType = literalDataPacket.text === null ?
29898 enums.signature.binary : enums.signature.text;
29899
29900 await Promise.all(signingKeys.map(async (primaryKey, i) => {
29901 const userID = userIDs[i];
29902 if (!primaryKey.isPrivate()) {
29903 throw new Error('Need private key for signing');
29904 }
29905 const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);
29906 return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, detached, config);
29907 })).then(signatureList => {
29908 packetlist.push(...signatureList);
29909 });
29910
29911 if (signature) {
29912 const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29913 packetlist.push(...existingSigPacketlist);
29914 }
29915 return packetlist;
29916}
29917
29918/**
29919 * Create object containing signer's keyID and validity of signature
29920 * @param {SignaturePacket} signature - Signature packet
29921 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
29922 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29923 * @param {Date} [date] - Check signature validity with respect to the given date
29924 * @param {Boolean} [detached] - Whether to verify detached signature packets
29925 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29926 * @returns {Promise<{
29927 * keyID: module:type/keyid~KeyID,
29928 * signature: Promise<Signature>,
29929 * verified: Promise<true>
29930 * }>} signer's keyID and validity of signature
29931 * @async
29932 * @private
29933 */
29934async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
29935 let primaryKey;
29936 let unverifiedSigningKey;
29937
29938 for (const key of verificationKeys) {
29939 const issuerKeys = key.getKeys(signature.issuerKeyID);
29940 if (issuerKeys.length > 0) {
29941 primaryKey = key;
29942 unverifiedSigningKey = issuerKeys[0];
29943 break;
29944 }
29945 }
29946
29947 const isOnePassSignature = signature instanceof OnePassSignaturePacket;
29948 const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;
29949
29950 const verifiedSig = {
29951 keyID: signature.issuerKeyID,
29952 verified: (async () => {
29953 if (!unverifiedSigningKey) {
29954 throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);
29955 }
29956
29957 await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);
29958 const signaturePacket = await signaturePacketPromise;
29959 if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {
29960 throw new Error('Key is newer than the signature');
29961 }
29962 // We pass the signature creation time to check whether the key was expired at the time of signing.
29963 // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before
29964 try {
29965 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);
29966 } catch (e) {
29967 // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,
29968 // making the key invalid at the time of signing.
29969 // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.
29970 // Note: we do not support the edge case of a key that was reformatted and it has expired.
29971 if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {
29972 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);
29973 } else {
29974 throw e;
29975 }
29976 }
29977 return true;
29978 })(),
29979 signature: (async () => {
29980 const signaturePacket = await signaturePacketPromise;
29981 const packetlist = new PacketList();
29982 signaturePacket && packetlist.push(signaturePacket);
29983 return new Signature(packetlist);
29984 })()
29985 };
29986
29987 // Mark potential promise rejections as "handled". This is needed because in
29988 // some cases, we reject them before the user has a reasonable chance to
29989 // handle them (e.g. `await readToEnd(result.data); await result.verified` and
29990 // the data stream errors).
29991 verifiedSig.signature.catch(() => {});
29992 verifiedSig.verified.catch(() => {});
29993
29994 return verifiedSig;
29995}
29996
29997/**
29998 * Create list of objects containing signer's keyID and validity of signature
29999 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
30000 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
30001 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30002 * @param {Date} date - Verify the signature against the given date,
30003 * i.e. check signature creation time < date < expiration time
30004 * @param {Boolean} [detached] - Whether to verify detached signature packets
30005 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30006 * @returns {Promise<Array<{
30007 * keyID: module:type/keyid~KeyID,
30008 * signature: Promise<Signature>,
30009 * verified: Promise<true>
30010 * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)
30011 * @async
30012 * @private
30013 */
30014async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
30015 return Promise.all(signatureList.filter(function(signature) {
30016 return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
30017 }).map(async function(signature) {
30018 return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);
30019 }));
30020}
30021
30022/**
30023 * Reads an (optionally armored) OpenPGP message and returns a Message object
30024 * @param {Object} options
30025 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
30026 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
30027 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30028 * @returns {Promise<Message>} New message object.
30029 * @async
30030 * @static
30031 */
30032async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {
30033 config = { ...defaultConfig, ...config };
30034 let input = armoredMessage || binaryMessage;
30035 if (!input) {
30036 throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
30037 }
30038 if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {
30039 throw new Error('readMessage: options.armoredMessage must be a string or stream');
30040 }
30041 if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {
30042 throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');
30043 }
30044 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30045
30046 const streamType = util.isStream(input);
30047 if (streamType) {
30048 await loadStreamsPonyfill();
30049 input = toStream(input);
30050 }
30051 if (armoredMessage) {
30052 const { type, data } = await unarmor(input, config);
30053 if (type !== enums.armor.message) {
30054 throw new Error('Armored text not of type message');
30055 }
30056 input = data;
30057 }
30058 const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);
30059 const message = new Message(packetlist);
30060 message.fromStream = streamType;
30061 return message;
30062}
30063
30064/**
30065 * Creates new message object from text or binary data.
30066 * @param {Object} options
30067 * @param {String | ReadableStream<String>} [options.text] - The text message contents
30068 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binary] - The binary message contents
30069 * @param {String} [options.filename=""] - Name of the file (if any)
30070 * @param {Date} [options.date=current date] - Date of the message, or modification date of the file
30071 * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type
30072 * @returns {Promise<Message>} New message object.
30073 * @async
30074 * @static
30075 */
30076async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {
30077 let input = text !== undefined ? text : binary;
30078 if (input === undefined) {
30079 throw new Error('createMessage: must pass options object containing `text` or `binary`');
30080 }
30081 if (text && !util.isString(text) && !util.isStream(text)) {
30082 throw new Error('createMessage: options.text must be a string or stream');
30083 }
30084 if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {
30085 throw new Error('createMessage: options.binary must be a Uint8Array or stream');
30086 }
30087 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30088
30089 const streamType = util.isStream(input);
30090 if (streamType) {
30091 await loadStreamsPonyfill();
30092 input = toStream(input);
30093 }
30094 const literalDataPacket = new LiteralDataPacket(date);
30095 if (text !== undefined) {
30096 literalDataPacket.setText(input, enums.write(enums.literal, format));
30097 } else {
30098 literalDataPacket.setBytes(input, enums.write(enums.literal, format));
30099 }
30100 if (filename !== undefined) {
30101 literalDataPacket.setFilename(filename);
30102 }
30103 const literalDataPacketlist = new PacketList();
30104 literalDataPacketlist.push(literalDataPacket);
30105 const message = new Message(literalDataPacketlist);
30106 message.fromStream = streamType;
30107 return message;
30108}
30109
30110// GPG4Browsers - An OpenPGP implementation in javascript
30111
30112// A Cleartext message can contain the following packets
30113const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
30114
30115/**
30116 * Class that represents an OpenPGP cleartext signed message.
30117 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
30118 */
30119class CleartextMessage {
30120 /**
30121 * @param {String} text - The cleartext of the signed message
30122 * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
30123 */
30124 constructor(text, signature) {
30125 // normalize EOL to canonical form <CR><LF>
30126 this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
30127 if (signature && !(signature instanceof Signature)) {
30128 throw new Error('Invalid signature input');
30129 }
30130 this.signature = signature || new Signature(new PacketList());
30131 }
30132
30133 /**
30134 * Returns the key IDs of the keys that signed the cleartext message
30135 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
30136 */
30137 getSigningKeyIDs() {
30138 const keyIDs = [];
30139 const signatureList = this.signature.packets;
30140 signatureList.forEach(function(packet) {
30141 keyIDs.push(packet.issuerKeyID);
30142 });
30143 return keyIDs;
30144 }
30145
30146 /**
30147 * Sign the cleartext message
30148 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
30149 * @param {Signature} [signature] - Any existing detached signature
30150 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
30151 * @param {Date} [date] - The creation time of the signature that should be created
30152 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30153 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30154 * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
30155 * @async
30156 */
30157 async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
30158 const literalDataPacket = new LiteralDataPacket();
30159 literalDataPacket.setText(this.text);
30160 const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, true, config));
30161 return new CleartextMessage(this.text, newSignature);
30162 }
30163
30164 /**
30165 * Verify signatures of cleartext signed message
30166 * @param {Array<Key>} keys - Array of keys to verify signatures
30167 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
30168 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30169 * @returns {Promise<Array<{
30170 * keyID: module:type/keyid~KeyID,
30171 * signature: Promise<Signature>,
30172 * verified: Promise<true>
30173 * }>>} List of signer's keyID and validity of signature.
30174 * @async
30175 */
30176 verify(keys, date = new Date(), config = defaultConfig) {
30177 const signatureList = this.signature.packets;
30178 const literalDataPacket = new LiteralDataPacket();
30179 // we assume that cleartext signature is generated based on UTF8 cleartext
30180 literalDataPacket.setText(this.text);
30181 return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);
30182 }
30183
30184 /**
30185 * Get cleartext
30186 * @returns {String} Cleartext of message.
30187 */
30188 getText() {
30189 // normalize end of line to \n
30190 return this.text.replace(/\r\n/g, '\n');
30191 }
30192
30193 /**
30194 * Returns ASCII armored text of cleartext signed message
30195 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30196 * @returns {String | ReadableStream<String>} ASCII armor.
30197 */
30198 armor(config = defaultConfig) {
30199 let hashes = this.signature.packets.map(function(packet) {
30200 return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();
30201 });
30202 hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });
30203 const body = {
30204 hash: hashes.join(),
30205 text: this.text,
30206 data: this.signature.packets.write()
30207 };
30208 return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
30209 }
30210}
30211
30212/**
30213 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
30214 * @param {Object} options
30215 * @param {String} options.cleartextMessage - Text to be parsed
30216 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30217 * @returns {Promise<CleartextMessage>} New cleartext message object.
30218 * @async
30219 * @static
30220 */
30221async function readCleartextMessage({ cleartextMessage, config, ...rest }) {
30222 config = { ...defaultConfig, ...config };
30223 if (!cleartextMessage) {
30224 throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
30225 }
30226 if (!util.isString(cleartextMessage)) {
30227 throw new Error('readCleartextMessage: options.cleartextMessage must be a string');
30228 }
30229 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30230
30231 const input = await unarmor(cleartextMessage);
30232 if (input.type !== enums.armor.signed) {
30233 throw new Error('No cleartext signed message.');
30234 }
30235 const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config);
30236 verifyHeaders$1(input.headers, packetlist);
30237 const signature = new Signature(packetlist);
30238 return new CleartextMessage(input.text, signature);
30239}
30240
30241/**
30242 * Compare hash algorithm specified in the armor header with signatures
30243 * @param {Array<String>} headers - Armor headers
30244 * @param {PacketList} packetlist - The packetlist with signature packets
30245 * @private
30246 */
30247function verifyHeaders$1(headers, packetlist) {
30248 const checkHashAlgos = function(hashAlgos) {
30249 const check = packet => algo => packet.hashAlgorithm === algo;
30250
30251 for (let i = 0; i < packetlist.length; i++) {
30252 if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
30253 return false;
30254 }
30255 }
30256 return true;
30257 };
30258
30259 let oneHeader = null;
30260 let hashAlgos = [];
30261 headers.forEach(function(header) {
30262 oneHeader = header.match(/Hash: (.+)/); // get header value
30263 if (oneHeader) {
30264 oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
30265 oneHeader = oneHeader.split(',');
30266 oneHeader = oneHeader.map(function(hash) {
30267 hash = hash.toLowerCase();
30268 try {
30269 return enums.write(enums.hash, hash);
30270 } catch (e) {
30271 throw new Error('Unknown hash algorithm in armor header: ' + hash);
30272 }
30273 });
30274 hashAlgos = hashAlgos.concat(oneHeader);
30275 } else {
30276 throw new Error('Only "Hash" header allowed in cleartext signed message');
30277 }
30278 });
30279
30280 if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
30281 throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
30282 } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
30283 throw new Error('Hash algorithm mismatch in armor header and signature');
30284 }
30285}
30286
30287/**
30288 * Creates a new CleartextMessage object from text
30289 * @param {Object} options
30290 * @param {String} options.text
30291 * @static
30292 * @async
30293 */
30294async function createCleartextMessage({ text, ...rest }) {
30295 if (!text) {
30296 throw new Error('createCleartextMessage: must pass options object containing `text`');
30297 }
30298 if (!util.isString(text)) {
30299 throw new Error('createCleartextMessage: options.text must be a string');
30300 }
30301 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30302
30303 return new CleartextMessage(text);
30304}
30305
30306// OpenPGP.js - An OpenPGP implementation in javascript
30307
30308
30309//////////////////////
30310// //
30311// Key handling //
30312// //
30313//////////////////////
30314
30315
30316/**
30317 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.
30318 * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.
30319 * @param {Object} options
30320 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30321 * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA
30322 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.
30323 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
30324 * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:
30325 * curve25519 (default), p256, p384, p521, secp256k1,
30326 * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
30327 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
30328 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30329 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`
30330 * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt
30331 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30332 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30333 * @returns {Promise<Object>} The generated key object in the form:
30334 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30335 * @async
30336 * @static
30337 */
30338async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {
30339 config = { ...defaultConfig, ...config }; checkConfig(config);
30340 userIDs = toArray$1(userIDs);
30341 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30342
30343 if (userIDs.length === 0) {
30344 throw new Error('UserIDs are required for key generation');
30345 }
30346 if (type === 'rsa' && rsaBits < config.minRSABits) {
30347 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);
30348 }
30349
30350 const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };
30351
30352 try {
30353 const { key, revocationCertificate } = await generate$2(options, config);
30354 key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));
30355
30356 return {
30357 privateKey: formatObject(key, format, config),
30358 publicKey: formatObject(key.toPublic(), format, config),
30359 revocationCertificate
30360 };
30361 } catch (err) {
30362 throw util.wrapError('Error generating keypair', err);
30363 }
30364}
30365
30366/**
30367 * Reformats signature packets for a key and rewraps key object.
30368 * @param {Object} options
30369 * @param {PrivateKey} options.privateKey - Private key to reformat
30370 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30371 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.
30372 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30373 * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended
30374 * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.
30375 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30376 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30377 * @returns {Promise<Object>} The generated key object in the form:
30378 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30379 * @async
30380 * @static
30381 */
30382async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {
30383 config = { ...defaultConfig, ...config }; checkConfig(config);
30384 userIDs = toArray$1(userIDs);
30385 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30386
30387 if (userIDs.length === 0) {
30388 throw new Error('UserIDs are required for key reformat');
30389 }
30390 const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };
30391
30392 try {
30393 const { key: reformattedKey, revocationCertificate } = await reformat(options, config);
30394
30395 return {
30396 privateKey: formatObject(reformattedKey, format, config),
30397 publicKey: formatObject(reformattedKey.toPublic(), format, config),
30398 revocationCertificate
30399 };
30400 } catch (err) {
30401 throw util.wrapError('Error reformatting keypair', err);
30402 }
30403}
30404
30405/**
30406 * Revokes a key. Requires either a private key or a revocation certificate.
30407 * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
30408 * @param {Object} options
30409 * @param {Key} options.key - Public or private key to revoke
30410 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
30411 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
30412 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
30413 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
30414 * @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
30415 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)
30416 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30417 * @returns {Promise<Object>} The revoked key in the form:
30418 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or
30419 * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise
30420 * @async
30421 * @static
30422 */
30423async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {
30424 config = { ...defaultConfig, ...config }; checkConfig(config);
30425 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30426
30427 try {
30428 const revokedKey = revocationCertificate ?
30429 await key.applyRevocationCertificate(revocationCertificate, date, config) :
30430 await key.revoke(reasonForRevocation, date, config);
30431
30432 return revokedKey.isPrivate() ? {
30433 privateKey: formatObject(revokedKey, format, config),
30434 publicKey: formatObject(revokedKey.toPublic(), format, config)
30435 } : {
30436 privateKey: null,
30437 publicKey: formatObject(revokedKey, format, config)
30438 };
30439 } catch (err) {
30440 throw util.wrapError('Error revoking key', err);
30441 }
30442}
30443
30444/**
30445 * Unlock a private key with the given passphrase.
30446 * This method does not change the original key.
30447 * @param {Object} options
30448 * @param {PrivateKey} options.privateKey - The private key to decrypt
30449 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
30450 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30451 * @returns {Promise<PrivateKey>} The unlocked key object.
30452 * @async
30453 */
30454async function decryptKey({ privateKey, passphrase, config, ...rest }) {
30455 config = { ...defaultConfig, ...config }; checkConfig(config);
30456 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30457
30458 if (!privateKey.isPrivate()) {
30459 throw new Error('Cannot decrypt a public key');
30460 }
30461 const clonedPrivateKey = privateKey.clone(true);
30462 const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];
30463
30464 try {
30465 await Promise.all(clonedPrivateKey.getKeys().map(key => (
30466 // try to decrypt each key with any of the given passphrases
30467 util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))
30468 )));
30469
30470 await clonedPrivateKey.validate(config);
30471 return clonedPrivateKey;
30472 } catch (err) {
30473 clonedPrivateKey.clearPrivateParams();
30474 throw util.wrapError('Error decrypting private key', err);
30475 }
30476}
30477
30478/**
30479 * Lock a private key with the given passphrase.
30480 * This method does not change the original key.
30481 * @param {Object} options
30482 * @param {PrivateKey} options.privateKey - The private key to encrypt
30483 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
30484 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30485 * @returns {Promise<PrivateKey>} The locked key object.
30486 * @async
30487 */
30488async function encryptKey({ privateKey, passphrase, config, ...rest }) {
30489 config = { ...defaultConfig, ...config }; checkConfig(config);
30490 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30491
30492 if (!privateKey.isPrivate()) {
30493 throw new Error('Cannot encrypt a public key');
30494 }
30495 const clonedPrivateKey = privateKey.clone(true);
30496
30497 const keys = clonedPrivateKey.getKeys();
30498 const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);
30499 if (passphrases.length !== keys.length) {
30500 throw new Error('Invalid number of passphrases given for key encryption');
30501 }
30502
30503 try {
30504 await Promise.all(keys.map(async (key, i) => {
30505 const { keyPacket } = key;
30506 await keyPacket.encrypt(passphrases[i], config);
30507 keyPacket.clearPrivateParams();
30508 }));
30509 return clonedPrivateKey;
30510 } catch (err) {
30511 clonedPrivateKey.clearPrivateParams();
30512 throw util.wrapError('Error encrypting private key', err);
30513 }
30514}
30515
30516
30517///////////////////////////////////////////
30518// //
30519// Message encryption and decryption //
30520// //
30521///////////////////////////////////////////
30522
30523
30524/**
30525 * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys` or `passwords`
30526 * must be specified. If signing keys are specified, those will be used to sign the message.
30527 * @param {Object} options
30528 * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}
30529 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message
30530 * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed
30531 * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message
30532 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
30533 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30534 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
30535 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30536 * @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]`
30537 * @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]`
30538 * @param {Date} [options.date=current date] - Override the creation date of the message signature
30539 * @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' }]`
30540 * @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' }]`
30541 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30542 * @returns {Promise<MaybeStream<String>|MaybeStream<Uint8Array>>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30543 * @async
30544 * @static
30545 */
30546async function encrypt$4({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], config, ...rest }) {
30547 config = { ...defaultConfig, ...config }; checkConfig(config);
30548 checkMessage(message); checkOutputMessageFormat(format);
30549 encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords);
30550 signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30551 if (rest.detached) {
30552 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.");
30553 }
30554 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');
30555 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');
30556 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');
30557 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30558
30559 if (!signingKeys) {
30560 signingKeys = [];
30561 }
30562 const streaming = message.fromStream;
30563 try {
30564 if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified
30565 message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, config);
30566 }
30567 message = message.compress(
30568 await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),
30569 config
30570 );
30571 message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30572 if (format === 'object') return message;
30573 // serialize data
30574 const armor = format === 'armored';
30575 const data = armor ? message.armor(config) : message.write();
30576 return convertStream(data, streaming, armor ? 'utf8' : 'binary');
30577 } catch (err) {
30578 throw util.wrapError('Error encrypting message', err);
30579 }
30580}
30581
30582/**
30583 * Decrypts a message with the user's private key, a session key or a password.
30584 * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).
30585 * @param {Object} options
30586 * @param {Message} options.message - The message object with the encrypted data
30587 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key
30588 * @param {String|String[]} [options.passwords] - Passwords to decrypt the message
30589 * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
30590 * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures
30591 * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys
30592 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30593 * @param {Signature} [options.signature] - Detached signature for verification
30594 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30595 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30596 * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
30597 *
30598 * {
30599 * data: MaybeStream<String>, (if format was 'utf8', the default)
30600 * data: MaybeStream<Uint8Array>, (if format was 'binary')
30601 * filename: String,
30602 * signatures: [
30603 * {
30604 * keyID: module:type/keyid~KeyID,
30605 * verified: Promise<true>,
30606 * signature: Promise<Signature>
30607 * }, ...
30608 * ]
30609 * }
30610 *
30611 * where `signatures` contains a separate entry for each signature packet found in the input message.
30612 * @async
30613 * @static
30614 */
30615async function decrypt$4({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30616 config = { ...defaultConfig, ...config }; checkConfig(config);
30617 checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys);
30618 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');
30619 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');
30620 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30621
30622 try {
30623 const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);
30624 if (!verificationKeys) {
30625 verificationKeys = [];
30626 }
30627
30628 const result = {};
30629 result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);
30630 result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
30631 result.filename = decrypted.getFilename();
30632 linkStreams(result, message);
30633 if (expectSigned) {
30634 if (verificationKeys.length === 0) {
30635 throw new Error('Verification keys are required to verify message signatures');
30636 }
30637 if (result.signatures.length === 0) {
30638 throw new Error('Message is not signed');
30639 }
30640 result.data = concat([
30641 result.data,
30642 fromAsync(async () => {
30643 await util.anyPromise(result.signatures.map(sig => sig.verified));
30644 })
30645 ]);
30646 }
30647 result.data = await convertStream(result.data, message.fromStream, format);
30648 return result;
30649 } catch (err) {
30650 throw util.wrapError('Error decrypting message', err);
30651 }
30652}
30653
30654
30655//////////////////////////////////////////
30656// //
30657// Message signing and verification //
30658// //
30659//////////////////////////////////////////
30660
30661
30662/**
30663 * Signs a message.
30664 * @param {Object} options
30665 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
30666 * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext
30667 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30668 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
30669 * @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]
30670 * @param {Date} [options.date=current date] - Override the creation date of the signature
30671 * @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' }]`
30672 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30673 * @returns {Promise<MaybeStream<String|Uint8Array>>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30674 * @async
30675 * @static
30676 */
30677async function sign$5({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], config, ...rest }) {
30678 config = { ...defaultConfig, ...config }; checkConfig(config);
30679 checkCleartextOrMessage(message); checkOutputMessageFormat(format);
30680 signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs);
30681
30682 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');
30683 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');
30684 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30685
30686 if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');
30687 if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');
30688
30689 if (!signingKeys || signingKeys.length === 0) {
30690 throw new Error('No signing keys provided');
30691 }
30692
30693 try {
30694 let signature;
30695 if (detached) {
30696 signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30697 } else {
30698 signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30699 }
30700 if (format === 'object') return signature;
30701
30702 const armor = format === 'armored';
30703 signature = armor ? signature.armor(config) : signature.write();
30704 if (detached) {
30705 signature = transformPair(message.packets.write(), async (readable, writable) => {
30706 await Promise.all([
30707 pipe(signature, writable),
30708 readToEnd(readable).catch(() => {})
30709 ]);
30710 });
30711 }
30712 return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');
30713 } catch (err) {
30714 throw util.wrapError('Error signing message', err);
30715 }
30716}
30717
30718/**
30719 * Verifies signatures of cleartext signed message
30720 * @param {Object} options
30721 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
30722 * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures
30723 * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys
30724 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30725 * @param {Signature} [options.signature] - Detached signature for verification
30726 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30727 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30728 * @returns {Promise<Object>} Object containing verified message in the form:
30729 *
30730 * {
30731 * data: MaybeStream<String>, (if `message` was a CleartextMessage)
30732 * data: MaybeStream<Uint8Array>, (if `message` was a Message)
30733 * signatures: [
30734 * {
30735 * keyID: module:type/keyid~KeyID,
30736 * verified: Promise<true>,
30737 * signature: Promise<Signature>
30738 * }, ...
30739 * ]
30740 * }
30741 *
30742 * where `signatures` contains a separate entry for each signature packet found in the input message.
30743 * @async
30744 * @static
30745 */
30746async function verify$5({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30747 config = { ...defaultConfig, ...config }; checkConfig(config);
30748 checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys);
30749 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');
30750 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30751
30752 if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary");
30753 if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature");
30754
30755 try {
30756 const result = {};
30757 if (signature) {
30758 result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);
30759 } else {
30760 result.signatures = await message.verify(verificationKeys, date, config);
30761 }
30762 result.data = format === 'binary' ? message.getLiteralData() : message.getText();
30763 if (message.fromStream) linkStreams(result, message);
30764 if (expectSigned) {
30765 if (result.signatures.length === 0) {
30766 throw new Error('Message is not signed');
30767 }
30768 result.data = concat([
30769 result.data,
30770 fromAsync(async () => {
30771 await util.anyPromise(result.signatures.map(sig => sig.verified));
30772 })
30773 ]);
30774 }
30775 result.data = await convertStream(result.data, message.fromStream, format);
30776 return result;
30777 } catch (err) {
30778 throw util.wrapError('Error verifying signed message', err);
30779 }
30780}
30781
30782
30783///////////////////////////////////////////////
30784// //
30785// Session key encryption and decryption //
30786// //
30787///////////////////////////////////////////////
30788
30789/**
30790 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account.
30791 * @param {Object} options
30792 * @param {PublicKey|PublicKey[]} options.encryptionKeys - Array of public keys or single key used to select algorithm preferences for
30793 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
30794 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for
30795 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30796 * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.
30797 * @async
30798 * @static
30799 */
30800async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30801 config = { ...defaultConfig, ...config }; checkConfig(config);
30802 encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs);
30803 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');
30804 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30805
30806 try {
30807 const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);
30808 return sessionKeys;
30809 } catch (err) {
30810 throw util.wrapError('Error generating session key', err);
30811 }
30812}
30813
30814/**
30815 * Encrypt a symmetric session key with public keys, passwords, or both at once.
30816 * At least one of `encryptionKeys` or `passwords` must be specified.
30817 * @param {Object} options
30818 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
30819 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
30820 * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
30821 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key
30822 * @param {String|String[]} [options.passwords] - Passwords for the message
30823 * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value
30824 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30825 * @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]
30826 * @param {Date} [options.date=current date] - Override the date
30827 * @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' }]`
30828 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30829 * @returns {Promise<String|Uint8Array>} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
30830 * @async
30831 * @static
30832 */
30833async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30834 config = { ...defaultConfig, ...config }; checkConfig(config);
30835 checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);
30836 encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30837 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');
30838 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30839
30840 try {
30841 const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30842 return formatObject(message, format, config);
30843 } catch (err) {
30844 throw util.wrapError('Error encrypting session key', err);
30845 }
30846}
30847
30848/**
30849 * Decrypt symmetric session keys using private keys or passwords (not both).
30850 * One of `decryptionKeys` or `passwords` must be specified.
30851 * @param {Object} options
30852 * @param {Message} options.message - A message object containing the encrypted session key packets
30853 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data
30854 * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key
30855 * @param {Date} [options.date] - Date to use for key verification instead of the current time
30856 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30857 * @returns {Promise<Object[]>} Array of decrypted session key, algorithm pairs in the form:
30858 * { data:Uint8Array, algorithm:String }
30859 * @throws if no session key could be found or decrypted
30860 * @async
30861 * @static
30862 */
30863async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {
30864 config = { ...defaultConfig, ...config }; checkConfig(config);
30865 checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords);
30866 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');
30867 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30868
30869 try {
30870 const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);
30871 return sessionKeys;
30872 } catch (err) {
30873 throw util.wrapError('Error decrypting session keys', err);
30874 }
30875}
30876
30877
30878//////////////////////////
30879// //
30880// Helper functions //
30881// //
30882//////////////////////////
30883
30884
30885/**
30886 * Input validation
30887 * @private
30888 */
30889function checkString(data, name) {
30890 if (!util.isString(data)) {
30891 throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
30892 }
30893}
30894function checkBinary(data, name) {
30895 if (!util.isUint8Array(data)) {
30896 throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
30897 }
30898}
30899function checkMessage(message) {
30900 if (!(message instanceof Message)) {
30901 throw new Error('Parameter [message] needs to be of type Message');
30902 }
30903}
30904function checkCleartextOrMessage(message) {
30905 if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
30906 throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
30907 }
30908}
30909function checkOutputMessageFormat(format) {
30910 if (format !== 'armored' && format !== 'binary' && format !== 'object') {
30911 throw new Error(`Unsupported format ${format}`);
30912 }
30913}
30914const defaultConfigPropsCount = Object.keys(defaultConfig).length;
30915function checkConfig(config) {
30916 const inputConfigProps = Object.keys(config);
30917 if (inputConfigProps.length !== defaultConfigPropsCount) {
30918 for (const inputProp of inputConfigProps) {
30919 if (defaultConfig[inputProp] === undefined) {
30920 throw new Error(`Unknown config property: ${inputProp}`);
30921 }
30922 }
30923 }
30924}
30925
30926/**
30927 * Normalize parameter to an array if it is not undefined.
30928 * @param {Object} param - the parameter to be normalized
30929 * @returns {Array<Object>|undefined} The resulting array or undefined.
30930 * @private
30931 */
30932function toArray$1(param) {
30933 if (param && !util.isArray(param)) {
30934 param = [param];
30935 }
30936 return param;
30937}
30938
30939/**
30940 * Convert data to or from Stream
30941 * @param {Object} data - the data to convert
30942 * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type
30943 * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams
30944 * @returns {Promise<Object>} The data in the respective format.
30945 * @async
30946 * @private
30947 */
30948async function convertStream(data, streaming, encoding = 'utf8') {
30949 const streamType = util.isStream(data);
30950 if (streamType === 'array') {
30951 return readToEnd(data);
30952 }
30953 if (streaming === 'node') {
30954 data = webToNode(data);
30955 if (encoding !== 'binary') data.setEncoding(encoding);
30956 return data;
30957 }
30958 if (streaming === 'web' && streamType === 'ponyfill') {
30959 return toNativeReadable(data);
30960 }
30961 return data;
30962}
30963
30964/**
30965 * Link result.data to the message stream for cancellation.
30966 * Also, forward errors in the message to result.data.
30967 * @param {Object} result - the data to convert
30968 * @param {Message} message - message object
30969 * @returns {Object}
30970 * @private
30971 */
30972function linkStreams(result, message) {
30973 result.data = transformPair(message.packets.stream, async (readable, writable) => {
30974 await pipe(result.data, writable, {
30975 preventClose: true
30976 });
30977 const writer = getWriter(writable);
30978 try {
30979 // Forward errors in the message stream to result.data.
30980 await readToEnd(readable, _ => _);
30981 await writer.close();
30982 } catch (e) {
30983 await writer.abort(e);
30984 }
30985 });
30986}
30987
30988/**
30989 * Convert the object to the given format
30990 * @param {Key|Message} object
30991 * @param {'armored'|'binary'|'object'} format
30992 * @param {Object} config - Full configuration
30993 * @returns {String|Uint8Array|Object}
30994 */
30995function formatObject(object, format, config) {
30996 switch (format) {
30997 case 'object':
30998 return object;
30999 case 'armored':
31000 return object.armor(config);
31001 case 'binary':
31002 return object.write();
31003 default:
31004 throw new Error(`Unsupported format ${format}`);
31005 }
31006}
31007
31008/**
31009 * web-streams-polyfill v3.0.3
31010 */
31011/// <reference lib="es2015.symbol" />
31012const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
31013 Symbol :
31014 description => `Symbol(${description})`;
31015
31016/// <reference lib="dom" />
31017function noop() {
31018 return undefined;
31019}
31020function getGlobals() {
31021 if (typeof self !== 'undefined') {
31022 return self;
31023 }
31024 else if (typeof window !== 'undefined') {
31025 return window;
31026 }
31027 else if (typeof global !== 'undefined') {
31028 return global;
31029 }
31030 return undefined;
31031}
31032const globals = getGlobals();
31033
31034function typeIsObject(x) {
31035 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31036}
31037const rethrowAssertionErrorRejection = noop;
31038
31039const originalPromise = Promise;
31040const originalPromiseThen = Promise.prototype.then;
31041const originalPromiseResolve = Promise.resolve.bind(originalPromise);
31042const originalPromiseReject = Promise.reject.bind(originalPromise);
31043function newPromise(executor) {
31044 return new originalPromise(executor);
31045}
31046function promiseResolvedWith(value) {
31047 return originalPromiseResolve(value);
31048}
31049function promiseRejectedWith(reason) {
31050 return originalPromiseReject(reason);
31051}
31052function PerformPromiseThen(promise, onFulfilled, onRejected) {
31053 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
31054 // approximation.
31055 return originalPromiseThen.call(promise, onFulfilled, onRejected);
31056}
31057function uponPromise(promise, onFulfilled, onRejected) {
31058 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
31059}
31060function uponFulfillment(promise, onFulfilled) {
31061 uponPromise(promise, onFulfilled);
31062}
31063function uponRejection(promise, onRejected) {
31064 uponPromise(promise, undefined, onRejected);
31065}
31066function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
31067 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
31068}
31069function setPromiseIsHandledToTrue(promise) {
31070 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
31071}
31072const queueMicrotask = (() => {
31073 const globalQueueMicrotask = globals && globals.queueMicrotask;
31074 if (typeof globalQueueMicrotask === 'function') {
31075 return globalQueueMicrotask;
31076 }
31077 const resolvedPromise = promiseResolvedWith(undefined);
31078 return (fn) => PerformPromiseThen(resolvedPromise, fn);
31079})();
31080function reflectCall(F, V, args) {
31081 if (typeof F !== 'function') {
31082 throw new TypeError('Argument is not a function');
31083 }
31084 return Function.prototype.apply.call(F, V, args);
31085}
31086function promiseCall(F, V, args) {
31087 try {
31088 return promiseResolvedWith(reflectCall(F, V, args));
31089 }
31090 catch (value) {
31091 return promiseRejectedWith(value);
31092 }
31093}
31094
31095// Original from Chromium
31096// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
31097const QUEUE_MAX_ARRAY_SIZE = 16384;
31098/**
31099 * Simple queue structure.
31100 *
31101 * Avoids scalability issues with using a packed array directly by using
31102 * multiple arrays in a linked list and keeping the array size bounded.
31103 */
31104class SimpleQueue {
31105 constructor() {
31106 this._cursor = 0;
31107 this._size = 0;
31108 // _front and _back are always defined.
31109 this._front = {
31110 _elements: [],
31111 _next: undefined
31112 };
31113 this._back = this._front;
31114 // The cursor is used to avoid calling Array.shift().
31115 // It contains the index of the front element of the array inside the
31116 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
31117 this._cursor = 0;
31118 // When there is only one node, size === elements.length - cursor.
31119 this._size = 0;
31120 }
31121 get length() {
31122 return this._size;
31123 }
31124 // For exception safety, this method is structured in order:
31125 // 1. Read state
31126 // 2. Calculate required state mutations
31127 // 3. Perform state mutations
31128 push(element) {
31129 const oldBack = this._back;
31130 let newBack = oldBack;
31131 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
31132 newBack = {
31133 _elements: [],
31134 _next: undefined
31135 };
31136 }
31137 // push() is the mutation most likely to throw an exception, so it
31138 // goes first.
31139 oldBack._elements.push(element);
31140 if (newBack !== oldBack) {
31141 this._back = newBack;
31142 oldBack._next = newBack;
31143 }
31144 ++this._size;
31145 }
31146 // Like push(), shift() follows the read -> calculate -> mutate pattern for
31147 // exception safety.
31148 shift() { // must not be called on an empty queue
31149 const oldFront = this._front;
31150 let newFront = oldFront;
31151 const oldCursor = this._cursor;
31152 let newCursor = oldCursor + 1;
31153 const elements = oldFront._elements;
31154 const element = elements[oldCursor];
31155 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
31156 newFront = oldFront._next;
31157 newCursor = 0;
31158 }
31159 // No mutations before this point.
31160 --this._size;
31161 this._cursor = newCursor;
31162 if (oldFront !== newFront) {
31163 this._front = newFront;
31164 }
31165 // Permit shifted element to be garbage collected.
31166 elements[oldCursor] = undefined;
31167 return element;
31168 }
31169 // The tricky thing about forEach() is that it can be called
31170 // re-entrantly. The queue may be mutated inside the callback. It is easy to
31171 // see that push() within the callback has no negative effects since the end
31172 // of the queue is checked for on every iteration. If shift() is called
31173 // repeatedly within the callback then the next iteration may return an
31174 // element that has been removed. In this case the callback will be called
31175 // with undefined values until we either "catch up" with elements that still
31176 // exist or reach the back of the queue.
31177 forEach(callback) {
31178 let i = this._cursor;
31179 let node = this._front;
31180 let elements = node._elements;
31181 while (i !== elements.length || node._next !== undefined) {
31182 if (i === elements.length) {
31183 node = node._next;
31184 elements = node._elements;
31185 i = 0;
31186 if (elements.length === 0) {
31187 break;
31188 }
31189 }
31190 callback(elements[i]);
31191 ++i;
31192 }
31193 }
31194 // Return the element that would be returned if shift() was called now,
31195 // without modifying the queue.
31196 peek() { // must not be called on an empty queue
31197 const front = this._front;
31198 const cursor = this._cursor;
31199 return front._elements[cursor];
31200 }
31201}
31202
31203function ReadableStreamReaderGenericInitialize(reader, stream) {
31204 reader._ownerReadableStream = stream;
31205 stream._reader = reader;
31206 if (stream._state === 'readable') {
31207 defaultReaderClosedPromiseInitialize(reader);
31208 }
31209 else if (stream._state === 'closed') {
31210 defaultReaderClosedPromiseInitializeAsResolved(reader);
31211 }
31212 else {
31213 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
31214 }
31215}
31216// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
31217// check.
31218function ReadableStreamReaderGenericCancel(reader, reason) {
31219 const stream = reader._ownerReadableStream;
31220 return ReadableStreamCancel(stream, reason);
31221}
31222function ReadableStreamReaderGenericRelease(reader) {
31223 if (reader._ownerReadableStream._state === 'readable') {
31224 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31225 }
31226 else {
31227 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31228 }
31229 reader._ownerReadableStream._reader = undefined;
31230 reader._ownerReadableStream = undefined;
31231}
31232// Helper functions for the readers.
31233function readerLockException(name) {
31234 return new TypeError('Cannot ' + name + ' a stream using a released reader');
31235}
31236// Helper functions for the ReadableStreamDefaultReader.
31237function defaultReaderClosedPromiseInitialize(reader) {
31238 reader._closedPromise = newPromise((resolve, reject) => {
31239 reader._closedPromise_resolve = resolve;
31240 reader._closedPromise_reject = reject;
31241 });
31242}
31243function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
31244 defaultReaderClosedPromiseInitialize(reader);
31245 defaultReaderClosedPromiseReject(reader, reason);
31246}
31247function defaultReaderClosedPromiseInitializeAsResolved(reader) {
31248 defaultReaderClosedPromiseInitialize(reader);
31249 defaultReaderClosedPromiseResolve(reader);
31250}
31251function defaultReaderClosedPromiseReject(reader, reason) {
31252 if (reader._closedPromise_reject === undefined) {
31253 return;
31254 }
31255 setPromiseIsHandledToTrue(reader._closedPromise);
31256 reader._closedPromise_reject(reason);
31257 reader._closedPromise_resolve = undefined;
31258 reader._closedPromise_reject = undefined;
31259}
31260function defaultReaderClosedPromiseResetToRejected(reader, reason) {
31261 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
31262}
31263function defaultReaderClosedPromiseResolve(reader) {
31264 if (reader._closedPromise_resolve === undefined) {
31265 return;
31266 }
31267 reader._closedPromise_resolve(undefined);
31268 reader._closedPromise_resolve = undefined;
31269 reader._closedPromise_reject = undefined;
31270}
31271
31272const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
31273const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
31274const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
31275const PullSteps = SymbolPolyfill('[[PullSteps]]');
31276
31277/// <reference lib="es2015.core" />
31278// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
31279const NumberIsFinite = Number.isFinite || function (x) {
31280 return typeof x === 'number' && isFinite(x);
31281};
31282
31283/// <reference lib="es2015.core" />
31284// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
31285const MathTrunc = Math.trunc || function (v) {
31286 return v < 0 ? Math.ceil(v) : Math.floor(v);
31287};
31288
31289// https://heycam.github.io/webidl/#idl-dictionaries
31290function isDictionary(x) {
31291 return typeof x === 'object' || typeof x === 'function';
31292}
31293function assertDictionary(obj, context) {
31294 if (obj !== undefined && !isDictionary(obj)) {
31295 throw new TypeError(`${context} is not an object.`);
31296 }
31297}
31298// https://heycam.github.io/webidl/#idl-callback-functions
31299function assertFunction(x, context) {
31300 if (typeof x !== 'function') {
31301 throw new TypeError(`${context} is not a function.`);
31302 }
31303}
31304// https://heycam.github.io/webidl/#idl-object
31305function isObject(x) {
31306 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31307}
31308function assertObject(x, context) {
31309 if (!isObject(x)) {
31310 throw new TypeError(`${context} is not an object.`);
31311 }
31312}
31313function assertRequiredArgument(x, position, context) {
31314 if (x === undefined) {
31315 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
31316 }
31317}
31318function assertRequiredField(x, field, context) {
31319 if (x === undefined) {
31320 throw new TypeError(`${field} is required in '${context}'.`);
31321 }
31322}
31323// https://heycam.github.io/webidl/#idl-unrestricted-double
31324function convertUnrestrictedDouble(value) {
31325 return Number(value);
31326}
31327function censorNegativeZero(x) {
31328 return x === 0 ? 0 : x;
31329}
31330function integerPart(x) {
31331 return censorNegativeZero(MathTrunc(x));
31332}
31333// https://heycam.github.io/webidl/#idl-unsigned-long-long
31334function convertUnsignedLongLongWithEnforceRange(value, context) {
31335 const lowerBound = 0;
31336 const upperBound = Number.MAX_SAFE_INTEGER;
31337 let x = Number(value);
31338 x = censorNegativeZero(x);
31339 if (!NumberIsFinite(x)) {
31340 throw new TypeError(`${context} is not a finite number`);
31341 }
31342 x = integerPart(x);
31343 if (x < lowerBound || x > upperBound) {
31344 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
31345 }
31346 if (!NumberIsFinite(x) || x === 0) {
31347 return 0;
31348 }
31349 // TODO Use BigInt if supported?
31350 // let xBigInt = BigInt(integerPart(x));
31351 // xBigInt = BigInt.asUintN(64, xBigInt);
31352 // return Number(xBigInt);
31353 return x;
31354}
31355
31356function assertReadableStream(x, context) {
31357 if (!IsReadableStream(x)) {
31358 throw new TypeError(`${context} is not a ReadableStream.`);
31359 }
31360}
31361
31362// Abstract operations for the ReadableStream.
31363function AcquireReadableStreamDefaultReader(stream) {
31364 return new ReadableStreamDefaultReader(stream);
31365}
31366// ReadableStream API exposed for controllers.
31367function ReadableStreamAddReadRequest(stream, readRequest) {
31368 stream._reader._readRequests.push(readRequest);
31369}
31370function ReadableStreamFulfillReadRequest(stream, chunk, done) {
31371 const reader = stream._reader;
31372 const readRequest = reader._readRequests.shift();
31373 if (done) {
31374 readRequest._closeSteps();
31375 }
31376 else {
31377 readRequest._chunkSteps(chunk);
31378 }
31379}
31380function ReadableStreamGetNumReadRequests(stream) {
31381 return stream._reader._readRequests.length;
31382}
31383function ReadableStreamHasDefaultReader(stream) {
31384 const reader = stream._reader;
31385 if (reader === undefined) {
31386 return false;
31387 }
31388 if (!IsReadableStreamDefaultReader(reader)) {
31389 return false;
31390 }
31391 return true;
31392}
31393/**
31394 * A default reader vended by a {@link ReadableStream}.
31395 *
31396 * @public
31397 */
31398class ReadableStreamDefaultReader {
31399 constructor(stream) {
31400 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
31401 assertReadableStream(stream, 'First parameter');
31402 if (IsReadableStreamLocked(stream)) {
31403 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
31404 }
31405 ReadableStreamReaderGenericInitialize(this, stream);
31406 this._readRequests = new SimpleQueue();
31407 }
31408 /**
31409 * Returns a promise that will be fulfilled when the stream becomes closed,
31410 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
31411 */
31412 get closed() {
31413 if (!IsReadableStreamDefaultReader(this)) {
31414 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
31415 }
31416 return this._closedPromise;
31417 }
31418 /**
31419 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
31420 */
31421 cancel(reason = undefined) {
31422 if (!IsReadableStreamDefaultReader(this)) {
31423 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
31424 }
31425 if (this._ownerReadableStream === undefined) {
31426 return promiseRejectedWith(readerLockException('cancel'));
31427 }
31428 return ReadableStreamReaderGenericCancel(this, reason);
31429 }
31430 /**
31431 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
31432 *
31433 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
31434 */
31435 read() {
31436 if (!IsReadableStreamDefaultReader(this)) {
31437 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
31438 }
31439 if (this._ownerReadableStream === undefined) {
31440 return promiseRejectedWith(readerLockException('read from'));
31441 }
31442 let resolvePromise;
31443 let rejectPromise;
31444 const promise = newPromise((resolve, reject) => {
31445 resolvePromise = resolve;
31446 rejectPromise = reject;
31447 });
31448 const readRequest = {
31449 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
31450 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
31451 _errorSteps: e => rejectPromise(e)
31452 };
31453 ReadableStreamDefaultReaderRead(this, readRequest);
31454 return promise;
31455 }
31456 /**
31457 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
31458 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
31459 * from now on; otherwise, the reader will appear closed.
31460 *
31461 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
31462 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
31463 * do so will throw a `TypeError` and leave the reader locked to the stream.
31464 */
31465 releaseLock() {
31466 if (!IsReadableStreamDefaultReader(this)) {
31467 throw defaultReaderBrandCheckException('releaseLock');
31468 }
31469 if (this._ownerReadableStream === undefined) {
31470 return;
31471 }
31472 if (this._readRequests.length > 0) {
31473 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
31474 }
31475 ReadableStreamReaderGenericRelease(this);
31476 }
31477}
31478Object.defineProperties(ReadableStreamDefaultReader.prototype, {
31479 cancel: { enumerable: true },
31480 read: { enumerable: true },
31481 releaseLock: { enumerable: true },
31482 closed: { enumerable: true }
31483});
31484if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31485 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
31486 value: 'ReadableStreamDefaultReader',
31487 configurable: true
31488 });
31489}
31490// Abstract operations for the readers.
31491function IsReadableStreamDefaultReader(x) {
31492 if (!typeIsObject(x)) {
31493 return false;
31494 }
31495 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
31496 return false;
31497 }
31498 return true;
31499}
31500function ReadableStreamDefaultReaderRead(reader, readRequest) {
31501 const stream = reader._ownerReadableStream;
31502 stream._disturbed = true;
31503 if (stream._state === 'closed') {
31504 readRequest._closeSteps();
31505 }
31506 else if (stream._state === 'errored') {
31507 readRequest._errorSteps(stream._storedError);
31508 }
31509 else {
31510 stream._readableStreamController[PullSteps](readRequest);
31511 }
31512}
31513// Helper functions for the ReadableStreamDefaultReader.
31514function defaultReaderBrandCheckException(name) {
31515 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
31516}
31517
31518/// <reference lib="es2018.asynciterable" />
31519let AsyncIteratorPrototype;
31520if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
31521 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
31522 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
31523 AsyncIteratorPrototype = {
31524 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
31525 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
31526 [SymbolPolyfill.asyncIterator]() {
31527 return this;
31528 }
31529 };
31530 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
31531}
31532
31533/// <reference lib="es2018.asynciterable" />
31534class ReadableStreamAsyncIteratorImpl {
31535 constructor(reader, preventCancel) {
31536 this._ongoingPromise = undefined;
31537 this._isFinished = false;
31538 this._reader = reader;
31539 this._preventCancel = preventCancel;
31540 }
31541 next() {
31542 const nextSteps = () => this._nextSteps();
31543 this._ongoingPromise = this._ongoingPromise ?
31544 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
31545 nextSteps();
31546 return this._ongoingPromise;
31547 }
31548 return(value) {
31549 const returnSteps = () => this._returnSteps(value);
31550 return this._ongoingPromise ?
31551 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
31552 returnSteps();
31553 }
31554 _nextSteps() {
31555 if (this._isFinished) {
31556 return Promise.resolve({ value: undefined, done: true });
31557 }
31558 const reader = this._reader;
31559 if (reader._ownerReadableStream === undefined) {
31560 return promiseRejectedWith(readerLockException('iterate'));
31561 }
31562 let resolvePromise;
31563 let rejectPromise;
31564 const promise = newPromise((resolve, reject) => {
31565 resolvePromise = resolve;
31566 rejectPromise = reject;
31567 });
31568 const readRequest = {
31569 _chunkSteps: chunk => {
31570 this._ongoingPromise = undefined;
31571 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
31572 // FIXME Is this a bug in the specification, or in the test?
31573 queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
31574 },
31575 _closeSteps: () => {
31576 this._ongoingPromise = undefined;
31577 this._isFinished = true;
31578 ReadableStreamReaderGenericRelease(reader);
31579 resolvePromise({ value: undefined, done: true });
31580 },
31581 _errorSteps: reason => {
31582 this._ongoingPromise = undefined;
31583 this._isFinished = true;
31584 ReadableStreamReaderGenericRelease(reader);
31585 rejectPromise(reason);
31586 }
31587 };
31588 ReadableStreamDefaultReaderRead(reader, readRequest);
31589 return promise;
31590 }
31591 _returnSteps(value) {
31592 if (this._isFinished) {
31593 return Promise.resolve({ value, done: true });
31594 }
31595 this._isFinished = true;
31596 const reader = this._reader;
31597 if (reader._ownerReadableStream === undefined) {
31598 return promiseRejectedWith(readerLockException('finish iterating'));
31599 }
31600 if (!this._preventCancel) {
31601 const result = ReadableStreamReaderGenericCancel(reader, value);
31602 ReadableStreamReaderGenericRelease(reader);
31603 return transformPromiseWith(result, () => ({ value, done: true }));
31604 }
31605 ReadableStreamReaderGenericRelease(reader);
31606 return promiseResolvedWith({ value, done: true });
31607 }
31608}
31609const ReadableStreamAsyncIteratorPrototype = {
31610 next() {
31611 if (!IsReadableStreamAsyncIterator(this)) {
31612 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
31613 }
31614 return this._asyncIteratorImpl.next();
31615 },
31616 return(value) {
31617 if (!IsReadableStreamAsyncIterator(this)) {
31618 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
31619 }
31620 return this._asyncIteratorImpl.return(value);
31621 }
31622};
31623if (AsyncIteratorPrototype !== undefined) {
31624 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
31625}
31626// Abstract operations for the ReadableStream.
31627function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
31628 const reader = AcquireReadableStreamDefaultReader(stream);
31629 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
31630 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
31631 iterator._asyncIteratorImpl = impl;
31632 return iterator;
31633}
31634function IsReadableStreamAsyncIterator(x) {
31635 if (!typeIsObject(x)) {
31636 return false;
31637 }
31638 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
31639 return false;
31640 }
31641 return true;
31642}
31643// Helper functions for the ReadableStream.
31644function streamAsyncIteratorBrandCheckException(name) {
31645 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
31646}
31647
31648/// <reference lib="es2015.core" />
31649// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
31650const NumberIsNaN = Number.isNaN || function (x) {
31651 // eslint-disable-next-line no-self-compare
31652 return x !== x;
31653};
31654
31655function IsFiniteNonNegativeNumber(v) {
31656 if (!IsNonNegativeNumber(v)) {
31657 return false;
31658 }
31659 if (v === Infinity) {
31660 return false;
31661 }
31662 return true;
31663}
31664function IsNonNegativeNumber(v) {
31665 if (typeof v !== 'number') {
31666 return false;
31667 }
31668 if (NumberIsNaN(v)) {
31669 return false;
31670 }
31671 if (v < 0) {
31672 return false;
31673 }
31674 return true;
31675}
31676
31677function DequeueValue(container) {
31678 const pair = container._queue.shift();
31679 container._queueTotalSize -= pair.size;
31680 if (container._queueTotalSize < 0) {
31681 container._queueTotalSize = 0;
31682 }
31683 return pair.value;
31684}
31685function EnqueueValueWithSize(container, value, size) {
31686 size = Number(size);
31687 if (!IsFiniteNonNegativeNumber(size)) {
31688 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
31689 }
31690 container._queue.push({ value, size });
31691 container._queueTotalSize += size;
31692}
31693function PeekQueueValue(container) {
31694 const pair = container._queue.peek();
31695 return pair.value;
31696}
31697function ResetQueue(container) {
31698 container._queue = new SimpleQueue();
31699 container._queueTotalSize = 0;
31700}
31701
31702function CreateArrayFromList(elements) {
31703 // We use arrays to represent lists, so this is basically a no-op.
31704 // Do a slice though just in case we happen to depend on the unique-ness.
31705 return elements.slice();
31706}
31707function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
31708 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
31709}
31710// Not implemented correctly
31711function TransferArrayBuffer(O) {
31712 return O;
31713}
31714// Not implemented correctly
31715function IsDetachedBuffer(O) {
31716 return false;
31717}
31718
31719/**
31720 * A pull-into request in a {@link ReadableByteStreamController}.
31721 *
31722 * @public
31723 */
31724class ReadableStreamBYOBRequest {
31725 constructor() {
31726 throw new TypeError('Illegal constructor');
31727 }
31728 /**
31729 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
31730 */
31731 get view() {
31732 if (!IsReadableStreamBYOBRequest(this)) {
31733 throw byobRequestBrandCheckException('view');
31734 }
31735 return this._view;
31736 }
31737 respond(bytesWritten) {
31738 if (!IsReadableStreamBYOBRequest(this)) {
31739 throw byobRequestBrandCheckException('respond');
31740 }
31741 assertRequiredArgument(bytesWritten, 1, 'respond');
31742 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
31743 if (this._associatedReadableByteStreamController === undefined) {
31744 throw new TypeError('This BYOB request has been invalidated');
31745 }
31746 if (IsDetachedBuffer(this._view.buffer)) ;
31747 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
31748 }
31749 respondWithNewView(view) {
31750 if (!IsReadableStreamBYOBRequest(this)) {
31751 throw byobRequestBrandCheckException('respondWithNewView');
31752 }
31753 assertRequiredArgument(view, 1, 'respondWithNewView');
31754 if (!ArrayBuffer.isView(view)) {
31755 throw new TypeError('You can only respond with array buffer views');
31756 }
31757 if (view.byteLength === 0) {
31758 throw new TypeError('chunk must have non-zero byteLength');
31759 }
31760 if (view.buffer.byteLength === 0) {
31761 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31762 }
31763 if (this._associatedReadableByteStreamController === undefined) {
31764 throw new TypeError('This BYOB request has been invalidated');
31765 }
31766 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
31767 }
31768}
31769Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
31770 respond: { enumerable: true },
31771 respondWithNewView: { enumerable: true },
31772 view: { enumerable: true }
31773});
31774if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31775 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
31776 value: 'ReadableStreamBYOBRequest',
31777 configurable: true
31778 });
31779}
31780/**
31781 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
31782 *
31783 * @public
31784 */
31785class ReadableByteStreamController {
31786 constructor() {
31787 throw new TypeError('Illegal constructor');
31788 }
31789 /**
31790 * Returns the current BYOB pull request, or `null` if there isn't one.
31791 */
31792 get byobRequest() {
31793 if (!IsReadableByteStreamController(this)) {
31794 throw byteStreamControllerBrandCheckException('byobRequest');
31795 }
31796 if (this._byobRequest === null && this._pendingPullIntos.length > 0) {
31797 const firstDescriptor = this._pendingPullIntos.peek();
31798 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
31799 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
31800 SetUpReadableStreamBYOBRequest(byobRequest, this, view);
31801 this._byobRequest = byobRequest;
31802 }
31803 return this._byobRequest;
31804 }
31805 /**
31806 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
31807 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
31808 */
31809 get desiredSize() {
31810 if (!IsReadableByteStreamController(this)) {
31811 throw byteStreamControllerBrandCheckException('desiredSize');
31812 }
31813 return ReadableByteStreamControllerGetDesiredSize(this);
31814 }
31815 /**
31816 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
31817 * the stream, but once those are read, the stream will become closed.
31818 */
31819 close() {
31820 if (!IsReadableByteStreamController(this)) {
31821 throw byteStreamControllerBrandCheckException('close');
31822 }
31823 if (this._closeRequested) {
31824 throw new TypeError('The stream has already been closed; do not close it again!');
31825 }
31826 const state = this._controlledReadableByteStream._state;
31827 if (state !== 'readable') {
31828 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
31829 }
31830 ReadableByteStreamControllerClose(this);
31831 }
31832 enqueue(chunk) {
31833 if (!IsReadableByteStreamController(this)) {
31834 throw byteStreamControllerBrandCheckException('enqueue');
31835 }
31836 assertRequiredArgument(chunk, 1, 'enqueue');
31837 if (!ArrayBuffer.isView(chunk)) {
31838 throw new TypeError('chunk must be an array buffer view');
31839 }
31840 if (chunk.byteLength === 0) {
31841 throw new TypeError('chunk must have non-zero byteLength');
31842 }
31843 if (chunk.buffer.byteLength === 0) {
31844 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31845 }
31846 if (this._closeRequested) {
31847 throw new TypeError('stream is closed or draining');
31848 }
31849 const state = this._controlledReadableByteStream._state;
31850 if (state !== 'readable') {
31851 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
31852 }
31853 ReadableByteStreamControllerEnqueue(this, chunk);
31854 }
31855 /**
31856 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
31857 */
31858 error(e = undefined) {
31859 if (!IsReadableByteStreamController(this)) {
31860 throw byteStreamControllerBrandCheckException('error');
31861 }
31862 ReadableByteStreamControllerError(this, e);
31863 }
31864 /** @internal */
31865 [CancelSteps](reason) {
31866 if (this._pendingPullIntos.length > 0) {
31867 const firstDescriptor = this._pendingPullIntos.peek();
31868 firstDescriptor.bytesFilled = 0;
31869 }
31870 ResetQueue(this);
31871 const result = this._cancelAlgorithm(reason);
31872 ReadableByteStreamControllerClearAlgorithms(this);
31873 return result;
31874 }
31875 /** @internal */
31876 [PullSteps](readRequest) {
31877 const stream = this._controlledReadableByteStream;
31878 if (this._queueTotalSize > 0) {
31879 const entry = this._queue.shift();
31880 this._queueTotalSize -= entry.byteLength;
31881 ReadableByteStreamControllerHandleQueueDrain(this);
31882 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
31883 readRequest._chunkSteps(view);
31884 return;
31885 }
31886 const autoAllocateChunkSize = this._autoAllocateChunkSize;
31887 if (autoAllocateChunkSize !== undefined) {
31888 let buffer;
31889 try {
31890 buffer = new ArrayBuffer(autoAllocateChunkSize);
31891 }
31892 catch (bufferE) {
31893 readRequest._errorSteps(bufferE);
31894 return;
31895 }
31896 const pullIntoDescriptor = {
31897 buffer,
31898 byteOffset: 0,
31899 byteLength: autoAllocateChunkSize,
31900 bytesFilled: 0,
31901 elementSize: 1,
31902 viewConstructor: Uint8Array,
31903 readerType: 'default'
31904 };
31905 this._pendingPullIntos.push(pullIntoDescriptor);
31906 }
31907 ReadableStreamAddReadRequest(stream, readRequest);
31908 ReadableByteStreamControllerCallPullIfNeeded(this);
31909 }
31910}
31911Object.defineProperties(ReadableByteStreamController.prototype, {
31912 close: { enumerable: true },
31913 enqueue: { enumerable: true },
31914 error: { enumerable: true },
31915 byobRequest: { enumerable: true },
31916 desiredSize: { enumerable: true }
31917});
31918if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31919 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
31920 value: 'ReadableByteStreamController',
31921 configurable: true
31922 });
31923}
31924// Abstract operations for the ReadableByteStreamController.
31925function IsReadableByteStreamController(x) {
31926 if (!typeIsObject(x)) {
31927 return false;
31928 }
31929 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
31930 return false;
31931 }
31932 return true;
31933}
31934function IsReadableStreamBYOBRequest(x) {
31935 if (!typeIsObject(x)) {
31936 return false;
31937 }
31938 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
31939 return false;
31940 }
31941 return true;
31942}
31943function ReadableByteStreamControllerCallPullIfNeeded(controller) {
31944 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
31945 if (!shouldPull) {
31946 return;
31947 }
31948 if (controller._pulling) {
31949 controller._pullAgain = true;
31950 return;
31951 }
31952 controller._pulling = true;
31953 // TODO: Test controller argument
31954 const pullPromise = controller._pullAlgorithm();
31955 uponPromise(pullPromise, () => {
31956 controller._pulling = false;
31957 if (controller._pullAgain) {
31958 controller._pullAgain = false;
31959 ReadableByteStreamControllerCallPullIfNeeded(controller);
31960 }
31961 }, e => {
31962 ReadableByteStreamControllerError(controller, e);
31963 });
31964}
31965function ReadableByteStreamControllerClearPendingPullIntos(controller) {
31966 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
31967 controller._pendingPullIntos = new SimpleQueue();
31968}
31969function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
31970 let done = false;
31971 if (stream._state === 'closed') {
31972 done = true;
31973 }
31974 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
31975 if (pullIntoDescriptor.readerType === 'default') {
31976 ReadableStreamFulfillReadRequest(stream, filledView, done);
31977 }
31978 else {
31979 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
31980 }
31981}
31982function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
31983 const bytesFilled = pullIntoDescriptor.bytesFilled;
31984 const elementSize = pullIntoDescriptor.elementSize;
31985 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
31986}
31987function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
31988 controller._queue.push({ buffer, byteOffset, byteLength });
31989 controller._queueTotalSize += byteLength;
31990}
31991function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
31992 const elementSize = pullIntoDescriptor.elementSize;
31993 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
31994 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
31995 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
31996 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
31997 let totalBytesToCopyRemaining = maxBytesToCopy;
31998 let ready = false;
31999 if (maxAlignedBytes > currentAlignedBytes) {
32000 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
32001 ready = true;
32002 }
32003 const queue = controller._queue;
32004 while (totalBytesToCopyRemaining > 0) {
32005 const headOfQueue = queue.peek();
32006 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
32007 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32008 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
32009 if (headOfQueue.byteLength === bytesToCopy) {
32010 queue.shift();
32011 }
32012 else {
32013 headOfQueue.byteOffset += bytesToCopy;
32014 headOfQueue.byteLength -= bytesToCopy;
32015 }
32016 controller._queueTotalSize -= bytesToCopy;
32017 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
32018 totalBytesToCopyRemaining -= bytesToCopy;
32019 }
32020 return ready;
32021}
32022function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
32023 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32024 pullIntoDescriptor.bytesFilled += size;
32025}
32026function ReadableByteStreamControllerHandleQueueDrain(controller) {
32027 if (controller._queueTotalSize === 0 && controller._closeRequested) {
32028 ReadableByteStreamControllerClearAlgorithms(controller);
32029 ReadableStreamClose(controller._controlledReadableByteStream);
32030 }
32031 else {
32032 ReadableByteStreamControllerCallPullIfNeeded(controller);
32033 }
32034}
32035function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
32036 if (controller._byobRequest === null) {
32037 return;
32038 }
32039 controller._byobRequest._associatedReadableByteStreamController = undefined;
32040 controller._byobRequest._view = null;
32041 controller._byobRequest = null;
32042}
32043function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
32044 while (controller._pendingPullIntos.length > 0) {
32045 if (controller._queueTotalSize === 0) {
32046 return;
32047 }
32048 const pullIntoDescriptor = controller._pendingPullIntos.peek();
32049 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32050 ReadableByteStreamControllerShiftPendingPullInto(controller);
32051 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32052 }
32053 }
32054}
32055function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
32056 const stream = controller._controlledReadableByteStream;
32057 let elementSize = 1;
32058 if (view.constructor !== DataView) {
32059 elementSize = view.constructor.BYTES_PER_ELEMENT;
32060 }
32061 const ctor = view.constructor;
32062 const buffer = TransferArrayBuffer(view.buffer);
32063 const pullIntoDescriptor = {
32064 buffer,
32065 byteOffset: view.byteOffset,
32066 byteLength: view.byteLength,
32067 bytesFilled: 0,
32068 elementSize,
32069 viewConstructor: ctor,
32070 readerType: 'byob'
32071 };
32072 if (controller._pendingPullIntos.length > 0) {
32073 controller._pendingPullIntos.push(pullIntoDescriptor);
32074 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
32075 // - No change happens on desiredSize
32076 // - The source has already been notified of that there's at least 1 pending read(view)
32077 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32078 return;
32079 }
32080 if (stream._state === 'closed') {
32081 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
32082 readIntoRequest._closeSteps(emptyView);
32083 return;
32084 }
32085 if (controller._queueTotalSize > 0) {
32086 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32087 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
32088 ReadableByteStreamControllerHandleQueueDrain(controller);
32089 readIntoRequest._chunkSteps(filledView);
32090 return;
32091 }
32092 if (controller._closeRequested) {
32093 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32094 ReadableByteStreamControllerError(controller, e);
32095 readIntoRequest._errorSteps(e);
32096 return;
32097 }
32098 }
32099 controller._pendingPullIntos.push(pullIntoDescriptor);
32100 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32101 ReadableByteStreamControllerCallPullIfNeeded(controller);
32102}
32103function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
32104 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
32105 const stream = controller._controlledReadableByteStream;
32106 if (ReadableStreamHasBYOBReader(stream)) {
32107 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32108 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
32109 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
32110 }
32111 }
32112}
32113function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
32114 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
32115 throw new RangeError('bytesWritten out of range');
32116 }
32117 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
32118 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
32119 // TODO: Figure out whether we should detach the buffer or not here.
32120 return;
32121 }
32122 ReadableByteStreamControllerShiftPendingPullInto(controller);
32123 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
32124 if (remainderSize > 0) {
32125 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32126 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
32127 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
32128 }
32129 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
32130 pullIntoDescriptor.bytesFilled -= remainderSize;
32131 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32132 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32133}
32134function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
32135 const firstDescriptor = controller._pendingPullIntos.peek();
32136 const state = controller._controlledReadableByteStream._state;
32137 if (state === 'closed') {
32138 if (bytesWritten !== 0) {
32139 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
32140 }
32141 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
32142 }
32143 else {
32144 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
32145 }
32146 ReadableByteStreamControllerCallPullIfNeeded(controller);
32147}
32148function ReadableByteStreamControllerShiftPendingPullInto(controller) {
32149 const descriptor = controller._pendingPullIntos.shift();
32150 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32151 return descriptor;
32152}
32153function ReadableByteStreamControllerShouldCallPull(controller) {
32154 const stream = controller._controlledReadableByteStream;
32155 if (stream._state !== 'readable') {
32156 return false;
32157 }
32158 if (controller._closeRequested) {
32159 return false;
32160 }
32161 if (!controller._started) {
32162 return false;
32163 }
32164 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
32165 return true;
32166 }
32167 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32168 return true;
32169 }
32170 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
32171 if (desiredSize > 0) {
32172 return true;
32173 }
32174 return false;
32175}
32176function ReadableByteStreamControllerClearAlgorithms(controller) {
32177 controller._pullAlgorithm = undefined;
32178 controller._cancelAlgorithm = undefined;
32179}
32180// A client of ReadableByteStreamController may use these functions directly to bypass state check.
32181function ReadableByteStreamControllerClose(controller) {
32182 const stream = controller._controlledReadableByteStream;
32183 if (controller._closeRequested || stream._state !== 'readable') {
32184 return;
32185 }
32186 if (controller._queueTotalSize > 0) {
32187 controller._closeRequested = true;
32188 return;
32189 }
32190 if (controller._pendingPullIntos.length > 0) {
32191 const firstPendingPullInto = controller._pendingPullIntos.peek();
32192 if (firstPendingPullInto.bytesFilled > 0) {
32193 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32194 ReadableByteStreamControllerError(controller, e);
32195 throw e;
32196 }
32197 }
32198 ReadableByteStreamControllerClearAlgorithms(controller);
32199 ReadableStreamClose(stream);
32200}
32201function ReadableByteStreamControllerEnqueue(controller, chunk) {
32202 const stream = controller._controlledReadableByteStream;
32203 if (controller._closeRequested || stream._state !== 'readable') {
32204 return;
32205 }
32206 const buffer = chunk.buffer;
32207 const byteOffset = chunk.byteOffset;
32208 const byteLength = chunk.byteLength;
32209 const transferredBuffer = TransferArrayBuffer(buffer);
32210 if (ReadableStreamHasDefaultReader(stream)) {
32211 if (ReadableStreamGetNumReadRequests(stream) === 0) {
32212 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32213 }
32214 else {
32215 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
32216 ReadableStreamFulfillReadRequest(stream, transferredView, false);
32217 }
32218 }
32219 else if (ReadableStreamHasBYOBReader(stream)) {
32220 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
32221 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32222 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32223 }
32224 else {
32225 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32226 }
32227 ReadableByteStreamControllerCallPullIfNeeded(controller);
32228}
32229function ReadableByteStreamControllerError(controller, e) {
32230 const stream = controller._controlledReadableByteStream;
32231 if (stream._state !== 'readable') {
32232 return;
32233 }
32234 ReadableByteStreamControllerClearPendingPullIntos(controller);
32235 ResetQueue(controller);
32236 ReadableByteStreamControllerClearAlgorithms(controller);
32237 ReadableStreamError(stream, e);
32238}
32239function ReadableByteStreamControllerGetDesiredSize(controller) {
32240 const state = controller._controlledReadableByteStream._state;
32241 if (state === 'errored') {
32242 return null;
32243 }
32244 if (state === 'closed') {
32245 return 0;
32246 }
32247 return controller._strategyHWM - controller._queueTotalSize;
32248}
32249function ReadableByteStreamControllerRespond(controller, bytesWritten) {
32250 bytesWritten = Number(bytesWritten);
32251 if (!IsFiniteNonNegativeNumber(bytesWritten)) {
32252 throw new RangeError('bytesWritten must be a finite');
32253 }
32254 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
32255}
32256function ReadableByteStreamControllerRespondWithNewView(controller, view) {
32257 const firstDescriptor = controller._pendingPullIntos.peek();
32258 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
32259 throw new RangeError('The region specified by view does not match byobRequest');
32260 }
32261 if (firstDescriptor.byteLength !== view.byteLength) {
32262 throw new RangeError('The buffer of view has different capacity than byobRequest');
32263 }
32264 firstDescriptor.buffer = view.buffer;
32265 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
32266}
32267function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
32268 controller._controlledReadableByteStream = stream;
32269 controller._pullAgain = false;
32270 controller._pulling = false;
32271 controller._byobRequest = null;
32272 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
32273 controller._queue = controller._queueTotalSize = undefined;
32274 ResetQueue(controller);
32275 controller._closeRequested = false;
32276 controller._started = false;
32277 controller._strategyHWM = highWaterMark;
32278 controller._pullAlgorithm = pullAlgorithm;
32279 controller._cancelAlgorithm = cancelAlgorithm;
32280 controller._autoAllocateChunkSize = autoAllocateChunkSize;
32281 controller._pendingPullIntos = new SimpleQueue();
32282 stream._readableStreamController = controller;
32283 const startResult = startAlgorithm();
32284 uponPromise(promiseResolvedWith(startResult), () => {
32285 controller._started = true;
32286 ReadableByteStreamControllerCallPullIfNeeded(controller);
32287 }, r => {
32288 ReadableByteStreamControllerError(controller, r);
32289 });
32290}
32291function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
32292 const controller = Object.create(ReadableByteStreamController.prototype);
32293 let startAlgorithm = () => undefined;
32294 let pullAlgorithm = () => promiseResolvedWith(undefined);
32295 let cancelAlgorithm = () => promiseResolvedWith(undefined);
32296 if (underlyingByteSource.start !== undefined) {
32297 startAlgorithm = () => underlyingByteSource.start(controller);
32298 }
32299 if (underlyingByteSource.pull !== undefined) {
32300 pullAlgorithm = () => underlyingByteSource.pull(controller);
32301 }
32302 if (underlyingByteSource.cancel !== undefined) {
32303 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
32304 }
32305 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
32306 if (autoAllocateChunkSize === 0) {
32307 throw new TypeError('autoAllocateChunkSize must be greater than 0');
32308 }
32309 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
32310}
32311function SetUpReadableStreamBYOBRequest(request, controller, view) {
32312 request._associatedReadableByteStreamController = controller;
32313 request._view = view;
32314}
32315// Helper functions for the ReadableStreamBYOBRequest.
32316function byobRequestBrandCheckException(name) {
32317 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
32318}
32319// Helper functions for the ReadableByteStreamController.
32320function byteStreamControllerBrandCheckException(name) {
32321 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
32322}
32323
32324// Abstract operations for the ReadableStream.
32325function AcquireReadableStreamBYOBReader(stream) {
32326 return new ReadableStreamBYOBReader(stream);
32327}
32328// ReadableStream API exposed for controllers.
32329function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
32330 stream._reader._readIntoRequests.push(readIntoRequest);
32331}
32332function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
32333 const reader = stream._reader;
32334 const readIntoRequest = reader._readIntoRequests.shift();
32335 if (done) {
32336 readIntoRequest._closeSteps(chunk);
32337 }
32338 else {
32339 readIntoRequest._chunkSteps(chunk);
32340 }
32341}
32342function ReadableStreamGetNumReadIntoRequests(stream) {
32343 return stream._reader._readIntoRequests.length;
32344}
32345function ReadableStreamHasBYOBReader(stream) {
32346 const reader = stream._reader;
32347 if (reader === undefined) {
32348 return false;
32349 }
32350 if (!IsReadableStreamBYOBReader(reader)) {
32351 return false;
32352 }
32353 return true;
32354}
32355/**
32356 * A BYOB reader vended by a {@link ReadableStream}.
32357 *
32358 * @public
32359 */
32360class ReadableStreamBYOBReader {
32361 constructor(stream) {
32362 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
32363 assertReadableStream(stream, 'First parameter');
32364 if (IsReadableStreamLocked(stream)) {
32365 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
32366 }
32367 if (!IsReadableByteStreamController(stream._readableStreamController)) {
32368 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
32369 'source');
32370 }
32371 ReadableStreamReaderGenericInitialize(this, stream);
32372 this._readIntoRequests = new SimpleQueue();
32373 }
32374 /**
32375 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32376 * the reader's lock is released before the stream finishes closing.
32377 */
32378 get closed() {
32379 if (!IsReadableStreamBYOBReader(this)) {
32380 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
32381 }
32382 return this._closedPromise;
32383 }
32384 /**
32385 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
32386 */
32387 cancel(reason = undefined) {
32388 if (!IsReadableStreamBYOBReader(this)) {
32389 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
32390 }
32391 if (this._ownerReadableStream === undefined) {
32392 return promiseRejectedWith(readerLockException('cancel'));
32393 }
32394 return ReadableStreamReaderGenericCancel(this, reason);
32395 }
32396 /**
32397 * Attempts to reads bytes into view, and returns a promise resolved with the result.
32398 *
32399 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
32400 */
32401 read(view) {
32402 if (!IsReadableStreamBYOBReader(this)) {
32403 return promiseRejectedWith(byobReaderBrandCheckException('read'));
32404 }
32405 if (!ArrayBuffer.isView(view)) {
32406 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
32407 }
32408 if (view.byteLength === 0) {
32409 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
32410 }
32411 if (view.buffer.byteLength === 0) {
32412 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
32413 }
32414 if (this._ownerReadableStream === undefined) {
32415 return promiseRejectedWith(readerLockException('read from'));
32416 }
32417 let resolvePromise;
32418 let rejectPromise;
32419 const promise = newPromise((resolve, reject) => {
32420 resolvePromise = resolve;
32421 rejectPromise = reject;
32422 });
32423 const readIntoRequest = {
32424 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
32425 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
32426 _errorSteps: e => rejectPromise(e)
32427 };
32428 ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
32429 return promise;
32430 }
32431 /**
32432 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
32433 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
32434 * from now on; otherwise, the reader will appear closed.
32435 *
32436 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
32437 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
32438 * do so will throw a `TypeError` and leave the reader locked to the stream.
32439 */
32440 releaseLock() {
32441 if (!IsReadableStreamBYOBReader(this)) {
32442 throw byobReaderBrandCheckException('releaseLock');
32443 }
32444 if (this._ownerReadableStream === undefined) {
32445 return;
32446 }
32447 if (this._readIntoRequests.length > 0) {
32448 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
32449 }
32450 ReadableStreamReaderGenericRelease(this);
32451 }
32452}
32453Object.defineProperties(ReadableStreamBYOBReader.prototype, {
32454 cancel: { enumerable: true },
32455 read: { enumerable: true },
32456 releaseLock: { enumerable: true },
32457 closed: { enumerable: true }
32458});
32459if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32460 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
32461 value: 'ReadableStreamBYOBReader',
32462 configurable: true
32463 });
32464}
32465// Abstract operations for the readers.
32466function IsReadableStreamBYOBReader(x) {
32467 if (!typeIsObject(x)) {
32468 return false;
32469 }
32470 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
32471 return false;
32472 }
32473 return true;
32474}
32475function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
32476 const stream = reader._ownerReadableStream;
32477 stream._disturbed = true;
32478 if (stream._state === 'errored') {
32479 readIntoRequest._errorSteps(stream._storedError);
32480 }
32481 else {
32482 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
32483 }
32484}
32485// Helper functions for the ReadableStreamBYOBReader.
32486function byobReaderBrandCheckException(name) {
32487 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
32488}
32489
32490function ExtractHighWaterMark(strategy, defaultHWM) {
32491 const { highWaterMark } = strategy;
32492 if (highWaterMark === undefined) {
32493 return defaultHWM;
32494 }
32495 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
32496 throw new RangeError('Invalid highWaterMark');
32497 }
32498 return highWaterMark;
32499}
32500function ExtractSizeAlgorithm(strategy) {
32501 const { size } = strategy;
32502 if (!size) {
32503 return () => 1;
32504 }
32505 return size;
32506}
32507
32508function convertQueuingStrategy(init, context) {
32509 assertDictionary(init, context);
32510 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
32511 const size = init === null || init === void 0 ? void 0 : init.size;
32512 return {
32513 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
32514 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
32515 };
32516}
32517function convertQueuingStrategySize(fn, context) {
32518 assertFunction(fn, context);
32519 return chunk => convertUnrestrictedDouble(fn(chunk));
32520}
32521
32522function convertUnderlyingSink(original, context) {
32523 assertDictionary(original, context);
32524 const abort = original === null || original === void 0 ? void 0 : original.abort;
32525 const close = original === null || original === void 0 ? void 0 : original.close;
32526 const start = original === null || original === void 0 ? void 0 : original.start;
32527 const type = original === null || original === void 0 ? void 0 : original.type;
32528 const write = original === null || original === void 0 ? void 0 : original.write;
32529 return {
32530 abort: abort === undefined ?
32531 undefined :
32532 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
32533 close: close === undefined ?
32534 undefined :
32535 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
32536 start: start === undefined ?
32537 undefined :
32538 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
32539 write: write === undefined ?
32540 undefined :
32541 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
32542 type
32543 };
32544}
32545function convertUnderlyingSinkAbortCallback(fn, original, context) {
32546 assertFunction(fn, context);
32547 return (reason) => promiseCall(fn, original, [reason]);
32548}
32549function convertUnderlyingSinkCloseCallback(fn, original, context) {
32550 assertFunction(fn, context);
32551 return () => promiseCall(fn, original, []);
32552}
32553function convertUnderlyingSinkStartCallback(fn, original, context) {
32554 assertFunction(fn, context);
32555 return (controller) => reflectCall(fn, original, [controller]);
32556}
32557function convertUnderlyingSinkWriteCallback(fn, original, context) {
32558 assertFunction(fn, context);
32559 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
32560}
32561
32562function assertWritableStream(x, context) {
32563 if (!IsWritableStream(x)) {
32564 throw new TypeError(`${context} is not a WritableStream.`);
32565 }
32566}
32567
32568/**
32569 * A writable stream represents a destination for data, into which you can write.
32570 *
32571 * @public
32572 */
32573class WritableStream$1 {
32574 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
32575 if (rawUnderlyingSink === undefined) {
32576 rawUnderlyingSink = null;
32577 }
32578 else {
32579 assertObject(rawUnderlyingSink, 'First parameter');
32580 }
32581 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
32582 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
32583 InitializeWritableStream(this);
32584 const type = underlyingSink.type;
32585 if (type !== undefined) {
32586 throw new RangeError('Invalid type is specified');
32587 }
32588 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
32589 const highWaterMark = ExtractHighWaterMark(strategy, 1);
32590 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
32591 }
32592 /**
32593 * Returns whether or not the writable stream is locked to a writer.
32594 */
32595 get locked() {
32596 if (!IsWritableStream(this)) {
32597 throw streamBrandCheckException$2('locked');
32598 }
32599 return IsWritableStreamLocked(this);
32600 }
32601 /**
32602 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
32603 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
32604 * mechanism of the underlying sink.
32605 *
32606 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
32607 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
32608 * the stream) if the stream is currently locked.
32609 */
32610 abort(reason = undefined) {
32611 if (!IsWritableStream(this)) {
32612 return promiseRejectedWith(streamBrandCheckException$2('abort'));
32613 }
32614 if (IsWritableStreamLocked(this)) {
32615 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
32616 }
32617 return WritableStreamAbort(this, reason);
32618 }
32619 /**
32620 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
32621 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
32622 *
32623 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
32624 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
32625 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
32626 */
32627 close() {
32628 if (!IsWritableStream(this)) {
32629 return promiseRejectedWith(streamBrandCheckException$2('close'));
32630 }
32631 if (IsWritableStreamLocked(this)) {
32632 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
32633 }
32634 if (WritableStreamCloseQueuedOrInFlight(this)) {
32635 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
32636 }
32637 return WritableStreamClose(this);
32638 }
32639 /**
32640 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
32641 * is locked, no other writer can be acquired until this one is released.
32642 *
32643 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
32644 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
32645 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
32646 */
32647 getWriter() {
32648 if (!IsWritableStream(this)) {
32649 throw streamBrandCheckException$2('getWriter');
32650 }
32651 return AcquireWritableStreamDefaultWriter(this);
32652 }
32653}
32654Object.defineProperties(WritableStream$1.prototype, {
32655 abort: { enumerable: true },
32656 close: { enumerable: true },
32657 getWriter: { enumerable: true },
32658 locked: { enumerable: true }
32659});
32660if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32661 Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, {
32662 value: 'WritableStream',
32663 configurable: true
32664 });
32665}
32666// Abstract operations for the WritableStream.
32667function AcquireWritableStreamDefaultWriter(stream) {
32668 return new WritableStreamDefaultWriter(stream);
32669}
32670// Throws if and only if startAlgorithm throws.
32671function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
32672 const stream = Object.create(WritableStream$1.prototype);
32673 InitializeWritableStream(stream);
32674 const controller = Object.create(WritableStreamDefaultController.prototype);
32675 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
32676 return stream;
32677}
32678function InitializeWritableStream(stream) {
32679 stream._state = 'writable';
32680 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
32681 // 'erroring' or 'errored'. May be set to an undefined value.
32682 stream._storedError = undefined;
32683 stream._writer = undefined;
32684 // Initialize to undefined first because the constructor of the controller checks this
32685 // variable to validate the caller.
32686 stream._writableStreamController = undefined;
32687 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
32688 // producer without waiting for the queued writes to finish.
32689 stream._writeRequests = new SimpleQueue();
32690 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
32691 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
32692 stream._inFlightWriteRequest = undefined;
32693 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
32694 // has been detached.
32695 stream._closeRequest = undefined;
32696 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
32697 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
32698 stream._inFlightCloseRequest = undefined;
32699 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
32700 stream._pendingAbortRequest = undefined;
32701 // The backpressure signal set by the controller.
32702 stream._backpressure = false;
32703}
32704function IsWritableStream(x) {
32705 if (!typeIsObject(x)) {
32706 return false;
32707 }
32708 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
32709 return false;
32710 }
32711 return true;
32712}
32713function IsWritableStreamLocked(stream) {
32714 if (stream._writer === undefined) {
32715 return false;
32716 }
32717 return true;
32718}
32719function WritableStreamAbort(stream, reason) {
32720 const state = stream._state;
32721 if (state === 'closed' || state === 'errored') {
32722 return promiseResolvedWith(undefined);
32723 }
32724 if (stream._pendingAbortRequest !== undefined) {
32725 return stream._pendingAbortRequest._promise;
32726 }
32727 let wasAlreadyErroring = false;
32728 if (state === 'erroring') {
32729 wasAlreadyErroring = true;
32730 // reason will not be used, so don't keep a reference to it.
32731 reason = undefined;
32732 }
32733 const promise = newPromise((resolve, reject) => {
32734 stream._pendingAbortRequest = {
32735 _promise: undefined,
32736 _resolve: resolve,
32737 _reject: reject,
32738 _reason: reason,
32739 _wasAlreadyErroring: wasAlreadyErroring
32740 };
32741 });
32742 stream._pendingAbortRequest._promise = promise;
32743 if (!wasAlreadyErroring) {
32744 WritableStreamStartErroring(stream, reason);
32745 }
32746 return promise;
32747}
32748function WritableStreamClose(stream) {
32749 const state = stream._state;
32750 if (state === 'closed' || state === 'errored') {
32751 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
32752 }
32753 const promise = newPromise((resolve, reject) => {
32754 const closeRequest = {
32755 _resolve: resolve,
32756 _reject: reject
32757 };
32758 stream._closeRequest = closeRequest;
32759 });
32760 const writer = stream._writer;
32761 if (writer !== undefined && stream._backpressure && state === 'writable') {
32762 defaultWriterReadyPromiseResolve(writer);
32763 }
32764 WritableStreamDefaultControllerClose(stream._writableStreamController);
32765 return promise;
32766}
32767// WritableStream API exposed for controllers.
32768function WritableStreamAddWriteRequest(stream) {
32769 const promise = newPromise((resolve, reject) => {
32770 const writeRequest = {
32771 _resolve: resolve,
32772 _reject: reject
32773 };
32774 stream._writeRequests.push(writeRequest);
32775 });
32776 return promise;
32777}
32778function WritableStreamDealWithRejection(stream, error) {
32779 const state = stream._state;
32780 if (state === 'writable') {
32781 WritableStreamStartErroring(stream, error);
32782 return;
32783 }
32784 WritableStreamFinishErroring(stream);
32785}
32786function WritableStreamStartErroring(stream, reason) {
32787 const controller = stream._writableStreamController;
32788 stream._state = 'erroring';
32789 stream._storedError = reason;
32790 const writer = stream._writer;
32791 if (writer !== undefined) {
32792 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
32793 }
32794 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
32795 WritableStreamFinishErroring(stream);
32796 }
32797}
32798function WritableStreamFinishErroring(stream) {
32799 stream._state = 'errored';
32800 stream._writableStreamController[ErrorSteps]();
32801 const storedError = stream._storedError;
32802 stream._writeRequests.forEach(writeRequest => {
32803 writeRequest._reject(storedError);
32804 });
32805 stream._writeRequests = new SimpleQueue();
32806 if (stream._pendingAbortRequest === undefined) {
32807 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32808 return;
32809 }
32810 const abortRequest = stream._pendingAbortRequest;
32811 stream._pendingAbortRequest = undefined;
32812 if (abortRequest._wasAlreadyErroring) {
32813 abortRequest._reject(storedError);
32814 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32815 return;
32816 }
32817 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
32818 uponPromise(promise, () => {
32819 abortRequest._resolve();
32820 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32821 }, (reason) => {
32822 abortRequest._reject(reason);
32823 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32824 });
32825}
32826function WritableStreamFinishInFlightWrite(stream) {
32827 stream._inFlightWriteRequest._resolve(undefined);
32828 stream._inFlightWriteRequest = undefined;
32829}
32830function WritableStreamFinishInFlightWriteWithError(stream, error) {
32831 stream._inFlightWriteRequest._reject(error);
32832 stream._inFlightWriteRequest = undefined;
32833 WritableStreamDealWithRejection(stream, error);
32834}
32835function WritableStreamFinishInFlightClose(stream) {
32836 stream._inFlightCloseRequest._resolve(undefined);
32837 stream._inFlightCloseRequest = undefined;
32838 const state = stream._state;
32839 if (state === 'erroring') {
32840 // The error was too late to do anything, so it is ignored.
32841 stream._storedError = undefined;
32842 if (stream._pendingAbortRequest !== undefined) {
32843 stream._pendingAbortRequest._resolve();
32844 stream._pendingAbortRequest = undefined;
32845 }
32846 }
32847 stream._state = 'closed';
32848 const writer = stream._writer;
32849 if (writer !== undefined) {
32850 defaultWriterClosedPromiseResolve(writer);
32851 }
32852}
32853function WritableStreamFinishInFlightCloseWithError(stream, error) {
32854 stream._inFlightCloseRequest._reject(error);
32855 stream._inFlightCloseRequest = undefined;
32856 // Never execute sink abort() after sink close().
32857 if (stream._pendingAbortRequest !== undefined) {
32858 stream._pendingAbortRequest._reject(error);
32859 stream._pendingAbortRequest = undefined;
32860 }
32861 WritableStreamDealWithRejection(stream, error);
32862}
32863// TODO(ricea): Fix alphabetical order.
32864function WritableStreamCloseQueuedOrInFlight(stream) {
32865 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
32866 return false;
32867 }
32868 return true;
32869}
32870function WritableStreamHasOperationMarkedInFlight(stream) {
32871 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
32872 return false;
32873 }
32874 return true;
32875}
32876function WritableStreamMarkCloseRequestInFlight(stream) {
32877 stream._inFlightCloseRequest = stream._closeRequest;
32878 stream._closeRequest = undefined;
32879}
32880function WritableStreamMarkFirstWriteRequestInFlight(stream) {
32881 stream._inFlightWriteRequest = stream._writeRequests.shift();
32882}
32883function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
32884 if (stream._closeRequest !== undefined) {
32885 stream._closeRequest._reject(stream._storedError);
32886 stream._closeRequest = undefined;
32887 }
32888 const writer = stream._writer;
32889 if (writer !== undefined) {
32890 defaultWriterClosedPromiseReject(writer, stream._storedError);
32891 }
32892}
32893function WritableStreamUpdateBackpressure(stream, backpressure) {
32894 const writer = stream._writer;
32895 if (writer !== undefined && backpressure !== stream._backpressure) {
32896 if (backpressure) {
32897 defaultWriterReadyPromiseReset(writer);
32898 }
32899 else {
32900 defaultWriterReadyPromiseResolve(writer);
32901 }
32902 }
32903 stream._backpressure = backpressure;
32904}
32905/**
32906 * A default writer vended by a {@link WritableStream}.
32907 *
32908 * @public
32909 */
32910class WritableStreamDefaultWriter {
32911 constructor(stream) {
32912 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
32913 assertWritableStream(stream, 'First parameter');
32914 if (IsWritableStreamLocked(stream)) {
32915 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
32916 }
32917 this._ownerWritableStream = stream;
32918 stream._writer = this;
32919 const state = stream._state;
32920 if (state === 'writable') {
32921 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
32922 defaultWriterReadyPromiseInitialize(this);
32923 }
32924 else {
32925 defaultWriterReadyPromiseInitializeAsResolved(this);
32926 }
32927 defaultWriterClosedPromiseInitialize(this);
32928 }
32929 else if (state === 'erroring') {
32930 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
32931 defaultWriterClosedPromiseInitialize(this);
32932 }
32933 else if (state === 'closed') {
32934 defaultWriterReadyPromiseInitializeAsResolved(this);
32935 defaultWriterClosedPromiseInitializeAsResolved(this);
32936 }
32937 else {
32938 const storedError = stream._storedError;
32939 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
32940 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
32941 }
32942 }
32943 /**
32944 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32945 * the writer’s lock is released before the stream finishes closing.
32946 */
32947 get closed() {
32948 if (!IsWritableStreamDefaultWriter(this)) {
32949 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
32950 }
32951 return this._closedPromise;
32952 }
32953 /**
32954 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
32955 * A producer can use this information to determine the right amount of data to write.
32956 *
32957 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
32958 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
32959 * the writer’s lock is released.
32960 */
32961 get desiredSize() {
32962 if (!IsWritableStreamDefaultWriter(this)) {
32963 throw defaultWriterBrandCheckException('desiredSize');
32964 }
32965 if (this._ownerWritableStream === undefined) {
32966 throw defaultWriterLockException('desiredSize');
32967 }
32968 return WritableStreamDefaultWriterGetDesiredSize(this);
32969 }
32970 /**
32971 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
32972 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
32973 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
32974 *
32975 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
32976 * rejected.
32977 */
32978 get ready() {
32979 if (!IsWritableStreamDefaultWriter(this)) {
32980 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
32981 }
32982 return this._readyPromise;
32983 }
32984 /**
32985 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
32986 */
32987 abort(reason = undefined) {
32988 if (!IsWritableStreamDefaultWriter(this)) {
32989 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
32990 }
32991 if (this._ownerWritableStream === undefined) {
32992 return promiseRejectedWith(defaultWriterLockException('abort'));
32993 }
32994 return WritableStreamDefaultWriterAbort(this, reason);
32995 }
32996 /**
32997 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
32998 */
32999 close() {
33000 if (!IsWritableStreamDefaultWriter(this)) {
33001 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
33002 }
33003 const stream = this._ownerWritableStream;
33004 if (stream === undefined) {
33005 return promiseRejectedWith(defaultWriterLockException('close'));
33006 }
33007 if (WritableStreamCloseQueuedOrInFlight(stream)) {
33008 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
33009 }
33010 return WritableStreamDefaultWriterClose(this);
33011 }
33012 /**
33013 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
33014 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
33015 * now on; otherwise, the writer will appear closed.
33016 *
33017 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
33018 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
33019 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
33020 * other producers from writing in an interleaved manner.
33021 */
33022 releaseLock() {
33023 if (!IsWritableStreamDefaultWriter(this)) {
33024 throw defaultWriterBrandCheckException('releaseLock');
33025 }
33026 const stream = this._ownerWritableStream;
33027 if (stream === undefined) {
33028 return;
33029 }
33030 WritableStreamDefaultWriterRelease(this);
33031 }
33032 write(chunk = undefined) {
33033 if (!IsWritableStreamDefaultWriter(this)) {
33034 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
33035 }
33036 if (this._ownerWritableStream === undefined) {
33037 return promiseRejectedWith(defaultWriterLockException('write to'));
33038 }
33039 return WritableStreamDefaultWriterWrite(this, chunk);
33040 }
33041}
33042Object.defineProperties(WritableStreamDefaultWriter.prototype, {
33043 abort: { enumerable: true },
33044 close: { enumerable: true },
33045 releaseLock: { enumerable: true },
33046 write: { enumerable: true },
33047 closed: { enumerable: true },
33048 desiredSize: { enumerable: true },
33049 ready: { enumerable: true }
33050});
33051if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33052 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
33053 value: 'WritableStreamDefaultWriter',
33054 configurable: true
33055 });
33056}
33057// Abstract operations for the WritableStreamDefaultWriter.
33058function IsWritableStreamDefaultWriter(x) {
33059 if (!typeIsObject(x)) {
33060 return false;
33061 }
33062 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
33063 return false;
33064 }
33065 return true;
33066}
33067// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
33068function WritableStreamDefaultWriterAbort(writer, reason) {
33069 const stream = writer._ownerWritableStream;
33070 return WritableStreamAbort(stream, reason);
33071}
33072function WritableStreamDefaultWriterClose(writer) {
33073 const stream = writer._ownerWritableStream;
33074 return WritableStreamClose(stream);
33075}
33076function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
33077 const stream = writer._ownerWritableStream;
33078 const state = stream._state;
33079 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33080 return promiseResolvedWith(undefined);
33081 }
33082 if (state === 'errored') {
33083 return promiseRejectedWith(stream._storedError);
33084 }
33085 return WritableStreamDefaultWriterClose(writer);
33086}
33087function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
33088 if (writer._closedPromiseState === 'pending') {
33089 defaultWriterClosedPromiseReject(writer, error);
33090 }
33091 else {
33092 defaultWriterClosedPromiseResetToRejected(writer, error);
33093 }
33094}
33095function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
33096 if (writer._readyPromiseState === 'pending') {
33097 defaultWriterReadyPromiseReject(writer, error);
33098 }
33099 else {
33100 defaultWriterReadyPromiseResetToRejected(writer, error);
33101 }
33102}
33103function WritableStreamDefaultWriterGetDesiredSize(writer) {
33104 const stream = writer._ownerWritableStream;
33105 const state = stream._state;
33106 if (state === 'errored' || state === 'erroring') {
33107 return null;
33108 }
33109 if (state === 'closed') {
33110 return 0;
33111 }
33112 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
33113}
33114function WritableStreamDefaultWriterRelease(writer) {
33115 const stream = writer._ownerWritableStream;
33116 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
33117 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
33118 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
33119 // rejected until afterwards. This means that simply testing state will not work.
33120 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
33121 stream._writer = undefined;
33122 writer._ownerWritableStream = undefined;
33123}
33124function WritableStreamDefaultWriterWrite(writer, chunk) {
33125 const stream = writer._ownerWritableStream;
33126 const controller = stream._writableStreamController;
33127 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
33128 if (stream !== writer._ownerWritableStream) {
33129 return promiseRejectedWith(defaultWriterLockException('write to'));
33130 }
33131 const state = stream._state;
33132 if (state === 'errored') {
33133 return promiseRejectedWith(stream._storedError);
33134 }
33135 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33136 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
33137 }
33138 if (state === 'erroring') {
33139 return promiseRejectedWith(stream._storedError);
33140 }
33141 const promise = WritableStreamAddWriteRequest(stream);
33142 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
33143 return promise;
33144}
33145const closeSentinel = {};
33146/**
33147 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
33148 *
33149 * @public
33150 */
33151class WritableStreamDefaultController {
33152 constructor() {
33153 throw new TypeError('Illegal constructor');
33154 }
33155 /**
33156 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
33157 *
33158 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
33159 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
33160 * normal lifecycle of interactions with the underlying sink.
33161 */
33162 error(e = undefined) {
33163 if (!IsWritableStreamDefaultController(this)) {
33164 throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
33165 }
33166 const state = this._controlledWritableStream._state;
33167 if (state !== 'writable') {
33168 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
33169 // just treat it as a no-op.
33170 return;
33171 }
33172 WritableStreamDefaultControllerError(this, e);
33173 }
33174 /** @internal */
33175 [AbortSteps](reason) {
33176 const result = this._abortAlgorithm(reason);
33177 WritableStreamDefaultControllerClearAlgorithms(this);
33178 return result;
33179 }
33180 /** @internal */
33181 [ErrorSteps]() {
33182 ResetQueue(this);
33183 }
33184}
33185Object.defineProperties(WritableStreamDefaultController.prototype, {
33186 error: { enumerable: true }
33187});
33188if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33189 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33190 value: 'WritableStreamDefaultController',
33191 configurable: true
33192 });
33193}
33194// Abstract operations implementing interface required by the WritableStream.
33195function IsWritableStreamDefaultController(x) {
33196 if (!typeIsObject(x)) {
33197 return false;
33198 }
33199 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
33200 return false;
33201 }
33202 return true;
33203}
33204function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
33205 controller._controlledWritableStream = stream;
33206 stream._writableStreamController = controller;
33207 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
33208 controller._queue = undefined;
33209 controller._queueTotalSize = undefined;
33210 ResetQueue(controller);
33211 controller._started = false;
33212 controller._strategySizeAlgorithm = sizeAlgorithm;
33213 controller._strategyHWM = highWaterMark;
33214 controller._writeAlgorithm = writeAlgorithm;
33215 controller._closeAlgorithm = closeAlgorithm;
33216 controller._abortAlgorithm = abortAlgorithm;
33217 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33218 WritableStreamUpdateBackpressure(stream, backpressure);
33219 const startResult = startAlgorithm();
33220 const startPromise = promiseResolvedWith(startResult);
33221 uponPromise(startPromise, () => {
33222 controller._started = true;
33223 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33224 }, r => {
33225 controller._started = true;
33226 WritableStreamDealWithRejection(stream, r);
33227 });
33228}
33229function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
33230 const controller = Object.create(WritableStreamDefaultController.prototype);
33231 let startAlgorithm = () => undefined;
33232 let writeAlgorithm = () => promiseResolvedWith(undefined);
33233 let closeAlgorithm = () => promiseResolvedWith(undefined);
33234 let abortAlgorithm = () => promiseResolvedWith(undefined);
33235 if (underlyingSink.start !== undefined) {
33236 startAlgorithm = () => underlyingSink.start(controller);
33237 }
33238 if (underlyingSink.write !== undefined) {
33239 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
33240 }
33241 if (underlyingSink.close !== undefined) {
33242 closeAlgorithm = () => underlyingSink.close();
33243 }
33244 if (underlyingSink.abort !== undefined) {
33245 abortAlgorithm = reason => underlyingSink.abort(reason);
33246 }
33247 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
33248}
33249// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
33250function WritableStreamDefaultControllerClearAlgorithms(controller) {
33251 controller._writeAlgorithm = undefined;
33252 controller._closeAlgorithm = undefined;
33253 controller._abortAlgorithm = undefined;
33254 controller._strategySizeAlgorithm = undefined;
33255}
33256function WritableStreamDefaultControllerClose(controller) {
33257 EnqueueValueWithSize(controller, closeSentinel, 0);
33258 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33259}
33260function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
33261 try {
33262 return controller._strategySizeAlgorithm(chunk);
33263 }
33264 catch (chunkSizeE) {
33265 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
33266 return 1;
33267 }
33268}
33269function WritableStreamDefaultControllerGetDesiredSize(controller) {
33270 return controller._strategyHWM - controller._queueTotalSize;
33271}
33272function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
33273 try {
33274 EnqueueValueWithSize(controller, chunk, chunkSize);
33275 }
33276 catch (enqueueE) {
33277 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
33278 return;
33279 }
33280 const stream = controller._controlledWritableStream;
33281 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
33282 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33283 WritableStreamUpdateBackpressure(stream, backpressure);
33284 }
33285 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33286}
33287// Abstract operations for the WritableStreamDefaultController.
33288function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
33289 const stream = controller._controlledWritableStream;
33290 if (!controller._started) {
33291 return;
33292 }
33293 if (stream._inFlightWriteRequest !== undefined) {
33294 return;
33295 }
33296 const state = stream._state;
33297 if (state === 'erroring') {
33298 WritableStreamFinishErroring(stream);
33299 return;
33300 }
33301 if (controller._queue.length === 0) {
33302 return;
33303 }
33304 const value = PeekQueueValue(controller);
33305 if (value === closeSentinel) {
33306 WritableStreamDefaultControllerProcessClose(controller);
33307 }
33308 else {
33309 WritableStreamDefaultControllerProcessWrite(controller, value);
33310 }
33311}
33312function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
33313 if (controller._controlledWritableStream._state === 'writable') {
33314 WritableStreamDefaultControllerError(controller, error);
33315 }
33316}
33317function WritableStreamDefaultControllerProcessClose(controller) {
33318 const stream = controller._controlledWritableStream;
33319 WritableStreamMarkCloseRequestInFlight(stream);
33320 DequeueValue(controller);
33321 const sinkClosePromise = controller._closeAlgorithm();
33322 WritableStreamDefaultControllerClearAlgorithms(controller);
33323 uponPromise(sinkClosePromise, () => {
33324 WritableStreamFinishInFlightClose(stream);
33325 }, reason => {
33326 WritableStreamFinishInFlightCloseWithError(stream, reason);
33327 });
33328}
33329function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
33330 const stream = controller._controlledWritableStream;
33331 WritableStreamMarkFirstWriteRequestInFlight(stream);
33332 const sinkWritePromise = controller._writeAlgorithm(chunk);
33333 uponPromise(sinkWritePromise, () => {
33334 WritableStreamFinishInFlightWrite(stream);
33335 const state = stream._state;
33336 DequeueValue(controller);
33337 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
33338 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33339 WritableStreamUpdateBackpressure(stream, backpressure);
33340 }
33341 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33342 }, reason => {
33343 if (stream._state === 'writable') {
33344 WritableStreamDefaultControllerClearAlgorithms(controller);
33345 }
33346 WritableStreamFinishInFlightWriteWithError(stream, reason);
33347 });
33348}
33349function WritableStreamDefaultControllerGetBackpressure(controller) {
33350 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
33351 return desiredSize <= 0;
33352}
33353// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
33354function WritableStreamDefaultControllerError(controller, error) {
33355 const stream = controller._controlledWritableStream;
33356 WritableStreamDefaultControllerClearAlgorithms(controller);
33357 WritableStreamStartErroring(stream, error);
33358}
33359// Helper functions for the WritableStream.
33360function streamBrandCheckException$2(name) {
33361 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
33362}
33363// Helper functions for the WritableStreamDefaultWriter.
33364function defaultWriterBrandCheckException(name) {
33365 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
33366}
33367function defaultWriterLockException(name) {
33368 return new TypeError('Cannot ' + name + ' a stream using a released writer');
33369}
33370function defaultWriterClosedPromiseInitialize(writer) {
33371 writer._closedPromise = newPromise((resolve, reject) => {
33372 writer._closedPromise_resolve = resolve;
33373 writer._closedPromise_reject = reject;
33374 writer._closedPromiseState = 'pending';
33375 });
33376}
33377function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
33378 defaultWriterClosedPromiseInitialize(writer);
33379 defaultWriterClosedPromiseReject(writer, reason);
33380}
33381function defaultWriterClosedPromiseInitializeAsResolved(writer) {
33382 defaultWriterClosedPromiseInitialize(writer);
33383 defaultWriterClosedPromiseResolve(writer);
33384}
33385function defaultWriterClosedPromiseReject(writer, reason) {
33386 if (writer._closedPromise_reject === undefined) {
33387 return;
33388 }
33389 setPromiseIsHandledToTrue(writer._closedPromise);
33390 writer._closedPromise_reject(reason);
33391 writer._closedPromise_resolve = undefined;
33392 writer._closedPromise_reject = undefined;
33393 writer._closedPromiseState = 'rejected';
33394}
33395function defaultWriterClosedPromiseResetToRejected(writer, reason) {
33396 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
33397}
33398function defaultWriterClosedPromiseResolve(writer) {
33399 if (writer._closedPromise_resolve === undefined) {
33400 return;
33401 }
33402 writer._closedPromise_resolve(undefined);
33403 writer._closedPromise_resolve = undefined;
33404 writer._closedPromise_reject = undefined;
33405 writer._closedPromiseState = 'resolved';
33406}
33407function defaultWriterReadyPromiseInitialize(writer) {
33408 writer._readyPromise = newPromise((resolve, reject) => {
33409 writer._readyPromise_resolve = resolve;
33410 writer._readyPromise_reject = reject;
33411 });
33412 writer._readyPromiseState = 'pending';
33413}
33414function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
33415 defaultWriterReadyPromiseInitialize(writer);
33416 defaultWriterReadyPromiseReject(writer, reason);
33417}
33418function defaultWriterReadyPromiseInitializeAsResolved(writer) {
33419 defaultWriterReadyPromiseInitialize(writer);
33420 defaultWriterReadyPromiseResolve(writer);
33421}
33422function defaultWriterReadyPromiseReject(writer, reason) {
33423 if (writer._readyPromise_reject === undefined) {
33424 return;
33425 }
33426 setPromiseIsHandledToTrue(writer._readyPromise);
33427 writer._readyPromise_reject(reason);
33428 writer._readyPromise_resolve = undefined;
33429 writer._readyPromise_reject = undefined;
33430 writer._readyPromiseState = 'rejected';
33431}
33432function defaultWriterReadyPromiseReset(writer) {
33433 defaultWriterReadyPromiseInitialize(writer);
33434}
33435function defaultWriterReadyPromiseResetToRejected(writer, reason) {
33436 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
33437}
33438function defaultWriterReadyPromiseResolve(writer) {
33439 if (writer._readyPromise_resolve === undefined) {
33440 return;
33441 }
33442 writer._readyPromise_resolve(undefined);
33443 writer._readyPromise_resolve = undefined;
33444 writer._readyPromise_reject = undefined;
33445 writer._readyPromiseState = 'fulfilled';
33446}
33447
33448function isAbortSignal(value) {
33449 if (typeof value !== 'object' || value === null) {
33450 return false;
33451 }
33452 try {
33453 return typeof value.aborted === 'boolean';
33454 }
33455 catch (_a) {
33456 // AbortSignal.prototype.aborted throws if its brand check fails
33457 return false;
33458 }
33459}
33460
33461/// <reference lib="dom" />
33462const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
33463
33464/// <reference types="node" />
33465function isDOMExceptionConstructor(ctor) {
33466 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
33467 return false;
33468 }
33469 try {
33470 new ctor();
33471 return true;
33472 }
33473 catch (_a) {
33474 return false;
33475 }
33476}
33477function createDOMExceptionPolyfill() {
33478 // eslint-disable-next-line no-shadow
33479 const ctor = function DOMException(message, name) {
33480 this.message = message || '';
33481 this.name = name || 'Error';
33482 if (Error.captureStackTrace) {
33483 Error.captureStackTrace(this, this.constructor);
33484 }
33485 };
33486 ctor.prototype = Object.create(Error.prototype);
33487 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
33488 return ctor;
33489}
33490// eslint-disable-next-line no-redeclare
33491const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
33492
33493function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
33494 const reader = AcquireReadableStreamDefaultReader(source);
33495 const writer = AcquireWritableStreamDefaultWriter(dest);
33496 source._disturbed = true;
33497 let shuttingDown = false;
33498 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
33499 let currentWrite = promiseResolvedWith(undefined);
33500 return newPromise((resolve, reject) => {
33501 let abortAlgorithm;
33502 if (signal !== undefined) {
33503 abortAlgorithm = () => {
33504 const error = new DOMException$1('Aborted', 'AbortError');
33505 const actions = [];
33506 if (!preventAbort) {
33507 actions.push(() => {
33508 if (dest._state === 'writable') {
33509 return WritableStreamAbort(dest, error);
33510 }
33511 return promiseResolvedWith(undefined);
33512 });
33513 }
33514 if (!preventCancel) {
33515 actions.push(() => {
33516 if (source._state === 'readable') {
33517 return ReadableStreamCancel(source, error);
33518 }
33519 return promiseResolvedWith(undefined);
33520 });
33521 }
33522 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
33523 };
33524 if (signal.aborted) {
33525 abortAlgorithm();
33526 return;
33527 }
33528 signal.addEventListener('abort', abortAlgorithm);
33529 }
33530 // Using reader and writer, read all chunks from this and write them to dest
33531 // - Backpressure must be enforced
33532 // - Shutdown must stop all activity
33533 function pipeLoop() {
33534 return newPromise((resolveLoop, rejectLoop) => {
33535 function next(done) {
33536 if (done) {
33537 resolveLoop();
33538 }
33539 else {
33540 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
33541 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
33542 PerformPromiseThen(pipeStep(), next, rejectLoop);
33543 }
33544 }
33545 next(false);
33546 });
33547 }
33548 function pipeStep() {
33549 if (shuttingDown) {
33550 return promiseResolvedWith(true);
33551 }
33552 return PerformPromiseThen(writer._readyPromise, () => {
33553 return newPromise((resolveRead, rejectRead) => {
33554 ReadableStreamDefaultReaderRead(reader, {
33555 _chunkSteps: chunk => {
33556 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
33557 resolveRead(false);
33558 },
33559 _closeSteps: () => resolveRead(true),
33560 _errorSteps: rejectRead
33561 });
33562 });
33563 });
33564 }
33565 // Errors must be propagated forward
33566 isOrBecomesErrored(source, reader._closedPromise, storedError => {
33567 if (!preventAbort) {
33568 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
33569 }
33570 else {
33571 shutdown(true, storedError);
33572 }
33573 });
33574 // Errors must be propagated backward
33575 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
33576 if (!preventCancel) {
33577 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
33578 }
33579 else {
33580 shutdown(true, storedError);
33581 }
33582 });
33583 // Closing must be propagated forward
33584 isOrBecomesClosed(source, reader._closedPromise, () => {
33585 if (!preventClose) {
33586 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
33587 }
33588 else {
33589 shutdown();
33590 }
33591 });
33592 // Closing must be propagated backward
33593 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
33594 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
33595 if (!preventCancel) {
33596 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
33597 }
33598 else {
33599 shutdown(true, destClosed);
33600 }
33601 }
33602 setPromiseIsHandledToTrue(pipeLoop());
33603 function waitForWritesToFinish() {
33604 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
33605 // for that too.
33606 const oldCurrentWrite = currentWrite;
33607 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
33608 }
33609 function isOrBecomesErrored(stream, promise, action) {
33610 if (stream._state === 'errored') {
33611 action(stream._storedError);
33612 }
33613 else {
33614 uponRejection(promise, action);
33615 }
33616 }
33617 function isOrBecomesClosed(stream, promise, action) {
33618 if (stream._state === 'closed') {
33619 action();
33620 }
33621 else {
33622 uponFulfillment(promise, action);
33623 }
33624 }
33625 function shutdownWithAction(action, originalIsError, originalError) {
33626 if (shuttingDown) {
33627 return;
33628 }
33629 shuttingDown = true;
33630 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33631 uponFulfillment(waitForWritesToFinish(), doTheRest);
33632 }
33633 else {
33634 doTheRest();
33635 }
33636 function doTheRest() {
33637 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
33638 }
33639 }
33640 function shutdown(isError, error) {
33641 if (shuttingDown) {
33642 return;
33643 }
33644 shuttingDown = true;
33645 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33646 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
33647 }
33648 else {
33649 finalize(isError, error);
33650 }
33651 }
33652 function finalize(isError, error) {
33653 WritableStreamDefaultWriterRelease(writer);
33654 ReadableStreamReaderGenericRelease(reader);
33655 if (signal !== undefined) {
33656 signal.removeEventListener('abort', abortAlgorithm);
33657 }
33658 if (isError) {
33659 reject(error);
33660 }
33661 else {
33662 resolve(undefined);
33663 }
33664 }
33665 });
33666}
33667
33668/**
33669 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
33670 *
33671 * @public
33672 */
33673class ReadableStreamDefaultController {
33674 constructor() {
33675 throw new TypeError('Illegal constructor');
33676 }
33677 /**
33678 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
33679 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
33680 */
33681 get desiredSize() {
33682 if (!IsReadableStreamDefaultController(this)) {
33683 throw defaultControllerBrandCheckException$1('desiredSize');
33684 }
33685 return ReadableStreamDefaultControllerGetDesiredSize(this);
33686 }
33687 /**
33688 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
33689 * the stream, but once those are read, the stream will become closed.
33690 */
33691 close() {
33692 if (!IsReadableStreamDefaultController(this)) {
33693 throw defaultControllerBrandCheckException$1('close');
33694 }
33695 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33696 throw new TypeError('The stream is not in a state that permits close');
33697 }
33698 ReadableStreamDefaultControllerClose(this);
33699 }
33700 enqueue(chunk = undefined) {
33701 if (!IsReadableStreamDefaultController(this)) {
33702 throw defaultControllerBrandCheckException$1('enqueue');
33703 }
33704 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33705 throw new TypeError('The stream is not in a state that permits enqueue');
33706 }
33707 return ReadableStreamDefaultControllerEnqueue(this, chunk);
33708 }
33709 /**
33710 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
33711 */
33712 error(e = undefined) {
33713 if (!IsReadableStreamDefaultController(this)) {
33714 throw defaultControllerBrandCheckException$1('error');
33715 }
33716 ReadableStreamDefaultControllerError(this, e);
33717 }
33718 /** @internal */
33719 [CancelSteps](reason) {
33720 ResetQueue(this);
33721 const result = this._cancelAlgorithm(reason);
33722 ReadableStreamDefaultControllerClearAlgorithms(this);
33723 return result;
33724 }
33725 /** @internal */
33726 [PullSteps](readRequest) {
33727 const stream = this._controlledReadableStream;
33728 if (this._queue.length > 0) {
33729 const chunk = DequeueValue(this);
33730 if (this._closeRequested && this._queue.length === 0) {
33731 ReadableStreamDefaultControllerClearAlgorithms(this);
33732 ReadableStreamClose(stream);
33733 }
33734 else {
33735 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33736 }
33737 readRequest._chunkSteps(chunk);
33738 }
33739 else {
33740 ReadableStreamAddReadRequest(stream, readRequest);
33741 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33742 }
33743 }
33744}
33745Object.defineProperties(ReadableStreamDefaultController.prototype, {
33746 close: { enumerable: true },
33747 enqueue: { enumerable: true },
33748 error: { enumerable: true },
33749 desiredSize: { enumerable: true }
33750});
33751if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33752 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33753 value: 'ReadableStreamDefaultController',
33754 configurable: true
33755 });
33756}
33757// Abstract operations for the ReadableStreamDefaultController.
33758function IsReadableStreamDefaultController(x) {
33759 if (!typeIsObject(x)) {
33760 return false;
33761 }
33762 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
33763 return false;
33764 }
33765 return true;
33766}
33767function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
33768 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
33769 if (!shouldPull) {
33770 return;
33771 }
33772 if (controller._pulling) {
33773 controller._pullAgain = true;
33774 return;
33775 }
33776 controller._pulling = true;
33777 const pullPromise = controller._pullAlgorithm();
33778 uponPromise(pullPromise, () => {
33779 controller._pulling = false;
33780 if (controller._pullAgain) {
33781 controller._pullAgain = false;
33782 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33783 }
33784 }, e => {
33785 ReadableStreamDefaultControllerError(controller, e);
33786 });
33787}
33788function ReadableStreamDefaultControllerShouldCallPull(controller) {
33789 const stream = controller._controlledReadableStream;
33790 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33791 return false;
33792 }
33793 if (!controller._started) {
33794 return false;
33795 }
33796 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33797 return true;
33798 }
33799 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
33800 if (desiredSize > 0) {
33801 return true;
33802 }
33803 return false;
33804}
33805function ReadableStreamDefaultControllerClearAlgorithms(controller) {
33806 controller._pullAlgorithm = undefined;
33807 controller._cancelAlgorithm = undefined;
33808 controller._strategySizeAlgorithm = undefined;
33809}
33810// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
33811function ReadableStreamDefaultControllerClose(controller) {
33812 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33813 return;
33814 }
33815 const stream = controller._controlledReadableStream;
33816 controller._closeRequested = true;
33817 if (controller._queue.length === 0) {
33818 ReadableStreamDefaultControllerClearAlgorithms(controller);
33819 ReadableStreamClose(stream);
33820 }
33821}
33822function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
33823 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33824 return;
33825 }
33826 const stream = controller._controlledReadableStream;
33827 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33828 ReadableStreamFulfillReadRequest(stream, chunk, false);
33829 }
33830 else {
33831 let chunkSize;
33832 try {
33833 chunkSize = controller._strategySizeAlgorithm(chunk);
33834 }
33835 catch (chunkSizeE) {
33836 ReadableStreamDefaultControllerError(controller, chunkSizeE);
33837 throw chunkSizeE;
33838 }
33839 try {
33840 EnqueueValueWithSize(controller, chunk, chunkSize);
33841 }
33842 catch (enqueueE) {
33843 ReadableStreamDefaultControllerError(controller, enqueueE);
33844 throw enqueueE;
33845 }
33846 }
33847 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33848}
33849function ReadableStreamDefaultControllerError(controller, e) {
33850 const stream = controller._controlledReadableStream;
33851 if (stream._state !== 'readable') {
33852 return;
33853 }
33854 ResetQueue(controller);
33855 ReadableStreamDefaultControllerClearAlgorithms(controller);
33856 ReadableStreamError(stream, e);
33857}
33858function ReadableStreamDefaultControllerGetDesiredSize(controller) {
33859 const state = controller._controlledReadableStream._state;
33860 if (state === 'errored') {
33861 return null;
33862 }
33863 if (state === 'closed') {
33864 return 0;
33865 }
33866 return controller._strategyHWM - controller._queueTotalSize;
33867}
33868// This is used in the implementation of TransformStream.
33869function ReadableStreamDefaultControllerHasBackpressure(controller) {
33870 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
33871 return false;
33872 }
33873 return true;
33874}
33875function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
33876 const state = controller._controlledReadableStream._state;
33877 if (!controller._closeRequested && state === 'readable') {
33878 return true;
33879 }
33880 return false;
33881}
33882function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
33883 controller._controlledReadableStream = stream;
33884 controller._queue = undefined;
33885 controller._queueTotalSize = undefined;
33886 ResetQueue(controller);
33887 controller._started = false;
33888 controller._closeRequested = false;
33889 controller._pullAgain = false;
33890 controller._pulling = false;
33891 controller._strategySizeAlgorithm = sizeAlgorithm;
33892 controller._strategyHWM = highWaterMark;
33893 controller._pullAlgorithm = pullAlgorithm;
33894 controller._cancelAlgorithm = cancelAlgorithm;
33895 stream._readableStreamController = controller;
33896 const startResult = startAlgorithm();
33897 uponPromise(promiseResolvedWith(startResult), () => {
33898 controller._started = true;
33899 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33900 }, r => {
33901 ReadableStreamDefaultControllerError(controller, r);
33902 });
33903}
33904function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
33905 const controller = Object.create(ReadableStreamDefaultController.prototype);
33906 let startAlgorithm = () => undefined;
33907 let pullAlgorithm = () => promiseResolvedWith(undefined);
33908 let cancelAlgorithm = () => promiseResolvedWith(undefined);
33909 if (underlyingSource.start !== undefined) {
33910 startAlgorithm = () => underlyingSource.start(controller);
33911 }
33912 if (underlyingSource.pull !== undefined) {
33913 pullAlgorithm = () => underlyingSource.pull(controller);
33914 }
33915 if (underlyingSource.cancel !== undefined) {
33916 cancelAlgorithm = reason => underlyingSource.cancel(reason);
33917 }
33918 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
33919}
33920// Helper functions for the ReadableStreamDefaultController.
33921function defaultControllerBrandCheckException$1(name) {
33922 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
33923}
33924
33925function ReadableStreamTee(stream, cloneForBranch2) {
33926 const reader = AcquireReadableStreamDefaultReader(stream);
33927 let reading = false;
33928 let canceled1 = false;
33929 let canceled2 = false;
33930 let reason1;
33931 let reason2;
33932 let branch1;
33933 let branch2;
33934 let resolveCancelPromise;
33935 const cancelPromise = newPromise(resolve => {
33936 resolveCancelPromise = resolve;
33937 });
33938 function pullAlgorithm() {
33939 if (reading) {
33940 return promiseResolvedWith(undefined);
33941 }
33942 reading = true;
33943 const readRequest = {
33944 _chunkSteps: value => {
33945 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
33946 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
33947 // successful synchronously-available reads get ahead of asynchronously-available errors.
33948 queueMicrotask(() => {
33949 reading = false;
33950 const value1 = value;
33951 const value2 = value;
33952 // There is no way to access the cloning code right now in the reference implementation.
33953 // If we add one then we'll need an implementation for serializable objects.
33954 // if (!canceled2 && cloneForBranch2) {
33955 // value2 = StructuredDeserialize(StructuredSerialize(value2));
33956 // }
33957 if (!canceled1) {
33958 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
33959 }
33960 if (!canceled2) {
33961 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
33962 }
33963 });
33964 },
33965 _closeSteps: () => {
33966 reading = false;
33967 if (!canceled1) {
33968 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
33969 }
33970 if (!canceled2) {
33971 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
33972 }
33973 if (!canceled1 || !canceled2) {
33974 resolveCancelPromise(undefined);
33975 }
33976 },
33977 _errorSteps: () => {
33978 reading = false;
33979 }
33980 };
33981 ReadableStreamDefaultReaderRead(reader, readRequest);
33982 return promiseResolvedWith(undefined);
33983 }
33984 function cancel1Algorithm(reason) {
33985 canceled1 = true;
33986 reason1 = reason;
33987 if (canceled2) {
33988 const compositeReason = CreateArrayFromList([reason1, reason2]);
33989 const cancelResult = ReadableStreamCancel(stream, compositeReason);
33990 resolveCancelPromise(cancelResult);
33991 }
33992 return cancelPromise;
33993 }
33994 function cancel2Algorithm(reason) {
33995 canceled2 = true;
33996 reason2 = reason;
33997 if (canceled1) {
33998 const compositeReason = CreateArrayFromList([reason1, reason2]);
33999 const cancelResult = ReadableStreamCancel(stream, compositeReason);
34000 resolveCancelPromise(cancelResult);
34001 }
34002 return cancelPromise;
34003 }
34004 function startAlgorithm() {
34005 // do nothing
34006 }
34007 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
34008 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
34009 uponRejection(reader._closedPromise, (r) => {
34010 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
34011 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
34012 if (!canceled1 || !canceled2) {
34013 resolveCancelPromise(undefined);
34014 }
34015 });
34016 return [branch1, branch2];
34017}
34018
34019function convertUnderlyingDefaultOrByteSource(source, context) {
34020 assertDictionary(source, context);
34021 const original = source;
34022 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
34023 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
34024 const pull = original === null || original === void 0 ? void 0 : original.pull;
34025 const start = original === null || original === void 0 ? void 0 : original.start;
34026 const type = original === null || original === void 0 ? void 0 : original.type;
34027 return {
34028 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
34029 undefined :
34030 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
34031 cancel: cancel === undefined ?
34032 undefined :
34033 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
34034 pull: pull === undefined ?
34035 undefined :
34036 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
34037 start: start === undefined ?
34038 undefined :
34039 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
34040 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
34041 };
34042}
34043function convertUnderlyingSourceCancelCallback(fn, original, context) {
34044 assertFunction(fn, context);
34045 return (reason) => promiseCall(fn, original, [reason]);
34046}
34047function convertUnderlyingSourcePullCallback(fn, original, context) {
34048 assertFunction(fn, context);
34049 return (controller) => promiseCall(fn, original, [controller]);
34050}
34051function convertUnderlyingSourceStartCallback(fn, original, context) {
34052 assertFunction(fn, context);
34053 return (controller) => reflectCall(fn, original, [controller]);
34054}
34055function convertReadableStreamType(type, context) {
34056 type = `${type}`;
34057 if (type !== 'bytes') {
34058 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
34059 }
34060 return type;
34061}
34062
34063function convertReaderOptions(options, context) {
34064 assertDictionary(options, context);
34065 const mode = options === null || options === void 0 ? void 0 : options.mode;
34066 return {
34067 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
34068 };
34069}
34070function convertReadableStreamReaderMode(mode, context) {
34071 mode = `${mode}`;
34072 if (mode !== 'byob') {
34073 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
34074 }
34075 return mode;
34076}
34077
34078function convertIteratorOptions(options, context) {
34079 assertDictionary(options, context);
34080 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34081 return { preventCancel: Boolean(preventCancel) };
34082}
34083
34084function convertPipeOptions(options, context) {
34085 assertDictionary(options, context);
34086 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
34087 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34088 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
34089 const signal = options === null || options === void 0 ? void 0 : options.signal;
34090 if (signal !== undefined) {
34091 assertAbortSignal(signal, `${context} has member 'signal' that`);
34092 }
34093 return {
34094 preventAbort: Boolean(preventAbort),
34095 preventCancel: Boolean(preventCancel),
34096 preventClose: Boolean(preventClose),
34097 signal
34098 };
34099}
34100function assertAbortSignal(signal, context) {
34101 if (!isAbortSignal(signal)) {
34102 throw new TypeError(`${context} is not an AbortSignal.`);
34103 }
34104}
34105
34106function convertReadableWritablePair(pair, context) {
34107 assertDictionary(pair, context);
34108 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
34109 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
34110 assertReadableStream(readable, `${context} has member 'readable' that`);
34111 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
34112 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
34113 assertWritableStream(writable, `${context} has member 'writable' that`);
34114 return { readable, writable };
34115}
34116
34117/**
34118 * A readable stream represents a source of data, from which you can read.
34119 *
34120 * @public
34121 */
34122class ReadableStream$1 {
34123 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
34124 if (rawUnderlyingSource === undefined) {
34125 rawUnderlyingSource = null;
34126 }
34127 else {
34128 assertObject(rawUnderlyingSource, 'First parameter');
34129 }
34130 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
34131 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
34132 InitializeReadableStream(this);
34133 if (underlyingSource.type === 'bytes') {
34134 if (strategy.size !== undefined) {
34135 throw new RangeError('The strategy for a byte stream cannot have a size function');
34136 }
34137 const highWaterMark = ExtractHighWaterMark(strategy, 0);
34138 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
34139 }
34140 else {
34141 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
34142 const highWaterMark = ExtractHighWaterMark(strategy, 1);
34143 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
34144 }
34145 }
34146 /**
34147 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
34148 */
34149 get locked() {
34150 if (!IsReadableStream(this)) {
34151 throw streamBrandCheckException$1('locked');
34152 }
34153 return IsReadableStreamLocked(this);
34154 }
34155 /**
34156 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
34157 *
34158 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
34159 * method, which might or might not use it.
34160 */
34161 cancel(reason = undefined) {
34162 if (!IsReadableStream(this)) {
34163 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
34164 }
34165 if (IsReadableStreamLocked(this)) {
34166 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
34167 }
34168 return ReadableStreamCancel(this, reason);
34169 }
34170 getReader(rawOptions = undefined) {
34171 if (!IsReadableStream(this)) {
34172 throw streamBrandCheckException$1('getReader');
34173 }
34174 const options = convertReaderOptions(rawOptions, 'First parameter');
34175 if (options.mode === undefined) {
34176 return AcquireReadableStreamDefaultReader(this);
34177 }
34178 return AcquireReadableStreamBYOBReader(this);
34179 }
34180 pipeThrough(rawTransform, rawOptions = {}) {
34181 if (!IsReadableStream(this)) {
34182 throw streamBrandCheckException$1('pipeThrough');
34183 }
34184 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
34185 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
34186 const options = convertPipeOptions(rawOptions, 'Second parameter');
34187 if (IsReadableStreamLocked(this)) {
34188 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
34189 }
34190 if (IsWritableStreamLocked(transform.writable)) {
34191 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
34192 }
34193 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34194 setPromiseIsHandledToTrue(promise);
34195 return transform.readable;
34196 }
34197 pipeTo(destination, rawOptions = {}) {
34198 if (!IsReadableStream(this)) {
34199 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
34200 }
34201 if (destination === undefined) {
34202 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
34203 }
34204 if (!IsWritableStream(destination)) {
34205 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
34206 }
34207 let options;
34208 try {
34209 options = convertPipeOptions(rawOptions, 'Second parameter');
34210 }
34211 catch (e) {
34212 return promiseRejectedWith(e);
34213 }
34214 if (IsReadableStreamLocked(this)) {
34215 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
34216 }
34217 if (IsWritableStreamLocked(destination)) {
34218 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
34219 }
34220 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34221 }
34222 /**
34223 * Tees this readable stream, returning a two-element array containing the two resulting branches as
34224 * new {@link ReadableStream} instances.
34225 *
34226 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
34227 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
34228 * propagated to the stream's underlying source.
34229 *
34230 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
34231 * this could allow interference between the two branches.
34232 */
34233 tee() {
34234 if (!IsReadableStream(this)) {
34235 throw streamBrandCheckException$1('tee');
34236 }
34237 const branches = ReadableStreamTee(this);
34238 return CreateArrayFromList(branches);
34239 }
34240 values(rawOptions = undefined) {
34241 if (!IsReadableStream(this)) {
34242 throw streamBrandCheckException$1('values');
34243 }
34244 const options = convertIteratorOptions(rawOptions, 'First parameter');
34245 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
34246 }
34247}
34248Object.defineProperties(ReadableStream$1.prototype, {
34249 cancel: { enumerable: true },
34250 getReader: { enumerable: true },
34251 pipeThrough: { enumerable: true },
34252 pipeTo: { enumerable: true },
34253 tee: { enumerable: true },
34254 values: { enumerable: true },
34255 locked: { enumerable: true }
34256});
34257if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34258 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, {
34259 value: 'ReadableStream',
34260 configurable: true
34261 });
34262}
34263if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
34264 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, {
34265 value: ReadableStream$1.prototype.values,
34266 writable: true,
34267 configurable: true
34268 });
34269}
34270// Abstract operations for the ReadableStream.
34271// Throws if and only if startAlgorithm throws.
34272function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
34273 const stream = Object.create(ReadableStream$1.prototype);
34274 InitializeReadableStream(stream);
34275 const controller = Object.create(ReadableStreamDefaultController.prototype);
34276 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
34277 return stream;
34278}
34279function InitializeReadableStream(stream) {
34280 stream._state = 'readable';
34281 stream._reader = undefined;
34282 stream._storedError = undefined;
34283 stream._disturbed = false;
34284}
34285function IsReadableStream(x) {
34286 if (!typeIsObject(x)) {
34287 return false;
34288 }
34289 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
34290 return false;
34291 }
34292 return true;
34293}
34294function IsReadableStreamLocked(stream) {
34295 if (stream._reader === undefined) {
34296 return false;
34297 }
34298 return true;
34299}
34300// ReadableStream API exposed for controllers.
34301function ReadableStreamCancel(stream, reason) {
34302 stream._disturbed = true;
34303 if (stream._state === 'closed') {
34304 return promiseResolvedWith(undefined);
34305 }
34306 if (stream._state === 'errored') {
34307 return promiseRejectedWith(stream._storedError);
34308 }
34309 ReadableStreamClose(stream);
34310 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
34311 return transformPromiseWith(sourceCancelPromise, noop);
34312}
34313function ReadableStreamClose(stream) {
34314 stream._state = 'closed';
34315 const reader = stream._reader;
34316 if (reader === undefined) {
34317 return;
34318 }
34319 defaultReaderClosedPromiseResolve(reader);
34320 if (IsReadableStreamDefaultReader(reader)) {
34321 reader._readRequests.forEach(readRequest => {
34322 readRequest._closeSteps();
34323 });
34324 reader._readRequests = new SimpleQueue();
34325 }
34326}
34327function ReadableStreamError(stream, e) {
34328 stream._state = 'errored';
34329 stream._storedError = e;
34330 const reader = stream._reader;
34331 if (reader === undefined) {
34332 return;
34333 }
34334 defaultReaderClosedPromiseReject(reader, e);
34335 if (IsReadableStreamDefaultReader(reader)) {
34336 reader._readRequests.forEach(readRequest => {
34337 readRequest._errorSteps(e);
34338 });
34339 reader._readRequests = new SimpleQueue();
34340 }
34341 else {
34342 reader._readIntoRequests.forEach(readIntoRequest => {
34343 readIntoRequest._errorSteps(e);
34344 });
34345 reader._readIntoRequests = new SimpleQueue();
34346 }
34347}
34348// Helper functions for the ReadableStream.
34349function streamBrandCheckException$1(name) {
34350 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
34351}
34352
34353function convertQueuingStrategyInit(init, context) {
34354 assertDictionary(init, context);
34355 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
34356 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
34357 return {
34358 highWaterMark: convertUnrestrictedDouble(highWaterMark)
34359 };
34360}
34361
34362const byteLengthSizeFunction = function size(chunk) {
34363 return chunk.byteLength;
34364};
34365/**
34366 * A queuing strategy that counts the number of bytes in each chunk.
34367 *
34368 * @public
34369 */
34370class ByteLengthQueuingStrategy {
34371 constructor(options) {
34372 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
34373 options = convertQueuingStrategyInit(options, 'First parameter');
34374 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
34375 }
34376 /**
34377 * Returns the high water mark provided to the constructor.
34378 */
34379 get highWaterMark() {
34380 if (!IsByteLengthQueuingStrategy(this)) {
34381 throw byteLengthBrandCheckException('highWaterMark');
34382 }
34383 return this._byteLengthQueuingStrategyHighWaterMark;
34384 }
34385 /**
34386 * Measures the size of `chunk` by returning the value of its `byteLength` property.
34387 */
34388 get size() {
34389 if (!IsByteLengthQueuingStrategy(this)) {
34390 throw byteLengthBrandCheckException('size');
34391 }
34392 return byteLengthSizeFunction;
34393 }
34394}
34395Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
34396 highWaterMark: { enumerable: true },
34397 size: { enumerable: true }
34398});
34399if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34400 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34401 value: 'ByteLengthQueuingStrategy',
34402 configurable: true
34403 });
34404}
34405// Helper functions for the ByteLengthQueuingStrategy.
34406function byteLengthBrandCheckException(name) {
34407 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
34408}
34409function IsByteLengthQueuingStrategy(x) {
34410 if (!typeIsObject(x)) {
34411 return false;
34412 }
34413 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
34414 return false;
34415 }
34416 return true;
34417}
34418
34419const countSizeFunction = function size() {
34420 return 1;
34421};
34422/**
34423 * A queuing strategy that counts the number of chunks.
34424 *
34425 * @public
34426 */
34427class CountQueuingStrategy {
34428 constructor(options) {
34429 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
34430 options = convertQueuingStrategyInit(options, 'First parameter');
34431 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
34432 }
34433 /**
34434 * Returns the high water mark provided to the constructor.
34435 */
34436 get highWaterMark() {
34437 if (!IsCountQueuingStrategy(this)) {
34438 throw countBrandCheckException('highWaterMark');
34439 }
34440 return this._countQueuingStrategyHighWaterMark;
34441 }
34442 /**
34443 * Measures the size of `chunk` by always returning 1.
34444 * This ensures that the total queue size is a count of the number of chunks in the queue.
34445 */
34446 get size() {
34447 if (!IsCountQueuingStrategy(this)) {
34448 throw countBrandCheckException('size');
34449 }
34450 return countSizeFunction;
34451 }
34452}
34453Object.defineProperties(CountQueuingStrategy.prototype, {
34454 highWaterMark: { enumerable: true },
34455 size: { enumerable: true }
34456});
34457if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34458 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34459 value: 'CountQueuingStrategy',
34460 configurable: true
34461 });
34462}
34463// Helper functions for the CountQueuingStrategy.
34464function countBrandCheckException(name) {
34465 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
34466}
34467function IsCountQueuingStrategy(x) {
34468 if (!typeIsObject(x)) {
34469 return false;
34470 }
34471 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
34472 return false;
34473 }
34474 return true;
34475}
34476
34477function convertTransformer(original, context) {
34478 assertDictionary(original, context);
34479 const flush = original === null || original === void 0 ? void 0 : original.flush;
34480 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
34481 const start = original === null || original === void 0 ? void 0 : original.start;
34482 const transform = original === null || original === void 0 ? void 0 : original.transform;
34483 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
34484 return {
34485 flush: flush === undefined ?
34486 undefined :
34487 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
34488 readableType,
34489 start: start === undefined ?
34490 undefined :
34491 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
34492 transform: transform === undefined ?
34493 undefined :
34494 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
34495 writableType
34496 };
34497}
34498function convertTransformerFlushCallback(fn, original, context) {
34499 assertFunction(fn, context);
34500 return (controller) => promiseCall(fn, original, [controller]);
34501}
34502function convertTransformerStartCallback(fn, original, context) {
34503 assertFunction(fn, context);
34504 return (controller) => reflectCall(fn, original, [controller]);
34505}
34506function convertTransformerTransformCallback(fn, original, context) {
34507 assertFunction(fn, context);
34508 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
34509}
34510
34511// Class TransformStream
34512/**
34513 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
34514 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
34515 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
34516 * made available for reading from the readable side.
34517 *
34518 * @public
34519 */
34520class TransformStream$1 {
34521 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
34522 if (rawTransformer === undefined) {
34523 rawTransformer = null;
34524 }
34525 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
34526 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
34527 const transformer = convertTransformer(rawTransformer, 'First parameter');
34528 if (transformer.readableType !== undefined) {
34529 throw new RangeError('Invalid readableType specified');
34530 }
34531 if (transformer.writableType !== undefined) {
34532 throw new RangeError('Invalid writableType specified');
34533 }
34534 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
34535 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
34536 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
34537 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
34538 let startPromise_resolve;
34539 const startPromise = newPromise(resolve => {
34540 startPromise_resolve = resolve;
34541 });
34542 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34543 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
34544 if (transformer.start !== undefined) {
34545 startPromise_resolve(transformer.start(this._transformStreamController));
34546 }
34547 else {
34548 startPromise_resolve(undefined);
34549 }
34550 }
34551 /**
34552 * The readable side of the transform stream.
34553 */
34554 get readable() {
34555 if (!IsTransformStream(this)) {
34556 throw streamBrandCheckException('readable');
34557 }
34558 return this._readable;
34559 }
34560 /**
34561 * The writable side of the transform stream.
34562 */
34563 get writable() {
34564 if (!IsTransformStream(this)) {
34565 throw streamBrandCheckException('writable');
34566 }
34567 return this._writable;
34568 }
34569}
34570Object.defineProperties(TransformStream$1.prototype, {
34571 readable: { enumerable: true },
34572 writable: { enumerable: true }
34573});
34574if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34575 Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, {
34576 value: 'TransformStream',
34577 configurable: true
34578 });
34579}
34580function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
34581 function startAlgorithm() {
34582 return startPromise;
34583 }
34584 function writeAlgorithm(chunk) {
34585 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
34586 }
34587 function abortAlgorithm(reason) {
34588 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
34589 }
34590 function closeAlgorithm() {
34591 return TransformStreamDefaultSinkCloseAlgorithm(stream);
34592 }
34593 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
34594 function pullAlgorithm() {
34595 return TransformStreamDefaultSourcePullAlgorithm(stream);
34596 }
34597 function cancelAlgorithm(reason) {
34598 TransformStreamErrorWritableAndUnblockWrite(stream, reason);
34599 return promiseResolvedWith(undefined);
34600 }
34601 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34602 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
34603 stream._backpressure = undefined;
34604 stream._backpressureChangePromise = undefined;
34605 stream._backpressureChangePromise_resolve = undefined;
34606 TransformStreamSetBackpressure(stream, true);
34607 stream._transformStreamController = undefined;
34608}
34609function IsTransformStream(x) {
34610 if (!typeIsObject(x)) {
34611 return false;
34612 }
34613 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
34614 return false;
34615 }
34616 return true;
34617}
34618// This is a no-op if both sides are already errored.
34619function TransformStreamError(stream, e) {
34620 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
34621 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34622}
34623function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
34624 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
34625 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
34626 if (stream._backpressure) {
34627 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
34628 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
34629 // _backpressure is set.
34630 TransformStreamSetBackpressure(stream, false);
34631 }
34632}
34633function TransformStreamSetBackpressure(stream, backpressure) {
34634 // Passes also when called during construction.
34635 if (stream._backpressureChangePromise !== undefined) {
34636 stream._backpressureChangePromise_resolve();
34637 }
34638 stream._backpressureChangePromise = newPromise(resolve => {
34639 stream._backpressureChangePromise_resolve = resolve;
34640 });
34641 stream._backpressure = backpressure;
34642}
34643// Class TransformStreamDefaultController
34644/**
34645 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
34646 *
34647 * @public
34648 */
34649class TransformStreamDefaultController {
34650 constructor() {
34651 throw new TypeError('Illegal constructor');
34652 }
34653 /**
34654 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
34655 */
34656 get desiredSize() {
34657 if (!IsTransformStreamDefaultController(this)) {
34658 throw defaultControllerBrandCheckException('desiredSize');
34659 }
34660 const readableController = this._controlledTransformStream._readable._readableStreamController;
34661 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
34662 }
34663 enqueue(chunk = undefined) {
34664 if (!IsTransformStreamDefaultController(this)) {
34665 throw defaultControllerBrandCheckException('enqueue');
34666 }
34667 TransformStreamDefaultControllerEnqueue(this, chunk);
34668 }
34669 /**
34670 * Errors both the readable side and the writable side of the controlled transform stream, making all future
34671 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
34672 */
34673 error(reason = undefined) {
34674 if (!IsTransformStreamDefaultController(this)) {
34675 throw defaultControllerBrandCheckException('error');
34676 }
34677 TransformStreamDefaultControllerError(this, reason);
34678 }
34679 /**
34680 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
34681 * transformer only needs to consume a portion of the chunks written to the writable side.
34682 */
34683 terminate() {
34684 if (!IsTransformStreamDefaultController(this)) {
34685 throw defaultControllerBrandCheckException('terminate');
34686 }
34687 TransformStreamDefaultControllerTerminate(this);
34688 }
34689}
34690Object.defineProperties(TransformStreamDefaultController.prototype, {
34691 enqueue: { enumerable: true },
34692 error: { enumerable: true },
34693 terminate: { enumerable: true },
34694 desiredSize: { enumerable: true }
34695});
34696if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34697 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
34698 value: 'TransformStreamDefaultController',
34699 configurable: true
34700 });
34701}
34702// Transform Stream Default Controller Abstract Operations
34703function IsTransformStreamDefaultController(x) {
34704 if (!typeIsObject(x)) {
34705 return false;
34706 }
34707 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
34708 return false;
34709 }
34710 return true;
34711}
34712function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
34713 controller._controlledTransformStream = stream;
34714 stream._transformStreamController = controller;
34715 controller._transformAlgorithm = transformAlgorithm;
34716 controller._flushAlgorithm = flushAlgorithm;
34717}
34718function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
34719 const controller = Object.create(TransformStreamDefaultController.prototype);
34720 let transformAlgorithm = (chunk) => {
34721 try {
34722 TransformStreamDefaultControllerEnqueue(controller, chunk);
34723 return promiseResolvedWith(undefined);
34724 }
34725 catch (transformResultE) {
34726 return promiseRejectedWith(transformResultE);
34727 }
34728 };
34729 let flushAlgorithm = () => promiseResolvedWith(undefined);
34730 if (transformer.transform !== undefined) {
34731 transformAlgorithm = chunk => transformer.transform(chunk, controller);
34732 }
34733 if (transformer.flush !== undefined) {
34734 flushAlgorithm = () => transformer.flush(controller);
34735 }
34736 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
34737}
34738function TransformStreamDefaultControllerClearAlgorithms(controller) {
34739 controller._transformAlgorithm = undefined;
34740 controller._flushAlgorithm = undefined;
34741}
34742function TransformStreamDefaultControllerEnqueue(controller, chunk) {
34743 const stream = controller._controlledTransformStream;
34744 const readableController = stream._readable._readableStreamController;
34745 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
34746 throw new TypeError('Readable side is not in a state that permits enqueue');
34747 }
34748 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
34749 // accept TransformStreamDefaultControllerEnqueue() calls.
34750 try {
34751 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
34752 }
34753 catch (e) {
34754 // This happens when readableStrategy.size() throws.
34755 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34756 throw stream._readable._storedError;
34757 }
34758 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
34759 if (backpressure !== stream._backpressure) {
34760 TransformStreamSetBackpressure(stream, true);
34761 }
34762}
34763function TransformStreamDefaultControllerError(controller, e) {
34764 TransformStreamError(controller._controlledTransformStream, e);
34765}
34766function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
34767 const transformPromise = controller._transformAlgorithm(chunk);
34768 return transformPromiseWith(transformPromise, undefined, r => {
34769 TransformStreamError(controller._controlledTransformStream, r);
34770 throw r;
34771 });
34772}
34773function TransformStreamDefaultControllerTerminate(controller) {
34774 const stream = controller._controlledTransformStream;
34775 const readableController = stream._readable._readableStreamController;
34776 ReadableStreamDefaultControllerClose(readableController);
34777 const error = new TypeError('TransformStream terminated');
34778 TransformStreamErrorWritableAndUnblockWrite(stream, error);
34779}
34780// TransformStreamDefaultSink Algorithms
34781function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
34782 const controller = stream._transformStreamController;
34783 if (stream._backpressure) {
34784 const backpressureChangePromise = stream._backpressureChangePromise;
34785 return transformPromiseWith(backpressureChangePromise, () => {
34786 const writable = stream._writable;
34787 const state = writable._state;
34788 if (state === 'erroring') {
34789 throw writable._storedError;
34790 }
34791 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34792 });
34793 }
34794 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34795}
34796function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
34797 // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
34798 // errored.
34799 TransformStreamError(stream, reason);
34800 return promiseResolvedWith(undefined);
34801}
34802function TransformStreamDefaultSinkCloseAlgorithm(stream) {
34803 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
34804 const readable = stream._readable;
34805 const controller = stream._transformStreamController;
34806 const flushPromise = controller._flushAlgorithm();
34807 TransformStreamDefaultControllerClearAlgorithms(controller);
34808 // Return a promise that is fulfilled with undefined on success.
34809 return transformPromiseWith(flushPromise, () => {
34810 if (readable._state === 'errored') {
34811 throw readable._storedError;
34812 }
34813 ReadableStreamDefaultControllerClose(readable._readableStreamController);
34814 }, r => {
34815 TransformStreamError(stream, r);
34816 throw readable._storedError;
34817 });
34818}
34819// TransformStreamDefaultSource Algorithms
34820function TransformStreamDefaultSourcePullAlgorithm(stream) {
34821 // Invariant. Enforced by the promises returned by start() and pull().
34822 TransformStreamSetBackpressure(stream, false);
34823 // Prevent the next pull() call until there is backpressure.
34824 return stream._backpressureChangePromise;
34825}
34826// Helper functions for the TransformStreamDefaultController.
34827function defaultControllerBrandCheckException(name) {
34828 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
34829}
34830// Helper functions for the TransformStream.
34831function streamBrandCheckException(name) {
34832 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
34833}
34834
34835var ponyfill_es6 = /*#__PURE__*/Object.freeze({
34836 __proto__: null,
34837 ByteLengthQueuingStrategy: ByteLengthQueuingStrategy,
34838 CountQueuingStrategy: CountQueuingStrategy,
34839 ReadableByteStreamController: ReadableByteStreamController,
34840 ReadableStream: ReadableStream$1,
34841 ReadableStreamBYOBReader: ReadableStreamBYOBReader,
34842 ReadableStreamBYOBRequest: ReadableStreamBYOBRequest,
34843 ReadableStreamDefaultController: ReadableStreamDefaultController,
34844 ReadableStreamDefaultReader: ReadableStreamDefaultReader,
34845 TransformStream: TransformStream$1,
34846 TransformStreamDefaultController: TransformStreamDefaultController,
34847 WritableStream: WritableStream$1,
34848 WritableStreamDefaultController: WritableStreamDefaultController,
34849 WritableStreamDefaultWriter: WritableStreamDefaultWriter
34850});
34851
34852/*! *****************************************************************************
34853Copyright (c) Microsoft Corporation.
34854
34855Permission to use, copy, modify, and/or distribute this software for any
34856purpose with or without fee is hereby granted.
34857
34858THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
34859REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
34860AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
34861INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
34862LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34863OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
34864PERFORMANCE OF THIS SOFTWARE.
34865***************************************************************************** */
34866/* global Reflect, Promise */
34867
34868var extendStatics = function(d, b) {
34869 extendStatics = Object.setPrototypeOf ||
34870 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34871 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
34872 return extendStatics(d, b);
34873};
34874
34875function __extends(d, b) {
34876 if (typeof b !== "function" && b !== null)
34877 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
34878 extendStatics(d, b);
34879 function __() { this.constructor = d; }
34880 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34881}
34882
34883function assert$1(test) {
34884 if (!test) {
34885 throw new TypeError('Assertion failed');
34886 }
34887}
34888
34889function noop$1() {
34890 return;
34891}
34892function typeIsObject$1(x) {
34893 return (typeof x === 'object' && x !== null) || typeof x === 'function';
34894}
34895
34896function isStreamConstructor(ctor) {
34897 if (typeof ctor !== 'function') {
34898 return false;
34899 }
34900 var startCalled = false;
34901 try {
34902 new ctor({
34903 start: function () {
34904 startCalled = true;
34905 }
34906 });
34907 }
34908 catch (e) {
34909 // ignore
34910 }
34911 return startCalled;
34912}
34913function isReadableStream(readable) {
34914 if (!typeIsObject$1(readable)) {
34915 return false;
34916 }
34917 if (typeof readable.getReader !== 'function') {
34918 return false;
34919 }
34920 return true;
34921}
34922function isReadableStreamConstructor(ctor) {
34923 if (!isStreamConstructor(ctor)) {
34924 return false;
34925 }
34926 if (!isReadableStream(new ctor())) {
34927 return false;
34928 }
34929 return true;
34930}
34931function isWritableStream(writable) {
34932 if (!typeIsObject$1(writable)) {
34933 return false;
34934 }
34935 if (typeof writable.getWriter !== 'function') {
34936 return false;
34937 }
34938 return true;
34939}
34940function isWritableStreamConstructor(ctor) {
34941 if (!isStreamConstructor(ctor)) {
34942 return false;
34943 }
34944 if (!isWritableStream(new ctor())) {
34945 return false;
34946 }
34947 return true;
34948}
34949function isTransformStream(transform) {
34950 if (!typeIsObject$1(transform)) {
34951 return false;
34952 }
34953 if (!isReadableStream(transform.readable)) {
34954 return false;
34955 }
34956 if (!isWritableStream(transform.writable)) {
34957 return false;
34958 }
34959 return true;
34960}
34961function isTransformStreamConstructor(ctor) {
34962 if (!isStreamConstructor(ctor)) {
34963 return false;
34964 }
34965 if (!isTransformStream(new ctor())) {
34966 return false;
34967 }
34968 return true;
34969}
34970function supportsByobReader(readable) {
34971 try {
34972 var reader = readable.getReader({ mode: 'byob' });
34973 reader.releaseLock();
34974 return true;
34975 }
34976 catch (_a) {
34977 return false;
34978 }
34979}
34980function supportsByteSource(ctor) {
34981 try {
34982 new ctor({ type: 'bytes' });
34983 return true;
34984 }
34985 catch (_a) {
34986 return false;
34987 }
34988}
34989
34990function createReadableStreamWrapper(ctor) {
34991 assert$1(isReadableStreamConstructor(ctor));
34992 var byteSourceSupported = supportsByteSource(ctor);
34993 return function (readable, _a) {
34994 var _b = _a === void 0 ? {} : _a, type = _b.type;
34995 type = parseReadableType(type);
34996 if (type === 'bytes' && !byteSourceSupported) {
34997 type = undefined;
34998 }
34999 if (readable.constructor === ctor) {
35000 if (type !== 'bytes' || supportsByobReader(readable)) {
35001 return readable;
35002 }
35003 }
35004 if (type === 'bytes') {
35005 var source = createWrappingReadableSource(readable, { type: type });
35006 return new ctor(source);
35007 }
35008 else {
35009 var source = createWrappingReadableSource(readable);
35010 return new ctor(source);
35011 }
35012 };
35013}
35014function createWrappingReadableSource(readable, _a) {
35015 var _b = _a === void 0 ? {} : _a, type = _b.type;
35016 assert$1(isReadableStream(readable));
35017 assert$1(readable.locked === false);
35018 type = parseReadableType(type);
35019 var source;
35020 if (type === 'bytes') {
35021 source = new WrappingReadableByteStreamSource(readable);
35022 }
35023 else {
35024 source = new WrappingReadableStreamDefaultSource(readable);
35025 }
35026 return source;
35027}
35028function parseReadableType(type) {
35029 var typeString = String(type);
35030 if (typeString === 'bytes') {
35031 return typeString;
35032 }
35033 else if (type === undefined) {
35034 return type;
35035 }
35036 else {
35037 throw new RangeError('Invalid type is specified');
35038 }
35039}
35040var AbstractWrappingReadableStreamSource = /** @class */ (function () {
35041 function AbstractWrappingReadableStreamSource(underlyingStream) {
35042 this._underlyingReader = undefined;
35043 this._readerMode = undefined;
35044 this._readableStreamController = undefined;
35045 this._pendingRead = undefined;
35046 this._underlyingStream = underlyingStream;
35047 // always keep a reader attached to detect close/error
35048 this._attachDefaultReader();
35049 }
35050 AbstractWrappingReadableStreamSource.prototype.start = function (controller) {
35051 this._readableStreamController = controller;
35052 };
35053 AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {
35054 assert$1(this._underlyingReader !== undefined);
35055 return this._underlyingReader.cancel(reason);
35056 };
35057 AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {
35058 if (this._readerMode === "default" /* DEFAULT */) {
35059 return;
35060 }
35061 this._detachReader();
35062 var reader = this._underlyingStream.getReader();
35063 this._readerMode = "default" /* DEFAULT */;
35064 this._attachReader(reader);
35065 };
35066 AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {
35067 var _this = this;
35068 assert$1(this._underlyingReader === undefined);
35069 this._underlyingReader = reader;
35070 var closed = this._underlyingReader.closed;
35071 if (!closed) {
35072 return;
35073 }
35074 closed
35075 .then(function () { return _this._finishPendingRead(); })
35076 .then(function () {
35077 if (reader === _this._underlyingReader) {
35078 _this._readableStreamController.close();
35079 }
35080 }, function (reason) {
35081 if (reader === _this._underlyingReader) {
35082 _this._readableStreamController.error(reason);
35083 }
35084 })
35085 .catch(noop$1);
35086 };
35087 AbstractWrappingReadableStreamSource.prototype._detachReader = function () {
35088 if (this._underlyingReader === undefined) {
35089 return;
35090 }
35091 this._underlyingReader.releaseLock();
35092 this._underlyingReader = undefined;
35093 this._readerMode = undefined;
35094 };
35095 AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {
35096 var _this = this;
35097 this._attachDefaultReader();
35098 // TODO Backpressure?
35099 var read = this._underlyingReader.read()
35100 .then(function (result) {
35101 var controller = _this._readableStreamController;
35102 if (result.done) {
35103 _this._tryClose();
35104 }
35105 else {
35106 controller.enqueue(result.value);
35107 }
35108 });
35109 this._setPendingRead(read);
35110 return read;
35111 };
35112 AbstractWrappingReadableStreamSource.prototype._tryClose = function () {
35113 try {
35114 this._readableStreamController.close();
35115 }
35116 catch (_a) {
35117 // already errored or closed
35118 }
35119 };
35120 AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {
35121 var _this = this;
35122 var pendingRead;
35123 var finishRead = function () {
35124 if (_this._pendingRead === pendingRead) {
35125 _this._pendingRead = undefined;
35126 }
35127 };
35128 this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);
35129 };
35130 AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {
35131 var _this = this;
35132 if (!this._pendingRead) {
35133 return undefined;
35134 }
35135 var afterRead = function () { return _this._finishPendingRead(); };
35136 return this._pendingRead.then(afterRead, afterRead);
35137 };
35138 return AbstractWrappingReadableStreamSource;
35139}());
35140var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {
35141 __extends(WrappingReadableStreamDefaultSource, _super);
35142 function WrappingReadableStreamDefaultSource() {
35143 return _super !== null && _super.apply(this, arguments) || this;
35144 }
35145 WrappingReadableStreamDefaultSource.prototype.pull = function () {
35146 return this._pullWithDefaultReader();
35147 };
35148 return WrappingReadableStreamDefaultSource;
35149}(AbstractWrappingReadableStreamSource));
35150function toUint8Array(view) {
35151 return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
35152}
35153function copyArrayBufferView(from, to) {
35154 var fromArray = toUint8Array(from);
35155 var toArray = toUint8Array(to);
35156 toArray.set(fromArray, 0);
35157}
35158var WrappingReadableByteStreamSource = /** @class */ (function (_super) {
35159 __extends(WrappingReadableByteStreamSource, _super);
35160 function WrappingReadableByteStreamSource(underlyingStream) {
35161 var _this = this;
35162 var supportsByob = supportsByobReader(underlyingStream);
35163 _this = _super.call(this, underlyingStream) || this;
35164 _this._supportsByob = supportsByob;
35165 return _this;
35166 }
35167 Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", {
35168 get: function () {
35169 return 'bytes';
35170 },
35171 enumerable: false,
35172 configurable: true
35173 });
35174 WrappingReadableByteStreamSource.prototype._attachByobReader = function () {
35175 if (this._readerMode === "byob" /* BYOB */) {
35176 return;
35177 }
35178 assert$1(this._supportsByob);
35179 this._detachReader();
35180 var reader = this._underlyingStream.getReader({ mode: 'byob' });
35181 this._readerMode = "byob" /* BYOB */;
35182 this._attachReader(reader);
35183 };
35184 WrappingReadableByteStreamSource.prototype.pull = function () {
35185 if (this._supportsByob) {
35186 var byobRequest = this._readableStreamController.byobRequest;
35187 if (byobRequest) {
35188 return this._pullWithByobRequest(byobRequest);
35189 }
35190 }
35191 return this._pullWithDefaultReader();
35192 };
35193 WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {
35194 var _this = this;
35195 this._attachByobReader();
35196 // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly
35197 // create a separate buffer to read into, then copy that to byobRequest.view
35198 var buffer = new Uint8Array(byobRequest.view.byteLength);
35199 // TODO Backpressure?
35200 var read = this._underlyingReader.read(buffer)
35201 .then(function (result) {
35202 _this._readableStreamController;
35203 if (result.done) {
35204 _this._tryClose();
35205 byobRequest.respond(0);
35206 }
35207 else {
35208 copyArrayBufferView(result.value, byobRequest.view);
35209 byobRequest.respond(result.value.byteLength);
35210 }
35211 });
35212 this._setPendingRead(read);
35213 return read;
35214 };
35215 return WrappingReadableByteStreamSource;
35216}(AbstractWrappingReadableStreamSource));
35217
35218function createWritableStreamWrapper(ctor) {
35219 assert$1(isWritableStreamConstructor(ctor));
35220 return function (writable) {
35221 if (writable.constructor === ctor) {
35222 return writable;
35223 }
35224 var sink = createWrappingWritableSink(writable);
35225 return new ctor(sink);
35226 };
35227}
35228function createWrappingWritableSink(writable) {
35229 assert$1(isWritableStream(writable));
35230 assert$1(writable.locked === false);
35231 var writer = writable.getWriter();
35232 return new WrappingWritableStreamSink(writer);
35233}
35234var WrappingWritableStreamSink = /** @class */ (function () {
35235 function WrappingWritableStreamSink(underlyingWriter) {
35236 var _this = this;
35237 this._writableStreamController = undefined;
35238 this._pendingWrite = undefined;
35239 this._state = "writable" /* WRITABLE */;
35240 this._storedError = undefined;
35241 this._underlyingWriter = underlyingWriter;
35242 this._errorPromise = new Promise(function (resolve, reject) {
35243 _this._errorPromiseReject = reject;
35244 });
35245 this._errorPromise.catch(noop$1);
35246 }
35247 WrappingWritableStreamSink.prototype.start = function (controller) {
35248 var _this = this;
35249 this._writableStreamController = controller;
35250 this._underlyingWriter.closed
35251 .then(function () {
35252 _this._state = "closed" /* CLOSED */;
35253 })
35254 .catch(function (reason) { return _this._finishErroring(reason); });
35255 };
35256 WrappingWritableStreamSink.prototype.write = function (chunk) {
35257 var _this = this;
35258 var writer = this._underlyingWriter;
35259 // Detect past errors
35260 if (writer.desiredSize === null) {
35261 return writer.ready;
35262 }
35263 var writeRequest = writer.write(chunk);
35264 // Detect future errors
35265 writeRequest.catch(function (reason) { return _this._finishErroring(reason); });
35266 writer.ready.catch(function (reason) { return _this._startErroring(reason); });
35267 // Reject write when errored
35268 var write = Promise.race([writeRequest, this._errorPromise]);
35269 this._setPendingWrite(write);
35270 return write;
35271 };
35272 WrappingWritableStreamSink.prototype.close = function () {
35273 var _this = this;
35274 if (this._pendingWrite === undefined) {
35275 return this._underlyingWriter.close();
35276 }
35277 return this._finishPendingWrite().then(function () { return _this.close(); });
35278 };
35279 WrappingWritableStreamSink.prototype.abort = function (reason) {
35280 if (this._state === "errored" /* ERRORED */) {
35281 return undefined;
35282 }
35283 var writer = this._underlyingWriter;
35284 return writer.abort(reason);
35285 };
35286 WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {
35287 var _this = this;
35288 var pendingWrite;
35289 var finishWrite = function () {
35290 if (_this._pendingWrite === pendingWrite) {
35291 _this._pendingWrite = undefined;
35292 }
35293 };
35294 this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);
35295 };
35296 WrappingWritableStreamSink.prototype._finishPendingWrite = function () {
35297 var _this = this;
35298 if (this._pendingWrite === undefined) {
35299 return Promise.resolve();
35300 }
35301 var afterWrite = function () { return _this._finishPendingWrite(); };
35302 return this._pendingWrite.then(afterWrite, afterWrite);
35303 };
35304 WrappingWritableStreamSink.prototype._startErroring = function (reason) {
35305 var _this = this;
35306 if (this._state === "writable" /* WRITABLE */) {
35307 this._state = "erroring" /* ERRORING */;
35308 this._storedError = reason;
35309 var afterWrite = function () { return _this._finishErroring(reason); };
35310 if (this._pendingWrite === undefined) {
35311 afterWrite();
35312 }
35313 else {
35314 this._finishPendingWrite().then(afterWrite, afterWrite);
35315 }
35316 this._writableStreamController.error(reason);
35317 }
35318 };
35319 WrappingWritableStreamSink.prototype._finishErroring = function (reason) {
35320 if (this._state === "writable" /* WRITABLE */) {
35321 this._startErroring(reason);
35322 }
35323 if (this._state === "erroring" /* ERRORING */) {
35324 this._state = "errored" /* ERRORED */;
35325 this._errorPromiseReject(this._storedError);
35326 }
35327 };
35328 return WrappingWritableStreamSink;
35329}());
35330
35331function createTransformStreamWrapper(ctor) {
35332 assert$1(isTransformStreamConstructor(ctor));
35333 return function (transform) {
35334 if (transform.constructor === ctor) {
35335 return transform;
35336 }
35337 var transformer = createWrappingTransformer(transform);
35338 return new ctor(transformer);
35339 };
35340}
35341function createWrappingTransformer(transform) {
35342 assert$1(isTransformStream(transform));
35343 var readable = transform.readable, writable = transform.writable;
35344 assert$1(readable.locked === false);
35345 assert$1(writable.locked === false);
35346 var reader = readable.getReader();
35347 var writer;
35348 try {
35349 writer = writable.getWriter();
35350 }
35351 catch (e) {
35352 reader.releaseLock(); // do not leak reader
35353 throw e;
35354 }
35355 return new WrappingTransformStreamTransformer(reader, writer);
35356}
35357var WrappingTransformStreamTransformer = /** @class */ (function () {
35358 function WrappingTransformStreamTransformer(reader, writer) {
35359 var _this = this;
35360 this._transformStreamController = undefined;
35361 this._onRead = function (result) {
35362 if (result.done) {
35363 return;
35364 }
35365 _this._transformStreamController.enqueue(result.value);
35366 return _this._reader.read().then(_this._onRead);
35367 };
35368 this._onError = function (reason) {
35369 _this._flushReject(reason);
35370 _this._transformStreamController.error(reason);
35371 _this._reader.cancel(reason).catch(noop$1);
35372 _this._writer.abort(reason).catch(noop$1);
35373 };
35374 this._onTerminate = function () {
35375 _this._flushResolve();
35376 _this._transformStreamController.terminate();
35377 var error = new TypeError('TransformStream terminated');
35378 _this._writer.abort(error).catch(noop$1);
35379 };
35380 this._reader = reader;
35381 this._writer = writer;
35382 this._flushPromise = new Promise(function (resolve, reject) {
35383 _this._flushResolve = resolve;
35384 _this._flushReject = reject;
35385 });
35386 }
35387 WrappingTransformStreamTransformer.prototype.start = function (controller) {
35388 this._transformStreamController = controller;
35389 this._reader.read()
35390 .then(this._onRead)
35391 .then(this._onTerminate, this._onError);
35392 var readerClosed = this._reader.closed;
35393 if (readerClosed) {
35394 readerClosed
35395 .then(this._onTerminate, this._onError);
35396 }
35397 };
35398 WrappingTransformStreamTransformer.prototype.transform = function (chunk) {
35399 return this._writer.write(chunk);
35400 };
35401 WrappingTransformStreamTransformer.prototype.flush = function () {
35402 var _this = this;
35403 return this._writer.close()
35404 .then(function () { return _this._flushPromise; });
35405 };
35406 return WrappingTransformStreamTransformer;
35407}());
35408
35409var webStreamsAdapter = /*#__PURE__*/Object.freeze({
35410 __proto__: null,
35411 createReadableStreamWrapper: createReadableStreamWrapper,
35412 createTransformStreamWrapper: createTransformStreamWrapper,
35413 createWrappingReadableSource: createWrappingReadableSource,
35414 createWrappingTransformer: createWrappingTransformer,
35415 createWrappingWritableSink: createWrappingWritableSink,
35416 createWritableStreamWrapper: createWritableStreamWrapper
35417});
35418
35419var bn = createCommonjsModule(function (module) {
35420(function (module, exports) {
35421
35422 // Utils
35423 function assert (val, msg) {
35424 if (!val) throw new Error(msg || 'Assertion failed');
35425 }
35426
35427 // Could use `inherits` module, but don't want to move from single file
35428 // architecture yet.
35429 function inherits (ctor, superCtor) {
35430 ctor.super_ = superCtor;
35431 var TempCtor = function () {};
35432 TempCtor.prototype = superCtor.prototype;
35433 ctor.prototype = new TempCtor();
35434 ctor.prototype.constructor = ctor;
35435 }
35436
35437 // BN
35438
35439 function BN (number, base, endian) {
35440 if (BN.isBN(number)) {
35441 return number;
35442 }
35443
35444 this.negative = 0;
35445 this.words = null;
35446 this.length = 0;
35447
35448 // Reduction context
35449 this.red = null;
35450
35451 if (number !== null) {
35452 if (base === 'le' || base === 'be') {
35453 endian = base;
35454 base = 10;
35455 }
35456
35457 this._init(number || 0, base || 10, endian || 'be');
35458 }
35459 }
35460 if (typeof module === 'object') {
35461 module.exports = BN;
35462 } else {
35463 exports.BN = BN;
35464 }
35465
35466 BN.BN = BN;
35467 BN.wordSize = 26;
35468
35469 var Buffer;
35470 try {
35471 Buffer = void('buffer').Buffer;
35472 } catch (e) {
35473 }
35474
35475 BN.isBN = function isBN (num) {
35476 if (num instanceof BN) {
35477 return true;
35478 }
35479
35480 return num !== null && typeof num === 'object' &&
35481 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
35482 };
35483
35484 BN.max = function max (left, right) {
35485 if (left.cmp(right) > 0) return left;
35486 return right;
35487 };
35488
35489 BN.min = function min (left, right) {
35490 if (left.cmp(right) < 0) return left;
35491 return right;
35492 };
35493
35494 BN.prototype._init = function init (number, base, endian) {
35495 if (typeof number === 'number') {
35496 return this._initNumber(number, base, endian);
35497 }
35498
35499 if (typeof number === 'object') {
35500 return this._initArray(number, base, endian);
35501 }
35502
35503 if (base === 'hex') {
35504 base = 16;
35505 }
35506 assert(base === (base | 0) && base >= 2 && base <= 36);
35507
35508 number = number.toString().replace(/\s+/g, '');
35509 var start = 0;
35510 if (number[0] === '-') {
35511 start++;
35512 }
35513
35514 if (base === 16) {
35515 this._parseHex(number, start);
35516 } else {
35517 this._parseBase(number, base, start);
35518 }
35519
35520 if (number[0] === '-') {
35521 this.negative = 1;
35522 }
35523
35524 this.strip();
35525
35526 if (endian !== 'le') return;
35527
35528 this._initArray(this.toArray(), base, endian);
35529 };
35530
35531 BN.prototype._initNumber = function _initNumber (number, base, endian) {
35532 if (number < 0) {
35533 this.negative = 1;
35534 number = -number;
35535 }
35536 if (number < 0x4000000) {
35537 this.words = [ number & 0x3ffffff ];
35538 this.length = 1;
35539 } else if (number < 0x10000000000000) {
35540 this.words = [
35541 number & 0x3ffffff,
35542 (number / 0x4000000) & 0x3ffffff
35543 ];
35544 this.length = 2;
35545 } else {
35546 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
35547 this.words = [
35548 number & 0x3ffffff,
35549 (number / 0x4000000) & 0x3ffffff,
35550 1
35551 ];
35552 this.length = 3;
35553 }
35554
35555 if (endian !== 'le') return;
35556
35557 // Reverse the bytes
35558 this._initArray(this.toArray(), base, endian);
35559 };
35560
35561 BN.prototype._initArray = function _initArray (number, base, endian) {
35562 // Perhaps a Uint8Array
35563 assert(typeof number.length === 'number');
35564 if (number.length <= 0) {
35565 this.words = [ 0 ];
35566 this.length = 1;
35567 return this;
35568 }
35569
35570 this.length = Math.ceil(number.length / 3);
35571 this.words = new Array(this.length);
35572 for (var i = 0; i < this.length; i++) {
35573 this.words[i] = 0;
35574 }
35575
35576 var j, w;
35577 var off = 0;
35578 if (endian === 'be') {
35579 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
35580 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
35581 this.words[j] |= (w << off) & 0x3ffffff;
35582 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35583 off += 24;
35584 if (off >= 26) {
35585 off -= 26;
35586 j++;
35587 }
35588 }
35589 } else if (endian === 'le') {
35590 for (i = 0, j = 0; i < number.length; i += 3) {
35591 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
35592 this.words[j] |= (w << off) & 0x3ffffff;
35593 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35594 off += 24;
35595 if (off >= 26) {
35596 off -= 26;
35597 j++;
35598 }
35599 }
35600 }
35601 return this.strip();
35602 };
35603
35604 function parseHex (str, start, end) {
35605 var r = 0;
35606 var len = Math.min(str.length, end);
35607 for (var i = start; i < len; i++) {
35608 var c = str.charCodeAt(i) - 48;
35609
35610 r <<= 4;
35611
35612 // 'a' - 'f'
35613 if (c >= 49 && c <= 54) {
35614 r |= c - 49 + 0xa;
35615
35616 // 'A' - 'F'
35617 } else if (c >= 17 && c <= 22) {
35618 r |= c - 17 + 0xa;
35619
35620 // '0' - '9'
35621 } else {
35622 r |= c & 0xf;
35623 }
35624 }
35625 return r;
35626 }
35627
35628 BN.prototype._parseHex = function _parseHex (number, start) {
35629 // Create possibly bigger array to ensure that it fits the number
35630 this.length = Math.ceil((number.length - start) / 6);
35631 this.words = new Array(this.length);
35632 for (var i = 0; i < this.length; i++) {
35633 this.words[i] = 0;
35634 }
35635
35636 var j, w;
35637 // Scan 24-bit chunks and add them to the number
35638 var off = 0;
35639 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
35640 w = parseHex(number, i, i + 6);
35641 this.words[j] |= (w << off) & 0x3ffffff;
35642 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
35643 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35644 off += 24;
35645 if (off >= 26) {
35646 off -= 26;
35647 j++;
35648 }
35649 }
35650 if (i + 6 !== start) {
35651 w = parseHex(number, start, i + 6);
35652 this.words[j] |= (w << off) & 0x3ffffff;
35653 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35654 }
35655 this.strip();
35656 };
35657
35658 function parseBase (str, start, end, mul) {
35659 var r = 0;
35660 var len = Math.min(str.length, end);
35661 for (var i = start; i < len; i++) {
35662 var c = str.charCodeAt(i) - 48;
35663
35664 r *= mul;
35665
35666 // 'a'
35667 if (c >= 49) {
35668 r += c - 49 + 0xa;
35669
35670 // 'A'
35671 } else if (c >= 17) {
35672 r += c - 17 + 0xa;
35673
35674 // '0' - '9'
35675 } else {
35676 r += c;
35677 }
35678 }
35679 return r;
35680 }
35681
35682 BN.prototype._parseBase = function _parseBase (number, base, start) {
35683 // Initialize as zero
35684 this.words = [ 0 ];
35685 this.length = 1;
35686
35687 // Find length of limb in base
35688 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
35689 limbLen++;
35690 }
35691 limbLen--;
35692 limbPow = (limbPow / base) | 0;
35693
35694 var total = number.length - start;
35695 var mod = total % limbLen;
35696 var end = Math.min(total, total - mod) + start;
35697
35698 var word = 0;
35699 for (var i = start; i < end; i += limbLen) {
35700 word = parseBase(number, i, i + limbLen, base);
35701
35702 this.imuln(limbPow);
35703 if (this.words[0] + word < 0x4000000) {
35704 this.words[0] += word;
35705 } else {
35706 this._iaddn(word);
35707 }
35708 }
35709
35710 if (mod !== 0) {
35711 var pow = 1;
35712 word = parseBase(number, i, number.length, base);
35713
35714 for (i = 0; i < mod; i++) {
35715 pow *= base;
35716 }
35717
35718 this.imuln(pow);
35719 if (this.words[0] + word < 0x4000000) {
35720 this.words[0] += word;
35721 } else {
35722 this._iaddn(word);
35723 }
35724 }
35725 };
35726
35727 BN.prototype.copy = function copy (dest) {
35728 dest.words = new Array(this.length);
35729 for (var i = 0; i < this.length; i++) {
35730 dest.words[i] = this.words[i];
35731 }
35732 dest.length = this.length;
35733 dest.negative = this.negative;
35734 dest.red = this.red;
35735 };
35736
35737 BN.prototype.clone = function clone () {
35738 var r = new BN(null);
35739 this.copy(r);
35740 return r;
35741 };
35742
35743 BN.prototype._expand = function _expand (size) {
35744 while (this.length < size) {
35745 this.words[this.length++] = 0;
35746 }
35747 return this;
35748 };
35749
35750 // Remove leading `0` from `this`
35751 BN.prototype.strip = function strip () {
35752 while (this.length > 1 && this.words[this.length - 1] === 0) {
35753 this.length--;
35754 }
35755 return this._normSign();
35756 };
35757
35758 BN.prototype._normSign = function _normSign () {
35759 // -0 = 0
35760 if (this.length === 1 && this.words[0] === 0) {
35761 this.negative = 0;
35762 }
35763 return this;
35764 };
35765
35766 BN.prototype.inspect = function inspect () {
35767 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
35768 };
35769
35770 /*
35771
35772 var zeros = [];
35773 var groupSizes = [];
35774 var groupBases = [];
35775
35776 var s = '';
35777 var i = -1;
35778 while (++i < BN.wordSize) {
35779 zeros[i] = s;
35780 s += '0';
35781 }
35782 groupSizes[0] = 0;
35783 groupSizes[1] = 0;
35784 groupBases[0] = 0;
35785 groupBases[1] = 0;
35786 var base = 2 - 1;
35787 while (++base < 36 + 1) {
35788 var groupSize = 0;
35789 var groupBase = 1;
35790 while (groupBase < (1 << BN.wordSize) / base) {
35791 groupBase *= base;
35792 groupSize += 1;
35793 }
35794 groupSizes[base] = groupSize;
35795 groupBases[base] = groupBase;
35796 }
35797
35798 */
35799
35800 var zeros = [
35801 '',
35802 '0',
35803 '00',
35804 '000',
35805 '0000',
35806 '00000',
35807 '000000',
35808 '0000000',
35809 '00000000',
35810 '000000000',
35811 '0000000000',
35812 '00000000000',
35813 '000000000000',
35814 '0000000000000',
35815 '00000000000000',
35816 '000000000000000',
35817 '0000000000000000',
35818 '00000000000000000',
35819 '000000000000000000',
35820 '0000000000000000000',
35821 '00000000000000000000',
35822 '000000000000000000000',
35823 '0000000000000000000000',
35824 '00000000000000000000000',
35825 '000000000000000000000000',
35826 '0000000000000000000000000'
35827 ];
35828
35829 var groupSizes = [
35830 0, 0,
35831 25, 16, 12, 11, 10, 9, 8,
35832 8, 7, 7, 7, 7, 6, 6,
35833 6, 6, 6, 6, 6, 5, 5,
35834 5, 5, 5, 5, 5, 5, 5,
35835 5, 5, 5, 5, 5, 5, 5
35836 ];
35837
35838 var groupBases = [
35839 0, 0,
35840 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
35841 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
35842 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
35843 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
35844 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
35845 ];
35846
35847 BN.prototype.toString = function toString (base, padding) {
35848 base = base || 10;
35849 padding = padding | 0 || 1;
35850
35851 var out;
35852 if (base === 16 || base === 'hex') {
35853 out = '';
35854 var off = 0;
35855 var carry = 0;
35856 for (var i = 0; i < this.length; i++) {
35857 var w = this.words[i];
35858 var word = (((w << off) | carry) & 0xffffff).toString(16);
35859 carry = (w >>> (24 - off)) & 0xffffff;
35860 if (carry !== 0 || i !== this.length - 1) {
35861 out = zeros[6 - word.length] + word + out;
35862 } else {
35863 out = word + out;
35864 }
35865 off += 2;
35866 if (off >= 26) {
35867 off -= 26;
35868 i--;
35869 }
35870 }
35871 if (carry !== 0) {
35872 out = carry.toString(16) + out;
35873 }
35874 while (out.length % padding !== 0) {
35875 out = '0' + out;
35876 }
35877 if (this.negative !== 0) {
35878 out = '-' + out;
35879 }
35880 return out;
35881 }
35882
35883 if (base === (base | 0) && base >= 2 && base <= 36) {
35884 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
35885 var groupSize = groupSizes[base];
35886 // var groupBase = Math.pow(base, groupSize);
35887 var groupBase = groupBases[base];
35888 out = '';
35889 var c = this.clone();
35890 c.negative = 0;
35891 while (!c.isZero()) {
35892 var r = c.modn(groupBase).toString(base);
35893 c = c.idivn(groupBase);
35894
35895 if (!c.isZero()) {
35896 out = zeros[groupSize - r.length] + r + out;
35897 } else {
35898 out = r + out;
35899 }
35900 }
35901 if (this.isZero()) {
35902 out = '0' + out;
35903 }
35904 while (out.length % padding !== 0) {
35905 out = '0' + out;
35906 }
35907 if (this.negative !== 0) {
35908 out = '-' + out;
35909 }
35910 return out;
35911 }
35912
35913 assert(false, 'Base should be between 2 and 36');
35914 };
35915
35916 BN.prototype.toNumber = function toNumber () {
35917 var ret = this.words[0];
35918 if (this.length === 2) {
35919 ret += this.words[1] * 0x4000000;
35920 } else if (this.length === 3 && this.words[2] === 0x01) {
35921 // NOTE: at this stage it is known that the top bit is set
35922 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
35923 } else if (this.length > 2) {
35924 assert(false, 'Number can only safely store up to 53 bits');
35925 }
35926 return (this.negative !== 0) ? -ret : ret;
35927 };
35928
35929 BN.prototype.toJSON = function toJSON () {
35930 return this.toString(16);
35931 };
35932
35933 BN.prototype.toBuffer = function toBuffer (endian, length) {
35934 assert(typeof Buffer !== 'undefined');
35935 return this.toArrayLike(Buffer, endian, length);
35936 };
35937
35938 BN.prototype.toArray = function toArray (endian, length) {
35939 return this.toArrayLike(Array, endian, length);
35940 };
35941
35942 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
35943 var byteLength = this.byteLength();
35944 var reqLength = length || Math.max(1, byteLength);
35945 assert(byteLength <= reqLength, 'byte array longer than desired length');
35946 assert(reqLength > 0, 'Requested array length <= 0');
35947
35948 this.strip();
35949 var littleEndian = endian === 'le';
35950 var res = new ArrayType(reqLength);
35951
35952 var b, i;
35953 var q = this.clone();
35954 if (!littleEndian) {
35955 // Assume big-endian
35956 for (i = 0; i < reqLength - byteLength; i++) {
35957 res[i] = 0;
35958 }
35959
35960 for (i = 0; !q.isZero(); i++) {
35961 b = q.andln(0xff);
35962 q.iushrn(8);
35963
35964 res[reqLength - i - 1] = b;
35965 }
35966 } else {
35967 for (i = 0; !q.isZero(); i++) {
35968 b = q.andln(0xff);
35969 q.iushrn(8);
35970
35971 res[i] = b;
35972 }
35973
35974 for (; i < reqLength; i++) {
35975 res[i] = 0;
35976 }
35977 }
35978
35979 return res;
35980 };
35981
35982 if (Math.clz32) {
35983 BN.prototype._countBits = function _countBits (w) {
35984 return 32 - Math.clz32(w);
35985 };
35986 } else {
35987 BN.prototype._countBits = function _countBits (w) {
35988 var t = w;
35989 var r = 0;
35990 if (t >= 0x1000) {
35991 r += 13;
35992 t >>>= 13;
35993 }
35994 if (t >= 0x40) {
35995 r += 7;
35996 t >>>= 7;
35997 }
35998 if (t >= 0x8) {
35999 r += 4;
36000 t >>>= 4;
36001 }
36002 if (t >= 0x02) {
36003 r += 2;
36004 t >>>= 2;
36005 }
36006 return r + t;
36007 };
36008 }
36009
36010 BN.prototype._zeroBits = function _zeroBits (w) {
36011 // Short-cut
36012 if (w === 0) return 26;
36013
36014 var t = w;
36015 var r = 0;
36016 if ((t & 0x1fff) === 0) {
36017 r += 13;
36018 t >>>= 13;
36019 }
36020 if ((t & 0x7f) === 0) {
36021 r += 7;
36022 t >>>= 7;
36023 }
36024 if ((t & 0xf) === 0) {
36025 r += 4;
36026 t >>>= 4;
36027 }
36028 if ((t & 0x3) === 0) {
36029 r += 2;
36030 t >>>= 2;
36031 }
36032 if ((t & 0x1) === 0) {
36033 r++;
36034 }
36035 return r;
36036 };
36037
36038 // Return number of used bits in a BN
36039 BN.prototype.bitLength = function bitLength () {
36040 var w = this.words[this.length - 1];
36041 var hi = this._countBits(w);
36042 return (this.length - 1) * 26 + hi;
36043 };
36044
36045 function toBitArray (num) {
36046 var w = new Array(num.bitLength());
36047
36048 for (var bit = 0; bit < w.length; bit++) {
36049 var off = (bit / 26) | 0;
36050 var wbit = bit % 26;
36051
36052 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
36053 }
36054
36055 return w;
36056 }
36057
36058 // Number of trailing zero bits
36059 BN.prototype.zeroBits = function zeroBits () {
36060 if (this.isZero()) return 0;
36061
36062 var r = 0;
36063 for (var i = 0; i < this.length; i++) {
36064 var b = this._zeroBits(this.words[i]);
36065 r += b;
36066 if (b !== 26) break;
36067 }
36068 return r;
36069 };
36070
36071 BN.prototype.byteLength = function byteLength () {
36072 return Math.ceil(this.bitLength() / 8);
36073 };
36074
36075 BN.prototype.toTwos = function toTwos (width) {
36076 if (this.negative !== 0) {
36077 return this.abs().inotn(width).iaddn(1);
36078 }
36079 return this.clone();
36080 };
36081
36082 BN.prototype.fromTwos = function fromTwos (width) {
36083 if (this.testn(width - 1)) {
36084 return this.notn(width).iaddn(1).ineg();
36085 }
36086 return this.clone();
36087 };
36088
36089 BN.prototype.isNeg = function isNeg () {
36090 return this.negative !== 0;
36091 };
36092
36093 // Return negative clone of `this`
36094 BN.prototype.neg = function neg () {
36095 return this.clone().ineg();
36096 };
36097
36098 BN.prototype.ineg = function ineg () {
36099 if (!this.isZero()) {
36100 this.negative ^= 1;
36101 }
36102
36103 return this;
36104 };
36105
36106 // Or `num` with `this` in-place
36107 BN.prototype.iuor = function iuor (num) {
36108 while (this.length < num.length) {
36109 this.words[this.length++] = 0;
36110 }
36111
36112 for (var i = 0; i < num.length; i++) {
36113 this.words[i] = this.words[i] | num.words[i];
36114 }
36115
36116 return this.strip();
36117 };
36118
36119 BN.prototype.ior = function ior (num) {
36120 assert((this.negative | num.negative) === 0);
36121 return this.iuor(num);
36122 };
36123
36124 // Or `num` with `this`
36125 BN.prototype.or = function or (num) {
36126 if (this.length > num.length) return this.clone().ior(num);
36127 return num.clone().ior(this);
36128 };
36129
36130 BN.prototype.uor = function uor (num) {
36131 if (this.length > num.length) return this.clone().iuor(num);
36132 return num.clone().iuor(this);
36133 };
36134
36135 // And `num` with `this` in-place
36136 BN.prototype.iuand = function iuand (num) {
36137 // b = min-length(num, this)
36138 var b;
36139 if (this.length > num.length) {
36140 b = num;
36141 } else {
36142 b = this;
36143 }
36144
36145 for (var i = 0; i < b.length; i++) {
36146 this.words[i] = this.words[i] & num.words[i];
36147 }
36148
36149 this.length = b.length;
36150
36151 return this.strip();
36152 };
36153
36154 BN.prototype.iand = function iand (num) {
36155 assert((this.negative | num.negative) === 0);
36156 return this.iuand(num);
36157 };
36158
36159 // And `num` with `this`
36160 BN.prototype.and = function and (num) {
36161 if (this.length > num.length) return this.clone().iand(num);
36162 return num.clone().iand(this);
36163 };
36164
36165 BN.prototype.uand = function uand (num) {
36166 if (this.length > num.length) return this.clone().iuand(num);
36167 return num.clone().iuand(this);
36168 };
36169
36170 // Xor `num` with `this` in-place
36171 BN.prototype.iuxor = function iuxor (num) {
36172 // a.length > b.length
36173 var a;
36174 var b;
36175 if (this.length > num.length) {
36176 a = this;
36177 b = num;
36178 } else {
36179 a = num;
36180 b = this;
36181 }
36182
36183 for (var i = 0; i < b.length; i++) {
36184 this.words[i] = a.words[i] ^ b.words[i];
36185 }
36186
36187 if (this !== a) {
36188 for (; i < a.length; i++) {
36189 this.words[i] = a.words[i];
36190 }
36191 }
36192
36193 this.length = a.length;
36194
36195 return this.strip();
36196 };
36197
36198 BN.prototype.ixor = function ixor (num) {
36199 assert((this.negative | num.negative) === 0);
36200 return this.iuxor(num);
36201 };
36202
36203 // Xor `num` with `this`
36204 BN.prototype.xor = function xor (num) {
36205 if (this.length > num.length) return this.clone().ixor(num);
36206 return num.clone().ixor(this);
36207 };
36208
36209 BN.prototype.uxor = function uxor (num) {
36210 if (this.length > num.length) return this.clone().iuxor(num);
36211 return num.clone().iuxor(this);
36212 };
36213
36214 // Not ``this`` with ``width`` bitwidth
36215 BN.prototype.inotn = function inotn (width) {
36216 assert(typeof width === 'number' && width >= 0);
36217
36218 var bytesNeeded = Math.ceil(width / 26) | 0;
36219 var bitsLeft = width % 26;
36220
36221 // Extend the buffer with leading zeroes
36222 this._expand(bytesNeeded);
36223
36224 if (bitsLeft > 0) {
36225 bytesNeeded--;
36226 }
36227
36228 // Handle complete words
36229 for (var i = 0; i < bytesNeeded; i++) {
36230 this.words[i] = ~this.words[i] & 0x3ffffff;
36231 }
36232
36233 // Handle the residue
36234 if (bitsLeft > 0) {
36235 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
36236 }
36237
36238 // And remove leading zeroes
36239 return this.strip();
36240 };
36241
36242 BN.prototype.notn = function notn (width) {
36243 return this.clone().inotn(width);
36244 };
36245
36246 // Set `bit` of `this`
36247 BN.prototype.setn = function setn (bit, val) {
36248 assert(typeof bit === 'number' && bit >= 0);
36249
36250 var off = (bit / 26) | 0;
36251 var wbit = bit % 26;
36252
36253 this._expand(off + 1);
36254
36255 if (val) {
36256 this.words[off] = this.words[off] | (1 << wbit);
36257 } else {
36258 this.words[off] = this.words[off] & ~(1 << wbit);
36259 }
36260
36261 return this.strip();
36262 };
36263
36264 // Add `num` to `this` in-place
36265 BN.prototype.iadd = function iadd (num) {
36266 var r;
36267
36268 // negative + positive
36269 if (this.negative !== 0 && num.negative === 0) {
36270 this.negative = 0;
36271 r = this.isub(num);
36272 this.negative ^= 1;
36273 return this._normSign();
36274
36275 // positive + negative
36276 } else if (this.negative === 0 && num.negative !== 0) {
36277 num.negative = 0;
36278 r = this.isub(num);
36279 num.negative = 1;
36280 return r._normSign();
36281 }
36282
36283 // a.length > b.length
36284 var a, b;
36285 if (this.length > num.length) {
36286 a = this;
36287 b = num;
36288 } else {
36289 a = num;
36290 b = this;
36291 }
36292
36293 var carry = 0;
36294 for (var i = 0; i < b.length; i++) {
36295 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
36296 this.words[i] = r & 0x3ffffff;
36297 carry = r >>> 26;
36298 }
36299 for (; carry !== 0 && i < a.length; i++) {
36300 r = (a.words[i] | 0) + carry;
36301 this.words[i] = r & 0x3ffffff;
36302 carry = r >>> 26;
36303 }
36304
36305 this.length = a.length;
36306 if (carry !== 0) {
36307 this.words[this.length] = carry;
36308 this.length++;
36309 // Copy the rest of the words
36310 } else if (a !== this) {
36311 for (; i < a.length; i++) {
36312 this.words[i] = a.words[i];
36313 }
36314 }
36315
36316 return this;
36317 };
36318
36319 // Add `num` to `this`
36320 BN.prototype.add = function add (num) {
36321 var res;
36322 if (num.negative !== 0 && this.negative === 0) {
36323 num.negative = 0;
36324 res = this.sub(num);
36325 num.negative ^= 1;
36326 return res;
36327 } else if (num.negative === 0 && this.negative !== 0) {
36328 this.negative = 0;
36329 res = num.sub(this);
36330 this.negative = 1;
36331 return res;
36332 }
36333
36334 if (this.length > num.length) return this.clone().iadd(num);
36335
36336 return num.clone().iadd(this);
36337 };
36338
36339 // Subtract `num` from `this` in-place
36340 BN.prototype.isub = function isub (num) {
36341 // this - (-num) = this + num
36342 if (num.negative !== 0) {
36343 num.negative = 0;
36344 var r = this.iadd(num);
36345 num.negative = 1;
36346 return r._normSign();
36347
36348 // -this - num = -(this + num)
36349 } else if (this.negative !== 0) {
36350 this.negative = 0;
36351 this.iadd(num);
36352 this.negative = 1;
36353 return this._normSign();
36354 }
36355
36356 // At this point both numbers are positive
36357 var cmp = this.cmp(num);
36358
36359 // Optimization - zeroify
36360 if (cmp === 0) {
36361 this.negative = 0;
36362 this.length = 1;
36363 this.words[0] = 0;
36364 return this;
36365 }
36366
36367 // a > b
36368 var a, b;
36369 if (cmp > 0) {
36370 a = this;
36371 b = num;
36372 } else {
36373 a = num;
36374 b = this;
36375 }
36376
36377 var carry = 0;
36378 for (var i = 0; i < b.length; i++) {
36379 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
36380 carry = r >> 26;
36381 this.words[i] = r & 0x3ffffff;
36382 }
36383 for (; carry !== 0 && i < a.length; i++) {
36384 r = (a.words[i] | 0) + carry;
36385 carry = r >> 26;
36386 this.words[i] = r & 0x3ffffff;
36387 }
36388
36389 // Copy rest of the words
36390 if (carry === 0 && i < a.length && a !== this) {
36391 for (; i < a.length; i++) {
36392 this.words[i] = a.words[i];
36393 }
36394 }
36395
36396 this.length = Math.max(this.length, i);
36397
36398 if (a !== this) {
36399 this.negative = 1;
36400 }
36401
36402 return this.strip();
36403 };
36404
36405 // Subtract `num` from `this`
36406 BN.prototype.sub = function sub (num) {
36407 return this.clone().isub(num);
36408 };
36409
36410 function smallMulTo (self, num, out) {
36411 out.negative = num.negative ^ self.negative;
36412 var len = (self.length + num.length) | 0;
36413 out.length = len;
36414 len = (len - 1) | 0;
36415
36416 // Peel one iteration (compiler can't do it, because of code complexity)
36417 var a = self.words[0] | 0;
36418 var b = num.words[0] | 0;
36419 var r = a * b;
36420
36421 var lo = r & 0x3ffffff;
36422 var carry = (r / 0x4000000) | 0;
36423 out.words[0] = lo;
36424
36425 for (var k = 1; k < len; k++) {
36426 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
36427 // note that ncarry could be >= 0x3ffffff
36428 var ncarry = carry >>> 26;
36429 var rword = carry & 0x3ffffff;
36430 var maxJ = Math.min(k, num.length - 1);
36431 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
36432 var i = (k - j) | 0;
36433 a = self.words[i] | 0;
36434 b = num.words[j] | 0;
36435 r = a * b + rword;
36436 ncarry += (r / 0x4000000) | 0;
36437 rword = r & 0x3ffffff;
36438 }
36439 out.words[k] = rword | 0;
36440 carry = ncarry | 0;
36441 }
36442 if (carry !== 0) {
36443 out.words[k] = carry | 0;
36444 } else {
36445 out.length--;
36446 }
36447
36448 return out.strip();
36449 }
36450
36451 // TODO(indutny): it may be reasonable to omit it for users who don't need
36452 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
36453 // multiplication (like elliptic secp256k1).
36454 var comb10MulTo = function comb10MulTo (self, num, out) {
36455 var a = self.words;
36456 var b = num.words;
36457 var o = out.words;
36458 var c = 0;
36459 var lo;
36460 var mid;
36461 var hi;
36462 var a0 = a[0] | 0;
36463 var al0 = a0 & 0x1fff;
36464 var ah0 = a0 >>> 13;
36465 var a1 = a[1] | 0;
36466 var al1 = a1 & 0x1fff;
36467 var ah1 = a1 >>> 13;
36468 var a2 = a[2] | 0;
36469 var al2 = a2 & 0x1fff;
36470 var ah2 = a2 >>> 13;
36471 var a3 = a[3] | 0;
36472 var al3 = a3 & 0x1fff;
36473 var ah3 = a3 >>> 13;
36474 var a4 = a[4] | 0;
36475 var al4 = a4 & 0x1fff;
36476 var ah4 = a4 >>> 13;
36477 var a5 = a[5] | 0;
36478 var al5 = a5 & 0x1fff;
36479 var ah5 = a5 >>> 13;
36480 var a6 = a[6] | 0;
36481 var al6 = a6 & 0x1fff;
36482 var ah6 = a6 >>> 13;
36483 var a7 = a[7] | 0;
36484 var al7 = a7 & 0x1fff;
36485 var ah7 = a7 >>> 13;
36486 var a8 = a[8] | 0;
36487 var al8 = a8 & 0x1fff;
36488 var ah8 = a8 >>> 13;
36489 var a9 = a[9] | 0;
36490 var al9 = a9 & 0x1fff;
36491 var ah9 = a9 >>> 13;
36492 var b0 = b[0] | 0;
36493 var bl0 = b0 & 0x1fff;
36494 var bh0 = b0 >>> 13;
36495 var b1 = b[1] | 0;
36496 var bl1 = b1 & 0x1fff;
36497 var bh1 = b1 >>> 13;
36498 var b2 = b[2] | 0;
36499 var bl2 = b2 & 0x1fff;
36500 var bh2 = b2 >>> 13;
36501 var b3 = b[3] | 0;
36502 var bl3 = b3 & 0x1fff;
36503 var bh3 = b3 >>> 13;
36504 var b4 = b[4] | 0;
36505 var bl4 = b4 & 0x1fff;
36506 var bh4 = b4 >>> 13;
36507 var b5 = b[5] | 0;
36508 var bl5 = b5 & 0x1fff;
36509 var bh5 = b5 >>> 13;
36510 var b6 = b[6] | 0;
36511 var bl6 = b6 & 0x1fff;
36512 var bh6 = b6 >>> 13;
36513 var b7 = b[7] | 0;
36514 var bl7 = b7 & 0x1fff;
36515 var bh7 = b7 >>> 13;
36516 var b8 = b[8] | 0;
36517 var bl8 = b8 & 0x1fff;
36518 var bh8 = b8 >>> 13;
36519 var b9 = b[9] | 0;
36520 var bl9 = b9 & 0x1fff;
36521 var bh9 = b9 >>> 13;
36522
36523 out.negative = self.negative ^ num.negative;
36524 out.length = 19;
36525 /* k = 0 */
36526 lo = Math.imul(al0, bl0);
36527 mid = Math.imul(al0, bh0);
36528 mid = (mid + Math.imul(ah0, bl0)) | 0;
36529 hi = Math.imul(ah0, bh0);
36530 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36531 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
36532 w0 &= 0x3ffffff;
36533 /* k = 1 */
36534 lo = Math.imul(al1, bl0);
36535 mid = Math.imul(al1, bh0);
36536 mid = (mid + Math.imul(ah1, bl0)) | 0;
36537 hi = Math.imul(ah1, bh0);
36538 lo = (lo + Math.imul(al0, bl1)) | 0;
36539 mid = (mid + Math.imul(al0, bh1)) | 0;
36540 mid = (mid + Math.imul(ah0, bl1)) | 0;
36541 hi = (hi + Math.imul(ah0, bh1)) | 0;
36542 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36543 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
36544 w1 &= 0x3ffffff;
36545 /* k = 2 */
36546 lo = Math.imul(al2, bl0);
36547 mid = Math.imul(al2, bh0);
36548 mid = (mid + Math.imul(ah2, bl0)) | 0;
36549 hi = Math.imul(ah2, bh0);
36550 lo = (lo + Math.imul(al1, bl1)) | 0;
36551 mid = (mid + Math.imul(al1, bh1)) | 0;
36552 mid = (mid + Math.imul(ah1, bl1)) | 0;
36553 hi = (hi + Math.imul(ah1, bh1)) | 0;
36554 lo = (lo + Math.imul(al0, bl2)) | 0;
36555 mid = (mid + Math.imul(al0, bh2)) | 0;
36556 mid = (mid + Math.imul(ah0, bl2)) | 0;
36557 hi = (hi + Math.imul(ah0, bh2)) | 0;
36558 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36559 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
36560 w2 &= 0x3ffffff;
36561 /* k = 3 */
36562 lo = Math.imul(al3, bl0);
36563 mid = Math.imul(al3, bh0);
36564 mid = (mid + Math.imul(ah3, bl0)) | 0;
36565 hi = Math.imul(ah3, bh0);
36566 lo = (lo + Math.imul(al2, bl1)) | 0;
36567 mid = (mid + Math.imul(al2, bh1)) | 0;
36568 mid = (mid + Math.imul(ah2, bl1)) | 0;
36569 hi = (hi + Math.imul(ah2, bh1)) | 0;
36570 lo = (lo + Math.imul(al1, bl2)) | 0;
36571 mid = (mid + Math.imul(al1, bh2)) | 0;
36572 mid = (mid + Math.imul(ah1, bl2)) | 0;
36573 hi = (hi + Math.imul(ah1, bh2)) | 0;
36574 lo = (lo + Math.imul(al0, bl3)) | 0;
36575 mid = (mid + Math.imul(al0, bh3)) | 0;
36576 mid = (mid + Math.imul(ah0, bl3)) | 0;
36577 hi = (hi + Math.imul(ah0, bh3)) | 0;
36578 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36579 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
36580 w3 &= 0x3ffffff;
36581 /* k = 4 */
36582 lo = Math.imul(al4, bl0);
36583 mid = Math.imul(al4, bh0);
36584 mid = (mid + Math.imul(ah4, bl0)) | 0;
36585 hi = Math.imul(ah4, bh0);
36586 lo = (lo + Math.imul(al3, bl1)) | 0;
36587 mid = (mid + Math.imul(al3, bh1)) | 0;
36588 mid = (mid + Math.imul(ah3, bl1)) | 0;
36589 hi = (hi + Math.imul(ah3, bh1)) | 0;
36590 lo = (lo + Math.imul(al2, bl2)) | 0;
36591 mid = (mid + Math.imul(al2, bh2)) | 0;
36592 mid = (mid + Math.imul(ah2, bl2)) | 0;
36593 hi = (hi + Math.imul(ah2, bh2)) | 0;
36594 lo = (lo + Math.imul(al1, bl3)) | 0;
36595 mid = (mid + Math.imul(al1, bh3)) | 0;
36596 mid = (mid + Math.imul(ah1, bl3)) | 0;
36597 hi = (hi + Math.imul(ah1, bh3)) | 0;
36598 lo = (lo + Math.imul(al0, bl4)) | 0;
36599 mid = (mid + Math.imul(al0, bh4)) | 0;
36600 mid = (mid + Math.imul(ah0, bl4)) | 0;
36601 hi = (hi + Math.imul(ah0, bh4)) | 0;
36602 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36603 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
36604 w4 &= 0x3ffffff;
36605 /* k = 5 */
36606 lo = Math.imul(al5, bl0);
36607 mid = Math.imul(al5, bh0);
36608 mid = (mid + Math.imul(ah5, bl0)) | 0;
36609 hi = Math.imul(ah5, bh0);
36610 lo = (lo + Math.imul(al4, bl1)) | 0;
36611 mid = (mid + Math.imul(al4, bh1)) | 0;
36612 mid = (mid + Math.imul(ah4, bl1)) | 0;
36613 hi = (hi + Math.imul(ah4, bh1)) | 0;
36614 lo = (lo + Math.imul(al3, bl2)) | 0;
36615 mid = (mid + Math.imul(al3, bh2)) | 0;
36616 mid = (mid + Math.imul(ah3, bl2)) | 0;
36617 hi = (hi + Math.imul(ah3, bh2)) | 0;
36618 lo = (lo + Math.imul(al2, bl3)) | 0;
36619 mid = (mid + Math.imul(al2, bh3)) | 0;
36620 mid = (mid + Math.imul(ah2, bl3)) | 0;
36621 hi = (hi + Math.imul(ah2, bh3)) | 0;
36622 lo = (lo + Math.imul(al1, bl4)) | 0;
36623 mid = (mid + Math.imul(al1, bh4)) | 0;
36624 mid = (mid + Math.imul(ah1, bl4)) | 0;
36625 hi = (hi + Math.imul(ah1, bh4)) | 0;
36626 lo = (lo + Math.imul(al0, bl5)) | 0;
36627 mid = (mid + Math.imul(al0, bh5)) | 0;
36628 mid = (mid + Math.imul(ah0, bl5)) | 0;
36629 hi = (hi + Math.imul(ah0, bh5)) | 0;
36630 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36631 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
36632 w5 &= 0x3ffffff;
36633 /* k = 6 */
36634 lo = Math.imul(al6, bl0);
36635 mid = Math.imul(al6, bh0);
36636 mid = (mid + Math.imul(ah6, bl0)) | 0;
36637 hi = Math.imul(ah6, bh0);
36638 lo = (lo + Math.imul(al5, bl1)) | 0;
36639 mid = (mid + Math.imul(al5, bh1)) | 0;
36640 mid = (mid + Math.imul(ah5, bl1)) | 0;
36641 hi = (hi + Math.imul(ah5, bh1)) | 0;
36642 lo = (lo + Math.imul(al4, bl2)) | 0;
36643 mid = (mid + Math.imul(al4, bh2)) | 0;
36644 mid = (mid + Math.imul(ah4, bl2)) | 0;
36645 hi = (hi + Math.imul(ah4, bh2)) | 0;
36646 lo = (lo + Math.imul(al3, bl3)) | 0;
36647 mid = (mid + Math.imul(al3, bh3)) | 0;
36648 mid = (mid + Math.imul(ah3, bl3)) | 0;
36649 hi = (hi + Math.imul(ah3, bh3)) | 0;
36650 lo = (lo + Math.imul(al2, bl4)) | 0;
36651 mid = (mid + Math.imul(al2, bh4)) | 0;
36652 mid = (mid + Math.imul(ah2, bl4)) | 0;
36653 hi = (hi + Math.imul(ah2, bh4)) | 0;
36654 lo = (lo + Math.imul(al1, bl5)) | 0;
36655 mid = (mid + Math.imul(al1, bh5)) | 0;
36656 mid = (mid + Math.imul(ah1, bl5)) | 0;
36657 hi = (hi + Math.imul(ah1, bh5)) | 0;
36658 lo = (lo + Math.imul(al0, bl6)) | 0;
36659 mid = (mid + Math.imul(al0, bh6)) | 0;
36660 mid = (mid + Math.imul(ah0, bl6)) | 0;
36661 hi = (hi + Math.imul(ah0, bh6)) | 0;
36662 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36663 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
36664 w6 &= 0x3ffffff;
36665 /* k = 7 */
36666 lo = Math.imul(al7, bl0);
36667 mid = Math.imul(al7, bh0);
36668 mid = (mid + Math.imul(ah7, bl0)) | 0;
36669 hi = Math.imul(ah7, bh0);
36670 lo = (lo + Math.imul(al6, bl1)) | 0;
36671 mid = (mid + Math.imul(al6, bh1)) | 0;
36672 mid = (mid + Math.imul(ah6, bl1)) | 0;
36673 hi = (hi + Math.imul(ah6, bh1)) | 0;
36674 lo = (lo + Math.imul(al5, bl2)) | 0;
36675 mid = (mid + Math.imul(al5, bh2)) | 0;
36676 mid = (mid + Math.imul(ah5, bl2)) | 0;
36677 hi = (hi + Math.imul(ah5, bh2)) | 0;
36678 lo = (lo + Math.imul(al4, bl3)) | 0;
36679 mid = (mid + Math.imul(al4, bh3)) | 0;
36680 mid = (mid + Math.imul(ah4, bl3)) | 0;
36681 hi = (hi + Math.imul(ah4, bh3)) | 0;
36682 lo = (lo + Math.imul(al3, bl4)) | 0;
36683 mid = (mid + Math.imul(al3, bh4)) | 0;
36684 mid = (mid + Math.imul(ah3, bl4)) | 0;
36685 hi = (hi + Math.imul(ah3, bh4)) | 0;
36686 lo = (lo + Math.imul(al2, bl5)) | 0;
36687 mid = (mid + Math.imul(al2, bh5)) | 0;
36688 mid = (mid + Math.imul(ah2, bl5)) | 0;
36689 hi = (hi + Math.imul(ah2, bh5)) | 0;
36690 lo = (lo + Math.imul(al1, bl6)) | 0;
36691 mid = (mid + Math.imul(al1, bh6)) | 0;
36692 mid = (mid + Math.imul(ah1, bl6)) | 0;
36693 hi = (hi + Math.imul(ah1, bh6)) | 0;
36694 lo = (lo + Math.imul(al0, bl7)) | 0;
36695 mid = (mid + Math.imul(al0, bh7)) | 0;
36696 mid = (mid + Math.imul(ah0, bl7)) | 0;
36697 hi = (hi + Math.imul(ah0, bh7)) | 0;
36698 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36699 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
36700 w7 &= 0x3ffffff;
36701 /* k = 8 */
36702 lo = Math.imul(al8, bl0);
36703 mid = Math.imul(al8, bh0);
36704 mid = (mid + Math.imul(ah8, bl0)) | 0;
36705 hi = Math.imul(ah8, bh0);
36706 lo = (lo + Math.imul(al7, bl1)) | 0;
36707 mid = (mid + Math.imul(al7, bh1)) | 0;
36708 mid = (mid + Math.imul(ah7, bl1)) | 0;
36709 hi = (hi + Math.imul(ah7, bh1)) | 0;
36710 lo = (lo + Math.imul(al6, bl2)) | 0;
36711 mid = (mid + Math.imul(al6, bh2)) | 0;
36712 mid = (mid + Math.imul(ah6, bl2)) | 0;
36713 hi = (hi + Math.imul(ah6, bh2)) | 0;
36714 lo = (lo + Math.imul(al5, bl3)) | 0;
36715 mid = (mid + Math.imul(al5, bh3)) | 0;
36716 mid = (mid + Math.imul(ah5, bl3)) | 0;
36717 hi = (hi + Math.imul(ah5, bh3)) | 0;
36718 lo = (lo + Math.imul(al4, bl4)) | 0;
36719 mid = (mid + Math.imul(al4, bh4)) | 0;
36720 mid = (mid + Math.imul(ah4, bl4)) | 0;
36721 hi = (hi + Math.imul(ah4, bh4)) | 0;
36722 lo = (lo + Math.imul(al3, bl5)) | 0;
36723 mid = (mid + Math.imul(al3, bh5)) | 0;
36724 mid = (mid + Math.imul(ah3, bl5)) | 0;
36725 hi = (hi + Math.imul(ah3, bh5)) | 0;
36726 lo = (lo + Math.imul(al2, bl6)) | 0;
36727 mid = (mid + Math.imul(al2, bh6)) | 0;
36728 mid = (mid + Math.imul(ah2, bl6)) | 0;
36729 hi = (hi + Math.imul(ah2, bh6)) | 0;
36730 lo = (lo + Math.imul(al1, bl7)) | 0;
36731 mid = (mid + Math.imul(al1, bh7)) | 0;
36732 mid = (mid + Math.imul(ah1, bl7)) | 0;
36733 hi = (hi + Math.imul(ah1, bh7)) | 0;
36734 lo = (lo + Math.imul(al0, bl8)) | 0;
36735 mid = (mid + Math.imul(al0, bh8)) | 0;
36736 mid = (mid + Math.imul(ah0, bl8)) | 0;
36737 hi = (hi + Math.imul(ah0, bh8)) | 0;
36738 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36739 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
36740 w8 &= 0x3ffffff;
36741 /* k = 9 */
36742 lo = Math.imul(al9, bl0);
36743 mid = Math.imul(al9, bh0);
36744 mid = (mid + Math.imul(ah9, bl0)) | 0;
36745 hi = Math.imul(ah9, bh0);
36746 lo = (lo + Math.imul(al8, bl1)) | 0;
36747 mid = (mid + Math.imul(al8, bh1)) | 0;
36748 mid = (mid + Math.imul(ah8, bl1)) | 0;
36749 hi = (hi + Math.imul(ah8, bh1)) | 0;
36750 lo = (lo + Math.imul(al7, bl2)) | 0;
36751 mid = (mid + Math.imul(al7, bh2)) | 0;
36752 mid = (mid + Math.imul(ah7, bl2)) | 0;
36753 hi = (hi + Math.imul(ah7, bh2)) | 0;
36754 lo = (lo + Math.imul(al6, bl3)) | 0;
36755 mid = (mid + Math.imul(al6, bh3)) | 0;
36756 mid = (mid + Math.imul(ah6, bl3)) | 0;
36757 hi = (hi + Math.imul(ah6, bh3)) | 0;
36758 lo = (lo + Math.imul(al5, bl4)) | 0;
36759 mid = (mid + Math.imul(al5, bh4)) | 0;
36760 mid = (mid + Math.imul(ah5, bl4)) | 0;
36761 hi = (hi + Math.imul(ah5, bh4)) | 0;
36762 lo = (lo + Math.imul(al4, bl5)) | 0;
36763 mid = (mid + Math.imul(al4, bh5)) | 0;
36764 mid = (mid + Math.imul(ah4, bl5)) | 0;
36765 hi = (hi + Math.imul(ah4, bh5)) | 0;
36766 lo = (lo + Math.imul(al3, bl6)) | 0;
36767 mid = (mid + Math.imul(al3, bh6)) | 0;
36768 mid = (mid + Math.imul(ah3, bl6)) | 0;
36769 hi = (hi + Math.imul(ah3, bh6)) | 0;
36770 lo = (lo + Math.imul(al2, bl7)) | 0;
36771 mid = (mid + Math.imul(al2, bh7)) | 0;
36772 mid = (mid + Math.imul(ah2, bl7)) | 0;
36773 hi = (hi + Math.imul(ah2, bh7)) | 0;
36774 lo = (lo + Math.imul(al1, bl8)) | 0;
36775 mid = (mid + Math.imul(al1, bh8)) | 0;
36776 mid = (mid + Math.imul(ah1, bl8)) | 0;
36777 hi = (hi + Math.imul(ah1, bh8)) | 0;
36778 lo = (lo + Math.imul(al0, bl9)) | 0;
36779 mid = (mid + Math.imul(al0, bh9)) | 0;
36780 mid = (mid + Math.imul(ah0, bl9)) | 0;
36781 hi = (hi + Math.imul(ah0, bh9)) | 0;
36782 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36783 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
36784 w9 &= 0x3ffffff;
36785 /* k = 10 */
36786 lo = Math.imul(al9, bl1);
36787 mid = Math.imul(al9, bh1);
36788 mid = (mid + Math.imul(ah9, bl1)) | 0;
36789 hi = Math.imul(ah9, bh1);
36790 lo = (lo + Math.imul(al8, bl2)) | 0;
36791 mid = (mid + Math.imul(al8, bh2)) | 0;
36792 mid = (mid + Math.imul(ah8, bl2)) | 0;
36793 hi = (hi + Math.imul(ah8, bh2)) | 0;
36794 lo = (lo + Math.imul(al7, bl3)) | 0;
36795 mid = (mid + Math.imul(al7, bh3)) | 0;
36796 mid = (mid + Math.imul(ah7, bl3)) | 0;
36797 hi = (hi + Math.imul(ah7, bh3)) | 0;
36798 lo = (lo + Math.imul(al6, bl4)) | 0;
36799 mid = (mid + Math.imul(al6, bh4)) | 0;
36800 mid = (mid + Math.imul(ah6, bl4)) | 0;
36801 hi = (hi + Math.imul(ah6, bh4)) | 0;
36802 lo = (lo + Math.imul(al5, bl5)) | 0;
36803 mid = (mid + Math.imul(al5, bh5)) | 0;
36804 mid = (mid + Math.imul(ah5, bl5)) | 0;
36805 hi = (hi + Math.imul(ah5, bh5)) | 0;
36806 lo = (lo + Math.imul(al4, bl6)) | 0;
36807 mid = (mid + Math.imul(al4, bh6)) | 0;
36808 mid = (mid + Math.imul(ah4, bl6)) | 0;
36809 hi = (hi + Math.imul(ah4, bh6)) | 0;
36810 lo = (lo + Math.imul(al3, bl7)) | 0;
36811 mid = (mid + Math.imul(al3, bh7)) | 0;
36812 mid = (mid + Math.imul(ah3, bl7)) | 0;
36813 hi = (hi + Math.imul(ah3, bh7)) | 0;
36814 lo = (lo + Math.imul(al2, bl8)) | 0;
36815 mid = (mid + Math.imul(al2, bh8)) | 0;
36816 mid = (mid + Math.imul(ah2, bl8)) | 0;
36817 hi = (hi + Math.imul(ah2, bh8)) | 0;
36818 lo = (lo + Math.imul(al1, bl9)) | 0;
36819 mid = (mid + Math.imul(al1, bh9)) | 0;
36820 mid = (mid + Math.imul(ah1, bl9)) | 0;
36821 hi = (hi + Math.imul(ah1, bh9)) | 0;
36822 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36823 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
36824 w10 &= 0x3ffffff;
36825 /* k = 11 */
36826 lo = Math.imul(al9, bl2);
36827 mid = Math.imul(al9, bh2);
36828 mid = (mid + Math.imul(ah9, bl2)) | 0;
36829 hi = Math.imul(ah9, bh2);
36830 lo = (lo + Math.imul(al8, bl3)) | 0;
36831 mid = (mid + Math.imul(al8, bh3)) | 0;
36832 mid = (mid + Math.imul(ah8, bl3)) | 0;
36833 hi = (hi + Math.imul(ah8, bh3)) | 0;
36834 lo = (lo + Math.imul(al7, bl4)) | 0;
36835 mid = (mid + Math.imul(al7, bh4)) | 0;
36836 mid = (mid + Math.imul(ah7, bl4)) | 0;
36837 hi = (hi + Math.imul(ah7, bh4)) | 0;
36838 lo = (lo + Math.imul(al6, bl5)) | 0;
36839 mid = (mid + Math.imul(al6, bh5)) | 0;
36840 mid = (mid + Math.imul(ah6, bl5)) | 0;
36841 hi = (hi + Math.imul(ah6, bh5)) | 0;
36842 lo = (lo + Math.imul(al5, bl6)) | 0;
36843 mid = (mid + Math.imul(al5, bh6)) | 0;
36844 mid = (mid + Math.imul(ah5, bl6)) | 0;
36845 hi = (hi + Math.imul(ah5, bh6)) | 0;
36846 lo = (lo + Math.imul(al4, bl7)) | 0;
36847 mid = (mid + Math.imul(al4, bh7)) | 0;
36848 mid = (mid + Math.imul(ah4, bl7)) | 0;
36849 hi = (hi + Math.imul(ah4, bh7)) | 0;
36850 lo = (lo + Math.imul(al3, bl8)) | 0;
36851 mid = (mid + Math.imul(al3, bh8)) | 0;
36852 mid = (mid + Math.imul(ah3, bl8)) | 0;
36853 hi = (hi + Math.imul(ah3, bh8)) | 0;
36854 lo = (lo + Math.imul(al2, bl9)) | 0;
36855 mid = (mid + Math.imul(al2, bh9)) | 0;
36856 mid = (mid + Math.imul(ah2, bl9)) | 0;
36857 hi = (hi + Math.imul(ah2, bh9)) | 0;
36858 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36859 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
36860 w11 &= 0x3ffffff;
36861 /* k = 12 */
36862 lo = Math.imul(al9, bl3);
36863 mid = Math.imul(al9, bh3);
36864 mid = (mid + Math.imul(ah9, bl3)) | 0;
36865 hi = Math.imul(ah9, bh3);
36866 lo = (lo + Math.imul(al8, bl4)) | 0;
36867 mid = (mid + Math.imul(al8, bh4)) | 0;
36868 mid = (mid + Math.imul(ah8, bl4)) | 0;
36869 hi = (hi + Math.imul(ah8, bh4)) | 0;
36870 lo = (lo + Math.imul(al7, bl5)) | 0;
36871 mid = (mid + Math.imul(al7, bh5)) | 0;
36872 mid = (mid + Math.imul(ah7, bl5)) | 0;
36873 hi = (hi + Math.imul(ah7, bh5)) | 0;
36874 lo = (lo + Math.imul(al6, bl6)) | 0;
36875 mid = (mid + Math.imul(al6, bh6)) | 0;
36876 mid = (mid + Math.imul(ah6, bl6)) | 0;
36877 hi = (hi + Math.imul(ah6, bh6)) | 0;
36878 lo = (lo + Math.imul(al5, bl7)) | 0;
36879 mid = (mid + Math.imul(al5, bh7)) | 0;
36880 mid = (mid + Math.imul(ah5, bl7)) | 0;
36881 hi = (hi + Math.imul(ah5, bh7)) | 0;
36882 lo = (lo + Math.imul(al4, bl8)) | 0;
36883 mid = (mid + Math.imul(al4, bh8)) | 0;
36884 mid = (mid + Math.imul(ah4, bl8)) | 0;
36885 hi = (hi + Math.imul(ah4, bh8)) | 0;
36886 lo = (lo + Math.imul(al3, bl9)) | 0;
36887 mid = (mid + Math.imul(al3, bh9)) | 0;
36888 mid = (mid + Math.imul(ah3, bl9)) | 0;
36889 hi = (hi + Math.imul(ah3, bh9)) | 0;
36890 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36891 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
36892 w12 &= 0x3ffffff;
36893 /* k = 13 */
36894 lo = Math.imul(al9, bl4);
36895 mid = Math.imul(al9, bh4);
36896 mid = (mid + Math.imul(ah9, bl4)) | 0;
36897 hi = Math.imul(ah9, bh4);
36898 lo = (lo + Math.imul(al8, bl5)) | 0;
36899 mid = (mid + Math.imul(al8, bh5)) | 0;
36900 mid = (mid + Math.imul(ah8, bl5)) | 0;
36901 hi = (hi + Math.imul(ah8, bh5)) | 0;
36902 lo = (lo + Math.imul(al7, bl6)) | 0;
36903 mid = (mid + Math.imul(al7, bh6)) | 0;
36904 mid = (mid + Math.imul(ah7, bl6)) | 0;
36905 hi = (hi + Math.imul(ah7, bh6)) | 0;
36906 lo = (lo + Math.imul(al6, bl7)) | 0;
36907 mid = (mid + Math.imul(al6, bh7)) | 0;
36908 mid = (mid + Math.imul(ah6, bl7)) | 0;
36909 hi = (hi + Math.imul(ah6, bh7)) | 0;
36910 lo = (lo + Math.imul(al5, bl8)) | 0;
36911 mid = (mid + Math.imul(al5, bh8)) | 0;
36912 mid = (mid + Math.imul(ah5, bl8)) | 0;
36913 hi = (hi + Math.imul(ah5, bh8)) | 0;
36914 lo = (lo + Math.imul(al4, bl9)) | 0;
36915 mid = (mid + Math.imul(al4, bh9)) | 0;
36916 mid = (mid + Math.imul(ah4, bl9)) | 0;
36917 hi = (hi + Math.imul(ah4, bh9)) | 0;
36918 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36919 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
36920 w13 &= 0x3ffffff;
36921 /* k = 14 */
36922 lo = Math.imul(al9, bl5);
36923 mid = Math.imul(al9, bh5);
36924 mid = (mid + Math.imul(ah9, bl5)) | 0;
36925 hi = Math.imul(ah9, bh5);
36926 lo = (lo + Math.imul(al8, bl6)) | 0;
36927 mid = (mid + Math.imul(al8, bh6)) | 0;
36928 mid = (mid + Math.imul(ah8, bl6)) | 0;
36929 hi = (hi + Math.imul(ah8, bh6)) | 0;
36930 lo = (lo + Math.imul(al7, bl7)) | 0;
36931 mid = (mid + Math.imul(al7, bh7)) | 0;
36932 mid = (mid + Math.imul(ah7, bl7)) | 0;
36933 hi = (hi + Math.imul(ah7, bh7)) | 0;
36934 lo = (lo + Math.imul(al6, bl8)) | 0;
36935 mid = (mid + Math.imul(al6, bh8)) | 0;
36936 mid = (mid + Math.imul(ah6, bl8)) | 0;
36937 hi = (hi + Math.imul(ah6, bh8)) | 0;
36938 lo = (lo + Math.imul(al5, bl9)) | 0;
36939 mid = (mid + Math.imul(al5, bh9)) | 0;
36940 mid = (mid + Math.imul(ah5, bl9)) | 0;
36941 hi = (hi + Math.imul(ah5, bh9)) | 0;
36942 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36943 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
36944 w14 &= 0x3ffffff;
36945 /* k = 15 */
36946 lo = Math.imul(al9, bl6);
36947 mid = Math.imul(al9, bh6);
36948 mid = (mid + Math.imul(ah9, bl6)) | 0;
36949 hi = Math.imul(ah9, bh6);
36950 lo = (lo + Math.imul(al8, bl7)) | 0;
36951 mid = (mid + Math.imul(al8, bh7)) | 0;
36952 mid = (mid + Math.imul(ah8, bl7)) | 0;
36953 hi = (hi + Math.imul(ah8, bh7)) | 0;
36954 lo = (lo + Math.imul(al7, bl8)) | 0;
36955 mid = (mid + Math.imul(al7, bh8)) | 0;
36956 mid = (mid + Math.imul(ah7, bl8)) | 0;
36957 hi = (hi + Math.imul(ah7, bh8)) | 0;
36958 lo = (lo + Math.imul(al6, bl9)) | 0;
36959 mid = (mid + Math.imul(al6, bh9)) | 0;
36960 mid = (mid + Math.imul(ah6, bl9)) | 0;
36961 hi = (hi + Math.imul(ah6, bh9)) | 0;
36962 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36963 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
36964 w15 &= 0x3ffffff;
36965 /* k = 16 */
36966 lo = Math.imul(al9, bl7);
36967 mid = Math.imul(al9, bh7);
36968 mid = (mid + Math.imul(ah9, bl7)) | 0;
36969 hi = Math.imul(ah9, bh7);
36970 lo = (lo + Math.imul(al8, bl8)) | 0;
36971 mid = (mid + Math.imul(al8, bh8)) | 0;
36972 mid = (mid + Math.imul(ah8, bl8)) | 0;
36973 hi = (hi + Math.imul(ah8, bh8)) | 0;
36974 lo = (lo + Math.imul(al7, bl9)) | 0;
36975 mid = (mid + Math.imul(al7, bh9)) | 0;
36976 mid = (mid + Math.imul(ah7, bl9)) | 0;
36977 hi = (hi + Math.imul(ah7, bh9)) | 0;
36978 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36979 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
36980 w16 &= 0x3ffffff;
36981 /* k = 17 */
36982 lo = Math.imul(al9, bl8);
36983 mid = Math.imul(al9, bh8);
36984 mid = (mid + Math.imul(ah9, bl8)) | 0;
36985 hi = Math.imul(ah9, bh8);
36986 lo = (lo + Math.imul(al8, bl9)) | 0;
36987 mid = (mid + Math.imul(al8, bh9)) | 0;
36988 mid = (mid + Math.imul(ah8, bl9)) | 0;
36989 hi = (hi + Math.imul(ah8, bh9)) | 0;
36990 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36991 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
36992 w17 &= 0x3ffffff;
36993 /* k = 18 */
36994 lo = Math.imul(al9, bl9);
36995 mid = Math.imul(al9, bh9);
36996 mid = (mid + Math.imul(ah9, bl9)) | 0;
36997 hi = Math.imul(ah9, bh9);
36998 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36999 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
37000 w18 &= 0x3ffffff;
37001 o[0] = w0;
37002 o[1] = w1;
37003 o[2] = w2;
37004 o[3] = w3;
37005 o[4] = w4;
37006 o[5] = w5;
37007 o[6] = w6;
37008 o[7] = w7;
37009 o[8] = w8;
37010 o[9] = w9;
37011 o[10] = w10;
37012 o[11] = w11;
37013 o[12] = w12;
37014 o[13] = w13;
37015 o[14] = w14;
37016 o[15] = w15;
37017 o[16] = w16;
37018 o[17] = w17;
37019 o[18] = w18;
37020 if (c !== 0) {
37021 o[19] = c;
37022 out.length++;
37023 }
37024 return out;
37025 };
37026
37027 // Polyfill comb
37028 if (!Math.imul) {
37029 comb10MulTo = smallMulTo;
37030 }
37031
37032 function bigMulTo (self, num, out) {
37033 out.negative = num.negative ^ self.negative;
37034 out.length = self.length + num.length;
37035
37036 var carry = 0;
37037 var hncarry = 0;
37038 for (var k = 0; k < out.length - 1; k++) {
37039 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
37040 // note that ncarry could be >= 0x3ffffff
37041 var ncarry = hncarry;
37042 hncarry = 0;
37043 var rword = carry & 0x3ffffff;
37044 var maxJ = Math.min(k, num.length - 1);
37045 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
37046 var i = k - j;
37047 var a = self.words[i] | 0;
37048 var b = num.words[j] | 0;
37049 var r = a * b;
37050
37051 var lo = r & 0x3ffffff;
37052 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
37053 lo = (lo + rword) | 0;
37054 rword = lo & 0x3ffffff;
37055 ncarry = (ncarry + (lo >>> 26)) | 0;
37056
37057 hncarry += ncarry >>> 26;
37058 ncarry &= 0x3ffffff;
37059 }
37060 out.words[k] = rword;
37061 carry = ncarry;
37062 ncarry = hncarry;
37063 }
37064 if (carry !== 0) {
37065 out.words[k] = carry;
37066 } else {
37067 out.length--;
37068 }
37069
37070 return out.strip();
37071 }
37072
37073 function jumboMulTo (self, num, out) {
37074 var fftm = new FFTM();
37075 return fftm.mulp(self, num, out);
37076 }
37077
37078 BN.prototype.mulTo = function mulTo (num, out) {
37079 var res;
37080 var len = this.length + num.length;
37081 if (this.length === 10 && num.length === 10) {
37082 res = comb10MulTo(this, num, out);
37083 } else if (len < 63) {
37084 res = smallMulTo(this, num, out);
37085 } else if (len < 1024) {
37086 res = bigMulTo(this, num, out);
37087 } else {
37088 res = jumboMulTo(this, num, out);
37089 }
37090
37091 return res;
37092 };
37093
37094 // Cooley-Tukey algorithm for FFT
37095 // slightly revisited to rely on looping instead of recursion
37096
37097 function FFTM (x, y) {
37098 this.x = x;
37099 this.y = y;
37100 }
37101
37102 FFTM.prototype.makeRBT = function makeRBT (N) {
37103 var t = new Array(N);
37104 var l = BN.prototype._countBits(N) - 1;
37105 for (var i = 0; i < N; i++) {
37106 t[i] = this.revBin(i, l, N);
37107 }
37108
37109 return t;
37110 };
37111
37112 // Returns binary-reversed representation of `x`
37113 FFTM.prototype.revBin = function revBin (x, l, N) {
37114 if (x === 0 || x === N - 1) return x;
37115
37116 var rb = 0;
37117 for (var i = 0; i < l; i++) {
37118 rb |= (x & 1) << (l - i - 1);
37119 x >>= 1;
37120 }
37121
37122 return rb;
37123 };
37124
37125 // Performs "tweedling" phase, therefore 'emulating'
37126 // behaviour of the recursive algorithm
37127 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
37128 for (var i = 0; i < N; i++) {
37129 rtws[i] = rws[rbt[i]];
37130 itws[i] = iws[rbt[i]];
37131 }
37132 };
37133
37134 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
37135 this.permute(rbt, rws, iws, rtws, itws, N);
37136
37137 for (var s = 1; s < N; s <<= 1) {
37138 var l = s << 1;
37139
37140 var rtwdf = Math.cos(2 * Math.PI / l);
37141 var itwdf = Math.sin(2 * Math.PI / l);
37142
37143 for (var p = 0; p < N; p += l) {
37144 var rtwdf_ = rtwdf;
37145 var itwdf_ = itwdf;
37146
37147 for (var j = 0; j < s; j++) {
37148 var re = rtws[p + j];
37149 var ie = itws[p + j];
37150
37151 var ro = rtws[p + j + s];
37152 var io = itws[p + j + s];
37153
37154 var rx = rtwdf_ * ro - itwdf_ * io;
37155
37156 io = rtwdf_ * io + itwdf_ * ro;
37157 ro = rx;
37158
37159 rtws[p + j] = re + ro;
37160 itws[p + j] = ie + io;
37161
37162 rtws[p + j + s] = re - ro;
37163 itws[p + j + s] = ie - io;
37164
37165 /* jshint maxdepth : false */
37166 if (j !== l) {
37167 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
37168
37169 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
37170 rtwdf_ = rx;
37171 }
37172 }
37173 }
37174 }
37175 };
37176
37177 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
37178 var N = Math.max(m, n) | 1;
37179 var odd = N & 1;
37180 var i = 0;
37181 for (N = N / 2 | 0; N; N = N >>> 1) {
37182 i++;
37183 }
37184
37185 return 1 << i + 1 + odd;
37186 };
37187
37188 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
37189 if (N <= 1) return;
37190
37191 for (var i = 0; i < N / 2; i++) {
37192 var t = rws[i];
37193
37194 rws[i] = rws[N - i - 1];
37195 rws[N - i - 1] = t;
37196
37197 t = iws[i];
37198
37199 iws[i] = -iws[N - i - 1];
37200 iws[N - i - 1] = -t;
37201 }
37202 };
37203
37204 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
37205 var carry = 0;
37206 for (var i = 0; i < N / 2; i++) {
37207 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
37208 Math.round(ws[2 * i] / N) +
37209 carry;
37210
37211 ws[i] = w & 0x3ffffff;
37212
37213 if (w < 0x4000000) {
37214 carry = 0;
37215 } else {
37216 carry = w / 0x4000000 | 0;
37217 }
37218 }
37219
37220 return ws;
37221 };
37222
37223 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
37224 var carry = 0;
37225 for (var i = 0; i < len; i++) {
37226 carry = carry + (ws[i] | 0);
37227
37228 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
37229 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
37230 }
37231
37232 // Pad with zeroes
37233 for (i = 2 * len; i < N; ++i) {
37234 rws[i] = 0;
37235 }
37236
37237 assert(carry === 0);
37238 assert((carry & ~0x1fff) === 0);
37239 };
37240
37241 FFTM.prototype.stub = function stub (N) {
37242 var ph = new Array(N);
37243 for (var i = 0; i < N; i++) {
37244 ph[i] = 0;
37245 }
37246
37247 return ph;
37248 };
37249
37250 FFTM.prototype.mulp = function mulp (x, y, out) {
37251 var N = 2 * this.guessLen13b(x.length, y.length);
37252
37253 var rbt = this.makeRBT(N);
37254
37255 var _ = this.stub(N);
37256
37257 var rws = new Array(N);
37258 var rwst = new Array(N);
37259 var iwst = new Array(N);
37260
37261 var nrws = new Array(N);
37262 var nrwst = new Array(N);
37263 var niwst = new Array(N);
37264
37265 var rmws = out.words;
37266 rmws.length = N;
37267
37268 this.convert13b(x.words, x.length, rws, N);
37269 this.convert13b(y.words, y.length, nrws, N);
37270
37271 this.transform(rws, _, rwst, iwst, N, rbt);
37272 this.transform(nrws, _, nrwst, niwst, N, rbt);
37273
37274 for (var i = 0; i < N; i++) {
37275 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
37276 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
37277 rwst[i] = rx;
37278 }
37279
37280 this.conjugate(rwst, iwst, N);
37281 this.transform(rwst, iwst, rmws, _, N, rbt);
37282 this.conjugate(rmws, _, N);
37283 this.normalize13b(rmws, N);
37284
37285 out.negative = x.negative ^ y.negative;
37286 out.length = x.length + y.length;
37287 return out.strip();
37288 };
37289
37290 // Multiply `this` by `num`
37291 BN.prototype.mul = function mul (num) {
37292 var out = new BN(null);
37293 out.words = new Array(this.length + num.length);
37294 return this.mulTo(num, out);
37295 };
37296
37297 // Multiply employing FFT
37298 BN.prototype.mulf = function mulf (num) {
37299 var out = new BN(null);
37300 out.words = new Array(this.length + num.length);
37301 return jumboMulTo(this, num, out);
37302 };
37303
37304 // In-place Multiplication
37305 BN.prototype.imul = function imul (num) {
37306 return this.clone().mulTo(num, this);
37307 };
37308
37309 BN.prototype.imuln = function imuln (num) {
37310 assert(typeof num === 'number');
37311 assert(num < 0x4000000);
37312
37313 // Carry
37314 var carry = 0;
37315 for (var i = 0; i < this.length; i++) {
37316 var w = (this.words[i] | 0) * num;
37317 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
37318 carry >>= 26;
37319 carry += (w / 0x4000000) | 0;
37320 // NOTE: lo is 27bit maximum
37321 carry += lo >>> 26;
37322 this.words[i] = lo & 0x3ffffff;
37323 }
37324
37325 if (carry !== 0) {
37326 this.words[i] = carry;
37327 this.length++;
37328 }
37329
37330 return this;
37331 };
37332
37333 BN.prototype.muln = function muln (num) {
37334 return this.clone().imuln(num);
37335 };
37336
37337 // `this` * `this`
37338 BN.prototype.sqr = function sqr () {
37339 return this.mul(this);
37340 };
37341
37342 // `this` * `this` in-place
37343 BN.prototype.isqr = function isqr () {
37344 return this.imul(this.clone());
37345 };
37346
37347 // Math.pow(`this`, `num`)
37348 BN.prototype.pow = function pow (num) {
37349 var w = toBitArray(num);
37350 if (w.length === 0) return new BN(1);
37351
37352 // Skip leading zeroes
37353 var res = this;
37354 for (var i = 0; i < w.length; i++, res = res.sqr()) {
37355 if (w[i] !== 0) break;
37356 }
37357
37358 if (++i < w.length) {
37359 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
37360 if (w[i] === 0) continue;
37361
37362 res = res.mul(q);
37363 }
37364 }
37365
37366 return res;
37367 };
37368
37369 // Shift-left in-place
37370 BN.prototype.iushln = function iushln (bits) {
37371 assert(typeof bits === 'number' && bits >= 0);
37372 var r = bits % 26;
37373 var s = (bits - r) / 26;
37374 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
37375 var i;
37376
37377 if (r !== 0) {
37378 var carry = 0;
37379
37380 for (i = 0; i < this.length; i++) {
37381 var newCarry = this.words[i] & carryMask;
37382 var c = ((this.words[i] | 0) - newCarry) << r;
37383 this.words[i] = c | carry;
37384 carry = newCarry >>> (26 - r);
37385 }
37386
37387 if (carry) {
37388 this.words[i] = carry;
37389 this.length++;
37390 }
37391 }
37392
37393 if (s !== 0) {
37394 for (i = this.length - 1; i >= 0; i--) {
37395 this.words[i + s] = this.words[i];
37396 }
37397
37398 for (i = 0; i < s; i++) {
37399 this.words[i] = 0;
37400 }
37401
37402 this.length += s;
37403 }
37404
37405 return this.strip();
37406 };
37407
37408 BN.prototype.ishln = function ishln (bits) {
37409 // TODO(indutny): implement me
37410 assert(this.negative === 0);
37411 return this.iushln(bits);
37412 };
37413
37414 // Shift-right in-place
37415 // NOTE: `hint` is a lowest bit before trailing zeroes
37416 // NOTE: if `extended` is present - it will be filled with destroyed bits
37417 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
37418 assert(typeof bits === 'number' && bits >= 0);
37419 var h;
37420 if (hint) {
37421 h = (hint - (hint % 26)) / 26;
37422 } else {
37423 h = 0;
37424 }
37425
37426 var r = bits % 26;
37427 var s = Math.min((bits - r) / 26, this.length);
37428 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37429 var maskedWords = extended;
37430
37431 h -= s;
37432 h = Math.max(0, h);
37433
37434 // Extended mode, copy masked part
37435 if (maskedWords) {
37436 for (var i = 0; i < s; i++) {
37437 maskedWords.words[i] = this.words[i];
37438 }
37439 maskedWords.length = s;
37440 }
37441
37442 if (s === 0) ; else if (this.length > s) {
37443 this.length -= s;
37444 for (i = 0; i < this.length; i++) {
37445 this.words[i] = this.words[i + s];
37446 }
37447 } else {
37448 this.words[0] = 0;
37449 this.length = 1;
37450 }
37451
37452 var carry = 0;
37453 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
37454 var word = this.words[i] | 0;
37455 this.words[i] = (carry << (26 - r)) | (word >>> r);
37456 carry = word & mask;
37457 }
37458
37459 // Push carried bits as a mask
37460 if (maskedWords && carry !== 0) {
37461 maskedWords.words[maskedWords.length++] = carry;
37462 }
37463
37464 if (this.length === 0) {
37465 this.words[0] = 0;
37466 this.length = 1;
37467 }
37468
37469 return this.strip();
37470 };
37471
37472 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
37473 // TODO(indutny): implement me
37474 assert(this.negative === 0);
37475 return this.iushrn(bits, hint, extended);
37476 };
37477
37478 // Shift-left
37479 BN.prototype.shln = function shln (bits) {
37480 return this.clone().ishln(bits);
37481 };
37482
37483 BN.prototype.ushln = function ushln (bits) {
37484 return this.clone().iushln(bits);
37485 };
37486
37487 // Shift-right
37488 BN.prototype.shrn = function shrn (bits) {
37489 return this.clone().ishrn(bits);
37490 };
37491
37492 BN.prototype.ushrn = function ushrn (bits) {
37493 return this.clone().iushrn(bits);
37494 };
37495
37496 // Test if n bit is set
37497 BN.prototype.testn = function testn (bit) {
37498 assert(typeof bit === 'number' && bit >= 0);
37499 var r = bit % 26;
37500 var s = (bit - r) / 26;
37501 var q = 1 << r;
37502
37503 // Fast case: bit is much higher than all existing words
37504 if (this.length <= s) return false;
37505
37506 // Check bit and return
37507 var w = this.words[s];
37508
37509 return !!(w & q);
37510 };
37511
37512 // Return only lowers bits of number (in-place)
37513 BN.prototype.imaskn = function imaskn (bits) {
37514 assert(typeof bits === 'number' && bits >= 0);
37515 var r = bits % 26;
37516 var s = (bits - r) / 26;
37517
37518 assert(this.negative === 0, 'imaskn works only with positive numbers');
37519
37520 if (this.length <= s) {
37521 return this;
37522 }
37523
37524 if (r !== 0) {
37525 s++;
37526 }
37527 this.length = Math.min(s, this.length);
37528
37529 if (r !== 0) {
37530 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37531 this.words[this.length - 1] &= mask;
37532 }
37533
37534 return this.strip();
37535 };
37536
37537 // Return only lowers bits of number
37538 BN.prototype.maskn = function maskn (bits) {
37539 return this.clone().imaskn(bits);
37540 };
37541
37542 // Add plain number `num` to `this`
37543 BN.prototype.iaddn = function iaddn (num) {
37544 assert(typeof num === 'number');
37545 assert(num < 0x4000000);
37546 if (num < 0) return this.isubn(-num);
37547
37548 // Possible sign change
37549 if (this.negative !== 0) {
37550 if (this.length === 1 && (this.words[0] | 0) < num) {
37551 this.words[0] = num - (this.words[0] | 0);
37552 this.negative = 0;
37553 return this;
37554 }
37555
37556 this.negative = 0;
37557 this.isubn(num);
37558 this.negative = 1;
37559 return this;
37560 }
37561
37562 // Add without checks
37563 return this._iaddn(num);
37564 };
37565
37566 BN.prototype._iaddn = function _iaddn (num) {
37567 this.words[0] += num;
37568
37569 // Carry
37570 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
37571 this.words[i] -= 0x4000000;
37572 if (i === this.length - 1) {
37573 this.words[i + 1] = 1;
37574 } else {
37575 this.words[i + 1]++;
37576 }
37577 }
37578 this.length = Math.max(this.length, i + 1);
37579
37580 return this;
37581 };
37582
37583 // Subtract plain number `num` from `this`
37584 BN.prototype.isubn = function isubn (num) {
37585 assert(typeof num === 'number');
37586 assert(num < 0x4000000);
37587 if (num < 0) return this.iaddn(-num);
37588
37589 if (this.negative !== 0) {
37590 this.negative = 0;
37591 this.iaddn(num);
37592 this.negative = 1;
37593 return this;
37594 }
37595
37596 this.words[0] -= num;
37597
37598 if (this.length === 1 && this.words[0] < 0) {
37599 this.words[0] = -this.words[0];
37600 this.negative = 1;
37601 } else {
37602 // Carry
37603 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
37604 this.words[i] += 0x4000000;
37605 this.words[i + 1] -= 1;
37606 }
37607 }
37608
37609 return this.strip();
37610 };
37611
37612 BN.prototype.addn = function addn (num) {
37613 return this.clone().iaddn(num);
37614 };
37615
37616 BN.prototype.subn = function subn (num) {
37617 return this.clone().isubn(num);
37618 };
37619
37620 BN.prototype.iabs = function iabs () {
37621 this.negative = 0;
37622
37623 return this;
37624 };
37625
37626 BN.prototype.abs = function abs () {
37627 return this.clone().iabs();
37628 };
37629
37630 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
37631 var len = num.length + shift;
37632 var i;
37633
37634 this._expand(len);
37635
37636 var w;
37637 var carry = 0;
37638 for (i = 0; i < num.length; i++) {
37639 w = (this.words[i + shift] | 0) + carry;
37640 var right = (num.words[i] | 0) * mul;
37641 w -= right & 0x3ffffff;
37642 carry = (w >> 26) - ((right / 0x4000000) | 0);
37643 this.words[i + shift] = w & 0x3ffffff;
37644 }
37645 for (; i < this.length - shift; i++) {
37646 w = (this.words[i + shift] | 0) + carry;
37647 carry = w >> 26;
37648 this.words[i + shift] = w & 0x3ffffff;
37649 }
37650
37651 if (carry === 0) return this.strip();
37652
37653 // Subtraction overflow
37654 assert(carry === -1);
37655 carry = 0;
37656 for (i = 0; i < this.length; i++) {
37657 w = -(this.words[i] | 0) + carry;
37658 carry = w >> 26;
37659 this.words[i] = w & 0x3ffffff;
37660 }
37661 this.negative = 1;
37662
37663 return this.strip();
37664 };
37665
37666 BN.prototype._wordDiv = function _wordDiv (num, mode) {
37667 var shift = this.length - num.length;
37668
37669 var a = this.clone();
37670 var b = num;
37671
37672 // Normalize
37673 var bhi = b.words[b.length - 1] | 0;
37674 var bhiBits = this._countBits(bhi);
37675 shift = 26 - bhiBits;
37676 if (shift !== 0) {
37677 b = b.ushln(shift);
37678 a.iushln(shift);
37679 bhi = b.words[b.length - 1] | 0;
37680 }
37681
37682 // Initialize quotient
37683 var m = a.length - b.length;
37684 var q;
37685
37686 if (mode !== 'mod') {
37687 q = new BN(null);
37688 q.length = m + 1;
37689 q.words = new Array(q.length);
37690 for (var i = 0; i < q.length; i++) {
37691 q.words[i] = 0;
37692 }
37693 }
37694
37695 var diff = a.clone()._ishlnsubmul(b, 1, m);
37696 if (diff.negative === 0) {
37697 a = diff;
37698 if (q) {
37699 q.words[m] = 1;
37700 }
37701 }
37702
37703 for (var j = m - 1; j >= 0; j--) {
37704 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
37705 (a.words[b.length + j - 1] | 0);
37706
37707 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
37708 // (0x7ffffff)
37709 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
37710
37711 a._ishlnsubmul(b, qj, j);
37712 while (a.negative !== 0) {
37713 qj--;
37714 a.negative = 0;
37715 a._ishlnsubmul(b, 1, j);
37716 if (!a.isZero()) {
37717 a.negative ^= 1;
37718 }
37719 }
37720 if (q) {
37721 q.words[j] = qj;
37722 }
37723 }
37724 if (q) {
37725 q.strip();
37726 }
37727 a.strip();
37728
37729 // Denormalize
37730 if (mode !== 'div' && shift !== 0) {
37731 a.iushrn(shift);
37732 }
37733
37734 return {
37735 div: q || null,
37736 mod: a
37737 };
37738 };
37739
37740 // NOTE: 1) `mode` can be set to `mod` to request mod only,
37741 // to `div` to request div only, or be absent to
37742 // request both div & mod
37743 // 2) `positive` is true if unsigned mod is requested
37744 BN.prototype.divmod = function divmod (num, mode, positive) {
37745 assert(!num.isZero());
37746
37747 if (this.isZero()) {
37748 return {
37749 div: new BN(0),
37750 mod: new BN(0)
37751 };
37752 }
37753
37754 var div, mod, res;
37755 if (this.negative !== 0 && num.negative === 0) {
37756 res = this.neg().divmod(num, mode);
37757
37758 if (mode !== 'mod') {
37759 div = res.div.neg();
37760 }
37761
37762 if (mode !== 'div') {
37763 mod = res.mod.neg();
37764 if (positive && mod.negative !== 0) {
37765 mod.iadd(num);
37766 }
37767 }
37768
37769 return {
37770 div: div,
37771 mod: mod
37772 };
37773 }
37774
37775 if (this.negative === 0 && num.negative !== 0) {
37776 res = this.divmod(num.neg(), mode);
37777
37778 if (mode !== 'mod') {
37779 div = res.div.neg();
37780 }
37781
37782 return {
37783 div: div,
37784 mod: res.mod
37785 };
37786 }
37787
37788 if ((this.negative & num.negative) !== 0) {
37789 res = this.neg().divmod(num.neg(), mode);
37790
37791 if (mode !== 'div') {
37792 mod = res.mod.neg();
37793 if (positive && mod.negative !== 0) {
37794 mod.isub(num);
37795 }
37796 }
37797
37798 return {
37799 div: res.div,
37800 mod: mod
37801 };
37802 }
37803
37804 // Both numbers are positive at this point
37805
37806 // Strip both numbers to approximate shift value
37807 if (num.length > this.length || this.cmp(num) < 0) {
37808 return {
37809 div: new BN(0),
37810 mod: this
37811 };
37812 }
37813
37814 // Very short reduction
37815 if (num.length === 1) {
37816 if (mode === 'div') {
37817 return {
37818 div: this.divn(num.words[0]),
37819 mod: null
37820 };
37821 }
37822
37823 if (mode === 'mod') {
37824 return {
37825 div: null,
37826 mod: new BN(this.modn(num.words[0]))
37827 };
37828 }
37829
37830 return {
37831 div: this.divn(num.words[0]),
37832 mod: new BN(this.modn(num.words[0]))
37833 };
37834 }
37835
37836 return this._wordDiv(num, mode);
37837 };
37838
37839 // Find `this` / `num`
37840 BN.prototype.div = function div (num) {
37841 return this.divmod(num, 'div', false).div;
37842 };
37843
37844 // Find `this` % `num`
37845 BN.prototype.mod = function mod (num) {
37846 return this.divmod(num, 'mod', false).mod;
37847 };
37848
37849 BN.prototype.umod = function umod (num) {
37850 return this.divmod(num, 'mod', true).mod;
37851 };
37852
37853 // Find Round(`this` / `num`)
37854 BN.prototype.divRound = function divRound (num) {
37855 var dm = this.divmod(num);
37856
37857 // Fast case - exact division
37858 if (dm.mod.isZero()) return dm.div;
37859
37860 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
37861
37862 var half = num.ushrn(1);
37863 var r2 = num.andln(1);
37864 var cmp = mod.cmp(half);
37865
37866 // Round down
37867 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
37868
37869 // Round up
37870 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
37871 };
37872
37873 BN.prototype.modn = function modn (num) {
37874 assert(num <= 0x3ffffff);
37875 var p = (1 << 26) % num;
37876
37877 var acc = 0;
37878 for (var i = this.length - 1; i >= 0; i--) {
37879 acc = (p * acc + (this.words[i] | 0)) % num;
37880 }
37881
37882 return acc;
37883 };
37884
37885 // In-place division by number
37886 BN.prototype.idivn = function idivn (num) {
37887 assert(num <= 0x3ffffff);
37888
37889 var carry = 0;
37890 for (var i = this.length - 1; i >= 0; i--) {
37891 var w = (this.words[i] | 0) + carry * 0x4000000;
37892 this.words[i] = (w / num) | 0;
37893 carry = w % num;
37894 }
37895
37896 return this.strip();
37897 };
37898
37899 BN.prototype.divn = function divn (num) {
37900 return this.clone().idivn(num);
37901 };
37902
37903 BN.prototype.egcd = function egcd (p) {
37904 assert(p.negative === 0);
37905 assert(!p.isZero());
37906
37907 var x = this;
37908 var y = p.clone();
37909
37910 if (x.negative !== 0) {
37911 x = x.umod(p);
37912 } else {
37913 x = x.clone();
37914 }
37915
37916 // A * x + B * y = x
37917 var A = new BN(1);
37918 var B = new BN(0);
37919
37920 // C * x + D * y = y
37921 var C = new BN(0);
37922 var D = new BN(1);
37923
37924 var g = 0;
37925
37926 while (x.isEven() && y.isEven()) {
37927 x.iushrn(1);
37928 y.iushrn(1);
37929 ++g;
37930 }
37931
37932 var yp = y.clone();
37933 var xp = x.clone();
37934
37935 while (!x.isZero()) {
37936 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
37937 if (i > 0) {
37938 x.iushrn(i);
37939 while (i-- > 0) {
37940 if (A.isOdd() || B.isOdd()) {
37941 A.iadd(yp);
37942 B.isub(xp);
37943 }
37944
37945 A.iushrn(1);
37946 B.iushrn(1);
37947 }
37948 }
37949
37950 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
37951 if (j > 0) {
37952 y.iushrn(j);
37953 while (j-- > 0) {
37954 if (C.isOdd() || D.isOdd()) {
37955 C.iadd(yp);
37956 D.isub(xp);
37957 }
37958
37959 C.iushrn(1);
37960 D.iushrn(1);
37961 }
37962 }
37963
37964 if (x.cmp(y) >= 0) {
37965 x.isub(y);
37966 A.isub(C);
37967 B.isub(D);
37968 } else {
37969 y.isub(x);
37970 C.isub(A);
37971 D.isub(B);
37972 }
37973 }
37974
37975 return {
37976 a: C,
37977 b: D,
37978 gcd: y.iushln(g)
37979 };
37980 };
37981
37982 // This is reduced incarnation of the binary EEA
37983 // above, designated to invert members of the
37984 // _prime_ fields F(p) at a maximal speed
37985 BN.prototype._invmp = function _invmp (p) {
37986 assert(p.negative === 0);
37987 assert(!p.isZero());
37988
37989 var a = this;
37990 var b = p.clone();
37991
37992 if (a.negative !== 0) {
37993 a = a.umod(p);
37994 } else {
37995 a = a.clone();
37996 }
37997
37998 var x1 = new BN(1);
37999 var x2 = new BN(0);
38000
38001 var delta = b.clone();
38002
38003 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
38004 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
38005 if (i > 0) {
38006 a.iushrn(i);
38007 while (i-- > 0) {
38008 if (x1.isOdd()) {
38009 x1.iadd(delta);
38010 }
38011
38012 x1.iushrn(1);
38013 }
38014 }
38015
38016 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
38017 if (j > 0) {
38018 b.iushrn(j);
38019 while (j-- > 0) {
38020 if (x2.isOdd()) {
38021 x2.iadd(delta);
38022 }
38023
38024 x2.iushrn(1);
38025 }
38026 }
38027
38028 if (a.cmp(b) >= 0) {
38029 a.isub(b);
38030 x1.isub(x2);
38031 } else {
38032 b.isub(a);
38033 x2.isub(x1);
38034 }
38035 }
38036
38037 var res;
38038 if (a.cmpn(1) === 0) {
38039 res = x1;
38040 } else {
38041 res = x2;
38042 }
38043
38044 if (res.cmpn(0) < 0) {
38045 res.iadd(p);
38046 }
38047
38048 return res;
38049 };
38050
38051 BN.prototype.gcd = function gcd (num) {
38052 if (this.isZero()) return num.abs();
38053 if (num.isZero()) return this.abs();
38054
38055 var a = this.clone();
38056 var b = num.clone();
38057 a.negative = 0;
38058 b.negative = 0;
38059
38060 // Remove common factor of two
38061 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
38062 a.iushrn(1);
38063 b.iushrn(1);
38064 }
38065
38066 do {
38067 while (a.isEven()) {
38068 a.iushrn(1);
38069 }
38070 while (b.isEven()) {
38071 b.iushrn(1);
38072 }
38073
38074 var r = a.cmp(b);
38075 if (r < 0) {
38076 // Swap `a` and `b` to make `a` always bigger than `b`
38077 var t = a;
38078 a = b;
38079 b = t;
38080 } else if (r === 0 || b.cmpn(1) === 0) {
38081 break;
38082 }
38083
38084 a.isub(b);
38085 } while (true);
38086
38087 return b.iushln(shift);
38088 };
38089
38090 // Invert number in the field F(num)
38091 BN.prototype.invm = function invm (num) {
38092 return this.egcd(num).a.umod(num);
38093 };
38094
38095 BN.prototype.isEven = function isEven () {
38096 return (this.words[0] & 1) === 0;
38097 };
38098
38099 BN.prototype.isOdd = function isOdd () {
38100 return (this.words[0] & 1) === 1;
38101 };
38102
38103 // And first word and num
38104 BN.prototype.andln = function andln (num) {
38105 return this.words[0] & num;
38106 };
38107
38108 // Increment at the bit position in-line
38109 BN.prototype.bincn = function bincn (bit) {
38110 assert(typeof bit === 'number');
38111 var r = bit % 26;
38112 var s = (bit - r) / 26;
38113 var q = 1 << r;
38114
38115 // Fast case: bit is much higher than all existing words
38116 if (this.length <= s) {
38117 this._expand(s + 1);
38118 this.words[s] |= q;
38119 return this;
38120 }
38121
38122 // Add bit and propagate, if needed
38123 var carry = q;
38124 for (var i = s; carry !== 0 && i < this.length; i++) {
38125 var w = this.words[i] | 0;
38126 w += carry;
38127 carry = w >>> 26;
38128 w &= 0x3ffffff;
38129 this.words[i] = w;
38130 }
38131 if (carry !== 0) {
38132 this.words[i] = carry;
38133 this.length++;
38134 }
38135 return this;
38136 };
38137
38138 BN.prototype.isZero = function isZero () {
38139 return this.length === 1 && this.words[0] === 0;
38140 };
38141
38142 BN.prototype.cmpn = function cmpn (num) {
38143 var negative = num < 0;
38144
38145 if (this.negative !== 0 && !negative) return -1;
38146 if (this.negative === 0 && negative) return 1;
38147
38148 this.strip();
38149
38150 var res;
38151 if (this.length > 1) {
38152 res = 1;
38153 } else {
38154 if (negative) {
38155 num = -num;
38156 }
38157
38158 assert(num <= 0x3ffffff, 'Number is too big');
38159
38160 var w = this.words[0] | 0;
38161 res = w === num ? 0 : w < num ? -1 : 1;
38162 }
38163 if (this.negative !== 0) return -res | 0;
38164 return res;
38165 };
38166
38167 // Compare two numbers and return:
38168 // 1 - if `this` > `num`
38169 // 0 - if `this` == `num`
38170 // -1 - if `this` < `num`
38171 BN.prototype.cmp = function cmp (num) {
38172 if (this.negative !== 0 && num.negative === 0) return -1;
38173 if (this.negative === 0 && num.negative !== 0) return 1;
38174
38175 var res = this.ucmp(num);
38176 if (this.negative !== 0) return -res | 0;
38177 return res;
38178 };
38179
38180 // Unsigned comparison
38181 BN.prototype.ucmp = function ucmp (num) {
38182 // At this point both numbers have the same sign
38183 if (this.length > num.length) return 1;
38184 if (this.length < num.length) return -1;
38185
38186 var res = 0;
38187 for (var i = this.length - 1; i >= 0; i--) {
38188 var a = this.words[i] | 0;
38189 var b = num.words[i] | 0;
38190
38191 if (a === b) continue;
38192 if (a < b) {
38193 res = -1;
38194 } else if (a > b) {
38195 res = 1;
38196 }
38197 break;
38198 }
38199 return res;
38200 };
38201
38202 BN.prototype.gtn = function gtn (num) {
38203 return this.cmpn(num) === 1;
38204 };
38205
38206 BN.prototype.gt = function gt (num) {
38207 return this.cmp(num) === 1;
38208 };
38209
38210 BN.prototype.gten = function gten (num) {
38211 return this.cmpn(num) >= 0;
38212 };
38213
38214 BN.prototype.gte = function gte (num) {
38215 return this.cmp(num) >= 0;
38216 };
38217
38218 BN.prototype.ltn = function ltn (num) {
38219 return this.cmpn(num) === -1;
38220 };
38221
38222 BN.prototype.lt = function lt (num) {
38223 return this.cmp(num) === -1;
38224 };
38225
38226 BN.prototype.lten = function lten (num) {
38227 return this.cmpn(num) <= 0;
38228 };
38229
38230 BN.prototype.lte = function lte (num) {
38231 return this.cmp(num) <= 0;
38232 };
38233
38234 BN.prototype.eqn = function eqn (num) {
38235 return this.cmpn(num) === 0;
38236 };
38237
38238 BN.prototype.eq = function eq (num) {
38239 return this.cmp(num) === 0;
38240 };
38241
38242 //
38243 // A reduce context, could be using montgomery or something better, depending
38244 // on the `m` itself.
38245 //
38246 BN.red = function red (num) {
38247 return new Red(num);
38248 };
38249
38250 BN.prototype.toRed = function toRed (ctx) {
38251 assert(!this.red, 'Already a number in reduction context');
38252 assert(this.negative === 0, 'red works only with positives');
38253 return ctx.convertTo(this)._forceRed(ctx);
38254 };
38255
38256 BN.prototype.fromRed = function fromRed () {
38257 assert(this.red, 'fromRed works only with numbers in reduction context');
38258 return this.red.convertFrom(this);
38259 };
38260
38261 BN.prototype._forceRed = function _forceRed (ctx) {
38262 this.red = ctx;
38263 return this;
38264 };
38265
38266 BN.prototype.forceRed = function forceRed (ctx) {
38267 assert(!this.red, 'Already a number in reduction context');
38268 return this._forceRed(ctx);
38269 };
38270
38271 BN.prototype.redAdd = function redAdd (num) {
38272 assert(this.red, 'redAdd works only with red numbers');
38273 return this.red.add(this, num);
38274 };
38275
38276 BN.prototype.redIAdd = function redIAdd (num) {
38277 assert(this.red, 'redIAdd works only with red numbers');
38278 return this.red.iadd(this, num);
38279 };
38280
38281 BN.prototype.redSub = function redSub (num) {
38282 assert(this.red, 'redSub works only with red numbers');
38283 return this.red.sub(this, num);
38284 };
38285
38286 BN.prototype.redISub = function redISub (num) {
38287 assert(this.red, 'redISub works only with red numbers');
38288 return this.red.isub(this, num);
38289 };
38290
38291 BN.prototype.redShl = function redShl (num) {
38292 assert(this.red, 'redShl works only with red numbers');
38293 return this.red.shl(this, num);
38294 };
38295
38296 BN.prototype.redMul = function redMul (num) {
38297 assert(this.red, 'redMul works only with red numbers');
38298 this.red._verify2(this, num);
38299 return this.red.mul(this, num);
38300 };
38301
38302 BN.prototype.redIMul = function redIMul (num) {
38303 assert(this.red, 'redMul works only with red numbers');
38304 this.red._verify2(this, num);
38305 return this.red.imul(this, num);
38306 };
38307
38308 BN.prototype.redSqr = function redSqr () {
38309 assert(this.red, 'redSqr works only with red numbers');
38310 this.red._verify1(this);
38311 return this.red.sqr(this);
38312 };
38313
38314 BN.prototype.redISqr = function redISqr () {
38315 assert(this.red, 'redISqr works only with red numbers');
38316 this.red._verify1(this);
38317 return this.red.isqr(this);
38318 };
38319
38320 // Square root over p
38321 BN.prototype.redSqrt = function redSqrt () {
38322 assert(this.red, 'redSqrt works only with red numbers');
38323 this.red._verify1(this);
38324 return this.red.sqrt(this);
38325 };
38326
38327 BN.prototype.redInvm = function redInvm () {
38328 assert(this.red, 'redInvm works only with red numbers');
38329 this.red._verify1(this);
38330 return this.red.invm(this);
38331 };
38332
38333 // Return negative clone of `this` % `red modulo`
38334 BN.prototype.redNeg = function redNeg () {
38335 assert(this.red, 'redNeg works only with red numbers');
38336 this.red._verify1(this);
38337 return this.red.neg(this);
38338 };
38339
38340 BN.prototype.redPow = function redPow (num) {
38341 assert(this.red && !num.red, 'redPow(normalNum)');
38342 this.red._verify1(this);
38343 return this.red.pow(this, num);
38344 };
38345
38346 // Prime numbers with efficient reduction
38347 var primes = {
38348 k256: null,
38349 p224: null,
38350 p192: null,
38351 p25519: null
38352 };
38353
38354 // Pseudo-Mersenne prime
38355 function MPrime (name, p) {
38356 // P = 2 ^ N - K
38357 this.name = name;
38358 this.p = new BN(p, 16);
38359 this.n = this.p.bitLength();
38360 this.k = new BN(1).iushln(this.n).isub(this.p);
38361
38362 this.tmp = this._tmp();
38363 }
38364
38365 MPrime.prototype._tmp = function _tmp () {
38366 var tmp = new BN(null);
38367 tmp.words = new Array(Math.ceil(this.n / 13));
38368 return tmp;
38369 };
38370
38371 MPrime.prototype.ireduce = function ireduce (num) {
38372 // Assumes that `num` is less than `P^2`
38373 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
38374 var r = num;
38375 var rlen;
38376
38377 do {
38378 this.split(r, this.tmp);
38379 r = this.imulK(r);
38380 r = r.iadd(this.tmp);
38381 rlen = r.bitLength();
38382 } while (rlen > this.n);
38383
38384 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
38385 if (cmp === 0) {
38386 r.words[0] = 0;
38387 r.length = 1;
38388 } else if (cmp > 0) {
38389 r.isub(this.p);
38390 } else {
38391 r.strip();
38392 }
38393
38394 return r;
38395 };
38396
38397 MPrime.prototype.split = function split (input, out) {
38398 input.iushrn(this.n, 0, out);
38399 };
38400
38401 MPrime.prototype.imulK = function imulK (num) {
38402 return num.imul(this.k);
38403 };
38404
38405 function K256 () {
38406 MPrime.call(
38407 this,
38408 'k256',
38409 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
38410 }
38411 inherits(K256, MPrime);
38412
38413 K256.prototype.split = function split (input, output) {
38414 // 256 = 9 * 26 + 22
38415 var mask = 0x3fffff;
38416
38417 var outLen = Math.min(input.length, 9);
38418 for (var i = 0; i < outLen; i++) {
38419 output.words[i] = input.words[i];
38420 }
38421 output.length = outLen;
38422
38423 if (input.length <= 9) {
38424 input.words[0] = 0;
38425 input.length = 1;
38426 return;
38427 }
38428
38429 // Shift by 9 limbs
38430 var prev = input.words[9];
38431 output.words[output.length++] = prev & mask;
38432
38433 for (i = 10; i < input.length; i++) {
38434 var next = input.words[i] | 0;
38435 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
38436 prev = next;
38437 }
38438 prev >>>= 22;
38439 input.words[i - 10] = prev;
38440 if (prev === 0 && input.length > 10) {
38441 input.length -= 10;
38442 } else {
38443 input.length -= 9;
38444 }
38445 };
38446
38447 K256.prototype.imulK = function imulK (num) {
38448 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
38449 num.words[num.length] = 0;
38450 num.words[num.length + 1] = 0;
38451 num.length += 2;
38452
38453 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
38454 var lo = 0;
38455 for (var i = 0; i < num.length; i++) {
38456 var w = num.words[i] | 0;
38457 lo += w * 0x3d1;
38458 num.words[i] = lo & 0x3ffffff;
38459 lo = w * 0x40 + ((lo / 0x4000000) | 0);
38460 }
38461
38462 // Fast length reduction
38463 if (num.words[num.length - 1] === 0) {
38464 num.length--;
38465 if (num.words[num.length - 1] === 0) {
38466 num.length--;
38467 }
38468 }
38469 return num;
38470 };
38471
38472 function P224 () {
38473 MPrime.call(
38474 this,
38475 'p224',
38476 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
38477 }
38478 inherits(P224, MPrime);
38479
38480 function P192 () {
38481 MPrime.call(
38482 this,
38483 'p192',
38484 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
38485 }
38486 inherits(P192, MPrime);
38487
38488 function P25519 () {
38489 // 2 ^ 255 - 19
38490 MPrime.call(
38491 this,
38492 '25519',
38493 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
38494 }
38495 inherits(P25519, MPrime);
38496
38497 P25519.prototype.imulK = function imulK (num) {
38498 // K = 0x13
38499 var carry = 0;
38500 for (var i = 0; i < num.length; i++) {
38501 var hi = (num.words[i] | 0) * 0x13 + carry;
38502 var lo = hi & 0x3ffffff;
38503 hi >>>= 26;
38504
38505 num.words[i] = lo;
38506 carry = hi;
38507 }
38508 if (carry !== 0) {
38509 num.words[num.length++] = carry;
38510 }
38511 return num;
38512 };
38513
38514 // Exported mostly for testing purposes, use plain name instead
38515 BN._prime = function prime (name) {
38516 // Cached version of prime
38517 if (primes[name]) return primes[name];
38518
38519 var prime;
38520 if (name === 'k256') {
38521 prime = new K256();
38522 } else if (name === 'p224') {
38523 prime = new P224();
38524 } else if (name === 'p192') {
38525 prime = new P192();
38526 } else if (name === 'p25519') {
38527 prime = new P25519();
38528 } else {
38529 throw new Error('Unknown prime ' + name);
38530 }
38531 primes[name] = prime;
38532
38533 return prime;
38534 };
38535
38536 //
38537 // Base reduction engine
38538 //
38539 function Red (m) {
38540 if (typeof m === 'string') {
38541 var prime = BN._prime(m);
38542 this.m = prime.p;
38543 this.prime = prime;
38544 } else {
38545 assert(m.gtn(1), 'modulus must be greater than 1');
38546 this.m = m;
38547 this.prime = null;
38548 }
38549 }
38550
38551 Red.prototype._verify1 = function _verify1 (a) {
38552 assert(a.negative === 0, 'red works only with positives');
38553 assert(a.red, 'red works only with red numbers');
38554 };
38555
38556 Red.prototype._verify2 = function _verify2 (a, b) {
38557 assert((a.negative | b.negative) === 0, 'red works only with positives');
38558 assert(a.red && a.red === b.red,
38559 'red works only with red numbers');
38560 };
38561
38562 Red.prototype.imod = function imod (a) {
38563 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
38564 return a.umod(this.m)._forceRed(this);
38565 };
38566
38567 Red.prototype.neg = function neg (a) {
38568 if (a.isZero()) {
38569 return a.clone();
38570 }
38571
38572 return this.m.sub(a)._forceRed(this);
38573 };
38574
38575 Red.prototype.add = function add (a, b) {
38576 this._verify2(a, b);
38577
38578 var res = a.add(b);
38579 if (res.cmp(this.m) >= 0) {
38580 res.isub(this.m);
38581 }
38582 return res._forceRed(this);
38583 };
38584
38585 Red.prototype.iadd = function iadd (a, b) {
38586 this._verify2(a, b);
38587
38588 var res = a.iadd(b);
38589 if (res.cmp(this.m) >= 0) {
38590 res.isub(this.m);
38591 }
38592 return res;
38593 };
38594
38595 Red.prototype.sub = function sub (a, b) {
38596 this._verify2(a, b);
38597
38598 var res = a.sub(b);
38599 if (res.cmpn(0) < 0) {
38600 res.iadd(this.m);
38601 }
38602 return res._forceRed(this);
38603 };
38604
38605 Red.prototype.isub = function isub (a, b) {
38606 this._verify2(a, b);
38607
38608 var res = a.isub(b);
38609 if (res.cmpn(0) < 0) {
38610 res.iadd(this.m);
38611 }
38612 return res;
38613 };
38614
38615 Red.prototype.shl = function shl (a, num) {
38616 this._verify1(a);
38617 return this.imod(a.ushln(num));
38618 };
38619
38620 Red.prototype.imul = function imul (a, b) {
38621 this._verify2(a, b);
38622 return this.imod(a.imul(b));
38623 };
38624
38625 Red.prototype.mul = function mul (a, b) {
38626 this._verify2(a, b);
38627 return this.imod(a.mul(b));
38628 };
38629
38630 Red.prototype.isqr = function isqr (a) {
38631 return this.imul(a, a.clone());
38632 };
38633
38634 Red.prototype.sqr = function sqr (a) {
38635 return this.mul(a, a);
38636 };
38637
38638 Red.prototype.sqrt = function sqrt (a) {
38639 if (a.isZero()) return a.clone();
38640
38641 var mod3 = this.m.andln(3);
38642 assert(mod3 % 2 === 1);
38643
38644 // Fast case
38645 if (mod3 === 3) {
38646 var pow = this.m.add(new BN(1)).iushrn(2);
38647 return this.pow(a, pow);
38648 }
38649
38650 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
38651 //
38652 // Find Q and S, that Q * 2 ^ S = (P - 1)
38653 var q = this.m.subn(1);
38654 var s = 0;
38655 while (!q.isZero() && q.andln(1) === 0) {
38656 s++;
38657 q.iushrn(1);
38658 }
38659 assert(!q.isZero());
38660
38661 var one = new BN(1).toRed(this);
38662 var nOne = one.redNeg();
38663
38664 // Find quadratic non-residue
38665 // NOTE: Max is such because of generalized Riemann hypothesis.
38666 var lpow = this.m.subn(1).iushrn(1);
38667 var z = this.m.bitLength();
38668 z = new BN(2 * z * z).toRed(this);
38669
38670 while (this.pow(z, lpow).cmp(nOne) !== 0) {
38671 z.redIAdd(nOne);
38672 }
38673
38674 var c = this.pow(z, q);
38675 var r = this.pow(a, q.addn(1).iushrn(1));
38676 var t = this.pow(a, q);
38677 var m = s;
38678 while (t.cmp(one) !== 0) {
38679 var tmp = t;
38680 for (var i = 0; tmp.cmp(one) !== 0; i++) {
38681 tmp = tmp.redSqr();
38682 }
38683 assert(i < m);
38684 var b = this.pow(c, new BN(1).iushln(m - i - 1));
38685
38686 r = r.redMul(b);
38687 c = b.redSqr();
38688 t = t.redMul(c);
38689 m = i;
38690 }
38691
38692 return r;
38693 };
38694
38695 Red.prototype.invm = function invm (a) {
38696 var inv = a._invmp(this.m);
38697 if (inv.negative !== 0) {
38698 inv.negative = 0;
38699 return this.imod(inv).redNeg();
38700 } else {
38701 return this.imod(inv);
38702 }
38703 };
38704
38705 Red.prototype.pow = function pow (a, num) {
38706 if (num.isZero()) return new BN(1).toRed(this);
38707 if (num.cmpn(1) === 0) return a.clone();
38708
38709 var windowSize = 4;
38710 var wnd = new Array(1 << windowSize);
38711 wnd[0] = new BN(1).toRed(this);
38712 wnd[1] = a;
38713 for (var i = 2; i < wnd.length; i++) {
38714 wnd[i] = this.mul(wnd[i - 1], a);
38715 }
38716
38717 var res = wnd[0];
38718 var current = 0;
38719 var currentLen = 0;
38720 var start = num.bitLength() % 26;
38721 if (start === 0) {
38722 start = 26;
38723 }
38724
38725 for (i = num.length - 1; i >= 0; i--) {
38726 var word = num.words[i];
38727 for (var j = start - 1; j >= 0; j--) {
38728 var bit = (word >> j) & 1;
38729 if (res !== wnd[0]) {
38730 res = this.sqr(res);
38731 }
38732
38733 if (bit === 0 && current === 0) {
38734 currentLen = 0;
38735 continue;
38736 }
38737
38738 current <<= 1;
38739 current |= bit;
38740 currentLen++;
38741 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
38742
38743 res = this.mul(res, wnd[current]);
38744 currentLen = 0;
38745 current = 0;
38746 }
38747 start = 26;
38748 }
38749
38750 return res;
38751 };
38752
38753 Red.prototype.convertTo = function convertTo (num) {
38754 var r = num.umod(this.m);
38755
38756 return r === num ? r.clone() : r;
38757 };
38758
38759 Red.prototype.convertFrom = function convertFrom (num) {
38760 var res = num.clone();
38761 res.red = null;
38762 return res;
38763 };
38764
38765 //
38766 // Montgomery method engine
38767 //
38768
38769 BN.mont = function mont (num) {
38770 return new Mont(num);
38771 };
38772
38773 function Mont (m) {
38774 Red.call(this, m);
38775
38776 this.shift = this.m.bitLength();
38777 if (this.shift % 26 !== 0) {
38778 this.shift += 26 - (this.shift % 26);
38779 }
38780
38781 this.r = new BN(1).iushln(this.shift);
38782 this.r2 = this.imod(this.r.sqr());
38783 this.rinv = this.r._invmp(this.m);
38784
38785 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
38786 this.minv = this.minv.umod(this.r);
38787 this.minv = this.r.sub(this.minv);
38788 }
38789 inherits(Mont, Red);
38790
38791 Mont.prototype.convertTo = function convertTo (num) {
38792 return this.imod(num.ushln(this.shift));
38793 };
38794
38795 Mont.prototype.convertFrom = function convertFrom (num) {
38796 var r = this.imod(num.mul(this.rinv));
38797 r.red = null;
38798 return r;
38799 };
38800
38801 Mont.prototype.imul = function imul (a, b) {
38802 if (a.isZero() || b.isZero()) {
38803 a.words[0] = 0;
38804 a.length = 1;
38805 return a;
38806 }
38807
38808 var t = a.imul(b);
38809 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38810 var u = t.isub(c).iushrn(this.shift);
38811 var res = u;
38812
38813 if (u.cmp(this.m) >= 0) {
38814 res = u.isub(this.m);
38815 } else if (u.cmpn(0) < 0) {
38816 res = u.iadd(this.m);
38817 }
38818
38819 return res._forceRed(this);
38820 };
38821
38822 Mont.prototype.mul = function mul (a, b) {
38823 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
38824
38825 var t = a.mul(b);
38826 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38827 var u = t.isub(c).iushrn(this.shift);
38828 var res = u;
38829 if (u.cmp(this.m) >= 0) {
38830 res = u.isub(this.m);
38831 } else if (u.cmpn(0) < 0) {
38832 res = u.iadd(this.m);
38833 }
38834
38835 return res._forceRed(this);
38836 };
38837
38838 Mont.prototype.invm = function invm (a) {
38839 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
38840 var res = this.imod(a._invmp(this.m).mul(this.r2));
38841 return res._forceRed(this);
38842 };
38843})(module, commonjsGlobal);
38844});
38845
38846var bn$1 = /*#__PURE__*/Object.freeze({
38847 __proto__: null,
38848 'default': bn,
38849 __moduleExports: bn
38850});
38851
38852/**
38853 * @fileoverview
38854 * BigInteger implementation of basic operations
38855 * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
38856 * @module biginteger/bn
38857 * @private
38858 */
38859
38860/**
38861 * @private
38862 */
38863class BigInteger$1 {
38864 /**
38865 * Get a BigInteger (input must be big endian for strings and arrays)
38866 * @param {Number|String|Uint8Array} n - Value to convert
38867 * @throws {Error} on undefined input
38868 */
38869 constructor(n) {
38870 if (n === undefined) {
38871 throw new Error('Invalid BigInteger input');
38872 }
38873
38874 this.value = new bn(n);
38875 }
38876
38877 clone() {
38878 const clone = new BigInteger$1(null);
38879 this.value.copy(clone.value);
38880 return clone;
38881 }
38882
38883 /**
38884 * BigInteger increment in place
38885 */
38886 iinc() {
38887 this.value.iadd(new bn(1));
38888 return this;
38889 }
38890
38891 /**
38892 * BigInteger increment
38893 * @returns {BigInteger} this + 1.
38894 */
38895 inc() {
38896 return this.clone().iinc();
38897 }
38898
38899 /**
38900 * BigInteger decrement in place
38901 */
38902 idec() {
38903 this.value.isub(new bn(1));
38904 return this;
38905 }
38906
38907 /**
38908 * BigInteger decrement
38909 * @returns {BigInteger} this - 1.
38910 */
38911 dec() {
38912 return this.clone().idec();
38913 }
38914
38915
38916 /**
38917 * BigInteger addition in place
38918 * @param {BigInteger} x - Value to add
38919 */
38920 iadd(x) {
38921 this.value.iadd(x.value);
38922 return this;
38923 }
38924
38925 /**
38926 * BigInteger addition
38927 * @param {BigInteger} x - Value to add
38928 * @returns {BigInteger} this + x.
38929 */
38930 add(x) {
38931 return this.clone().iadd(x);
38932 }
38933
38934 /**
38935 * BigInteger subtraction in place
38936 * @param {BigInteger} x - Value to subtract
38937 */
38938 isub(x) {
38939 this.value.isub(x.value);
38940 return this;
38941 }
38942
38943 /**
38944 * BigInteger subtraction
38945 * @param {BigInteger} x - Value to subtract
38946 * @returns {BigInteger} this - x.
38947 */
38948 sub(x) {
38949 return this.clone().isub(x);
38950 }
38951
38952 /**
38953 * BigInteger multiplication in place
38954 * @param {BigInteger} x - Value to multiply
38955 */
38956 imul(x) {
38957 this.value.imul(x.value);
38958 return this;
38959 }
38960
38961 /**
38962 * BigInteger multiplication
38963 * @param {BigInteger} x - Value to multiply
38964 * @returns {BigInteger} this * x.
38965 */
38966 mul(x) {
38967 return this.clone().imul(x);
38968 }
38969
38970 /**
38971 * Compute value modulo m, in place
38972 * @param {BigInteger} m - Modulo
38973 */
38974 imod(m) {
38975 this.value = this.value.umod(m.value);
38976 return this;
38977 }
38978
38979 /**
38980 * Compute value modulo m
38981 * @param {BigInteger} m - Modulo
38982 * @returns {BigInteger} this mod m.
38983 */
38984 mod(m) {
38985 return this.clone().imod(m);
38986 }
38987
38988 /**
38989 * Compute modular exponentiation
38990 * Much faster than this.exp(e).mod(n)
38991 * @param {BigInteger} e - Exponent
38992 * @param {BigInteger} n - Modulo
38993 * @returns {BigInteger} this ** e mod n.
38994 */
38995 modExp(e, n) {
38996 // We use either Montgomery or normal reduction context
38997 // Montgomery requires coprime n and R (montogmery multiplier)
38998 // bn.js picks R as power of 2, so n must be odd
38999 const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value);
39000 const x = this.clone();
39001 x.value = x.value.toRed(nred).redPow(e.value).fromRed();
39002 return x;
39003 }
39004
39005 /**
39006 * Compute the inverse of this value modulo n
39007 * Note: this and and n must be relatively prime
39008 * @param {BigInteger} n - Modulo
39009 * @returns {BigInteger} x such that this*x = 1 mod n
39010 * @throws {Error} if the inverse does not exist
39011 */
39012 modInv(n) {
39013 // invm returns a wrong result if the inverse does not exist
39014 if (!this.gcd(n).isOne()) {
39015 throw new Error('Inverse does not exist');
39016 }
39017 return new BigInteger$1(this.value.invm(n.value));
39018 }
39019
39020 /**
39021 * Compute greatest common divisor between this and n
39022 * @param {BigInteger} n - Operand
39023 * @returns {BigInteger} gcd
39024 */
39025 gcd(n) {
39026 return new BigInteger$1(this.value.gcd(n.value));
39027 }
39028
39029 /**
39030 * Shift this to the left by x, in place
39031 * @param {BigInteger} x - Shift value
39032 */
39033 ileftShift(x) {
39034 this.value.ishln(x.value.toNumber());
39035 return this;
39036 }
39037
39038 /**
39039 * Shift this to the left by x
39040 * @param {BigInteger} x - Shift value
39041 * @returns {BigInteger} this << x.
39042 */
39043 leftShift(x) {
39044 return this.clone().ileftShift(x);
39045 }
39046
39047 /**
39048 * Shift this to the right by x, in place
39049 * @param {BigInteger} x - Shift value
39050 */
39051 irightShift(x) {
39052 this.value.ishrn(x.value.toNumber());
39053 return this;
39054 }
39055
39056 /**
39057 * Shift this to the right by x
39058 * @param {BigInteger} x - Shift value
39059 * @returns {BigInteger} this >> x.
39060 */
39061 rightShift(x) {
39062 return this.clone().irightShift(x);
39063 }
39064
39065 /**
39066 * Whether this value is equal to x
39067 * @param {BigInteger} x
39068 * @returns {Boolean}
39069 */
39070 equal(x) {
39071 return this.value.eq(x.value);
39072 }
39073
39074 /**
39075 * Whether this value is less than x
39076 * @param {BigInteger} x
39077 * @returns {Boolean}
39078 */
39079 lt(x) {
39080 return this.value.lt(x.value);
39081 }
39082
39083 /**
39084 * Whether this value is less than or equal to x
39085 * @param {BigInteger} x
39086 * @returns {Boolean}
39087 */
39088 lte(x) {
39089 return this.value.lte(x.value);
39090 }
39091
39092 /**
39093 * Whether this value is greater than x
39094 * @param {BigInteger} x
39095 * @returns {Boolean}
39096 */
39097 gt(x) {
39098 return this.value.gt(x.value);
39099 }
39100
39101 /**
39102 * Whether this value is greater than or equal to x
39103 * @param {BigInteger} x
39104 * @returns {Boolean}
39105 */
39106 gte(x) {
39107 return this.value.gte(x.value);
39108 }
39109
39110 isZero() {
39111 return this.value.isZero();
39112 }
39113
39114 isOne() {
39115 return this.value.eq(new bn(1));
39116 }
39117
39118 isNegative() {
39119 return this.value.isNeg();
39120 }
39121
39122 isEven() {
39123 return this.value.isEven();
39124 }
39125
39126 abs() {
39127 const res = this.clone();
39128 res.value = res.value.abs();
39129 return res;
39130 }
39131
39132 /**
39133 * Get this value as a string
39134 * @returns {String} this value.
39135 */
39136 toString() {
39137 return this.value.toString();
39138 }
39139
39140 /**
39141 * Get this value as an exact Number (max 53 bits)
39142 * Fails if this value is too large
39143 * @returns {Number}
39144 */
39145 toNumber() {
39146 return this.value.toNumber();
39147 }
39148
39149 /**
39150 * Get value of i-th bit
39151 * @param {Number} i - Bit index
39152 * @returns {Number} Bit value.
39153 */
39154 getBit(i) {
39155 return this.value.testn(i) ? 1 : 0;
39156 }
39157
39158 /**
39159 * Compute bit length
39160 * @returns {Number} Bit length.
39161 */
39162 bitLength() {
39163 return this.value.bitLength();
39164 }
39165
39166 /**
39167 * Compute byte length
39168 * @returns {Number} Byte length.
39169 */
39170 byteLength() {
39171 return this.value.byteLength();
39172 }
39173
39174 /**
39175 * Get Uint8Array representation of this number
39176 * @param {String} endian - Endianess of output array (defaults to 'be')
39177 * @param {Number} length - Of output array
39178 * @returns {Uint8Array}
39179 */
39180 toUint8Array(endian = 'be', length) {
39181 return this.value.toArrayLike(Uint8Array, endian, length);
39182 }
39183}
39184
39185var bn_interface = /*#__PURE__*/Object.freeze({
39186 __proto__: null,
39187 'default': BigInteger$1
39188});
39189
39190var utils_1 = createCommonjsModule(function (module, exports) {
39191
39192var utils = exports;
39193
39194function toArray(msg, enc) {
39195 if (Array.isArray(msg))
39196 return msg.slice();
39197 if (!msg)
39198 return [];
39199 var res = [];
39200 if (typeof msg !== 'string') {
39201 for (var i = 0; i < msg.length; i++)
39202 res[i] = msg[i] | 0;
39203 return res;
39204 }
39205 if (enc === 'hex') {
39206 msg = msg.replace(/[^a-z0-9]+/ig, '');
39207 if (msg.length % 2 !== 0)
39208 msg = '0' + msg;
39209 for (var i = 0; i < msg.length; i += 2)
39210 res.push(parseInt(msg[i] + msg[i + 1], 16));
39211 } else {
39212 for (var i = 0; i < msg.length; i++) {
39213 var c = msg.charCodeAt(i);
39214 var hi = c >> 8;
39215 var lo = c & 0xff;
39216 if (hi)
39217 res.push(hi, lo);
39218 else
39219 res.push(lo);
39220 }
39221 }
39222 return res;
39223}
39224utils.toArray = toArray;
39225
39226function zero2(word) {
39227 if (word.length === 1)
39228 return '0' + word;
39229 else
39230 return word;
39231}
39232utils.zero2 = zero2;
39233
39234function toHex(msg) {
39235 var res = '';
39236 for (var i = 0; i < msg.length; i++)
39237 res += zero2(msg[i].toString(16));
39238 return res;
39239}
39240utils.toHex = toHex;
39241
39242utils.encode = function encode(arr, enc) {
39243 if (enc === 'hex')
39244 return toHex(arr);
39245 else
39246 return arr;
39247};
39248});
39249
39250var utils_1$1 = createCommonjsModule(function (module, exports) {
39251
39252var utils = exports;
39253
39254
39255
39256
39257utils.assert = minimalisticAssert;
39258utils.toArray = utils_1.toArray;
39259utils.zero2 = utils_1.zero2;
39260utils.toHex = utils_1.toHex;
39261utils.encode = utils_1.encode;
39262
39263// Represent num in a w-NAF form
39264function getNAF(num, w) {
39265 var naf = [];
39266 var ws = 1 << (w + 1);
39267 var k = num.clone();
39268 while (k.cmpn(1) >= 0) {
39269 var z;
39270 if (k.isOdd()) {
39271 var mod = k.andln(ws - 1);
39272 if (mod > (ws >> 1) - 1)
39273 z = (ws >> 1) - mod;
39274 else
39275 z = mod;
39276 k.isubn(z);
39277 } else {
39278 z = 0;
39279 }
39280 naf.push(z);
39281
39282 // Optimization, shift by word if possible
39283 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
39284 for (var i = 1; i < shift; i++)
39285 naf.push(0);
39286 k.iushrn(shift);
39287 }
39288
39289 return naf;
39290}
39291utils.getNAF = getNAF;
39292
39293// Represent k1, k2 in a Joint Sparse Form
39294function getJSF(k1, k2) {
39295 var jsf = [
39296 [],
39297 []
39298 ];
39299
39300 k1 = k1.clone();
39301 k2 = k2.clone();
39302 var d1 = 0;
39303 var d2 = 0;
39304 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
39305
39306 // First phase
39307 var m14 = (k1.andln(3) + d1) & 3;
39308 var m24 = (k2.andln(3) + d2) & 3;
39309 if (m14 === 3)
39310 m14 = -1;
39311 if (m24 === 3)
39312 m24 = -1;
39313 var u1;
39314 if ((m14 & 1) === 0) {
39315 u1 = 0;
39316 } else {
39317 var m8 = (k1.andln(7) + d1) & 7;
39318 if ((m8 === 3 || m8 === 5) && m24 === 2)
39319 u1 = -m14;
39320 else
39321 u1 = m14;
39322 }
39323 jsf[0].push(u1);
39324
39325 var u2;
39326 if ((m24 & 1) === 0) {
39327 u2 = 0;
39328 } else {
39329 var m8 = (k2.andln(7) + d2) & 7;
39330 if ((m8 === 3 || m8 === 5) && m14 === 2)
39331 u2 = -m24;
39332 else
39333 u2 = m24;
39334 }
39335 jsf[1].push(u2);
39336
39337 // Second phase
39338 if (2 * d1 === u1 + 1)
39339 d1 = 1 - d1;
39340 if (2 * d2 === u2 + 1)
39341 d2 = 1 - d2;
39342 k1.iushrn(1);
39343 k2.iushrn(1);
39344 }
39345
39346 return jsf;
39347}
39348utils.getJSF = getJSF;
39349
39350function cachedProperty(obj, name, computer) {
39351 var key = '_' + name;
39352 obj.prototype[name] = function cachedProperty() {
39353 return this[key] !== undefined ? this[key] :
39354 this[key] = computer.call(this);
39355 };
39356}
39357utils.cachedProperty = cachedProperty;
39358
39359function parseBytes(bytes) {
39360 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
39361 bytes;
39362}
39363utils.parseBytes = parseBytes;
39364
39365function intFromLE(bytes) {
39366 return new bn(bytes, 'hex', 'le');
39367}
39368utils.intFromLE = intFromLE;
39369});
39370
39371var r$1;
39372
39373var brorand = function rand(len) {
39374 if (!r$1)
39375 r$1 = new Rand(null);
39376
39377 return r$1.generate(len);
39378};
39379
39380function Rand(rand) {
39381 this.rand = rand;
39382}
39383var Rand_1 = Rand;
39384
39385Rand.prototype.generate = function generate(len) {
39386 return this._rand(len);
39387};
39388
39389// Emulate crypto API using randy
39390Rand.prototype._rand = function _rand(n) {
39391 if (this.rand.getBytes)
39392 return this.rand.getBytes(n);
39393
39394 var res = new Uint8Array(n);
39395 for (var i = 0; i < res.length; i++)
39396 res[i] = this.rand.getByte();
39397 return res;
39398};
39399
39400if (typeof self === 'object') {
39401 if (self.crypto && self.crypto.getRandomValues) {
39402 // Modern browsers
39403 Rand.prototype._rand = function _rand(n) {
39404 var arr = new Uint8Array(n);
39405 self.crypto.getRandomValues(arr);
39406 return arr;
39407 };
39408 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39409 // IE
39410 Rand.prototype._rand = function _rand(n) {
39411 var arr = new Uint8Array(n);
39412 self.msCrypto.getRandomValues(arr);
39413 return arr;
39414 };
39415
39416 // Safari's WebWorkers do not have `crypto`
39417 } else if (typeof window === 'object') {
39418 // Old junk
39419 Rand.prototype._rand = function() {
39420 throw new Error('Not implemented yet');
39421 };
39422 }
39423} else {
39424 // Node.js or Web worker with no crypto support
39425 try {
39426 var crypto$2 = void('crypto');
39427 if (typeof crypto$2.randomBytes !== 'function')
39428 throw new Error('Not supported');
39429
39430 Rand.prototype._rand = function _rand(n) {
39431 return crypto$2.randomBytes(n);
39432 };
39433 } catch (e) {
39434 }
39435}
39436brorand.Rand = Rand_1;
39437
39438var getNAF = utils_1$1.getNAF;
39439var getJSF = utils_1$1.getJSF;
39440var assert$2 = utils_1$1.assert;
39441
39442function BaseCurve(type, conf) {
39443 this.type = type;
39444 this.p = new bn(conf.p, 16);
39445
39446 // Use Montgomery, when there is no fast reduction for the prime
39447 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
39448
39449 // Useful for many curves
39450 this.zero = new bn(0).toRed(this.red);
39451 this.one = new bn(1).toRed(this.red);
39452 this.two = new bn(2).toRed(this.red);
39453
39454 // Curve configuration, optional
39455 this.n = conf.n && new bn(conf.n, 16);
39456 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
39457
39458 // Temporary arrays
39459 this._wnafT1 = new Array(4);
39460 this._wnafT2 = new Array(4);
39461 this._wnafT3 = new Array(4);
39462 this._wnafT4 = new Array(4);
39463
39464 // Generalized Greg Maxwell's trick
39465 var adjustCount = this.n && this.p.div(this.n);
39466 if (!adjustCount || adjustCount.cmpn(100) > 0) {
39467 this.redN = null;
39468 } else {
39469 this._maxwellTrick = true;
39470 this.redN = this.n.toRed(this.red);
39471 }
39472}
39473var base = BaseCurve;
39474
39475BaseCurve.prototype.point = function point() {
39476 throw new Error('Not implemented');
39477};
39478
39479BaseCurve.prototype.validate = function validate() {
39480 throw new Error('Not implemented');
39481};
39482
39483BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
39484 assert$2(p.precomputed);
39485 var doubles = p._getDoubles();
39486
39487 var naf = getNAF(k, 1);
39488 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
39489 I /= 3;
39490
39491 // Translate into more windowed form
39492 var repr = [];
39493 for (var j = 0; j < naf.length; j += doubles.step) {
39494 var nafW = 0;
39495 for (var k = j + doubles.step - 1; k >= j; k--)
39496 nafW = (nafW << 1) + naf[k];
39497 repr.push(nafW);
39498 }
39499
39500 var a = this.jpoint(null, null, null);
39501 var b = this.jpoint(null, null, null);
39502 for (var i = I; i > 0; i--) {
39503 for (var j = 0; j < repr.length; j++) {
39504 var nafW = repr[j];
39505 if (nafW === i)
39506 b = b.mixedAdd(doubles.points[j]);
39507 else if (nafW === -i)
39508 b = b.mixedAdd(doubles.points[j].neg());
39509 }
39510 a = a.add(b);
39511 }
39512 return a.toP();
39513};
39514
39515BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
39516 var w = 4;
39517
39518 // Precompute window
39519 var nafPoints = p._getNAFPoints(w);
39520 w = nafPoints.wnd;
39521 var wnd = nafPoints.points;
39522
39523 // Get NAF form
39524 var naf = getNAF(k, w);
39525
39526 // Add `this`*(N+1) for every w-NAF index
39527 var acc = this.jpoint(null, null, null);
39528 for (var i = naf.length - 1; i >= 0; i--) {
39529 // Count zeroes
39530 for (var k = 0; i >= 0 && naf[i] === 0; i--)
39531 k++;
39532 if (i >= 0)
39533 k++;
39534 acc = acc.dblp(k);
39535
39536 if (i < 0)
39537 break;
39538 var z = naf[i];
39539 assert$2(z !== 0);
39540 if (p.type === 'affine') {
39541 // J +- P
39542 if (z > 0)
39543 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
39544 else
39545 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
39546 } else {
39547 // J +- J
39548 if (z > 0)
39549 acc = acc.add(wnd[(z - 1) >> 1]);
39550 else
39551 acc = acc.add(wnd[(-z - 1) >> 1].neg());
39552 }
39553 }
39554 return p.type === 'affine' ? acc.toP() : acc;
39555};
39556
39557BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
39558 points,
39559 coeffs,
39560 len,
39561 jacobianResult) {
39562 var wndWidth = this._wnafT1;
39563 var wnd = this._wnafT2;
39564 var naf = this._wnafT3;
39565
39566 // Fill all arrays
39567 var max = 0;
39568 for (var i = 0; i < len; i++) {
39569 var p = points[i];
39570 var nafPoints = p._getNAFPoints(defW);
39571 wndWidth[i] = nafPoints.wnd;
39572 wnd[i] = nafPoints.points;
39573 }
39574
39575 // Comb small window NAFs
39576 for (var i = len - 1; i >= 1; i -= 2) {
39577 var a = i - 1;
39578 var b = i;
39579 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
39580 naf[a] = getNAF(coeffs[a], wndWidth[a]);
39581 naf[b] = getNAF(coeffs[b], wndWidth[b]);
39582 max = Math.max(naf[a].length, max);
39583 max = Math.max(naf[b].length, max);
39584 continue;
39585 }
39586
39587 var comb = [
39588 points[a], /* 1 */
39589 null, /* 3 */
39590 null, /* 5 */
39591 points[b] /* 7 */
39592 ];
39593
39594 // Try to avoid Projective points, if possible
39595 if (points[a].y.cmp(points[b].y) === 0) {
39596 comb[1] = points[a].add(points[b]);
39597 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39598 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
39599 comb[1] = points[a].toJ().mixedAdd(points[b]);
39600 comb[2] = points[a].add(points[b].neg());
39601 } else {
39602 comb[1] = points[a].toJ().mixedAdd(points[b]);
39603 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39604 }
39605
39606 var index = [
39607 -3, /* -1 -1 */
39608 -1, /* -1 0 */
39609 -5, /* -1 1 */
39610 -7, /* 0 -1 */
39611 0, /* 0 0 */
39612 7, /* 0 1 */
39613 5, /* 1 -1 */
39614 1, /* 1 0 */
39615 3 /* 1 1 */
39616 ];
39617
39618 var jsf = getJSF(coeffs[a], coeffs[b]);
39619 max = Math.max(jsf[0].length, max);
39620 naf[a] = new Array(max);
39621 naf[b] = new Array(max);
39622 for (var j = 0; j < max; j++) {
39623 var ja = jsf[0][j] | 0;
39624 var jb = jsf[1][j] | 0;
39625
39626 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
39627 naf[b][j] = 0;
39628 wnd[a] = comb;
39629 }
39630 }
39631
39632 var acc = this.jpoint(null, null, null);
39633 var tmp = this._wnafT4;
39634 for (var i = max; i >= 0; i--) {
39635 var k = 0;
39636
39637 while (i >= 0) {
39638 var zero = true;
39639 for (var j = 0; j < len; j++) {
39640 tmp[j] = naf[j][i] | 0;
39641 if (tmp[j] !== 0)
39642 zero = false;
39643 }
39644 if (!zero)
39645 break;
39646 k++;
39647 i--;
39648 }
39649 if (i >= 0)
39650 k++;
39651 acc = acc.dblp(k);
39652 if (i < 0)
39653 break;
39654
39655 for (var j = 0; j < len; j++) {
39656 var z = tmp[j];
39657 var p;
39658 if (z === 0)
39659 continue;
39660 else if (z > 0)
39661 p = wnd[j][(z - 1) >> 1];
39662 else if (z < 0)
39663 p = wnd[j][(-z - 1) >> 1].neg();
39664
39665 if (p.type === 'affine')
39666 acc = acc.mixedAdd(p);
39667 else
39668 acc = acc.add(p);
39669 }
39670 }
39671 // Zeroify references
39672 for (var i = 0; i < len; i++)
39673 wnd[i] = null;
39674
39675 if (jacobianResult)
39676 return acc;
39677 else
39678 return acc.toP();
39679};
39680
39681function BasePoint(curve, type) {
39682 this.curve = curve;
39683 this.type = type;
39684 this.precomputed = null;
39685}
39686BaseCurve.BasePoint = BasePoint;
39687
39688BasePoint.prototype.eq = function eq(/*other*/) {
39689 throw new Error('Not implemented');
39690};
39691
39692BasePoint.prototype.validate = function validate() {
39693 return this.curve.validate(this);
39694};
39695
39696BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
39697 bytes = utils_1$1.toArray(bytes, enc);
39698
39699 var len = this.p.byteLength();
39700
39701 // uncompressed, hybrid-odd, hybrid-even
39702 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
39703 bytes.length - 1 === 2 * len) {
39704 if (bytes[0] === 0x06)
39705 assert$2(bytes[bytes.length - 1] % 2 === 0);
39706 else if (bytes[0] === 0x07)
39707 assert$2(bytes[bytes.length - 1] % 2 === 1);
39708
39709 var res = this.point(bytes.slice(1, 1 + len),
39710 bytes.slice(1 + len, 1 + 2 * len));
39711
39712 return res;
39713 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
39714 bytes.length - 1 === len) {
39715 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
39716 }
39717 throw new Error('Unknown point format');
39718};
39719
39720BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
39721 return this.encode(enc, true);
39722};
39723
39724BasePoint.prototype._encode = function _encode(compact) {
39725 var len = this.curve.p.byteLength();
39726 var x = this.getX().toArray('be', len);
39727
39728 if (compact)
39729 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
39730
39731 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
39732};
39733
39734BasePoint.prototype.encode = function encode(enc, compact) {
39735 return utils_1$1.encode(this._encode(compact), enc);
39736};
39737
39738BasePoint.prototype.precompute = function precompute(power) {
39739 if (this.precomputed)
39740 return this;
39741
39742 var precomputed = {
39743 doubles: null,
39744 naf: null,
39745 beta: null
39746 };
39747 precomputed.naf = this._getNAFPoints(8);
39748 precomputed.doubles = this._getDoubles(4, power);
39749 precomputed.beta = this._getBeta();
39750 this.precomputed = precomputed;
39751
39752 return this;
39753};
39754
39755BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
39756 if (!this.precomputed)
39757 return false;
39758
39759 var doubles = this.precomputed.doubles;
39760 if (!doubles)
39761 return false;
39762
39763 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
39764};
39765
39766BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
39767 if (this.precomputed && this.precomputed.doubles)
39768 return this.precomputed.doubles;
39769
39770 var doubles = [ this ];
39771 var acc = this;
39772 for (var i = 0; i < power; i += step) {
39773 for (var j = 0; j < step; j++)
39774 acc = acc.dbl();
39775 doubles.push(acc);
39776 }
39777 return {
39778 step: step,
39779 points: doubles
39780 };
39781};
39782
39783BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
39784 if (this.precomputed && this.precomputed.naf)
39785 return this.precomputed.naf;
39786
39787 var res = [ this ];
39788 var max = (1 << wnd) - 1;
39789 var dbl = max === 1 ? null : this.dbl();
39790 for (var i = 1; i < max; i++)
39791 res[i] = res[i - 1].add(dbl);
39792 return {
39793 wnd: wnd,
39794 points: res
39795 };
39796};
39797
39798BasePoint.prototype._getBeta = function _getBeta() {
39799 return null;
39800};
39801
39802BasePoint.prototype.dblp = function dblp(k) {
39803 var r = this;
39804 for (var i = 0; i < k; i++)
39805 r = r.dbl();
39806 return r;
39807};
39808
39809var assert$3 = utils_1$1.assert;
39810
39811function ShortCurve(conf) {
39812 base.call(this, 'short', conf);
39813
39814 this.a = new bn(conf.a, 16).toRed(this.red);
39815 this.b = new bn(conf.b, 16).toRed(this.red);
39816 this.tinv = this.two.redInvm();
39817
39818 this.zeroA = this.a.fromRed().cmpn(0) === 0;
39819 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
39820
39821 // If the curve is endomorphic, precalculate beta and lambda
39822 this.endo = this._getEndomorphism(conf);
39823 this._endoWnafT1 = new Array(4);
39824 this._endoWnafT2 = new Array(4);
39825}
39826inherits_browser(ShortCurve, base);
39827var short_1 = ShortCurve;
39828
39829ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
39830 // No efficient endomorphism
39831 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
39832 return;
39833
39834 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
39835 var beta;
39836 var lambda;
39837 if (conf.beta) {
39838 beta = new bn(conf.beta, 16).toRed(this.red);
39839 } else {
39840 var betas = this._getEndoRoots(this.p);
39841 // Choose the smallest beta
39842 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
39843 beta = beta.toRed(this.red);
39844 }
39845 if (conf.lambda) {
39846 lambda = new bn(conf.lambda, 16);
39847 } else {
39848 // Choose the lambda that is matching selected beta
39849 var lambdas = this._getEndoRoots(this.n);
39850 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
39851 lambda = lambdas[0];
39852 } else {
39853 lambda = lambdas[1];
39854 assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
39855 }
39856 }
39857
39858 // Get basis vectors, used for balanced length-two representation
39859 var basis;
39860 if (conf.basis) {
39861 basis = conf.basis.map(function(vec) {
39862 return {
39863 a: new bn(vec.a, 16),
39864 b: new bn(vec.b, 16)
39865 };
39866 });
39867 } else {
39868 basis = this._getEndoBasis(lambda);
39869 }
39870
39871 return {
39872 beta: beta,
39873 lambda: lambda,
39874 basis: basis
39875 };
39876};
39877
39878ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
39879 // Find roots of for x^2 + x + 1 in F
39880 // Root = (-1 +- Sqrt(-3)) / 2
39881 //
39882 var red = num === this.p ? this.red : bn.mont(num);
39883 var tinv = new bn(2).toRed(red).redInvm();
39884 var ntinv = tinv.redNeg();
39885
39886 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
39887
39888 var l1 = ntinv.redAdd(s).fromRed();
39889 var l2 = ntinv.redSub(s).fromRed();
39890 return [ l1, l2 ];
39891};
39892
39893ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
39894 // aprxSqrt >= sqrt(this.n)
39895 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
39896
39897 // 3.74
39898 // Run EGCD, until r(L + 1) < aprxSqrt
39899 var u = lambda;
39900 var v = this.n.clone();
39901 var x1 = new bn(1);
39902 var y1 = new bn(0);
39903 var x2 = new bn(0);
39904 var y2 = new bn(1);
39905
39906 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
39907 var a0;
39908 var b0;
39909 // First vector
39910 var a1;
39911 var b1;
39912 // Second vector
39913 var a2;
39914 var b2;
39915
39916 var prevR;
39917 var i = 0;
39918 var r;
39919 var x;
39920 while (u.cmpn(0) !== 0) {
39921 var q = v.div(u);
39922 r = v.sub(q.mul(u));
39923 x = x2.sub(q.mul(x1));
39924 var y = y2.sub(q.mul(y1));
39925
39926 if (!a1 && r.cmp(aprxSqrt) < 0) {
39927 a0 = prevR.neg();
39928 b0 = x1;
39929 a1 = r.neg();
39930 b1 = x;
39931 } else if (a1 && ++i === 2) {
39932 break;
39933 }
39934 prevR = r;
39935
39936 v = u;
39937 u = r;
39938 x2 = x1;
39939 x1 = x;
39940 y2 = y1;
39941 y1 = y;
39942 }
39943 a2 = r.neg();
39944 b2 = x;
39945
39946 var len1 = a1.sqr().add(b1.sqr());
39947 var len2 = a2.sqr().add(b2.sqr());
39948 if (len2.cmp(len1) >= 0) {
39949 a2 = a0;
39950 b2 = b0;
39951 }
39952
39953 // Normalize signs
39954 if (a1.negative) {
39955 a1 = a1.neg();
39956 b1 = b1.neg();
39957 }
39958 if (a2.negative) {
39959 a2 = a2.neg();
39960 b2 = b2.neg();
39961 }
39962
39963 return [
39964 { a: a1, b: b1 },
39965 { a: a2, b: b2 }
39966 ];
39967};
39968
39969ShortCurve.prototype._endoSplit = function _endoSplit(k) {
39970 var basis = this.endo.basis;
39971 var v1 = basis[0];
39972 var v2 = basis[1];
39973
39974 var c1 = v2.b.mul(k).divRound(this.n);
39975 var c2 = v1.b.neg().mul(k).divRound(this.n);
39976
39977 var p1 = c1.mul(v1.a);
39978 var p2 = c2.mul(v2.a);
39979 var q1 = c1.mul(v1.b);
39980 var q2 = c2.mul(v2.b);
39981
39982 // Calculate answer
39983 var k1 = k.sub(p1).sub(p2);
39984 var k2 = q1.add(q2).neg();
39985 return { k1: k1, k2: k2 };
39986};
39987
39988ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
39989 x = new bn(x, 16);
39990 if (!x.red)
39991 x = x.toRed(this.red);
39992
39993 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
39994 var y = y2.redSqrt();
39995 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
39996 throw new Error('invalid point');
39997
39998 // XXX Is there any way to tell if the number is odd without converting it
39999 // to non-red form?
40000 var isOdd = y.fromRed().isOdd();
40001 if (odd && !isOdd || !odd && isOdd)
40002 y = y.redNeg();
40003
40004 return this.point(x, y);
40005};
40006
40007ShortCurve.prototype.validate = function validate(point) {
40008 if (point.inf)
40009 return true;
40010
40011 var x = point.x;
40012 var y = point.y;
40013
40014 var ax = this.a.redMul(x);
40015 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
40016 return y.redSqr().redISub(rhs).cmpn(0) === 0;
40017};
40018
40019ShortCurve.prototype._endoWnafMulAdd =
40020 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
40021 var npoints = this._endoWnafT1;
40022 var ncoeffs = this._endoWnafT2;
40023 for (var i = 0; i < points.length; i++) {
40024 var split = this._endoSplit(coeffs[i]);
40025 var p = points[i];
40026 var beta = p._getBeta();
40027
40028 if (split.k1.negative) {
40029 split.k1.ineg();
40030 p = p.neg(true);
40031 }
40032 if (split.k2.negative) {
40033 split.k2.ineg();
40034 beta = beta.neg(true);
40035 }
40036
40037 npoints[i * 2] = p;
40038 npoints[i * 2 + 1] = beta;
40039 ncoeffs[i * 2] = split.k1;
40040 ncoeffs[i * 2 + 1] = split.k2;
40041 }
40042 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
40043
40044 // Clean-up references to points and coefficients
40045 for (var j = 0; j < i * 2; j++) {
40046 npoints[j] = null;
40047 ncoeffs[j] = null;
40048 }
40049 return res;
40050};
40051
40052function Point(curve, x, y, isRed) {
40053 base.BasePoint.call(this, curve, 'affine');
40054 if (x === null && y === null) {
40055 this.x = null;
40056 this.y = null;
40057 this.inf = true;
40058 } else {
40059 this.x = new bn(x, 16);
40060 this.y = new bn(y, 16);
40061 // Force redgomery representation when loading from JSON
40062 if (isRed) {
40063 this.x.forceRed(this.curve.red);
40064 this.y.forceRed(this.curve.red);
40065 }
40066 if (!this.x.red)
40067 this.x = this.x.toRed(this.curve.red);
40068 if (!this.y.red)
40069 this.y = this.y.toRed(this.curve.red);
40070 this.inf = false;
40071 }
40072}
40073inherits_browser(Point, base.BasePoint);
40074
40075ShortCurve.prototype.point = function point(x, y, isRed) {
40076 return new Point(this, x, y, isRed);
40077};
40078
40079ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
40080 return Point.fromJSON(this, obj, red);
40081};
40082
40083Point.prototype._getBeta = function _getBeta() {
40084 if (!this.curve.endo)
40085 return;
40086
40087 var pre = this.precomputed;
40088 if (pre && pre.beta)
40089 return pre.beta;
40090
40091 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
40092 if (pre) {
40093 var curve = this.curve;
40094 var endoMul = function(p) {
40095 return curve.point(p.x.redMul(curve.endo.beta), p.y);
40096 };
40097 pre.beta = beta;
40098 beta.precomputed = {
40099 beta: null,
40100 naf: pre.naf && {
40101 wnd: pre.naf.wnd,
40102 points: pre.naf.points.map(endoMul)
40103 },
40104 doubles: pre.doubles && {
40105 step: pre.doubles.step,
40106 points: pre.doubles.points.map(endoMul)
40107 }
40108 };
40109 }
40110 return beta;
40111};
40112
40113Point.prototype.toJSON = function toJSON() {
40114 if (!this.precomputed)
40115 return [ this.x, this.y ];
40116
40117 return [ this.x, this.y, this.precomputed && {
40118 doubles: this.precomputed.doubles && {
40119 step: this.precomputed.doubles.step,
40120 points: this.precomputed.doubles.points.slice(1)
40121 },
40122 naf: this.precomputed.naf && {
40123 wnd: this.precomputed.naf.wnd,
40124 points: this.precomputed.naf.points.slice(1)
40125 }
40126 } ];
40127};
40128
40129Point.fromJSON = function fromJSON(curve, obj, red) {
40130 if (typeof obj === 'string')
40131 obj = JSON.parse(obj);
40132 var res = curve.point(obj[0], obj[1], red);
40133 if (!obj[2])
40134 return res;
40135
40136 function obj2point(obj) {
40137 return curve.point(obj[0], obj[1], red);
40138 }
40139
40140 var pre = obj[2];
40141 res.precomputed = {
40142 beta: null,
40143 doubles: pre.doubles && {
40144 step: pre.doubles.step,
40145 points: [ res ].concat(pre.doubles.points.map(obj2point))
40146 },
40147 naf: pre.naf && {
40148 wnd: pre.naf.wnd,
40149 points: [ res ].concat(pre.naf.points.map(obj2point))
40150 }
40151 };
40152 return res;
40153};
40154
40155Point.prototype.inspect = function inspect() {
40156 if (this.isInfinity())
40157 return '<EC Point Infinity>';
40158 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40159 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
40160};
40161
40162Point.prototype.isInfinity = function isInfinity() {
40163 return this.inf;
40164};
40165
40166Point.prototype.add = function add(p) {
40167 // O + P = P
40168 if (this.inf)
40169 return p;
40170
40171 // P + O = P
40172 if (p.inf)
40173 return this;
40174
40175 // P + P = 2P
40176 if (this.eq(p))
40177 return this.dbl();
40178
40179 // P + (-P) = O
40180 if (this.neg().eq(p))
40181 return this.curve.point(null, null);
40182
40183 // P + Q = O
40184 if (this.x.cmp(p.x) === 0)
40185 return this.curve.point(null, null);
40186
40187 var c = this.y.redSub(p.y);
40188 if (c.cmpn(0) !== 0)
40189 c = c.redMul(this.x.redSub(p.x).redInvm());
40190 var nx = c.redSqr().redISub(this.x).redISub(p.x);
40191 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40192 return this.curve.point(nx, ny);
40193};
40194
40195Point.prototype.dbl = function dbl() {
40196 if (this.inf)
40197 return this;
40198
40199 // 2P = O
40200 var ys1 = this.y.redAdd(this.y);
40201 if (ys1.cmpn(0) === 0)
40202 return this.curve.point(null, null);
40203
40204 var a = this.curve.a;
40205
40206 var x2 = this.x.redSqr();
40207 var dyinv = ys1.redInvm();
40208 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
40209
40210 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
40211 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40212 return this.curve.point(nx, ny);
40213};
40214
40215Point.prototype.getX = function getX() {
40216 return this.x.fromRed();
40217};
40218
40219Point.prototype.getY = function getY() {
40220 return this.y.fromRed();
40221};
40222
40223Point.prototype.mul = function mul(k) {
40224 k = new bn(k, 16);
40225 if (this.isInfinity())
40226 return this;
40227 else if (this._hasDoubles(k))
40228 return this.curve._fixedNafMul(this, k);
40229 else if (this.curve.endo)
40230 return this.curve._endoWnafMulAdd([ this ], [ k ]);
40231 else
40232 return this.curve._wnafMul(this, k);
40233};
40234
40235Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
40236 var points = [ this, p2 ];
40237 var coeffs = [ k1, k2 ];
40238 if (this.curve.endo)
40239 return this.curve._endoWnafMulAdd(points, coeffs);
40240 else
40241 return this.curve._wnafMulAdd(1, points, coeffs, 2);
40242};
40243
40244Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
40245 var points = [ this, p2 ];
40246 var coeffs = [ k1, k2 ];
40247 if (this.curve.endo)
40248 return this.curve._endoWnafMulAdd(points, coeffs, true);
40249 else
40250 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
40251};
40252
40253Point.prototype.eq = function eq(p) {
40254 return this === p ||
40255 this.inf === p.inf &&
40256 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
40257};
40258
40259Point.prototype.neg = function neg(_precompute) {
40260 if (this.inf)
40261 return this;
40262
40263 var res = this.curve.point(this.x, this.y.redNeg());
40264 if (_precompute && this.precomputed) {
40265 var pre = this.precomputed;
40266 var negate = function(p) {
40267 return p.neg();
40268 };
40269 res.precomputed = {
40270 naf: pre.naf && {
40271 wnd: pre.naf.wnd,
40272 points: pre.naf.points.map(negate)
40273 },
40274 doubles: pre.doubles && {
40275 step: pre.doubles.step,
40276 points: pre.doubles.points.map(negate)
40277 }
40278 };
40279 }
40280 return res;
40281};
40282
40283Point.prototype.toJ = function toJ() {
40284 if (this.inf)
40285 return this.curve.jpoint(null, null, null);
40286
40287 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
40288 return res;
40289};
40290
40291function JPoint(curve, x, y, z) {
40292 base.BasePoint.call(this, curve, 'jacobian');
40293 if (x === null && y === null && z === null) {
40294 this.x = this.curve.one;
40295 this.y = this.curve.one;
40296 this.z = new bn(0);
40297 } else {
40298 this.x = new bn(x, 16);
40299 this.y = new bn(y, 16);
40300 this.z = new bn(z, 16);
40301 }
40302 if (!this.x.red)
40303 this.x = this.x.toRed(this.curve.red);
40304 if (!this.y.red)
40305 this.y = this.y.toRed(this.curve.red);
40306 if (!this.z.red)
40307 this.z = this.z.toRed(this.curve.red);
40308
40309 this.zOne = this.z === this.curve.one;
40310}
40311inherits_browser(JPoint, base.BasePoint);
40312
40313ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
40314 return new JPoint(this, x, y, z);
40315};
40316
40317JPoint.prototype.toP = function toP() {
40318 if (this.isInfinity())
40319 return this.curve.point(null, null);
40320
40321 var zinv = this.z.redInvm();
40322 var zinv2 = zinv.redSqr();
40323 var ax = this.x.redMul(zinv2);
40324 var ay = this.y.redMul(zinv2).redMul(zinv);
40325
40326 return this.curve.point(ax, ay);
40327};
40328
40329JPoint.prototype.neg = function neg() {
40330 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
40331};
40332
40333JPoint.prototype.add = function add(p) {
40334 // O + P = P
40335 if (this.isInfinity())
40336 return p;
40337
40338 // P + O = P
40339 if (p.isInfinity())
40340 return this;
40341
40342 // 12M + 4S + 7A
40343 var pz2 = p.z.redSqr();
40344 var z2 = this.z.redSqr();
40345 var u1 = this.x.redMul(pz2);
40346 var u2 = p.x.redMul(z2);
40347 var s1 = this.y.redMul(pz2.redMul(p.z));
40348 var s2 = p.y.redMul(z2.redMul(this.z));
40349
40350 var h = u1.redSub(u2);
40351 var r = s1.redSub(s2);
40352 if (h.cmpn(0) === 0) {
40353 if (r.cmpn(0) !== 0)
40354 return this.curve.jpoint(null, null, null);
40355 else
40356 return this.dbl();
40357 }
40358
40359 var h2 = h.redSqr();
40360 var h3 = h2.redMul(h);
40361 var v = u1.redMul(h2);
40362
40363 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40364 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40365 var nz = this.z.redMul(p.z).redMul(h);
40366
40367 return this.curve.jpoint(nx, ny, nz);
40368};
40369
40370JPoint.prototype.mixedAdd = function mixedAdd(p) {
40371 // O + P = P
40372 if (this.isInfinity())
40373 return p.toJ();
40374
40375 // P + O = P
40376 if (p.isInfinity())
40377 return this;
40378
40379 // 8M + 3S + 7A
40380 var z2 = this.z.redSqr();
40381 var u1 = this.x;
40382 var u2 = p.x.redMul(z2);
40383 var s1 = this.y;
40384 var s2 = p.y.redMul(z2).redMul(this.z);
40385
40386 var h = u1.redSub(u2);
40387 var r = s1.redSub(s2);
40388 if (h.cmpn(0) === 0) {
40389 if (r.cmpn(0) !== 0)
40390 return this.curve.jpoint(null, null, null);
40391 else
40392 return this.dbl();
40393 }
40394
40395 var h2 = h.redSqr();
40396 var h3 = h2.redMul(h);
40397 var v = u1.redMul(h2);
40398
40399 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40400 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40401 var nz = this.z.redMul(h);
40402
40403 return this.curve.jpoint(nx, ny, nz);
40404};
40405
40406JPoint.prototype.dblp = function dblp(pow) {
40407 if (pow === 0)
40408 return this;
40409 if (this.isInfinity())
40410 return this;
40411 if (!pow)
40412 return this.dbl();
40413
40414 if (this.curve.zeroA || this.curve.threeA) {
40415 var r = this;
40416 for (var i = 0; i < pow; i++)
40417 r = r.dbl();
40418 return r;
40419 }
40420
40421 // 1M + 2S + 1A + N * (4S + 5M + 8A)
40422 // N = 1 => 6M + 6S + 9A
40423 var a = this.curve.a;
40424 var tinv = this.curve.tinv;
40425
40426 var jx = this.x;
40427 var jy = this.y;
40428 var jz = this.z;
40429 var jz4 = jz.redSqr().redSqr();
40430
40431 // Reuse results
40432 var jyd = jy.redAdd(jy);
40433 for (var i = 0; i < pow; i++) {
40434 var jx2 = jx.redSqr();
40435 var jyd2 = jyd.redSqr();
40436 var jyd4 = jyd2.redSqr();
40437 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40438
40439 var t1 = jx.redMul(jyd2);
40440 var nx = c.redSqr().redISub(t1.redAdd(t1));
40441 var t2 = t1.redISub(nx);
40442 var dny = c.redMul(t2);
40443 dny = dny.redIAdd(dny).redISub(jyd4);
40444 var nz = jyd.redMul(jz);
40445 if (i + 1 < pow)
40446 jz4 = jz4.redMul(jyd4);
40447
40448 jx = nx;
40449 jz = nz;
40450 jyd = dny;
40451 }
40452
40453 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
40454};
40455
40456JPoint.prototype.dbl = function dbl() {
40457 if (this.isInfinity())
40458 return this;
40459
40460 if (this.curve.zeroA)
40461 return this._zeroDbl();
40462 else if (this.curve.threeA)
40463 return this._threeDbl();
40464 else
40465 return this._dbl();
40466};
40467
40468JPoint.prototype._zeroDbl = function _zeroDbl() {
40469 var nx;
40470 var ny;
40471 var nz;
40472 // Z = 1
40473 if (this.zOne) {
40474 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40475 // #doubling-mdbl-2007-bl
40476 // 1M + 5S + 14A
40477
40478 // XX = X1^2
40479 var xx = this.x.redSqr();
40480 // YY = Y1^2
40481 var yy = this.y.redSqr();
40482 // YYYY = YY^2
40483 var yyyy = yy.redSqr();
40484 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40485 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40486 s = s.redIAdd(s);
40487 // M = 3 * XX + a; a = 0
40488 var m = xx.redAdd(xx).redIAdd(xx);
40489 // T = M ^ 2 - 2*S
40490 var t = m.redSqr().redISub(s).redISub(s);
40491
40492 // 8 * YYYY
40493 var yyyy8 = yyyy.redIAdd(yyyy);
40494 yyyy8 = yyyy8.redIAdd(yyyy8);
40495 yyyy8 = yyyy8.redIAdd(yyyy8);
40496
40497 // X3 = T
40498 nx = t;
40499 // Y3 = M * (S - T) - 8 * YYYY
40500 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40501 // Z3 = 2*Y1
40502 nz = this.y.redAdd(this.y);
40503 } else {
40504 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40505 // #doubling-dbl-2009-l
40506 // 2M + 5S + 13A
40507
40508 // A = X1^2
40509 var a = this.x.redSqr();
40510 // B = Y1^2
40511 var b = this.y.redSqr();
40512 // C = B^2
40513 var c = b.redSqr();
40514 // D = 2 * ((X1 + B)^2 - A - C)
40515 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
40516 d = d.redIAdd(d);
40517 // E = 3 * A
40518 var e = a.redAdd(a).redIAdd(a);
40519 // F = E^2
40520 var f = e.redSqr();
40521
40522 // 8 * C
40523 var c8 = c.redIAdd(c);
40524 c8 = c8.redIAdd(c8);
40525 c8 = c8.redIAdd(c8);
40526
40527 // X3 = F - 2 * D
40528 nx = f.redISub(d).redISub(d);
40529 // Y3 = E * (D - X3) - 8 * C
40530 ny = e.redMul(d.redISub(nx)).redISub(c8);
40531 // Z3 = 2 * Y1 * Z1
40532 nz = this.y.redMul(this.z);
40533 nz = nz.redIAdd(nz);
40534 }
40535
40536 return this.curve.jpoint(nx, ny, nz);
40537};
40538
40539JPoint.prototype._threeDbl = function _threeDbl() {
40540 var nx;
40541 var ny;
40542 var nz;
40543 // Z = 1
40544 if (this.zOne) {
40545 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
40546 // #doubling-mdbl-2007-bl
40547 // 1M + 5S + 15A
40548
40549 // XX = X1^2
40550 var xx = this.x.redSqr();
40551 // YY = Y1^2
40552 var yy = this.y.redSqr();
40553 // YYYY = YY^2
40554 var yyyy = yy.redSqr();
40555 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40556 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40557 s = s.redIAdd(s);
40558 // M = 3 * XX + a
40559 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
40560 // T = M^2 - 2 * S
40561 var t = m.redSqr().redISub(s).redISub(s);
40562 // X3 = T
40563 nx = t;
40564 // Y3 = M * (S - T) - 8 * YYYY
40565 var yyyy8 = yyyy.redIAdd(yyyy);
40566 yyyy8 = yyyy8.redIAdd(yyyy8);
40567 yyyy8 = yyyy8.redIAdd(yyyy8);
40568 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40569 // Z3 = 2 * Y1
40570 nz = this.y.redAdd(this.y);
40571 } else {
40572 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
40573 // 3M + 5S
40574
40575 // delta = Z1^2
40576 var delta = this.z.redSqr();
40577 // gamma = Y1^2
40578 var gamma = this.y.redSqr();
40579 // beta = X1 * gamma
40580 var beta = this.x.redMul(gamma);
40581 // alpha = 3 * (X1 - delta) * (X1 + delta)
40582 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
40583 alpha = alpha.redAdd(alpha).redIAdd(alpha);
40584 // X3 = alpha^2 - 8 * beta
40585 var beta4 = beta.redIAdd(beta);
40586 beta4 = beta4.redIAdd(beta4);
40587 var beta8 = beta4.redAdd(beta4);
40588 nx = alpha.redSqr().redISub(beta8);
40589 // Z3 = (Y1 + Z1)^2 - gamma - delta
40590 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
40591 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
40592 var ggamma8 = gamma.redSqr();
40593 ggamma8 = ggamma8.redIAdd(ggamma8);
40594 ggamma8 = ggamma8.redIAdd(ggamma8);
40595 ggamma8 = ggamma8.redIAdd(ggamma8);
40596 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
40597 }
40598
40599 return this.curve.jpoint(nx, ny, nz);
40600};
40601
40602JPoint.prototype._dbl = function _dbl() {
40603 var a = this.curve.a;
40604
40605 // 4M + 6S + 10A
40606 var jx = this.x;
40607 var jy = this.y;
40608 var jz = this.z;
40609 var jz4 = jz.redSqr().redSqr();
40610
40611 var jx2 = jx.redSqr();
40612 var jy2 = jy.redSqr();
40613
40614 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40615
40616 var jxd4 = jx.redAdd(jx);
40617 jxd4 = jxd4.redIAdd(jxd4);
40618 var t1 = jxd4.redMul(jy2);
40619 var nx = c.redSqr().redISub(t1.redAdd(t1));
40620 var t2 = t1.redISub(nx);
40621
40622 var jyd8 = jy2.redSqr();
40623 jyd8 = jyd8.redIAdd(jyd8);
40624 jyd8 = jyd8.redIAdd(jyd8);
40625 jyd8 = jyd8.redIAdd(jyd8);
40626 var ny = c.redMul(t2).redISub(jyd8);
40627 var nz = jy.redAdd(jy).redMul(jz);
40628
40629 return this.curve.jpoint(nx, ny, nz);
40630};
40631
40632JPoint.prototype.trpl = function trpl() {
40633 if (!this.curve.zeroA)
40634 return this.dbl().add(this);
40635
40636 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
40637 // 5M + 10S + ...
40638
40639 // XX = X1^2
40640 var xx = this.x.redSqr();
40641 // YY = Y1^2
40642 var yy = this.y.redSqr();
40643 // ZZ = Z1^2
40644 var zz = this.z.redSqr();
40645 // YYYY = YY^2
40646 var yyyy = yy.redSqr();
40647 // M = 3 * XX + a * ZZ2; a = 0
40648 var m = xx.redAdd(xx).redIAdd(xx);
40649 // MM = M^2
40650 var mm = m.redSqr();
40651 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
40652 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40653 e = e.redIAdd(e);
40654 e = e.redAdd(e).redIAdd(e);
40655 e = e.redISub(mm);
40656 // EE = E^2
40657 var ee = e.redSqr();
40658 // T = 16*YYYY
40659 var t = yyyy.redIAdd(yyyy);
40660 t = t.redIAdd(t);
40661 t = t.redIAdd(t);
40662 t = t.redIAdd(t);
40663 // U = (M + E)^2 - MM - EE - T
40664 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
40665 // X3 = 4 * (X1 * EE - 4 * YY * U)
40666 var yyu4 = yy.redMul(u);
40667 yyu4 = yyu4.redIAdd(yyu4);
40668 yyu4 = yyu4.redIAdd(yyu4);
40669 var nx = this.x.redMul(ee).redISub(yyu4);
40670 nx = nx.redIAdd(nx);
40671 nx = nx.redIAdd(nx);
40672 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
40673 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
40674 ny = ny.redIAdd(ny);
40675 ny = ny.redIAdd(ny);
40676 ny = ny.redIAdd(ny);
40677 // Z3 = (Z1 + E)^2 - ZZ - EE
40678 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
40679
40680 return this.curve.jpoint(nx, ny, nz);
40681};
40682
40683JPoint.prototype.mul = function mul(k, kbase) {
40684 k = new bn(k, kbase);
40685
40686 return this.curve._wnafMul(this, k);
40687};
40688
40689JPoint.prototype.eq = function eq(p) {
40690 if (p.type === 'affine')
40691 return this.eq(p.toJ());
40692
40693 if (this === p)
40694 return true;
40695
40696 // x1 * z2^2 == x2 * z1^2
40697 var z2 = this.z.redSqr();
40698 var pz2 = p.z.redSqr();
40699 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
40700 return false;
40701
40702 // y1 * z2^3 == y2 * z1^3
40703 var z3 = z2.redMul(this.z);
40704 var pz3 = pz2.redMul(p.z);
40705 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
40706};
40707
40708JPoint.prototype.eqXToP = function eqXToP(x) {
40709 var zs = this.z.redSqr();
40710 var rx = x.toRed(this.curve.red).redMul(zs);
40711 if (this.x.cmp(rx) === 0)
40712 return true;
40713
40714 var xc = x.clone();
40715 var t = this.curve.redN.redMul(zs);
40716 for (;;) {
40717 xc.iadd(this.curve.n);
40718 if (xc.cmp(this.curve.p) >= 0)
40719 return false;
40720
40721 rx.redIAdd(t);
40722 if (this.x.cmp(rx) === 0)
40723 return true;
40724 }
40725};
40726
40727JPoint.prototype.inspect = function inspect() {
40728 if (this.isInfinity())
40729 return '<EC JPoint Infinity>';
40730 return '<EC JPoint x: ' + this.x.toString(16, 2) +
40731 ' y: ' + this.y.toString(16, 2) +
40732 ' z: ' + this.z.toString(16, 2) + '>';
40733};
40734
40735JPoint.prototype.isInfinity = function isInfinity() {
40736 // XXX This code assumes that zero is always zero in red
40737 return this.z.cmpn(0) === 0;
40738};
40739
40740function MontCurve(conf) {
40741 base.call(this, 'mont', conf);
40742
40743 this.a = new bn(conf.a, 16).toRed(this.red);
40744 this.b = new bn(conf.b, 16).toRed(this.red);
40745 this.i4 = new bn(4).toRed(this.red).redInvm();
40746 this.two = new bn(2).toRed(this.red);
40747 // Note: this implementation is according to the original paper
40748 // by P. Montgomery, NOT the one by D. J. Bernstein.
40749 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
40750}
40751inherits_browser(MontCurve, base);
40752var mont = MontCurve;
40753
40754MontCurve.prototype.validate = function validate(point) {
40755 var x = point.normalize().x;
40756 var x2 = x.redSqr();
40757 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
40758 var y = rhs.redSqrt();
40759
40760 return y.redSqr().cmp(rhs) === 0;
40761};
40762
40763function Point$1(curve, x, z) {
40764 base.BasePoint.call(this, curve, 'projective');
40765 if (x === null && z === null) {
40766 this.x = this.curve.one;
40767 this.z = this.curve.zero;
40768 } else {
40769 this.x = new bn(x, 16);
40770 this.z = new bn(z, 16);
40771 if (!this.x.red)
40772 this.x = this.x.toRed(this.curve.red);
40773 if (!this.z.red)
40774 this.z = this.z.toRed(this.curve.red);
40775 }
40776}
40777inherits_browser(Point$1, base.BasePoint);
40778
40779MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
40780 var bytes = utils_1$1.toArray(bytes, enc);
40781
40782 // TODO Curve448
40783 // Montgomery curve points must be represented in the compressed format
40784 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40785 if (bytes.length === 33 && bytes[0] === 0x40)
40786 bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
40787 if (bytes.length !== 32)
40788 throw new Error('Unknown point compression format');
40789 return this.point(bytes, 1);
40790};
40791
40792MontCurve.prototype.point = function point(x, z) {
40793 return new Point$1(this, x, z);
40794};
40795
40796MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
40797 return Point$1.fromJSON(this, obj);
40798};
40799
40800Point$1.prototype.precompute = function precompute() {
40801 // No-op
40802};
40803
40804Point$1.prototype._encode = function _encode(compact) {
40805 var len = this.curve.p.byteLength();
40806
40807 // Note: the output should always be little-endian
40808 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40809 if (compact) {
40810 return [ 0x40 ].concat(this.getX().toArray('le', len));
40811 } else {
40812 return this.getX().toArray('be', len);
40813 }
40814};
40815
40816Point$1.fromJSON = function fromJSON(curve, obj) {
40817 return new Point$1(curve, obj[0], obj[1] || curve.one);
40818};
40819
40820Point$1.prototype.inspect = function inspect() {
40821 if (this.isInfinity())
40822 return '<EC Point Infinity>';
40823 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40824 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
40825};
40826
40827Point$1.prototype.isInfinity = function isInfinity() {
40828 // XXX This code assumes that zero is always zero in red
40829 return this.z.cmpn(0) === 0;
40830};
40831
40832Point$1.prototype.dbl = function dbl() {
40833 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
40834 // 2M + 2S + 4A
40835
40836 // A = X1 + Z1
40837 var a = this.x.redAdd(this.z);
40838 // AA = A^2
40839 var aa = a.redSqr();
40840 // B = X1 - Z1
40841 var b = this.x.redSub(this.z);
40842 // BB = B^2
40843 var bb = b.redSqr();
40844 // C = AA - BB
40845 var c = aa.redSub(bb);
40846 // X3 = AA * BB
40847 var nx = aa.redMul(bb);
40848 // Z3 = C * (BB + A24 * C)
40849 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
40850 return this.curve.point(nx, nz);
40851};
40852
40853Point$1.prototype.add = function add() {
40854 throw new Error('Not supported on Montgomery curve');
40855};
40856
40857Point$1.prototype.diffAdd = function diffAdd(p, diff) {
40858 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
40859 // 4M + 2S + 6A
40860
40861 // A = X2 + Z2
40862 var a = this.x.redAdd(this.z);
40863 // B = X2 - Z2
40864 var b = this.x.redSub(this.z);
40865 // C = X3 + Z3
40866 var c = p.x.redAdd(p.z);
40867 // D = X3 - Z3
40868 var d = p.x.redSub(p.z);
40869 // DA = D * A
40870 var da = d.redMul(a);
40871 // CB = C * B
40872 var cb = c.redMul(b);
40873 // X5 = Z1 * (DA + CB)^2
40874 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
40875 // Z5 = X1 * (DA - CB)^2
40876 var nz = diff.x.redMul(da.redISub(cb).redSqr());
40877 return this.curve.point(nx, nz);
40878};
40879
40880Point$1.prototype.mul = function mul(k) {
40881 k = new bn(k, 16);
40882
40883 var t = k.clone();
40884 var a = this; // (N / 2) * Q + Q
40885 var b = this.curve.point(null, null); // (N / 2) * Q
40886 var c = this; // Q
40887
40888 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
40889 bits.push(t.andln(1));
40890
40891 for (var i = bits.length - 1; i >= 0; i--) {
40892 if (bits[i] === 0) {
40893 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
40894 a = a.diffAdd(b, c);
40895 // N * Q = 2 * ((N / 2) * Q + Q))
40896 b = b.dbl();
40897 } else {
40898 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
40899 b = a.diffAdd(b, c);
40900 // N * Q + Q = 2 * ((N / 2) * Q + Q)
40901 a = a.dbl();
40902 }
40903 }
40904 return b;
40905};
40906
40907Point$1.prototype.mulAdd = function mulAdd() {
40908 throw new Error('Not supported on Montgomery curve');
40909};
40910
40911Point$1.prototype.jumlAdd = function jumlAdd() {
40912 throw new Error('Not supported on Montgomery curve');
40913};
40914
40915Point$1.prototype.eq = function eq(other) {
40916 return this.getX().cmp(other.getX()) === 0;
40917};
40918
40919Point$1.prototype.normalize = function normalize() {
40920 this.x = this.x.redMul(this.z.redInvm());
40921 this.z = this.curve.one;
40922 return this;
40923};
40924
40925Point$1.prototype.getX = function getX() {
40926 // Normalize coordinates
40927 this.normalize();
40928
40929 return this.x.fromRed();
40930};
40931
40932var assert$4 = utils_1$1.assert;
40933
40934function EdwardsCurve(conf) {
40935 // NOTE: Important as we are creating point in Base.call()
40936 this.twisted = (conf.a | 0) !== 1;
40937 this.mOneA = this.twisted && (conf.a | 0) === -1;
40938 this.extended = this.mOneA;
40939
40940 base.call(this, 'edwards', conf);
40941
40942 this.a = new bn(conf.a, 16).umod(this.red.m);
40943 this.a = this.a.toRed(this.red);
40944 this.c = new bn(conf.c, 16).toRed(this.red);
40945 this.c2 = this.c.redSqr();
40946 this.d = new bn(conf.d, 16).toRed(this.red);
40947 this.dd = this.d.redAdd(this.d);
40948
40949 assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0);
40950 this.oneC = (conf.c | 0) === 1;
40951}
40952inherits_browser(EdwardsCurve, base);
40953var edwards = EdwardsCurve;
40954
40955EdwardsCurve.prototype._mulA = function _mulA(num) {
40956 if (this.mOneA)
40957 return num.redNeg();
40958 else
40959 return this.a.redMul(num);
40960};
40961
40962EdwardsCurve.prototype._mulC = function _mulC(num) {
40963 if (this.oneC)
40964 return num;
40965 else
40966 return this.c.redMul(num);
40967};
40968
40969// Just for compatibility with Short curve
40970EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
40971 return this.point(x, y, z, t);
40972};
40973
40974EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
40975 x = new bn(x, 16);
40976 if (!x.red)
40977 x = x.toRed(this.red);
40978
40979 var x2 = x.redSqr();
40980 var rhs = this.c2.redSub(this.a.redMul(x2));
40981 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
40982
40983 var y2 = rhs.redMul(lhs.redInvm());
40984 var y = y2.redSqrt();
40985 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
40986 throw new Error('invalid point');
40987
40988 var isOdd = y.fromRed().isOdd();
40989 if (odd && !isOdd || !odd && isOdd)
40990 y = y.redNeg();
40991
40992 return this.point(x, y);
40993};
40994
40995EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
40996 y = new bn(y, 16);
40997 if (!y.red)
40998 y = y.toRed(this.red);
40999
41000 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
41001 var y2 = y.redSqr();
41002 var lhs = y2.redSub(this.c2);
41003 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
41004 var x2 = lhs.redMul(rhs.redInvm());
41005
41006 if (x2.cmp(this.zero) === 0) {
41007 if (odd)
41008 throw new Error('invalid point');
41009 else
41010 return this.point(this.zero, y);
41011 }
41012
41013 var x = x2.redSqrt();
41014 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
41015 throw new Error('invalid point');
41016
41017 if (x.fromRed().isOdd() !== odd)
41018 x = x.redNeg();
41019
41020 return this.point(x, y);
41021};
41022
41023EdwardsCurve.prototype.validate = function validate(point) {
41024 if (point.isInfinity())
41025 return true;
41026
41027 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
41028 point.normalize();
41029
41030 var x2 = point.x.redSqr();
41031 var y2 = point.y.redSqr();
41032 var lhs = x2.redMul(this.a).redAdd(y2);
41033 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
41034
41035 return lhs.cmp(rhs) === 0;
41036};
41037
41038function Point$2(curve, x, y, z, t) {
41039 base.BasePoint.call(this, curve, 'projective');
41040 if (x === null && y === null && z === null) {
41041 this.x = this.curve.zero;
41042 this.y = this.curve.one;
41043 this.z = this.curve.one;
41044 this.t = this.curve.zero;
41045 this.zOne = true;
41046 } else {
41047 this.x = new bn(x, 16);
41048 this.y = new bn(y, 16);
41049 this.z = z ? new bn(z, 16) : this.curve.one;
41050 this.t = t && new bn(t, 16);
41051 if (!this.x.red)
41052 this.x = this.x.toRed(this.curve.red);
41053 if (!this.y.red)
41054 this.y = this.y.toRed(this.curve.red);
41055 if (!this.z.red)
41056 this.z = this.z.toRed(this.curve.red);
41057 if (this.t && !this.t.red)
41058 this.t = this.t.toRed(this.curve.red);
41059 this.zOne = this.z === this.curve.one;
41060
41061 // Use extended coordinates
41062 if (this.curve.extended && !this.t) {
41063 this.t = this.x.redMul(this.y);
41064 if (!this.zOne)
41065 this.t = this.t.redMul(this.z.redInvm());
41066 }
41067 }
41068}
41069inherits_browser(Point$2, base.BasePoint);
41070
41071EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
41072 return Point$2.fromJSON(this, obj);
41073};
41074
41075EdwardsCurve.prototype.point = function point(x, y, z, t) {
41076 return new Point$2(this, x, y, z, t);
41077};
41078
41079Point$2.fromJSON = function fromJSON(curve, obj) {
41080 return new Point$2(curve, obj[0], obj[1], obj[2]);
41081};
41082
41083Point$2.prototype.inspect = function inspect() {
41084 if (this.isInfinity())
41085 return '<EC Point Infinity>';
41086 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
41087 ' y: ' + this.y.fromRed().toString(16, 2) +
41088 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
41089};
41090
41091Point$2.prototype.isInfinity = function isInfinity() {
41092 // XXX This code assumes that zero is always zero in red
41093 return this.x.cmpn(0) === 0 &&
41094 (this.y.cmp(this.z) === 0 ||
41095 (this.zOne && this.y.cmp(this.curve.c) === 0));
41096};
41097
41098Point$2.prototype._extDbl = function _extDbl() {
41099 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41100 // #doubling-dbl-2008-hwcd
41101 // 4M + 4S
41102
41103 // A = X1^2
41104 var a = this.x.redSqr();
41105 // B = Y1^2
41106 var b = this.y.redSqr();
41107 // C = 2 * Z1^2
41108 var c = this.z.redSqr();
41109 c = c.redIAdd(c);
41110 // D = a * A
41111 var d = this.curve._mulA(a);
41112 // E = (X1 + Y1)^2 - A - B
41113 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
41114 // G = D + B
41115 var g = d.redAdd(b);
41116 // F = G - C
41117 var f = g.redSub(c);
41118 // H = D - B
41119 var h = d.redSub(b);
41120 // X3 = E * F
41121 var nx = e.redMul(f);
41122 // Y3 = G * H
41123 var ny = g.redMul(h);
41124 // T3 = E * H
41125 var nt = e.redMul(h);
41126 // Z3 = F * G
41127 var nz = f.redMul(g);
41128 return this.curve.point(nx, ny, nz, nt);
41129};
41130
41131Point$2.prototype._projDbl = function _projDbl() {
41132 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41133 // #doubling-dbl-2008-bbjlp
41134 // #doubling-dbl-2007-bl
41135 // and others
41136 // Generally 3M + 4S or 2M + 4S
41137
41138 // B = (X1 + Y1)^2
41139 var b = this.x.redAdd(this.y).redSqr();
41140 // C = X1^2
41141 var c = this.x.redSqr();
41142 // D = Y1^2
41143 var d = this.y.redSqr();
41144
41145 var nx;
41146 var ny;
41147 var nz;
41148 if (this.curve.twisted) {
41149 // E = a * C
41150 var e = this.curve._mulA(c);
41151 // F = E + D
41152 var f = e.redAdd(d);
41153 if (this.zOne) {
41154 // X3 = (B - C - D) * (F - 2)
41155 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
41156 // Y3 = F * (E - D)
41157 ny = f.redMul(e.redSub(d));
41158 // Z3 = F^2 - 2 * F
41159 nz = f.redSqr().redSub(f).redSub(f);
41160 } else {
41161 // H = Z1^2
41162 var h = this.z.redSqr();
41163 // J = F - 2 * H
41164 var j = f.redSub(h).redISub(h);
41165 // X3 = (B-C-D)*J
41166 nx = b.redSub(c).redISub(d).redMul(j);
41167 // Y3 = F * (E - D)
41168 ny = f.redMul(e.redSub(d));
41169 // Z3 = F * J
41170 nz = f.redMul(j);
41171 }
41172 } else {
41173 // E = C + D
41174 var e = c.redAdd(d);
41175 // H = (c * Z1)^2
41176 var h = this.curve._mulC(this.z).redSqr();
41177 // J = E - 2 * H
41178 var j = e.redSub(h).redSub(h);
41179 // X3 = c * (B - E) * J
41180 nx = this.curve._mulC(b.redISub(e)).redMul(j);
41181 // Y3 = c * E * (C - D)
41182 ny = this.curve._mulC(e).redMul(c.redISub(d));
41183 // Z3 = E * J
41184 nz = e.redMul(j);
41185 }
41186 return this.curve.point(nx, ny, nz);
41187};
41188
41189Point$2.prototype.dbl = function dbl() {
41190 if (this.isInfinity())
41191 return this;
41192
41193 // Double in extended coordinates
41194 if (this.curve.extended)
41195 return this._extDbl();
41196 else
41197 return this._projDbl();
41198};
41199
41200Point$2.prototype._extAdd = function _extAdd(p) {
41201 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41202 // #addition-add-2008-hwcd-3
41203 // 8M
41204
41205 // A = (Y1 - X1) * (Y2 - X2)
41206 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
41207 // B = (Y1 + X1) * (Y2 + X2)
41208 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
41209 // C = T1 * k * T2
41210 var c = this.t.redMul(this.curve.dd).redMul(p.t);
41211 // D = Z1 * 2 * Z2
41212 var d = this.z.redMul(p.z.redAdd(p.z));
41213 // E = B - A
41214 var e = b.redSub(a);
41215 // F = D - C
41216 var f = d.redSub(c);
41217 // G = D + C
41218 var g = d.redAdd(c);
41219 // H = B + A
41220 var h = b.redAdd(a);
41221 // X3 = E * F
41222 var nx = e.redMul(f);
41223 // Y3 = G * H
41224 var ny = g.redMul(h);
41225 // T3 = E * H
41226 var nt = e.redMul(h);
41227 // Z3 = F * G
41228 var nz = f.redMul(g);
41229 return this.curve.point(nx, ny, nz, nt);
41230};
41231
41232Point$2.prototype._projAdd = function _projAdd(p) {
41233 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41234 // #addition-add-2008-bbjlp
41235 // #addition-add-2007-bl
41236 // 10M + 1S
41237
41238 // A = Z1 * Z2
41239 var a = this.z.redMul(p.z);
41240 // B = A^2
41241 var b = a.redSqr();
41242 // C = X1 * X2
41243 var c = this.x.redMul(p.x);
41244 // D = Y1 * Y2
41245 var d = this.y.redMul(p.y);
41246 // E = d * C * D
41247 var e = this.curve.d.redMul(c).redMul(d);
41248 // F = B - E
41249 var f = b.redSub(e);
41250 // G = B + E
41251 var g = b.redAdd(e);
41252 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
41253 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
41254 var nx = a.redMul(f).redMul(tmp);
41255 var ny;
41256 var nz;
41257 if (this.curve.twisted) {
41258 // Y3 = A * G * (D - a * C)
41259 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
41260 // Z3 = F * G
41261 nz = f.redMul(g);
41262 } else {
41263 // Y3 = A * G * (D - C)
41264 ny = a.redMul(g).redMul(d.redSub(c));
41265 // Z3 = c * F * G
41266 nz = this.curve._mulC(f).redMul(g);
41267 }
41268 return this.curve.point(nx, ny, nz);
41269};
41270
41271Point$2.prototype.add = function add(p) {
41272 if (this.isInfinity())
41273 return p;
41274 if (p.isInfinity())
41275 return this;
41276
41277 if (this.curve.extended)
41278 return this._extAdd(p);
41279 else
41280 return this._projAdd(p);
41281};
41282
41283Point$2.prototype.mul = function mul(k) {
41284 if (this._hasDoubles(k))
41285 return this.curve._fixedNafMul(this, k);
41286 else
41287 return this.curve._wnafMul(this, k);
41288};
41289
41290Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) {
41291 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
41292};
41293
41294Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
41295 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
41296};
41297
41298Point$2.prototype.normalize = function normalize() {
41299 if (this.zOne)
41300 return this;
41301
41302 // Normalize coordinates
41303 var zi = this.z.redInvm();
41304 this.x = this.x.redMul(zi);
41305 this.y = this.y.redMul(zi);
41306 if (this.t)
41307 this.t = this.t.redMul(zi);
41308 this.z = this.curve.one;
41309 this.zOne = true;
41310 return this;
41311};
41312
41313Point$2.prototype.neg = function neg() {
41314 return this.curve.point(this.x.redNeg(),
41315 this.y,
41316 this.z,
41317 this.t && this.t.redNeg());
41318};
41319
41320Point$2.prototype.getX = function getX() {
41321 this.normalize();
41322 return this.x.fromRed();
41323};
41324
41325Point$2.prototype.getY = function getY() {
41326 this.normalize();
41327 return this.y.fromRed();
41328};
41329
41330Point$2.prototype.eq = function eq(other) {
41331 return this === other ||
41332 this.getX().cmp(other.getX()) === 0 &&
41333 this.getY().cmp(other.getY()) === 0;
41334};
41335
41336Point$2.prototype.eqXToP = function eqXToP(x) {
41337 var rx = x.toRed(this.curve.red).redMul(this.z);
41338 if (this.x.cmp(rx) === 0)
41339 return true;
41340
41341 var xc = x.clone();
41342 var t = this.curve.redN.redMul(this.z);
41343 for (;;) {
41344 xc.iadd(this.curve.n);
41345 if (xc.cmp(this.curve.p) >= 0)
41346 return false;
41347
41348 rx.redIAdd(t);
41349 if (this.x.cmp(rx) === 0)
41350 return true;
41351 }
41352};
41353
41354// Compatibility with BaseCurve
41355Point$2.prototype.toP = Point$2.prototype.normalize;
41356Point$2.prototype.mixedAdd = Point$2.prototype.add;
41357
41358var curve_1 = createCommonjsModule(function (module, exports) {
41359
41360var curve = exports;
41361
41362curve.base = base;
41363curve.short = short_1;
41364curve.mont = mont;
41365curve.edwards = edwards;
41366});
41367
41368var rotl32$2 = utils.rotl32;
41369var sum32$3 = utils.sum32;
41370var sum32_5$2 = utils.sum32_5;
41371var ft_1$1 = common$1.ft_1;
41372var BlockHash$4 = common.BlockHash;
41373
41374var sha1_K = [
41375 0x5A827999, 0x6ED9EBA1,
41376 0x8F1BBCDC, 0xCA62C1D6
41377];
41378
41379function SHA1() {
41380 if (!(this instanceof SHA1))
41381 return new SHA1();
41382
41383 BlockHash$4.call(this);
41384 this.h = [
41385 0x67452301, 0xefcdab89, 0x98badcfe,
41386 0x10325476, 0xc3d2e1f0 ];
41387 this.W = new Array(80);
41388}
41389
41390utils.inherits(SHA1, BlockHash$4);
41391var _1 = SHA1;
41392
41393SHA1.blockSize = 512;
41394SHA1.outSize = 160;
41395SHA1.hmacStrength = 80;
41396SHA1.padLength = 64;
41397
41398SHA1.prototype._update = function _update(msg, start) {
41399 var W = this.W;
41400
41401 for (var i = 0; i < 16; i++)
41402 W[i] = msg[start + i];
41403
41404 for(; i < W.length; i++)
41405 W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
41406
41407 var a = this.h[0];
41408 var b = this.h[1];
41409 var c = this.h[2];
41410 var d = this.h[3];
41411 var e = this.h[4];
41412
41413 for (i = 0; i < W.length; i++) {
41414 var s = ~~(i / 20);
41415 var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
41416 e = d;
41417 d = c;
41418 c = rotl32$2(b, 30);
41419 b = a;
41420 a = t;
41421 }
41422
41423 this.h[0] = sum32$3(this.h[0], a);
41424 this.h[1] = sum32$3(this.h[1], b);
41425 this.h[2] = sum32$3(this.h[2], c);
41426 this.h[3] = sum32$3(this.h[3], d);
41427 this.h[4] = sum32$3(this.h[4], e);
41428};
41429
41430SHA1.prototype._digest = function digest(enc) {
41431 if (enc === 'hex')
41432 return utils.toHex32(this.h, 'big');
41433 else
41434 return utils.split32(this.h, 'big');
41435};
41436
41437var sha1 = _1;
41438var sha224 = _224;
41439var sha256 = _256;
41440var sha384 = _384;
41441var sha512 = _512;
41442
41443var sha = {
41444 sha1: sha1,
41445 sha224: sha224,
41446 sha256: sha256,
41447 sha384: sha384,
41448 sha512: sha512
41449};
41450
41451function Hmac(hash, key, enc) {
41452 if (!(this instanceof Hmac))
41453 return new Hmac(hash, key, enc);
41454 this.Hash = hash;
41455 this.blockSize = hash.blockSize / 8;
41456 this.outSize = hash.outSize / 8;
41457 this.inner = null;
41458 this.outer = null;
41459
41460 this._init(utils.toArray(key, enc));
41461}
41462var hmac = Hmac;
41463
41464Hmac.prototype._init = function init(key) {
41465 // Shorten key, if needed
41466 if (key.length > this.blockSize)
41467 key = new this.Hash().update(key).digest();
41468 minimalisticAssert(key.length <= this.blockSize);
41469
41470 // Add padding to key
41471 for (var i = key.length; i < this.blockSize; i++)
41472 key.push(0);
41473
41474 for (i = 0; i < key.length; i++)
41475 key[i] ^= 0x36;
41476 this.inner = new this.Hash().update(key);
41477
41478 // 0x36 ^ 0x5c = 0x6a
41479 for (i = 0; i < key.length; i++)
41480 key[i] ^= 0x6a;
41481 this.outer = new this.Hash().update(key);
41482};
41483
41484Hmac.prototype.update = function update(msg, enc) {
41485 this.inner.update(msg, enc);
41486 return this;
41487};
41488
41489Hmac.prototype.digest = function digest(enc) {
41490 this.outer.update(this.inner.digest());
41491 return this.outer.digest(enc);
41492};
41493
41494var hash_1 = createCommonjsModule(function (module, exports) {
41495var hash = exports;
41496
41497hash.utils = utils;
41498hash.common = common;
41499hash.sha = sha;
41500hash.ripemd = ripemd;
41501hash.hmac = hmac;
41502
41503// Proxy hash functions to the main object
41504hash.sha1 = hash.sha.sha1;
41505hash.sha256 = hash.sha.sha256;
41506hash.sha224 = hash.sha.sha224;
41507hash.sha384 = hash.sha.sha384;
41508hash.sha512 = hash.sha.sha512;
41509hash.ripemd160 = hash.ripemd.ripemd160;
41510});
41511
41512var secp256k1 = {
41513 doubles: {
41514 step: 4,
41515 points: [
41516 [
41517 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
41518 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
41519 ],
41520 [
41521 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
41522 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
41523 ],
41524 [
41525 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
41526 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
41527 ],
41528 [
41529 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
41530 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
41531 ],
41532 [
41533 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
41534 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
41535 ],
41536 [
41537 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
41538 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
41539 ],
41540 [
41541 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
41542 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
41543 ],
41544 [
41545 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
41546 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
41547 ],
41548 [
41549 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
41550 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
41551 ],
41552 [
41553 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
41554 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
41555 ],
41556 [
41557 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
41558 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
41559 ],
41560 [
41561 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
41562 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
41563 ],
41564 [
41565 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
41566 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
41567 ],
41568 [
41569 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
41570 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
41571 ],
41572 [
41573 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
41574 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
41575 ],
41576 [
41577 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
41578 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
41579 ],
41580 [
41581 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
41582 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
41583 ],
41584 [
41585 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
41586 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
41587 ],
41588 [
41589 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
41590 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
41591 ],
41592 [
41593 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
41594 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
41595 ],
41596 [
41597 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
41598 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
41599 ],
41600 [
41601 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
41602 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
41603 ],
41604 [
41605 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
41606 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
41607 ],
41608 [
41609 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
41610 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
41611 ],
41612 [
41613 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
41614 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
41615 ],
41616 [
41617 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
41618 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
41619 ],
41620 [
41621 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
41622 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
41623 ],
41624 [
41625 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
41626 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
41627 ],
41628 [
41629 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
41630 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
41631 ],
41632 [
41633 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
41634 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
41635 ],
41636 [
41637 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
41638 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
41639 ],
41640 [
41641 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
41642 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
41643 ],
41644 [
41645 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
41646 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
41647 ],
41648 [
41649 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
41650 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
41651 ],
41652 [
41653 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
41654 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
41655 ],
41656 [
41657 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
41658 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
41659 ],
41660 [
41661 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
41662 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
41663 ],
41664 [
41665 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
41666 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
41667 ],
41668 [
41669 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
41670 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
41671 ],
41672 [
41673 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
41674 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
41675 ],
41676 [
41677 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
41678 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
41679 ],
41680 [
41681 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
41682 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
41683 ],
41684 [
41685 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
41686 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
41687 ],
41688 [
41689 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
41690 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
41691 ],
41692 [
41693 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
41694 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
41695 ],
41696 [
41697 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
41698 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
41699 ],
41700 [
41701 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
41702 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
41703 ],
41704 [
41705 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
41706 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
41707 ],
41708 [
41709 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
41710 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
41711 ],
41712 [
41713 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
41714 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
41715 ],
41716 [
41717 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
41718 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
41719 ],
41720 [
41721 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
41722 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
41723 ],
41724 [
41725 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
41726 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
41727 ],
41728 [
41729 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
41730 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
41731 ],
41732 [
41733 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
41734 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
41735 ],
41736 [
41737 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
41738 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
41739 ],
41740 [
41741 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
41742 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
41743 ],
41744 [
41745 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
41746 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
41747 ],
41748 [
41749 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
41750 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
41751 ],
41752 [
41753 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
41754 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
41755 ],
41756 [
41757 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
41758 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
41759 ],
41760 [
41761 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
41762 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
41763 ],
41764 [
41765 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
41766 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
41767 ],
41768 [
41769 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
41770 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
41771 ],
41772 [
41773 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
41774 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
41775 ]
41776 ]
41777 },
41778 naf: {
41779 wnd: 7,
41780 points: [
41781 [
41782 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
41783 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
41784 ],
41785 [
41786 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
41787 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
41788 ],
41789 [
41790 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
41791 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
41792 ],
41793 [
41794 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
41795 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
41796 ],
41797 [
41798 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
41799 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
41800 ],
41801 [
41802 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
41803 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
41804 ],
41805 [
41806 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
41807 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
41808 ],
41809 [
41810 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
41811 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
41812 ],
41813 [
41814 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
41815 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
41816 ],
41817 [
41818 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
41819 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
41820 ],
41821 [
41822 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
41823 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
41824 ],
41825 [
41826 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
41827 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
41828 ],
41829 [
41830 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
41831 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
41832 ],
41833 [
41834 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
41835 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
41836 ],
41837 [
41838 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
41839 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
41840 ],
41841 [
41842 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
41843 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
41844 ],
41845 [
41846 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
41847 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
41848 ],
41849 [
41850 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
41851 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
41852 ],
41853 [
41854 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
41855 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
41856 ],
41857 [
41858 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
41859 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
41860 ],
41861 [
41862 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
41863 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
41864 ],
41865 [
41866 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
41867 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
41868 ],
41869 [
41870 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
41871 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
41872 ],
41873 [
41874 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
41875 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
41876 ],
41877 [
41878 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
41879 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
41880 ],
41881 [
41882 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
41883 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
41884 ],
41885 [
41886 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
41887 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
41888 ],
41889 [
41890 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
41891 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
41892 ],
41893 [
41894 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
41895 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
41896 ],
41897 [
41898 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
41899 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
41900 ],
41901 [
41902 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
41903 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
41904 ],
41905 [
41906 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
41907 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
41908 ],
41909 [
41910 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
41911 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
41912 ],
41913 [
41914 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
41915 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
41916 ],
41917 [
41918 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
41919 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
41920 ],
41921 [
41922 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
41923 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
41924 ],
41925 [
41926 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
41927 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
41928 ],
41929 [
41930 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
41931 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
41932 ],
41933 [
41934 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
41935 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
41936 ],
41937 [
41938 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
41939 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
41940 ],
41941 [
41942 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
41943 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
41944 ],
41945 [
41946 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
41947 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
41948 ],
41949 [
41950 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
41951 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
41952 ],
41953 [
41954 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
41955 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
41956 ],
41957 [
41958 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
41959 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
41960 ],
41961 [
41962 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
41963 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
41964 ],
41965 [
41966 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
41967 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
41968 ],
41969 [
41970 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
41971 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
41972 ],
41973 [
41974 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
41975 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
41976 ],
41977 [
41978 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
41979 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
41980 ],
41981 [
41982 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
41983 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
41984 ],
41985 [
41986 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
41987 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
41988 ],
41989 [
41990 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
41991 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
41992 ],
41993 [
41994 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
41995 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
41996 ],
41997 [
41998 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
41999 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
42000 ],
42001 [
42002 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
42003 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
42004 ],
42005 [
42006 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
42007 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
42008 ],
42009 [
42010 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
42011 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
42012 ],
42013 [
42014 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
42015 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
42016 ],
42017 [
42018 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
42019 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
42020 ],
42021 [
42022 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
42023 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
42024 ],
42025 [
42026 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
42027 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
42028 ],
42029 [
42030 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
42031 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
42032 ],
42033 [
42034 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
42035 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
42036 ],
42037 [
42038 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
42039 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
42040 ],
42041 [
42042 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
42043 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
42044 ],
42045 [
42046 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
42047 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
42048 ],
42049 [
42050 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
42051 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
42052 ],
42053 [
42054 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
42055 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
42056 ],
42057 [
42058 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
42059 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
42060 ],
42061 [
42062 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
42063 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
42064 ],
42065 [
42066 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
42067 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
42068 ],
42069 [
42070 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
42071 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
42072 ],
42073 [
42074 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
42075 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
42076 ],
42077 [
42078 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
42079 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
42080 ],
42081 [
42082 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
42083 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
42084 ],
42085 [
42086 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
42087 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
42088 ],
42089 [
42090 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
42091 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
42092 ],
42093 [
42094 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
42095 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
42096 ],
42097 [
42098 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
42099 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
42100 ],
42101 [
42102 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
42103 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
42104 ],
42105 [
42106 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
42107 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
42108 ],
42109 [
42110 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
42111 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
42112 ],
42113 [
42114 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
42115 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
42116 ],
42117 [
42118 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
42119 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
42120 ],
42121 [
42122 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
42123 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
42124 ],
42125 [
42126 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
42127 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
42128 ],
42129 [
42130 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
42131 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
42132 ],
42133 [
42134 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
42135 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
42136 ],
42137 [
42138 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
42139 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
42140 ],
42141 [
42142 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
42143 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
42144 ],
42145 [
42146 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
42147 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
42148 ],
42149 [
42150 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
42151 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
42152 ],
42153 [
42154 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
42155 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
42156 ],
42157 [
42158 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
42159 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
42160 ],
42161 [
42162 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
42163 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
42164 ],
42165 [
42166 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
42167 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
42168 ],
42169 [
42170 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
42171 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
42172 ],
42173 [
42174 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
42175 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
42176 ],
42177 [
42178 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
42179 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
42180 ],
42181 [
42182 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
42183 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
42184 ],
42185 [
42186 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
42187 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
42188 ],
42189 [
42190 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
42191 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
42192 ],
42193 [
42194 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
42195 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
42196 ],
42197 [
42198 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
42199 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
42200 ],
42201 [
42202 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
42203 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
42204 ],
42205 [
42206 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
42207 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
42208 ],
42209 [
42210 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
42211 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
42212 ],
42213 [
42214 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
42215 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
42216 ],
42217 [
42218 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
42219 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
42220 ],
42221 [
42222 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
42223 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
42224 ],
42225 [
42226 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
42227 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
42228 ],
42229 [
42230 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
42231 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
42232 ],
42233 [
42234 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
42235 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
42236 ],
42237 [
42238 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
42239 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
42240 ],
42241 [
42242 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
42243 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
42244 ],
42245 [
42246 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
42247 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
42248 ],
42249 [
42250 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
42251 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
42252 ],
42253 [
42254 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
42255 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
42256 ],
42257 [
42258 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
42259 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
42260 ],
42261 [
42262 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
42263 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
42264 ],
42265 [
42266 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
42267 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
42268 ],
42269 [
42270 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
42271 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
42272 ],
42273 [
42274 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
42275 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
42276 ],
42277 [
42278 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
42279 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
42280 ],
42281 [
42282 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
42283 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
42284 ],
42285 [
42286 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
42287 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
42288 ]
42289 ]
42290 }
42291};
42292
42293var curves_1 = createCommonjsModule(function (module, exports) {
42294
42295var curves = exports;
42296
42297
42298
42299
42300
42301var assert = utils_1$1.assert;
42302
42303function PresetCurve(options) {
42304 if (options.type === 'short')
42305 this.curve = new curve_1.short(options);
42306 else if (options.type === 'edwards')
42307 this.curve = new curve_1.edwards(options);
42308 else if (options.type === 'mont')
42309 this.curve = new curve_1.mont(options);
42310 else throw new Error('Unknown curve type.');
42311 this.g = this.curve.g;
42312 this.n = this.curve.n;
42313 this.hash = options.hash;
42314
42315 assert(this.g.validate(), 'Invalid curve');
42316 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
42317}
42318curves.PresetCurve = PresetCurve;
42319
42320function defineCurve(name, options) {
42321 Object.defineProperty(curves, name, {
42322 configurable: true,
42323 enumerable: true,
42324 get: function() {
42325 var curve = new PresetCurve(options);
42326 Object.defineProperty(curves, name, {
42327 configurable: true,
42328 enumerable: true,
42329 value: curve
42330 });
42331 return curve;
42332 }
42333 });
42334}
42335
42336defineCurve('p192', {
42337 type: 'short',
42338 prime: 'p192',
42339 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
42340 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
42341 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
42342 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
42343 hash: hash_1.sha256,
42344 gRed: false,
42345 g: [
42346 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
42347 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
42348 ]
42349});
42350
42351defineCurve('p224', {
42352 type: 'short',
42353 prime: 'p224',
42354 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
42355 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
42356 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
42357 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
42358 hash: hash_1.sha256,
42359 gRed: false,
42360 g: [
42361 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
42362 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
42363 ]
42364});
42365
42366defineCurve('p256', {
42367 type: 'short',
42368 prime: null,
42369 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
42370 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
42371 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
42372 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
42373 hash: hash_1.sha256,
42374 gRed: false,
42375 g: [
42376 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
42377 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
42378 ]
42379});
42380
42381defineCurve('p384', {
42382 type: 'short',
42383 prime: null,
42384 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42385 'fffffffe ffffffff 00000000 00000000 ffffffff',
42386 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42387 'fffffffe ffffffff 00000000 00000000 fffffffc',
42388 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
42389 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
42390 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
42391 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
42392 hash: hash_1.sha384,
42393 gRed: false,
42394 g: [
42395 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
42396 '5502f25d bf55296c 3a545e38 72760ab7',
42397 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
42398 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
42399 ]
42400});
42401
42402defineCurve('p521', {
42403 type: 'short',
42404 prime: null,
42405 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42406 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42407 'ffffffff ffffffff ffffffff ffffffff ffffffff',
42408 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42409 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42410 'ffffffff ffffffff ffffffff ffffffff fffffffc',
42411 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
42412 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
42413 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
42414 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42415 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
42416 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
42417 hash: hash_1.sha512,
42418 gRed: false,
42419 g: [
42420 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
42421 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
42422 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
42423 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
42424 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
42425 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
42426 ]
42427});
42428
42429// https://tools.ietf.org/html/rfc7748#section-4.1
42430defineCurve('curve25519', {
42431 type: 'mont',
42432 prime: 'p25519',
42433 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42434 a: '76d06',
42435 b: '1',
42436 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42437 cofactor: '8',
42438 hash: hash_1.sha256,
42439 gRed: false,
42440 g: [
42441 '9'
42442 ]
42443});
42444
42445defineCurve('ed25519', {
42446 type: 'edwards',
42447 prime: 'p25519',
42448 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42449 a: '-1',
42450 c: '1',
42451 // -121665 * (121666^(-1)) (mod P)
42452 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
42453 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42454 cofactor: '8',
42455 hash: hash_1.sha256,
42456 gRed: false,
42457 g: [
42458 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
42459 // 4/5
42460 '6666666666666666666666666666666666666666666666666666666666666658'
42461 ]
42462});
42463
42464// https://tools.ietf.org/html/rfc5639#section-3.4
42465defineCurve('brainpoolP256r1', {
42466 type: 'short',
42467 prime: null,
42468 p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
42469 a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
42470 b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
42471 n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
42472 hash: hash_1.sha256, // or 384, or 512
42473 gRed: false,
42474 g: [
42475 '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
42476 '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
42477 ]
42478});
42479
42480// https://tools.ietf.org/html/rfc5639#section-3.6
42481defineCurve('brainpoolP384r1', {
42482 type: 'short',
42483 prime: null,
42484 p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
42485 'ACD3A729 901D1A71 87470013 3107EC53',
42486 a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
42487 '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
42488 b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
42489 '7CB43902 95DBC994 3AB78696 FA504C11',
42490 n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
42491 'CF3AB6AF 6B7FC310 3B883202 E9046565',
42492 hash: hash_1.sha384, // or 512
42493 gRed: false,
42494 g: [
42495 '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
42496 'E8E826E03436D646AAEF87B2E247D4AF1E',
42497 '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
42498 '280E4646217791811142820341263C5315'
42499 ]
42500});
42501
42502// https://tools.ietf.org/html/rfc5639#section-3.7
42503defineCurve('brainpoolP512r1', {
42504 type: 'short',
42505 prime: null,
42506 p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
42507 '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
42508 a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
42509 '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
42510 b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
42511 '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
42512 n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
42513 '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
42514 hash: hash_1.sha512,
42515 gRed: false,
42516 g: [
42517 '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
42518 '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
42519 '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
42520 '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
42521 ]
42522});
42523
42524// https://en.bitcoin.it/wiki/Secp256k1
42525var pre;
42526try {
42527 pre = secp256k1;
42528} catch (e) {
42529 pre = undefined;
42530}
42531
42532defineCurve('secp256k1', {
42533 type: 'short',
42534 prime: 'k256',
42535 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
42536 a: '0',
42537 b: '7',
42538 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
42539 h: '1',
42540 hash: hash_1.sha256,
42541
42542 // Precomputed endomorphism
42543 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
42544 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
42545 basis: [
42546 {
42547 a: '3086d221a7d46bcde86c90e49284eb15',
42548 b: '-e4437ed6010e88286f547fa90abfe4c3'
42549 },
42550 {
42551 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
42552 b: '3086d221a7d46bcde86c90e49284eb15'
42553 }
42554 ],
42555
42556 gRed: false,
42557 g: [
42558 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
42559 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
42560 pre
42561 ]
42562});
42563});
42564
42565function HmacDRBG(options) {
42566 if (!(this instanceof HmacDRBG))
42567 return new HmacDRBG(options);
42568 this.hash = options.hash;
42569 this.predResist = !!options.predResist;
42570
42571 this.outLen = this.hash.outSize;
42572 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
42573
42574 this._reseed = null;
42575 this.reseedInterval = null;
42576 this.K = null;
42577 this.V = null;
42578
42579 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
42580 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
42581 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
42582 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42583 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42584 this._init(entropy, nonce, pers);
42585}
42586var hmacDrbg = HmacDRBG;
42587
42588HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
42589 var seed = entropy.concat(nonce).concat(pers);
42590
42591 this.K = new Array(this.outLen / 8);
42592 this.V = new Array(this.outLen / 8);
42593 for (var i = 0; i < this.V.length; i++) {
42594 this.K[i] = 0x00;
42595 this.V[i] = 0x01;
42596 }
42597
42598 this._update(seed);
42599 this._reseed = 1;
42600 this.reseedInterval = 0x1000000000000; // 2^48
42601};
42602
42603HmacDRBG.prototype._hmac = function hmac() {
42604 return new hash_1.hmac(this.hash, this.K);
42605};
42606
42607HmacDRBG.prototype._update = function update(seed) {
42608 var kmac = this._hmac()
42609 .update(this.V)
42610 .update([ 0x00 ]);
42611 if (seed)
42612 kmac = kmac.update(seed);
42613 this.K = kmac.digest();
42614 this.V = this._hmac().update(this.V).digest();
42615 if (!seed)
42616 return;
42617
42618 this.K = this._hmac()
42619 .update(this.V)
42620 .update([ 0x01 ])
42621 .update(seed)
42622 .digest();
42623 this.V = this._hmac().update(this.V).digest();
42624};
42625
42626HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
42627 // Optional entropy enc
42628 if (typeof entropyEnc !== 'string') {
42629 addEnc = add;
42630 add = entropyEnc;
42631 entropyEnc = null;
42632 }
42633
42634 entropy = utils_1.toArray(entropy, entropyEnc);
42635 add = utils_1.toArray(add, addEnc);
42636
42637 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42638 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42639
42640 this._update(entropy.concat(add || []));
42641 this._reseed = 1;
42642};
42643
42644HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
42645 if (this._reseed > this.reseedInterval)
42646 throw new Error('Reseed is required');
42647
42648 // Optional encoding
42649 if (typeof enc !== 'string') {
42650 addEnc = add;
42651 add = enc;
42652 enc = null;
42653 }
42654
42655 // Optional additional data
42656 if (add) {
42657 add = utils_1.toArray(add, addEnc || 'hex');
42658 this._update(add);
42659 }
42660
42661 var temp = [];
42662 while (temp.length < len) {
42663 this.V = this._hmac().update(this.V).digest();
42664 temp = temp.concat(this.V);
42665 }
42666
42667 var res = temp.slice(0, len);
42668 this._update(add);
42669 this._reseed++;
42670 return utils_1.encode(res, enc);
42671};
42672
42673var assert$5 = utils_1$1.assert;
42674
42675function KeyPair(ec, options) {
42676 this.ec = ec;
42677 this.priv = null;
42678 this.pub = null;
42679
42680 // KeyPair(ec, { priv: ..., pub: ... })
42681 if (options.priv)
42682 this._importPrivate(options.priv, options.privEnc);
42683 if (options.pub)
42684 this._importPublic(options.pub, options.pubEnc);
42685}
42686var key = KeyPair;
42687
42688KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
42689 if (pub instanceof KeyPair)
42690 return pub;
42691
42692 return new KeyPair(ec, {
42693 pub: pub,
42694 pubEnc: enc
42695 });
42696};
42697
42698KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
42699 if (priv instanceof KeyPair)
42700 return priv;
42701
42702 return new KeyPair(ec, {
42703 priv: priv,
42704 privEnc: enc
42705 });
42706};
42707
42708// TODO: should not validate for X25519
42709KeyPair.prototype.validate = function validate() {
42710 var pub = this.getPublic();
42711
42712 if (pub.isInfinity())
42713 return { result: false, reason: 'Invalid public key' };
42714 if (!pub.validate())
42715 return { result: false, reason: 'Public key is not a point' };
42716 if (!pub.mul(this.ec.curve.n).isInfinity())
42717 return { result: false, reason: 'Public key * N != O' };
42718
42719 return { result: true, reason: null };
42720};
42721
42722KeyPair.prototype.getPublic = function getPublic(enc, compact) {
42723 if (!this.pub)
42724 this.pub = this.ec.g.mul(this.priv);
42725
42726 if (!enc)
42727 return this.pub;
42728
42729 return this.pub.encode(enc, compact);
42730};
42731
42732KeyPair.prototype.getPrivate = function getPrivate(enc) {
42733 if (enc === 'hex')
42734 return this.priv.toString(16, 2);
42735 else
42736 return this.priv;
42737};
42738
42739KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
42740 this.priv = new bn(key, enc || 16);
42741
42742 // For Curve25519/Curve448 we have a specific procedure.
42743 // TODO Curve448
42744 if (this.ec.curve.type === 'mont') {
42745 var one = this.ec.curve.one;
42746 var mask = one.ushln(255 - 3).sub(one).ushln(3);
42747 this.priv = this.priv.or(one.ushln(255 - 1));
42748 this.priv = this.priv.and(mask);
42749 } else
42750 // Ensure that the priv won't be bigger than n, otherwise we may fail
42751 // in fixed multiplication method
42752 this.priv = this.priv.umod(this.ec.curve.n);
42753};
42754
42755KeyPair.prototype._importPublic = function _importPublic(key, enc) {
42756 if (key.x || key.y) {
42757 // Montgomery points only have an `x` coordinate.
42758 // Weierstrass/Edwards points on the other hand have both `x` and
42759 // `y` coordinates.
42760 if (this.ec.curve.type === 'mont') {
42761 assert$5(key.x, 'Need x coordinate');
42762 } else if (this.ec.curve.type === 'short' ||
42763 this.ec.curve.type === 'edwards') {
42764 assert$5(key.x && key.y, 'Need both x and y coordinate');
42765 }
42766 this.pub = this.ec.curve.point(key.x, key.y);
42767 return;
42768 }
42769 this.pub = this.ec.curve.decodePoint(key, enc);
42770};
42771
42772// ECDH
42773KeyPair.prototype.derive = function derive(pub) {
42774 return pub.mul(this.priv).getX();
42775};
42776
42777// ECDSA
42778KeyPair.prototype.sign = function sign(msg, enc, options) {
42779 return this.ec.sign(msg, this, enc, options);
42780};
42781
42782KeyPair.prototype.verify = function verify(msg, signature) {
42783 return this.ec.verify(msg, signature, this);
42784};
42785
42786KeyPair.prototype.inspect = function inspect() {
42787 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
42788 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
42789};
42790
42791var assert$6 = utils_1$1.assert;
42792
42793function Signature$1(options, enc) {
42794 if (options instanceof Signature$1)
42795 return options;
42796
42797 if (this._importDER(options, enc))
42798 return;
42799
42800 assert$6(options.r && options.s, 'Signature without r or s');
42801 this.r = new bn(options.r, 16);
42802 this.s = new bn(options.s, 16);
42803 if (options.recoveryParam === undefined)
42804 this.recoveryParam = null;
42805 else
42806 this.recoveryParam = options.recoveryParam;
42807}
42808var signature$1 = Signature$1;
42809
42810function Position() {
42811 this.place = 0;
42812}
42813
42814function getLength(buf, p) {
42815 var initial = buf[p.place++];
42816 if (!(initial & 0x80)) {
42817 return initial;
42818 }
42819 var octetLen = initial & 0xf;
42820 var val = 0;
42821 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
42822 val <<= 8;
42823 val |= buf[off];
42824 }
42825 p.place = off;
42826 return val;
42827}
42828
42829function rmPadding(buf) {
42830 var i = 0;
42831 var len = buf.length - 1;
42832 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
42833 i++;
42834 }
42835 if (i === 0) {
42836 return buf;
42837 }
42838 return buf.slice(i);
42839}
42840
42841Signature$1.prototype._importDER = function _importDER(data, enc) {
42842 data = utils_1$1.toArray(data, enc);
42843 var p = new Position();
42844 if (data[p.place++] !== 0x30) {
42845 return false;
42846 }
42847 var len = getLength(data, p);
42848 if ((len + p.place) !== data.length) {
42849 return false;
42850 }
42851 if (data[p.place++] !== 0x02) {
42852 return false;
42853 }
42854 var rlen = getLength(data, p);
42855 var r = data.slice(p.place, rlen + p.place);
42856 p.place += rlen;
42857 if (data[p.place++] !== 0x02) {
42858 return false;
42859 }
42860 var slen = getLength(data, p);
42861 if (data.length !== slen + p.place) {
42862 return false;
42863 }
42864 var s = data.slice(p.place, slen + p.place);
42865 if (r[0] === 0 && (r[1] & 0x80)) {
42866 r = r.slice(1);
42867 }
42868 if (s[0] === 0 && (s[1] & 0x80)) {
42869 s = s.slice(1);
42870 }
42871
42872 this.r = new bn(r);
42873 this.s = new bn(s);
42874 this.recoveryParam = null;
42875
42876 return true;
42877};
42878
42879function constructLength(arr, len) {
42880 if (len < 0x80) {
42881 arr.push(len);
42882 return;
42883 }
42884 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
42885 arr.push(octets | 0x80);
42886 while (--octets) {
42887 arr.push((len >>> (octets << 3)) & 0xff);
42888 }
42889 arr.push(len);
42890}
42891
42892Signature$1.prototype.toDER = function toDER(enc) {
42893 var r = this.r.toArray();
42894 var s = this.s.toArray();
42895
42896 // Pad values
42897 if (r[0] & 0x80)
42898 r = [ 0 ].concat(r);
42899 // Pad values
42900 if (s[0] & 0x80)
42901 s = [ 0 ].concat(s);
42902
42903 r = rmPadding(r);
42904 s = rmPadding(s);
42905
42906 while (!s[0] && !(s[1] & 0x80)) {
42907 s = s.slice(1);
42908 }
42909 var arr = [ 0x02 ];
42910 constructLength(arr, r.length);
42911 arr = arr.concat(r);
42912 arr.push(0x02);
42913 constructLength(arr, s.length);
42914 var backHalf = arr.concat(s);
42915 var res = [ 0x30 ];
42916 constructLength(res, backHalf.length);
42917 res = res.concat(backHalf);
42918 return utils_1$1.encode(res, enc);
42919};
42920
42921var assert$7 = utils_1$1.assert;
42922
42923
42924
42925
42926function EC(options) {
42927 if (!(this instanceof EC))
42928 return new EC(options);
42929
42930 // Shortcut `elliptic.ec(curve-name)`
42931 if (typeof options === 'string') {
42932 assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
42933
42934 options = curves_1[options];
42935 }
42936
42937 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
42938 if (options instanceof curves_1.PresetCurve)
42939 options = { curve: options };
42940
42941 this.curve = options.curve.curve;
42942 this.n = this.curve.n;
42943 this.nh = this.n.ushrn(1);
42944 this.g = this.curve.g;
42945
42946 // Point on curve
42947 this.g = options.curve.g;
42948 this.g.precompute(options.curve.n.bitLength() + 1);
42949
42950 // Hash function for DRBG
42951 this.hash = options.hash || options.curve.hash;
42952}
42953var ec = EC;
42954
42955EC.prototype.keyPair = function keyPair(options) {
42956 return new key(this, options);
42957};
42958
42959EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
42960 return key.fromPrivate(this, priv, enc);
42961};
42962
42963EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
42964 return key.fromPublic(this, pub, enc);
42965};
42966
42967EC.prototype.genKeyPair = function genKeyPair(options) {
42968 if (!options)
42969 options = {};
42970
42971 // Instantiate Hmac_DRBG
42972 var drbg = new hmacDrbg({
42973 hash: this.hash,
42974 pers: options.pers,
42975 persEnc: options.persEnc || 'utf8',
42976 entropy: options.entropy || brorand(this.hash.hmacStrength),
42977 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
42978 nonce: this.n.toArray()
42979 });
42980
42981 // Key generation for curve25519 is simpler
42982 if (this.curve.type === 'mont') {
42983 var priv = new bn(drbg.generate(32));
42984 return this.keyFromPrivate(priv);
42985 }
42986
42987 var bytes = this.n.byteLength();
42988 var ns2 = this.n.sub(new bn(2));
42989 do {
42990 var priv = new bn(drbg.generate(bytes));
42991 if (priv.cmp(ns2) > 0)
42992 continue;
42993
42994 priv.iaddn(1);
42995 return this.keyFromPrivate(priv);
42996 } while (true);
42997};
42998
42999EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
43000 bitSize = bitSize || msg.byteLength() * 8;
43001 var delta = bitSize - this.n.bitLength();
43002 if (delta > 0)
43003 msg = msg.ushrn(delta);
43004 if (!truncOnly && msg.cmp(this.n) >= 0)
43005 return msg.sub(this.n);
43006 else
43007 return msg;
43008};
43009
43010EC.prototype.truncateMsg = function truncateMSG(msg) {
43011 // Bit size is only determined correctly for Uint8Arrays and hex strings
43012 var bitSize;
43013 if (msg instanceof Uint8Array) {
43014 bitSize = msg.byteLength * 8;
43015 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43016 } else if (typeof msg === 'string') {
43017 bitSize = msg.length * 4;
43018 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43019 } else {
43020 msg = this._truncateToN(new bn(msg, 16));
43021 }
43022 return msg;
43023};
43024
43025EC.prototype.sign = function sign(msg, key, enc, options) {
43026 if (typeof enc === 'object') {
43027 options = enc;
43028 enc = null;
43029 }
43030 if (!options)
43031 options = {};
43032
43033 key = this.keyFromPrivate(key, enc);
43034 msg = this.truncateMsg(msg);
43035
43036 // Zero-extend key to provide enough entropy
43037 var bytes = this.n.byteLength();
43038 var bkey = key.getPrivate().toArray('be', bytes);
43039
43040 // Zero-extend nonce to have the same byte size as N
43041 var nonce = msg.toArray('be', bytes);
43042
43043 // Instantiate Hmac_DRBG
43044 var drbg = new hmacDrbg({
43045 hash: this.hash,
43046 entropy: bkey,
43047 nonce: nonce,
43048 pers: options.pers,
43049 persEnc: options.persEnc || 'utf8'
43050 });
43051
43052 // Number of bytes to generate
43053 var ns1 = this.n.sub(new bn(1));
43054
43055 for (var iter = 0; true; iter++) {
43056 var k = options.k ?
43057 options.k(iter) :
43058 new bn(drbg.generate(this.n.byteLength()));
43059 k = this._truncateToN(k, true);
43060 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
43061 continue;
43062
43063 var kp = this.g.mul(k);
43064 if (kp.isInfinity())
43065 continue;
43066
43067 var kpX = kp.getX();
43068 var r = kpX.umod(this.n);
43069 if (r.cmpn(0) === 0)
43070 continue;
43071
43072 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
43073 s = s.umod(this.n);
43074 if (s.cmpn(0) === 0)
43075 continue;
43076
43077 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
43078 (kpX.cmp(r) !== 0 ? 2 : 0);
43079
43080 // Use complement of `s`, if it is > `n / 2`
43081 if (options.canonical && s.cmp(this.nh) > 0) {
43082 s = this.n.sub(s);
43083 recoveryParam ^= 1;
43084 }
43085
43086 return new signature$1({ r: r, s: s, recoveryParam: recoveryParam });
43087 }
43088};
43089
43090EC.prototype.verify = function verify(msg, signature, key, enc) {
43091 key = this.keyFromPublic(key, enc);
43092 signature = new signature$1(signature, 'hex');
43093 // Fallback to the old code
43094 var ret = this._verify(this.truncateMsg(msg), signature, key) ||
43095 this._verify(this._truncateToN(new bn(msg, 16)), signature, key);
43096 return ret;
43097};
43098
43099EC.prototype._verify = function _verify(msg, signature, key) {
43100 // Perform primitive values validation
43101 var r = signature.r;
43102 var s = signature.s;
43103 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
43104 return false;
43105 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
43106 return false;
43107
43108 // Validate signature
43109 var sinv = s.invm(this.n);
43110 var u1 = sinv.mul(msg).umod(this.n);
43111 var u2 = sinv.mul(r).umod(this.n);
43112
43113 if (!this.curve._maxwellTrick) {
43114 var p = this.g.mulAdd(u1, key.getPublic(), u2);
43115 if (p.isInfinity())
43116 return false;
43117
43118 return p.getX().umod(this.n).cmp(r) === 0;
43119 }
43120
43121 // NOTE: Greg Maxwell's trick, inspired by:
43122 // https://git.io/vad3K
43123
43124 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
43125 if (p.isInfinity())
43126 return false;
43127
43128 // Compare `p.x` of Jacobian point with `r`,
43129 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
43130 // inverse of `p.z^2`
43131 return p.eqXToP(r);
43132};
43133
43134EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
43135 assert$7((3 & j) === j, 'The recovery param is more than two bits');
43136 signature = new signature$1(signature, enc);
43137
43138 var n = this.n;
43139 var e = new bn(msg);
43140 var r = signature.r;
43141 var s = signature.s;
43142
43143 // A set LSB signifies that the y-coordinate is odd
43144 var isYOdd = j & 1;
43145 var isSecondKey = j >> 1;
43146 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
43147 throw new Error('Unable to find sencond key candinate');
43148
43149 // 1.1. Let x = r + jn.
43150 if (isSecondKey)
43151 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
43152 else
43153 r = this.curve.pointFromX(r, isYOdd);
43154
43155 var rInv = signature.r.invm(n);
43156 var s1 = n.sub(e).mul(rInv).umod(n);
43157 var s2 = s.mul(rInv).umod(n);
43158
43159 // 1.6.1 Compute Q = r^-1 (sR - eG)
43160 // Q = r^-1 (sR + -eG)
43161 return this.g.mulAdd(s1, r, s2);
43162};
43163
43164EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
43165 signature = new signature$1(signature, enc);
43166 if (signature.recoveryParam !== null)
43167 return signature.recoveryParam;
43168
43169 for (var i = 0; i < 4; i++) {
43170 var Qprime;
43171 try {
43172 Qprime = this.recoverPubKey(e, signature, i);
43173 } catch (e) {
43174 continue;
43175 }
43176
43177 if (Qprime.eq(Q))
43178 return i;
43179 }
43180 throw new Error('Unable to find valid recovery factor');
43181};
43182
43183var assert$8 = utils_1$1.assert;
43184var parseBytes = utils_1$1.parseBytes;
43185var cachedProperty = utils_1$1.cachedProperty;
43186
43187/**
43188* @param {EDDSA} eddsa - instance
43189* @param {Object} params - public/private key parameters
43190*
43191* @param {Array<Byte>} [params.secret] - secret seed bytes
43192* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
43193* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
43194*
43195*/
43196function KeyPair$1(eddsa, params) {
43197 this.eddsa = eddsa;
43198 if (params.hasOwnProperty('secret'))
43199 this._secret = parseBytes(params.secret);
43200 if (eddsa.isPoint(params.pub))
43201 this._pub = params.pub;
43202 else {
43203 this._pubBytes = parseBytes(params.pub);
43204 if (this._pubBytes && this._pubBytes.length === 33 &&
43205 this._pubBytes[0] === 0x40)
43206 this._pubBytes = this._pubBytes.slice(1, 33);
43207 if (this._pubBytes && this._pubBytes.length !== 32)
43208 throw new Error('Unknown point compression format');
43209 }
43210}
43211
43212KeyPair$1.fromPublic = function fromPublic(eddsa, pub) {
43213 if (pub instanceof KeyPair$1)
43214 return pub;
43215 return new KeyPair$1(eddsa, { pub: pub });
43216};
43217
43218KeyPair$1.fromSecret = function fromSecret(eddsa, secret) {
43219 if (secret instanceof KeyPair$1)
43220 return secret;
43221 return new KeyPair$1(eddsa, { secret: secret });
43222};
43223
43224KeyPair$1.prototype.secret = function secret() {
43225 return this._secret;
43226};
43227
43228cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() {
43229 return this.eddsa.encodePoint(this.pub());
43230});
43231
43232cachedProperty(KeyPair$1, 'pub', function pub() {
43233 if (this._pubBytes)
43234 return this.eddsa.decodePoint(this._pubBytes);
43235 return this.eddsa.g.mul(this.priv());
43236});
43237
43238cachedProperty(KeyPair$1, 'privBytes', function privBytes() {
43239 var eddsa = this.eddsa;
43240 var hash = this.hash();
43241 var lastIx = eddsa.encodingLength - 1;
43242
43243 // https://tools.ietf.org/html/rfc8032#section-5.1.5
43244 var a = hash.slice(0, eddsa.encodingLength);
43245 a[0] &= 248;
43246 a[lastIx] &= 127;
43247 a[lastIx] |= 64;
43248
43249 return a;
43250});
43251
43252cachedProperty(KeyPair$1, 'priv', function priv() {
43253 return this.eddsa.decodeInt(this.privBytes());
43254});
43255
43256cachedProperty(KeyPair$1, 'hash', function hash() {
43257 return this.eddsa.hash().update(this.secret()).digest();
43258});
43259
43260cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() {
43261 return this.hash().slice(this.eddsa.encodingLength);
43262});
43263
43264KeyPair$1.prototype.sign = function sign(message) {
43265 assert$8(this._secret, 'KeyPair can only verify');
43266 return this.eddsa.sign(message, this);
43267};
43268
43269KeyPair$1.prototype.verify = function verify(message, sig) {
43270 return this.eddsa.verify(message, sig, this);
43271};
43272
43273KeyPair$1.prototype.getSecret = function getSecret(enc) {
43274 assert$8(this._secret, 'KeyPair is public only');
43275 return utils_1$1.encode(this.secret(), enc);
43276};
43277
43278KeyPair$1.prototype.getPublic = function getPublic(enc, compact) {
43279 return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
43280};
43281
43282var key$1 = KeyPair$1;
43283
43284var assert$9 = utils_1$1.assert;
43285var cachedProperty$1 = utils_1$1.cachedProperty;
43286var parseBytes$1 = utils_1$1.parseBytes;
43287
43288/**
43289* @param {EDDSA} eddsa - eddsa instance
43290* @param {Array<Bytes>|Object} sig -
43291* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
43292* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
43293* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
43294* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
43295*/
43296function Signature$2(eddsa, sig) {
43297 this.eddsa = eddsa;
43298
43299 if (typeof sig !== 'object')
43300 sig = parseBytes$1(sig);
43301
43302 if (Array.isArray(sig)) {
43303 sig = {
43304 R: sig.slice(0, eddsa.encodingLength),
43305 S: sig.slice(eddsa.encodingLength)
43306 };
43307 }
43308
43309 assert$9(sig.R && sig.S, 'Signature without R or S');
43310
43311 if (eddsa.isPoint(sig.R))
43312 this._R = sig.R;
43313 if (sig.S instanceof bn)
43314 this._S = sig.S;
43315
43316 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
43317 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
43318}
43319
43320cachedProperty$1(Signature$2, 'S', function S() {
43321 return this.eddsa.decodeInt(this.Sencoded());
43322});
43323
43324cachedProperty$1(Signature$2, 'R', function R() {
43325 return this.eddsa.decodePoint(this.Rencoded());
43326});
43327
43328cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() {
43329 return this.eddsa.encodePoint(this.R());
43330});
43331
43332cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() {
43333 return this.eddsa.encodeInt(this.S());
43334});
43335
43336Signature$2.prototype.toBytes = function toBytes() {
43337 return this.Rencoded().concat(this.Sencoded());
43338};
43339
43340Signature$2.prototype.toHex = function toHex() {
43341 return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase();
43342};
43343
43344var signature$2 = Signature$2;
43345
43346var assert$a = utils_1$1.assert;
43347var parseBytes$2 = utils_1$1.parseBytes;
43348
43349
43350
43351function EDDSA(curve) {
43352 assert$a(curve === 'ed25519', 'only tested with ed25519 so far');
43353
43354 if (!(this instanceof EDDSA))
43355 return new EDDSA(curve);
43356
43357 var curve = curves_1[curve].curve;
43358 this.curve = curve;
43359 this.g = curve.g;
43360 this.g.precompute(curve.n.bitLength() + 1);
43361
43362 this.pointClass = curve.point().constructor;
43363 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
43364 this.hash = hash_1.sha512;
43365}
43366
43367var eddsa$1 = EDDSA;
43368
43369/**
43370* @param {Array|String} message - message bytes
43371* @param {Array|String|KeyPair} secret - secret bytes or a keypair
43372* @returns {Signature} - signature
43373*/
43374EDDSA.prototype.sign = function sign(message, secret) {
43375 message = parseBytes$2(message);
43376 var key = this.keyFromSecret(secret);
43377 var r = this.hashInt(key.messagePrefix(), message);
43378 var R = this.g.mul(r);
43379 var Rencoded = this.encodePoint(R);
43380 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
43381 .mul(key.priv());
43382 var S = r.add(s_).umod(this.curve.n);
43383 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
43384};
43385
43386/**
43387* @param {Array} message - message bytes
43388* @param {Array|String|Signature} sig - sig bytes
43389* @param {Array|String|Point|KeyPair} pub - public key
43390* @returns {Boolean} - true if public key matches sig of message
43391*/
43392EDDSA.prototype.verify = function verify(message, sig, pub) {
43393 message = parseBytes$2(message);
43394 sig = this.makeSignature(sig);
43395 var key = this.keyFromPublic(pub);
43396 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
43397 var SG = this.g.mul(sig.S());
43398 var RplusAh = sig.R().add(key.pub().mul(h));
43399 return RplusAh.eq(SG);
43400};
43401
43402EDDSA.prototype.hashInt = function hashInt() {
43403 var hash = this.hash();
43404 for (var i = 0; i < arguments.length; i++)
43405 hash.update(arguments[i]);
43406 return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n);
43407};
43408
43409EDDSA.prototype.keyPair = function keyPair(options) {
43410 return new key$1(this, options);
43411};
43412
43413EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
43414 return key$1.fromPublic(this, pub);
43415};
43416
43417EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
43418 return key$1.fromSecret(this, secret);
43419};
43420
43421EDDSA.prototype.genKeyPair = function genKeyPair(options) {
43422 if (!options)
43423 options = {};
43424
43425 // Instantiate Hmac_DRBG
43426 var drbg = new hmacDrbg({
43427 hash: this.hash,
43428 pers: options.pers,
43429 persEnc: options.persEnc || 'utf8',
43430 entropy: options.entropy || brorand(this.hash.hmacStrength),
43431 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43432 nonce: this.curve.n.toArray()
43433 });
43434
43435 return this.keyFromSecret(drbg.generate(32));
43436};
43437
43438EDDSA.prototype.makeSignature = function makeSignature(sig) {
43439 if (sig instanceof signature$2)
43440 return sig;
43441 return new signature$2(this, sig);
43442};
43443
43444/**
43445* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
43446*
43447* EDDSA defines methods for encoding and decoding points and integers. These are
43448* helper convenience methods, that pass along to utility functions implied
43449* parameters.
43450*
43451*/
43452EDDSA.prototype.encodePoint = function encodePoint(point) {
43453 var enc = point.getY().toArray('le', this.encodingLength);
43454 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
43455 return enc;
43456};
43457
43458EDDSA.prototype.decodePoint = function decodePoint(bytes) {
43459 bytes = utils_1$1.parseBytes(bytes);
43460
43461 var lastIx = bytes.length - 1;
43462 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
43463 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
43464
43465 var y = utils_1$1.intFromLE(normed);
43466 return this.curve.pointFromY(y, xIsOdd);
43467};
43468
43469EDDSA.prototype.encodeInt = function encodeInt(num) {
43470 return num.toArray('le', this.encodingLength);
43471};
43472
43473EDDSA.prototype.decodeInt = function decodeInt(bytes) {
43474 return utils_1$1.intFromLE(bytes);
43475};
43476
43477EDDSA.prototype.isPoint = function isPoint(val) {
43478 return val instanceof this.pointClass;
43479};
43480
43481var elliptic_1 = createCommonjsModule(function (module, exports) {
43482
43483var elliptic = exports;
43484
43485elliptic.utils = utils_1$1;
43486elliptic.rand = brorand;
43487elliptic.curve = curve_1;
43488elliptic.curves = curves_1;
43489
43490// Protocols
43491elliptic.ec = ec;
43492elliptic.eddsa = eddsa$1;
43493});
43494
43495var elliptic$1 = /*#__PURE__*/Object.freeze({
43496 __proto__: null,
43497 'default': elliptic_1,
43498 __moduleExports: elliptic_1
43499});
43500
43501export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, defaultConfig as config, createCleartextMessage, createMessage, decrypt$4 as decrypt, decryptKey, decryptSessionKeys, encrypt$4 as encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey$1 as generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign$5 as sign, unarmor, verify$5 as verify };