UNPKG

1.46 MBJavaScriptView Raw
1/*! OpenPGP.js v5.5.0 - 2022-08-31 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
2'use strict';
3
4const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5
6Object.defineProperty(exports, '__esModule', { value: true });
7
8var buffer = require('buffer');
9var stream$1 = require('stream');
10var crypto$3 = require('crypto');
11var zlib = require('zlib');
12var os = require('os');
13var util$1 = require('util');
14var asn1$2 = require('asn1.js');
15
16function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
18var buffer__default = /*#__PURE__*/_interopDefaultLegacy(buffer);
19var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$1);
20var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto$3);
21var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
22var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
23var util__default = /*#__PURE__*/_interopDefaultLegacy(util$1);
24var asn1__default = /*#__PURE__*/_interopDefaultLegacy(asn1$2);
25
26const doneWritingPromise = Symbol('doneWritingPromise');
27const doneWritingResolve = Symbol('doneWritingResolve');
28const doneWritingReject = Symbol('doneWritingReject');
29
30const readingIndex = Symbol('readingIndex');
31
32class ArrayStream extends Array {
33 constructor() {
34 super();
35 this[doneWritingPromise] = new Promise((resolve, reject) => {
36 this[doneWritingResolve] = resolve;
37 this[doneWritingReject] = reject;
38 });
39 this[doneWritingPromise].catch(() => {});
40 }
41}
42
43ArrayStream.prototype.getReader = function() {
44 if (this[readingIndex] === undefined) {
45 this[readingIndex] = 0;
46 }
47 return {
48 read: async () => {
49 await this[doneWritingPromise];
50 if (this[readingIndex] === this.length) {
51 return { value: undefined, done: true };
52 }
53 return { value: this[this[readingIndex]++], done: false };
54 }
55 };
56};
57
58ArrayStream.prototype.readToEnd = async function(join) {
59 await this[doneWritingPromise];
60 const result = join(this.slice(this[readingIndex]));
61 this.length = 0;
62 return result;
63};
64
65ArrayStream.prototype.clone = function() {
66 const clone = new ArrayStream();
67 clone[doneWritingPromise] = this[doneWritingPromise].then(() => {
68 clone.push(...this);
69 });
70 return clone;
71};
72
73/**
74 * Check whether data is an ArrayStream
75 * @param {Any} input data to check
76 * @returns {boolean}
77 */
78function isArrayStream(input) {
79 return input && input.getReader && Array.isArray(input);
80}
81
82/**
83 * A wrapper class over the native WritableStreamDefaultWriter.
84 * It also lets you "write data to" array streams instead of streams.
85 * @class
86 */
87function Writer(input) {
88 if (!isArrayStream(input)) {
89 const writer = input.getWriter();
90 const releaseLock = writer.releaseLock;
91 writer.releaseLock = () => {
92 writer.closed.catch(function() {});
93 releaseLock.call(writer);
94 };
95 return writer;
96 }
97 this.stream = input;
98}
99
100/**
101 * Write a chunk of data.
102 * @returns {Promise<undefined>}
103 * @async
104 */
105Writer.prototype.write = async function(chunk) {
106 this.stream.push(chunk);
107};
108
109/**
110 * Close the stream.
111 * @returns {Promise<undefined>}
112 * @async
113 */
114Writer.prototype.close = async function() {
115 this.stream[doneWritingResolve]();
116};
117
118/**
119 * Error the stream.
120 * @returns {Promise<Object>}
121 * @async
122 */
123Writer.prototype.abort = async function(reason) {
124 this.stream[doneWritingReject](reason);
125 return reason;
126};
127
128/**
129 * Release the writer's lock.
130 * @returns {undefined}
131 * @async
132 */
133Writer.prototype.releaseLock = function() {};
134
135const isNode = typeof globalThis.process === 'object' &&
136 typeof globalThis.process.versions === 'object';
137
138const NodeReadableStream = isNode && stream__default['default'].Readable;
139
140/**
141 * Check whether data is a Stream, and if so of which type
142 * @param {Any} input data to check
143 * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}
144 */
145function isStream(input) {
146 if (isArrayStream(input)) {
147 return 'array';
148 }
149 if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
150 return 'web';
151 }
152 if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) {
153 return 'ponyfill';
154 }
155 if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
156 return 'node';
157 }
158 if (input && input.getReader) {
159 return 'web-like';
160 }
161 return false;
162}
163
164/**
165 * Check whether data is a Uint8Array
166 * @param {Any} input data to check
167 * @returns {Boolean}
168 */
169function isUint8Array(input) {
170 return Uint8Array.prototype.isPrototypeOf(input);
171}
172
173/**
174 * Concat Uint8Arrays
175 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
176 * @returns {Uint8array} Concatenated array
177 */
178function concatUint8Array(arrays) {
179 if (arrays.length === 1) return arrays[0];
180
181 let totalLength = 0;
182 for (let i = 0; i < arrays.length; i++) {
183 if (!isUint8Array(arrays[i])) {
184 throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
185 }
186
187 totalLength += arrays[i].length;
188 }
189
190 const result = new Uint8Array(totalLength);
191 let pos = 0;
192 arrays.forEach(function (element) {
193 result.set(element, pos);
194 pos += element.length;
195 });
196
197 return result;
198}
199
200const NodeBuffer = isNode && buffer__default['default'].Buffer;
201const NodeReadableStream$1 = isNode && stream__default['default'].Readable;
202
203/**
204 * Web / node stream conversion functions
205 * From https://github.com/gwicke/node-web-streams
206 */
207
208let nodeToWeb;
209let webToNode;
210
211if (NodeReadableStream$1) {
212
213 /**
214 * Convert a Node Readable Stream to a Web ReadableStream
215 * @param {Readable} nodeStream
216 * @returns {ReadableStream}
217 */
218 nodeToWeb = function(nodeStream) {
219 let canceled = false;
220 return new ReadableStream({
221 start(controller) {
222 nodeStream.pause();
223 nodeStream.on('data', chunk => {
224 if (canceled) {
225 return;
226 }
227 if (NodeBuffer.isBuffer(chunk)) {
228 chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
229 }
230 controller.enqueue(chunk);
231 nodeStream.pause();
232 });
233 nodeStream.on('end', () => {
234 if (canceled) {
235 return;
236 }
237 controller.close();
238 });
239 nodeStream.on('error', e => controller.error(e));
240 },
241 pull() {
242 nodeStream.resume();
243 },
244 cancel(reason) {
245 canceled = true;
246 nodeStream.destroy(reason);
247 }
248 });
249 };
250
251
252 class NodeReadable extends NodeReadableStream$1 {
253 constructor(webStream, options) {
254 super(options);
255 this._reader = getReader(webStream);
256 }
257
258 async _read(size) {
259 try {
260 while (true) {
261 const { done, value } = await this._reader.read();
262 if (done) {
263 this.push(null);
264 break;
265 }
266 if (!this.push(value) || this._cancelling) {
267 this._reading = false;
268 break;
269 }
270 }
271 } catch(e) {
272 this.emit('error', e);
273 }
274 }
275
276 _destroy(reason) {
277 this._reader.cancel(reason);
278 }
279 }
280
281 /**
282 * Convert a Web ReadableStream to a Node Readable Stream
283 * @param {ReadableStream} webStream
284 * @param {Object} options
285 * @returns {Readable}
286 */
287 webToNode = function(webStream, options) {
288 return new NodeReadable(webStream, options);
289 };
290
291}
292
293const doneReadingSet = new WeakSet();
294const externalBuffer = Symbol('externalBuffer');
295
296/**
297 * A wrapper class over the native ReadableStreamDefaultReader.
298 * This additionally implements pushing back data on the stream, which
299 * lets us implement peeking and a host of convenience functions.
300 * It also lets you read data other than streams, such as a Uint8Array.
301 * @class
302 */
303function Reader(input) {
304 this.stream = input;
305 if (input[externalBuffer]) {
306 this[externalBuffer] = input[externalBuffer].slice();
307 }
308 if (isArrayStream(input)) {
309 const reader = input.getReader();
310 this._read = reader.read.bind(reader);
311 this._releaseLock = () => {};
312 this._cancel = () => {};
313 return;
314 }
315 let streamType = isStream(input);
316 if (streamType === 'node') {
317 input = nodeToWeb(input);
318 }
319 if (streamType) {
320 const reader = input.getReader();
321 this._read = reader.read.bind(reader);
322 this._releaseLock = () => {
323 reader.closed.catch(function() {});
324 reader.releaseLock();
325 };
326 this._cancel = reader.cancel.bind(reader);
327 return;
328 }
329 let doneReading = false;
330 this._read = async () => {
331 if (doneReading || doneReadingSet.has(input)) {
332 return { value: undefined, done: true };
333 }
334 doneReading = true;
335 return { value: input, done: false };
336 };
337 this._releaseLock = () => {
338 if (doneReading) {
339 try {
340 doneReadingSet.add(input);
341 } catch(e) {}
342 }
343 };
344}
345
346/**
347 * Read a chunk of data.
348 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
349 * @async
350 */
351Reader.prototype.read = async function() {
352 if (this[externalBuffer] && this[externalBuffer].length) {
353 const value = this[externalBuffer].shift();
354 return { done: false, value };
355 }
356 return this._read();
357};
358
359/**
360 * Allow others to read the stream.
361 */
362Reader.prototype.releaseLock = function() {
363 if (this[externalBuffer]) {
364 this.stream[externalBuffer] = this[externalBuffer];
365 }
366 this._releaseLock();
367};
368
369/**
370 * Cancel the stream.
371 */
372Reader.prototype.cancel = function(reason) {
373 return this._cancel(reason);
374};
375
376/**
377 * Read up to and including the first \n character.
378 * @returns {Promise<String|Undefined>}
379 * @async
380 */
381Reader.prototype.readLine = async function() {
382 let buffer = [];
383 let returnVal;
384 while (!returnVal) {
385 let { done, value } = await this.read();
386 value += '';
387 if (done) {
388 if (buffer.length) return concat(buffer);
389 return;
390 }
391 const lineEndIndex = value.indexOf('\n') + 1;
392 if (lineEndIndex) {
393 returnVal = concat(buffer.concat(value.substr(0, lineEndIndex)));
394 buffer = [];
395 }
396 if (lineEndIndex !== value.length) {
397 buffer.push(value.substr(lineEndIndex));
398 }
399 }
400 this.unshift(...buffer);
401 return returnVal;
402};
403
404/**
405 * Read a single byte/character.
406 * @returns {Promise<Number|String|Undefined>}
407 * @async
408 */
409Reader.prototype.readByte = async function() {
410 const { done, value } = await this.read();
411 if (done) return;
412 const byte = value[0];
413 this.unshift(slice(value, 1));
414 return byte;
415};
416
417/**
418 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
419 * @returns {Promise<Uint8Array|String|Undefined>}
420 * @async
421 */
422Reader.prototype.readBytes = async function(length) {
423 const buffer = [];
424 let bufferLength = 0;
425 while (true) {
426 const { done, value } = await this.read();
427 if (done) {
428 if (buffer.length) return concat(buffer);
429 return;
430 }
431 buffer.push(value);
432 bufferLength += value.length;
433 if (bufferLength >= length) {
434 const bufferConcat = concat(buffer);
435 this.unshift(slice(bufferConcat, length));
436 return slice(bufferConcat, 0, length);
437 }
438 }
439};
440
441/**
442 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
443 * @returns {Promise<Uint8Array|String|Undefined>}
444 * @async
445 */
446Reader.prototype.peekBytes = async function(length) {
447 const bytes = await this.readBytes(length);
448 this.unshift(bytes);
449 return bytes;
450};
451
452/**
453 * Push data to the front of the stream.
454 * Data must have been read in the last call to read*.
455 * @param {...(Uint8Array|String|Undefined)} values
456 */
457Reader.prototype.unshift = function(...values) {
458 if (!this[externalBuffer]) {
459 this[externalBuffer] = [];
460 }
461 if (
462 values.length === 1 && isUint8Array(values[0]) &&
463 this[externalBuffer].length && values[0].length &&
464 this[externalBuffer][0].byteOffset >= values[0].length
465 ) {
466 this[externalBuffer][0] = new Uint8Array(
467 this[externalBuffer][0].buffer,
468 this[externalBuffer][0].byteOffset - values[0].length,
469 this[externalBuffer][0].byteLength + values[0].length
470 );
471 return;
472 }
473 this[externalBuffer].unshift(...values.filter(value => value && value.length));
474};
475
476/**
477 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
478 * @param {Function} join
479 * @returns {Promise<Uint8array|String|Any>} the return value of join()
480 * @async
481 */
482Reader.prototype.readToEnd = async function(join=concat) {
483 const result = [];
484 while (true) {
485 const { done, value } = await this.read();
486 if (done) break;
487 result.push(value);
488 }
489 return join(result);
490};
491
492let { ReadableStream, WritableStream, TransformStream } = globalThis;
493
494let toPonyfillReadable, toNativeReadable;
495
496async function loadStreamsPonyfill() {
497 if (TransformStream) {
498 return;
499 }
500
501 const [ponyfill, adapter] = await Promise.all([
502 Promise.resolve().then(function () { return ponyfill_es6; }),
503 Promise.resolve().then(function () { return webStreamsAdapter; })
504 ]);
505
506 ({ ReadableStream, WritableStream, TransformStream } = ponyfill);
507
508 const { createReadableStreamWrapper } = adapter;
509
510 if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {
511 toPonyfillReadable = createReadableStreamWrapper(ReadableStream);
512 toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);
513 }
514}
515
516const NodeBuffer$1 = isNode && buffer__default['default'].Buffer;
517
518/**
519 * Convert data to Stream
520 * @param {ReadableStream|Uint8array|String} input data to convert
521 * @returns {ReadableStream} Converted data
522 */
523function toStream(input) {
524 let streamType = isStream(input);
525 if (streamType === 'node') {
526 return nodeToWeb(input);
527 }
528 if (streamType === 'web' && toPonyfillReadable) {
529 return toPonyfillReadable(input);
530 }
531 if (streamType) {
532 return input;
533 }
534 return new ReadableStream({
535 start(controller) {
536 controller.enqueue(input);
537 controller.close();
538 }
539 });
540}
541
542/**
543 * Convert data to ArrayStream
544 * @param {Object} input data to convert
545 * @returns {ArrayStream} Converted data
546 */
547function toArrayStream(input) {
548 if (isStream(input)) {
549 return input;
550 }
551 const stream = new ArrayStream();
552 (async () => {
553 const writer = getWriter(stream);
554 await writer.write(input);
555 await writer.close();
556 })();
557 return stream;
558}
559
560/**
561 * Concat a list of Uint8Arrays, Strings or Streams
562 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
563 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
564 * @returns {Uint8array|String|ReadableStream} Concatenated array
565 */
566function concat(list) {
567 if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {
568 return concatStream(list);
569 }
570 if (list.some(stream => isArrayStream(stream))) {
571 return concatArrayStream(list);
572 }
573 if (typeof list[0] === 'string') {
574 return list.join('');
575 }
576 if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) {
577 return NodeBuffer$1.concat(list);
578 }
579 return concatUint8Array(list);
580}
581
582/**
583 * Concat a list of Streams
584 * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
585 * @returns {ReadableStream} Concatenated list
586 */
587function concatStream(list) {
588 list = list.map(toStream);
589 const transform = transformWithCancel(async function(reason) {
590 await Promise.all(transforms.map(stream => cancel(stream, reason)));
591 });
592 let prev = Promise.resolve();
593 const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
594 prev = prev.then(() => pipe(readable, transform.writable, {
595 preventClose: i !== list.length - 1
596 }));
597 return prev;
598 }));
599 return transform.readable;
600}
601
602/**
603 * Concat a list of ArrayStreams
604 * @param {Array<ArrayStream|Uint8array|String>} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate
605 * @returns {ArrayStream} Concatenated streams
606 */
607function concatArrayStream(list) {
608 const result = new ArrayStream();
609 let prev = Promise.resolve();
610 list.forEach((stream, i) => {
611 prev = prev.then(() => pipe(stream, result, {
612 preventClose: i !== list.length - 1
613 }));
614 return prev;
615 });
616 return result;
617}
618
619/**
620 * Get a Reader
621 * @param {ReadableStream|Uint8array|String} input
622 * @returns {Reader}
623 */
624function getReader(input) {
625 return new Reader(input);
626}
627
628/**
629 * Get a Writer
630 * @param {WritableStream} input
631 * @returns {Writer}
632 */
633function getWriter(input) {
634 return new Writer(input);
635}
636
637/**
638 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
639 * @param {ReadableStream|Uint8array|String} input
640 * @param {WritableStream} target
641 * @param {Object} (optional) options
642 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
643 * @async
644 */
645async function pipe(input, target, {
646 preventClose = false,
647 preventAbort = false,
648 preventCancel = false
649} = {}) {
650 if (isStream(input) && !isArrayStream(input)) {
651 input = toStream(input);
652 try {
653 if (input[externalBuffer]) {
654 const writer = getWriter(target);
655 for (let i = 0; i < input[externalBuffer].length; i++) {
656 await writer.ready;
657 await writer.write(input[externalBuffer][i]);
658 }
659 writer.releaseLock();
660 }
661 await input.pipeTo(target, {
662 preventClose,
663 preventAbort,
664 preventCancel
665 });
666 } catch(e) {}
667 return;
668 }
669 input = toArrayStream(input);
670 const reader = getReader(input);
671 const writer = getWriter(target);
672 try {
673 while (true) {
674 await writer.ready;
675 const { done, value } = await reader.read();
676 if (done) {
677 if (!preventClose) await writer.close();
678 break;
679 }
680 await writer.write(value);
681 }
682 } catch (e) {
683 if (!preventAbort) await writer.abort(e);
684 } finally {
685 reader.releaseLock();
686 writer.releaseLock();
687 }
688}
689
690/**
691 * Pipe a readable stream through a transform stream.
692 * @param {ReadableStream|Uint8array|String} input
693 * @param {Object} (optional) options
694 * @returns {ReadableStream} transformed stream
695 */
696function transformRaw(input, options) {
697 const transformStream = new TransformStream(options);
698 pipe(input, transformStream.writable);
699 return transformStream.readable;
700}
701
702/**
703 * Create a cancelable TransformStream.
704 * @param {Function} cancel
705 * @returns {TransformStream}
706 */
707function transformWithCancel(cancel) {
708 let pulled = false;
709 let backpressureChangePromiseResolve;
710 let outputController;
711 return {
712 readable: new ReadableStream({
713 start(controller) {
714 outputController = controller;
715 },
716 pull() {
717 if (backpressureChangePromiseResolve) {
718 backpressureChangePromiseResolve();
719 } else {
720 pulled = true;
721 }
722 },
723 cancel
724 }, {highWaterMark: 0}),
725 writable: new WritableStream({
726 write: async function(chunk) {
727 outputController.enqueue(chunk);
728 if (!pulled) {
729 await new Promise(resolve => {
730 backpressureChangePromiseResolve = resolve;
731 });
732 backpressureChangePromiseResolve = null;
733 } else {
734 pulled = false;
735 }
736 },
737 close: outputController.close.bind(outputController),
738 abort: outputController.error.bind(outputController)
739 })
740 };
741}
742
743/**
744 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
745 * @param {ReadableStream|Uint8array|String} input
746 * @param {Function} process
747 * @param {Function} finish
748 * @returns {ReadableStream|Uint8array|String}
749 */
750function transform(input, process = () => undefined, finish = () => undefined) {
751 if (isArrayStream(input)) {
752 const output = new ArrayStream();
753 (async () => {
754 const writer = getWriter(output);
755 try {
756 const data = await readToEnd(input);
757 const result1 = process(data);
758 const result2 = finish();
759 let result;
760 if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);
761 else result = result1 !== undefined ? result1 : result2;
762 await writer.write(result);
763 await writer.close();
764 } catch (e) {
765 await writer.abort(e);
766 }
767 })();
768 return output;
769 }
770 if (isStream(input)) {
771 return transformRaw(input, {
772 async transform(value, controller) {
773 try {
774 const result = await process(value);
775 if (result !== undefined) controller.enqueue(result);
776 } catch(e) {
777 controller.error(e);
778 }
779 },
780 async flush(controller) {
781 try {
782 const result = await finish();
783 if (result !== undefined) controller.enqueue(result);
784 } catch(e) {
785 controller.error(e);
786 }
787 }
788 });
789 }
790 const result1 = process(input);
791 const result2 = finish();
792 if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
793 return result1 !== undefined ? result1 : result2;
794}
795
796/**
797 * Transform a stream using a helper function which is passed a readable and a writable stream.
798 * This function also maintains the possibility to cancel the input stream,
799 * and does so on cancelation of the output stream, despite cancelation
800 * normally being impossible when the input stream is being read from.
801 * @param {ReadableStream|Uint8array|String} input
802 * @param {Function} fn
803 * @returns {ReadableStream}
804 */
805function transformPair(input, fn) {
806 if (isStream(input) && !isArrayStream(input)) {
807 let incomingTransformController;
808 const incoming = new TransformStream({
809 start(controller) {
810 incomingTransformController = controller;
811 }
812 });
813
814 const pipeDonePromise = pipe(input, incoming.writable);
815
816 const outgoing = transformWithCancel(async function(reason) {
817 incomingTransformController.error(reason);
818 await pipeDonePromise;
819 await new Promise(setTimeout);
820 });
821 fn(incoming.readable, outgoing.writable);
822 return outgoing.readable;
823 }
824 input = toArrayStream(input);
825 const output = new ArrayStream();
826 fn(input, output);
827 return output;
828}
829
830/**
831 * Parse a stream using a helper function which is passed a Reader.
832 * The reader additionally has a remainder() method which returns a
833 * stream pointing to the remainder of input, and is linked to input
834 * for cancelation.
835 * @param {ReadableStream|Uint8array|String} input
836 * @param {Function} fn
837 * @returns {Any} the return value of fn()
838 */
839function parse(input, fn) {
840 let returnValue;
841 const transformed = transformPair(input, (readable, writable) => {
842 const reader = getReader(readable);
843 reader.remainder = () => {
844 reader.releaseLock();
845 pipe(readable, writable);
846 return transformed;
847 };
848 returnValue = fn(reader);
849 });
850 return returnValue;
851}
852
853/**
854 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
855 * Reading either of the two returned streams will pull from the input stream.
856 * The input stream will only be canceled if both of the returned streams are canceled.
857 * @param {ReadableStream|Uint8array|String} input
858 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
859 */
860function tee(input) {
861 if (isArrayStream(input)) {
862 throw new Error('ArrayStream cannot be tee()d, use clone() instead');
863 }
864 if (isStream(input)) {
865 const teed = toStream(input).tee();
866 teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
867 return teed;
868 }
869 return [slice(input), slice(input)];
870}
871
872/**
873 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
874 * Reading from the clone will pull from the input stream.
875 * The input stream will only be canceled if both the clone and the input stream are canceled.
876 * @param {ReadableStream|Uint8array|String} input
877 * @returns {ReadableStream|Uint8array|String} cloned input
878 */
879function clone(input) {
880 if (isArrayStream(input)) {
881 return input.clone();
882 }
883 if (isStream(input)) {
884 const teed = tee(input);
885 overwrite(input, teed[0]);
886 return teed[1];
887 }
888 return slice(input);
889}
890
891/**
892 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
893 * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
894 * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
895 * If the input stream is canceled, the clone will be errored.
896 * @param {ReadableStream|Uint8array|String} input
897 * @returns {ReadableStream|Uint8array|String} cloned input
898 */
899function passiveClone(input) {
900 if (isArrayStream(input)) {
901 return clone(input);
902 }
903 if (isStream(input)) {
904 return new ReadableStream({
905 start(controller) {
906 const transformed = transformPair(input, async (readable, writable) => {
907 const reader = getReader(readable);
908 const writer = getWriter(writable);
909 try {
910 while (true) {
911 await writer.ready;
912 const { done, value } = await reader.read();
913 if (done) {
914 try { controller.close(); } catch(e) {}
915 await writer.close();
916 return;
917 }
918 try { controller.enqueue(value); } catch(e) {}
919 await writer.write(value);
920 }
921 } catch(e) {
922 controller.error(e);
923 await writer.abort(e);
924 }
925 });
926 overwrite(input, transformed);
927 }
928 });
929 }
930 return slice(input);
931}
932
933/**
934 * Modify a stream object to point to a different stream object.
935 * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
936 * @param {ReadableStream} input
937 * @param {ReadableStream} clone
938 */
939function overwrite(input, clone) {
940 // Overwrite input.getReader, input.locked, etc to point to clone
941 Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {
942 if (name === 'constructor') {
943 return;
944 }
945 if (descriptor.value) {
946 descriptor.value = descriptor.value.bind(clone);
947 } else {
948 descriptor.get = descriptor.get.bind(clone);
949 }
950 Object.defineProperty(input, name, descriptor);
951 });
952}
953
954/**
955 * Return a stream pointing to a part of the input stream.
956 * @param {ReadableStream|Uint8array|String} input
957 * @returns {ReadableStream|Uint8array|String} clone
958 */
959function slice(input, begin=0, end=Infinity) {
960 if (isArrayStream(input)) {
961 throw new Error('Not implemented');
962 }
963 if (isStream(input)) {
964 if (begin >= 0 && end >= 0) {
965 let bytesRead = 0;
966 return transformRaw(input, {
967 transform(value, controller) {
968 if (bytesRead < end) {
969 if (bytesRead + value.length >= begin) {
970 controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
971 }
972 bytesRead += value.length;
973 } else {
974 controller.terminate();
975 }
976 }
977 });
978 }
979 if (begin < 0 && (end < 0 || end === Infinity)) {
980 let lastBytes = [];
981 return transform(input, value => {
982 if (value.length >= -begin) lastBytes = [value];
983 else lastBytes.push(value);
984 }, () => slice(concat(lastBytes), begin, end));
985 }
986 if (begin === 0 && end < 0) {
987 let lastBytes;
988 return transform(input, value => {
989 const returnValue = lastBytes ? concat([lastBytes, value]) : value;
990 if (returnValue.length >= -end) {
991 lastBytes = slice(returnValue, end);
992 return slice(returnValue, begin, end);
993 } else {
994 lastBytes = returnValue;
995 }
996 });
997 }
998 console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
999 return fromAsync(async () => slice(await readToEnd(input), begin, end));
1000 }
1001 if (input[externalBuffer]) {
1002 input = concat(input[externalBuffer].concat([input]));
1003 }
1004 if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) {
1005 if (end === Infinity) end = input.length;
1006 return input.subarray(begin, end);
1007 }
1008 return input.slice(begin, end);
1009}
1010
1011/**
1012 * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).
1013 * @param {ReadableStream|Uint8array|String} input
1014 * @param {Function} join
1015 * @returns {Promise<Uint8array|String|Any>} the return value of join()
1016 * @async
1017 */
1018async function readToEnd(input, join=concat) {
1019 if (isArrayStream(input)) {
1020 return input.readToEnd(join);
1021 }
1022 if (isStream(input)) {
1023 return getReader(input).readToEnd(join);
1024 }
1025 return input;
1026}
1027
1028/**
1029 * Cancel a stream.
1030 * @param {ReadableStream|Uint8array|String} input
1031 * @param {Any} reason
1032 * @returns {Promise<Any>} indicates when the stream has been canceled
1033 * @async
1034 */
1035async function cancel(input, reason) {
1036 if (isStream(input)) {
1037 if (input.cancel) {
1038 return input.cancel(reason);
1039 }
1040 if (input.destroy) {
1041 input.destroy(reason);
1042 await new Promise(setTimeout);
1043 return reason;
1044 }
1045 }
1046}
1047
1048/**
1049 * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.
1050 * @param {Function} fn
1051 * @returns {ArrayStream}
1052 */
1053function fromAsync(fn) {
1054 const arrayStream = new ArrayStream();
1055 (async () => {
1056 const writer = getWriter(arrayStream);
1057 try {
1058 await writer.write(await fn());
1059 await writer.close();
1060 } catch (e) {
1061 await writer.abort(e);
1062 }
1063 })();
1064 return arrayStream;
1065}
1066
1067/* eslint-disable new-cap */
1068
1069/**
1070 * @fileoverview
1071 * BigInteger implementation of basic operations
1072 * that wraps the native BigInt library.
1073 * Operations are not constant time,
1074 * but we try and limit timing leakage where we can
1075 * @module biginteger/native
1076 * @private
1077 */
1078
1079/**
1080 * @private
1081 */
1082class BigInteger {
1083 /**
1084 * Get a BigInteger (input must be big endian for strings and arrays)
1085 * @param {Number|String|Uint8Array} n - Value to convert
1086 * @throws {Error} on null or undefined input
1087 */
1088 constructor(n) {
1089 if (n === undefined) {
1090 throw new Error('Invalid BigInteger input');
1091 }
1092
1093 if (n instanceof Uint8Array) {
1094 const bytes = n;
1095 const hex = new Array(bytes.length);
1096 for (let i = 0; i < bytes.length; i++) {
1097 const hexByte = bytes[i].toString(16);
1098 hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
1099 }
1100 this.value = BigInt('0x0' + hex.join(''));
1101 } else {
1102 this.value = BigInt(n);
1103 }
1104 }
1105
1106 clone() {
1107 return new BigInteger(this.value);
1108 }
1109
1110 /**
1111 * BigInteger increment in place
1112 */
1113 iinc() {
1114 this.value++;
1115 return this;
1116 }
1117
1118 /**
1119 * BigInteger increment
1120 * @returns {BigInteger} this + 1.
1121 */
1122 inc() {
1123 return this.clone().iinc();
1124 }
1125
1126 /**
1127 * BigInteger decrement in place
1128 */
1129 idec() {
1130 this.value--;
1131 return this;
1132 }
1133
1134 /**
1135 * BigInteger decrement
1136 * @returns {BigInteger} this - 1.
1137 */
1138 dec() {
1139 return this.clone().idec();
1140 }
1141
1142 /**
1143 * BigInteger addition in place
1144 * @param {BigInteger} x - Value to add
1145 */
1146 iadd(x) {
1147 this.value += x.value;
1148 return this;
1149 }
1150
1151 /**
1152 * BigInteger addition
1153 * @param {BigInteger} x - Value to add
1154 * @returns {BigInteger} this + x.
1155 */
1156 add(x) {
1157 return this.clone().iadd(x);
1158 }
1159
1160 /**
1161 * BigInteger subtraction in place
1162 * @param {BigInteger} x - Value to subtract
1163 */
1164 isub(x) {
1165 this.value -= x.value;
1166 return this;
1167 }
1168
1169 /**
1170 * BigInteger subtraction
1171 * @param {BigInteger} x - Value to subtract
1172 * @returns {BigInteger} this - x.
1173 */
1174 sub(x) {
1175 return this.clone().isub(x);
1176 }
1177
1178 /**
1179 * BigInteger multiplication in place
1180 * @param {BigInteger} x - Value to multiply
1181 */
1182 imul(x) {
1183 this.value *= x.value;
1184 return this;
1185 }
1186
1187 /**
1188 * BigInteger multiplication
1189 * @param {BigInteger} x - Value to multiply
1190 * @returns {BigInteger} this * x.
1191 */
1192 mul(x) {
1193 return this.clone().imul(x);
1194 }
1195
1196 /**
1197 * Compute value modulo m, in place
1198 * @param {BigInteger} m - Modulo
1199 */
1200 imod(m) {
1201 this.value %= m.value;
1202 if (this.isNegative()) {
1203 this.iadd(m);
1204 }
1205 return this;
1206 }
1207
1208 /**
1209 * Compute value modulo m
1210 * @param {BigInteger} m - Modulo
1211 * @returns {BigInteger} this mod m.
1212 */
1213 mod(m) {
1214 return this.clone().imod(m);
1215 }
1216
1217 /**
1218 * Compute modular exponentiation using square and multiply
1219 * @param {BigInteger} e - Exponent
1220 * @param {BigInteger} n - Modulo
1221 * @returns {BigInteger} this ** e mod n.
1222 */
1223 modExp(e, n) {
1224 if (n.isZero()) throw Error('Modulo cannot be zero');
1225 if (n.isOne()) return new BigInteger(0);
1226 if (e.isNegative()) throw Error('Unsopported negative exponent');
1227
1228 let exp = e.value;
1229 let x = this.value;
1230
1231 x %= n.value;
1232 let r = BigInt(1);
1233 while (exp > BigInt(0)) {
1234 const lsb = exp & BigInt(1);
1235 exp >>= BigInt(1); // e / 2
1236 // Always compute multiplication step, to reduce timing leakage
1237 const rx = (r * x) % n.value;
1238 // Update r only if lsb is 1 (odd exponent)
1239 r = lsb ? rx : r;
1240 x = (x * x) % n.value; // Square
1241 }
1242 return new BigInteger(r);
1243 }
1244
1245
1246 /**
1247 * Compute the inverse of this value modulo n
1248 * Note: this and and n must be relatively prime
1249 * @param {BigInteger} n - Modulo
1250 * @returns {BigInteger} x such that this*x = 1 mod n
1251 * @throws {Error} if the inverse does not exist
1252 */
1253 modInv(n) {
1254 const { gcd, x } = this._egcd(n);
1255 if (!gcd.isOne()) {
1256 throw new Error('Inverse does not exist');
1257 }
1258 return x.add(n).mod(n);
1259 }
1260
1261 /**
1262 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
1263 * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
1264 * @param {BigInteger} b - Second operand
1265 * @returns {{ gcd, x, y: BigInteger }}
1266 */
1267 _egcd(b) {
1268 let x = BigInt(0);
1269 let y = BigInt(1);
1270 let xPrev = BigInt(1);
1271 let yPrev = BigInt(0);
1272
1273 let a = this.value;
1274 b = b.value;
1275
1276 while (b !== BigInt(0)) {
1277 const q = a / b;
1278 let tmp = x;
1279 x = xPrev - q * x;
1280 xPrev = tmp;
1281
1282 tmp = y;
1283 y = yPrev - q * y;
1284 yPrev = tmp;
1285
1286 tmp = b;
1287 b = a % b;
1288 a = tmp;
1289 }
1290
1291 return {
1292 x: new BigInteger(xPrev),
1293 y: new BigInteger(yPrev),
1294 gcd: new BigInteger(a)
1295 };
1296 }
1297
1298 /**
1299 * Compute greatest common divisor between this and n
1300 * @param {BigInteger} b - Operand
1301 * @returns {BigInteger} gcd
1302 */
1303 gcd(b) {
1304 let a = this.value;
1305 b = b.value;
1306 while (b !== BigInt(0)) {
1307 const tmp = b;
1308 b = a % b;
1309 a = tmp;
1310 }
1311 return new BigInteger(a);
1312 }
1313
1314 /**
1315 * Shift this to the left by x, in place
1316 * @param {BigInteger} x - Shift value
1317 */
1318 ileftShift(x) {
1319 this.value <<= x.value;
1320 return this;
1321 }
1322
1323 /**
1324 * Shift this to the left by x
1325 * @param {BigInteger} x - Shift value
1326 * @returns {BigInteger} this << x.
1327 */
1328 leftShift(x) {
1329 return this.clone().ileftShift(x);
1330 }
1331
1332 /**
1333 * Shift this to the right by x, in place
1334 * @param {BigInteger} x - Shift value
1335 */
1336 irightShift(x) {
1337 this.value >>= x.value;
1338 return this;
1339 }
1340
1341 /**
1342 * Shift this to the right by x
1343 * @param {BigInteger} x - Shift value
1344 * @returns {BigInteger} this >> x.
1345 */
1346 rightShift(x) {
1347 return this.clone().irightShift(x);
1348 }
1349
1350 /**
1351 * Whether this value is equal to x
1352 * @param {BigInteger} x
1353 * @returns {Boolean}
1354 */
1355 equal(x) {
1356 return this.value === x.value;
1357 }
1358
1359 /**
1360 * Whether this value is less than x
1361 * @param {BigInteger} x
1362 * @returns {Boolean}
1363 */
1364 lt(x) {
1365 return this.value < x.value;
1366 }
1367
1368 /**
1369 * Whether this value is less than or equal to x
1370 * @param {BigInteger} x
1371 * @returns {Boolean}
1372 */
1373 lte(x) {
1374 return this.value <= x.value;
1375 }
1376
1377 /**
1378 * Whether this value is greater than x
1379 * @param {BigInteger} x
1380 * @returns {Boolean}
1381 */
1382 gt(x) {
1383 return this.value > x.value;
1384 }
1385
1386 /**
1387 * Whether this value is greater than or equal to x
1388 * @param {BigInteger} x
1389 * @returns {Boolean}
1390 */
1391 gte(x) {
1392 return this.value >= x.value;
1393 }
1394
1395 isZero() {
1396 return this.value === BigInt(0);
1397 }
1398
1399 isOne() {
1400 return this.value === BigInt(1);
1401 }
1402
1403 isNegative() {
1404 return this.value < BigInt(0);
1405 }
1406
1407 isEven() {
1408 return !(this.value & BigInt(1));
1409 }
1410
1411 abs() {
1412 const res = this.clone();
1413 if (this.isNegative()) {
1414 res.value = -res.value;
1415 }
1416 return res;
1417 }
1418
1419 /**
1420 * Get this value as a string
1421 * @returns {String} this value.
1422 */
1423 toString() {
1424 return this.value.toString();
1425 }
1426
1427 /**
1428 * Get this value as an exact Number (max 53 bits)
1429 * Fails if this value is too large
1430 * @returns {Number}
1431 */
1432 toNumber() {
1433 const number = Number(this.value);
1434 if (number > Number.MAX_SAFE_INTEGER) {
1435 // We throw and error to conform with the bn.js implementation
1436 throw new Error('Number can only safely store up to 53 bits');
1437 }
1438 return number;
1439 }
1440
1441 /**
1442 * Get value of i-th bit
1443 * @param {Number} i - Bit index
1444 * @returns {Number} Bit value.
1445 */
1446 getBit(i) {
1447 const bit = (this.value >> BigInt(i)) & BigInt(1);
1448 return (bit === BigInt(0)) ? 0 : 1;
1449 }
1450
1451 /**
1452 * Compute bit length
1453 * @returns {Number} Bit length.
1454 */
1455 bitLength() {
1456 const zero = new BigInteger(0);
1457 const one = new BigInteger(1);
1458 const negOne = new BigInteger(-1);
1459
1460 // -1n >> -1n is -1n
1461 // 1n >> 1n is 0n
1462 const target = this.isNegative() ? negOne : zero;
1463 let bitlen = 1;
1464 const tmp = this.clone();
1465 while (!tmp.irightShift(one).equal(target)) {
1466 bitlen++;
1467 }
1468 return bitlen;
1469 }
1470
1471 /**
1472 * Compute byte length
1473 * @returns {Number} Byte length.
1474 */
1475 byteLength() {
1476 const zero = new BigInteger(0);
1477 const negOne = new BigInteger(-1);
1478
1479 const target = this.isNegative() ? negOne : zero;
1480 const eight = new BigInteger(8);
1481 let len = 1;
1482 const tmp = this.clone();
1483 while (!tmp.irightShift(eight).equal(target)) {
1484 len++;
1485 }
1486 return len;
1487 }
1488
1489 /**
1490 * Get Uint8Array representation of this number
1491 * @param {String} endian - Endianess of output array (defaults to 'be')
1492 * @param {Number} length - Of output array
1493 * @returns {Uint8Array}
1494 */
1495 toUint8Array(endian = 'be', length) {
1496 // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
1497 // this is faster than shift+mod iterations
1498 let hex = this.value.toString(16);
1499 if (hex.length % 2 === 1) {
1500 hex = '0' + hex;
1501 }
1502
1503 const rawLength = hex.length / 2;
1504 const bytes = new Uint8Array(length || rawLength);
1505 // parse hex
1506 const offset = length ? (length - rawLength) : 0;
1507 let i = 0;
1508 while (i < rawLength) {
1509 bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
1510 i++;
1511 }
1512
1513 if (endian !== 'be') {
1514 bytes.reverse();
1515 }
1516
1517 return bytes;
1518 }
1519}
1520
1521async function getBigInteger() {
1522 if (util.detectBigInt()) {
1523 return BigInteger;
1524 } else {
1525 const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; });
1526 return BigInteger;
1527 }
1528}
1529
1530const debugMode = (() => {
1531 try {
1532 return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env
1533 } catch (e) {}
1534 return false;
1535})();
1536
1537const util = {
1538 isString: function(data) {
1539 return typeof data === 'string' || String.prototype.isPrototypeOf(data);
1540 },
1541
1542 isArray: function(data) {
1543 return Array.prototype.isPrototypeOf(data);
1544 },
1545
1546 isUint8Array: isUint8Array,
1547
1548 isStream: isStream,
1549
1550 readNumber: function (bytes) {
1551 let n = 0;
1552 for (let i = 0; i < bytes.length; i++) {
1553 n += (256 ** i) * bytes[bytes.length - 1 - i];
1554 }
1555 return n;
1556 },
1557
1558 writeNumber: function (n, bytes) {
1559 const b = new Uint8Array(bytes);
1560 for (let i = 0; i < bytes; i++) {
1561 b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
1562 }
1563
1564 return b;
1565 },
1566
1567 readDate: function (bytes) {
1568 const n = util.readNumber(bytes);
1569 const d = new Date(n * 1000);
1570 return d;
1571 },
1572
1573 writeDate: function (time) {
1574 const numeric = Math.floor(time.getTime() / 1000);
1575
1576 return util.writeNumber(numeric, 4);
1577 },
1578
1579 normalizeDate: function (time = Date.now()) {
1580 return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
1581 },
1582
1583 /**
1584 * Read one MPI from bytes in input
1585 * @param {Uint8Array} bytes - Input data to parse
1586 * @returns {Uint8Array} Parsed MPI.
1587 */
1588 readMPI: function (bytes) {
1589 const bits = (bytes[0] << 8) | bytes[1];
1590 const bytelen = (bits + 7) >>> 3;
1591 return bytes.subarray(2, 2 + bytelen);
1592 },
1593
1594 /**
1595 * Left-pad Uint8Array to length by adding 0x0 bytes
1596 * @param {Uint8Array} bytes - Data to pad
1597 * @param {Number} length - Padded length
1598 * @returns {Uint8Array} Padded bytes.
1599 */
1600 leftPad(bytes, length) {
1601 const padded = new Uint8Array(length);
1602 const offset = length - bytes.length;
1603 padded.set(bytes, offset);
1604 return padded;
1605 },
1606
1607 /**
1608 * Convert a Uint8Array to an MPI-formatted Uint8Array.
1609 * @param {Uint8Array} bin - An array of 8-bit integers to convert
1610 * @returns {Uint8Array} MPI-formatted Uint8Array.
1611 */
1612 uint8ArrayToMPI: function (bin) {
1613 const bitSize = util.uint8ArrayBitLength(bin);
1614 if (bitSize === 0) {
1615 throw new Error('Zero MPI');
1616 }
1617 const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));
1618 const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);
1619 return util.concatUint8Array([prefix, stripped]);
1620 },
1621
1622 /**
1623 * Return bit length of the input data
1624 * @param {Uint8Array} bin input data (big endian)
1625 * @returns bit length
1626 */
1627 uint8ArrayBitLength: function (bin) {
1628 let i; // index of leading non-zero byte
1629 for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;
1630 if (i === bin.length) {
1631 return 0;
1632 }
1633 const stripped = bin.subarray(i);
1634 return (stripped.length - 1) * 8 + util.nbits(stripped[0]);
1635 },
1636
1637 /**
1638 * Convert a hex string to an array of 8-bit integers
1639 * @param {String} hex - A hex string to convert
1640 * @returns {Uint8Array} An array of 8-bit integers.
1641 */
1642 hexToUint8Array: function (hex) {
1643 const result = new Uint8Array(hex.length >> 1);
1644 for (let k = 0; k < hex.length >> 1; k++) {
1645 result[k] = parseInt(hex.substr(k << 1, 2), 16);
1646 }
1647 return result;
1648 },
1649
1650 /**
1651 * Convert an array of 8-bit integers to a hex string
1652 * @param {Uint8Array} bytes - Array of 8-bit integers to convert
1653 * @returns {String} Hexadecimal representation of the array.
1654 */
1655 uint8ArrayToHex: function (bytes) {
1656 const r = [];
1657 const e = bytes.length;
1658 let c = 0;
1659 let h;
1660 while (c < e) {
1661 h = bytes[c++].toString(16);
1662 while (h.length < 2) {
1663 h = '0' + h;
1664 }
1665 r.push('' + h);
1666 }
1667 return r.join('');
1668 },
1669
1670 /**
1671 * Convert a string to an array of 8-bit integers
1672 * @param {String} str - String to convert
1673 * @returns {Uint8Array} An array of 8-bit integers.
1674 */
1675 stringToUint8Array: function (str) {
1676 return transform(str, str => {
1677 if (!util.isString(str)) {
1678 throw new Error('stringToUint8Array: Data must be in the form of a string');
1679 }
1680
1681 const result = new Uint8Array(str.length);
1682 for (let i = 0; i < str.length; i++) {
1683 result[i] = str.charCodeAt(i);
1684 }
1685 return result;
1686 });
1687 },
1688
1689 /**
1690 * Convert an array of 8-bit integers to a string
1691 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
1692 * @returns {String} String representation of the array.
1693 */
1694 uint8ArrayToString: function (bytes) {
1695 bytes = new Uint8Array(bytes);
1696 const result = [];
1697 const bs = 1 << 14;
1698 const j = bytes.length;
1699
1700 for (let i = 0; i < j; i += bs) {
1701 result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
1702 }
1703 return result.join('');
1704 },
1705
1706 /**
1707 * Convert a native javascript string to a Uint8Array of utf8 bytes
1708 * @param {String|ReadableStream} str - The string to convert
1709 * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
1710 */
1711 encodeUTF8: function (str) {
1712 const encoder = new TextEncoder('utf-8');
1713 // eslint-disable-next-line no-inner-declarations
1714 function process(value, lastChunk = false) {
1715 return encoder.encode(value, { stream: !lastChunk });
1716 }
1717 return transform(str, process, () => process('', true));
1718 },
1719
1720 /**
1721 * Convert a Uint8Array of utf8 bytes to a native javascript string
1722 * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
1723 * @returns {String|ReadableStream} A native javascript string.
1724 */
1725 decodeUTF8: function (utf8) {
1726 const decoder = new TextDecoder('utf-8');
1727 // eslint-disable-next-line no-inner-declarations
1728 function process(value, lastChunk = false) {
1729 return decoder.decode(value, { stream: !lastChunk });
1730 }
1731 return transform(utf8, process, () => process(new Uint8Array(), true));
1732 },
1733
1734 /**
1735 * Concat a list of Uint8Arrays, Strings or Streams
1736 * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
1737 * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
1738 * @returns {Uint8Array|String|ReadableStream} Concatenated array.
1739 */
1740 concat: concat,
1741
1742 /**
1743 * Concat Uint8Arrays
1744 * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
1745 * @returns {Uint8Array} Concatenated array.
1746 */
1747 concatUint8Array: concatUint8Array,
1748
1749 /**
1750 * Check Uint8Array equality
1751 * @param {Uint8Array} array1 - First array
1752 * @param {Uint8Array} array2 - Second array
1753 * @returns {Boolean} Equality.
1754 */
1755 equalsUint8Array: function (array1, array2) {
1756 if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
1757 throw new Error('Data must be in the form of a Uint8Array');
1758 }
1759
1760 if (array1.length !== array2.length) {
1761 return false;
1762 }
1763
1764 for (let i = 0; i < array1.length; i++) {
1765 if (array1[i] !== array2[i]) {
1766 return false;
1767 }
1768 }
1769 return true;
1770 },
1771
1772 /**
1773 * Calculates a 16bit sum of a Uint8Array by adding each character
1774 * codes modulus 65535
1775 * @param {Uint8Array} Uint8Array - To create a sum of
1776 * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
1777 */
1778 writeChecksum: function (text) {
1779 let s = 0;
1780 for (let i = 0; i < text.length; i++) {
1781 s = (s + text[i]) & 0xFFFF;
1782 }
1783 return util.writeNumber(s, 2);
1784 },
1785
1786 /**
1787 * Helper function to print a debug message. Debug
1788 * messages are only printed if
1789 * @param {String} str - String of the debug message
1790 */
1791 printDebug: function (str) {
1792 if (debugMode) {
1793 console.log('[OpenPGP.js debug]', str);
1794 }
1795 },
1796
1797 /**
1798 * Helper function to print a debug error. Debug
1799 * messages are only printed if
1800 * @param {String} str - String of the debug message
1801 */
1802 printDebugError: function (error) {
1803 if (debugMode) {
1804 console.error('[OpenPGP.js debug]', error);
1805 }
1806 },
1807
1808 // returns bit length of the integer x
1809 nbits: function (x) {
1810 let r = 1;
1811 let t = x >>> 16;
1812 if (t !== 0) {
1813 x = t;
1814 r += 16;
1815 }
1816 t = x >> 8;
1817 if (t !== 0) {
1818 x = t;
1819 r += 8;
1820 }
1821 t = x >> 4;
1822 if (t !== 0) {
1823 x = t;
1824 r += 4;
1825 }
1826 t = x >> 2;
1827 if (t !== 0) {
1828 x = t;
1829 r += 2;
1830 }
1831 t = x >> 1;
1832 if (t !== 0) {
1833 x = t;
1834 r += 1;
1835 }
1836 return r;
1837 },
1838
1839 /**
1840 * If S[1] == 0, then double(S) == (S[2..128] || 0);
1841 * otherwise, double(S) == (S[2..128] || 0) xor
1842 * (zeros(120) || 10000111).
1843 *
1844 * Both OCB and EAX (through CMAC) require this function to be constant-time.
1845 *
1846 * @param {Uint8Array} data
1847 */
1848 double: function(data) {
1849 const doubleVar = new Uint8Array(data.length);
1850 const last = data.length - 1;
1851 for (let i = 0; i < last; i++) {
1852 doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
1853 }
1854 doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
1855 return doubleVar;
1856 },
1857
1858 /**
1859 * Shift a Uint8Array to the right by n bits
1860 * @param {Uint8Array} array - The array to shift
1861 * @param {Integer} bits - Amount of bits to shift (MUST be smaller
1862 * than 8)
1863 * @returns {String} Resulting array.
1864 */
1865 shiftRight: function (array, bits) {
1866 if (bits) {
1867 for (let i = array.length - 1; i >= 0; i--) {
1868 array[i] >>= bits;
1869 if (i > 0) {
1870 array[i] |= (array[i - 1] << (8 - bits));
1871 }
1872 }
1873 }
1874 return array;
1875 },
1876
1877 /**
1878 * Get native Web Cryptography api, only the current version of the spec.
1879 * @returns {Object} The SubtleCrypto api or 'undefined'.
1880 */
1881 getWebCrypto: function() {
1882 return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
1883 },
1884
1885 /**
1886 * Detect native BigInt support
1887 */
1888 detectBigInt: () => typeof BigInt !== 'undefined',
1889
1890 /**
1891 * Get BigInteger class
1892 * It wraps the native BigInt type if it's available
1893 * Otherwise it relies on bn.js
1894 * @returns {BigInteger}
1895 * @async
1896 */
1897 getBigInteger,
1898
1899 /**
1900 * Get native Node.js crypto api.
1901 * @returns {Object} The crypto module or 'undefined'.
1902 */
1903 getNodeCrypto: function() {
1904 return crypto__default['default'];
1905 },
1906
1907 getNodeZlib: function() {
1908 return zlib__default['default'];
1909 },
1910
1911 /**
1912 * Get native Node.js Buffer constructor. This should be used since
1913 * Buffer is not available under browserify.
1914 * @returns {Function} The Buffer constructor or 'undefined'.
1915 */
1916 getNodeBuffer: function() {
1917 return (buffer__default['default'] || {}).Buffer;
1918 },
1919
1920 getHardwareConcurrency: function() {
1921 if (typeof navigator !== 'undefined') {
1922 return navigator.hardwareConcurrency || 1;
1923 }
1924
1925 const os = os__default['default']; // Assume we're on Node.js.
1926 return os.cpus().length;
1927 },
1928
1929 isEmailAddress: function(data) {
1930 if (!util.isString(data)) {
1931 return false;
1932 }
1933 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]+)))$/;
1934 return re.test(data);
1935 },
1936
1937 /**
1938 * Normalize line endings to <CR><LF>
1939 * Support any encoding where CR=0x0D, LF=0x0A
1940 */
1941 canonicalizeEOL: function(data) {
1942 const CR = 13;
1943 const LF = 10;
1944 let carryOverCR = false;
1945
1946 return transform(data, bytes => {
1947 if (carryOverCR) {
1948 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1949 }
1950
1951 if (bytes[bytes.length - 1] === CR) {
1952 carryOverCR = true;
1953 bytes = bytes.subarray(0, -1);
1954 } else {
1955 carryOverCR = false;
1956 }
1957
1958 let index;
1959 const indices = [];
1960 for (let i = 0; ; i = index) {
1961 index = bytes.indexOf(LF, i) + 1;
1962 if (index) {
1963 if (bytes[index - 2] !== CR) indices.push(index);
1964 } else {
1965 break;
1966 }
1967 }
1968 if (!indices.length) {
1969 return bytes;
1970 }
1971
1972 const normalized = new Uint8Array(bytes.length + indices.length);
1973 let j = 0;
1974 for (let i = 0; i < indices.length; i++) {
1975 const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
1976 normalized.set(sub, j);
1977 j += sub.length;
1978 normalized[j - 1] = CR;
1979 normalized[j] = LF;
1980 j++;
1981 }
1982 normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
1983 return normalized;
1984 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
1985 },
1986
1987 /**
1988 * Convert line endings from canonicalized <CR><LF> to native <LF>
1989 * Support any encoding where CR=0x0D, LF=0x0A
1990 */
1991 nativeEOL: function(data) {
1992 const CR = 13;
1993 const LF = 10;
1994 let carryOverCR = false;
1995
1996 return transform(data, bytes => {
1997 if (carryOverCR && bytes[0] !== LF) {
1998 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1999 } else {
2000 bytes = new Uint8Array(bytes); // Don't mutate passed bytes
2001 }
2002
2003 if (bytes[bytes.length - 1] === CR) {
2004 carryOverCR = true;
2005 bytes = bytes.subarray(0, -1);
2006 } else {
2007 carryOverCR = false;
2008 }
2009
2010 let index;
2011 let j = 0;
2012 for (let i = 0; i !== bytes.length; i = index) {
2013 index = bytes.indexOf(CR, i) + 1;
2014 if (!index) index = bytes.length;
2015 const last = index - (bytes[index] === LF ? 1 : 0);
2016 if (i) bytes.copyWithin(j, i, last);
2017 j += last - i;
2018 }
2019 return bytes.subarray(0, j);
2020 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
2021 },
2022
2023 /**
2024 * Remove trailing spaces, carriage returns and tabs from each line
2025 */
2026 removeTrailingSpaces: function(text) {
2027 return text.split('\n').map(line => {
2028 let i = line.length - 1;
2029 for (; i >= 0 && (line[i] === ' ' || line[i] === '\t' || line[i] === '\r'); i--);
2030 return line.substr(0, i + 1);
2031 }).join('\n');
2032 },
2033
2034 wrapError: function(message, error) {
2035 if (!error) {
2036 return new Error(message);
2037 }
2038
2039 // update error message
2040 try {
2041 error.message = message + ': ' + error.message;
2042 } catch (e) {}
2043
2044 return error;
2045 },
2046
2047 /**
2048 * Map allowed packet tags to corresponding classes
2049 * Meant to be used to format `allowedPacket` for Packetlist.read
2050 * @param {Array<Object>} allowedClasses
2051 * @returns {Object} map from enum.packet to corresponding *Packet class
2052 */
2053 constructAllowedPackets: function(allowedClasses) {
2054 const map = {};
2055 allowedClasses.forEach(PacketClass => {
2056 if (!PacketClass.tag) {
2057 throw new Error('Invalid input: expected a packet class');
2058 }
2059 map[PacketClass.tag] = PacketClass;
2060 });
2061 return map;
2062 },
2063
2064 /**
2065 * Return a Promise that will resolve as soon as one of the promises in input resolves
2066 * or will reject if all input promises all rejected
2067 * (similar to Promise.any, but with slightly different error handling)
2068 * @param {Array<Promise>} promises
2069 * @return {Promise<Any>} Promise resolving to the result of the fastest fulfilled promise
2070 * or rejected with the Error of the last resolved Promise (if all promises are rejected)
2071 */
2072 anyPromise: function(promises) {
2073 return new Promise(async (resolve, reject) => {
2074 let exception;
2075 await Promise.all(promises.map(async promise => {
2076 try {
2077 resolve(await promise);
2078 } catch (e) {
2079 exception = e;
2080 }
2081 }));
2082 reject(exception);
2083 });
2084 },
2085
2086 /**
2087 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2088 * @param {Boolean} cond
2089 * @param {Uint8Array} a
2090 * @param {Uint8Array} b
2091 * @returns `a` if `cond` is true, `b` otherwise
2092 */
2093 selectUint8Array: function(cond, a, b) {
2094 const length = Math.max(a.length, b.length);
2095 const result = new Uint8Array(length);
2096 let end = 0;
2097 for (let i = 0; i < result.length; i++) {
2098 result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));
2099 end += (cond & i < a.length) | ((1 - cond) & i < b.length);
2100 }
2101 return result.subarray(0, end);
2102 },
2103 /**
2104 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2105 * NB: it only supports `a, b` with values between 0-255.
2106 * @param {Boolean} cond
2107 * @param {Uint8} a
2108 * @param {Uint8} b
2109 * @returns `a` if `cond` is true, `b` otherwise
2110 */
2111 selectUint8: function(cond, a, b) {
2112 return (a & (256 - cond)) | (b & (255 + cond));
2113 }
2114};
2115
2116/* OpenPGP radix-64/base64 string encoding/decoding
2117 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
2118 * version 1.0, check www.haneWIN.de for the latest version
2119 *
2120 * This software is provided as-is, without express or implied warranty.
2121 * Permission to use, copy, modify, distribute or sell this software, with or
2122 * without fee, for any purpose and by any individual or organization, is hereby
2123 * granted, provided that the above copyright notice and this paragraph appear
2124 * in all copies. Distribution as a part of an application or binary must
2125 * include the above copyright notice in the documentation and/or other materials
2126 * provided with the application or distribution.
2127 */
2128
2129const Buffer = util.getNodeBuffer();
2130
2131let encodeChunk;
2132let decodeChunk;
2133if (Buffer) {
2134 encodeChunk = buf => Buffer.from(buf).toString('base64');
2135 decodeChunk = str => {
2136 const b = Buffer.from(str, 'base64');
2137 return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
2138 };
2139} else {
2140 encodeChunk = buf => btoa(util.uint8ArrayToString(buf));
2141 decodeChunk = str => util.stringToUint8Array(atob(str));
2142}
2143
2144/**
2145 * Convert binary array to radix-64
2146 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
2147 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
2148 * @static
2149 */
2150function encode(data) {
2151 let buf = new Uint8Array();
2152 return transform(data, value => {
2153 buf = util.concatUint8Array([buf, value]);
2154 const r = [];
2155 const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
2156 const lines = Math.floor(buf.length / bytesPerLine);
2157 const bytes = lines * bytesPerLine;
2158 const encoded = encodeChunk(buf.subarray(0, bytes));
2159 for (let i = 0; i < lines; i++) {
2160 r.push(encoded.substr(i * 60, 60));
2161 r.push('\n');
2162 }
2163 buf = buf.subarray(bytes);
2164 return r.join('');
2165 }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
2166}
2167
2168/**
2169 * Convert radix-64 to binary array
2170 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
2171 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
2172 * @static
2173 */
2174function decode(data) {
2175 let buf = '';
2176 return transform(data, value => {
2177 buf += value;
2178
2179 // Count how many whitespace characters there are in buf
2180 let spaces = 0;
2181 const spacechars = [' ', '\t', '\r', '\n'];
2182 for (let i = 0; i < spacechars.length; i++) {
2183 const spacechar = spacechars[i];
2184 for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
2185 spaces++;
2186 }
2187 }
2188
2189 // Backtrack until we have 4n non-whitespace characters
2190 // that we can safely base64-decode
2191 let length = buf.length;
2192 for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
2193 if (spacechars.includes(buf[length])) spaces--;
2194 }
2195
2196 const decoded = decodeChunk(buf.substr(0, length));
2197 buf = buf.substr(length);
2198 return decoded;
2199 }, () => decodeChunk(buf));
2200}
2201
2202/**
2203 * Convert a Base-64 encoded string an array of 8-bit integer
2204 *
2205 * Note: accepts both Radix-64 and URL-safe strings
2206 * @param {String} base64 - Base-64 encoded string to convert
2207 * @returns {Uint8Array} An array of 8-bit integers.
2208 */
2209function b64ToUint8Array(base64) {
2210 return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
2211}
2212
2213/**
2214 * Convert an array of 8-bit integer to a Base-64 encoded string
2215 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
2216 * @param {bool} url - If true, output is URL-safe
2217 * @returns {String} Base-64 encoded string.
2218 */
2219function uint8ArrayToB64(bytes, url) {
2220 let encoded = encode(bytes).replace(/[\r\n]/g, '');
2221 if (url) {
2222 encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
2223 }
2224 return encoded;
2225}
2226
2227/**
2228 * @module enums
2229 */
2230
2231const byValue = Symbol('byValue');
2232
2233var enums = {
2234
2235 /** Maps curve names under various standards to one
2236 * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
2237 * @enum {String}
2238 * @readonly
2239 */
2240 curve: {
2241 /** NIST P-256 Curve */
2242 'p256': 'p256',
2243 'P-256': 'p256',
2244 'secp256r1': 'p256',
2245 'prime256v1': 'p256',
2246 '1.2.840.10045.3.1.7': 'p256',
2247 '2a8648ce3d030107': 'p256',
2248 '2A8648CE3D030107': 'p256',
2249
2250 /** NIST P-384 Curve */
2251 'p384': 'p384',
2252 'P-384': 'p384',
2253 'secp384r1': 'p384',
2254 '1.3.132.0.34': 'p384',
2255 '2b81040022': 'p384',
2256 '2B81040022': 'p384',
2257
2258 /** NIST P-521 Curve */
2259 'p521': 'p521',
2260 'P-521': 'p521',
2261 'secp521r1': 'p521',
2262 '1.3.132.0.35': 'p521',
2263 '2b81040023': 'p521',
2264 '2B81040023': 'p521',
2265
2266 /** SECG SECP256k1 Curve */
2267 'secp256k1': 'secp256k1',
2268 '1.3.132.0.10': 'secp256k1',
2269 '2b8104000a': 'secp256k1',
2270 '2B8104000A': 'secp256k1',
2271
2272 /** Ed25519 */
2273 'ED25519': 'ed25519',
2274 'ed25519': 'ed25519',
2275 'Ed25519': 'ed25519',
2276 '1.3.6.1.4.1.11591.15.1': 'ed25519',
2277 '2b06010401da470f01': 'ed25519',
2278 '2B06010401DA470F01': 'ed25519',
2279
2280 /** Curve25519 */
2281 'X25519': 'curve25519',
2282 'cv25519': 'curve25519',
2283 'curve25519': 'curve25519',
2284 'Curve25519': 'curve25519',
2285 '1.3.6.1.4.1.3029.1.5.1': 'curve25519',
2286 '2b060104019755010501': 'curve25519',
2287 '2B060104019755010501': 'curve25519',
2288
2289 /** BrainpoolP256r1 Curve */
2290 'brainpoolP256r1': 'brainpoolP256r1',
2291 '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',
2292 '2b2403030208010107': 'brainpoolP256r1',
2293 '2B2403030208010107': 'brainpoolP256r1',
2294
2295 /** BrainpoolP384r1 Curve */
2296 'brainpoolP384r1': 'brainpoolP384r1',
2297 '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',
2298 '2b240303020801010b': 'brainpoolP384r1',
2299 '2B240303020801010B': 'brainpoolP384r1',
2300
2301 /** BrainpoolP512r1 Curve */
2302 'brainpoolP512r1': 'brainpoolP512r1',
2303 '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',
2304 '2b240303020801010d': 'brainpoolP512r1',
2305 '2B240303020801010D': 'brainpoolP512r1'
2306 },
2307
2308 /** A string to key specifier type
2309 * @enum {Integer}
2310 * @readonly
2311 */
2312 s2k: {
2313 simple: 0,
2314 salted: 1,
2315 iterated: 3,
2316 gnu: 101
2317 },
2318
2319 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
2320 * @enum {Integer}
2321 * @readonly
2322 */
2323 publicKey: {
2324 /** RSA (Encrypt or Sign) [HAC] */
2325 rsaEncryptSign: 1,
2326 /** RSA (Encrypt only) [HAC] */
2327 rsaEncrypt: 2,
2328 /** RSA (Sign only) [HAC] */
2329 rsaSign: 3,
2330 /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
2331 elgamal: 16,
2332 /** DSA (Sign only) [FIPS186] [HAC] */
2333 dsa: 17,
2334 /** ECDH (Encrypt only) [RFC6637] */
2335 ecdh: 18,
2336 /** ECDSA (Sign only) [RFC6637] */
2337 ecdsa: 19,
2338 /** EdDSA (Sign only)
2339 * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
2340 eddsa: 22,
2341 /** Reserved for AEDH */
2342 aedh: 23,
2343 /** Reserved for AEDSA */
2344 aedsa: 24
2345 },
2346
2347 /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
2348 * @enum {Integer}
2349 * @readonly
2350 */
2351 symmetric: {
2352 plaintext: 0,
2353 /** Not implemented! */
2354 idea: 1,
2355 tripledes: 2,
2356 cast5: 3,
2357 blowfish: 4,
2358 aes128: 7,
2359 aes192: 8,
2360 aes256: 9,
2361 twofish: 10
2362 },
2363
2364 /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
2365 * @enum {Integer}
2366 * @readonly
2367 */
2368 compression: {
2369 uncompressed: 0,
2370 /** RFC1951 */
2371 zip: 1,
2372 /** RFC1950 */
2373 zlib: 2,
2374 bzip2: 3
2375 },
2376
2377 /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
2378 * @enum {Integer}
2379 * @readonly
2380 */
2381 hash: {
2382 md5: 1,
2383 sha1: 2,
2384 ripemd: 3,
2385 sha256: 8,
2386 sha384: 9,
2387 sha512: 10,
2388 sha224: 11
2389 },
2390
2391 /** A list of hash names as accepted by webCrypto functions.
2392 * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
2393 * @enum {String}
2394 */
2395 webHash: {
2396 'SHA-1': 2,
2397 'SHA-256': 8,
2398 'SHA-384': 9,
2399 'SHA-512': 10
2400 },
2401
2402 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
2403 * @enum {Integer}
2404 * @readonly
2405 */
2406 aead: {
2407 eax: 1,
2408 ocb: 2,
2409 experimentalGCM: 100 // Private algorithm
2410 },
2411
2412 /** A list of packet types and numeric tags associated with them.
2413 * @enum {Integer}
2414 * @readonly
2415 */
2416 packet: {
2417 publicKeyEncryptedSessionKey: 1,
2418 signature: 2,
2419 symEncryptedSessionKey: 3,
2420 onePassSignature: 4,
2421 secretKey: 5,
2422 publicKey: 6,
2423 secretSubkey: 7,
2424 compressedData: 8,
2425 symmetricallyEncryptedData: 9,
2426 marker: 10,
2427 literalData: 11,
2428 trust: 12,
2429 userID: 13,
2430 publicSubkey: 14,
2431 userAttribute: 17,
2432 symEncryptedIntegrityProtectedData: 18,
2433 modificationDetectionCode: 19,
2434 aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
2435 },
2436
2437 /** Data types in the literal packet
2438 * @enum {Integer}
2439 * @readonly
2440 */
2441 literal: {
2442 /** Binary data 'b' */
2443 binary: 'b'.charCodeAt(),
2444 /** Text data 't' */
2445 text: 't'.charCodeAt(),
2446 /** Utf8 data 'u' */
2447 utf8: 'u'.charCodeAt(),
2448 /** MIME message body part 'm' */
2449 mime: 'm'.charCodeAt()
2450 },
2451
2452
2453 /** One pass signature packet type
2454 * @enum {Integer}
2455 * @readonly
2456 */
2457 signature: {
2458 /** 0x00: Signature of a binary document. */
2459 binary: 0,
2460 /** 0x01: Signature of a canonical text document.
2461 *
2462 * Canonicalyzing the document by converting line endings. */
2463 text: 1,
2464 /** 0x02: Standalone signature.
2465 *
2466 * This signature is a signature of only its own subpacket contents.
2467 * It is calculated identically to a signature over a zero-lengh
2468 * binary document. Note that it doesn't make sense to have a V3
2469 * standalone signature. */
2470 standalone: 2,
2471 /** 0x10: Generic certification of a User ID and Public-Key packet.
2472 *
2473 * The issuer of this certification does not make any particular
2474 * assertion as to how well the certifier has checked that the owner
2475 * of the key is in fact the person described by the User ID. */
2476 certGeneric: 16,
2477 /** 0x11: Persona certification of a User ID and Public-Key packet.
2478 *
2479 * The issuer of this certification has not done any verification of
2480 * the claim that the owner of this key is the User ID specified. */
2481 certPersona: 17,
2482 /** 0x12: Casual certification of a User ID and Public-Key packet.
2483 *
2484 * The issuer of this certification has done some casual
2485 * verification of the claim of identity. */
2486 certCasual: 18,
2487 /** 0x13: Positive certification of a User ID and Public-Key packet.
2488 *
2489 * The issuer of this certification has done substantial
2490 * verification of the claim of identity.
2491 *
2492 * Most OpenPGP implementations make their "key signatures" as 0x10
2493 * certifications. Some implementations can issue 0x11-0x13
2494 * certifications, but few differentiate between the types. */
2495 certPositive: 19,
2496 /** 0x30: Certification revocation signature
2497 *
2498 * This signature revokes an earlier User ID certification signature
2499 * (signature class 0x10 through 0x13) or direct-key signature
2500 * (0x1F). It should be issued by the same key that issued the
2501 * revoked signature or an authorized revocation key. The signature
2502 * is computed over the same data as the certificate that it
2503 * revokes, and should have a later creation date than that
2504 * certificate. */
2505 certRevocation: 48,
2506 /** 0x18: Subkey Binding Signature
2507 *
2508 * This signature is a statement by the top-level signing key that
2509 * indicates that it owns the subkey. This signature is calculated
2510 * directly on the primary key and subkey, and not on any User ID or
2511 * other packets. A signature that binds a signing subkey MUST have
2512 * an Embedded Signature subpacket in this binding signature that
2513 * contains a 0x19 signature made by the signing subkey on the
2514 * primary key and subkey. */
2515 subkeyBinding: 24,
2516 /** 0x19: Primary Key Binding Signature
2517 *
2518 * This signature is a statement by a signing subkey, indicating
2519 * that it is owned by the primary key and subkey. This signature
2520 * is calculated the same way as a 0x18 signature: directly on the
2521 * primary key and subkey, and not on any User ID or other packets.
2522 *
2523 * When a signature is made over a key, the hash data starts with the
2524 * octet 0x99, followed by a two-octet length of the key, and then body
2525 * of the key packet. (Note that this is an old-style packet header for
2526 * a key packet with two-octet length.) A subkey binding signature
2527 * (type 0x18) or primary key binding signature (type 0x19) then hashes
2528 * the subkey using the same format as the main key (also using 0x99 as
2529 * the first octet). */
2530 keyBinding: 25,
2531 /** 0x1F: Signature directly on a key
2532 *
2533 * This signature is calculated directly on a key. It binds the
2534 * information in the Signature subpackets to the key, and is
2535 * appropriate to be used for subpackets that provide information
2536 * about the key, such as the Revocation Key subpacket. It is also
2537 * appropriate for statements that non-self certifiers want to make
2538 * about the key itself, rather than the binding between a key and a
2539 * name. */
2540 key: 31,
2541 /** 0x20: Key revocation signature
2542 *
2543 * The signature is calculated directly on the key being revoked. A
2544 * revoked key is not to be used. Only revocation signatures by the
2545 * key being revoked, or by an authorized revocation key, should be
2546 * considered valid revocation signatures.a */
2547 keyRevocation: 32,
2548 /** 0x28: Subkey revocation signature
2549 *
2550 * The signature is calculated directly on the subkey being revoked.
2551 * A revoked subkey is not to be used. Only revocation signatures
2552 * by the top-level signature key that is bound to this subkey, or
2553 * by an authorized revocation key, should be considered valid
2554 * revocation signatures.
2555 *
2556 * Key revocation signatures (types 0x20 and 0x28)
2557 * hash only the key being revoked. */
2558 subkeyRevocation: 40,
2559 /** 0x40: Timestamp signature.
2560 * This signature is only meaningful for the timestamp contained in
2561 * it. */
2562 timestamp: 64,
2563 /** 0x50: Third-Party Confirmation signature.
2564 *
2565 * This signature is a signature over some other OpenPGP Signature
2566 * packet(s). It is analogous to a notary seal on the signed data.
2567 * A third-party signature SHOULD include Signature Target
2568 * subpacket(s) to give easy identification. Note that we really do
2569 * mean SHOULD. There are plausible uses for this (such as a blind
2570 * party that only sees the signature, not the key or source
2571 * document) that cannot include a target subpacket. */
2572 thirdParty: 80
2573 },
2574
2575 /** Signature subpacket type
2576 * @enum {Integer}
2577 * @readonly
2578 */
2579 signatureSubpacket: {
2580 signatureCreationTime: 2,
2581 signatureExpirationTime: 3,
2582 exportableCertification: 4,
2583 trustSignature: 5,
2584 regularExpression: 6,
2585 revocable: 7,
2586 keyExpirationTime: 9,
2587 placeholderBackwardsCompatibility: 10,
2588 preferredSymmetricAlgorithms: 11,
2589 revocationKey: 12,
2590 issuer: 16,
2591 notationData: 20,
2592 preferredHashAlgorithms: 21,
2593 preferredCompressionAlgorithms: 22,
2594 keyServerPreferences: 23,
2595 preferredKeyServer: 24,
2596 primaryUserID: 25,
2597 policyURI: 26,
2598 keyFlags: 27,
2599 signersUserID: 28,
2600 reasonForRevocation: 29,
2601 features: 30,
2602 signatureTarget: 31,
2603 embeddedSignature: 32,
2604 issuerFingerprint: 33,
2605 preferredAEADAlgorithms: 34
2606 },
2607
2608 /** Key flags
2609 * @enum {Integer}
2610 * @readonly
2611 */
2612 keyFlags: {
2613 /** 0x01 - This key may be used to certify other keys. */
2614 certifyKeys: 1,
2615 /** 0x02 - This key may be used to sign data. */
2616 signData: 2,
2617 /** 0x04 - This key may be used to encrypt communications. */
2618 encryptCommunication: 4,
2619 /** 0x08 - This key may be used to encrypt storage. */
2620 encryptStorage: 8,
2621 /** 0x10 - The private component of this key may have been split
2622 * by a secret-sharing mechanism. */
2623 splitPrivateKey: 16,
2624 /** 0x20 - This key may be used for authentication. */
2625 authentication: 32,
2626 /** 0x80 - The private component of this key may be in the
2627 * possession of more than one person. */
2628 sharedPrivateKey: 128
2629 },
2630
2631 /** Armor type
2632 * @enum {Integer}
2633 * @readonly
2634 */
2635 armor: {
2636 multipartSection: 0,
2637 multipartLast: 1,
2638 signed: 2,
2639 message: 3,
2640 publicKey: 4,
2641 privateKey: 5,
2642 signature: 6
2643 },
2644
2645 /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
2646 * @enum {Integer}
2647 * @readonly
2648 */
2649 reasonForRevocation: {
2650 /** No reason specified (key revocations or cert revocations) */
2651 noReason: 0,
2652 /** Key is superseded (key revocations) */
2653 keySuperseded: 1,
2654 /** Key material has been compromised (key revocations) */
2655 keyCompromised: 2,
2656 /** Key is retired and no longer used (key revocations) */
2657 keyRetired: 3,
2658 /** User ID information is no longer valid (cert revocations) */
2659 userIDInvalid: 32
2660 },
2661
2662 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
2663 * @enum {Integer}
2664 * @readonly
2665 */
2666 features: {
2667 /** 0x01 - Modification Detection (packets 18 and 19) */
2668 modificationDetection: 1,
2669 /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
2670 * Symmetric-Key Encrypted Session Key Packets (packet 3) */
2671 aead: 2,
2672 /** 0x04 - Version 5 Public-Key Packet format and corresponding new
2673 * fingerprint format */
2674 v5Keys: 4
2675 },
2676
2677 /**
2678 * Asserts validity of given value and converts from string/integer to integer.
2679 * @param {Object} type target enum type
2680 * @param {String|Integer} e value to check and/or convert
2681 * @returns {Integer} enum value if it exists
2682 * @throws {Error} if the value is invalid
2683 */
2684 write: function(type, e) {
2685 if (typeof e === 'number') {
2686 e = this.read(type, e);
2687 }
2688
2689 if (type[e] !== undefined) {
2690 return type[e];
2691 }
2692
2693 throw new Error('Invalid enum value.');
2694 },
2695
2696 /**
2697 * Converts enum integer value to the corresponding string, if it exists.
2698 * @param {Object} type target enum type
2699 * @param {Integer} e value to convert
2700 * @returns {String} name of enum value if it exists
2701 * @throws {Error} if the value is invalid
2702 */
2703 read: function(type, e) {
2704 if (!type[byValue]) {
2705 type[byValue] = [];
2706 Object.entries(type).forEach(([key, value]) => {
2707 type[byValue][value] = key;
2708 });
2709 }
2710
2711 if (type[byValue][e] !== undefined) {
2712 return type[byValue][e];
2713 }
2714
2715 throw new Error('Invalid enum value.');
2716 }
2717};
2718
2719// GPG4Browsers - An OpenPGP implementation in javascript
2720
2721var defaultConfig = {
2722 /**
2723 * @memberof module:config
2724 * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
2725 */
2726 preferredHashAlgorithm: enums.hash.sha256,
2727 /**
2728 * @memberof module:config
2729 * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
2730 */
2731 preferredSymmetricAlgorithm: enums.symmetric.aes256,
2732 /**
2733 * @memberof module:config
2734 * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
2735 */
2736 preferredCompressionAlgorithm: enums.compression.uncompressed,
2737 /**
2738 * @memberof module:config
2739 * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
2740 */
2741 deflateLevel: 6,
2742
2743 /**
2744 * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
2745 * Note: not all OpenPGP implementations are compatible with this option.
2746 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2747 * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
2748 * @memberof module:config
2749 * @property {Boolean} aeadProtect
2750 */
2751 aeadProtect: false,
2752 /**
2753 * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
2754 * Only has an effect when aeadProtect is set to true.
2755 * @memberof module:config
2756 * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
2757 */
2758 preferredAEADAlgorithm: enums.aead.eax,
2759 /**
2760 * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
2761 * Only has an effect when aeadProtect is set to true.
2762 * Must be an integer value from 0 to 56.
2763 * @memberof module:config
2764 * @property {Integer} aeadChunkSizeByte
2765 */
2766 aeadChunkSizeByte: 12,
2767 /**
2768 * Use V5 keys.
2769 * Note: not all OpenPGP implementations are compatible with this option.
2770 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2771 * @memberof module:config
2772 * @property {Boolean} v5Keys
2773 */
2774 v5Keys: false,
2775 /**
2776 * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
2777 * Iteration Count Byte for S2K (String to Key)
2778 * @memberof module:config
2779 * @property {Integer} s2kIterationCountByte
2780 */
2781 s2kIterationCountByte: 224,
2782 /**
2783 * Allow decryption of messages without integrity protection.
2784 * This is an **insecure** setting:
2785 * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
2786 * - it enables downgrade attacks against integrity-protected messages.
2787 * @memberof module:config
2788 * @property {Boolean} allowUnauthenticatedMessages
2789 */
2790 allowUnauthenticatedMessages: false,
2791 /**
2792 * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to
2793 * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible
2794 * and deferring checking their integrity until the decrypted stream has been read in full.
2795 *
2796 * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.
2797 * @memberof module:config
2798 * @property {Boolean} allowUnauthenticatedStream
2799 */
2800 allowUnauthenticatedStream: false,
2801 /**
2802 * @memberof module:config
2803 * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
2804 */
2805 checksumRequired: false,
2806 /**
2807 * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
2808 * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
2809 * @memberof module:config
2810 * @property {Number} minRSABits
2811 */
2812 minRSABits: 2047,
2813 /**
2814 * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
2815 * **Slower and slightly less secure**
2816 * @memberof module:config
2817 * @property {Boolean} passwordCollisionCheck
2818 */
2819 passwordCollisionCheck: false,
2820 /**
2821 * @memberof module:config
2822 * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
2823 */
2824 revocationsExpire: false,
2825 /**
2826 * Allow decryption using RSA keys without `encrypt` flag.
2827 * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
2828 * where key flags were ignored when selecting a key for encryption.
2829 * @memberof module:config
2830 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2831 */
2832 allowInsecureDecryptionWithSigningKeys: false,
2833 /**
2834 * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.
2835 * Instead, a verification key will also be consider valid as long as it is valid at the current time.
2836 * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,
2837 * and have self-signature's creation date that does not match the primary key creation date.
2838 * @memberof module:config
2839 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2840 */
2841 allowInsecureVerificationWithReformattedKeys: false,
2842
2843 /**
2844 * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).
2845 * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:
2846 * - new/incoming messages are automatically decrypted (without user interaction);
2847 * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).
2848 * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.
2849 * @memberof module:config
2850 * @property {Boolean} constantTimePKCS1Decryption
2851 */
2852 constantTimePKCS1Decryption: false,
2853 /**
2854 * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.
2855 * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.
2856 * However, the more algorithms are added, the slower the decryption procedure becomes.
2857 * @memberof module:config
2858 * @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}
2859 */
2860 constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),
2861
2862 /**
2863 * @memberof module:config
2864 * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
2865 */
2866 minBytesForWebCrypto: 1000,
2867 /**
2868 * @memberof module:config
2869 * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
2870 */
2871 ignoreUnsupportedPackets: true,
2872 /**
2873 * @memberof module:config
2874 * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error
2875 */
2876 ignoreMalformedPackets: false,
2877 /**
2878 * @memberof module:config
2879 * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
2880 */
2881 showVersion: false,
2882 /**
2883 * @memberof module:config
2884 * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
2885 */
2886 showComment: false,
2887 /**
2888 * @memberof module:config
2889 * @property {String} versionString A version string to be included in armored messages
2890 */
2891 versionString: 'OpenPGP.js 5.5.0',
2892 /**
2893 * @memberof module:config
2894 * @property {String} commentString A comment string to be included in armored messages
2895 */
2896 commentString: 'https://openpgpjs.org',
2897
2898 /**
2899 * Max userID string length (used for parsing)
2900 * @memberof module:config
2901 * @property {Integer} maxUserIDLength
2902 */
2903 maxUserIDLength: 1024 * 5,
2904 /**
2905 * Contains notatations that are considered "known". Known notations do not trigger
2906 * validation error when the notation is marked as critical.
2907 * @memberof module:config
2908 * @property {Array} knownNotations
2909 */
2910 knownNotations: ['preferred-email-encoding@pgp.com', 'pka-address@gnupg.org'],
2911 /**
2912 * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.
2913 * When false, certain standard curves will not be supported (depending on the platform).
2914 * Note: the indutny/elliptic curve library is not designed to be constant time.
2915 * @memberof module:config
2916 * @property {Boolean} useIndutnyElliptic
2917 */
2918 useIndutnyElliptic: true,
2919 /**
2920 * Reject insecure hash algorithms
2921 * @memberof module:config
2922 * @property {Set<Integer>} rejectHashAlgorithms {@link module:enums.hash}
2923 */
2924 rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),
2925 /**
2926 * Reject insecure message hash algorithms
2927 * @memberof module:config
2928 * @property {Set<Integer>} rejectMessageHashAlgorithms {@link module:enums.hash}
2929 */
2930 rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),
2931 /**
2932 * Reject insecure public key algorithms for key generation and message encryption, signing or verification
2933 * @memberof module:config
2934 * @property {Set<Integer>} rejectPublicKeyAlgorithms {@link module:enums.publicKey}
2935 */
2936 rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),
2937 /**
2938 * Reject non-standard curves for key generation, message encryption, signing or verification
2939 * @memberof module:config
2940 * @property {Set<String>} rejectCurves {@link module:enums.curve}
2941 */
2942 rejectCurves: new Set([enums.curve.brainpoolP256r1, enums.curve.brainpoolP384r1, enums.curve.brainpoolP512r1, enums.curve.secp256k1])
2943};
2944
2945// GPG4Browsers - An OpenPGP implementation in javascript
2946
2947/**
2948 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
2949 * @param {String} text - ascii armored text
2950 * @returns {Integer} 0 = MESSAGE PART n of m.
2951 * 1 = MESSAGE PART n
2952 * 2 = SIGNED MESSAGE
2953 * 3 = PGP MESSAGE
2954 * 4 = PUBLIC KEY BLOCK
2955 * 5 = PRIVATE KEY BLOCK
2956 * 6 = SIGNATURE
2957 * @private
2958 */
2959function getType(text) {
2960 const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
2961
2962 const header = text.match(reHeader);
2963
2964 if (!header) {
2965 throw new Error('Unknown ASCII armor type');
2966 }
2967
2968 // BEGIN PGP MESSAGE, PART X/Y
2969 // Used for multi-part messages, where the armor is split amongst Y
2970 // parts, and this is the Xth part out of Y.
2971 if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
2972 return enums.armor.multipartSection;
2973 } else
2974 // BEGIN PGP MESSAGE, PART X
2975 // Used for multi-part messages, where this is the Xth part of an
2976 // unspecified number of parts. Requires the MESSAGE-ID Armor
2977 // Header to be used.
2978 if (/MESSAGE, PART \d+/.test(header[1])) {
2979 return enums.armor.multipartLast;
2980 } else
2981 // BEGIN PGP SIGNED MESSAGE
2982 if (/SIGNED MESSAGE/.test(header[1])) {
2983 return enums.armor.signed;
2984 } else
2985 // BEGIN PGP MESSAGE
2986 // Used for signed, encrypted, or compressed files.
2987 if (/MESSAGE/.test(header[1])) {
2988 return enums.armor.message;
2989 } else
2990 // BEGIN PGP PUBLIC KEY BLOCK
2991 // Used for armoring public keys.
2992 if (/PUBLIC KEY BLOCK/.test(header[1])) {
2993 return enums.armor.publicKey;
2994 } else
2995 // BEGIN PGP PRIVATE KEY BLOCK
2996 // Used for armoring private keys.
2997 if (/PRIVATE KEY BLOCK/.test(header[1])) {
2998 return enums.armor.privateKey;
2999 } else
3000 // BEGIN PGP SIGNATURE
3001 // Used for detached signatures, OpenPGP/MIME signatures, and
3002 // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
3003 // for detached signatures.
3004 if (/SIGNATURE/.test(header[1])) {
3005 return enums.armor.signature;
3006 }
3007}
3008
3009/**
3010 * Add additional information to the armor version of an OpenPGP binary
3011 * packet block.
3012 * @author Alex
3013 * @version 2011-12-16
3014 * @param {String} [customComment] - Additional comment to add to the armored string
3015 * @returns {String} The header information.
3016 * @private
3017 */
3018function addheader(customComment, config) {
3019 let result = '';
3020 if (config.showVersion) {
3021 result += 'Version: ' + config.versionString + '\n';
3022 }
3023 if (config.showComment) {
3024 result += 'Comment: ' + config.commentString + '\n';
3025 }
3026 if (customComment) {
3027 result += 'Comment: ' + customComment + '\n';
3028 }
3029 result += '\n';
3030 return result;
3031}
3032
3033
3034/**
3035 * Calculates a checksum over the given data and returns it base64 encoded
3036 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
3037 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
3038 * @private
3039 */
3040function getCheckSum(data) {
3041 const crc = createcrc24(data);
3042 return encode(crc);
3043}
3044
3045// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
3046
3047const crc_table = [
3048 new Array(0xFF),
3049 new Array(0xFF),
3050 new Array(0xFF),
3051 new Array(0xFF)
3052];
3053
3054for (let i = 0; i <= 0xFF; i++) {
3055 let crc = i << 16;
3056 for (let j = 0; j < 8; j++) {
3057 crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
3058 }
3059 crc_table[0][i] =
3060 ((crc & 0xFF0000) >> 16) |
3061 (crc & 0x00FF00) |
3062 ((crc & 0x0000FF) << 16);
3063}
3064for (let i = 0; i <= 0xFF; i++) {
3065 crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
3066}
3067for (let i = 0; i <= 0xFF; i++) {
3068 crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
3069}
3070for (let i = 0; i <= 0xFF; i++) {
3071 crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
3072}
3073
3074// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
3075const isLittleEndian = (function() {
3076 const buffer = new ArrayBuffer(2);
3077 new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
3078 // Int16Array uses the platform's endianness.
3079 return new Int16Array(buffer)[0] === 0xFF;
3080}());
3081
3082/**
3083 * Internal function to calculate a CRC-24 checksum over a given string (data)
3084 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
3085 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
3086 * @private
3087 */
3088function createcrc24(input) {
3089 let crc = 0xCE04B7;
3090 return transform(input, value => {
3091 const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;
3092 const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
3093 for (let i = 0; i < len32; i++) {
3094 crc ^= arr32[i];
3095 crc =
3096 crc_table[0][(crc >> 24) & 0xFF] ^
3097 crc_table[1][(crc >> 16) & 0xFF] ^
3098 crc_table[2][(crc >> 8) & 0xFF] ^
3099 crc_table[3][(crc >> 0) & 0xFF];
3100 }
3101 for (let i = len32 * 4; i < value.length; i++) {
3102 crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
3103 }
3104 }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
3105}
3106
3107/**
3108 * Verify armored headers. crypto-refresh-06, section 6.2:
3109 * "An OpenPGP implementation may consider improperly formatted Armor
3110 * Headers to be corruption of the ASCII Armor, but SHOULD make an
3111 * effort to recover."
3112 * @private
3113 * @param {Array<String>} headers - Armor headers
3114 */
3115function verifyHeaders(headers) {
3116 for (let i = 0; i < headers.length; i++) {
3117 if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
3118 util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));
3119 }
3120 if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
3121 util.printDebugError(new Error('Unknown header: ' + headers[i]));
3122 }
3123 }
3124}
3125
3126/**
3127 * Splits a message into two parts, the body and the checksum. This is an internal function
3128 * @param {String} text - OpenPGP armored message part
3129 * @returns {Object} An object with attribute "body" containing the body.
3130 * and an attribute "checksum" containing the checksum.
3131 * @private
3132 */
3133function splitChecksum(text) {
3134 let body = text;
3135 let checksum = '';
3136
3137 const lastEquals = text.lastIndexOf('=');
3138
3139 if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
3140 body = text.slice(0, lastEquals);
3141 checksum = text.slice(lastEquals + 1).substr(0, 4);
3142 }
3143
3144 return { body: body, checksum: checksum };
3145}
3146
3147/**
3148 * Dearmor an OpenPGP armored message; verify the checksum and return
3149 * the encoded bytes
3150 * @param {String} input - OpenPGP armored message
3151 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
3152 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
3153 * @async
3154 * @static
3155 */
3156function unarmor(input, config = defaultConfig) {
3157 return new Promise(async (resolve, reject) => {
3158 try {
3159 const reSplit = /^-----[^-]+-----$/m;
3160 const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
3161
3162 let type;
3163 const headers = [];
3164 let lastHeaders = headers;
3165 let headersDone;
3166 let text = [];
3167 let textDone;
3168 let checksum;
3169 let data = decode(transformPair(input, async (readable, writable) => {
3170 const reader = getReader(readable);
3171 try {
3172 while (true) {
3173 let line = await reader.readLine();
3174 if (line === undefined) {
3175 throw new Error('Misformed armored text');
3176 }
3177 // remove trailing whitespace at end of lines
3178 line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
3179 if (!type) {
3180 if (reSplit.test(line)) {
3181 type = getType(line);
3182 }
3183 } else if (!headersDone) {
3184 if (reSplit.test(line)) {
3185 reject(new Error('Mandatory blank line missing between armor headers and armor data'));
3186 }
3187 if (!reEmptyLine.test(line)) {
3188 lastHeaders.push(line);
3189 } else {
3190 verifyHeaders(lastHeaders);
3191 headersDone = true;
3192 if (textDone || type !== 2) {
3193 resolve({ text, data, headers, type });
3194 break;
3195 }
3196 }
3197 } else if (!textDone && type === 2) {
3198 if (!reSplit.test(line)) {
3199 // Reverse dash-escaping for msg
3200 text.push(line.replace(/^- /, ''));
3201 } else {
3202 text = text.join('\r\n');
3203 textDone = true;
3204 verifyHeaders(lastHeaders);
3205 lastHeaders = [];
3206 headersDone = false;
3207 }
3208 }
3209 }
3210 } catch (e) {
3211 reject(e);
3212 return;
3213 }
3214 const writer = getWriter(writable);
3215 try {
3216 while (true) {
3217 await writer.ready;
3218 const { done, value } = await reader.read();
3219 if (done) {
3220 throw new Error('Misformed armored text');
3221 }
3222 const line = value + '';
3223 if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
3224 await writer.write(line);
3225 } else {
3226 let remainder = await reader.readToEnd();
3227 if (!remainder.length) remainder = '';
3228 remainder = line + remainder;
3229 remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
3230 const parts = remainder.split(reSplit);
3231 if (parts.length === 1) {
3232 throw new Error('Misformed armored text');
3233 }
3234 const split = splitChecksum(parts[0].slice(0, -1));
3235 checksum = split.checksum;
3236 await writer.write(split.body);
3237 break;
3238 }
3239 }
3240 await writer.ready;
3241 await writer.close();
3242 } catch (e) {
3243 await writer.abort(e);
3244 }
3245 }));
3246 data = transformPair(data, async (readable, writable) => {
3247 const checksumVerified = readToEnd(getCheckSum(passiveClone(readable)));
3248 checksumVerified.catch(() => {});
3249 await pipe(readable, writable, {
3250 preventClose: true
3251 });
3252 const writer = getWriter(writable);
3253 try {
3254 const checksumVerifiedString = (await checksumVerified).replace('\n', '');
3255 if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {
3256 throw new Error('Ascii armor integrity check failed');
3257 }
3258 await writer.ready;
3259 await writer.close();
3260 } catch (e) {
3261 await writer.abort(e);
3262 }
3263 });
3264 } catch (e) {
3265 reject(e);
3266 }
3267 }).then(async result => {
3268 if (isArrayStream(result.data)) {
3269 result.data = await readToEnd(result.data);
3270 }
3271 return result;
3272 });
3273}
3274
3275
3276/**
3277 * Armor an OpenPGP binary packet block
3278 * @param {module:enums.armor} messageType - Type of the message
3279 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
3280 * @param {Integer} [partIndex]
3281 * @param {Integer} [partTotal]
3282 * @param {String} [customComment] - Additional comment to add to the armored string
3283 * @returns {String | ReadableStream<String>} Armored text.
3284 * @static
3285 */
3286function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {
3287 let text;
3288 let hash;
3289 if (messageType === enums.armor.signed) {
3290 text = body.text;
3291 hash = body.hash;
3292 body = body.data;
3293 }
3294 const bodyClone = passiveClone(body);
3295 const result = [];
3296 switch (messageType) {
3297 case enums.armor.multipartSection:
3298 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3299 result.push(addheader(customComment, config));
3300 result.push(encode(body));
3301 result.push('=', getCheckSum(bodyClone));
3302 result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3303 break;
3304 case enums.armor.multipartLast:
3305 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n');
3306 result.push(addheader(customComment, config));
3307 result.push(encode(body));
3308 result.push('=', getCheckSum(bodyClone));
3309 result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n');
3310 break;
3311 case enums.armor.signed:
3312 result.push('-----BEGIN PGP SIGNED MESSAGE-----\n');
3313 result.push('Hash: ' + hash + '\n\n');
3314 result.push(text.replace(/^-/mg, '- -'));
3315 result.push('\n-----BEGIN PGP SIGNATURE-----\n');
3316 result.push(addheader(customComment, config));
3317 result.push(encode(body));
3318 result.push('=', getCheckSum(bodyClone));
3319 result.push('-----END PGP SIGNATURE-----\n');
3320 break;
3321 case enums.armor.message:
3322 result.push('-----BEGIN PGP MESSAGE-----\n');
3323 result.push(addheader(customComment, config));
3324 result.push(encode(body));
3325 result.push('=', getCheckSum(bodyClone));
3326 result.push('-----END PGP MESSAGE-----\n');
3327 break;
3328 case enums.armor.publicKey:
3329 result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n');
3330 result.push(addheader(customComment, config));
3331 result.push(encode(body));
3332 result.push('=', getCheckSum(bodyClone));
3333 result.push('-----END PGP PUBLIC KEY BLOCK-----\n');
3334 break;
3335 case enums.armor.privateKey:
3336 result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n');
3337 result.push(addheader(customComment, config));
3338 result.push(encode(body));
3339 result.push('=', getCheckSum(bodyClone));
3340 result.push('-----END PGP PRIVATE KEY BLOCK-----\n');
3341 break;
3342 case enums.armor.signature:
3343 result.push('-----BEGIN PGP SIGNATURE-----\n');
3344 result.push(addheader(customComment, config));
3345 result.push(encode(body));
3346 result.push('=', getCheckSum(bodyClone));
3347 result.push('-----END PGP SIGNATURE-----\n');
3348 break;
3349 }
3350
3351 return util.concat(result);
3352}
3353
3354// GPG4Browsers - An OpenPGP implementation in javascript
3355
3356/**
3357 * Implementation of type key id
3358 *
3359 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
3360 * A Key ID is an eight-octet scalar that identifies a key.
3361 * Implementations SHOULD NOT assume that Key IDs are unique. The
3362 * section "Enhanced Key Formats" below describes how Key IDs are
3363 * formed.
3364 */
3365class KeyID {
3366 constructor() {
3367 this.bytes = '';
3368 }
3369
3370 /**
3371 * Parsing method for a key id
3372 * @param {Uint8Array} bytes - Input to read the key id from
3373 */
3374 read(bytes) {
3375 this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));
3376 }
3377
3378 /**
3379 * Serializes the Key ID
3380 * @returns {Uint8Array} Key ID as a Uint8Array.
3381 */
3382 write() {
3383 return util.stringToUint8Array(this.bytes);
3384 }
3385
3386 /**
3387 * Returns the Key ID represented as a hexadecimal string
3388 * @returns {String} Key ID as a hexadecimal string.
3389 */
3390 toHex() {
3391 return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));
3392 }
3393
3394 /**
3395 * Checks equality of Key ID's
3396 * @param {KeyID} keyID
3397 * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard
3398 */
3399 equals(keyID, matchWildcard = false) {
3400 return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;
3401 }
3402
3403 /**
3404 * Checks to see if the Key ID is unset
3405 * @returns {Boolean} True if the Key ID is null.
3406 */
3407 isNull() {
3408 return this.bytes === '';
3409 }
3410
3411 /**
3412 * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
3413 * @returns {Boolean} True if this is a wildcard Key ID.
3414 */
3415 isWildcard() {
3416 return /^0+$/.test(this.toHex());
3417 }
3418
3419 static mapToHex(keyID) {
3420 return keyID.toHex();
3421 }
3422
3423 static fromID(hex) {
3424 const keyID = new KeyID();
3425 keyID.read(util.hexToUint8Array(hex));
3426 return keyID;
3427 }
3428
3429 static wildcard() {
3430 const keyID = new KeyID();
3431 keyID.read(new Uint8Array(8));
3432 return keyID;
3433 }
3434}
3435
3436/**
3437 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
3438 * @author Artem S Vybornov <vybornov@gmail.com>
3439 * @license MIT
3440 */
3441var AES_asm = function () {
3442
3443 /**
3444 * Galois Field stuff init flag
3445 */
3446 var ginit_done = false;
3447
3448 /**
3449 * Galois Field exponentiation and logarithm tables for 3 (the generator)
3450 */
3451 var gexp3, glog3;
3452
3453 /**
3454 * Init Galois Field tables
3455 */
3456 function ginit() {
3457 gexp3 = [],
3458 glog3 = [];
3459
3460 var a = 1, c, d;
3461 for (c = 0; c < 255; c++) {
3462 gexp3[c] = a;
3463
3464 // Multiply by three
3465 d = a & 0x80, a <<= 1, a &= 255;
3466 if (d === 0x80) a ^= 0x1b;
3467 a ^= gexp3[c];
3468
3469 // Set the log table value
3470 glog3[gexp3[c]] = c;
3471 }
3472 gexp3[255] = gexp3[0];
3473 glog3[0] = 0;
3474
3475 ginit_done = true;
3476 }
3477
3478 /**
3479 * Galois Field multiplication
3480 * @param {number} a
3481 * @param {number} b
3482 * @return {number}
3483 */
3484 function gmul(a, b) {
3485 var c = gexp3[(glog3[a] + glog3[b]) % 255];
3486 if (a === 0 || b === 0) c = 0;
3487 return c;
3488 }
3489
3490 /**
3491 * Galois Field reciprocal
3492 * @param {number} a
3493 * @return {number}
3494 */
3495 function ginv(a) {
3496 var i = gexp3[255 - glog3[a]];
3497 if (a === 0) i = 0;
3498 return i;
3499 }
3500
3501 /**
3502 * AES stuff init flag
3503 */
3504 var aes_init_done = false;
3505
3506 /**
3507 * Encryption, Decryption, S-Box and KeyTransform tables
3508 *
3509 * @type {number[]}
3510 */
3511 var aes_sbox;
3512
3513 /**
3514 * @type {number[]}
3515 */
3516 var aes_sinv;
3517
3518 /**
3519 * @type {number[][]}
3520 */
3521 var aes_enc;
3522
3523 /**
3524 * @type {number[][]}
3525 */
3526 var aes_dec;
3527
3528 /**
3529 * Init AES tables
3530 */
3531 function aes_init() {
3532 if (!ginit_done) ginit();
3533
3534 // Calculates AES S-Box value
3535 function _s(a) {
3536 var c, s, x;
3537 s = x = ginv(a);
3538 for (c = 0; c < 4; c++) {
3539 s = ((s << 1) | (s >>> 7)) & 255;
3540 x ^= s;
3541 }
3542 x ^= 99;
3543 return x;
3544 }
3545
3546 // Tables
3547 aes_sbox = [],
3548 aes_sinv = [],
3549 aes_enc = [[], [], [], []],
3550 aes_dec = [[], [], [], []];
3551
3552 for (var i = 0; i < 256; i++) {
3553 var s = _s(i);
3554
3555 // S-Box and its inverse
3556 aes_sbox[i] = s;
3557 aes_sinv[s] = i;
3558
3559 // Ecryption and Decryption tables
3560 aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);
3561 aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);
3562 // Rotate tables
3563 for (var t = 1; t < 4; t++) {
3564 aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);
3565 aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);
3566 }
3567 }
3568
3569 aes_init_done = true;
3570 }
3571
3572 /**
3573 * Asm.js module constructor.
3574 *
3575 * <p>
3576 * Heap buffer layout by offset:
3577 * <pre>
3578 * 0x0000 encryption key schedule
3579 * 0x0400 decryption key schedule
3580 * 0x0800 sbox
3581 * 0x0c00 inv sbox
3582 * 0x1000 encryption tables
3583 * 0x2000 decryption tables
3584 * 0x3000 reserved (future GCM multiplication lookup table)
3585 * 0x4000 data
3586 * </pre>
3587 * Don't touch anything before <code>0x400</code>.
3588 * </p>
3589 *
3590 * @alias AES_asm
3591 * @class
3592 * @param foreign - <i>ignored</i>
3593 * @param buffer - heap buffer to link with
3594 */
3595 var wrapper = function (foreign, buffer) {
3596 // Init AES stuff for the first time
3597 if (!aes_init_done) aes_init();
3598
3599 // Fill up AES tables
3600 var heap = new Uint32Array(buffer);
3601 heap.set(aes_sbox, 0x0800 >> 2);
3602 heap.set(aes_sinv, 0x0c00 >> 2);
3603 for (var i = 0; i < 4; i++) {
3604 heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);
3605 heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);
3606 }
3607
3608 /**
3609 * Calculate AES key schedules.
3610 * @instance
3611 * @memberof AES_asm
3612 * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
3613 * @param {number} k0 - key vector components
3614 * @param {number} k1 - key vector components
3615 * @param {number} k2 - key vector components
3616 * @param {number} k3 - key vector components
3617 * @param {number} k4 - key vector components
3618 * @param {number} k5 - key vector components
3619 * @param {number} k6 - key vector components
3620 * @param {number} k7 - key vector components
3621 */
3622 function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
3623 var ekeys = heap.subarray(0x000, 60),
3624 dkeys = heap.subarray(0x100, 0x100 + 60);
3625
3626 // Encryption key schedule
3627 ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
3628 for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
3629 var k = ekeys[i - 1];
3630 if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {
3631 k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
3632 }
3633 if (i % ks === 0) {
3634 k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
3635 rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);
3636 }
3637 ekeys[i] = ekeys[i - ks] ^ k;
3638 }
3639
3640 // Decryption key schedule
3641 for (var j = 0; j < i; j += 4) {
3642 for (var jj = 0; jj < 4; jj++) {
3643 var k = ekeys[i - (4 + j) + (4 - jj) % 4];
3644 if (j < 4 || j >= i - 4) {
3645 dkeys[j + jj] = k;
3646 } else {
3647 dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]
3648 ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]
3649 ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]
3650 ^ aes_dec[3][aes_sbox[k & 255]];
3651 }
3652 }
3653 }
3654
3655 // Set rounds number
3656 asm.set_rounds(ks + 5);
3657 }
3658
3659 // create library object with necessary properties
3660 var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};
3661
3662 var asm = function (stdlib, foreign, buffer) {
3663 "use asm";
3664
3665 var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
3666 I0 = 0, I1 = 0, I2 = 0, I3 = 0,
3667 N0 = 0, N1 = 0, N2 = 0, N3 = 0,
3668 M0 = 0, M1 = 0, M2 = 0, M3 = 0,
3669 H0 = 0, H1 = 0, H2 = 0, H3 = 0,
3670 R = 0;
3671
3672 var HEAP = new stdlib.Uint32Array(buffer),
3673 DATA = new stdlib.Uint8Array(buffer);
3674
3675 /**
3676 * AES core
3677 * @param {number} k - precomputed key schedule offset
3678 * @param {number} s - precomputed sbox table offset
3679 * @param {number} t - precomputed round table offset
3680 * @param {number} r - number of inner rounds to perform
3681 * @param {number} x0 - 128-bit input block vector
3682 * @param {number} x1 - 128-bit input block vector
3683 * @param {number} x2 - 128-bit input block vector
3684 * @param {number} x3 - 128-bit input block vector
3685 */
3686 function _core(k, s, t, r, x0, x1, x2, x3) {
3687 k = k | 0;
3688 s = s | 0;
3689 t = t | 0;
3690 r = r | 0;
3691 x0 = x0 | 0;
3692 x1 = x1 | 0;
3693 x2 = x2 | 0;
3694 x3 = x3 | 0;
3695
3696 var t1 = 0, t2 = 0, t3 = 0,
3697 y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3698 i = 0;
3699
3700 t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
3701
3702 // round 0
3703 x0 = x0 ^ HEAP[(k | 0) >> 2],
3704 x1 = x1 ^ HEAP[(k | 4) >> 2],
3705 x2 = x2 ^ HEAP[(k | 8) >> 2],
3706 x3 = x3 ^ HEAP[(k | 12) >> 2];
3707
3708 // round 1..r
3709 for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {
3710 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],
3711 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],
3712 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],
3713 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];
3714 x0 = y0, x1 = y1, x2 = y2, x3 = y3;
3715 }
3716
3717 // final round
3718 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],
3719 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],
3720 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],
3721 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];
3722 }
3723
3724 /**
3725 * ECB mode encryption
3726 * @param {number} x0 - 128-bit input block vector
3727 * @param {number} x1 - 128-bit input block vector
3728 * @param {number} x2 - 128-bit input block vector
3729 * @param {number} x3 - 128-bit input block vector
3730 */
3731 function _ecb_enc(x0, x1, x2, x3) {
3732 x0 = x0 | 0;
3733 x1 = x1 | 0;
3734 x2 = x2 | 0;
3735 x3 = x3 | 0;
3736
3737 _core(
3738 0x0000, 0x0800, 0x1000,
3739 R,
3740 x0,
3741 x1,
3742 x2,
3743 x3
3744 );
3745 }
3746
3747 /**
3748 * ECB mode decryption
3749 * @param {number} x0 - 128-bit input block vector
3750 * @param {number} x1 - 128-bit input block vector
3751 * @param {number} x2 - 128-bit input block vector
3752 * @param {number} x3 - 128-bit input block vector
3753 */
3754 function _ecb_dec(x0, x1, x2, x3) {
3755 x0 = x0 | 0;
3756 x1 = x1 | 0;
3757 x2 = x2 | 0;
3758 x3 = x3 | 0;
3759
3760 var t = 0;
3761
3762 _core(
3763 0x0400, 0x0c00, 0x2000,
3764 R,
3765 x0,
3766 x3,
3767 x2,
3768 x1
3769 );
3770
3771 t = S1, S1 = S3, S3 = t;
3772 }
3773
3774
3775 /**
3776 * CBC mode encryption
3777 * @param {number} x0 - 128-bit input block vector
3778 * @param {number} x1 - 128-bit input block vector
3779 * @param {number} x2 - 128-bit input block vector
3780 * @param {number} x3 - 128-bit input block vector
3781 */
3782 function _cbc_enc(x0, x1, x2, x3) {
3783 x0 = x0 | 0;
3784 x1 = x1 | 0;
3785 x2 = x2 | 0;
3786 x3 = x3 | 0;
3787
3788 _core(
3789 0x0000, 0x0800, 0x1000,
3790 R,
3791 I0 ^ x0,
3792 I1 ^ x1,
3793 I2 ^ x2,
3794 I3 ^ x3
3795 );
3796
3797 I0 = S0,
3798 I1 = S1,
3799 I2 = S2,
3800 I3 = S3;
3801 }
3802
3803 /**
3804 * CBC mode decryption
3805 * @param {number} x0 - 128-bit input block vector
3806 * @param {number} x1 - 128-bit input block vector
3807 * @param {number} x2 - 128-bit input block vector
3808 * @param {number} x3 - 128-bit input block vector
3809 */
3810 function _cbc_dec(x0, x1, x2, x3) {
3811 x0 = x0 | 0;
3812 x1 = x1 | 0;
3813 x2 = x2 | 0;
3814 x3 = x3 | 0;
3815
3816 var t = 0;
3817
3818 _core(
3819 0x0400, 0x0c00, 0x2000,
3820 R,
3821 x0,
3822 x3,
3823 x2,
3824 x1
3825 );
3826
3827 t = S1, S1 = S3, S3 = t;
3828
3829 S0 = S0 ^ I0,
3830 S1 = S1 ^ I1,
3831 S2 = S2 ^ I2,
3832 S3 = S3 ^ I3;
3833
3834 I0 = x0,
3835 I1 = x1,
3836 I2 = x2,
3837 I3 = x3;
3838 }
3839
3840 /**
3841 * CFB mode encryption
3842 * @param {number} x0 - 128-bit input block vector
3843 * @param {number} x1 - 128-bit input block vector
3844 * @param {number} x2 - 128-bit input block vector
3845 * @param {number} x3 - 128-bit input block vector
3846 */
3847 function _cfb_enc(x0, x1, x2, x3) {
3848 x0 = x0 | 0;
3849 x1 = x1 | 0;
3850 x2 = x2 | 0;
3851 x3 = x3 | 0;
3852
3853 _core(
3854 0x0000, 0x0800, 0x1000,
3855 R,
3856 I0,
3857 I1,
3858 I2,
3859 I3
3860 );
3861
3862 I0 = S0 = S0 ^ x0,
3863 I1 = S1 = S1 ^ x1,
3864 I2 = S2 = S2 ^ x2,
3865 I3 = S3 = S3 ^ x3;
3866 }
3867
3868
3869 /**
3870 * CFB mode decryption
3871 * @param {number} x0 - 128-bit input block vector
3872 * @param {number} x1 - 128-bit input block vector
3873 * @param {number} x2 - 128-bit input block vector
3874 * @param {number} x3 - 128-bit input block vector
3875 */
3876 function _cfb_dec(x0, x1, x2, x3) {
3877 x0 = x0 | 0;
3878 x1 = x1 | 0;
3879 x2 = x2 | 0;
3880 x3 = x3 | 0;
3881
3882 _core(
3883 0x0000, 0x0800, 0x1000,
3884 R,
3885 I0,
3886 I1,
3887 I2,
3888 I3
3889 );
3890
3891 S0 = S0 ^ x0,
3892 S1 = S1 ^ x1,
3893 S2 = S2 ^ x2,
3894 S3 = S3 ^ x3;
3895
3896 I0 = x0,
3897 I1 = x1,
3898 I2 = x2,
3899 I3 = x3;
3900 }
3901
3902 /**
3903 * OFB mode encryption / decryption
3904 * @param {number} x0 - 128-bit input block vector
3905 * @param {number} x1 - 128-bit input block vector
3906 * @param {number} x2 - 128-bit input block vector
3907 * @param {number} x3 - 128-bit input block vector
3908 */
3909 function _ofb(x0, x1, x2, x3) {
3910 x0 = x0 | 0;
3911 x1 = x1 | 0;
3912 x2 = x2 | 0;
3913 x3 = x3 | 0;
3914
3915 _core(
3916 0x0000, 0x0800, 0x1000,
3917 R,
3918 I0,
3919 I1,
3920 I2,
3921 I3
3922 );
3923
3924 I0 = S0,
3925 I1 = S1,
3926 I2 = S2,
3927 I3 = S3;
3928
3929 S0 = S0 ^ x0,
3930 S1 = S1 ^ x1,
3931 S2 = S2 ^ x2,
3932 S3 = S3 ^ x3;
3933 }
3934
3935 /**
3936 * CTR mode encryption / decryption
3937 * @param {number} x0 - 128-bit input block vector
3938 * @param {number} x1 - 128-bit input block vector
3939 * @param {number} x2 - 128-bit input block vector
3940 * @param {number} x3 - 128-bit input block vector
3941 */
3942 function _ctr(x0, x1, x2, x3) {
3943 x0 = x0 | 0;
3944 x1 = x1 | 0;
3945 x2 = x2 | 0;
3946 x3 = x3 | 0;
3947
3948 _core(
3949 0x0000, 0x0800, 0x1000,
3950 R,
3951 N0,
3952 N1,
3953 N2,
3954 N3
3955 );
3956
3957 N3 = (~M3 & N3) | M3 & (N3 + 1);
3958 N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));
3959 N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));
3960 N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));
3961
3962 S0 = S0 ^ x0;
3963 S1 = S1 ^ x1;
3964 S2 = S2 ^ x2;
3965 S3 = S3 ^ x3;
3966 }
3967
3968 /**
3969 * GCM mode MAC calculation
3970 * @param {number} x0 - 128-bit input block vector
3971 * @param {number} x1 - 128-bit input block vector
3972 * @param {number} x2 - 128-bit input block vector
3973 * @param {number} x3 - 128-bit input block vector
3974 */
3975 function _gcm_mac(x0, x1, x2, x3) {
3976 x0 = x0 | 0;
3977 x1 = x1 | 0;
3978 x2 = x2 | 0;
3979 x3 = x3 | 0;
3980
3981 var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3982 z0 = 0, z1 = 0, z2 = 0, z3 = 0,
3983 i = 0, c = 0;
3984
3985 x0 = x0 ^ I0,
3986 x1 = x1 ^ I1,
3987 x2 = x2 ^ I2,
3988 x3 = x3 ^ I3;
3989
3990 y0 = H0 | 0,
3991 y1 = H1 | 0,
3992 y2 = H2 | 0,
3993 y3 = H3 | 0;
3994
3995 for (; (i | 0) < 128; i = (i + 1) | 0) {
3996 if (y0 >>> 31) {
3997 z0 = z0 ^ x0,
3998 z1 = z1 ^ x1,
3999 z2 = z2 ^ x2,
4000 z3 = z3 ^ x3;
4001 }
4002
4003 y0 = (y0 << 1) | (y1 >>> 31),
4004 y1 = (y1 << 1) | (y2 >>> 31),
4005 y2 = (y2 << 1) | (y3 >>> 31),
4006 y3 = (y3 << 1);
4007
4008 c = x3 & 1;
4009
4010 x3 = (x3 >>> 1) | (x2 << 31),
4011 x2 = (x2 >>> 1) | (x1 << 31),
4012 x1 = (x1 >>> 1) | (x0 << 31),
4013 x0 = (x0 >>> 1);
4014
4015 if (c) x0 = x0 ^ 0xe1000000;
4016 }
4017
4018 I0 = z0,
4019 I1 = z1,
4020 I2 = z2,
4021 I3 = z3;
4022 }
4023
4024 /**
4025 * Set the internal rounds number.
4026 * @instance
4027 * @memberof AES_asm
4028 * @param {number} r - number if inner AES rounds
4029 */
4030 function set_rounds(r) {
4031 r = r | 0;
4032 R = r;
4033 }
4034
4035 /**
4036 * Populate the internal state of the module.
4037 * @instance
4038 * @memberof AES_asm
4039 * @param {number} s0 - state vector
4040 * @param {number} s1 - state vector
4041 * @param {number} s2 - state vector
4042 * @param {number} s3 - state vector
4043 */
4044 function set_state(s0, s1, s2, s3) {
4045 s0 = s0 | 0;
4046 s1 = s1 | 0;
4047 s2 = s2 | 0;
4048 s3 = s3 | 0;
4049
4050 S0 = s0,
4051 S1 = s1,
4052 S2 = s2,
4053 S3 = s3;
4054 }
4055
4056 /**
4057 * Populate the internal iv of the module.
4058 * @instance
4059 * @memberof AES_asm
4060 * @param {number} i0 - iv vector
4061 * @param {number} i1 - iv vector
4062 * @param {number} i2 - iv vector
4063 * @param {number} i3 - iv vector
4064 */
4065 function set_iv(i0, i1, i2, i3) {
4066 i0 = i0 | 0;
4067 i1 = i1 | 0;
4068 i2 = i2 | 0;
4069 i3 = i3 | 0;
4070
4071 I0 = i0,
4072 I1 = i1,
4073 I2 = i2,
4074 I3 = i3;
4075 }
4076
4077 /**
4078 * Set nonce for CTR-family modes.
4079 * @instance
4080 * @memberof AES_asm
4081 * @param {number} n0 - nonce vector
4082 * @param {number} n1 - nonce vector
4083 * @param {number} n2 - nonce vector
4084 * @param {number} n3 - nonce vector
4085 */
4086 function set_nonce(n0, n1, n2, n3) {
4087 n0 = n0 | 0;
4088 n1 = n1 | 0;
4089 n2 = n2 | 0;
4090 n3 = n3 | 0;
4091
4092 N0 = n0,
4093 N1 = n1,
4094 N2 = n2,
4095 N3 = n3;
4096 }
4097
4098 /**
4099 * Set counter mask for CTR-family modes.
4100 * @instance
4101 * @memberof AES_asm
4102 * @param {number} m0 - counter mask vector
4103 * @param {number} m1 - counter mask vector
4104 * @param {number} m2 - counter mask vector
4105 * @param {number} m3 - counter mask vector
4106 */
4107 function set_mask(m0, m1, m2, m3) {
4108 m0 = m0 | 0;
4109 m1 = m1 | 0;
4110 m2 = m2 | 0;
4111 m3 = m3 | 0;
4112
4113 M0 = m0,
4114 M1 = m1,
4115 M2 = m2,
4116 M3 = m3;
4117 }
4118
4119 /**
4120 * Set counter for CTR-family modes.
4121 * @instance
4122 * @memberof AES_asm
4123 * @param {number} c0 - counter vector
4124 * @param {number} c1 - counter vector
4125 * @param {number} c2 - counter vector
4126 * @param {number} c3 - counter vector
4127 */
4128 function set_counter(c0, c1, c2, c3) {
4129 c0 = c0 | 0;
4130 c1 = c1 | 0;
4131 c2 = c2 | 0;
4132 c3 = c3 | 0;
4133
4134 N3 = (~M3 & N3) | M3 & c3,
4135 N2 = (~M2 & N2) | M2 & c2,
4136 N1 = (~M1 & N1) | M1 & c1,
4137 N0 = (~M0 & N0) | M0 & c0;
4138 }
4139
4140 /**
4141 * Store the internal state vector into the heap.
4142 * @instance
4143 * @memberof AES_asm
4144 * @param {number} pos - offset where to put the data
4145 * @return {number} The number of bytes have been written into the heap, always 16.
4146 */
4147 function get_state(pos) {
4148 pos = pos | 0;
4149
4150 if (pos & 15) return -1;
4151
4152 DATA[pos | 0] = S0 >>> 24,
4153 DATA[pos | 1] = S0 >>> 16 & 255,
4154 DATA[pos | 2] = S0 >>> 8 & 255,
4155 DATA[pos | 3] = S0 & 255,
4156 DATA[pos | 4] = S1 >>> 24,
4157 DATA[pos | 5] = S1 >>> 16 & 255,
4158 DATA[pos | 6] = S1 >>> 8 & 255,
4159 DATA[pos | 7] = S1 & 255,
4160 DATA[pos | 8] = S2 >>> 24,
4161 DATA[pos | 9] = S2 >>> 16 & 255,
4162 DATA[pos | 10] = S2 >>> 8 & 255,
4163 DATA[pos | 11] = S2 & 255,
4164 DATA[pos | 12] = S3 >>> 24,
4165 DATA[pos | 13] = S3 >>> 16 & 255,
4166 DATA[pos | 14] = S3 >>> 8 & 255,
4167 DATA[pos | 15] = S3 & 255;
4168
4169 return 16;
4170 }
4171
4172 /**
4173 * Store the internal iv vector into the heap.
4174 * @instance
4175 * @memberof AES_asm
4176 * @param {number} pos - offset where to put the data
4177 * @return {number} The number of bytes have been written into the heap, always 16.
4178 */
4179 function get_iv(pos) {
4180 pos = pos | 0;
4181
4182 if (pos & 15) return -1;
4183
4184 DATA[pos | 0] = I0 >>> 24,
4185 DATA[pos | 1] = I0 >>> 16 & 255,
4186 DATA[pos | 2] = I0 >>> 8 & 255,
4187 DATA[pos | 3] = I0 & 255,
4188 DATA[pos | 4] = I1 >>> 24,
4189 DATA[pos | 5] = I1 >>> 16 & 255,
4190 DATA[pos | 6] = I1 >>> 8 & 255,
4191 DATA[pos | 7] = I1 & 255,
4192 DATA[pos | 8] = I2 >>> 24,
4193 DATA[pos | 9] = I2 >>> 16 & 255,
4194 DATA[pos | 10] = I2 >>> 8 & 255,
4195 DATA[pos | 11] = I2 & 255,
4196 DATA[pos | 12] = I3 >>> 24,
4197 DATA[pos | 13] = I3 >>> 16 & 255,
4198 DATA[pos | 14] = I3 >>> 8 & 255,
4199 DATA[pos | 15] = I3 & 255;
4200
4201 return 16;
4202 }
4203
4204 /**
4205 * GCM initialization.
4206 * @instance
4207 * @memberof AES_asm
4208 */
4209 function gcm_init() {
4210 _ecb_enc(0, 0, 0, 0);
4211 H0 = S0,
4212 H1 = S1,
4213 H2 = S2,
4214 H3 = S3;
4215 }
4216
4217 /**
4218 * Perform ciphering operation on the supplied data.
4219 * @instance
4220 * @memberof AES_asm
4221 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4222 * @param {number} pos - offset of the data being processed
4223 * @param {number} len - length of the data being processed
4224 * @return {number} Actual amount of data have been processed.
4225 */
4226 function cipher(mode, pos, len) {
4227 mode = mode | 0;
4228 pos = pos | 0;
4229 len = len | 0;
4230
4231 var ret = 0;
4232
4233 if (pos & 15) return -1;
4234
4235 while ((len | 0) >= 16) {
4236 _cipher_modes[mode & 7](
4237 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4238 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4239 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4240 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4241 );
4242
4243 DATA[pos | 0] = S0 >>> 24,
4244 DATA[pos | 1] = S0 >>> 16 & 255,
4245 DATA[pos | 2] = S0 >>> 8 & 255,
4246 DATA[pos | 3] = S0 & 255,
4247 DATA[pos | 4] = S1 >>> 24,
4248 DATA[pos | 5] = S1 >>> 16 & 255,
4249 DATA[pos | 6] = S1 >>> 8 & 255,
4250 DATA[pos | 7] = S1 & 255,
4251 DATA[pos | 8] = S2 >>> 24,
4252 DATA[pos | 9] = S2 >>> 16 & 255,
4253 DATA[pos | 10] = S2 >>> 8 & 255,
4254 DATA[pos | 11] = S2 & 255,
4255 DATA[pos | 12] = S3 >>> 24,
4256 DATA[pos | 13] = S3 >>> 16 & 255,
4257 DATA[pos | 14] = S3 >>> 8 & 255,
4258 DATA[pos | 15] = S3 & 255;
4259
4260 ret = (ret + 16) | 0,
4261 pos = (pos + 16) | 0,
4262 len = (len - 16) | 0;
4263 }
4264
4265 return ret | 0;
4266 }
4267
4268 /**
4269 * Calculates MAC of the supplied data.
4270 * @instance
4271 * @memberof AES_asm
4272 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4273 * @param {number} pos - offset of the data being processed
4274 * @param {number} len - length of the data being processed
4275 * @return {number} Actual amount of data have been processed.
4276 */
4277 function mac(mode, pos, len) {
4278 mode = mode | 0;
4279 pos = pos | 0;
4280 len = len | 0;
4281
4282 var ret = 0;
4283
4284 if (pos & 15) return -1;
4285
4286 while ((len | 0) >= 16) {
4287 _mac_modes[mode & 1](
4288 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4289 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4290 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4291 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4292 );
4293
4294 ret = (ret + 16) | 0,
4295 pos = (pos + 16) | 0,
4296 len = (len - 16) | 0;
4297 }
4298
4299 return ret | 0;
4300 }
4301
4302 /**
4303 * AES cipher modes table (virual methods)
4304 */
4305 var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
4306
4307 /**
4308 * AES MAC modes table (virual methods)
4309 */
4310 var _mac_modes = [_cbc_enc, _gcm_mac];
4311
4312 /**
4313 * Asm.js module exports
4314 */
4315 return {
4316 set_rounds: set_rounds,
4317 set_state: set_state,
4318 set_iv: set_iv,
4319 set_nonce: set_nonce,
4320 set_mask: set_mask,
4321 set_counter: set_counter,
4322 get_state: get_state,
4323 get_iv: get_iv,
4324 gcm_init: gcm_init,
4325 cipher: cipher,
4326 mac: mac,
4327 };
4328 }(stdlib, foreign, buffer);
4329
4330 asm.set_key = set_key;
4331
4332 return asm;
4333 };
4334
4335 /**
4336 * AES enciphering mode constants
4337 * @enum {number}
4338 * @const
4339 */
4340 wrapper.ENC = {
4341 ECB: 0,
4342 CBC: 2,
4343 CFB: 4,
4344 OFB: 6,
4345 CTR: 7,
4346 },
4347
4348 /**
4349 * AES deciphering mode constants
4350 * @enum {number}
4351 * @const
4352 */
4353 wrapper.DEC = {
4354 ECB: 1,
4355 CBC: 3,
4356 CFB: 5,
4357 OFB: 6,
4358 CTR: 7,
4359 },
4360
4361 /**
4362 * AES MAC mode constants
4363 * @enum {number}
4364 * @const
4365 */
4366 wrapper.MAC = {
4367 CBC: 0,
4368 GCM: 1,
4369 };
4370
4371 /**
4372 * Heap data offset
4373 * @type {number}
4374 * @const
4375 */
4376 wrapper.HEAP_DATA = 0x4000;
4377
4378 return wrapper;
4379}();
4380
4381function is_bytes(a) {
4382 return a instanceof Uint8Array;
4383}
4384function _heap_init(heap, heapSize) {
4385 const size = heap ? heap.byteLength : heapSize || 65536;
4386 if (size & 0xfff || size <= 0)
4387 throw new Error('heap size must be a positive integer and a multiple of 4096');
4388 heap = heap || new Uint8Array(new ArrayBuffer(size));
4389 return heap;
4390}
4391function _heap_write(heap, hpos, data, dpos, dlen) {
4392 const hlen = heap.length - hpos;
4393 const wlen = hlen < dlen ? hlen : dlen;
4394 heap.set(data.subarray(dpos, dpos + wlen), hpos);
4395 return wlen;
4396}
4397function joinBytes(...arg) {
4398 const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);
4399 const ret = new Uint8Array(totalLenght);
4400 let cursor = 0;
4401 for (let i = 0; i < arg.length; i++) {
4402 ret.set(arg[i], cursor);
4403 cursor += arg[i].length;
4404 }
4405 return ret;
4406}
4407
4408class IllegalStateError extends Error {
4409 constructor(...args) {
4410 super(...args);
4411 }
4412}
4413class IllegalArgumentError extends Error {
4414 constructor(...args) {
4415 super(...args);
4416 }
4417}
4418class SecurityError extends Error {
4419 constructor(...args) {
4420 super(...args);
4421 }
4422}
4423
4424const heap_pool = [];
4425const asm_pool = [];
4426class AES {
4427 constructor(key, iv, padding = true, mode, heap, asm) {
4428 this.pos = 0;
4429 this.len = 0;
4430 this.mode = mode;
4431 // The AES object state
4432 this.pos = 0;
4433 this.len = 0;
4434 this.key = key;
4435 this.iv = iv;
4436 this.padding = padding;
4437 // The AES "worker"
4438 this.acquire_asm(heap, asm);
4439 }
4440 acquire_asm(heap, asm) {
4441 if (this.heap === undefined || this.asm === undefined) {
4442 this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);
4443 this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);
4444 this.reset(this.key, this.iv);
4445 }
4446 return { heap: this.heap, asm: this.asm };
4447 }
4448 release_asm() {
4449 if (this.heap !== undefined && this.asm !== undefined) {
4450 heap_pool.push(this.heap);
4451 asm_pool.push(this.asm);
4452 }
4453 this.heap = undefined;
4454 this.asm = undefined;
4455 }
4456 reset(key, iv) {
4457 const { asm } = this.acquire_asm();
4458 // Key
4459 const keylen = key.length;
4460 if (keylen !== 16 && keylen !== 24 && keylen !== 32)
4461 throw new IllegalArgumentError('illegal key size');
4462 const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
4463 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);
4464 // IV
4465 if (iv !== undefined) {
4466 if (iv.length !== 16)
4467 throw new IllegalArgumentError('illegal iv size');
4468 let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
4469 asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
4470 }
4471 else {
4472 asm.set_iv(0, 0, 0, 0);
4473 }
4474 }
4475 AES_Encrypt_process(data) {
4476 if (!is_bytes(data))
4477 throw new TypeError("data isn't of expected type");
4478 let { heap, asm } = this.acquire_asm();
4479 let amode = AES_asm.ENC[this.mode];
4480 let hpos = AES_asm.HEAP_DATA;
4481 let pos = this.pos;
4482 let len = this.len;
4483 let dpos = 0;
4484 let dlen = data.length || 0;
4485 let rpos = 0;
4486 let rlen = (len + dlen) & -16;
4487 let wlen = 0;
4488 let result = new Uint8Array(rlen);
4489 while (dlen > 0) {
4490 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4491 len += wlen;
4492 dpos += wlen;
4493 dlen -= wlen;
4494 wlen = asm.cipher(amode, hpos + pos, len);
4495 if (wlen)
4496 result.set(heap.subarray(pos, pos + wlen), rpos);
4497 rpos += wlen;
4498 if (wlen < len) {
4499 pos += wlen;
4500 len -= wlen;
4501 }
4502 else {
4503 pos = 0;
4504 len = 0;
4505 }
4506 }
4507 this.pos = pos;
4508 this.len = len;
4509 return result;
4510 }
4511 AES_Encrypt_finish() {
4512 let { heap, asm } = this.acquire_asm();
4513 let amode = AES_asm.ENC[this.mode];
4514 let hpos = AES_asm.HEAP_DATA;
4515 let pos = this.pos;
4516 let len = this.len;
4517 let plen = 16 - (len % 16);
4518 let rlen = len;
4519 if (this.hasOwnProperty('padding')) {
4520 if (this.padding) {
4521 for (let p = 0; p < plen; ++p) {
4522 heap[pos + len + p] = plen;
4523 }
4524 len += plen;
4525 rlen = len;
4526 }
4527 else if (len % 16) {
4528 throw new IllegalArgumentError('data length must be a multiple of the block size');
4529 }
4530 }
4531 else {
4532 len += plen;
4533 }
4534 const result = new Uint8Array(rlen);
4535 if (len)
4536 asm.cipher(amode, hpos + pos, len);
4537 if (rlen)
4538 result.set(heap.subarray(pos, pos + rlen));
4539 this.pos = 0;
4540 this.len = 0;
4541 this.release_asm();
4542 return result;
4543 }
4544 AES_Decrypt_process(data) {
4545 if (!is_bytes(data))
4546 throw new TypeError("data isn't of expected type");
4547 let { heap, asm } = this.acquire_asm();
4548 let amode = AES_asm.DEC[this.mode];
4549 let hpos = AES_asm.HEAP_DATA;
4550 let pos = this.pos;
4551 let len = this.len;
4552 let dpos = 0;
4553 let dlen = data.length || 0;
4554 let rpos = 0;
4555 let rlen = (len + dlen) & -16;
4556 let plen = 0;
4557 let wlen = 0;
4558 if (this.padding) {
4559 plen = len + dlen - rlen || 16;
4560 rlen -= plen;
4561 }
4562 const result = new Uint8Array(rlen);
4563 while (dlen > 0) {
4564 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4565 len += wlen;
4566 dpos += wlen;
4567 dlen -= wlen;
4568 wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
4569 if (wlen)
4570 result.set(heap.subarray(pos, pos + wlen), rpos);
4571 rpos += wlen;
4572 if (wlen < len) {
4573 pos += wlen;
4574 len -= wlen;
4575 }
4576 else {
4577 pos = 0;
4578 len = 0;
4579 }
4580 }
4581 this.pos = pos;
4582 this.len = len;
4583 return result;
4584 }
4585 AES_Decrypt_finish() {
4586 let { heap, asm } = this.acquire_asm();
4587 let amode = AES_asm.DEC[this.mode];
4588 let hpos = AES_asm.HEAP_DATA;
4589 let pos = this.pos;
4590 let len = this.len;
4591 let rlen = len;
4592 if (len > 0) {
4593 if (len % 16) {
4594 if (this.hasOwnProperty('padding')) {
4595 throw new IllegalArgumentError('data length must be a multiple of the block size');
4596 }
4597 else {
4598 len += 16 - (len % 16);
4599 }
4600 }
4601 asm.cipher(amode, hpos + pos, len);
4602 if (this.hasOwnProperty('padding') && this.padding) {
4603 let pad = heap[pos + rlen - 1];
4604 if (pad < 1 || pad > 16 || pad > rlen)
4605 throw new SecurityError('bad padding');
4606 let pcheck = 0;
4607 for (let i = pad; i > 1; i--)
4608 pcheck |= pad ^ heap[pos + rlen - i];
4609 if (pcheck)
4610 throw new SecurityError('bad padding');
4611 rlen -= pad;
4612 }
4613 }
4614 const result = new Uint8Array(rlen);
4615 if (rlen > 0) {
4616 result.set(heap.subarray(pos, pos + rlen));
4617 }
4618 this.pos = 0;
4619 this.len = 0;
4620 this.release_asm();
4621 return result;
4622 }
4623}
4624
4625class AES_ECB {
4626 static encrypt(data, key, padding = false) {
4627 return new AES_ECB(key, padding).encrypt(data);
4628 }
4629 static decrypt(data, key, padding = false) {
4630 return new AES_ECB(key, padding).decrypt(data);
4631 }
4632 constructor(key, padding = false, aes) {
4633 this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');
4634 }
4635 encrypt(data) {
4636 const r1 = this.aes.AES_Encrypt_process(data);
4637 const r2 = this.aes.AES_Encrypt_finish();
4638 return joinBytes(r1, r2);
4639 }
4640 decrypt(data) {
4641 const r1 = this.aes.AES_Decrypt_process(data);
4642 const r2 = this.aes.AES_Decrypt_finish();
4643 return joinBytes(r1, r2);
4644 }
4645}
4646
4647/**
4648 * Javascript AES implementation.
4649 * This is used as fallback if the native Crypto APIs are not available.
4650 */
4651function aes(length) {
4652 const C = function(key) {
4653 const aesECB = new AES_ECB(key);
4654
4655 this.encrypt = function(block) {
4656 return aesECB.encrypt(block);
4657 };
4658
4659 this.decrypt = function(block) {
4660 return aesECB.decrypt(block);
4661 };
4662 };
4663
4664 C.blockSize = C.prototype.blockSize = 16;
4665 C.keySize = C.prototype.keySize = length / 8;
4666
4667 return C;
4668}
4669
4670//Paul Tero, July 2001
4671//http://www.tero.co.uk/des/
4672//
4673//Optimised for performance with large blocks by Michael Hayworth, November 2001
4674//http://www.netdealing.com
4675//
4676// Modified by Recurity Labs GmbH
4677
4678//THIS SOFTWARE IS PROVIDED "AS IS" AND
4679//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4680//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4681//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4682//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4683//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4684//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4685//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4686//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4687//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4688//SUCH DAMAGE.
4689
4690//des
4691//this takes the key, the message, and whether to encrypt or decrypt
4692
4693function des(keys, message, encrypt, mode, iv, padding) {
4694 //declaring this locally speeds things up a bit
4695 const spfunction1 = [
4696 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
4697 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
4698 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
4699 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
4700 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
4701 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
4702 ];
4703 const spfunction2 = [
4704 -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,
4705 -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,
4706 -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,
4707 -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,
4708 -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,
4709 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,
4710 -0x7fef7fe0, 0x108000
4711 ];
4712 const spfunction3 = [
4713 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
4714 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
4715 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
4716 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
4717 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
4718 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
4719 ];
4720 const spfunction4 = [
4721 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
4722 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
4723 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
4724 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
4725 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
4726 ];
4727 const spfunction5 = [
4728 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
4729 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
4730 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
4731 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
4732 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
4733 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
4734 0x40080000, 0x2080100, 0x40000100
4735 ];
4736 const spfunction6 = [
4737 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
4738 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
4739 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
4740 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
4741 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
4742 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
4743 ];
4744 const spfunction7 = [
4745 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
4746 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
4747 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
4748 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
4749 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
4750 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
4751 ];
4752 const spfunction8 = [
4753 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
4754 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
4755 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
4756 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
4757 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
4758 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
4759 ];
4760
4761 //create the 16 or 48 subkeys we will need
4762 let m = 0;
4763 let i;
4764 let j;
4765 let temp;
4766 let right1;
4767 let right2;
4768 let left;
4769 let right;
4770 let looping;
4771 let cbcleft;
4772 let cbcleft2;
4773 let cbcright;
4774 let cbcright2;
4775 let endloop;
4776 let loopinc;
4777 let len = message.length;
4778
4779 //set up the loops for single and triple des
4780 const iterations = keys.length === 32 ? 3 : 9; //single or triple des
4781 if (iterations === 3) {
4782 looping = encrypt ? [0, 32, 2] : [30, -2, -2];
4783 } else {
4784 looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
4785 }
4786
4787 //pad the message depending on the padding parameter
4788 //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
4789 if (encrypt) {
4790 message = desAddPadding(message, padding);
4791 len = message.length;
4792 }
4793
4794 //store the result here
4795 let result = new Uint8Array(len);
4796 let k = 0;
4797
4798 if (mode === 1) { //CBC mode
4799 cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4800 cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4801 m = 0;
4802 }
4803
4804 //loop through each 64 bit chunk of the message
4805 while (m < len) {
4806 left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4807 right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4808
4809 //for Cipher Block Chaining mode, xor the message with the previous result
4810 if (mode === 1) {
4811 if (encrypt) {
4812 left ^= cbcleft;
4813 right ^= cbcright;
4814 } else {
4815 cbcleft2 = cbcleft;
4816 cbcright2 = cbcright;
4817 cbcleft = left;
4818 cbcright = right;
4819 }
4820 }
4821
4822 //first each 64 but chunk of the message must be permuted according to IP
4823 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4824 right ^= temp;
4825 left ^= (temp << 4);
4826 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4827 right ^= temp;
4828 left ^= (temp << 16);
4829 temp = ((right >>> 2) ^ left) & 0x33333333;
4830 left ^= temp;
4831 right ^= (temp << 2);
4832 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4833 left ^= temp;
4834 right ^= (temp << 8);
4835 temp = ((left >>> 1) ^ right) & 0x55555555;
4836 right ^= temp;
4837 left ^= (temp << 1);
4838
4839 left = ((left << 1) | (left >>> 31));
4840 right = ((right << 1) | (right >>> 31));
4841
4842 //do this either 1 or 3 times for each chunk of the message
4843 for (j = 0; j < iterations; j += 3) {
4844 endloop = looping[j + 1];
4845 loopinc = looping[j + 2];
4846 //now go through and perform the encryption or decryption
4847 for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
4848 right1 = right ^ keys[i];
4849 right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
4850 //the result is attained by passing these bytes through the S selection functions
4851 temp = left;
4852 left = right;
4853 right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
4854 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
4855 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
4856 }
4857 temp = left;
4858 left = right;
4859 right = temp; //unreverse left and right
4860 } //for either 1 or 3 iterations
4861
4862 //move then each one bit to the right
4863 left = ((left >>> 1) | (left << 31));
4864 right = ((right >>> 1) | (right << 31));
4865
4866 //now perform IP-1, which is IP in the opposite direction
4867 temp = ((left >>> 1) ^ right) & 0x55555555;
4868 right ^= temp;
4869 left ^= (temp << 1);
4870 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4871 left ^= temp;
4872 right ^= (temp << 8);
4873 temp = ((right >>> 2) ^ left) & 0x33333333;
4874 left ^= temp;
4875 right ^= (temp << 2);
4876 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4877 right ^= temp;
4878 left ^= (temp << 16);
4879 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4880 right ^= temp;
4881 left ^= (temp << 4);
4882
4883 //for Cipher Block Chaining mode, xor the message with the previous result
4884 if (mode === 1) {
4885 if (encrypt) {
4886 cbcleft = left;
4887 cbcright = right;
4888 } else {
4889 left ^= cbcleft2;
4890 right ^= cbcright2;
4891 }
4892 }
4893
4894 result[k++] = (left >>> 24);
4895 result[k++] = ((left >>> 16) & 0xff);
4896 result[k++] = ((left >>> 8) & 0xff);
4897 result[k++] = (left & 0xff);
4898 result[k++] = (right >>> 24);
4899 result[k++] = ((right >>> 16) & 0xff);
4900 result[k++] = ((right >>> 8) & 0xff);
4901 result[k++] = (right & 0xff);
4902 } //for every 8 characters, or 64 bits in the message
4903
4904 //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
4905 if (!encrypt) {
4906 result = desRemovePadding(result, padding);
4907 }
4908
4909 return result;
4910} //end of des
4911
4912
4913//desCreateKeys
4914//this takes as input a 64 bit key (even though only 56 bits are used)
4915//as an array of 2 integers, and returns 16 48 bit keys
4916
4917function desCreateKeys(key) {
4918 //declaring this locally speeds things up a bit
4919 const pc2bytes0 = [
4920 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
4921 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
4922 ];
4923 const pc2bytes1 = [
4924 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
4925 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
4926 ];
4927 const pc2bytes2 = [
4928 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
4929 0x1000000, 0x1000008, 0x1000800, 0x1000808
4930 ];
4931 const pc2bytes3 = [
4932 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
4933 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
4934 ];
4935 const pc2bytes4 = [
4936 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
4937 0x41000, 0x1010, 0x41010
4938 ];
4939 const pc2bytes5 = [
4940 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
4941 0x2000000, 0x2000400, 0x2000020, 0x2000420
4942 ];
4943 const pc2bytes6 = [
4944 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
4945 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
4946 ];
4947 const pc2bytes7 = [
4948 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
4949 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
4950 ];
4951 const pc2bytes8 = [
4952 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
4953 0x2000002, 0x2040002, 0x2000002, 0x2040002
4954 ];
4955 const pc2bytes9 = [
4956 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
4957 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
4958 ];
4959 const pc2bytes10 = [
4960 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
4961 0x102000, 0x102020, 0x102000, 0x102020
4962 ];
4963 const pc2bytes11 = [
4964 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
4965 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
4966 ];
4967 const pc2bytes12 = [
4968 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
4969 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
4970 ];
4971 const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
4972
4973 //how many iterations (1 for des, 3 for triple des)
4974 const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
4975 //stores the return keys
4976 const keys = new Array(32 * iterations);
4977 //now define the left shifts which need to be done
4978 const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
4979 //other variables
4980 let lefttemp;
4981 let righttemp;
4982 let m = 0;
4983 let n = 0;
4984 let temp;
4985
4986 for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
4987 let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4988 let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4989
4990 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4991 right ^= temp;
4992 left ^= (temp << 4);
4993 temp = ((right >>> -16) ^ left) & 0x0000ffff;
4994 left ^= temp;
4995 right ^= (temp << -16);
4996 temp = ((left >>> 2) ^ right) & 0x33333333;
4997 right ^= temp;
4998 left ^= (temp << 2);
4999 temp = ((right >>> -16) ^ left) & 0x0000ffff;
5000 left ^= temp;
5001 right ^= (temp << -16);
5002 temp = ((left >>> 1) ^ right) & 0x55555555;
5003 right ^= temp;
5004 left ^= (temp << 1);
5005 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
5006 left ^= temp;
5007 right ^= (temp << 8);
5008 temp = ((left >>> 1) ^ right) & 0x55555555;
5009 right ^= temp;
5010 left ^= (temp << 1);
5011
5012 //the right side needs to be shifted and to get the last four bits of the left side
5013 temp = (left << 8) | ((right >>> 20) & 0x000000f0);
5014 //left needs to be put upside down
5015 left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
5016 right = temp;
5017
5018 //now go through and perform these shifts on the left and right keys
5019 for (let i = 0; i < shifts.length; i++) {
5020 //shift the keys either one or two bits to the left
5021 if (shifts[i]) {
5022 left = (left << 2) | (left >>> 26);
5023 right = (right << 2) | (right >>> 26);
5024 } else {
5025 left = (left << 1) | (left >>> 27);
5026 right = (right << 1) | (right >>> 27);
5027 }
5028 left &= -0xf;
5029 right &= -0xf;
5030
5031 //now apply PC-2, in such a way that E is easier when encrypting or decrypting
5032 //this conversion will look like PC-2 except only the last 6 bits of each byte are used
5033 //rather than 48 consecutive bits and the order of lines will be according to
5034 //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
5035 lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(
5036 left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
5037 0xf];
5038 righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
5039 pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
5040 pc2bytes13[(right >>> 4) & 0xf];
5041 temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
5042 keys[n++] = lefttemp ^ temp;
5043 keys[n++] = righttemp ^ (temp << 16);
5044 }
5045 } //for each iterations
5046 //return the keys we've created
5047 return keys;
5048} //end of desCreateKeys
5049
5050
5051function desAddPadding(message, padding) {
5052 const padLength = 8 - (message.length % 8);
5053
5054 let pad;
5055 if (padding === 2 && (padLength < 8)) { //pad the message with spaces
5056 pad = ' '.charCodeAt(0);
5057 } else if (padding === 1) { //PKCS7 padding
5058 pad = padLength;
5059 } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
5060 pad = 0;
5061 } else if (padLength === 8) {
5062 return message;
5063 } else {
5064 throw new Error('des: invalid padding');
5065 }
5066
5067 const paddedMessage = new Uint8Array(message.length + padLength);
5068 for (let i = 0; i < message.length; i++) {
5069 paddedMessage[i] = message[i];
5070 }
5071 for (let j = 0; j < padLength; j++) {
5072 paddedMessage[message.length + j] = pad;
5073 }
5074
5075 return paddedMessage;
5076}
5077
5078function desRemovePadding(message, padding) {
5079 let padLength = null;
5080 let pad;
5081 if (padding === 2) { // space padded
5082 pad = ' '.charCodeAt(0);
5083 } else if (padding === 1) { // PKCS7
5084 padLength = message[message.length - 1];
5085 } else if (!padding) { // null padding
5086 pad = 0;
5087 } else {
5088 throw new Error('des: invalid padding');
5089 }
5090
5091 if (!padLength) {
5092 padLength = 1;
5093 while (message[message.length - padLength] === pad) {
5094 padLength++;
5095 }
5096 padLength--;
5097 }
5098
5099 return message.subarray(0, message.length - padLength);
5100}
5101
5102// added by Recurity Labs
5103
5104function TripleDES(key) {
5105 this.key = [];
5106
5107 for (let i = 0; i < 3; i++) {
5108 this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
5109 }
5110
5111 this.encrypt = function(block) {
5112 return des(
5113 desCreateKeys(this.key[2]),
5114 des(
5115 desCreateKeys(this.key[1]),
5116 des(
5117 desCreateKeys(this.key[0]),
5118 block, true, 0, null, null
5119 ),
5120 false, 0, null, null
5121 ), true, 0, null, null
5122 );
5123 };
5124}
5125
5126TripleDES.keySize = TripleDES.prototype.keySize = 24;
5127TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
5128
5129// This is "original" DES
5130
5131function DES(key) {
5132 this.key = key;
5133
5134 this.encrypt = function(block, padding) {
5135 const keys = desCreateKeys(this.key);
5136 return des(keys, block, true, 0, null, padding);
5137 };
5138
5139 this.decrypt = function(block, padding) {
5140 const keys = desCreateKeys(this.key);
5141 return des(keys, block, false, 0, null, padding);
5142 };
5143}
5144
5145// Use of this source code is governed by a BSD-style
5146// license that can be found in the LICENSE file.
5147
5148// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
5149
5150// Modified by Recurity Labs GmbH
5151
5152// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
5153// check www.haneWIN.de for the latest version
5154
5155// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
5156// CAST-128 is a common OpenPGP cipher.
5157
5158
5159// CAST5 constructor
5160
5161function OpenPGPSymEncCAST5() {
5162 this.BlockSize = 8;
5163 this.KeySize = 16;
5164
5165 this.setKey = function(key) {
5166 this.masking = new Array(16);
5167 this.rotate = new Array(16);
5168
5169 this.reset();
5170
5171 if (key.length === this.KeySize) {
5172 this.keySchedule(key);
5173 } else {
5174 throw new Error('CAST-128: keys must be 16 bytes');
5175 }
5176 return true;
5177 };
5178
5179 this.reset = function() {
5180 for (let i = 0; i < 16; i++) {
5181 this.masking[i] = 0;
5182 this.rotate[i] = 0;
5183 }
5184 };
5185
5186 this.getBlockSize = function() {
5187 return this.BlockSize;
5188 };
5189
5190 this.encrypt = function(src) {
5191 const dst = new Array(src.length);
5192
5193 for (let i = 0; i < src.length; i += 8) {
5194 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5195 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5196 let t;
5197
5198 t = r;
5199 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5200 l = t;
5201 t = r;
5202 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5203 l = t;
5204 t = r;
5205 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5206 l = t;
5207 t = r;
5208 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5209 l = t;
5210
5211 t = r;
5212 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5213 l = t;
5214 t = r;
5215 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5216 l = t;
5217 t = r;
5218 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5219 l = t;
5220 t = r;
5221 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5222 l = t;
5223
5224 t = r;
5225 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5226 l = t;
5227 t = r;
5228 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5229 l = t;
5230 t = r;
5231 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5232 l = t;
5233 t = r;
5234 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5235 l = t;
5236
5237 t = r;
5238 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5239 l = t;
5240 t = r;
5241 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5242 l = t;
5243 t = r;
5244 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5245 l = t;
5246 t = r;
5247 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5248 l = t;
5249
5250 dst[i] = (r >>> 24) & 255;
5251 dst[i + 1] = (r >>> 16) & 255;
5252 dst[i + 2] = (r >>> 8) & 255;
5253 dst[i + 3] = r & 255;
5254 dst[i + 4] = (l >>> 24) & 255;
5255 dst[i + 5] = (l >>> 16) & 255;
5256 dst[i + 6] = (l >>> 8) & 255;
5257 dst[i + 7] = l & 255;
5258 }
5259
5260 return dst;
5261 };
5262
5263 this.decrypt = function(src) {
5264 const dst = new Array(src.length);
5265
5266 for (let i = 0; i < src.length; i += 8) {
5267 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5268 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5269 let t;
5270
5271 t = r;
5272 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5273 l = t;
5274 t = r;
5275 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5276 l = t;
5277 t = r;
5278 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5279 l = t;
5280 t = r;
5281 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5282 l = t;
5283
5284 t = r;
5285 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5286 l = t;
5287 t = r;
5288 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5289 l = t;
5290 t = r;
5291 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5292 l = t;
5293 t = r;
5294 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5295 l = t;
5296
5297 t = r;
5298 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5299 l = t;
5300 t = r;
5301 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5302 l = t;
5303 t = r;
5304 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5305 l = t;
5306 t = r;
5307 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5308 l = t;
5309
5310 t = r;
5311 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5312 l = t;
5313 t = r;
5314 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5315 l = t;
5316 t = r;
5317 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5318 l = t;
5319 t = r;
5320 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5321 l = t;
5322
5323 dst[i] = (r >>> 24) & 255;
5324 dst[i + 1] = (r >>> 16) & 255;
5325 dst[i + 2] = (r >>> 8) & 255;
5326 dst[i + 3] = r & 255;
5327 dst[i + 4] = (l >>> 24) & 255;
5328 dst[i + 5] = (l >> 16) & 255;
5329 dst[i + 6] = (l >> 8) & 255;
5330 dst[i + 7] = l & 255;
5331 }
5332
5333 return dst;
5334 };
5335 const scheduleA = new Array(4);
5336
5337 scheduleA[0] = new Array(4);
5338 scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
5339 scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5340 scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5341 scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5342
5343 scheduleA[1] = new Array(4);
5344 scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5345 scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5346 scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5347 scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5348
5349 scheduleA[2] = new Array(4);
5350 scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
5351 scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5352 scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5353 scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5354
5355
5356 scheduleA[3] = new Array(4);
5357 scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5358 scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5359 scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5360 scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5361
5362 const scheduleB = new Array(4);
5363
5364 scheduleB[0] = new Array(4);
5365 scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
5366 scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
5367 scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
5368 scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
5369
5370 scheduleB[1] = new Array(4);
5371 scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
5372 scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
5373 scheduleB[1][2] = [7, 6, 8, 9, 3];
5374 scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
5375
5376
5377 scheduleB[2] = new Array(4);
5378 scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
5379 scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
5380 scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
5381 scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
5382
5383
5384 scheduleB[3] = new Array(4);
5385 scheduleB[3][0] = [8, 9, 7, 6, 3];
5386 scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
5387 scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
5388 scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
5389
5390 // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
5391 this.keySchedule = function(inn) {
5392 const t = new Array(8);
5393 const k = new Array(32);
5394
5395 let j;
5396
5397 for (let i = 0; i < 4; i++) {
5398 j = i * 4;
5399 t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
5400 }
5401
5402 const x = [6, 7, 4, 5];
5403 let ki = 0;
5404 let w;
5405
5406 for (let half = 0; half < 2; half++) {
5407 for (let round = 0; round < 4; round++) {
5408 for (j = 0; j < 4; j++) {
5409 const a = scheduleA[round][j];
5410 w = t[a[1]];
5411
5412 w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
5413 w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
5414 w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
5415 w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
5416 w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
5417 t[a[0]] = w;
5418 }
5419
5420 for (j = 0; j < 4; j++) {
5421 const b = scheduleB[round][j];
5422 w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
5423
5424 w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
5425 w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
5426 w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
5427 w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
5428 k[ki] = w;
5429 ki++;
5430 }
5431 }
5432 }
5433
5434 for (let i = 0; i < 16; i++) {
5435 this.masking[i] = k[i];
5436 this.rotate[i] = k[16 + i] & 0x1f;
5437 }
5438 };
5439
5440 // These are the three 'f' functions. See RFC 2144, section 2.2.
5441
5442 function f1(d, m, r) {
5443 const t = m + d;
5444 const I = (t << r) | (t >>> (32 - r));
5445 return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
5446 }
5447
5448 function f2(d, m, r) {
5449 const t = m ^ d;
5450 const I = (t << r) | (t >>> (32 - r));
5451 return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
5452 }
5453
5454 function f3(d, m, r) {
5455 const t = m - d;
5456 const I = (t << r) | (t >>> (32 - r));
5457 return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
5458 }
5459
5460 const sBox = new Array(8);
5461 sBox[0] = [
5462 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
5463 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
5464 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
5465 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
5466 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
5467 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
5468 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
5469 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
5470 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
5471 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
5472 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
5473 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
5474 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
5475 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
5476 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
5477 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
5478 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
5479 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
5480 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
5481 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
5482 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
5483 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
5484 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
5485 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
5486 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
5487 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
5488 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
5489 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
5490 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
5491 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
5492 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
5493 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
5494 ];
5495
5496 sBox[1] = [
5497 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
5498 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
5499 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
5500 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
5501 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
5502 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
5503 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
5504 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
5505 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
5506 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
5507 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
5508 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
5509 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
5510 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
5511 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
5512 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
5513 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
5514 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
5515 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
5516 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
5517 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
5518 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
5519 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
5520 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
5521 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
5522 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
5523 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
5524 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
5525 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
5526 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
5527 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
5528 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
5529 ];
5530
5531 sBox[2] = [
5532 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
5533 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
5534 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
5535 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
5536 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
5537 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
5538 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
5539 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
5540 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
5541 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
5542 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
5543 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
5544 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
5545 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
5546 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
5547 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
5548 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
5549 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
5550 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
5551 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
5552 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
5553 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
5554 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
5555 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
5556 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
5557 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
5558 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
5559 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
5560 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
5561 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
5562 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
5563 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
5564 ];
5565
5566 sBox[3] = [
5567 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
5568 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
5569 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
5570 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
5571 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
5572 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
5573 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
5574 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
5575 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
5576 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
5577 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
5578 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
5579 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
5580 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
5581 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
5582 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
5583 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
5584 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
5585 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
5586 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
5587 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
5588 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
5589 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
5590 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
5591 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
5592 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
5593 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
5594 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
5595 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
5596 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
5597 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
5598 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
5599 ];
5600
5601 sBox[4] = [
5602 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
5603 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
5604 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
5605 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
5606 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
5607 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
5608 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
5609 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
5610 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
5611 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
5612 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
5613 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
5614 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
5615 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
5616 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
5617 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
5618 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
5619 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
5620 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
5621 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
5622 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
5623 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
5624 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
5625 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
5626 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
5627 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
5628 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
5629 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
5630 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
5631 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
5632 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
5633 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
5634 ];
5635
5636 sBox[5] = [
5637 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
5638 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
5639 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
5640 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
5641 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
5642 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
5643 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
5644 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
5645 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
5646 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
5647 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
5648 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
5649 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
5650 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
5651 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
5652 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
5653 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
5654 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
5655 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
5656 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
5657 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
5658 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
5659 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
5660 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
5661 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
5662 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
5663 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
5664 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
5665 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
5666 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
5667 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
5668 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
5669 ];
5670
5671 sBox[6] = [
5672 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
5673 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
5674 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
5675 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
5676 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
5677 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
5678 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
5679 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
5680 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
5681 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
5682 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
5683 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
5684 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
5685 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
5686 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
5687 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
5688 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
5689 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
5690 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
5691 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
5692 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
5693 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
5694 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
5695 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
5696 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
5697 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
5698 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
5699 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
5700 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
5701 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
5702 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
5703 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
5704 ];
5705
5706 sBox[7] = [
5707 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
5708 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
5709 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
5710 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
5711 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
5712 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
5713 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
5714 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
5715 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
5716 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
5717 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
5718 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
5719 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
5720 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
5721 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
5722 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
5723 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
5724 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
5725 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
5726 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
5727 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
5728 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
5729 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
5730 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
5731 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
5732 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
5733 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
5734 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
5735 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
5736 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
5737 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
5738 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
5739 ];
5740}
5741
5742function CAST5(key) {
5743 this.cast5 = new OpenPGPSymEncCAST5();
5744 this.cast5.setKey(key);
5745
5746 this.encrypt = function(block) {
5747 return this.cast5.encrypt(block);
5748 };
5749}
5750
5751CAST5.blockSize = CAST5.prototype.blockSize = 8;
5752CAST5.keySize = CAST5.prototype.keySize = 16;
5753
5754/* eslint-disable no-mixed-operators, no-fallthrough */
5755
5756
5757/* Modified by Recurity Labs GmbH
5758 *
5759 * Cipher.js
5760 * A block-cipher algorithm implementation on JavaScript
5761 * See Cipher.readme.txt for further information.
5762 *
5763 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
5764 * This script file is distributed under the LGPL
5765 *
5766 * ACKNOWLEDGMENT
5767 *
5768 * The main subroutines are written by Michiel van Everdingen.
5769 *
5770 * Michiel van Everdingen
5771 * http://home.versatel.nl/MAvanEverdingen/index.html
5772 *
5773 * All rights for these routines are reserved to Michiel van Everdingen.
5774 *
5775 */
5776
5777////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5778//Math
5779////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5780
5781const MAXINT = 0xFFFFFFFF;
5782
5783function rotw(w, n) {
5784 return (w << n | w >>> (32 - n)) & MAXINT;
5785}
5786
5787function getW(a, i) {
5788 return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
5789}
5790
5791function setW(a, i, w) {
5792 a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
5793}
5794
5795function getB(x, n) {
5796 return (x >>> (n * 8)) & 0xFF;
5797}
5798
5799// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5800// Twofish
5801// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5802
5803function createTwofish() {
5804 //
5805 let keyBytes = null;
5806 let dataBytes = null;
5807 let dataOffset = -1;
5808 // var dataLength = -1;
5809 // var idx2 = -1;
5810 //
5811
5812 let tfsKey = [];
5813 let tfsM = [
5814 [],
5815 [],
5816 [],
5817 []
5818 ];
5819
5820 function tfsInit(key) {
5821 keyBytes = key;
5822 let i;
5823 let a;
5824 let b;
5825 let c;
5826 let d;
5827 const meKey = [];
5828 const moKey = [];
5829 const inKey = [];
5830 let kLen;
5831 const sKey = [];
5832 let f01;
5833 let f5b;
5834 let fef;
5835
5836 const q0 = [
5837 [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
5838 [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
5839 ];
5840 const q1 = [
5841 [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
5842 [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
5843 ];
5844 const q2 = [
5845 [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
5846 [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
5847 ];
5848 const q3 = [
5849 [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
5850 [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
5851 ];
5852 const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
5853 const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
5854 const q = [
5855 [],
5856 []
5857 ];
5858 const m = [
5859 [],
5860 [],
5861 [],
5862 []
5863 ];
5864
5865 function ffm5b(x) {
5866 return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
5867 }
5868
5869 function ffmEf(x) {
5870 return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
5871 }
5872
5873 function mdsRem(p, q) {
5874 let i;
5875 let t;
5876 let u;
5877 for (i = 0; i < 8; i++) {
5878 t = q >>> 24;
5879 q = ((q << 8) & MAXINT) | p >>> 24;
5880 p = (p << 8) & MAXINT;
5881 u = t << 1;
5882 if (t & 128) {
5883 u ^= 333;
5884 }
5885 q ^= t ^ (u << 16);
5886 u ^= t >>> 1;
5887 if (t & 1) {
5888 u ^= 166;
5889 }
5890 q ^= u << 24 | u << 8;
5891 }
5892 return q;
5893 }
5894
5895 function qp(n, x) {
5896 const a = x >> 4;
5897 const b = x & 15;
5898 const c = q0[n][a ^ b];
5899 const d = q1[n][ror4[b] ^ ashx[a]];
5900 return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
5901 }
5902
5903 function hFun(x, key) {
5904 let a = getB(x, 0);
5905 let b = getB(x, 1);
5906 let c = getB(x, 2);
5907 let d = getB(x, 3);
5908 switch (kLen) {
5909 case 4:
5910 a = q[1][a] ^ getB(key[3], 0);
5911 b = q[0][b] ^ getB(key[3], 1);
5912 c = q[0][c] ^ getB(key[3], 2);
5913 d = q[1][d] ^ getB(key[3], 3);
5914 case 3:
5915 a = q[1][a] ^ getB(key[2], 0);
5916 b = q[1][b] ^ getB(key[2], 1);
5917 c = q[0][c] ^ getB(key[2], 2);
5918 d = q[0][d] ^ getB(key[2], 3);
5919 case 2:
5920 a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
5921 b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
5922 c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
5923 d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
5924 }
5925 return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
5926 }
5927
5928 keyBytes = keyBytes.slice(0, 32);
5929 i = keyBytes.length;
5930 while (i !== 16 && i !== 24 && i !== 32) {
5931 keyBytes[i++] = 0;
5932 }
5933
5934 for (i = 0; i < keyBytes.length; i += 4) {
5935 inKey[i >> 2] = getW(keyBytes, i);
5936 }
5937 for (i = 0; i < 256; i++) {
5938 q[0][i] = qp(0, i);
5939 q[1][i] = qp(1, i);
5940 }
5941 for (i = 0; i < 256; i++) {
5942 f01 = q[1][i];
5943 f5b = ffm5b(f01);
5944 fef = ffmEf(f01);
5945 m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
5946 m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
5947 f01 = q[0][i];
5948 f5b = ffm5b(f01);
5949 fef = ffmEf(f01);
5950 m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
5951 m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
5952 }
5953
5954 kLen = inKey.length / 2;
5955 for (i = 0; i < kLen; i++) {
5956 a = inKey[i + i];
5957 meKey[i] = a;
5958 b = inKey[i + i + 1];
5959 moKey[i] = b;
5960 sKey[kLen - i - 1] = mdsRem(a, b);
5961 }
5962 for (i = 0; i < 40; i += 2) {
5963 a = 0x1010101 * i;
5964 b = a + 0x1010101;
5965 a = hFun(a, meKey);
5966 b = rotw(hFun(b, moKey), 8);
5967 tfsKey[i] = (a + b) & MAXINT;
5968 tfsKey[i + 1] = rotw(a + 2 * b, 9);
5969 }
5970 for (i = 0; i < 256; i++) {
5971 a = b = c = d = i;
5972 switch (kLen) {
5973 case 4:
5974 a = q[1][a] ^ getB(sKey[3], 0);
5975 b = q[0][b] ^ getB(sKey[3], 1);
5976 c = q[0][c] ^ getB(sKey[3], 2);
5977 d = q[1][d] ^ getB(sKey[3], 3);
5978 case 3:
5979 a = q[1][a] ^ getB(sKey[2], 0);
5980 b = q[1][b] ^ getB(sKey[2], 1);
5981 c = q[0][c] ^ getB(sKey[2], 2);
5982 d = q[0][d] ^ getB(sKey[2], 3);
5983 case 2:
5984 tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
5985 tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
5986 tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
5987 tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
5988 }
5989 }
5990 }
5991
5992 function tfsG0(x) {
5993 return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
5994 }
5995
5996 function tfsG1(x) {
5997 return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
5998 }
5999
6000 function tfsFrnd(r, blk) {
6001 let a = tfsG0(blk[0]);
6002 let b = tfsG1(blk[1]);
6003 blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
6004 blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
6005 a = tfsG0(blk[2]);
6006 b = tfsG1(blk[3]);
6007 blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
6008 blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
6009 }
6010
6011 function tfsIrnd(i, blk) {
6012 let a = tfsG0(blk[0]);
6013 let b = tfsG1(blk[1]);
6014 blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
6015 blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
6016 a = tfsG0(blk[2]);
6017 b = tfsG1(blk[3]);
6018 blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
6019 blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
6020 }
6021
6022 function tfsClose() {
6023 tfsKey = [];
6024 tfsM = [
6025 [],
6026 [],
6027 [],
6028 []
6029 ];
6030 }
6031
6032 function tfsEncrypt(data, offset) {
6033 dataBytes = data;
6034 dataOffset = offset;
6035 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
6036 getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
6037 getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
6038 getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
6039 for (let j = 0; j < 8; j++) {
6040 tfsFrnd(j, blk);
6041 }
6042 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
6043 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
6044 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
6045 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
6046 dataOffset += 16;
6047 return dataBytes;
6048 }
6049
6050 function tfsDecrypt(data, offset) {
6051 dataBytes = data;
6052 dataOffset = offset;
6053 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
6054 getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
6055 getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
6056 getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
6057 for (let j = 7; j >= 0; j--) {
6058 tfsIrnd(j, blk);
6059 }
6060 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
6061 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
6062 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
6063 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
6064 dataOffset += 16;
6065 }
6066
6067 // added by Recurity Labs
6068
6069 function tfsFinal() {
6070 return dataBytes;
6071 }
6072
6073 return {
6074 name: 'twofish',
6075 blocksize: 128 / 8,
6076 open: tfsInit,
6077 close: tfsClose,
6078 encrypt: tfsEncrypt,
6079 decrypt: tfsDecrypt,
6080 // added by Recurity Labs
6081 finalize: tfsFinal
6082 };
6083}
6084
6085// added by Recurity Labs
6086
6087function TF(key) {
6088 this.tf = createTwofish();
6089 this.tf.open(Array.from(key), 0);
6090
6091 this.encrypt = function(block) {
6092 return this.tf.encrypt(Array.from(block), 0);
6093 };
6094}
6095
6096TF.keySize = TF.prototype.keySize = 32;
6097TF.blockSize = TF.prototype.blockSize = 16;
6098
6099/* Modified by Recurity Labs GmbH
6100 *
6101 * Originally written by nklein software (nklein.com)
6102 */
6103
6104/*
6105 * Javascript implementation based on Bruce Schneier's reference implementation.
6106 *
6107 *
6108 * The constructor doesn't do much of anything. It's just here
6109 * so we can start defining properties and methods and such.
6110 */
6111function Blowfish() {}
6112
6113/*
6114 * Declare the block size so that protocols know what size
6115 * Initialization Vector (IV) they will need.
6116 */
6117Blowfish.prototype.BLOCKSIZE = 8;
6118
6119/*
6120 * These are the default SBOXES.
6121 */
6122Blowfish.prototype.SBOXES = [
6123 [
6124 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
6125 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
6126 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
6127 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
6128 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
6129 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
6130 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
6131 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
6132 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
6133 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
6134 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
6135 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
6136 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
6137 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
6138 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
6139 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
6140 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
6141 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
6142 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
6143 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
6144 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
6145 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
6146 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
6147 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
6148 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
6149 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
6150 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
6151 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
6152 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
6153 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
6154 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
6155 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
6156 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
6157 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
6158 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
6159 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
6160 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
6161 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
6162 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
6163 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
6164 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
6165 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
6166 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
6167 ],
6168 [
6169 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
6170 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
6171 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
6172 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
6173 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
6174 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
6175 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
6176 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
6177 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
6178 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
6179 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
6180 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
6181 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
6182 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
6183 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
6184 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
6185 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
6186 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
6187 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
6188 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
6189 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
6190 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
6191 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
6192 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
6193 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
6194 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
6195 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
6196 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
6197 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
6198 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
6199 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
6200 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
6201 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
6202 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
6203 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
6204 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
6205 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
6206 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
6207 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
6208 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
6209 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
6210 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
6211 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
6212 ],
6213 [
6214 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
6215 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
6216 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
6217 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
6218 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
6219 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
6220 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
6221 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
6222 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
6223 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
6224 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
6225 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
6226 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
6227 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
6228 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
6229 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
6230 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
6231 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
6232 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
6233 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
6234 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
6235 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
6236 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
6237 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
6238 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
6239 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
6240 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
6241 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
6242 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
6243 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
6244 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
6245 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
6246 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
6247 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
6248 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
6249 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
6250 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
6251 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
6252 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
6253 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
6254 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
6255 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
6256 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
6257 ],
6258 [
6259 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
6260 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
6261 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
6262 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
6263 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
6264 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
6265 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
6266 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
6267 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
6268 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
6269 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
6270 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
6271 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
6272 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
6273 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
6274 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
6275 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
6276 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
6277 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
6278 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
6279 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
6280 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
6281 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
6282 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
6283 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
6284 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
6285 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
6286 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
6287 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
6288 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
6289 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
6290 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
6291 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
6292 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
6293 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
6294 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
6295 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
6296 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
6297 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
6298 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
6299 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
6300 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
6301 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
6302 ]
6303];
6304
6305//*
6306//* This is the default PARRAY
6307//*
6308Blowfish.prototype.PARRAY = [
6309 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
6310 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
6311 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
6312];
6313
6314//*
6315//* This is the number of rounds the cipher will go
6316//*
6317Blowfish.prototype.NN = 16;
6318
6319//*
6320//* This function is needed to get rid of problems
6321//* with the high-bit getting set. If we don't do
6322//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
6323//* equal to ( bb & 0x00FFFFFFFF ) even when they
6324//* agree bit-for-bit for the first 32 bits.
6325//*
6326Blowfish.prototype._clean = function(xx) {
6327 if (xx < 0) {
6328 const yy = xx & 0x7FFFFFFF;
6329 xx = yy + 0x80000000;
6330 }
6331 return xx;
6332};
6333
6334//*
6335//* This is the mixing function that uses the sboxes
6336//*
6337Blowfish.prototype._F = function(xx) {
6338 let yy;
6339
6340 const dd = xx & 0x00FF;
6341 xx >>>= 8;
6342 const cc = xx & 0x00FF;
6343 xx >>>= 8;
6344 const bb = xx & 0x00FF;
6345 xx >>>= 8;
6346 const aa = xx & 0x00FF;
6347
6348 yy = this.sboxes[0][aa] + this.sboxes[1][bb];
6349 yy ^= this.sboxes[2][cc];
6350 yy += this.sboxes[3][dd];
6351
6352 return yy;
6353};
6354
6355//*
6356//* This method takes an array with two values, left and right
6357//* and does NN rounds of Blowfish on them.
6358//*
6359Blowfish.prototype._encryptBlock = function(vals) {
6360 let dataL = vals[0];
6361 let dataR = vals[1];
6362
6363 let ii;
6364
6365 for (ii = 0; ii < this.NN; ++ii) {
6366 dataL ^= this.parray[ii];
6367 dataR = this._F(dataL) ^ dataR;
6368
6369 const tmp = dataL;
6370 dataL = dataR;
6371 dataR = tmp;
6372 }
6373
6374 dataL ^= this.parray[this.NN + 0];
6375 dataR ^= this.parray[this.NN + 1];
6376
6377 vals[0] = this._clean(dataR);
6378 vals[1] = this._clean(dataL);
6379};
6380
6381//*
6382//* This method takes a vector of numbers and turns them
6383//* into long words so that they can be processed by the
6384//* real algorithm.
6385//*
6386//* Maybe I should make the real algorithm above take a vector
6387//* instead. That will involve more looping, but it won't require
6388//* the F() method to deconstruct the vector.
6389//*
6390Blowfish.prototype.encryptBlock = function(vector) {
6391 let ii;
6392 const vals = [0, 0];
6393 const off = this.BLOCKSIZE / 2;
6394 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6395 vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
6396 vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
6397 }
6398
6399 this._encryptBlock(vals);
6400
6401 const ret = [];
6402 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6403 ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
6404 ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
6405 // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
6406 // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
6407 }
6408
6409 return ret;
6410};
6411
6412//*
6413//* This method takes an array with two values, left and right
6414//* and undoes NN rounds of Blowfish on them.
6415//*
6416Blowfish.prototype._decryptBlock = function(vals) {
6417 let dataL = vals[0];
6418 let dataR = vals[1];
6419
6420 let ii;
6421
6422 for (ii = this.NN + 1; ii > 1; --ii) {
6423 dataL ^= this.parray[ii];
6424 dataR = this._F(dataL) ^ dataR;
6425
6426 const tmp = dataL;
6427 dataL = dataR;
6428 dataR = tmp;
6429 }
6430
6431 dataL ^= this.parray[1];
6432 dataR ^= this.parray[0];
6433
6434 vals[0] = this._clean(dataR);
6435 vals[1] = this._clean(dataL);
6436};
6437
6438//*
6439//* This method takes a key array and initializes the
6440//* sboxes and parray for this encryption.
6441//*
6442Blowfish.prototype.init = function(key) {
6443 let ii;
6444 let jj = 0;
6445
6446 this.parray = [];
6447 for (ii = 0; ii < this.NN + 2; ++ii) {
6448 let data = 0x00000000;
6449 for (let kk = 0; kk < 4; ++kk) {
6450 data = (data << 8) | (key[jj] & 0x00FF);
6451 if (++jj >= key.length) {
6452 jj = 0;
6453 }
6454 }
6455 this.parray[ii] = this.PARRAY[ii] ^ data;
6456 }
6457
6458 this.sboxes = [];
6459 for (ii = 0; ii < 4; ++ii) {
6460 this.sboxes[ii] = [];
6461 for (jj = 0; jj < 256; ++jj) {
6462 this.sboxes[ii][jj] = this.SBOXES[ii][jj];
6463 }
6464 }
6465
6466 const vals = [0x00000000, 0x00000000];
6467
6468 for (ii = 0; ii < this.NN + 2; ii += 2) {
6469 this._encryptBlock(vals);
6470 this.parray[ii + 0] = vals[0];
6471 this.parray[ii + 1] = vals[1];
6472 }
6473
6474 for (ii = 0; ii < 4; ++ii) {
6475 for (jj = 0; jj < 256; jj += 2) {
6476 this._encryptBlock(vals);
6477 this.sboxes[ii][jj + 0] = vals[0];
6478 this.sboxes[ii][jj + 1] = vals[1];
6479 }
6480 }
6481};
6482
6483// added by Recurity Labs
6484function BF(key) {
6485 this.bf = new Blowfish();
6486 this.bf.init(key);
6487
6488 this.encrypt = function(block) {
6489 return this.bf.encryptBlock(block);
6490 };
6491}
6492
6493BF.keySize = BF.prototype.keySize = 16;
6494BF.blockSize = BF.prototype.blockSize = 8;
6495
6496/**
6497 * @fileoverview Symmetric cryptography functions
6498 * @module crypto/cipher
6499 * @private
6500 */
6501
6502/**
6503 * AES-128 encryption and decryption (ID 7)
6504 * @function
6505 * @param {String} key - 128-bit key
6506 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6507 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6508 * @returns {Object}
6509 */
6510const aes128 = aes(128);
6511/**
6512 * AES-128 Block Cipher (ID 8)
6513 * @function
6514 * @param {String} key - 192-bit key
6515 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6516 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6517 * @returns {Object}
6518 */
6519const aes192 = aes(192);
6520/**
6521 * AES-128 Block Cipher (ID 9)
6522 * @function
6523 * @param {String} key - 256-bit key
6524 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6525 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6526 * @returns {Object}
6527 */
6528const aes256 = aes(256);
6529// Not in OpenPGP specifications
6530const des$1 = DES;
6531/**
6532 * Triple DES Block Cipher (ID 2)
6533 * @function
6534 * @param {String} key - 192-bit key
6535 * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
6536 * @returns {Object}
6537 */
6538const tripledes = TripleDES;
6539/**
6540 * CAST-128 Block Cipher (ID 3)
6541 * @function
6542 * @param {String} key - 128-bit key
6543 * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
6544 * @returns {Object}
6545 */
6546const cast5 = CAST5;
6547/**
6548 * Twofish Block Cipher (ID 10)
6549 * @function
6550 * @param {String} key - 256-bit key
6551 * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
6552 * @returns {Object}
6553 */
6554const twofish = TF;
6555/**
6556 * Blowfish Block Cipher (ID 4)
6557 * @function
6558 * @param {String} key - 128-bit key
6559 * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
6560 * @returns {Object}
6561 */
6562const blowfish = BF;
6563/**
6564 * Not implemented
6565 * @function
6566 * @throws {Error}
6567 */
6568const idea = function() {
6569 throw new Error('IDEA symmetric-key algorithm not implemented');
6570};
6571
6572var cipher = /*#__PURE__*/Object.freeze({
6573 __proto__: null,
6574 aes128: aes128,
6575 aes192: aes192,
6576 aes256: aes256,
6577 des: des$1,
6578 tripledes: tripledes,
6579 cast5: cast5,
6580 twofish: twofish,
6581 blowfish: blowfish,
6582 idea: idea
6583});
6584
6585var sha1_asm = function ( stdlib, foreign, buffer ) {
6586 "use asm";
6587
6588 // SHA256 state
6589 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
6590 TOTAL0 = 0, TOTAL1 = 0;
6591
6592 // HMAC state
6593 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
6594 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
6595
6596 // I/O buffer
6597 var HEAP = new stdlib.Uint8Array(buffer);
6598
6599 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
6600 w0 = w0|0;
6601 w1 = w1|0;
6602 w2 = w2|0;
6603 w3 = w3|0;
6604 w4 = w4|0;
6605 w5 = w5|0;
6606 w6 = w6|0;
6607 w7 = w7|0;
6608 w8 = w8|0;
6609 w9 = w9|0;
6610 w10 = w10|0;
6611 w11 = w11|0;
6612 w12 = w12|0;
6613 w13 = w13|0;
6614 w14 = w14|0;
6615 w15 = w15|0;
6616
6617 var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
6618 w16 = 0, w17 = 0, w18 = 0, w19 = 0,
6619 w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
6620 w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
6621 w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
6622 w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
6623 w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
6624 w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
6625
6626 a = H0;
6627 b = H1;
6628 c = H2;
6629 d = H3;
6630 e = H4;
6631
6632 // 0
6633 t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6634 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6635
6636 // 1
6637 t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6638 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6639
6640 // 2
6641 t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6642 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6643
6644 // 3
6645 t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6646 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6647
6648 // 4
6649 t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6650 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6651
6652 // 5
6653 t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6654 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6655
6656 // 6
6657 t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6658 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6659
6660 // 7
6661 t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6662 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6663
6664 // 8
6665 t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6666 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6667
6668 // 9
6669 t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6670 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6671
6672 // 10
6673 t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6674 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6675
6676 // 11
6677 t = ( w11 + ((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 // 12
6681 t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6682 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6683
6684 // 13
6685 t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6686 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6687
6688 // 14
6689 t = ( w14 + ((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 // 15
6693 t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6694 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6695
6696 // 16
6697 n = w13 ^ w8 ^ w2 ^ w0;
6698 w16 = (n << 1) | (n >>> 31);
6699 t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6700 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6701
6702 // 17
6703 n = w14 ^ w9 ^ w3 ^ w1;
6704 w17 = (n << 1) | (n >>> 31);
6705 t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6706 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6707
6708 // 18
6709 n = w15 ^ w10 ^ w4 ^ w2;
6710 w18 = (n << 1) | (n >>> 31);
6711 t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6712 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6713
6714 // 19
6715 n = w16 ^ w11 ^ w5 ^ w3;
6716 w19 = (n << 1) | (n >>> 31);
6717 t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6718 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6719
6720 // 20
6721 n = w17 ^ w12 ^ w6 ^ w4;
6722 w20 = (n << 1) | (n >>> 31);
6723 t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6724 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6725
6726 // 21
6727 n = w18 ^ w13 ^ w7 ^ w5;
6728 w21 = (n << 1) | (n >>> 31);
6729 t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6730 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6731
6732 // 22
6733 n = w19 ^ w14 ^ w8 ^ w6;
6734 w22 = (n << 1) | (n >>> 31);
6735 t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6736 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6737
6738 // 23
6739 n = w20 ^ w15 ^ w9 ^ w7;
6740 w23 = (n << 1) | (n >>> 31);
6741 t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6742 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6743
6744 // 24
6745 n = w21 ^ w16 ^ w10 ^ w8;
6746 w24 = (n << 1) | (n >>> 31);
6747 t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6748 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6749
6750 // 25
6751 n = w22 ^ w17 ^ w11 ^ w9;
6752 w25 = (n << 1) | (n >>> 31);
6753 t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6754 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6755
6756 // 26
6757 n = w23 ^ w18 ^ w12 ^ w10;
6758 w26 = (n << 1) | (n >>> 31);
6759 t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6760 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6761
6762 // 27
6763 n = w24 ^ w19 ^ w13 ^ w11;
6764 w27 = (n << 1) | (n >>> 31);
6765 t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6766 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6767
6768 // 28
6769 n = w25 ^ w20 ^ w14 ^ w12;
6770 w28 = (n << 1) | (n >>> 31);
6771 t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6772 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6773
6774 // 29
6775 n = w26 ^ w21 ^ w15 ^ w13;
6776 w29 = (n << 1) | (n >>> 31);
6777 t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6778 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6779
6780 // 30
6781 n = w27 ^ w22 ^ w16 ^ w14;
6782 w30 = (n << 1) | (n >>> 31);
6783 t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6784 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6785
6786 // 31
6787 n = w28 ^ w23 ^ w17 ^ w15;
6788 w31 = (n << 1) | (n >>> 31);
6789 t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6790 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6791
6792 // 32
6793 n = w29 ^ w24 ^ w18 ^ w16;
6794 w32 = (n << 1) | (n >>> 31);
6795 t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6796 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6797
6798 // 33
6799 n = w30 ^ w25 ^ w19 ^ w17;
6800 w33 = (n << 1) | (n >>> 31);
6801 t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6802 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6803
6804 // 34
6805 n = w31 ^ w26 ^ w20 ^ w18;
6806 w34 = (n << 1) | (n >>> 31);
6807 t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6808 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6809
6810 // 35
6811 n = w32 ^ w27 ^ w21 ^ w19;
6812 w35 = (n << 1) | (n >>> 31);
6813 t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6814 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6815
6816 // 36
6817 n = w33 ^ w28 ^ w22 ^ w20;
6818 w36 = (n << 1) | (n >>> 31);
6819 t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6820 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6821
6822 // 37
6823 n = w34 ^ w29 ^ w23 ^ w21;
6824 w37 = (n << 1) | (n >>> 31);
6825 t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6826 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6827
6828 // 38
6829 n = w35 ^ w30 ^ w24 ^ w22;
6830 w38 = (n << 1) | (n >>> 31);
6831 t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6832 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6833
6834 // 39
6835 n = w36 ^ w31 ^ w25 ^ w23;
6836 w39 = (n << 1) | (n >>> 31);
6837 t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6838 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6839
6840 // 40
6841 n = w37 ^ w32 ^ w26 ^ w24;
6842 w40 = (n << 1) | (n >>> 31);
6843 t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6844 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6845
6846 // 41
6847 n = w38 ^ w33 ^ w27 ^ w25;
6848 w41 = (n << 1) | (n >>> 31);
6849 t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6850 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6851
6852 // 42
6853 n = w39 ^ w34 ^ w28 ^ w26;
6854 w42 = (n << 1) | (n >>> 31);
6855 t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6856 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6857
6858 // 43
6859 n = w40 ^ w35 ^ w29 ^ w27;
6860 w43 = (n << 1) | (n >>> 31);
6861 t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6862 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6863
6864 // 44
6865 n = w41 ^ w36 ^ w30 ^ w28;
6866 w44 = (n << 1) | (n >>> 31);
6867 t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6868 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6869
6870 // 45
6871 n = w42 ^ w37 ^ w31 ^ w29;
6872 w45 = (n << 1) | (n >>> 31);
6873 t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6874 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6875
6876 // 46
6877 n = w43 ^ w38 ^ w32 ^ w30;
6878 w46 = (n << 1) | (n >>> 31);
6879 t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6880 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6881
6882 // 47
6883 n = w44 ^ w39 ^ w33 ^ w31;
6884 w47 = (n << 1) | (n >>> 31);
6885 t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6886 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6887
6888 // 48
6889 n = w45 ^ w40 ^ w34 ^ w32;
6890 w48 = (n << 1) | (n >>> 31);
6891 t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6892 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6893
6894 // 49
6895 n = w46 ^ w41 ^ w35 ^ w33;
6896 w49 = (n << 1) | (n >>> 31);
6897 t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6898 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6899
6900 // 50
6901 n = w47 ^ w42 ^ w36 ^ w34;
6902 w50 = (n << 1) | (n >>> 31);
6903 t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6904 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6905
6906 // 51
6907 n = w48 ^ w43 ^ w37 ^ w35;
6908 w51 = (n << 1) | (n >>> 31);
6909 t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6910 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6911
6912 // 52
6913 n = w49 ^ w44 ^ w38 ^ w36;
6914 w52 = (n << 1) | (n >>> 31);
6915 t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6916 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6917
6918 // 53
6919 n = w50 ^ w45 ^ w39 ^ w37;
6920 w53 = (n << 1) | (n >>> 31);
6921 t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6922 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6923
6924 // 54
6925 n = w51 ^ w46 ^ w40 ^ w38;
6926 w54 = (n << 1) | (n >>> 31);
6927 t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6928 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6929
6930 // 55
6931 n = w52 ^ w47 ^ w41 ^ w39;
6932 w55 = (n << 1) | (n >>> 31);
6933 t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6934 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6935
6936 // 56
6937 n = w53 ^ w48 ^ w42 ^ w40;
6938 w56 = (n << 1) | (n >>> 31);
6939 t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6940 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6941
6942 // 57
6943 n = w54 ^ w49 ^ w43 ^ w41;
6944 w57 = (n << 1) | (n >>> 31);
6945 t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6946 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6947
6948 // 58
6949 n = w55 ^ w50 ^ w44 ^ w42;
6950 w58 = (n << 1) | (n >>> 31);
6951 t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6952 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6953
6954 // 59
6955 n = w56 ^ w51 ^ w45 ^ w43;
6956 w59 = (n << 1) | (n >>> 31);
6957 t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6958 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6959
6960 // 60
6961 n = w57 ^ w52 ^ w46 ^ w44;
6962 w60 = (n << 1) | (n >>> 31);
6963 t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6964 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6965
6966 // 61
6967 n = w58 ^ w53 ^ w47 ^ w45;
6968 w61 = (n << 1) | (n >>> 31);
6969 t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6970 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6971
6972 // 62
6973 n = w59 ^ w54 ^ w48 ^ w46;
6974 w62 = (n << 1) | (n >>> 31);
6975 t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6976 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6977
6978 // 63
6979 n = w60 ^ w55 ^ w49 ^ w47;
6980 w63 = (n << 1) | (n >>> 31);
6981 t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6982 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6983
6984 // 64
6985 n = w61 ^ w56 ^ w50 ^ w48;
6986 w64 = (n << 1) | (n >>> 31);
6987 t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6988 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6989
6990 // 65
6991 n = w62 ^ w57 ^ w51 ^ w49;
6992 w65 = (n << 1) | (n >>> 31);
6993 t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6994 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6995
6996 // 66
6997 n = w63 ^ w58 ^ w52 ^ w50;
6998 w66 = (n << 1) | (n >>> 31);
6999 t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7000 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7001
7002 // 67
7003 n = w64 ^ w59 ^ w53 ^ w51;
7004 w67 = (n << 1) | (n >>> 31);
7005 t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7006 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7007
7008 // 68
7009 n = w65 ^ w60 ^ w54 ^ w52;
7010 w68 = (n << 1) | (n >>> 31);
7011 t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7012 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7013
7014 // 69
7015 n = w66 ^ w61 ^ w55 ^ w53;
7016 w69 = (n << 1) | (n >>> 31);
7017 t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7018 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7019
7020 // 70
7021 n = w67 ^ w62 ^ w56 ^ w54;
7022 w70 = (n << 1) | (n >>> 31);
7023 t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7024 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7025
7026 // 71
7027 n = w68 ^ w63 ^ w57 ^ w55;
7028 w71 = (n << 1) | (n >>> 31);
7029 t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7030 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7031
7032 // 72
7033 n = w69 ^ w64 ^ w58 ^ w56;
7034 w72 = (n << 1) | (n >>> 31);
7035 t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7036 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7037
7038 // 73
7039 n = w70 ^ w65 ^ w59 ^ w57;
7040 w73 = (n << 1) | (n >>> 31);
7041 t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7042 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7043
7044 // 74
7045 n = w71 ^ w66 ^ w60 ^ w58;
7046 w74 = (n << 1) | (n >>> 31);
7047 t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7048 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7049
7050 // 75
7051 n = w72 ^ w67 ^ w61 ^ w59;
7052 w75 = (n << 1) | (n >>> 31);
7053 t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7054 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7055
7056 // 76
7057 n = w73 ^ w68 ^ w62 ^ w60;
7058 w76 = (n << 1) | (n >>> 31);
7059 t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7060 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7061
7062 // 77
7063 n = w74 ^ w69 ^ w63 ^ w61;
7064 w77 = (n << 1) | (n >>> 31);
7065 t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7066 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7067
7068 // 78
7069 n = w75 ^ w70 ^ w64 ^ w62;
7070 w78 = (n << 1) | (n >>> 31);
7071 t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7072 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7073
7074 // 79
7075 n = w76 ^ w71 ^ w65 ^ w63;
7076 w79 = (n << 1) | (n >>> 31);
7077 t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7078 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7079
7080 H0 = ( H0 + a )|0;
7081 H1 = ( H1 + b )|0;
7082 H2 = ( H2 + c )|0;
7083 H3 = ( H3 + d )|0;
7084 H4 = ( H4 + e )|0;
7085
7086 }
7087
7088 function _core_heap ( offset ) {
7089 offset = offset|0;
7090
7091 _core(
7092 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7093 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7094 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7095 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7096 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7097 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7098 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7099 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7100 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7101 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7102 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7103 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7104 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7105 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7106 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7107 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7108 );
7109 }
7110
7111 // offset — multiple of 32
7112 function _state_to_heap ( output ) {
7113 output = output|0;
7114
7115 HEAP[output|0] = H0>>>24;
7116 HEAP[output|1] = H0>>>16&255;
7117 HEAP[output|2] = H0>>>8&255;
7118 HEAP[output|3] = H0&255;
7119 HEAP[output|4] = H1>>>24;
7120 HEAP[output|5] = H1>>>16&255;
7121 HEAP[output|6] = H1>>>8&255;
7122 HEAP[output|7] = H1&255;
7123 HEAP[output|8] = H2>>>24;
7124 HEAP[output|9] = H2>>>16&255;
7125 HEAP[output|10] = H2>>>8&255;
7126 HEAP[output|11] = H2&255;
7127 HEAP[output|12] = H3>>>24;
7128 HEAP[output|13] = H3>>>16&255;
7129 HEAP[output|14] = H3>>>8&255;
7130 HEAP[output|15] = H3&255;
7131 HEAP[output|16] = H4>>>24;
7132 HEAP[output|17] = H4>>>16&255;
7133 HEAP[output|18] = H4>>>8&255;
7134 HEAP[output|19] = H4&255;
7135 }
7136
7137 function reset () {
7138 H0 = 0x67452301;
7139 H1 = 0xefcdab89;
7140 H2 = 0x98badcfe;
7141 H3 = 0x10325476;
7142 H4 = 0xc3d2e1f0;
7143 TOTAL0 = TOTAL1 = 0;
7144 }
7145
7146 function init ( h0, h1, h2, h3, h4, total0, total1 ) {
7147 h0 = h0|0;
7148 h1 = h1|0;
7149 h2 = h2|0;
7150 h3 = h3|0;
7151 h4 = h4|0;
7152 total0 = total0|0;
7153 total1 = total1|0;
7154
7155 H0 = h0;
7156 H1 = h1;
7157 H2 = h2;
7158 H3 = h3;
7159 H4 = h4;
7160 TOTAL0 = total0;
7161 TOTAL1 = total1;
7162 }
7163
7164 // offset — multiple of 64
7165 function process ( offset, length ) {
7166 offset = offset|0;
7167 length = length|0;
7168
7169 var hashed = 0;
7170
7171 if ( offset & 63 )
7172 return -1;
7173
7174 while ( (length|0) >= 64 ) {
7175 _core_heap(offset);
7176
7177 offset = ( offset + 64 )|0;
7178 length = ( length - 64 )|0;
7179
7180 hashed = ( hashed + 64 )|0;
7181 }
7182
7183 TOTAL0 = ( TOTAL0 + hashed )|0;
7184 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
7185
7186 return hashed|0;
7187 }
7188
7189 // offset — multiple of 64
7190 // output — multiple of 32
7191 function finish ( offset, length, output ) {
7192 offset = offset|0;
7193 length = length|0;
7194 output = output|0;
7195
7196 var hashed = 0,
7197 i = 0;
7198
7199 if ( offset & 63 )
7200 return -1;
7201
7202 if ( ~output )
7203 if ( output & 31 )
7204 return -1;
7205
7206 if ( (length|0) >= 64 ) {
7207 hashed = process( offset, length )|0;
7208 if ( (hashed|0) == -1 )
7209 return -1;
7210
7211 offset = ( offset + hashed )|0;
7212 length = ( length - hashed )|0;
7213 }
7214
7215 hashed = ( hashed + length )|0;
7216 TOTAL0 = ( TOTAL0 + length )|0;
7217 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
7218
7219 HEAP[offset|length] = 0x80;
7220
7221 if ( (length|0) >= 56 ) {
7222 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
7223 HEAP[offset|i] = 0x00;
7224 _core_heap(offset);
7225
7226 length = 0;
7227
7228 HEAP[offset|0] = 0;
7229 }
7230
7231 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
7232 HEAP[offset|i] = 0;
7233
7234 HEAP[offset|56] = TOTAL1>>>21&255;
7235 HEAP[offset|57] = TOTAL1>>>13&255;
7236 HEAP[offset|58] = TOTAL1>>>5&255;
7237 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
7238 HEAP[offset|60] = TOTAL0>>>21&255;
7239 HEAP[offset|61] = TOTAL0>>>13&255;
7240 HEAP[offset|62] = TOTAL0>>>5&255;
7241 HEAP[offset|63] = TOTAL0<<3&255;
7242 _core_heap(offset);
7243
7244 if ( ~output )
7245 _state_to_heap(output);
7246
7247 return hashed|0;
7248 }
7249
7250 function hmac_reset () {
7251 H0 = I0;
7252 H1 = I1;
7253 H2 = I2;
7254 H3 = I3;
7255 H4 = I4;
7256 TOTAL0 = 64;
7257 TOTAL1 = 0;
7258 }
7259
7260 function _hmac_opad () {
7261 H0 = O0;
7262 H1 = O1;
7263 H2 = O2;
7264 H3 = O3;
7265 H4 = O4;
7266 TOTAL0 = 64;
7267 TOTAL1 = 0;
7268 }
7269
7270 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
7271 p0 = p0|0;
7272 p1 = p1|0;
7273 p2 = p2|0;
7274 p3 = p3|0;
7275 p4 = p4|0;
7276 p5 = p5|0;
7277 p6 = p6|0;
7278 p7 = p7|0;
7279 p8 = p8|0;
7280 p9 = p9|0;
7281 p10 = p10|0;
7282 p11 = p11|0;
7283 p12 = p12|0;
7284 p13 = p13|0;
7285 p14 = p14|0;
7286 p15 = p15|0;
7287
7288 // opad
7289 reset();
7290 _core(
7291 p0 ^ 0x5c5c5c5c,
7292 p1 ^ 0x5c5c5c5c,
7293 p2 ^ 0x5c5c5c5c,
7294 p3 ^ 0x5c5c5c5c,
7295 p4 ^ 0x5c5c5c5c,
7296 p5 ^ 0x5c5c5c5c,
7297 p6 ^ 0x5c5c5c5c,
7298 p7 ^ 0x5c5c5c5c,
7299 p8 ^ 0x5c5c5c5c,
7300 p9 ^ 0x5c5c5c5c,
7301 p10 ^ 0x5c5c5c5c,
7302 p11 ^ 0x5c5c5c5c,
7303 p12 ^ 0x5c5c5c5c,
7304 p13 ^ 0x5c5c5c5c,
7305 p14 ^ 0x5c5c5c5c,
7306 p15 ^ 0x5c5c5c5c
7307 );
7308 O0 = H0;
7309 O1 = H1;
7310 O2 = H2;
7311 O3 = H3;
7312 O4 = H4;
7313
7314 // ipad
7315 reset();
7316 _core(
7317 p0 ^ 0x36363636,
7318 p1 ^ 0x36363636,
7319 p2 ^ 0x36363636,
7320 p3 ^ 0x36363636,
7321 p4 ^ 0x36363636,
7322 p5 ^ 0x36363636,
7323 p6 ^ 0x36363636,
7324 p7 ^ 0x36363636,
7325 p8 ^ 0x36363636,
7326 p9 ^ 0x36363636,
7327 p10 ^ 0x36363636,
7328 p11 ^ 0x36363636,
7329 p12 ^ 0x36363636,
7330 p13 ^ 0x36363636,
7331 p14 ^ 0x36363636,
7332 p15 ^ 0x36363636
7333 );
7334 I0 = H0;
7335 I1 = H1;
7336 I2 = H2;
7337 I3 = H3;
7338 I4 = H4;
7339
7340 TOTAL0 = 64;
7341 TOTAL1 = 0;
7342 }
7343
7344 // offset — multiple of 64
7345 // output — multiple of 32
7346 function hmac_finish ( offset, length, output ) {
7347 offset = offset|0;
7348 length = length|0;
7349 output = output|0;
7350
7351 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
7352
7353 if ( offset & 63 )
7354 return -1;
7355
7356 if ( ~output )
7357 if ( output & 31 )
7358 return -1;
7359
7360 hashed = finish( offset, length, -1 )|0;
7361 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7362
7363 _hmac_opad();
7364 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7365
7366 if ( ~output )
7367 _state_to_heap(output);
7368
7369 return hashed|0;
7370 }
7371
7372 // salt is assumed to be already processed
7373 // offset — multiple of 64
7374 // output — multiple of 32
7375 function pbkdf2_generate_block ( offset, length, block, count, output ) {
7376 offset = offset|0;
7377 length = length|0;
7378 block = block|0;
7379 count = count|0;
7380 output = output|0;
7381
7382 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
7383 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
7384
7385 if ( offset & 63 )
7386 return -1;
7387
7388 if ( ~output )
7389 if ( output & 31 )
7390 return -1;
7391
7392 // pad block number into heap
7393 // FIXME probable OOB write
7394 HEAP[(offset+length)|0] = block>>>24;
7395 HEAP[(offset+length+1)|0] = block>>>16&255;
7396 HEAP[(offset+length+2)|0] = block>>>8&255;
7397 HEAP[(offset+length+3)|0] = block&255;
7398
7399 // finish first iteration
7400 hmac_finish( offset, (length+4)|0, -1 )|0;
7401 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
7402 count = (count-1)|0;
7403
7404 // perform the rest iterations
7405 while ( (count|0) > 0 ) {
7406 hmac_reset();
7407 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7408 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7409
7410 _hmac_opad();
7411 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7412 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7413
7414 h0 = h0 ^ H0;
7415 h1 = h1 ^ H1;
7416 h2 = h2 ^ H2;
7417 h3 = h3 ^ H3;
7418 h4 = h4 ^ H4;
7419
7420 count = (count-1)|0;
7421 }
7422
7423 H0 = h0;
7424 H1 = h1;
7425 H2 = h2;
7426 H3 = h3;
7427 H4 = h4;
7428
7429 if ( ~output )
7430 _state_to_heap(output);
7431
7432 return 0;
7433 }
7434
7435 return {
7436 // SHA1
7437 reset: reset,
7438 init: init,
7439 process: process,
7440 finish: finish,
7441
7442 // HMAC-SHA1
7443 hmac_reset: hmac_reset,
7444 hmac_init: hmac_init,
7445 hmac_finish: hmac_finish,
7446
7447 // PBKDF2-HMAC-SHA1
7448 pbkdf2_generate_block: pbkdf2_generate_block
7449 }
7450};
7451
7452class Hash {
7453 constructor() {
7454 this.pos = 0;
7455 this.len = 0;
7456 }
7457 reset() {
7458 const { asm } = this.acquire_asm();
7459 this.result = null;
7460 this.pos = 0;
7461 this.len = 0;
7462 asm.reset();
7463 return this;
7464 }
7465 process(data) {
7466 if (this.result !== null)
7467 throw new IllegalStateError('state must be reset before processing new data');
7468 const { asm, heap } = this.acquire_asm();
7469 let hpos = this.pos;
7470 let hlen = this.len;
7471 let dpos = 0;
7472 let dlen = data.length;
7473 let wlen = 0;
7474 while (dlen > 0) {
7475 wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
7476 hlen += wlen;
7477 dpos += wlen;
7478 dlen -= wlen;
7479 wlen = asm.process(hpos, hlen);
7480 hpos += wlen;
7481 hlen -= wlen;
7482 if (!hlen)
7483 hpos = 0;
7484 }
7485 this.pos = hpos;
7486 this.len = hlen;
7487 return this;
7488 }
7489 finish() {
7490 if (this.result !== null)
7491 throw new IllegalStateError('state must be reset before processing new data');
7492 const { asm, heap } = this.acquire_asm();
7493 asm.finish(this.pos, this.len, 0);
7494 this.result = new Uint8Array(this.HASH_SIZE);
7495 this.result.set(heap.subarray(0, this.HASH_SIZE));
7496 this.pos = 0;
7497 this.len = 0;
7498 this.release_asm();
7499 return this;
7500 }
7501}
7502
7503const _sha1_block_size = 64;
7504const _sha1_hash_size = 20;
7505const heap_pool$1 = [];
7506const asm_pool$1 = [];
7507class Sha1 extends Hash {
7508 constructor() {
7509 super();
7510 this.NAME = 'sha1';
7511 this.BLOCK_SIZE = _sha1_block_size;
7512 this.HASH_SIZE = _sha1_hash_size;
7513 this.acquire_asm();
7514 }
7515 acquire_asm() {
7516 if (this.heap === undefined || this.asm === undefined) {
7517 this.heap = heap_pool$1.pop() || _heap_init();
7518 this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
7519 this.reset();
7520 }
7521 return { heap: this.heap, asm: this.asm };
7522 }
7523 release_asm() {
7524 if (this.heap !== undefined && this.asm !== undefined) {
7525 heap_pool$1.push(this.heap);
7526 asm_pool$1.push(this.asm);
7527 }
7528 this.heap = undefined;
7529 this.asm = undefined;
7530 }
7531 static bytes(data) {
7532 return new Sha1().process(data).finish().result;
7533 }
7534}
7535Sha1.NAME = 'sha1';
7536Sha1.heap_pool = [];
7537Sha1.asm_pool = [];
7538Sha1.asm_function = sha1_asm;
7539
7540var sha256_asm = function ( stdlib, foreign, buffer ) {
7541 "use asm";
7542
7543 // SHA256 state
7544 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
7545 TOTAL0 = 0, TOTAL1 = 0;
7546
7547 // HMAC state
7548 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
7549 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
7550
7551 // I/O buffer
7552 var HEAP = new stdlib.Uint8Array(buffer);
7553
7554 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
7555 w0 = w0|0;
7556 w1 = w1|0;
7557 w2 = w2|0;
7558 w3 = w3|0;
7559 w4 = w4|0;
7560 w5 = w5|0;
7561 w6 = w6|0;
7562 w7 = w7|0;
7563 w8 = w8|0;
7564 w9 = w9|0;
7565 w10 = w10|0;
7566 w11 = w11|0;
7567 w12 = w12|0;
7568 w13 = w13|0;
7569 w14 = w14|0;
7570 w15 = w15|0;
7571
7572 var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
7573
7574 a = H0;
7575 b = H1;
7576 c = H2;
7577 d = H3;
7578 e = H4;
7579 f = H5;
7580 g = H6;
7581 h = H7;
7582
7583 // 0
7584 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
7585 d = ( d + h )|0;
7586 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7587
7588 // 1
7589 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
7590 c = ( c + g )|0;
7591 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7592
7593 // 2
7594 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
7595 b = ( b + f )|0;
7596 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7597
7598 // 3
7599 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
7600 a = ( a + e )|0;
7601 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7602
7603 // 4
7604 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
7605 h = ( h + d )|0;
7606 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7607
7608 // 5
7609 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
7610 g = ( g + c )|0;
7611 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7612
7613 // 6
7614 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
7615 f = ( f + b )|0;
7616 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7617
7618 // 7
7619 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
7620 e = ( e + a )|0;
7621 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7622
7623 // 8
7624 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
7625 d = ( d + h )|0;
7626 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7627
7628 // 9
7629 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
7630 c = ( c + g )|0;
7631 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7632
7633 // 10
7634 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
7635 b = ( b + f )|0;
7636 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7637
7638 // 11
7639 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
7640 a = ( a + e )|0;
7641 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7642
7643 // 12
7644 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
7645 h = ( h + d )|0;
7646 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7647
7648 // 13
7649 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
7650 g = ( g + c )|0;
7651 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7652
7653 // 14
7654 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
7655 f = ( f + b )|0;
7656 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7657
7658 // 15
7659 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
7660 e = ( e + a )|0;
7661 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7662
7663 // 16
7664 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7665 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
7666 d = ( d + h )|0;
7667 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7668
7669 // 17
7670 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7671 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
7672 c = ( c + g )|0;
7673 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7674
7675 // 18
7676 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7677 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
7678 b = ( b + f )|0;
7679 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7680
7681 // 19
7682 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7683 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
7684 a = ( a + e )|0;
7685 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7686
7687 // 20
7688 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7689 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
7690 h = ( h + d )|0;
7691 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7692
7693 // 21
7694 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7695 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
7696 g = ( g + c )|0;
7697 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7698
7699 // 22
7700 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7701 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
7702 f = ( f + b )|0;
7703 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7704
7705 // 23
7706 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7707 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
7708 e = ( e + a )|0;
7709 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7710
7711 // 24
7712 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7713 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
7714 d = ( d + h )|0;
7715 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7716
7717 // 25
7718 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7719 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
7720 c = ( c + g )|0;
7721 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7722
7723 // 26
7724 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7725 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
7726 b = ( b + f )|0;
7727 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7728
7729 // 27
7730 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7731 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
7732 a = ( a + e )|0;
7733 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7734
7735 // 28
7736 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7737 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
7738 h = ( h + d )|0;
7739 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7740
7741 // 29
7742 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7743 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
7744 g = ( g + c )|0;
7745 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7746
7747 // 30
7748 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7749 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
7750 f = ( f + b )|0;
7751 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7752
7753 // 31
7754 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7755 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
7756 e = ( e + a )|0;
7757 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7758
7759 // 32
7760 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7761 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
7762 d = ( d + h )|0;
7763 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7764
7765 // 33
7766 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7767 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
7768 c = ( c + g )|0;
7769 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7770
7771 // 34
7772 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7773 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
7774 b = ( b + f )|0;
7775 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7776
7777 // 35
7778 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7779 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
7780 a = ( a + e )|0;
7781 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7782
7783 // 36
7784 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7785 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
7786 h = ( h + d )|0;
7787 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7788
7789 // 37
7790 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7791 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
7792 g = ( g + c )|0;
7793 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7794
7795 // 38
7796 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7797 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
7798 f = ( f + b )|0;
7799 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7800
7801 // 39
7802 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7803 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
7804 e = ( e + a )|0;
7805 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7806
7807 // 40
7808 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7809 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
7810 d = ( d + h )|0;
7811 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7812
7813 // 41
7814 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7815 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
7816 c = ( c + g )|0;
7817 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7818
7819 // 42
7820 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7821 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
7822 b = ( b + f )|0;
7823 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7824
7825 // 43
7826 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7827 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
7828 a = ( a + e )|0;
7829 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7830
7831 // 44
7832 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7833 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
7834 h = ( h + d )|0;
7835 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7836
7837 // 45
7838 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7839 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
7840 g = ( g + c )|0;
7841 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7842
7843 // 46
7844 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7845 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
7846 f = ( f + b )|0;
7847 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7848
7849 // 47
7850 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7851 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
7852 e = ( e + a )|0;
7853 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7854
7855 // 48
7856 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7857 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
7858 d = ( d + h )|0;
7859 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7860
7861 // 49
7862 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7863 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
7864 c = ( c + g )|0;
7865 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7866
7867 // 50
7868 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7869 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
7870 b = ( b + f )|0;
7871 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7872
7873 // 51
7874 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7875 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
7876 a = ( a + e )|0;
7877 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7878
7879 // 52
7880 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7881 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
7882 h = ( h + d )|0;
7883 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7884
7885 // 53
7886 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7887 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
7888 g = ( g + c )|0;
7889 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7890
7891 // 54
7892 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7893 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
7894 f = ( f + b )|0;
7895 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7896
7897 // 55
7898 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7899 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
7900 e = ( e + a )|0;
7901 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7902
7903 // 56
7904 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7905 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
7906 d = ( d + h )|0;
7907 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7908
7909 // 57
7910 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7911 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
7912 c = ( c + g )|0;
7913 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7914
7915 // 58
7916 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7917 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
7918 b = ( b + f )|0;
7919 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7920
7921 // 59
7922 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7923 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
7924 a = ( a + e )|0;
7925 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7926
7927 // 60
7928 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7929 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
7930 h = ( h + d )|0;
7931 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7932
7933 // 61
7934 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7935 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
7936 g = ( g + c )|0;
7937 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7938
7939 // 62
7940 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7941 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
7942 f = ( f + b )|0;
7943 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7944
7945 // 63
7946 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7947 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
7948 e = ( e + a )|0;
7949 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7950
7951 H0 = ( H0 + a )|0;
7952 H1 = ( H1 + b )|0;
7953 H2 = ( H2 + c )|0;
7954 H3 = ( H3 + d )|0;
7955 H4 = ( H4 + e )|0;
7956 H5 = ( H5 + f )|0;
7957 H6 = ( H6 + g )|0;
7958 H7 = ( H7 + h )|0;
7959 }
7960
7961 function _core_heap ( offset ) {
7962 offset = offset|0;
7963
7964 _core(
7965 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7966 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7967 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7968 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7969 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7970 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7971 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7972 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7973 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7974 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7975 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7976 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7977 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7978 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7979 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7980 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7981 );
7982 }
7983
7984 // offset — multiple of 32
7985 function _state_to_heap ( output ) {
7986 output = output|0;
7987
7988 HEAP[output|0] = H0>>>24;
7989 HEAP[output|1] = H0>>>16&255;
7990 HEAP[output|2] = H0>>>8&255;
7991 HEAP[output|3] = H0&255;
7992 HEAP[output|4] = H1>>>24;
7993 HEAP[output|5] = H1>>>16&255;
7994 HEAP[output|6] = H1>>>8&255;
7995 HEAP[output|7] = H1&255;
7996 HEAP[output|8] = H2>>>24;
7997 HEAP[output|9] = H2>>>16&255;
7998 HEAP[output|10] = H2>>>8&255;
7999 HEAP[output|11] = H2&255;
8000 HEAP[output|12] = H3>>>24;
8001 HEAP[output|13] = H3>>>16&255;
8002 HEAP[output|14] = H3>>>8&255;
8003 HEAP[output|15] = H3&255;
8004 HEAP[output|16] = H4>>>24;
8005 HEAP[output|17] = H4>>>16&255;
8006 HEAP[output|18] = H4>>>8&255;
8007 HEAP[output|19] = H4&255;
8008 HEAP[output|20] = H5>>>24;
8009 HEAP[output|21] = H5>>>16&255;
8010 HEAP[output|22] = H5>>>8&255;
8011 HEAP[output|23] = H5&255;
8012 HEAP[output|24] = H6>>>24;
8013 HEAP[output|25] = H6>>>16&255;
8014 HEAP[output|26] = H6>>>8&255;
8015 HEAP[output|27] = H6&255;
8016 HEAP[output|28] = H7>>>24;
8017 HEAP[output|29] = H7>>>16&255;
8018 HEAP[output|30] = H7>>>8&255;
8019 HEAP[output|31] = H7&255;
8020 }
8021
8022 function reset () {
8023 H0 = 0x6a09e667;
8024 H1 = 0xbb67ae85;
8025 H2 = 0x3c6ef372;
8026 H3 = 0xa54ff53a;
8027 H4 = 0x510e527f;
8028 H5 = 0x9b05688c;
8029 H6 = 0x1f83d9ab;
8030 H7 = 0x5be0cd19;
8031 TOTAL0 = TOTAL1 = 0;
8032 }
8033
8034 function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
8035 h0 = h0|0;
8036 h1 = h1|0;
8037 h2 = h2|0;
8038 h3 = h3|0;
8039 h4 = h4|0;
8040 h5 = h5|0;
8041 h6 = h6|0;
8042 h7 = h7|0;
8043 total0 = total0|0;
8044 total1 = total1|0;
8045
8046 H0 = h0;
8047 H1 = h1;
8048 H2 = h2;
8049 H3 = h3;
8050 H4 = h4;
8051 H5 = h5;
8052 H6 = h6;
8053 H7 = h7;
8054 TOTAL0 = total0;
8055 TOTAL1 = total1;
8056 }
8057
8058 // offset — multiple of 64
8059 function process ( offset, length ) {
8060 offset = offset|0;
8061 length = length|0;
8062
8063 var hashed = 0;
8064
8065 if ( offset & 63 )
8066 return -1;
8067
8068 while ( (length|0) >= 64 ) {
8069 _core_heap(offset);
8070
8071 offset = ( offset + 64 )|0;
8072 length = ( length - 64 )|0;
8073
8074 hashed = ( hashed + 64 )|0;
8075 }
8076
8077 TOTAL0 = ( TOTAL0 + hashed )|0;
8078 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8079
8080 return hashed|0;
8081 }
8082
8083 // offset — multiple of 64
8084 // output — multiple of 32
8085 function finish ( offset, length, output ) {
8086 offset = offset|0;
8087 length = length|0;
8088 output = output|0;
8089
8090 var hashed = 0,
8091 i = 0;
8092
8093 if ( offset & 63 )
8094 return -1;
8095
8096 if ( ~output )
8097 if ( output & 31 )
8098 return -1;
8099
8100 if ( (length|0) >= 64 ) {
8101 hashed = process( offset, length )|0;
8102 if ( (hashed|0) == -1 )
8103 return -1;
8104
8105 offset = ( offset + hashed )|0;
8106 length = ( length - hashed )|0;
8107 }
8108
8109 hashed = ( hashed + length )|0;
8110 TOTAL0 = ( TOTAL0 + length )|0;
8111 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8112
8113 HEAP[offset|length] = 0x80;
8114
8115 if ( (length|0) >= 56 ) {
8116 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
8117 HEAP[offset|i] = 0x00;
8118
8119 _core_heap(offset);
8120
8121 length = 0;
8122
8123 HEAP[offset|0] = 0;
8124 }
8125
8126 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
8127 HEAP[offset|i] = 0;
8128
8129 HEAP[offset|56] = TOTAL1>>>21&255;
8130 HEAP[offset|57] = TOTAL1>>>13&255;
8131 HEAP[offset|58] = TOTAL1>>>5&255;
8132 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
8133 HEAP[offset|60] = TOTAL0>>>21&255;
8134 HEAP[offset|61] = TOTAL0>>>13&255;
8135 HEAP[offset|62] = TOTAL0>>>5&255;
8136 HEAP[offset|63] = TOTAL0<<3&255;
8137 _core_heap(offset);
8138
8139 if ( ~output )
8140 _state_to_heap(output);
8141
8142 return hashed|0;
8143 }
8144
8145 function hmac_reset () {
8146 H0 = I0;
8147 H1 = I1;
8148 H2 = I2;
8149 H3 = I3;
8150 H4 = I4;
8151 H5 = I5;
8152 H6 = I6;
8153 H7 = I7;
8154 TOTAL0 = 64;
8155 TOTAL1 = 0;
8156 }
8157
8158 function _hmac_opad () {
8159 H0 = O0;
8160 H1 = O1;
8161 H2 = O2;
8162 H3 = O3;
8163 H4 = O4;
8164 H5 = O5;
8165 H6 = O6;
8166 H7 = O7;
8167 TOTAL0 = 64;
8168 TOTAL1 = 0;
8169 }
8170
8171 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
8172 p0 = p0|0;
8173 p1 = p1|0;
8174 p2 = p2|0;
8175 p3 = p3|0;
8176 p4 = p4|0;
8177 p5 = p5|0;
8178 p6 = p6|0;
8179 p7 = p7|0;
8180 p8 = p8|0;
8181 p9 = p9|0;
8182 p10 = p10|0;
8183 p11 = p11|0;
8184 p12 = p12|0;
8185 p13 = p13|0;
8186 p14 = p14|0;
8187 p15 = p15|0;
8188
8189 // opad
8190 reset();
8191 _core(
8192 p0 ^ 0x5c5c5c5c,
8193 p1 ^ 0x5c5c5c5c,
8194 p2 ^ 0x5c5c5c5c,
8195 p3 ^ 0x5c5c5c5c,
8196 p4 ^ 0x5c5c5c5c,
8197 p5 ^ 0x5c5c5c5c,
8198 p6 ^ 0x5c5c5c5c,
8199 p7 ^ 0x5c5c5c5c,
8200 p8 ^ 0x5c5c5c5c,
8201 p9 ^ 0x5c5c5c5c,
8202 p10 ^ 0x5c5c5c5c,
8203 p11 ^ 0x5c5c5c5c,
8204 p12 ^ 0x5c5c5c5c,
8205 p13 ^ 0x5c5c5c5c,
8206 p14 ^ 0x5c5c5c5c,
8207 p15 ^ 0x5c5c5c5c
8208 );
8209 O0 = H0;
8210 O1 = H1;
8211 O2 = H2;
8212 O3 = H3;
8213 O4 = H4;
8214 O5 = H5;
8215 O6 = H6;
8216 O7 = H7;
8217
8218 // ipad
8219 reset();
8220 _core(
8221 p0 ^ 0x36363636,
8222 p1 ^ 0x36363636,
8223 p2 ^ 0x36363636,
8224 p3 ^ 0x36363636,
8225 p4 ^ 0x36363636,
8226 p5 ^ 0x36363636,
8227 p6 ^ 0x36363636,
8228 p7 ^ 0x36363636,
8229 p8 ^ 0x36363636,
8230 p9 ^ 0x36363636,
8231 p10 ^ 0x36363636,
8232 p11 ^ 0x36363636,
8233 p12 ^ 0x36363636,
8234 p13 ^ 0x36363636,
8235 p14 ^ 0x36363636,
8236 p15 ^ 0x36363636
8237 );
8238 I0 = H0;
8239 I1 = H1;
8240 I2 = H2;
8241 I3 = H3;
8242 I4 = H4;
8243 I5 = H5;
8244 I6 = H6;
8245 I7 = H7;
8246
8247 TOTAL0 = 64;
8248 TOTAL1 = 0;
8249 }
8250
8251 // offset — multiple of 64
8252 // output — multiple of 32
8253 function hmac_finish ( offset, length, output ) {
8254 offset = offset|0;
8255 length = length|0;
8256 output = output|0;
8257
8258 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
8259 hashed = 0;
8260
8261 if ( offset & 63 )
8262 return -1;
8263
8264 if ( ~output )
8265 if ( output & 31 )
8266 return -1;
8267
8268 hashed = finish( offset, length, -1 )|0;
8269 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8270
8271 _hmac_opad();
8272 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8273
8274 if ( ~output )
8275 _state_to_heap(output);
8276
8277 return hashed|0;
8278 }
8279
8280 // salt is assumed to be already processed
8281 // offset — multiple of 64
8282 // output — multiple of 32
8283 function pbkdf2_generate_block ( offset, length, block, count, output ) {
8284 offset = offset|0;
8285 length = length|0;
8286 block = block|0;
8287 count = count|0;
8288 output = output|0;
8289
8290 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
8291 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
8292
8293 if ( offset & 63 )
8294 return -1;
8295
8296 if ( ~output )
8297 if ( output & 31 )
8298 return -1;
8299
8300 // pad block number into heap
8301 // FIXME probable OOB write
8302 HEAP[(offset+length)|0] = block>>>24;
8303 HEAP[(offset+length+1)|0] = block>>>16&255;
8304 HEAP[(offset+length+2)|0] = block>>>8&255;
8305 HEAP[(offset+length+3)|0] = block&255;
8306
8307 // finish first iteration
8308 hmac_finish( offset, (length+4)|0, -1 )|0;
8309 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
8310 count = (count-1)|0;
8311
8312 // perform the rest iterations
8313 while ( (count|0) > 0 ) {
8314 hmac_reset();
8315 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8316 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8317
8318 _hmac_opad();
8319 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8320 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8321
8322 h0 = h0 ^ H0;
8323 h1 = h1 ^ H1;
8324 h2 = h2 ^ H2;
8325 h3 = h3 ^ H3;
8326 h4 = h4 ^ H4;
8327 h5 = h5 ^ H5;
8328 h6 = h6 ^ H6;
8329 h7 = h7 ^ H7;
8330
8331 count = (count-1)|0;
8332 }
8333
8334 H0 = h0;
8335 H1 = h1;
8336 H2 = h2;
8337 H3 = h3;
8338 H4 = h4;
8339 H5 = h5;
8340 H6 = h6;
8341 H7 = h7;
8342
8343 if ( ~output )
8344 _state_to_heap(output);
8345
8346 return 0;
8347 }
8348
8349 return {
8350 // SHA256
8351 reset: reset,
8352 init: init,
8353 process: process,
8354 finish: finish,
8355
8356 // HMAC-SHA256
8357 hmac_reset: hmac_reset,
8358 hmac_init: hmac_init,
8359 hmac_finish: hmac_finish,
8360
8361 // PBKDF2-HMAC-SHA256
8362 pbkdf2_generate_block: pbkdf2_generate_block
8363 }
8364};
8365
8366const _sha256_block_size = 64;
8367const _sha256_hash_size = 32;
8368const heap_pool$2 = [];
8369const asm_pool$2 = [];
8370class Sha256 extends Hash {
8371 constructor() {
8372 super();
8373 this.NAME = 'sha256';
8374 this.BLOCK_SIZE = _sha256_block_size;
8375 this.HASH_SIZE = _sha256_hash_size;
8376 this.acquire_asm();
8377 }
8378 acquire_asm() {
8379 if (this.heap === undefined || this.asm === undefined) {
8380 this.heap = heap_pool$2.pop() || _heap_init();
8381 this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
8382 this.reset();
8383 }
8384 return { heap: this.heap, asm: this.asm };
8385 }
8386 release_asm() {
8387 if (this.heap !== undefined && this.asm !== undefined) {
8388 heap_pool$2.push(this.heap);
8389 asm_pool$2.push(this.asm);
8390 }
8391 this.heap = undefined;
8392 this.asm = undefined;
8393 }
8394 static bytes(data) {
8395 return new Sha256().process(data).finish().result;
8396 }
8397}
8398Sha256.NAME = 'sha256';
8399
8400var minimalisticAssert = assert;
8401
8402function assert(val, msg) {
8403 if (!val)
8404 throw new Error(msg || 'Assertion failed');
8405}
8406
8407assert.equal = function assertEqual(l, r, msg) {
8408 if (l != r)
8409 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
8410};
8411
8412var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8413
8414function createCommonjsModule(fn, module) {
8415 return module = { exports: {} }, fn(module, module.exports), module.exports;
8416}
8417
8418function commonjsRequire () {
8419 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
8420}
8421
8422var inherits_browser = createCommonjsModule(function (module) {
8423if (typeof Object.create === 'function') {
8424 // implementation from standard node.js 'util' module
8425 module.exports = function inherits(ctor, superCtor) {
8426 ctor.super_ = superCtor;
8427 ctor.prototype = Object.create(superCtor.prototype, {
8428 constructor: {
8429 value: ctor,
8430 enumerable: false,
8431 writable: true,
8432 configurable: true
8433 }
8434 });
8435 };
8436} else {
8437 // old school shim for old browsers
8438 module.exports = function inherits(ctor, superCtor) {
8439 ctor.super_ = superCtor;
8440 var TempCtor = function () {};
8441 TempCtor.prototype = superCtor.prototype;
8442 ctor.prototype = new TempCtor();
8443 ctor.prototype.constructor = ctor;
8444 };
8445}
8446});
8447
8448var inherits = createCommonjsModule(function (module) {
8449try {
8450 var util = util__default['default'];
8451 if (typeof util.inherits !== 'function') throw '';
8452 module.exports = util.inherits;
8453} catch (e) {
8454 module.exports = inherits_browser;
8455}
8456});
8457
8458var inherits_1 = inherits;
8459
8460function toArray(msg, enc) {
8461 if (Array.isArray(msg))
8462 return msg.slice();
8463 if (!msg)
8464 return [];
8465 var res = [];
8466 if (typeof msg === 'string') {
8467 if (!enc) {
8468 for (var i = 0; i < msg.length; i++) {
8469 var c = msg.charCodeAt(i);
8470 var hi = c >> 8;
8471 var lo = c & 0xff;
8472 if (hi)
8473 res.push(hi, lo);
8474 else
8475 res.push(lo);
8476 }
8477 } else if (enc === 'hex') {
8478 msg = msg.replace(/[^a-z0-9]+/ig, '');
8479 if (msg.length % 2 !== 0)
8480 msg = '0' + msg;
8481 for (i = 0; i < msg.length; i += 2)
8482 res.push(parseInt(msg[i] + msg[i + 1], 16));
8483 }
8484 } else {
8485 for (i = 0; i < msg.length; i++)
8486 res[i] = msg[i] | 0;
8487 }
8488 return res;
8489}
8490var toArray_1 = toArray;
8491
8492function toHex(msg) {
8493 var res = '';
8494 for (var i = 0; i < msg.length; i++)
8495 res += zero2(msg[i].toString(16));
8496 return res;
8497}
8498var toHex_1 = toHex;
8499
8500function htonl(w) {
8501 var res = (w >>> 24) |
8502 ((w >>> 8) & 0xff00) |
8503 ((w << 8) & 0xff0000) |
8504 ((w & 0xff) << 24);
8505 return res >>> 0;
8506}
8507var htonl_1 = htonl;
8508
8509function toHex32(msg, endian) {
8510 var res = '';
8511 for (var i = 0; i < msg.length; i++) {
8512 var w = msg[i];
8513 if (endian === 'little')
8514 w = htonl(w);
8515 res += zero8(w.toString(16));
8516 }
8517 return res;
8518}
8519var toHex32_1 = toHex32;
8520
8521function zero2(word) {
8522 if (word.length === 1)
8523 return '0' + word;
8524 else
8525 return word;
8526}
8527var zero2_1 = zero2;
8528
8529function zero8(word) {
8530 if (word.length === 7)
8531 return '0' + word;
8532 else if (word.length === 6)
8533 return '00' + word;
8534 else if (word.length === 5)
8535 return '000' + word;
8536 else if (word.length === 4)
8537 return '0000' + word;
8538 else if (word.length === 3)
8539 return '00000' + word;
8540 else if (word.length === 2)
8541 return '000000' + word;
8542 else if (word.length === 1)
8543 return '0000000' + word;
8544 else
8545 return word;
8546}
8547var zero8_1 = zero8;
8548
8549function join32(msg, start, end, endian) {
8550 var len = end - start;
8551 minimalisticAssert(len % 4 === 0);
8552 var res = new Array(len / 4);
8553 for (var i = 0, k = start; i < res.length; i++, k += 4) {
8554 var w;
8555 if (endian === 'big')
8556 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
8557 else
8558 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
8559 res[i] = w >>> 0;
8560 }
8561 return res;
8562}
8563var join32_1 = join32;
8564
8565function split32(msg, endian) {
8566 var res = new Array(msg.length * 4);
8567 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
8568 var m = msg[i];
8569 if (endian === 'big') {
8570 res[k] = m >>> 24;
8571 res[k + 1] = (m >>> 16) & 0xff;
8572 res[k + 2] = (m >>> 8) & 0xff;
8573 res[k + 3] = m & 0xff;
8574 } else {
8575 res[k + 3] = m >>> 24;
8576 res[k + 2] = (m >>> 16) & 0xff;
8577 res[k + 1] = (m >>> 8) & 0xff;
8578 res[k] = m & 0xff;
8579 }
8580 }
8581 return res;
8582}
8583var split32_1 = split32;
8584
8585function rotr32(w, b) {
8586 return (w >>> b) | (w << (32 - b));
8587}
8588var rotr32_1 = rotr32;
8589
8590function rotl32(w, b) {
8591 return (w << b) | (w >>> (32 - b));
8592}
8593var rotl32_1 = rotl32;
8594
8595function sum32(a, b) {
8596 return (a + b) >>> 0;
8597}
8598var sum32_1 = sum32;
8599
8600function sum32_3(a, b, c) {
8601 return (a + b + c) >>> 0;
8602}
8603var sum32_3_1 = sum32_3;
8604
8605function sum32_4(a, b, c, d) {
8606 return (a + b + c + d) >>> 0;
8607}
8608var sum32_4_1 = sum32_4;
8609
8610function sum32_5(a, b, c, d, e) {
8611 return (a + b + c + d + e) >>> 0;
8612}
8613var sum32_5_1 = sum32_5;
8614
8615function sum64(buf, pos, ah, al) {
8616 var bh = buf[pos];
8617 var bl = buf[pos + 1];
8618
8619 var lo = (al + bl) >>> 0;
8620 var hi = (lo < al ? 1 : 0) + ah + bh;
8621 buf[pos] = hi >>> 0;
8622 buf[pos + 1] = lo;
8623}
8624var sum64_1 = sum64;
8625
8626function sum64_hi(ah, al, bh, bl) {
8627 var lo = (al + bl) >>> 0;
8628 var hi = (lo < al ? 1 : 0) + ah + bh;
8629 return hi >>> 0;
8630}
8631var sum64_hi_1 = sum64_hi;
8632
8633function sum64_lo(ah, al, bh, bl) {
8634 var lo = al + bl;
8635 return lo >>> 0;
8636}
8637var sum64_lo_1 = sum64_lo;
8638
8639function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
8640 var carry = 0;
8641 var lo = al;
8642 lo = (lo + bl) >>> 0;
8643 carry += lo < al ? 1 : 0;
8644 lo = (lo + cl) >>> 0;
8645 carry += lo < cl ? 1 : 0;
8646 lo = (lo + dl) >>> 0;
8647 carry += lo < dl ? 1 : 0;
8648
8649 var hi = ah + bh + ch + dh + carry;
8650 return hi >>> 0;
8651}
8652var sum64_4_hi_1 = sum64_4_hi;
8653
8654function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
8655 var lo = al + bl + cl + dl;
8656 return lo >>> 0;
8657}
8658var sum64_4_lo_1 = sum64_4_lo;
8659
8660function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8661 var carry = 0;
8662 var lo = al;
8663 lo = (lo + bl) >>> 0;
8664 carry += lo < al ? 1 : 0;
8665 lo = (lo + cl) >>> 0;
8666 carry += lo < cl ? 1 : 0;
8667 lo = (lo + dl) >>> 0;
8668 carry += lo < dl ? 1 : 0;
8669 lo = (lo + el) >>> 0;
8670 carry += lo < el ? 1 : 0;
8671
8672 var hi = ah + bh + ch + dh + eh + carry;
8673 return hi >>> 0;
8674}
8675var sum64_5_hi_1 = sum64_5_hi;
8676
8677function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8678 var lo = al + bl + cl + dl + el;
8679
8680 return lo >>> 0;
8681}
8682var sum64_5_lo_1 = sum64_5_lo;
8683
8684function rotr64_hi(ah, al, num) {
8685 var r = (al << (32 - num)) | (ah >>> num);
8686 return r >>> 0;
8687}
8688var rotr64_hi_1 = rotr64_hi;
8689
8690function rotr64_lo(ah, al, num) {
8691 var r = (ah << (32 - num)) | (al >>> num);
8692 return r >>> 0;
8693}
8694var rotr64_lo_1 = rotr64_lo;
8695
8696function shr64_hi(ah, al, num) {
8697 return ah >>> num;
8698}
8699var shr64_hi_1 = shr64_hi;
8700
8701function shr64_lo(ah, al, num) {
8702 var r = (ah << (32 - num)) | (al >>> num);
8703 return r >>> 0;
8704}
8705var shr64_lo_1 = shr64_lo;
8706
8707var utils = {
8708 inherits: inherits_1,
8709 toArray: toArray_1,
8710 toHex: toHex_1,
8711 htonl: htonl_1,
8712 toHex32: toHex32_1,
8713 zero2: zero2_1,
8714 zero8: zero8_1,
8715 join32: join32_1,
8716 split32: split32_1,
8717 rotr32: rotr32_1,
8718 rotl32: rotl32_1,
8719 sum32: sum32_1,
8720 sum32_3: sum32_3_1,
8721 sum32_4: sum32_4_1,
8722 sum32_5: sum32_5_1,
8723 sum64: sum64_1,
8724 sum64_hi: sum64_hi_1,
8725 sum64_lo: sum64_lo_1,
8726 sum64_4_hi: sum64_4_hi_1,
8727 sum64_4_lo: sum64_4_lo_1,
8728 sum64_5_hi: sum64_5_hi_1,
8729 sum64_5_lo: sum64_5_lo_1,
8730 rotr64_hi: rotr64_hi_1,
8731 rotr64_lo: rotr64_lo_1,
8732 shr64_hi: shr64_hi_1,
8733 shr64_lo: shr64_lo_1
8734};
8735
8736function BlockHash() {
8737 this.pending = null;
8738 this.pendingTotal = 0;
8739 this.blockSize = this.constructor.blockSize;
8740 this.outSize = this.constructor.outSize;
8741 this.hmacStrength = this.constructor.hmacStrength;
8742 this.padLength = this.constructor.padLength / 8;
8743 this.endian = 'big';
8744
8745 this._delta8 = this.blockSize / 8;
8746 this._delta32 = this.blockSize / 32;
8747}
8748var BlockHash_1 = BlockHash;
8749
8750BlockHash.prototype.update = function update(msg, enc) {
8751 // Convert message to array, pad it, and join into 32bit blocks
8752 msg = utils.toArray(msg, enc);
8753 if (!this.pending)
8754 this.pending = msg;
8755 else
8756 this.pending = this.pending.concat(msg);
8757 this.pendingTotal += msg.length;
8758
8759 // Enough data, try updating
8760 if (this.pending.length >= this._delta8) {
8761 msg = this.pending;
8762
8763 // Process pending data in blocks
8764 var r = msg.length % this._delta8;
8765 this.pending = msg.slice(msg.length - r, msg.length);
8766 if (this.pending.length === 0)
8767 this.pending = null;
8768
8769 msg = utils.join32(msg, 0, msg.length - r, this.endian);
8770 for (var i = 0; i < msg.length; i += this._delta32)
8771 this._update(msg, i, i + this._delta32);
8772 }
8773
8774 return this;
8775};
8776
8777BlockHash.prototype.digest = function digest(enc) {
8778 this.update(this._pad());
8779 minimalisticAssert(this.pending === null);
8780
8781 return this._digest(enc);
8782};
8783
8784BlockHash.prototype._pad = function pad() {
8785 var len = this.pendingTotal;
8786 var bytes = this._delta8;
8787 var k = bytes - ((len + this.padLength) % bytes);
8788 var res = new Array(k + this.padLength);
8789 res[0] = 0x80;
8790 for (var i = 1; i < k; i++)
8791 res[i] = 0;
8792
8793 // Append length
8794 len <<= 3;
8795 if (this.endian === 'big') {
8796 for (var t = 8; t < this.padLength; t++)
8797 res[i++] = 0;
8798
8799 res[i++] = 0;
8800 res[i++] = 0;
8801 res[i++] = 0;
8802 res[i++] = 0;
8803 res[i++] = (len >>> 24) & 0xff;
8804 res[i++] = (len >>> 16) & 0xff;
8805 res[i++] = (len >>> 8) & 0xff;
8806 res[i++] = len & 0xff;
8807 } else {
8808 res[i++] = len & 0xff;
8809 res[i++] = (len >>> 8) & 0xff;
8810 res[i++] = (len >>> 16) & 0xff;
8811 res[i++] = (len >>> 24) & 0xff;
8812 res[i++] = 0;
8813 res[i++] = 0;
8814 res[i++] = 0;
8815 res[i++] = 0;
8816
8817 for (t = 8; t < this.padLength; t++)
8818 res[i++] = 0;
8819 }
8820
8821 return res;
8822};
8823
8824var common = {
8825 BlockHash: BlockHash_1
8826};
8827
8828var rotr32$1 = utils.rotr32;
8829
8830function ft_1(s, x, y, z) {
8831 if (s === 0)
8832 return ch32(x, y, z);
8833 if (s === 1 || s === 3)
8834 return p32(x, y, z);
8835 if (s === 2)
8836 return maj32(x, y, z);
8837}
8838var ft_1_1 = ft_1;
8839
8840function ch32(x, y, z) {
8841 return (x & y) ^ ((~x) & z);
8842}
8843var ch32_1 = ch32;
8844
8845function maj32(x, y, z) {
8846 return (x & y) ^ (x & z) ^ (y & z);
8847}
8848var maj32_1 = maj32;
8849
8850function p32(x, y, z) {
8851 return x ^ y ^ z;
8852}
8853var p32_1 = p32;
8854
8855function s0_256(x) {
8856 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
8857}
8858var s0_256_1 = s0_256;
8859
8860function s1_256(x) {
8861 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
8862}
8863var s1_256_1 = s1_256;
8864
8865function g0_256(x) {
8866 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
8867}
8868var g0_256_1 = g0_256;
8869
8870function g1_256(x) {
8871 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
8872}
8873var g1_256_1 = g1_256;
8874
8875var common$1 = {
8876 ft_1: ft_1_1,
8877 ch32: ch32_1,
8878 maj32: maj32_1,
8879 p32: p32_1,
8880 s0_256: s0_256_1,
8881 s1_256: s1_256_1,
8882 g0_256: g0_256_1,
8883 g1_256: g1_256_1
8884};
8885
8886var sum32$1 = utils.sum32;
8887var sum32_4$1 = utils.sum32_4;
8888var sum32_5$1 = utils.sum32_5;
8889var ch32$1 = common$1.ch32;
8890var maj32$1 = common$1.maj32;
8891var s0_256$1 = common$1.s0_256;
8892var s1_256$1 = common$1.s1_256;
8893var g0_256$1 = common$1.g0_256;
8894var g1_256$1 = common$1.g1_256;
8895
8896var BlockHash$1 = common.BlockHash;
8897
8898var sha256_K = [
8899 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
8900 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8901 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
8902 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8903 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
8904 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
8905 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
8906 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8907 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
8908 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
8909 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
8910 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8911 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
8912 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
8913 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
8914 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
8915];
8916
8917function SHA256() {
8918 if (!(this instanceof SHA256))
8919 return new SHA256();
8920
8921 BlockHash$1.call(this);
8922 this.h = [
8923 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
8924 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
8925 ];
8926 this.k = sha256_K;
8927 this.W = new Array(64);
8928}
8929utils.inherits(SHA256, BlockHash$1);
8930var _256 = SHA256;
8931
8932SHA256.blockSize = 512;
8933SHA256.outSize = 256;
8934SHA256.hmacStrength = 192;
8935SHA256.padLength = 64;
8936
8937SHA256.prototype._update = function _update(msg, start) {
8938 var W = this.W;
8939
8940 for (var i = 0; i < 16; i++)
8941 W[i] = msg[start + i];
8942 for (; i < W.length; i++)
8943 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
8944
8945 var a = this.h[0];
8946 var b = this.h[1];
8947 var c = this.h[2];
8948 var d = this.h[3];
8949 var e = this.h[4];
8950 var f = this.h[5];
8951 var g = this.h[6];
8952 var h = this.h[7];
8953
8954 minimalisticAssert(this.k.length === W.length);
8955 for (i = 0; i < W.length; i++) {
8956 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
8957 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
8958 h = g;
8959 g = f;
8960 f = e;
8961 e = sum32$1(d, T1);
8962 d = c;
8963 c = b;
8964 b = a;
8965 a = sum32$1(T1, T2);
8966 }
8967
8968 this.h[0] = sum32$1(this.h[0], a);
8969 this.h[1] = sum32$1(this.h[1], b);
8970 this.h[2] = sum32$1(this.h[2], c);
8971 this.h[3] = sum32$1(this.h[3], d);
8972 this.h[4] = sum32$1(this.h[4], e);
8973 this.h[5] = sum32$1(this.h[5], f);
8974 this.h[6] = sum32$1(this.h[6], g);
8975 this.h[7] = sum32$1(this.h[7], h);
8976};
8977
8978SHA256.prototype._digest = function digest(enc) {
8979 if (enc === 'hex')
8980 return utils.toHex32(this.h, 'big');
8981 else
8982 return utils.split32(this.h, 'big');
8983};
8984
8985function SHA224() {
8986 if (!(this instanceof SHA224))
8987 return new SHA224();
8988
8989 _256.call(this);
8990 this.h = [
8991 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
8992 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
8993}
8994utils.inherits(SHA224, _256);
8995var _224 = SHA224;
8996
8997SHA224.blockSize = 512;
8998SHA224.outSize = 224;
8999SHA224.hmacStrength = 192;
9000SHA224.padLength = 64;
9001
9002SHA224.prototype._digest = function digest(enc) {
9003 // Just truncate output
9004 if (enc === 'hex')
9005 return utils.toHex32(this.h.slice(0, 7), 'big');
9006 else
9007 return utils.split32(this.h.slice(0, 7), 'big');
9008};
9009
9010var rotr64_hi$1 = utils.rotr64_hi;
9011var rotr64_lo$1 = utils.rotr64_lo;
9012var shr64_hi$1 = utils.shr64_hi;
9013var shr64_lo$1 = utils.shr64_lo;
9014var sum64$1 = utils.sum64;
9015var sum64_hi$1 = utils.sum64_hi;
9016var sum64_lo$1 = utils.sum64_lo;
9017var sum64_4_hi$1 = utils.sum64_4_hi;
9018var sum64_4_lo$1 = utils.sum64_4_lo;
9019var sum64_5_hi$1 = utils.sum64_5_hi;
9020var sum64_5_lo$1 = utils.sum64_5_lo;
9021
9022var BlockHash$2 = common.BlockHash;
9023
9024var sha512_K = [
9025 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
9026 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
9027 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
9028 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
9029 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
9030 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
9031 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
9032 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
9033 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
9034 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
9035 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
9036 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
9037 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
9038 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
9039 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
9040 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
9041 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
9042 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
9043 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
9044 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
9045 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
9046 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
9047 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
9048 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
9049 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
9050 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
9051 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
9052 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
9053 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
9054 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
9055 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
9056 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
9057 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
9058 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
9059 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
9060 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
9061 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
9062 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
9063 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
9064 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
9065];
9066
9067function SHA512() {
9068 if (!(this instanceof SHA512))
9069 return new SHA512();
9070
9071 BlockHash$2.call(this);
9072 this.h = [
9073 0x6a09e667, 0xf3bcc908,
9074 0xbb67ae85, 0x84caa73b,
9075 0x3c6ef372, 0xfe94f82b,
9076 0xa54ff53a, 0x5f1d36f1,
9077 0x510e527f, 0xade682d1,
9078 0x9b05688c, 0x2b3e6c1f,
9079 0x1f83d9ab, 0xfb41bd6b,
9080 0x5be0cd19, 0x137e2179 ];
9081 this.k = sha512_K;
9082 this.W = new Array(160);
9083}
9084utils.inherits(SHA512, BlockHash$2);
9085var _512 = SHA512;
9086
9087SHA512.blockSize = 1024;
9088SHA512.outSize = 512;
9089SHA512.hmacStrength = 192;
9090SHA512.padLength = 128;
9091
9092SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
9093 var W = this.W;
9094
9095 // 32 x 32bit words
9096 for (var i = 0; i < 32; i++)
9097 W[i] = msg[start + i];
9098 for (; i < W.length; i += 2) {
9099 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
9100 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
9101 var c1_hi = W[i - 14]; // i - 7
9102 var c1_lo = W[i - 13];
9103 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
9104 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
9105 var c3_hi = W[i - 32]; // i - 16
9106 var c3_lo = W[i - 31];
9107
9108 W[i] = sum64_4_hi$1(
9109 c0_hi, c0_lo,
9110 c1_hi, c1_lo,
9111 c2_hi, c2_lo,
9112 c3_hi, c3_lo);
9113 W[i + 1] = sum64_4_lo$1(
9114 c0_hi, c0_lo,
9115 c1_hi, c1_lo,
9116 c2_hi, c2_lo,
9117 c3_hi, c3_lo);
9118 }
9119};
9120
9121SHA512.prototype._update = function _update(msg, start) {
9122 this._prepareBlock(msg, start);
9123
9124 var W = this.W;
9125
9126 var ah = this.h[0];
9127 var al = this.h[1];
9128 var bh = this.h[2];
9129 var bl = this.h[3];
9130 var ch = this.h[4];
9131 var cl = this.h[5];
9132 var dh = this.h[6];
9133 var dl = this.h[7];
9134 var eh = this.h[8];
9135 var el = this.h[9];
9136 var fh = this.h[10];
9137 var fl = this.h[11];
9138 var gh = this.h[12];
9139 var gl = this.h[13];
9140 var hh = this.h[14];
9141 var hl = this.h[15];
9142
9143 minimalisticAssert(this.k.length === W.length);
9144 for (var i = 0; i < W.length; i += 2) {
9145 var c0_hi = hh;
9146 var c0_lo = hl;
9147 var c1_hi = s1_512_hi(eh, el);
9148 var c1_lo = s1_512_lo(eh, el);
9149 var c2_hi = ch64_hi(eh, el, fh, fl, gh);
9150 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
9151 var c3_hi = this.k[i];
9152 var c3_lo = this.k[i + 1];
9153 var c4_hi = W[i];
9154 var c4_lo = W[i + 1];
9155
9156 var T1_hi = sum64_5_hi$1(
9157 c0_hi, c0_lo,
9158 c1_hi, c1_lo,
9159 c2_hi, c2_lo,
9160 c3_hi, c3_lo,
9161 c4_hi, c4_lo);
9162 var T1_lo = sum64_5_lo$1(
9163 c0_hi, c0_lo,
9164 c1_hi, c1_lo,
9165 c2_hi, c2_lo,
9166 c3_hi, c3_lo,
9167 c4_hi, c4_lo);
9168
9169 c0_hi = s0_512_hi(ah, al);
9170 c0_lo = s0_512_lo(ah, al);
9171 c1_hi = maj64_hi(ah, al, bh, bl, ch);
9172 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
9173
9174 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
9175 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
9176
9177 hh = gh;
9178 hl = gl;
9179
9180 gh = fh;
9181 gl = fl;
9182
9183 fh = eh;
9184 fl = el;
9185
9186 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
9187 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
9188
9189 dh = ch;
9190 dl = cl;
9191
9192 ch = bh;
9193 cl = bl;
9194
9195 bh = ah;
9196 bl = al;
9197
9198 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
9199 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
9200 }
9201
9202 sum64$1(this.h, 0, ah, al);
9203 sum64$1(this.h, 2, bh, bl);
9204 sum64$1(this.h, 4, ch, cl);
9205 sum64$1(this.h, 6, dh, dl);
9206 sum64$1(this.h, 8, eh, el);
9207 sum64$1(this.h, 10, fh, fl);
9208 sum64$1(this.h, 12, gh, gl);
9209 sum64$1(this.h, 14, hh, hl);
9210};
9211
9212SHA512.prototype._digest = function digest(enc) {
9213 if (enc === 'hex')
9214 return utils.toHex32(this.h, 'big');
9215 else
9216 return utils.split32(this.h, 'big');
9217};
9218
9219function ch64_hi(xh, xl, yh, yl, zh) {
9220 var r = (xh & yh) ^ ((~xh) & zh);
9221 if (r < 0)
9222 r += 0x100000000;
9223 return r;
9224}
9225
9226function ch64_lo(xh, xl, yh, yl, zh, zl) {
9227 var r = (xl & yl) ^ ((~xl) & zl);
9228 if (r < 0)
9229 r += 0x100000000;
9230 return r;
9231}
9232
9233function maj64_hi(xh, xl, yh, yl, zh) {
9234 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
9235 if (r < 0)
9236 r += 0x100000000;
9237 return r;
9238}
9239
9240function maj64_lo(xh, xl, yh, yl, zh, zl) {
9241 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
9242 if (r < 0)
9243 r += 0x100000000;
9244 return r;
9245}
9246
9247function s0_512_hi(xh, xl) {
9248 var c0_hi = rotr64_hi$1(xh, xl, 28);
9249 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
9250 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
9251
9252 var r = c0_hi ^ c1_hi ^ c2_hi;
9253 if (r < 0)
9254 r += 0x100000000;
9255 return r;
9256}
9257
9258function s0_512_lo(xh, xl) {
9259 var c0_lo = rotr64_lo$1(xh, xl, 28);
9260 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
9261 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
9262
9263 var r = c0_lo ^ c1_lo ^ c2_lo;
9264 if (r < 0)
9265 r += 0x100000000;
9266 return r;
9267}
9268
9269function s1_512_hi(xh, xl) {
9270 var c0_hi = rotr64_hi$1(xh, xl, 14);
9271 var c1_hi = rotr64_hi$1(xh, xl, 18);
9272 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
9273
9274 var r = c0_hi ^ c1_hi ^ c2_hi;
9275 if (r < 0)
9276 r += 0x100000000;
9277 return r;
9278}
9279
9280function s1_512_lo(xh, xl) {
9281 var c0_lo = rotr64_lo$1(xh, xl, 14);
9282 var c1_lo = rotr64_lo$1(xh, xl, 18);
9283 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
9284
9285 var r = c0_lo ^ c1_lo ^ c2_lo;
9286 if (r < 0)
9287 r += 0x100000000;
9288 return r;
9289}
9290
9291function g0_512_hi(xh, xl) {
9292 var c0_hi = rotr64_hi$1(xh, xl, 1);
9293 var c1_hi = rotr64_hi$1(xh, xl, 8);
9294 var c2_hi = shr64_hi$1(xh, xl, 7);
9295
9296 var r = c0_hi ^ c1_hi ^ c2_hi;
9297 if (r < 0)
9298 r += 0x100000000;
9299 return r;
9300}
9301
9302function g0_512_lo(xh, xl) {
9303 var c0_lo = rotr64_lo$1(xh, xl, 1);
9304 var c1_lo = rotr64_lo$1(xh, xl, 8);
9305 var c2_lo = shr64_lo$1(xh, xl, 7);
9306
9307 var r = c0_lo ^ c1_lo ^ c2_lo;
9308 if (r < 0)
9309 r += 0x100000000;
9310 return r;
9311}
9312
9313function g1_512_hi(xh, xl) {
9314 var c0_hi = rotr64_hi$1(xh, xl, 19);
9315 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
9316 var c2_hi = shr64_hi$1(xh, xl, 6);
9317
9318 var r = c0_hi ^ c1_hi ^ c2_hi;
9319 if (r < 0)
9320 r += 0x100000000;
9321 return r;
9322}
9323
9324function g1_512_lo(xh, xl) {
9325 var c0_lo = rotr64_lo$1(xh, xl, 19);
9326 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
9327 var c2_lo = shr64_lo$1(xh, xl, 6);
9328
9329 var r = c0_lo ^ c1_lo ^ c2_lo;
9330 if (r < 0)
9331 r += 0x100000000;
9332 return r;
9333}
9334
9335function SHA384() {
9336 if (!(this instanceof SHA384))
9337 return new SHA384();
9338
9339 _512.call(this);
9340 this.h = [
9341 0xcbbb9d5d, 0xc1059ed8,
9342 0x629a292a, 0x367cd507,
9343 0x9159015a, 0x3070dd17,
9344 0x152fecd8, 0xf70e5939,
9345 0x67332667, 0xffc00b31,
9346 0x8eb44a87, 0x68581511,
9347 0xdb0c2e0d, 0x64f98fa7,
9348 0x47b5481d, 0xbefa4fa4 ];
9349}
9350utils.inherits(SHA384, _512);
9351var _384 = SHA384;
9352
9353SHA384.blockSize = 1024;
9354SHA384.outSize = 384;
9355SHA384.hmacStrength = 192;
9356SHA384.padLength = 128;
9357
9358SHA384.prototype._digest = function digest(enc) {
9359 if (enc === 'hex')
9360 return utils.toHex32(this.h.slice(0, 12), 'big');
9361 else
9362 return utils.split32(this.h.slice(0, 12), 'big');
9363};
9364
9365var rotl32$1 = utils.rotl32;
9366var sum32$2 = utils.sum32;
9367var sum32_3$1 = utils.sum32_3;
9368var sum32_4$2 = utils.sum32_4;
9369var BlockHash$3 = common.BlockHash;
9370
9371function RIPEMD160() {
9372 if (!(this instanceof RIPEMD160))
9373 return new RIPEMD160();
9374
9375 BlockHash$3.call(this);
9376
9377 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
9378 this.endian = 'little';
9379}
9380utils.inherits(RIPEMD160, BlockHash$3);
9381var ripemd160 = RIPEMD160;
9382
9383RIPEMD160.blockSize = 512;
9384RIPEMD160.outSize = 160;
9385RIPEMD160.hmacStrength = 192;
9386RIPEMD160.padLength = 64;
9387
9388RIPEMD160.prototype._update = function update(msg, start) {
9389 var A = this.h[0];
9390 var B = this.h[1];
9391 var C = this.h[2];
9392 var D = this.h[3];
9393 var E = this.h[4];
9394 var Ah = A;
9395 var Bh = B;
9396 var Ch = C;
9397 var Dh = D;
9398 var Eh = E;
9399 for (var j = 0; j < 80; j++) {
9400 var T = sum32$2(
9401 rotl32$1(
9402 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
9403 s[j]),
9404 E);
9405 A = E;
9406 E = D;
9407 D = rotl32$1(C, 10);
9408 C = B;
9409 B = T;
9410 T = sum32$2(
9411 rotl32$1(
9412 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
9413 sh[j]),
9414 Eh);
9415 Ah = Eh;
9416 Eh = Dh;
9417 Dh = rotl32$1(Ch, 10);
9418 Ch = Bh;
9419 Bh = T;
9420 }
9421 T = sum32_3$1(this.h[1], C, Dh);
9422 this.h[1] = sum32_3$1(this.h[2], D, Eh);
9423 this.h[2] = sum32_3$1(this.h[3], E, Ah);
9424 this.h[3] = sum32_3$1(this.h[4], A, Bh);
9425 this.h[4] = sum32_3$1(this.h[0], B, Ch);
9426 this.h[0] = T;
9427};
9428
9429RIPEMD160.prototype._digest = function digest(enc) {
9430 if (enc === 'hex')
9431 return utils.toHex32(this.h, 'little');
9432 else
9433 return utils.split32(this.h, 'little');
9434};
9435
9436function f(j, x, y, z) {
9437 if (j <= 15)
9438 return x ^ y ^ z;
9439 else if (j <= 31)
9440 return (x & y) | ((~x) & z);
9441 else if (j <= 47)
9442 return (x | (~y)) ^ z;
9443 else if (j <= 63)
9444 return (x & z) | (y & (~z));
9445 else
9446 return x ^ (y | (~z));
9447}
9448
9449function K(j) {
9450 if (j <= 15)
9451 return 0x00000000;
9452 else if (j <= 31)
9453 return 0x5a827999;
9454 else if (j <= 47)
9455 return 0x6ed9eba1;
9456 else if (j <= 63)
9457 return 0x8f1bbcdc;
9458 else
9459 return 0xa953fd4e;
9460}
9461
9462function Kh(j) {
9463 if (j <= 15)
9464 return 0x50a28be6;
9465 else if (j <= 31)
9466 return 0x5c4dd124;
9467 else if (j <= 47)
9468 return 0x6d703ef3;
9469 else if (j <= 63)
9470 return 0x7a6d76e9;
9471 else
9472 return 0x00000000;
9473}
9474
9475var r = [
9476 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
9477 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
9478 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
9479 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
9480 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
9481];
9482
9483var rh = [
9484 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
9485 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
9486 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
9487 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
9488 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
9489];
9490
9491var s = [
9492 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
9493 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
9494 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
9495 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9496 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
9497];
9498
9499var sh = [
9500 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9501 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9502 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
9503 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
9504 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
9505];
9506
9507var ripemd = {
9508 ripemd160: ripemd160
9509};
9510
9511/**
9512 * A fast MD5 JavaScript implementation
9513 * Copyright (c) 2012 Joseph Myers
9514 * http://www.myersdaily.org/joseph/javascript/md5-text.html
9515 *
9516 * Permission to use, copy, modify, and distribute this software
9517 * and its documentation for any purposes and without
9518 * fee is hereby granted provided that this copyright notice
9519 * appears in all copies.
9520 *
9521 * Of course, this soft is provided "as is" without express or implied
9522 * warranty of any kind.
9523 */
9524
9525// MD5 Digest
9526async function md5(entree) {
9527 const digest = md51(util.uint8ArrayToString(entree));
9528 return util.hexToUint8Array(hex(digest));
9529}
9530
9531function md5cycle(x, k) {
9532 let a = x[0];
9533 let b = x[1];
9534 let c = x[2];
9535 let d = x[3];
9536
9537 a = ff(a, b, c, d, k[0], 7, -680876936);
9538 d = ff(d, a, b, c, k[1], 12, -389564586);
9539 c = ff(c, d, a, b, k[2], 17, 606105819);
9540 b = ff(b, c, d, a, k[3], 22, -1044525330);
9541 a = ff(a, b, c, d, k[4], 7, -176418897);
9542 d = ff(d, a, b, c, k[5], 12, 1200080426);
9543 c = ff(c, d, a, b, k[6], 17, -1473231341);
9544 b = ff(b, c, d, a, k[7], 22, -45705983);
9545 a = ff(a, b, c, d, k[8], 7, 1770035416);
9546 d = ff(d, a, b, c, k[9], 12, -1958414417);
9547 c = ff(c, d, a, b, k[10], 17, -42063);
9548 b = ff(b, c, d, a, k[11], 22, -1990404162);
9549 a = ff(a, b, c, d, k[12], 7, 1804603682);
9550 d = ff(d, a, b, c, k[13], 12, -40341101);
9551 c = ff(c, d, a, b, k[14], 17, -1502002290);
9552 b = ff(b, c, d, a, k[15], 22, 1236535329);
9553
9554 a = gg(a, b, c, d, k[1], 5, -165796510);
9555 d = gg(d, a, b, c, k[6], 9, -1069501632);
9556 c = gg(c, d, a, b, k[11], 14, 643717713);
9557 b = gg(b, c, d, a, k[0], 20, -373897302);
9558 a = gg(a, b, c, d, k[5], 5, -701558691);
9559 d = gg(d, a, b, c, k[10], 9, 38016083);
9560 c = gg(c, d, a, b, k[15], 14, -660478335);
9561 b = gg(b, c, d, a, k[4], 20, -405537848);
9562 a = gg(a, b, c, d, k[9], 5, 568446438);
9563 d = gg(d, a, b, c, k[14], 9, -1019803690);
9564 c = gg(c, d, a, b, k[3], 14, -187363961);
9565 b = gg(b, c, d, a, k[8], 20, 1163531501);
9566 a = gg(a, b, c, d, k[13], 5, -1444681467);
9567 d = gg(d, a, b, c, k[2], 9, -51403784);
9568 c = gg(c, d, a, b, k[7], 14, 1735328473);
9569 b = gg(b, c, d, a, k[12], 20, -1926607734);
9570
9571 a = hh(a, b, c, d, k[5], 4, -378558);
9572 d = hh(d, a, b, c, k[8], 11, -2022574463);
9573 c = hh(c, d, a, b, k[11], 16, 1839030562);
9574 b = hh(b, c, d, a, k[14], 23, -35309556);
9575 a = hh(a, b, c, d, k[1], 4, -1530992060);
9576 d = hh(d, a, b, c, k[4], 11, 1272893353);
9577 c = hh(c, d, a, b, k[7], 16, -155497632);
9578 b = hh(b, c, d, a, k[10], 23, -1094730640);
9579 a = hh(a, b, c, d, k[13], 4, 681279174);
9580 d = hh(d, a, b, c, k[0], 11, -358537222);
9581 c = hh(c, d, a, b, k[3], 16, -722521979);
9582 b = hh(b, c, d, a, k[6], 23, 76029189);
9583 a = hh(a, b, c, d, k[9], 4, -640364487);
9584 d = hh(d, a, b, c, k[12], 11, -421815835);
9585 c = hh(c, d, a, b, k[15], 16, 530742520);
9586 b = hh(b, c, d, a, k[2], 23, -995338651);
9587
9588 a = ii(a, b, c, d, k[0], 6, -198630844);
9589 d = ii(d, a, b, c, k[7], 10, 1126891415);
9590 c = ii(c, d, a, b, k[14], 15, -1416354905);
9591 b = ii(b, c, d, a, k[5], 21, -57434055);
9592 a = ii(a, b, c, d, k[12], 6, 1700485571);
9593 d = ii(d, a, b, c, k[3], 10, -1894986606);
9594 c = ii(c, d, a, b, k[10], 15, -1051523);
9595 b = ii(b, c, d, a, k[1], 21, -2054922799);
9596 a = ii(a, b, c, d, k[8], 6, 1873313359);
9597 d = ii(d, a, b, c, k[15], 10, -30611744);
9598 c = ii(c, d, a, b, k[6], 15, -1560198380);
9599 b = ii(b, c, d, a, k[13], 21, 1309151649);
9600 a = ii(a, b, c, d, k[4], 6, -145523070);
9601 d = ii(d, a, b, c, k[11], 10, -1120210379);
9602 c = ii(c, d, a, b, k[2], 15, 718787259);
9603 b = ii(b, c, d, a, k[9], 21, -343485551);
9604
9605 x[0] = add32(a, x[0]);
9606 x[1] = add32(b, x[1]);
9607 x[2] = add32(c, x[2]);
9608 x[3] = add32(d, x[3]);
9609}
9610
9611function cmn(q, a, b, x, s, t) {
9612 a = add32(add32(a, q), add32(x, t));
9613 return add32((a << s) | (a >>> (32 - s)), b);
9614}
9615
9616function ff(a, b, c, d, x, s, t) {
9617 return cmn((b & c) | ((~b) & d), a, b, x, s, t);
9618}
9619
9620function gg(a, b, c, d, x, s, t) {
9621 return cmn((b & d) | (c & (~d)), a, b, x, s, t);
9622}
9623
9624function hh(a, b, c, d, x, s, t) {
9625 return cmn(b ^ c ^ d, a, b, x, s, t);
9626}
9627
9628function ii(a, b, c, d, x, s, t) {
9629 return cmn(c ^ (b | (~d)), a, b, x, s, t);
9630}
9631
9632function md51(s) {
9633 const n = s.length;
9634 const state = [1732584193, -271733879, -1732584194, 271733878];
9635 let i;
9636 for (i = 64; i <= s.length; i += 64) {
9637 md5cycle(state, md5blk(s.substring(i - 64, i)));
9638 }
9639 s = s.substring(i - 64);
9640 const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9641 for (i = 0; i < s.length; i++) {
9642 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
9643 }
9644 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
9645 if (i > 55) {
9646 md5cycle(state, tail);
9647 for (i = 0; i < 16; i++) {
9648 tail[i] = 0;
9649 }
9650 }
9651 tail[14] = n * 8;
9652 md5cycle(state, tail);
9653 return state;
9654}
9655
9656/* there needs to be support for Unicode here,
9657 * unless we pretend that we can redefine the MD-5
9658 * algorithm for multi-byte characters (perhaps
9659 * by adding every four 16-bit characters and
9660 * shortening the sum to 32 bits). Otherwise
9661 * I suggest performing MD-5 as if every character
9662 * was two bytes--e.g., 0040 0025 = @%--but then
9663 * how will an ordinary MD-5 sum be matched?
9664 * There is no way to standardize text to something
9665 * like UTF-8 before transformation; speed cost is
9666 * utterly prohibitive. The JavaScript standard
9667 * itself needs to look at this: it should start
9668 * providing access to strings as preformed UTF-8
9669 * 8-bit unsigned value arrays.
9670 */
9671function md5blk(s) { /* I figured global was faster. */
9672 const md5blks = [];
9673 let i; /* Andy King said do it this way. */
9674 for (i = 0; i < 64; i += 4) {
9675 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<
9676 24);
9677 }
9678 return md5blks;
9679}
9680
9681const hex_chr = '0123456789abcdef'.split('');
9682
9683function rhex(n) {
9684 let s = '';
9685 let j = 0;
9686 for (; j < 4; j++) {
9687 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
9688 }
9689 return s;
9690}
9691
9692function hex(x) {
9693 for (let i = 0; i < x.length; i++) {
9694 x[i] = rhex(x[i]);
9695 }
9696 return x.join('');
9697}
9698
9699/* this function is much faster,
9700so if possible we use it. Some IEs
9701are the only ones I know of that
9702need the idiotic second function,
9703generated by an if clause. */
9704
9705function add32(a, b) {
9706 return (a + b) & 0xFFFFFFFF;
9707}
9708
9709/**
9710 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
9711 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9712 * @see {@link https://github.com/indutny/hash.js|hash.js}
9713 * @module crypto/hash
9714 * @private
9715 */
9716
9717const webCrypto = util.getWebCrypto();
9718const nodeCrypto = util.getNodeCrypto();
9719const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();
9720
9721function nodeHash(type) {
9722 if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {
9723 return;
9724 }
9725 return async function (data) {
9726 const shasum = nodeCrypto.createHash(type);
9727 return transform(data, value => {
9728 shasum.update(value);
9729 }, () => new Uint8Array(shasum.digest()));
9730 };
9731}
9732
9733function hashjsHash(hash, webCryptoHash) {
9734 return async function(data, config = defaultConfig) {
9735 if (isArrayStream(data)) {
9736 data = await readToEnd(data);
9737 }
9738 if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9739 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9740 }
9741 const hashInstance = hash();
9742 return transform(data, value => {
9743 hashInstance.update(value);
9744 }, () => new Uint8Array(hashInstance.digest()));
9745 };
9746}
9747
9748function asmcryptoHash(hash, webCryptoHash) {
9749 return async function(data, config = defaultConfig) {
9750 if (isArrayStream(data)) {
9751 data = await readToEnd(data);
9752 }
9753 if (util.isStream(data)) {
9754 const hashInstance = new hash();
9755 return transform(data, value => {
9756 hashInstance.process(value);
9757 }, () => hashInstance.finish().result);
9758 } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9759 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9760 } else {
9761 return hash.bytes(data);
9762 }
9763 };
9764}
9765
9766const hashFunctions = {
9767 md5: nodeHash('md5') || md5,
9768 sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),
9769 sha224: nodeHash('sha224') || hashjsHash(_224),
9770 sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),
9771 sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'),
9772 sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge.
9773 ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)
9774};
9775
9776var hash = {
9777
9778 /** @see module:md5 */
9779 md5: hashFunctions.md5,
9780 /** @see asmCrypto */
9781 sha1: hashFunctions.sha1,
9782 /** @see hash.js */
9783 sha224: hashFunctions.sha224,
9784 /** @see asmCrypto */
9785 sha256: hashFunctions.sha256,
9786 /** @see hash.js */
9787 sha384: hashFunctions.sha384,
9788 /** @see asmCrypto */
9789 sha512: hashFunctions.sha512,
9790 /** @see hash.js */
9791 ripemd: hashFunctions.ripemd,
9792
9793 /**
9794 * Create a hash on the specified data using the specified algorithm
9795 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9796 * @param {Uint8Array} data - Data to be hashed
9797 * @returns {Promise<Uint8Array>} Hash value.
9798 */
9799 digest: function(algo, data) {
9800 switch (algo) {
9801 case enums.hash.md5:
9802 return this.md5(data);
9803 case enums.hash.sha1:
9804 return this.sha1(data);
9805 case enums.hash.ripemd:
9806 return this.ripemd(data);
9807 case enums.hash.sha256:
9808 return this.sha256(data);
9809 case enums.hash.sha384:
9810 return this.sha384(data);
9811 case enums.hash.sha512:
9812 return this.sha512(data);
9813 case enums.hash.sha224:
9814 return this.sha224(data);
9815 default:
9816 throw new Error('Invalid hash function.');
9817 }
9818 },
9819
9820 /**
9821 * Returns the hash size in bytes of the specified hash algorithm type
9822 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9823 * @returns {Integer} Size in bytes of the resulting hash.
9824 */
9825 getHashByteLength: function(algo) {
9826 switch (algo) {
9827 case enums.hash.md5:
9828 return 16;
9829 case enums.hash.sha1:
9830 case enums.hash.ripemd:
9831 return 20;
9832 case enums.hash.sha256:
9833 return 32;
9834 case enums.hash.sha384:
9835 return 48;
9836 case enums.hash.sha512:
9837 return 64;
9838 case enums.hash.sha224:
9839 return 28;
9840 default:
9841 throw new Error('Invalid hash algorithm.');
9842 }
9843 }
9844};
9845
9846class AES_CFB {
9847 static encrypt(data, key, iv) {
9848 return new AES_CFB(key, iv).encrypt(data);
9849 }
9850 static decrypt(data, key, iv) {
9851 return new AES_CFB(key, iv).decrypt(data);
9852 }
9853 constructor(key, iv, aes) {
9854 this.aes = aes ? aes : new AES(key, iv, true, 'CFB');
9855 delete this.aes.padding;
9856 }
9857 encrypt(data) {
9858 const r1 = this.aes.AES_Encrypt_process(data);
9859 const r2 = this.aes.AES_Encrypt_finish();
9860 return joinBytes(r1, r2);
9861 }
9862 decrypt(data) {
9863 const r1 = this.aes.AES_Decrypt_process(data);
9864 const r2 = this.aes.AES_Decrypt_finish();
9865 return joinBytes(r1, r2);
9866 }
9867}
9868
9869var naclFastLight = createCommonjsModule(function (module) {
9870/*jshint bitwise: false*/
9871
9872(function(nacl) {
9873
9874// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
9875// Public domain.
9876//
9877// Implementation derived from TweetNaCl version 20140427.
9878// See for details: http://tweetnacl.cr.yp.to/
9879
9880var gf = function(init) {
9881 var i, r = new Float64Array(16);
9882 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
9883 return r;
9884};
9885
9886// Pluggable, initialized in high-level API below.
9887var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
9888
9889var _9 = new Uint8Array(32); _9[0] = 9;
9890
9891var gf0 = gf(),
9892 gf1 = gf([1]),
9893 _121665 = gf([0xdb41, 1]),
9894 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
9895 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
9896 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
9897 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
9898 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
9899
9900function vn(x, xi, y, yi, n) {
9901 var i,d = 0;
9902 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
9903 return (1 & ((d - 1) >>> 8)) - 1;
9904}
9905
9906function crypto_verify_32(x, xi, y, yi) {
9907 return vn(x,xi,y,yi,32);
9908}
9909
9910function set25519(r, a) {
9911 var i;
9912 for (i = 0; i < 16; i++) r[i] = a[i]|0;
9913}
9914
9915function car25519(o) {
9916 var i, v, c = 1;
9917 for (i = 0; i < 16; i++) {
9918 v = o[i] + c + 65535;
9919 c = Math.floor(v / 65536);
9920 o[i] = v - c * 65536;
9921 }
9922 o[0] += c-1 + 37 * (c-1);
9923}
9924
9925function sel25519(p, q, b) {
9926 var t, c = ~(b-1);
9927 for (var i = 0; i < 16; i++) {
9928 t = c & (p[i] ^ q[i]);
9929 p[i] ^= t;
9930 q[i] ^= t;
9931 }
9932}
9933
9934function pack25519(o, n) {
9935 var i, j, b;
9936 var m = gf(), t = gf();
9937 for (i = 0; i < 16; i++) t[i] = n[i];
9938 car25519(t);
9939 car25519(t);
9940 car25519(t);
9941 for (j = 0; j < 2; j++) {
9942 m[0] = t[0] - 0xffed;
9943 for (i = 1; i < 15; i++) {
9944 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
9945 m[i-1] &= 0xffff;
9946 }
9947 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
9948 b = (m[15]>>16) & 1;
9949 m[14] &= 0xffff;
9950 sel25519(t, m, 1-b);
9951 }
9952 for (i = 0; i < 16; i++) {
9953 o[2*i] = t[i] & 0xff;
9954 o[2*i+1] = t[i]>>8;
9955 }
9956}
9957
9958function neq25519(a, b) {
9959 var c = new Uint8Array(32), d = new Uint8Array(32);
9960 pack25519(c, a);
9961 pack25519(d, b);
9962 return crypto_verify_32(c, 0, d, 0);
9963}
9964
9965function par25519(a) {
9966 var d = new Uint8Array(32);
9967 pack25519(d, a);
9968 return d[0] & 1;
9969}
9970
9971function unpack25519(o, n) {
9972 var i;
9973 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
9974 o[15] &= 0x7fff;
9975}
9976
9977function A(o, a, b) {
9978 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
9979}
9980
9981function Z(o, a, b) {
9982 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
9983}
9984
9985function M(o, a, b) {
9986 var v, c,
9987 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
9988 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
9989 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
9990 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
9991 b0 = b[0],
9992 b1 = b[1],
9993 b2 = b[2],
9994 b3 = b[3],
9995 b4 = b[4],
9996 b5 = b[5],
9997 b6 = b[6],
9998 b7 = b[7],
9999 b8 = b[8],
10000 b9 = b[9],
10001 b10 = b[10],
10002 b11 = b[11],
10003 b12 = b[12],
10004 b13 = b[13],
10005 b14 = b[14],
10006 b15 = b[15];
10007
10008 v = a[0];
10009 t0 += v * b0;
10010 t1 += v * b1;
10011 t2 += v * b2;
10012 t3 += v * b3;
10013 t4 += v * b4;
10014 t5 += v * b5;
10015 t6 += v * b6;
10016 t7 += v * b7;
10017 t8 += v * b8;
10018 t9 += v * b9;
10019 t10 += v * b10;
10020 t11 += v * b11;
10021 t12 += v * b12;
10022 t13 += v * b13;
10023 t14 += v * b14;
10024 t15 += v * b15;
10025 v = a[1];
10026 t1 += v * b0;
10027 t2 += v * b1;
10028 t3 += v * b2;
10029 t4 += v * b3;
10030 t5 += v * b4;
10031 t6 += v * b5;
10032 t7 += v * b6;
10033 t8 += v * b7;
10034 t9 += v * b8;
10035 t10 += v * b9;
10036 t11 += v * b10;
10037 t12 += v * b11;
10038 t13 += v * b12;
10039 t14 += v * b13;
10040 t15 += v * b14;
10041 t16 += v * b15;
10042 v = a[2];
10043 t2 += v * b0;
10044 t3 += v * b1;
10045 t4 += v * b2;
10046 t5 += v * b3;
10047 t6 += v * b4;
10048 t7 += v * b5;
10049 t8 += v * b6;
10050 t9 += v * b7;
10051 t10 += v * b8;
10052 t11 += v * b9;
10053 t12 += v * b10;
10054 t13 += v * b11;
10055 t14 += v * b12;
10056 t15 += v * b13;
10057 t16 += v * b14;
10058 t17 += v * b15;
10059 v = a[3];
10060 t3 += v * b0;
10061 t4 += v * b1;
10062 t5 += v * b2;
10063 t6 += v * b3;
10064 t7 += v * b4;
10065 t8 += v * b5;
10066 t9 += v * b6;
10067 t10 += v * b7;
10068 t11 += v * b8;
10069 t12 += v * b9;
10070 t13 += v * b10;
10071 t14 += v * b11;
10072 t15 += v * b12;
10073 t16 += v * b13;
10074 t17 += v * b14;
10075 t18 += v * b15;
10076 v = a[4];
10077 t4 += v * b0;
10078 t5 += v * b1;
10079 t6 += v * b2;
10080 t7 += v * b3;
10081 t8 += v * b4;
10082 t9 += v * b5;
10083 t10 += v * b6;
10084 t11 += v * b7;
10085 t12 += v * b8;
10086 t13 += v * b9;
10087 t14 += v * b10;
10088 t15 += v * b11;
10089 t16 += v * b12;
10090 t17 += v * b13;
10091 t18 += v * b14;
10092 t19 += v * b15;
10093 v = a[5];
10094 t5 += v * b0;
10095 t6 += v * b1;
10096 t7 += v * b2;
10097 t8 += v * b3;
10098 t9 += v * b4;
10099 t10 += v * b5;
10100 t11 += v * b6;
10101 t12 += v * b7;
10102 t13 += v * b8;
10103 t14 += v * b9;
10104 t15 += v * b10;
10105 t16 += v * b11;
10106 t17 += v * b12;
10107 t18 += v * b13;
10108 t19 += v * b14;
10109 t20 += v * b15;
10110 v = a[6];
10111 t6 += v * b0;
10112 t7 += v * b1;
10113 t8 += v * b2;
10114 t9 += v * b3;
10115 t10 += v * b4;
10116 t11 += v * b5;
10117 t12 += v * b6;
10118 t13 += v * b7;
10119 t14 += v * b8;
10120 t15 += v * b9;
10121 t16 += v * b10;
10122 t17 += v * b11;
10123 t18 += v * b12;
10124 t19 += v * b13;
10125 t20 += v * b14;
10126 t21 += v * b15;
10127 v = a[7];
10128 t7 += v * b0;
10129 t8 += v * b1;
10130 t9 += v * b2;
10131 t10 += v * b3;
10132 t11 += v * b4;
10133 t12 += v * b5;
10134 t13 += v * b6;
10135 t14 += v * b7;
10136 t15 += v * b8;
10137 t16 += v * b9;
10138 t17 += v * b10;
10139 t18 += v * b11;
10140 t19 += v * b12;
10141 t20 += v * b13;
10142 t21 += v * b14;
10143 t22 += v * b15;
10144 v = a[8];
10145 t8 += v * b0;
10146 t9 += v * b1;
10147 t10 += v * b2;
10148 t11 += v * b3;
10149 t12 += v * b4;
10150 t13 += v * b5;
10151 t14 += v * b6;
10152 t15 += v * b7;
10153 t16 += v * b8;
10154 t17 += v * b9;
10155 t18 += v * b10;
10156 t19 += v * b11;
10157 t20 += v * b12;
10158 t21 += v * b13;
10159 t22 += v * b14;
10160 t23 += v * b15;
10161 v = a[9];
10162 t9 += v * b0;
10163 t10 += v * b1;
10164 t11 += v * b2;
10165 t12 += v * b3;
10166 t13 += v * b4;
10167 t14 += v * b5;
10168 t15 += v * b6;
10169 t16 += v * b7;
10170 t17 += v * b8;
10171 t18 += v * b9;
10172 t19 += v * b10;
10173 t20 += v * b11;
10174 t21 += v * b12;
10175 t22 += v * b13;
10176 t23 += v * b14;
10177 t24 += v * b15;
10178 v = a[10];
10179 t10 += v * b0;
10180 t11 += v * b1;
10181 t12 += v * b2;
10182 t13 += v * b3;
10183 t14 += v * b4;
10184 t15 += v * b5;
10185 t16 += v * b6;
10186 t17 += v * b7;
10187 t18 += v * b8;
10188 t19 += v * b9;
10189 t20 += v * b10;
10190 t21 += v * b11;
10191 t22 += v * b12;
10192 t23 += v * b13;
10193 t24 += v * b14;
10194 t25 += v * b15;
10195 v = a[11];
10196 t11 += v * b0;
10197 t12 += v * b1;
10198 t13 += v * b2;
10199 t14 += v * b3;
10200 t15 += v * b4;
10201 t16 += v * b5;
10202 t17 += v * b6;
10203 t18 += v * b7;
10204 t19 += v * b8;
10205 t20 += v * b9;
10206 t21 += v * b10;
10207 t22 += v * b11;
10208 t23 += v * b12;
10209 t24 += v * b13;
10210 t25 += v * b14;
10211 t26 += v * b15;
10212 v = a[12];
10213 t12 += v * b0;
10214 t13 += v * b1;
10215 t14 += v * b2;
10216 t15 += v * b3;
10217 t16 += v * b4;
10218 t17 += v * b5;
10219 t18 += v * b6;
10220 t19 += v * b7;
10221 t20 += v * b8;
10222 t21 += v * b9;
10223 t22 += v * b10;
10224 t23 += v * b11;
10225 t24 += v * b12;
10226 t25 += v * b13;
10227 t26 += v * b14;
10228 t27 += v * b15;
10229 v = a[13];
10230 t13 += v * b0;
10231 t14 += v * b1;
10232 t15 += v * b2;
10233 t16 += v * b3;
10234 t17 += v * b4;
10235 t18 += v * b5;
10236 t19 += v * b6;
10237 t20 += v * b7;
10238 t21 += v * b8;
10239 t22 += v * b9;
10240 t23 += v * b10;
10241 t24 += v * b11;
10242 t25 += v * b12;
10243 t26 += v * b13;
10244 t27 += v * b14;
10245 t28 += v * b15;
10246 v = a[14];
10247 t14 += v * b0;
10248 t15 += v * b1;
10249 t16 += v * b2;
10250 t17 += v * b3;
10251 t18 += v * b4;
10252 t19 += v * b5;
10253 t20 += v * b6;
10254 t21 += v * b7;
10255 t22 += v * b8;
10256 t23 += v * b9;
10257 t24 += v * b10;
10258 t25 += v * b11;
10259 t26 += v * b12;
10260 t27 += v * b13;
10261 t28 += v * b14;
10262 t29 += v * b15;
10263 v = a[15];
10264 t15 += v * b0;
10265 t16 += v * b1;
10266 t17 += v * b2;
10267 t18 += v * b3;
10268 t19 += v * b4;
10269 t20 += v * b5;
10270 t21 += v * b6;
10271 t22 += v * b7;
10272 t23 += v * b8;
10273 t24 += v * b9;
10274 t25 += v * b10;
10275 t26 += v * b11;
10276 t27 += v * b12;
10277 t28 += v * b13;
10278 t29 += v * b14;
10279 t30 += v * b15;
10280
10281 t0 += 38 * t16;
10282 t1 += 38 * t17;
10283 t2 += 38 * t18;
10284 t3 += 38 * t19;
10285 t4 += 38 * t20;
10286 t5 += 38 * t21;
10287 t6 += 38 * t22;
10288 t7 += 38 * t23;
10289 t8 += 38 * t24;
10290 t9 += 38 * t25;
10291 t10 += 38 * t26;
10292 t11 += 38 * t27;
10293 t12 += 38 * t28;
10294 t13 += 38 * t29;
10295 t14 += 38 * t30;
10296 // t15 left as is
10297
10298 // first car
10299 c = 1;
10300 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
10301 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
10302 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
10303 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
10304 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
10305 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
10306 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
10307 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
10308 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
10309 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
10310 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
10311 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
10312 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
10313 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
10314 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
10315 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
10316 t0 += c-1 + 37 * (c-1);
10317
10318 // second car
10319 c = 1;
10320 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
10321 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
10322 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
10323 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
10324 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
10325 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
10326 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
10327 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
10328 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
10329 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
10330 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
10331 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
10332 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
10333 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
10334 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
10335 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
10336 t0 += c-1 + 37 * (c-1);
10337
10338 o[ 0] = t0;
10339 o[ 1] = t1;
10340 o[ 2] = t2;
10341 o[ 3] = t3;
10342 o[ 4] = t4;
10343 o[ 5] = t5;
10344 o[ 6] = t6;
10345 o[ 7] = t7;
10346 o[ 8] = t8;
10347 o[ 9] = t9;
10348 o[10] = t10;
10349 o[11] = t11;
10350 o[12] = t12;
10351 o[13] = t13;
10352 o[14] = t14;
10353 o[15] = t15;
10354}
10355
10356function S(o, a) {
10357 M(o, a, a);
10358}
10359
10360function inv25519(o, i) {
10361 var c = gf();
10362 var a;
10363 for (a = 0; a < 16; a++) c[a] = i[a];
10364 for (a = 253; a >= 0; a--) {
10365 S(c, c);
10366 if(a !== 2 && a !== 4) M(c, c, i);
10367 }
10368 for (a = 0; a < 16; a++) o[a] = c[a];
10369}
10370
10371function pow2523(o, i) {
10372 var c = gf();
10373 var a;
10374 for (a = 0; a < 16; a++) c[a] = i[a];
10375 for (a = 250; a >= 0; a--) {
10376 S(c, c);
10377 if(a !== 1) M(c, c, i);
10378 }
10379 for (a = 0; a < 16; a++) o[a] = c[a];
10380}
10381
10382function crypto_scalarmult(q, n, p) {
10383 var z = new Uint8Array(32);
10384 var x = new Float64Array(80), r, i;
10385 var a = gf(), b = gf(), c = gf(),
10386 d = gf(), e = gf(), f = gf();
10387 for (i = 0; i < 31; i++) z[i] = n[i];
10388 z[31]=(n[31]&127)|64;
10389 z[0]&=248;
10390 unpack25519(x,p);
10391 for (i = 0; i < 16; i++) {
10392 b[i]=x[i];
10393 d[i]=a[i]=c[i]=0;
10394 }
10395 a[0]=d[0]=1;
10396 for (i=254; i>=0; --i) {
10397 r=(z[i>>>3]>>>(i&7))&1;
10398 sel25519(a,b,r);
10399 sel25519(c,d,r);
10400 A(e,a,c);
10401 Z(a,a,c);
10402 A(c,b,d);
10403 Z(b,b,d);
10404 S(d,e);
10405 S(f,a);
10406 M(a,c,a);
10407 M(c,b,e);
10408 A(e,a,c);
10409 Z(a,a,c);
10410 S(b,a);
10411 Z(c,d,f);
10412 M(a,c,_121665);
10413 A(a,a,d);
10414 M(c,c,a);
10415 M(a,d,f);
10416 M(d,b,x);
10417 S(b,e);
10418 sel25519(a,b,r);
10419 sel25519(c,d,r);
10420 }
10421 for (i = 0; i < 16; i++) {
10422 x[i+16]=a[i];
10423 x[i+32]=c[i];
10424 x[i+48]=b[i];
10425 x[i+64]=d[i];
10426 }
10427 var x32 = x.subarray(32);
10428 var x16 = x.subarray(16);
10429 inv25519(x32,x32);
10430 M(x16,x16,x32);
10431 pack25519(q,x16);
10432 return 0;
10433}
10434
10435function crypto_scalarmult_base(q, n) {
10436 return crypto_scalarmult(q, n, _9);
10437}
10438
10439function crypto_box_keypair(y, x) {
10440 randombytes(x, 32);
10441 return crypto_scalarmult_base(y, x);
10442}
10443
10444function add(p, q) {
10445 var a = gf(), b = gf(), c = gf(),
10446 d = gf(), e = gf(), f = gf(),
10447 g = gf(), h = gf(), t = gf();
10448
10449 Z(a, p[1], p[0]);
10450 Z(t, q[1], q[0]);
10451 M(a, a, t);
10452 A(b, p[0], p[1]);
10453 A(t, q[0], q[1]);
10454 M(b, b, t);
10455 M(c, p[3], q[3]);
10456 M(c, c, D2);
10457 M(d, p[2], q[2]);
10458 A(d, d, d);
10459 Z(e, b, a);
10460 Z(f, d, c);
10461 A(g, d, c);
10462 A(h, b, a);
10463
10464 M(p[0], e, f);
10465 M(p[1], h, g);
10466 M(p[2], g, f);
10467 M(p[3], e, h);
10468}
10469
10470function cswap(p, q, b) {
10471 var i;
10472 for (i = 0; i < 4; i++) {
10473 sel25519(p[i], q[i], b);
10474 }
10475}
10476
10477function pack(r, p) {
10478 var tx = gf(), ty = gf(), zi = gf();
10479 inv25519(zi, p[2]);
10480 M(tx, p[0], zi);
10481 M(ty, p[1], zi);
10482 pack25519(r, ty);
10483 r[31] ^= par25519(tx) << 7;
10484}
10485
10486function scalarmult(p, q, s) {
10487 var b, i;
10488 set25519(p[0], gf0);
10489 set25519(p[1], gf1);
10490 set25519(p[2], gf1);
10491 set25519(p[3], gf0);
10492 for (i = 255; i >= 0; --i) {
10493 b = (s[(i/8)|0] >> (i&7)) & 1;
10494 cswap(p, q, b);
10495 add(q, p);
10496 add(p, p);
10497 cswap(p, q, b);
10498 }
10499}
10500
10501function scalarbase(p, s) {
10502 var q = [gf(), gf(), gf(), gf()];
10503 set25519(q[0], X);
10504 set25519(q[1], Y);
10505 set25519(q[2], gf1);
10506 M(q[3], X, Y);
10507 scalarmult(p, q, s);
10508}
10509
10510function crypto_sign_keypair(pk, sk, seeded) {
10511 var d;
10512 var p = [gf(), gf(), gf(), gf()];
10513 var i;
10514
10515 if (!seeded) randombytes(sk, 32);
10516 d = nacl.hash(sk.subarray(0, 32));
10517 d[0] &= 248;
10518 d[31] &= 127;
10519 d[31] |= 64;
10520
10521 scalarbase(p, d);
10522 pack(pk, p);
10523
10524 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
10525 return 0;
10526}
10527
10528var 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]);
10529
10530function modL(r, x) {
10531 var carry, i, j, k;
10532 for (i = 63; i >= 32; --i) {
10533 carry = 0;
10534 for (j = i - 32, k = i - 12; j < k; ++j) {
10535 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
10536 carry = Math.floor((x[j] + 128) / 256);
10537 x[j] -= carry * 256;
10538 }
10539 x[j] += carry;
10540 x[i] = 0;
10541 }
10542 carry = 0;
10543 for (j = 0; j < 32; j++) {
10544 x[j] += carry - (x[31] >> 4) * L[j];
10545 carry = x[j] >> 8;
10546 x[j] &= 255;
10547 }
10548 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
10549 for (i = 0; i < 32; i++) {
10550 x[i+1] += x[i] >> 8;
10551 r[i] = x[i] & 255;
10552 }
10553}
10554
10555function reduce(r) {
10556 var x = new Float64Array(64), i;
10557 for (i = 0; i < 64; i++) x[i] = r[i];
10558 for (i = 0; i < 64; i++) r[i] = 0;
10559 modL(r, x);
10560}
10561
10562// Note: difference from C - smlen returned, not passed as argument.
10563function crypto_sign(sm, m, n, sk) {
10564 var d, h, r;
10565 var i, j, x = new Float64Array(64);
10566 var p = [gf(), gf(), gf(), gf()];
10567
10568 d = nacl.hash(sk.subarray(0, 32));
10569 d[0] &= 248;
10570 d[31] &= 127;
10571 d[31] |= 64;
10572
10573 var smlen = n + 64;
10574 for (i = 0; i < n; i++) sm[64 + i] = m[i];
10575 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
10576
10577 r = nacl.hash(sm.subarray(32, smlen));
10578 reduce(r);
10579 scalarbase(p, r);
10580 pack(sm, p);
10581
10582 for (i = 32; i < 64; i++) sm[i] = sk[i];
10583 h = nacl.hash(sm.subarray(0, smlen));
10584 reduce(h);
10585
10586 for (i = 0; i < 64; i++) x[i] = 0;
10587 for (i = 0; i < 32; i++) x[i] = r[i];
10588 for (i = 0; i < 32; i++) {
10589 for (j = 0; j < 32; j++) {
10590 x[i+j] += h[i] * d[j];
10591 }
10592 }
10593
10594 modL(sm.subarray(32), x);
10595 return smlen;
10596}
10597
10598function unpackneg(r, p) {
10599 var t = gf(), chk = gf(), num = gf(),
10600 den = gf(), den2 = gf(), den4 = gf(),
10601 den6 = gf();
10602
10603 set25519(r[2], gf1);
10604 unpack25519(r[1], p);
10605 S(num, r[1]);
10606 M(den, num, D);
10607 Z(num, num, r[2]);
10608 A(den, r[2], den);
10609
10610 S(den2, den);
10611 S(den4, den2);
10612 M(den6, den4, den2);
10613 M(t, den6, num);
10614 M(t, t, den);
10615
10616 pow2523(t, t);
10617 M(t, t, num);
10618 M(t, t, den);
10619 M(t, t, den);
10620 M(r[0], t, den);
10621
10622 S(chk, r[0]);
10623 M(chk, chk, den);
10624 if (neq25519(chk, num)) M(r[0], r[0], I);
10625
10626 S(chk, r[0]);
10627 M(chk, chk, den);
10628 if (neq25519(chk, num)) return -1;
10629
10630 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
10631
10632 M(r[3], r[0], r[1]);
10633 return 0;
10634}
10635
10636function crypto_sign_open(m, sm, n, pk) {
10637 var i;
10638 var t = new Uint8Array(32), h;
10639 var p = [gf(), gf(), gf(), gf()],
10640 q = [gf(), gf(), gf(), gf()];
10641
10642 if (n < 64) return -1;
10643
10644 if (unpackneg(q, pk)) return -1;
10645
10646 for (i = 0; i < n; i++) m[i] = sm[i];
10647 for (i = 0; i < 32; i++) m[i+32] = pk[i];
10648 h = nacl.hash(m.subarray(0, n));
10649 reduce(h);
10650 scalarmult(p, q, h);
10651
10652 scalarbase(q, sm.subarray(32));
10653 add(p, q);
10654 pack(t, p);
10655
10656 n -= 64;
10657 if (crypto_verify_32(sm, 0, t, 0)) {
10658 for (i = 0; i < n; i++) m[i] = 0;
10659 return -1;
10660 }
10661
10662 for (i = 0; i < n; i++) m[i] = sm[i + 64];
10663 return n;
10664}
10665
10666var crypto_scalarmult_BYTES = 32,
10667 crypto_scalarmult_SCALARBYTES = 32,
10668 crypto_box_PUBLICKEYBYTES = 32,
10669 crypto_box_SECRETKEYBYTES = 32,
10670 crypto_sign_BYTES = 64,
10671 crypto_sign_PUBLICKEYBYTES = 32,
10672 crypto_sign_SECRETKEYBYTES = 64,
10673 crypto_sign_SEEDBYTES = 32;
10674
10675function checkArrayTypes() {
10676 for (var i = 0; i < arguments.length; i++) {
10677 if (!(arguments[i] instanceof Uint8Array))
10678 throw new TypeError('unexpected type, use Uint8Array');
10679 }
10680}
10681
10682function cleanup(arr) {
10683 for (var i = 0; i < arr.length; i++) arr[i] = 0;
10684}
10685
10686nacl.scalarMult = function(n, p) {
10687 checkArrayTypes(n, p);
10688 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
10689 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
10690 var q = new Uint8Array(crypto_scalarmult_BYTES);
10691 crypto_scalarmult(q, n, p);
10692 return q;
10693};
10694
10695nacl.box = {};
10696
10697nacl.box.keyPair = function() {
10698 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
10699 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
10700 crypto_box_keypair(pk, sk);
10701 return {publicKey: pk, secretKey: sk};
10702};
10703
10704nacl.box.keyPair.fromSecretKey = function(secretKey) {
10705 checkArrayTypes(secretKey);
10706 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
10707 throw new Error('bad secret key size');
10708 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
10709 crypto_scalarmult_base(pk, secretKey);
10710 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
10711};
10712
10713nacl.sign = function(msg, secretKey) {
10714 checkArrayTypes(msg, secretKey);
10715 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
10716 throw new Error('bad secret key size');
10717 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
10718 crypto_sign(signedMsg, msg, msg.length, secretKey);
10719 return signedMsg;
10720};
10721
10722nacl.sign.detached = function(msg, secretKey) {
10723 var signedMsg = nacl.sign(msg, secretKey);
10724 var sig = new Uint8Array(crypto_sign_BYTES);
10725 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
10726 return sig;
10727};
10728
10729nacl.sign.detached.verify = function(msg, sig, publicKey) {
10730 checkArrayTypes(msg, sig, publicKey);
10731 if (sig.length !== crypto_sign_BYTES)
10732 throw new Error('bad signature size');
10733 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
10734 throw new Error('bad public key size');
10735 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
10736 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
10737 var i;
10738 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
10739 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
10740 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
10741};
10742
10743nacl.sign.keyPair = function() {
10744 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10745 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
10746 crypto_sign_keypair(pk, sk);
10747 return {publicKey: pk, secretKey: sk};
10748};
10749
10750nacl.sign.keyPair.fromSecretKey = function(secretKey) {
10751 checkArrayTypes(secretKey);
10752 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
10753 throw new Error('bad secret key size');
10754 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10755 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
10756 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
10757};
10758
10759nacl.sign.keyPair.fromSeed = function(seed) {
10760 checkArrayTypes(seed);
10761 if (seed.length !== crypto_sign_SEEDBYTES)
10762 throw new Error('bad seed size');
10763 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
10764 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
10765 for (var i = 0; i < 32; i++) sk[i] = seed[i];
10766 crypto_sign_keypair(pk, sk, true);
10767 return {publicKey: pk, secretKey: sk};
10768};
10769
10770nacl.setPRNG = function(fn) {
10771 randombytes = fn;
10772};
10773
10774(function() {
10775 // Initialize PRNG if environment provides CSPRNG.
10776 // If not, methods calling randombytes will throw.
10777 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
10778 if (crypto && crypto.getRandomValues) {
10779 // Browsers.
10780 var QUOTA = 65536;
10781 nacl.setPRNG(function(x, n) {
10782 var i, v = new Uint8Array(n);
10783 for (i = 0; i < n; i += QUOTA) {
10784 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
10785 }
10786 for (i = 0; i < n; i++) x[i] = v[i];
10787 cleanup(v);
10788 });
10789 } else if (typeof commonjsRequire !== 'undefined') {
10790 // Node.js.
10791 crypto = crypto__default['default'];
10792 if (crypto && crypto.randomBytes) {
10793 nacl.setPRNG(function(x, n) {
10794 var i, v = crypto.randomBytes(n);
10795 for (i = 0; i < n; i++) x[i] = v[i];
10796 cleanup(v);
10797 });
10798 }
10799 }
10800})();
10801
10802})(module.exports ? module.exports : (self.nacl = self.nacl || {}));
10803});
10804
10805// GPG4Browsers - An OpenPGP implementation in javascript
10806
10807const nodeCrypto$1 = util.getNodeCrypto();
10808
10809/**
10810 * Buffer for secure random numbers
10811 */
10812class RandomBuffer {
10813 constructor() {
10814 this.buffer = null;
10815 this.size = null;
10816 this.callback = null;
10817 }
10818
10819 /**
10820 * Initialize buffer
10821 * @param {Integer} size - size of buffer
10822 */
10823 init(size, callback) {
10824 this.buffer = new Uint8Array(size);
10825 this.size = 0;
10826 this.callback = callback;
10827 }
10828
10829 /**
10830 * Concat array of secure random numbers to buffer
10831 * @param {Uint8Array} buf
10832 */
10833 set(buf) {
10834 if (!this.buffer) {
10835 throw new Error('RandomBuffer is not initialized');
10836 }
10837 if (!(buf instanceof Uint8Array)) {
10838 throw new Error('Invalid type: buf not an Uint8Array');
10839 }
10840 const freeSpace = this.buffer.length - this.size;
10841 if (buf.length > freeSpace) {
10842 buf = buf.subarray(0, freeSpace);
10843 }
10844 // set buf with offset old size of buffer
10845 this.buffer.set(buf, this.size);
10846 this.size += buf.length;
10847 }
10848
10849 /**
10850 * Take numbers out of buffer and copy to array
10851 * @param {Uint8Array} buf - The destination array
10852 */
10853 async get(buf) {
10854 if (!this.buffer) {
10855 throw new Error('RandomBuffer is not initialized');
10856 }
10857 if (!(buf instanceof Uint8Array)) {
10858 throw new Error('Invalid type: buf not an Uint8Array');
10859 }
10860 if (this.size < buf.length) {
10861 if (!this.callback) {
10862 throw new Error('Random number buffer depleted');
10863 }
10864 // Wait for random bytes from main context, then try again
10865 await this.callback();
10866 return this.get(buf);
10867 }
10868 for (let i = 0; i < buf.length; i++) {
10869 buf[i] = this.buffer[--this.size];
10870 // clear buffer value
10871 this.buffer[this.size] = 0;
10872 }
10873 }
10874}
10875
10876/**
10877 * Retrieve secure random byte array of the specified length
10878 * @param {Integer} length - Length in bytes to generate
10879 * @returns {Promise<Uint8Array>} Random byte array.
10880 * @async
10881 */
10882async function getRandomBytes(length) {
10883 const buf = new Uint8Array(length);
10884 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
10885 crypto.getRandomValues(buf);
10886 } else if (nodeCrypto$1) {
10887 const bytes = nodeCrypto$1.randomBytes(buf.length);
10888 buf.set(bytes);
10889 } else if (randomBuffer.buffer) {
10890 await randomBuffer.get(buf);
10891 } else {
10892 throw new Error('No secure random number generator available.');
10893 }
10894 return buf;
10895}
10896
10897/**
10898 * Create a secure random BigInteger that is greater than or equal to min and less than max.
10899 * @param {module:BigInteger} min - Lower bound, included
10900 * @param {module:BigInteger} max - Upper bound, excluded
10901 * @returns {Promise<module:BigInteger>} Random BigInteger.
10902 * @async
10903 */
10904async function getRandomBigInteger(min, max) {
10905 const BigInteger = await util.getBigInteger();
10906
10907 if (max.lt(min)) {
10908 throw new Error('Illegal parameter value: max <= min');
10909 }
10910
10911 const modulus = max.sub(min);
10912 const bytes = modulus.byteLength();
10913
10914 // Using a while loop is necessary to avoid bias introduced by the mod operation.
10915 // However, we request 64 extra random bits so that the bias is negligible.
10916 // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
10917 const r = new BigInteger(await getRandomBytes(bytes + 8));
10918 return r.mod(modulus).add(min);
10919}
10920
10921const randomBuffer = new RandomBuffer();
10922
10923var random = /*#__PURE__*/Object.freeze({
10924 __proto__: null,
10925 getRandomBytes: getRandomBytes,
10926 getRandomBigInteger: getRandomBigInteger,
10927 randomBuffer: randomBuffer
10928});
10929
10930// OpenPGP.js - An OpenPGP implementation in javascript
10931
10932/**
10933 * Generate a probably prime random number
10934 * @param {Integer} bits - Bit length of the prime
10935 * @param {BigInteger} e - Optional RSA exponent to check against the prime
10936 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
10937 * @returns BigInteger
10938 * @async
10939 */
10940async function randomProbablePrime(bits, e, k) {
10941 const BigInteger = await util.getBigInteger();
10942 const one = new BigInteger(1);
10943 const min = one.leftShift(new BigInteger(bits - 1));
10944 const thirty = new BigInteger(30);
10945 /*
10946 * We can avoid any multiples of 3 and 5 by looking at n mod 30
10947 * 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
10948 * the next possible prime is mod 30:
10949 * 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
10950 */
10951 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];
10952
10953 const n = await getRandomBigInteger(min, min.leftShift(one));
10954 let i = n.mod(thirty).toNumber();
10955
10956 do {
10957 n.iadd(new BigInteger(adds[i]));
10958 i = (i + adds[i]) % adds.length;
10959 // If reached the maximum, go back to the minimum.
10960 if (n.bitLength() > bits) {
10961 n.imod(min.leftShift(one)).iadd(min);
10962 i = n.mod(thirty).toNumber();
10963 }
10964 } while (!await isProbablePrime(n, e, k));
10965 return n;
10966}
10967
10968/**
10969 * Probabilistic primality testing
10970 * @param {BigInteger} n - Number to test
10971 * @param {BigInteger} e - Optional RSA exponent to check against the prime
10972 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
10973 * @returns {boolean}
10974 * @async
10975 */
10976async function isProbablePrime(n, e, k) {
10977 if (e && !n.dec().gcd(e).isOne()) {
10978 return false;
10979 }
10980 if (!await divisionTest(n)) {
10981 return false;
10982 }
10983 if (!await fermat(n)) {
10984 return false;
10985 }
10986 if (!await millerRabin(n, k)) {
10987 return false;
10988 }
10989 // TODO implement the Lucas test
10990 // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
10991 return true;
10992}
10993
10994/**
10995 * Tests whether n is probably prime or not using Fermat's test with b = 2.
10996 * Fails if b^(n-1) mod n != 1.
10997 * @param {BigInteger} n - Number to test
10998 * @param {BigInteger} b - Optional Fermat test base
10999 * @returns {boolean}
11000 */
11001async function fermat(n, b) {
11002 const BigInteger = await util.getBigInteger();
11003 b = b || new BigInteger(2);
11004 return b.modExp(n.dec(), n).isOne();
11005}
11006
11007async function divisionTest(n) {
11008 const BigInteger = await util.getBigInteger();
11009 return smallPrimes.every(m => {
11010 return n.mod(new BigInteger(m)) !== 0;
11011 });
11012}
11013
11014// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
11015const smallPrimes = [
11016 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
11017 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
11018 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
11019 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
11020 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
11021 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
11022 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
11023 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
11024 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
11025 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
11026 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
11027 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
11028 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
11029 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
11030 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
11031 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
11032 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
11033 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
11034 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
11035 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
11036 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
11037 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
11038 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
11039 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
11040 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
11041 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
11042 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
11043 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
11044 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
11045 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
11046 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
11047 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
11048 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
11049 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
11050 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
11051 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
11052 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
11053 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
11054 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
11055 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
11056 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
11057 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
11058 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
11059 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
11060 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
11061 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
11062 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
11063 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
11064 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
11065 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
11066 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
11067 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
11068 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
11069 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
11070 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
11071 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
11072 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
11073 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
11074 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
11075 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
11076 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
11077 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
11078 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
11079 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
11080 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
11081 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
11082 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
11083 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
11084 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
11085 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
11086 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
11087 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
11088 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
11089 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
11090 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
11091 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
11092 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
11093 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
11094 4957, 4967, 4969, 4973, 4987, 4993, 4999
11095];
11096
11097
11098// Miller-Rabin - Miller Rabin algorithm for primality test
11099// Copyright Fedor Indutny, 2014.
11100//
11101// This software is licensed under the MIT License.
11102//
11103// Permission is hereby granted, free of charge, to any person obtaining a
11104// copy of this software and associated documentation files (the
11105// "Software"), to deal in the Software without restriction, including
11106// without limitation the rights to use, copy, modify, merge, publish,
11107// distribute, sublicense, and/or sell copies of the Software, and to permit
11108// persons to whom the Software is furnished to do so, subject to the
11109// following conditions:
11110//
11111// The above copyright notice and this permission notice shall be included
11112// in all copies or substantial portions of the Software.
11113//
11114// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11115// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11116// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11117// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11118// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11119// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11120// USE OR OTHER DEALINGS IN THE SOFTWARE.
11121
11122// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
11123
11124// Sample syntax for Fixed-Base Miller-Rabin:
11125// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
11126
11127/**
11128 * Tests whether n is probably prime or not using the Miller-Rabin test.
11129 * See HAC Remark 4.28.
11130 * @param {BigInteger} n - Number to test
11131 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
11132 * @param {Function} rand - Optional function to generate potential witnesses
11133 * @returns {boolean}
11134 * @async
11135 */
11136async function millerRabin(n, k, rand) {
11137 const BigInteger = await util.getBigInteger();
11138 const len = n.bitLength();
11139
11140 if (!k) {
11141 k = Math.max(1, (len / 48) | 0);
11142 }
11143
11144 const n1 = n.dec(); // n - 1
11145
11146 // Find d and s, (n - 1) = (2 ^ s) * d;
11147 let s = 0;
11148 while (!n1.getBit(s)) { s++; }
11149 const d = n.rightShift(new BigInteger(s));
11150
11151 for (; k > 0; k--) {
11152 const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);
11153
11154 let x = a.modExp(d, n);
11155 if (x.isOne() || x.equal(n1)) {
11156 continue;
11157 }
11158
11159 let i;
11160 for (i = 1; i < s; i++) {
11161 x = x.mul(x).mod(n);
11162
11163 if (x.isOne()) {
11164 return false;
11165 }
11166 if (x.equal(n1)) {
11167 break;
11168 }
11169 }
11170
11171 if (i === s) {
11172 return false;
11173 }
11174 }
11175
11176 return true;
11177}
11178
11179// GPG4Browsers - An OpenPGP implementation in javascript
11180
11181/**
11182 * ASN1 object identifiers for hashes
11183 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
11184 */
11185const hash_headers = [];
11186hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
11187 0x10];
11188hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
11189hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
11190hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
11191 0x04, 0x20];
11192hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
11193 0x04, 0x30];
11194hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
11195 0x00, 0x04, 0x40];
11196hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
11197 0x00, 0x04, 0x1C];
11198
11199/**
11200 * Create padding with secure random data
11201 * @private
11202 * @param {Integer} length - Length of the padding in bytes
11203 * @returns {Promise<Uint8Array>} Random padding.
11204 * @async
11205 */
11206async function getPKCS1Padding(length) {
11207 const result = new Uint8Array(length);
11208 let count = 0;
11209 while (count < length) {
11210 const randomBytes = await getRandomBytes(length - count);
11211 for (let i = 0; i < randomBytes.length; i++) {
11212 if (randomBytes[i] !== 0) {
11213 result[count++] = randomBytes[i];
11214 }
11215 }
11216 }
11217 return result;
11218}
11219
11220/**
11221 * Create a EME-PKCS1-v1_5 padded message
11222 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
11223 * @param {Uint8Array} message - Message to be encoded
11224 * @param {Integer} keyLength - The length in octets of the key modulus
11225 * @returns {Promise<Uint8Array>} EME-PKCS1 padded message.
11226 * @async
11227 */
11228async function emeEncode(message, keyLength) {
11229 const mLength = message.length;
11230 // length checking
11231 if (mLength > keyLength - 11) {
11232 throw new Error('Message too long');
11233 }
11234 // Generate an octet string PS of length k - mLen - 3 consisting of
11235 // pseudo-randomly generated nonzero octets
11236 const PS = await getPKCS1Padding(keyLength - mLength - 3);
11237 // Concatenate PS, the message M, and other padding to form an
11238 // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
11239 const encoded = new Uint8Array(keyLength);
11240 // 0x00 byte
11241 encoded[1] = 2;
11242 encoded.set(PS, 2);
11243 // 0x00 bytes
11244 encoded.set(message, keyLength - mLength);
11245 return encoded;
11246}
11247
11248/**
11249 * Decode a EME-PKCS1-v1_5 padded message
11250 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
11251 * @param {Uint8Array} encoded - Encoded message bytes
11252 * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)
11253 * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)
11254 * @throws {Error} on decoding failure, unless `randomPayload` is provided
11255 */
11256function emeDecode(encoded, randomPayload) {
11257 // encoded format: 0x00 0x02 <PS> 0x00 <payload>
11258 let offset = 2;
11259 let separatorNotFound = 1;
11260 for (let j = offset; j < encoded.length; j++) {
11261 separatorNotFound &= encoded[j] !== 0;
11262 offset += separatorNotFound;
11263 }
11264
11265 const psLen = offset - 2;
11266 const payload = encoded.subarray(offset + 1); // discard the 0x00 separator
11267 const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;
11268
11269 if (randomPayload) {
11270 return util.selectUint8Array(isValidPadding, payload, randomPayload);
11271 }
11272
11273 if (isValidPadding) {
11274 return payload;
11275 }
11276
11277 throw new Error('Decryption error');
11278}
11279
11280/**
11281 * Create a EMSA-PKCS1-v1_5 padded message
11282 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
11283 * @param {Integer} algo - Hash algorithm type used
11284 * @param {Uint8Array} hashed - Message to be encoded
11285 * @param {Integer} emLen - Intended length in octets of the encoded message
11286 * @returns {Uint8Array} Encoded message.
11287 */
11288async function emsaEncode(algo, hashed, emLen) {
11289 let i;
11290 if (hashed.length !== hash.getHashByteLength(algo)) {
11291 throw new Error('Invalid hash length');
11292 }
11293 // produce an ASN.1 DER value for the hash function used.
11294 // Let T be the full hash prefix
11295 const hashPrefix = new Uint8Array(hash_headers[algo].length);
11296 for (i = 0; i < hash_headers[algo].length; i++) {
11297 hashPrefix[i] = hash_headers[algo][i];
11298 }
11299 // and let tLen be the length in octets prefix and hashed data
11300 const tLen = hashPrefix.length + hashed.length;
11301 if (emLen < tLen + 11) {
11302 throw new Error('Intended encoded message length too short');
11303 }
11304 // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
11305 // The length of PS will be at least 8 octets
11306 const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
11307
11308 // Concatenate PS, the hash prefix, hashed data, and other padding to form the
11309 // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
11310 const EM = new Uint8Array(emLen);
11311 EM[1] = 0x01;
11312 EM.set(PS, 2);
11313 EM.set(hashPrefix, emLen - tLen);
11314 EM.set(hashed, emLen - hashed.length);
11315 return EM;
11316}
11317
11318var pkcs1 = /*#__PURE__*/Object.freeze({
11319 __proto__: null,
11320 emeEncode: emeEncode,
11321 emeDecode: emeDecode,
11322 emsaEncode: emsaEncode
11323});
11324
11325const webCrypto$1 = util.getWebCrypto();
11326const nodeCrypto$2 = util.getNodeCrypto();
11327const asn1 = nodeCrypto$2 ? asn1__default['default'] : undefined;
11328
11329/* eslint-disable no-invalid-this */
11330const RSAPrivateKey = nodeCrypto$2 ? asn1.define('RSAPrivateKey', function () {
11331 this.seq().obj( // used for native NodeJS crypto
11332 this.key('version').int(), // 0
11333 this.key('modulus').int(), // n
11334 this.key('publicExponent').int(), // e
11335 this.key('privateExponent').int(), // d
11336 this.key('prime1').int(), // p
11337 this.key('prime2').int(), // q
11338 this.key('exponent1').int(), // dp
11339 this.key('exponent2').int(), // dq
11340 this.key('coefficient').int() // u
11341 );
11342}) : undefined;
11343
11344const RSAPublicKey = nodeCrypto$2 ? asn1.define('RSAPubliceKey', function () {
11345 this.seq().obj( // used for native NodeJS crypto
11346 this.key('modulus').int(), // n
11347 this.key('publicExponent').int(), // e
11348 );
11349}) : undefined;
11350/* eslint-enable no-invalid-this */
11351
11352/** Create signature
11353 * @param {module:enums.hash} hashAlgo - Hash algorithm
11354 * @param {Uint8Array} data - Message
11355 * @param {Uint8Array} n - RSA public modulus
11356 * @param {Uint8Array} e - RSA public exponent
11357 * @param {Uint8Array} d - RSA private exponent
11358 * @param {Uint8Array} p - RSA private prime p
11359 * @param {Uint8Array} q - RSA private prime q
11360 * @param {Uint8Array} u - RSA private coefficient
11361 * @param {Uint8Array} hashed - Hashed message
11362 * @returns {Promise<Uint8Array>} RSA Signature.
11363 * @async
11364 */
11365async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {
11366 if (data && !util.isStream(data)) {
11367 if (util.getWebCrypto()) {
11368 try {
11369 return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);
11370 } catch (err) {
11371 util.printDebugError(err);
11372 }
11373 } else if (util.getNodeCrypto()) {
11374 return nodeSign(hashAlgo, data, n, e, d, p, q, u);
11375 }
11376 }
11377 return bnSign(hashAlgo, n, d, hashed);
11378}
11379
11380/**
11381 * Verify signature
11382 * @param {module:enums.hash} hashAlgo - Hash algorithm
11383 * @param {Uint8Array} data - Message
11384 * @param {Uint8Array} s - Signature
11385 * @param {Uint8Array} n - RSA public modulus
11386 * @param {Uint8Array} e - RSA public exponent
11387 * @param {Uint8Array} hashed - Hashed message
11388 * @returns {Boolean}
11389 * @async
11390 */
11391async function verify(hashAlgo, data, s, n, e, hashed) {
11392 if (data && !util.isStream(data)) {
11393 if (util.getWebCrypto()) {
11394 try {
11395 return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);
11396 } catch (err) {
11397 util.printDebugError(err);
11398 }
11399 } else if (util.getNodeCrypto()) {
11400 return nodeVerify(hashAlgo, data, s, n, e);
11401 }
11402 }
11403 return bnVerify(hashAlgo, s, n, e, hashed);
11404}
11405
11406/**
11407 * Encrypt message
11408 * @param {Uint8Array} data - Message
11409 * @param {Uint8Array} n - RSA public modulus
11410 * @param {Uint8Array} e - RSA public exponent
11411 * @returns {Promise<Uint8Array>} RSA Ciphertext.
11412 * @async
11413 */
11414async function encrypt(data, n, e) {
11415 if (util.getNodeCrypto()) {
11416 return nodeEncrypt(data, n, e);
11417 }
11418 return bnEncrypt(data, n, e);
11419}
11420
11421/**
11422 * Decrypt RSA message
11423 * @param {Uint8Array} m - Message
11424 * @param {Uint8Array} n - RSA public modulus
11425 * @param {Uint8Array} e - RSA public exponent
11426 * @param {Uint8Array} d - RSA private exponent
11427 * @param {Uint8Array} p - RSA private prime p
11428 * @param {Uint8Array} q - RSA private prime q
11429 * @param {Uint8Array} u - RSA private coefficient
11430 * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing
11431 * (needed for constant-time processing)
11432 * @returns {Promise<String>} RSA Plaintext.
11433 * @throws {Error} on decryption error, unless `randomPayload` is given
11434 * @async
11435 */
11436async function decrypt(data, n, e, d, p, q, u, randomPayload) {
11437 if (util.getNodeCrypto()) {
11438 return nodeDecrypt(data, n, e, d, p, q, u, randomPayload);
11439 }
11440 return bnDecrypt(data, n, e, d, p, q, u, randomPayload);
11441}
11442
11443/**
11444 * Generate a new random private key B bits long with public exponent E.
11445 *
11446 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
11447 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
11448 * @see module:crypto/public_key/prime
11449 * @param {Integer} bits - RSA bit length
11450 * @param {Integer} e - RSA public exponent
11451 * @returns {{n, e, d,
11452 * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,
11453 * RSA private prime p, RSA private prime q, u = p ** -1 mod q
11454 * @async
11455 */
11456async function generate(bits, e) {
11457 const BigInteger = await util.getBigInteger();
11458
11459 e = new BigInteger(e);
11460
11461 // Native RSA keygen using Web Crypto
11462 if (util.getWebCrypto()) {
11463 const keyGenOpt = {
11464 name: 'RSASSA-PKCS1-v1_5',
11465 modulusLength: bits, // the specified keysize in bits
11466 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
11467 hash: {
11468 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
11469 }
11470 };
11471 const keyPair = await webCrypto$1.generateKey(keyGenOpt, true, ['sign', 'verify']);
11472
11473 // export the generated keys as JsonWebKey (JWK)
11474 // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
11475 const jwk = await webCrypto$1.exportKey('jwk', keyPair.privateKey);
11476 // map JWK parameters to corresponding OpenPGP names
11477 return {
11478 n: b64ToUint8Array(jwk.n),
11479 e: e.toUint8Array(),
11480 d: b64ToUint8Array(jwk.d),
11481 // switch p and q
11482 p: b64ToUint8Array(jwk.q),
11483 q: b64ToUint8Array(jwk.p),
11484 // Since p and q are switched in places, u is the inverse of jwk.q
11485 u: b64ToUint8Array(jwk.qi)
11486 };
11487 } else if (util.getNodeCrypto() && nodeCrypto$2.generateKeyPair && RSAPrivateKey) {
11488 const opts = {
11489 modulusLength: bits,
11490 publicExponent: e.toNumber(),
11491 publicKeyEncoding: { type: 'pkcs1', format: 'der' },
11492 privateKeyEncoding: { type: 'pkcs1', format: 'der' }
11493 };
11494 const prv = await new Promise((resolve, reject) => nodeCrypto$2.generateKeyPair('rsa', opts, (err, _, der) => {
11495 if (err) {
11496 reject(err);
11497 } else {
11498 resolve(RSAPrivateKey.decode(der, 'der'));
11499 }
11500 }));
11501 /**
11502 * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.
11503 * @link https://tools.ietf.org/html/rfc3447#section-3.2
11504 * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
11505 */
11506 return {
11507 n: prv.modulus.toArrayLike(Uint8Array),
11508 e: prv.publicExponent.toArrayLike(Uint8Array),
11509 d: prv.privateExponent.toArrayLike(Uint8Array),
11510 // switch p and q
11511 p: prv.prime2.toArrayLike(Uint8Array),
11512 q: prv.prime1.toArrayLike(Uint8Array),
11513 // Since p and q are switched in places, we can keep u as defined by DER
11514 u: prv.coefficient.toArrayLike(Uint8Array)
11515 };
11516 }
11517
11518 // RSA keygen fallback using 40 iterations of the Miller-Rabin test
11519 // See https://stackoverflow.com/a/6330138 for justification
11520 // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
11521 let p;
11522 let q;
11523 let n;
11524 do {
11525 q = await randomProbablePrime(bits - (bits >> 1), e, 40);
11526 p = await randomProbablePrime(bits >> 1, e, 40);
11527 n = p.mul(q);
11528 } while (n.bitLength() !== bits);
11529
11530 const phi = p.dec().imul(q.dec());
11531
11532 if (q.lt(p)) {
11533 [p, q] = [q, p];
11534 }
11535
11536 return {
11537 n: n.toUint8Array(),
11538 e: e.toUint8Array(),
11539 d: e.modInv(phi).toUint8Array(),
11540 p: p.toUint8Array(),
11541 q: q.toUint8Array(),
11542 // dp: d.mod(p.subn(1)),
11543 // dq: d.mod(q.subn(1)),
11544 u: p.modInv(q).toUint8Array()
11545 };
11546}
11547
11548/**
11549 * Validate RSA parameters
11550 * @param {Uint8Array} n - RSA public modulus
11551 * @param {Uint8Array} e - RSA public exponent
11552 * @param {Uint8Array} d - RSA private exponent
11553 * @param {Uint8Array} p - RSA private prime p
11554 * @param {Uint8Array} q - RSA private prime q
11555 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
11556 * @returns {Promise<Boolean>} Whether params are valid.
11557 * @async
11558 */
11559async function validateParams(n, e, d, p, q, u) {
11560 const BigInteger = await util.getBigInteger();
11561 n = new BigInteger(n);
11562 p = new BigInteger(p);
11563 q = new BigInteger(q);
11564
11565 // expect pq = n
11566 if (!p.mul(q).equal(n)) {
11567 return false;
11568 }
11569
11570 const two = new BigInteger(2);
11571 // expect p*u = 1 mod q
11572 u = new BigInteger(u);
11573 if (!p.mul(u).mod(q).isOne()) {
11574 return false;
11575 }
11576
11577 e = new BigInteger(e);
11578 d = new BigInteger(d);
11579 /**
11580 * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
11581 * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
11582 * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
11583 *
11584 * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
11585 */
11586 const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));
11587 const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q
11588 const rde = r.mul(d).mul(e);
11589
11590 const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);
11591 if (!areInverses) {
11592 return false;
11593 }
11594
11595 return true;
11596}
11597
11598async function bnSign(hashAlgo, n, d, hashed) {
11599 const BigInteger = await util.getBigInteger();
11600 n = new BigInteger(n);
11601 const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));
11602 d = new BigInteger(d);
11603 if (m.gte(n)) {
11604 throw new Error('Message size cannot exceed modulus size');
11605 }
11606 return m.modExp(d, n).toUint8Array('be', n.byteLength());
11607}
11608
11609async function webSign(hashName, data, n, e, d, p, q, u) {
11610 /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
11611 * We swap them in privateToJWK, so it usually works out, but nevertheless,
11612 * not all OpenPGP keys are compatible with this requirement.
11613 * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
11614 * does if the underlying Web Crypto does so (though the tested implementations
11615 * don't do so).
11616 */
11617 const jwk = await privateToJWK(n, e, d, p, q, u);
11618 const algo = {
11619 name: 'RSASSA-PKCS1-v1_5',
11620 hash: { name: hashName }
11621 };
11622 const key = await webCrypto$1.importKey('jwk', jwk, algo, false, ['sign']);
11623 return new Uint8Array(await webCrypto$1.sign('RSASSA-PKCS1-v1_5', key, data));
11624}
11625
11626async function nodeSign(hashAlgo, data, n, e, d, p, q, u) {
11627 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11628 const pBNum = new BN(p);
11629 const qBNum = new BN(q);
11630 const dBNum = new BN(d);
11631 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
11632 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
11633 const sign = nodeCrypto$2.createSign(enums.read(enums.hash, hashAlgo));
11634 sign.write(data);
11635 sign.end();
11636 const keyObject = {
11637 version: 0,
11638 modulus: new BN(n),
11639 publicExponent: new BN(e),
11640 privateExponent: new BN(d),
11641 // switch p and q
11642 prime1: new BN(q),
11643 prime2: new BN(p),
11644 // switch dp and dq
11645 exponent1: dq,
11646 exponent2: dp,
11647 coefficient: new BN(u)
11648 };
11649 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
11650 const der = RSAPrivateKey.encode(keyObject, 'der');
11651 return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
11652 }
11653 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
11654 label: 'RSA PRIVATE KEY'
11655 });
11656 return new Uint8Array(sign.sign(pem));
11657}
11658
11659async function bnVerify(hashAlgo, s, n, e, hashed) {
11660 const BigInteger = await util.getBigInteger();
11661 n = new BigInteger(n);
11662 s = new BigInteger(s);
11663 e = new BigInteger(e);
11664 if (s.gte(n)) {
11665 throw new Error('Signature size cannot exceed modulus size');
11666 }
11667 const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());
11668 const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());
11669 return util.equalsUint8Array(EM1, EM2);
11670}
11671
11672async function webVerify(hashName, data, s, n, e) {
11673 const jwk = publicToJWK(n, e);
11674 const key = await webCrypto$1.importKey('jwk', jwk, {
11675 name: 'RSASSA-PKCS1-v1_5',
11676 hash: { name: hashName }
11677 }, false, ['verify']);
11678 return webCrypto$1.verify('RSASSA-PKCS1-v1_5', key, s, data);
11679}
11680
11681async function nodeVerify(hashAlgo, data, s, n, e) {
11682 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11683
11684 const verify = nodeCrypto$2.createVerify(enums.read(enums.hash, hashAlgo));
11685 verify.write(data);
11686 verify.end();
11687 const keyObject = {
11688 modulus: new BN(n),
11689 publicExponent: new BN(e)
11690 };
11691 let key;
11692 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
11693 const der = RSAPublicKey.encode(keyObject, 'der');
11694 key = { key: der, format: 'der', type: 'pkcs1' };
11695 } else {
11696 key = RSAPublicKey.encode(keyObject, 'pem', {
11697 label: 'RSA PUBLIC KEY'
11698 });
11699 }
11700 try {
11701 return await verify.verify(key, s);
11702 } catch (err) {
11703 return false;
11704 }
11705}
11706
11707async function nodeEncrypt(data, n, e) {
11708 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11709
11710 const keyObject = {
11711 modulus: new BN(n),
11712 publicExponent: new BN(e)
11713 };
11714 let key;
11715 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') {
11716 const der = RSAPublicKey.encode(keyObject, 'der');
11717 key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11718 } else {
11719 const pem = RSAPublicKey.encode(keyObject, 'pem', {
11720 label: 'RSA PUBLIC KEY'
11721 });
11722 key = { key: pem, padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11723 }
11724 return new Uint8Array(nodeCrypto$2.publicEncrypt(key, data));
11725}
11726
11727async function bnEncrypt(data, n, e) {
11728 const BigInteger = await util.getBigInteger();
11729 n = new BigInteger(n);
11730 data = new BigInteger(await emeEncode(data, n.byteLength()));
11731 e = new BigInteger(e);
11732 if (data.gte(n)) {
11733 throw new Error('Message size cannot exceed modulus size');
11734 }
11735 return data.modExp(e, n).toUint8Array('be', n.byteLength());
11736}
11737
11738async function nodeDecrypt(data, n, e, d, p, q, u, randomPayload) {
11739 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
11740
11741 const pBNum = new BN(p);
11742 const qBNum = new BN(q);
11743 const dBNum = new BN(d);
11744 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
11745 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
11746 const keyObject = {
11747 version: 0,
11748 modulus: new BN(n),
11749 publicExponent: new BN(e),
11750 privateExponent: new BN(d),
11751 // switch p and q
11752 prime1: new BN(q),
11753 prime2: new BN(p),
11754 // switch dp and dq
11755 exponent1: dq,
11756 exponent2: dp,
11757 coefficient: new BN(u)
11758 };
11759 let key;
11760 if (typeof nodeCrypto$2.createPrivateKey !== 'undefined') {
11761 const der = RSAPrivateKey.encode(keyObject, 'der');
11762 key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11763 } else {
11764 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
11765 label: 'RSA PRIVATE KEY'
11766 });
11767 key = { key: pem, padding: nodeCrypto$2.constants.RSA_PKCS1_PADDING };
11768 }
11769 try {
11770 return new Uint8Array(nodeCrypto$2.privateDecrypt(key, data));
11771 } catch (err) {
11772 if (randomPayload) {
11773 return randomPayload;
11774 }
11775 throw new Error('Decryption error');
11776 }
11777}
11778
11779async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {
11780 const BigInteger = await util.getBigInteger();
11781 data = new BigInteger(data);
11782 n = new BigInteger(n);
11783 e = new BigInteger(e);
11784 d = new BigInteger(d);
11785 p = new BigInteger(p);
11786 q = new BigInteger(q);
11787 u = new BigInteger(u);
11788 if (data.gte(n)) {
11789 throw new Error('Data too large.');
11790 }
11791 const dq = d.mod(q.dec()); // d mod (q-1)
11792 const dp = d.mod(p.dec()); // d mod (p-1)
11793
11794 const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);
11795 const blinder = unblinder.modInv(n).modExp(e, n);
11796 data = data.mul(blinder).mod(n);
11797
11798
11799 const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p
11800 const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q
11801 const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)
11802
11803 let result = h.mul(p).add(mp); // result < n due to relations above
11804
11805 result = result.mul(unblinder).mod(n);
11806
11807
11808 return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);
11809}
11810
11811/** Convert Openpgp private key params to jwk key according to
11812 * @link https://tools.ietf.org/html/rfc7517
11813 * @param {String} hashAlgo
11814 * @param {Uint8Array} n
11815 * @param {Uint8Array} e
11816 * @param {Uint8Array} d
11817 * @param {Uint8Array} p
11818 * @param {Uint8Array} q
11819 * @param {Uint8Array} u
11820 */
11821async function privateToJWK(n, e, d, p, q, u) {
11822 const BigInteger = await util.getBigInteger();
11823 const pNum = new BigInteger(p);
11824 const qNum = new BigInteger(q);
11825 const dNum = new BigInteger(d);
11826
11827 let dq = dNum.mod(qNum.dec()); // d mod (q-1)
11828 let dp = dNum.mod(pNum.dec()); // d mod (p-1)
11829 dp = dp.toUint8Array();
11830 dq = dq.toUint8Array();
11831 return {
11832 kty: 'RSA',
11833 n: uint8ArrayToB64(n, true),
11834 e: uint8ArrayToB64(e, true),
11835 d: uint8ArrayToB64(d, true),
11836 // switch p and q
11837 p: uint8ArrayToB64(q, true),
11838 q: uint8ArrayToB64(p, true),
11839 // switch dp and dq
11840 dp: uint8ArrayToB64(dq, true),
11841 dq: uint8ArrayToB64(dp, true),
11842 qi: uint8ArrayToB64(u, true),
11843 ext: true
11844 };
11845}
11846
11847/** Convert Openpgp key public params to jwk key according to
11848 * @link https://tools.ietf.org/html/rfc7517
11849 * @param {String} hashAlgo
11850 * @param {Uint8Array} n
11851 * @param {Uint8Array} e
11852 */
11853function publicToJWK(n, e) {
11854 return {
11855 kty: 'RSA',
11856 n: uint8ArrayToB64(n, true),
11857 e: uint8ArrayToB64(e, true),
11858 ext: true
11859 };
11860}
11861
11862var rsa = /*#__PURE__*/Object.freeze({
11863 __proto__: null,
11864 sign: sign,
11865 verify: verify,
11866 encrypt: encrypt,
11867 decrypt: decrypt,
11868 generate: generate,
11869 validateParams: validateParams
11870});
11871
11872// GPG4Browsers - An OpenPGP implementation in javascript
11873
11874/**
11875 * ElGamal Encryption function
11876 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
11877 * @param {Uint8Array} data - To be padded and encrypted
11878 * @param {Uint8Array} p
11879 * @param {Uint8Array} g
11880 * @param {Uint8Array} y
11881 * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}
11882 * @async
11883 */
11884async function encrypt$1(data, p, g, y) {
11885 const BigInteger = await util.getBigInteger();
11886 p = new BigInteger(p);
11887 g = new BigInteger(g);
11888 y = new BigInteger(y);
11889
11890 const padded = await emeEncode(data, p.byteLength());
11891 const m = new BigInteger(padded);
11892
11893 // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
11894 // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
11895 const k = await getRandomBigInteger(new BigInteger(1), p.dec());
11896 return {
11897 c1: g.modExp(k, p).toUint8Array(),
11898 c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()
11899 };
11900}
11901
11902/**
11903 * ElGamal Encryption function
11904 * @param {Uint8Array} c1
11905 * @param {Uint8Array} c2
11906 * @param {Uint8Array} p
11907 * @param {Uint8Array} x
11908 * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing
11909 * (needed for constant-time processing)
11910 * @returns {Promise<Uint8Array>} Unpadded message.
11911 * @throws {Error} on decryption error, unless `randomPayload` is given
11912 * @async
11913 */
11914async function decrypt$1(c1, c2, p, x, randomPayload) {
11915 const BigInteger = await util.getBigInteger();
11916 c1 = new BigInteger(c1);
11917 c2 = new BigInteger(c2);
11918 p = new BigInteger(p);
11919 x = new BigInteger(x);
11920
11921 const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);
11922 return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);
11923}
11924
11925/**
11926 * Validate ElGamal parameters
11927 * @param {Uint8Array} p - ElGamal prime
11928 * @param {Uint8Array} g - ElGamal group generator
11929 * @param {Uint8Array} y - ElGamal public key
11930 * @param {Uint8Array} x - ElGamal private exponent
11931 * @returns {Promise<Boolean>} Whether params are valid.
11932 * @async
11933 */
11934async function validateParams$1(p, g, y, x) {
11935 const BigInteger = await util.getBigInteger();
11936 p = new BigInteger(p);
11937 g = new BigInteger(g);
11938 y = new BigInteger(y);
11939
11940 const one = new BigInteger(1);
11941 // Check that 1 < g < p
11942 if (g.lte(one) || g.gte(p)) {
11943 return false;
11944 }
11945
11946 // Expect p-1 to be large
11947 const pSize = new BigInteger(p.bitLength());
11948 const n1023 = new BigInteger(1023);
11949 if (pSize.lt(n1023)) {
11950 return false;
11951 }
11952
11953 /**
11954 * g should have order p-1
11955 * Check that g ** (p-1) = 1 mod p
11956 */
11957 if (!g.modExp(p.dec(), p).isOne()) {
11958 return false;
11959 }
11960
11961 /**
11962 * Since p-1 is not prime, g might have a smaller order that divides p-1
11963 * We want to make sure that the order is large enough to hinder a small subgroup attack
11964 *
11965 * We just check g**i != 1 for all i up to a threshold
11966 */
11967 let res = g;
11968 const i = new BigInteger(1);
11969 const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold
11970 while (i.lt(threshold)) {
11971 res = res.mul(g).imod(p);
11972 if (res.isOne()) {
11973 return false;
11974 }
11975 i.iinc();
11976 }
11977
11978 /**
11979 * Re-derive public key y' = g ** x mod p
11980 * Expect y == y'
11981 *
11982 * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
11983 */
11984 x = new BigInteger(x);
11985 const two = new BigInteger(2);
11986 const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1
11987 const rqx = p.dec().imul(r).iadd(x);
11988 if (!y.equal(g.modExp(rqx, p))) {
11989 return false;
11990 }
11991
11992 return true;
11993}
11994
11995var elgamal = /*#__PURE__*/Object.freeze({
11996 __proto__: null,
11997 encrypt: encrypt$1,
11998 decrypt: decrypt$1,
11999 validateParams: validateParams$1
12000});
12001
12002// OpenPGP.js - An OpenPGP implementation in javascript
12003
12004class OID {
12005 constructor(oid) {
12006 if (oid instanceof OID) {
12007 this.oid = oid.oid;
12008 } else if (util.isArray(oid) ||
12009 util.isUint8Array(oid)) {
12010 oid = new Uint8Array(oid);
12011 if (oid[0] === 0x06) { // DER encoded oid byte array
12012 if (oid[1] !== oid.length - 2) {
12013 throw new Error('Length mismatch in DER encoded oid');
12014 }
12015 oid = oid.subarray(2);
12016 }
12017 this.oid = oid;
12018 } else {
12019 this.oid = '';
12020 }
12021 }
12022
12023 /**
12024 * Method to read an OID object
12025 * @param {Uint8Array} input - Where to read the OID from
12026 * @returns {Number} Number of read bytes.
12027 */
12028 read(input) {
12029 if (input.length >= 1) {
12030 const length = input[0];
12031 if (input.length >= 1 + length) {
12032 this.oid = input.subarray(1, 1 + length);
12033 return 1 + this.oid.length;
12034 }
12035 }
12036 throw new Error('Invalid oid');
12037 }
12038
12039 /**
12040 * Serialize an OID object
12041 * @returns {Uint8Array} Array with the serialized value the OID.
12042 */
12043 write() {
12044 return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
12045 }
12046
12047 /**
12048 * Serialize an OID object as a hex string
12049 * @returns {string} String with the hex value of the OID.
12050 */
12051 toHex() {
12052 return util.uint8ArrayToHex(this.oid);
12053 }
12054
12055 /**
12056 * If a known curve object identifier, return the canonical name of the curve
12057 * @returns {string} String with the canonical name of the curve.
12058 */
12059 getName() {
12060 const hex = this.toHex();
12061 if (enums.curve[hex]) {
12062 return enums.write(enums.curve, hex);
12063 } else {
12064 throw new Error('Unknown curve object identifier.');
12065 }
12066 }
12067}
12068
12069// OpenPGP.js - An OpenPGP implementation in javascript
12070
12071function keyFromPrivate(indutnyCurve, priv) {
12072 const keyPair = indutnyCurve.keyPair({ priv: priv });
12073 return keyPair;
12074}
12075
12076function keyFromPublic(indutnyCurve, pub) {
12077 const keyPair = indutnyCurve.keyPair({ pub: pub });
12078 if (keyPair.validate().result !== true) {
12079 throw new Error('Invalid elliptic public key');
12080 }
12081 return keyPair;
12082}
12083
12084async function getIndutnyCurve(name) {
12085 if (!defaultConfig.useIndutnyElliptic) {
12086 throw new Error('This curve is only supported in the full build of OpenPGP.js');
12087 }
12088 const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; });
12089 return new elliptic.ec(name);
12090}
12091
12092// GPG4Browsers - An OpenPGP implementation in javascript
12093
12094function readSimpleLength(bytes) {
12095 let len = 0;
12096 let offset;
12097 const type = bytes[0];
12098
12099
12100 if (type < 192) {
12101 [len] = bytes;
12102 offset = 1;
12103 } else if (type < 255) {
12104 len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
12105 offset = 2;
12106 } else if (type === 255) {
12107 len = util.readNumber(bytes.subarray(1, 1 + 4));
12108 offset = 5;
12109 }
12110
12111 return {
12112 len: len,
12113 offset: offset
12114 };
12115}
12116
12117/**
12118 * Encodes a given integer of length to the openpgp length specifier to a
12119 * string
12120 *
12121 * @param {Integer} length - The length to encode
12122 * @returns {Uint8Array} String with openpgp length representation.
12123 */
12124function writeSimpleLength(length) {
12125 if (length < 192) {
12126 return new Uint8Array([length]);
12127 } else if (length > 191 && length < 8384) {
12128 /*
12129 * let a = (total data packet length) - 192 let bc = two octet
12130 * representation of a let d = b + 192
12131 */
12132 return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
12133 }
12134 return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
12135}
12136
12137function writePartialLength(power) {
12138 if (power < 0 || power > 30) {
12139 throw new Error('Partial Length power must be between 1 and 30');
12140 }
12141 return new Uint8Array([224 + power]);
12142}
12143
12144function writeTag(tag_type) {
12145 /* we're only generating v4 packet headers here */
12146 return new Uint8Array([0xC0 | tag_type]);
12147}
12148
12149/**
12150 * Writes a packet header version 4 with the given tag_type and length to a
12151 * string
12152 *
12153 * @param {Integer} tag_type - Tag type
12154 * @param {Integer} length - Length of the payload
12155 * @returns {String} String of the header.
12156 */
12157function writeHeader(tag_type, length) {
12158 /* we're only generating v4 packet headers here */
12159 return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
12160}
12161
12162/**
12163 * Whether the packet type supports partial lengths per RFC4880
12164 * @param {Integer} tag - Tag type
12165 * @returns {Boolean} String of the header.
12166 */
12167function supportsStreaming(tag) {
12168 return [
12169 enums.packet.literalData,
12170 enums.packet.compressedData,
12171 enums.packet.symmetricallyEncryptedData,
12172 enums.packet.symEncryptedIntegrityProtectedData,
12173 enums.packet.aeadEncryptedData
12174 ].includes(tag);
12175}
12176
12177/**
12178 * Generic static Packet Parser function
12179 *
12180 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
12181 * @param {Function} callback - Function to call with the parsed packet
12182 * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
12183 */
12184async function readPackets(input, callback) {
12185 const reader = getReader(input);
12186 let writer;
12187 let callbackReturned;
12188 try {
12189 const peekedBytes = await reader.peekBytes(2);
12190 // some sanity checks
12191 if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
12192 throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');
12193 }
12194 const headerByte = await reader.readByte();
12195 let tag = -1;
12196 let format = -1;
12197 let packetLength;
12198
12199 format = 0; // 0 = old format; 1 = new format
12200 if ((headerByte & 0x40) !== 0) {
12201 format = 1;
12202 }
12203
12204 let packetLengthType;
12205 if (format) {
12206 // new format header
12207 tag = headerByte & 0x3F; // bit 5-0
12208 } else {
12209 // old format header
12210 tag = (headerByte & 0x3F) >> 2; // bit 5-2
12211 packetLengthType = headerByte & 0x03; // bit 1-0
12212 }
12213
12214 const packetSupportsStreaming = supportsStreaming(tag);
12215 let packet = null;
12216 if (packetSupportsStreaming) {
12217 if (util.isStream(input) === 'array') {
12218 const arrayStream = new ArrayStream();
12219 writer = getWriter(arrayStream);
12220 packet = arrayStream;
12221 } else {
12222 const transform = new TransformStream();
12223 writer = getWriter(transform.writable);
12224 packet = transform.readable;
12225 }
12226 callbackReturned = callback({ tag, packet });
12227 } else {
12228 packet = [];
12229 }
12230
12231 let wasPartialLength;
12232 do {
12233 if (!format) {
12234 // 4.2.1. Old Format Packet Lengths
12235 switch (packetLengthType) {
12236 case 0:
12237 // The packet has a one-octet length. The header is 2 octets
12238 // long.
12239 packetLength = await reader.readByte();
12240 break;
12241 case 1:
12242 // The packet has a two-octet length. The header is 3 octets
12243 // long.
12244 packetLength = (await reader.readByte() << 8) | await reader.readByte();
12245 break;
12246 case 2:
12247 // The packet has a four-octet length. The header is 5
12248 // octets long.
12249 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
12250 8) | await reader.readByte();
12251 break;
12252 default:
12253 // 3 - The packet is of indeterminate length. The header is 1
12254 // octet long, and the implementation must determine how long
12255 // the packet is. If the packet is in a file, this means that
12256 // the packet extends until the end of the file. In general,
12257 // an implementation SHOULD NOT use indeterminate-length
12258 // packets except where the end of the data will be clear
12259 // from the context, and even then it is better to use a
12260 // definite length, or a new format header. The new format
12261 // headers described below have a mechanism for precisely
12262 // encoding data of indeterminate length.
12263 packetLength = Infinity;
12264 break;
12265 }
12266 } else { // 4.2.2. New Format Packet Lengths
12267 // 4.2.2.1. One-Octet Lengths
12268 const lengthByte = await reader.readByte();
12269 wasPartialLength = false;
12270 if (lengthByte < 192) {
12271 packetLength = lengthByte;
12272 // 4.2.2.2. Two-Octet Lengths
12273 } else if (lengthByte >= 192 && lengthByte < 224) {
12274 packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
12275 // 4.2.2.4. Partial Body Lengths
12276 } else if (lengthByte > 223 && lengthByte < 255) {
12277 packetLength = 1 << (lengthByte & 0x1F);
12278 wasPartialLength = true;
12279 if (!packetSupportsStreaming) {
12280 throw new TypeError('This packet type does not support partial lengths.');
12281 }
12282 // 4.2.2.3. Five-Octet Lengths
12283 } else {
12284 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
12285 8) | await reader.readByte();
12286 }
12287 }
12288 if (packetLength > 0) {
12289 let bytesRead = 0;
12290 while (true) {
12291 if (writer) await writer.ready;
12292 const { done, value } = await reader.read();
12293 if (done) {
12294 if (packetLength === Infinity) break;
12295 throw new Error('Unexpected end of packet');
12296 }
12297 const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);
12298 if (writer) await writer.write(chunk);
12299 else packet.push(chunk);
12300 bytesRead += value.length;
12301 if (bytesRead >= packetLength) {
12302 reader.unshift(value.subarray(packetLength - bytesRead + value.length));
12303 break;
12304 }
12305 }
12306 }
12307 } while (wasPartialLength);
12308
12309 // If this was not a packet that "supports streaming", we peek to check
12310 // whether it is the last packet in the message. We peek 2 bytes instead
12311 // of 1 because the beginning of this function also peeks 2 bytes, and we
12312 // want to cut a `subarray` of the correct length into `web-stream-tools`'
12313 // `externalBuffer` as a tiny optimization here.
12314 //
12315 // If it *was* a streaming packet (i.e. the data packets), we peek at the
12316 // entire remainder of the stream, in order to forward errors in the
12317 // remainder of the stream to the packet data. (Note that this means we
12318 // read/peek at all signature packets before closing the literal data
12319 // packet, for example.) This forwards MDC errors to the literal data
12320 // stream, for example, so that they don't get lost / forgotten on
12321 // decryptedMessage.packets.stream, which we never look at.
12322 //
12323 // An example of what we do when stream-parsing a message containing
12324 // [ one-pass signature packet, literal data packet, signature packet ]:
12325 // 1. Read the one-pass signature packet
12326 // 2. Peek 2 bytes of the literal data packet
12327 // 3. Parse the one-pass signature packet
12328 //
12329 // 4. Read the literal data packet, simultaneously stream-parsing it
12330 // 5. Peek until the end of the message
12331 // 6. Finish parsing the literal data packet
12332 //
12333 // 7. Read the signature packet again (we already peeked at it in step 5)
12334 // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
12335 // 9. Parse the signature packet
12336 //
12337 // Note that this means that if there's an error in the very end of the
12338 // stream, such as an MDC error, we throw in step 5 instead of in step 8
12339 // (or never), which is the point of this exercise.
12340 const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);
12341 if (writer) {
12342 await writer.ready;
12343 await writer.close();
12344 } else {
12345 packet = util.concatUint8Array(packet);
12346 await callback({ tag, packet });
12347 }
12348 return !nextPacket || !nextPacket.length;
12349 } catch (e) {
12350 if (writer) {
12351 await writer.abort(e);
12352 return true;
12353 } else {
12354 throw e;
12355 }
12356 } finally {
12357 if (writer) {
12358 await callbackReturned;
12359 }
12360 reader.releaseLock();
12361 }
12362}
12363
12364class UnsupportedError extends Error {
12365 constructor(...params) {
12366 super(...params);
12367
12368 if (Error.captureStackTrace) {
12369 Error.captureStackTrace(this, UnsupportedError);
12370 }
12371
12372 this.name = 'UnsupportedError';
12373 }
12374}
12375
12376class UnparseablePacket {
12377 constructor(tag, rawContent) {
12378 this.tag = tag;
12379 this.rawContent = rawContent;
12380 }
12381
12382 write() {
12383 return this.rawContent;
12384 }
12385}
12386
12387// OpenPGP.js - An OpenPGP implementation in javascript
12388
12389const webCrypto$2 = util.getWebCrypto();
12390const nodeCrypto$3 = util.getNodeCrypto();
12391
12392const webCurves = {
12393 'p256': 'P-256',
12394 'p384': 'P-384',
12395 'p521': 'P-521'
12396};
12397const knownCurves = nodeCrypto$3 ? nodeCrypto$3.getCurves() : [];
12398const nodeCurves = nodeCrypto$3 ? {
12399 secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
12400 p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
12401 p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
12402 p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
12403 ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
12404 curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
12405 brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
12406 brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
12407 brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
12408} : {};
12409
12410const curves = {
12411 p256: {
12412 oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
12413 keyType: enums.publicKey.ecdsa,
12414 hash: enums.hash.sha256,
12415 cipher: enums.symmetric.aes128,
12416 node: nodeCurves.p256,
12417 web: webCurves.p256,
12418 payloadSize: 32,
12419 sharedSize: 256
12420 },
12421 p384: {
12422 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
12423 keyType: enums.publicKey.ecdsa,
12424 hash: enums.hash.sha384,
12425 cipher: enums.symmetric.aes192,
12426 node: nodeCurves.p384,
12427 web: webCurves.p384,
12428 payloadSize: 48,
12429 sharedSize: 384
12430 },
12431 p521: {
12432 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
12433 keyType: enums.publicKey.ecdsa,
12434 hash: enums.hash.sha512,
12435 cipher: enums.symmetric.aes256,
12436 node: nodeCurves.p521,
12437 web: webCurves.p521,
12438 payloadSize: 66,
12439 sharedSize: 528
12440 },
12441 secp256k1: {
12442 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
12443 keyType: enums.publicKey.ecdsa,
12444 hash: enums.hash.sha256,
12445 cipher: enums.symmetric.aes128,
12446 node: nodeCurves.secp256k1,
12447 payloadSize: 32
12448 },
12449 ed25519: {
12450 oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
12451 keyType: enums.publicKey.eddsa,
12452 hash: enums.hash.sha512,
12453 node: false, // nodeCurves.ed25519 TODO
12454 payloadSize: 32
12455 },
12456 curve25519: {
12457 oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
12458 keyType: enums.publicKey.ecdh,
12459 hash: enums.hash.sha256,
12460 cipher: enums.symmetric.aes128,
12461 node: false, // nodeCurves.curve25519 TODO
12462 payloadSize: 32
12463 },
12464 brainpoolP256r1: {
12465 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
12466 keyType: enums.publicKey.ecdsa,
12467 hash: enums.hash.sha256,
12468 cipher: enums.symmetric.aes128,
12469 node: nodeCurves.brainpoolP256r1,
12470 payloadSize: 32
12471 },
12472 brainpoolP384r1: {
12473 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
12474 keyType: enums.publicKey.ecdsa,
12475 hash: enums.hash.sha384,
12476 cipher: enums.symmetric.aes192,
12477 node: nodeCurves.brainpoolP384r1,
12478 payloadSize: 48
12479 },
12480 brainpoolP512r1: {
12481 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
12482 keyType: enums.publicKey.ecdsa,
12483 hash: enums.hash.sha512,
12484 cipher: enums.symmetric.aes256,
12485 node: nodeCurves.brainpoolP512r1,
12486 payloadSize: 64
12487 }
12488};
12489
12490class Curve {
12491 constructor(oidOrName, params) {
12492 try {
12493 if (util.isArray(oidOrName) ||
12494 util.isUint8Array(oidOrName)) {
12495 // by oid byte array
12496 oidOrName = new OID(oidOrName);
12497 }
12498 if (oidOrName instanceof OID) {
12499 // by curve OID
12500 oidOrName = oidOrName.getName();
12501 }
12502 // by curve name or oid string
12503 this.name = enums.write(enums.curve, oidOrName);
12504 } catch (err) {
12505 throw new UnsupportedError('Unknown curve');
12506 }
12507 params = params || curves[this.name];
12508
12509 this.keyType = params.keyType;
12510
12511 this.oid = params.oid;
12512 this.hash = params.hash;
12513 this.cipher = params.cipher;
12514 this.node = params.node && curves[this.name];
12515 this.web = params.web && curves[this.name];
12516 this.payloadSize = params.payloadSize;
12517 if (this.web && util.getWebCrypto()) {
12518 this.type = 'web';
12519 } else if (this.node && util.getNodeCrypto()) {
12520 this.type = 'node';
12521 } else if (this.name === 'curve25519') {
12522 this.type = 'curve25519';
12523 } else if (this.name === 'ed25519') {
12524 this.type = 'ed25519';
12525 }
12526 }
12527
12528 async genKeyPair() {
12529 let keyPair;
12530 switch (this.type) {
12531 case 'web':
12532 try {
12533 return await webGenKeyPair(this.name);
12534 } catch (err) {
12535 util.printDebugError('Browser did not support generating ec key ' + err.message);
12536 break;
12537 }
12538 case 'node':
12539 return nodeGenKeyPair(this.name);
12540 case 'curve25519': {
12541 const privateKey = await getRandomBytes(32);
12542 privateKey[0] = (privateKey[0] & 127) | 64;
12543 privateKey[31] &= 248;
12544 const secretKey = privateKey.slice().reverse();
12545 keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey);
12546 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
12547 return { publicKey, privateKey };
12548 }
12549 case 'ed25519': {
12550 const privateKey = await getRandomBytes(32);
12551 const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey);
12552 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
12553 return { publicKey, privateKey };
12554 }
12555 }
12556 const indutnyCurve = await getIndutnyCurve(this.name);
12557 keyPair = await indutnyCurve.genKeyPair({
12558 entropy: util.uint8ArrayToString(await getRandomBytes(32))
12559 });
12560 return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
12561 }
12562}
12563
12564async function generate$1(curve) {
12565 const BigInteger = await util.getBigInteger();
12566
12567 curve = new Curve(curve);
12568 const keyPair = await curve.genKeyPair();
12569 const Q = new BigInteger(keyPair.publicKey).toUint8Array();
12570 const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);
12571 return {
12572 oid: curve.oid,
12573 Q,
12574 secret,
12575 hash: curve.hash,
12576 cipher: curve.cipher
12577 };
12578}
12579
12580/**
12581 * Get preferred hash algo to use with the given curve
12582 * @param {module:type/oid} oid - curve oid
12583 * @returns {enums.hash} hash algorithm
12584 */
12585function getPreferredHashAlgo(oid) {
12586 return curves[enums.write(enums.curve, oid.toHex())].hash;
12587}
12588
12589/**
12590 * Validate ECDH and ECDSA parameters
12591 * Not suitable for EdDSA (different secret key format)
12592 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
12593 * @param {module:type/oid} oid - EC object identifier
12594 * @param {Uint8Array} Q - EC public point
12595 * @param {Uint8Array} d - EC secret scalar
12596 * @returns {Promise<Boolean>} Whether params are valid.
12597 * @async
12598 */
12599async function validateStandardParams(algo, oid, Q, d) {
12600 const supportedCurves = {
12601 p256: true,
12602 p384: true,
12603 p521: true,
12604 secp256k1: true,
12605 curve25519: algo === enums.publicKey.ecdh,
12606 brainpoolP256r1: true,
12607 brainpoolP384r1: true,
12608 brainpoolP512r1: true
12609 };
12610
12611 // Check whether the given curve is supported
12612 const curveName = oid.getName();
12613 if (!supportedCurves[curveName]) {
12614 return false;
12615 }
12616
12617 if (curveName === 'curve25519') {
12618 d = d.slice().reverse();
12619 // Re-derive public point Q'
12620 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d);
12621
12622 Q = new Uint8Array(Q);
12623 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
12624 if (!util.equalsUint8Array(dG, Q)) {
12625 return false;
12626 }
12627
12628 return true;
12629 }
12630
12631 const curve = await getIndutnyCurve(curveName);
12632 try {
12633 // Parse Q and check that it is on the curve but not at infinity
12634 Q = keyFromPublic(curve, Q).getPublic();
12635 } catch (validationErrors) {
12636 return false;
12637 }
12638
12639 /**
12640 * Re-derive public point Q' = dG from private key
12641 * Expect Q == Q'
12642 */
12643 const dG = keyFromPrivate(curve, d).getPublic();
12644 if (!dG.eq(Q)) {
12645 return false;
12646 }
12647
12648 return true;
12649}
12650
12651//////////////////////////
12652// //
12653// Helper functions //
12654// //
12655//////////////////////////
12656
12657
12658async function webGenKeyPair(name) {
12659 // Note: keys generated with ECDSA and ECDH are structurally equivalent
12660 const webCryptoKey = await webCrypto$2.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);
12661
12662 const privateKey = await webCrypto$2.exportKey('jwk', webCryptoKey.privateKey);
12663 const publicKey = await webCrypto$2.exportKey('jwk', webCryptoKey.publicKey);
12664
12665 return {
12666 publicKey: jwkToRawPublic(publicKey),
12667 privateKey: b64ToUint8Array(privateKey.d)
12668 };
12669}
12670
12671async function nodeGenKeyPair(name) {
12672 // Note: ECDSA and ECDH key generation is structurally equivalent
12673 const ecdh = nodeCrypto$3.createECDH(nodeCurves[name]);
12674 await ecdh.generateKeys();
12675 return {
12676 publicKey: new Uint8Array(ecdh.getPublicKey()),
12677 privateKey: new Uint8Array(ecdh.getPrivateKey())
12678 };
12679}
12680
12681//////////////////////////
12682// //
12683// Helper functions //
12684// //
12685//////////////////////////
12686
12687/**
12688 * @param {JsonWebKey} jwk - key for conversion
12689 *
12690 * @returns {Uint8Array} Raw public key.
12691 */
12692function jwkToRawPublic(jwk) {
12693 const bufX = b64ToUint8Array(jwk.x);
12694 const bufY = b64ToUint8Array(jwk.y);
12695 const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
12696 publicKey[0] = 0x04;
12697 publicKey.set(bufX, 1);
12698 publicKey.set(bufY, bufX.length + 1);
12699 return publicKey;
12700}
12701
12702/**
12703 * @param {Integer} payloadSize - ec payload size
12704 * @param {String} name - curve name
12705 * @param {Uint8Array} publicKey - public key
12706 *
12707 * @returns {JsonWebKey} Public key in jwk format.
12708 */
12709function rawPublicToJWK(payloadSize, name, publicKey) {
12710 const len = payloadSize;
12711 const bufX = publicKey.slice(1, len + 1);
12712 const bufY = publicKey.slice(len + 1, len * 2 + 1);
12713 // https://www.rfc-editor.org/rfc/rfc7518.txt
12714 const jwk = {
12715 kty: 'EC',
12716 crv: name,
12717 x: uint8ArrayToB64(bufX, true),
12718 y: uint8ArrayToB64(bufY, true),
12719 ext: true
12720 };
12721 return jwk;
12722}
12723
12724/**
12725 * @param {Integer} payloadSize - ec payload size
12726 * @param {String} name - curve name
12727 * @param {Uint8Array} publicKey - public key
12728 * @param {Uint8Array} privateKey - private key
12729 *
12730 * @returns {JsonWebKey} Private key in jwk format.
12731 */
12732function privateToJWK$1(payloadSize, name, publicKey, privateKey) {
12733 const jwk = rawPublicToJWK(payloadSize, name, publicKey);
12734 jwk.d = uint8ArrayToB64(privateKey, true);
12735 return jwk;
12736}
12737
12738const webCrypto$3 = util.getWebCrypto();
12739const nodeCrypto$4 = util.getNodeCrypto();
12740
12741/**
12742 * Sign a message using the provided key
12743 * @param {module:type/oid} oid - Elliptic curve object identifier
12744 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign
12745 * @param {Uint8Array} message - Message to sign
12746 * @param {Uint8Array} publicKey - Public key
12747 * @param {Uint8Array} privateKey - Private key used to sign the message
12748 * @param {Uint8Array} hashed - The hashed message
12749 * @returns {Promise<{
12750 * r: Uint8Array,
12751 * s: Uint8Array
12752 * }>} Signature of the message
12753 * @async
12754 */
12755async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) {
12756 const curve = new Curve(oid);
12757 if (message && !util.isStream(message)) {
12758 const keyPair = { publicKey, privateKey };
12759 switch (curve.type) {
12760 case 'web': {
12761 // If browser doesn't support a curve, we'll catch it
12762 try {
12763 // Need to await to make sure browser succeeds
12764 return await webSign$1(curve, hashAlgo, message, keyPair);
12765 } catch (err) {
12766 // We do not fallback if the error is related to key integrity
12767 // Unfortunaley Safari does not support p521 and throws a DataError when using it
12768 // So we need to always fallback for that curve
12769 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
12770 throw err;
12771 }
12772 util.printDebugError('Browser did not support signing: ' + err.message);
12773 }
12774 break;
12775 }
12776 case 'node': {
12777 const signature = await nodeSign$1(curve, hashAlgo, message, keyPair);
12778 return {
12779 r: signature.r.toArrayLike(Uint8Array),
12780 s: signature.s.toArrayLike(Uint8Array)
12781 };
12782 }
12783 }
12784 }
12785 return ellipticSign(curve, hashed, privateKey);
12786}
12787
12788/**
12789 * Verifies if a signature is valid for a message
12790 * @param {module:type/oid} oid - Elliptic curve object identifier
12791 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
12792 * @param {{r: Uint8Array,
12793 s: Uint8Array}} signature Signature to verify
12794 * @param {Uint8Array} message - Message to verify
12795 * @param {Uint8Array} publicKey - Public key used to verify the message
12796 * @param {Uint8Array} hashed - The hashed message
12797 * @returns {Boolean}
12798 * @async
12799 */
12800async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) {
12801 const curve = new Curve(oid);
12802 if (message && !util.isStream(message)) {
12803 switch (curve.type) {
12804 case 'web':
12805 try {
12806 // Need to await to make sure browser succeeds
12807 return await webVerify$1(curve, hashAlgo, signature, message, publicKey);
12808 } catch (err) {
12809 // We do not fallback if the error is related to key integrity
12810 // Unfortunately Safari does not support p521 and throws a DataError when using it
12811 // So we need to always fallback for that curve
12812 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
12813 throw err;
12814 }
12815 util.printDebugError('Browser did not support verifying: ' + err.message);
12816 }
12817 break;
12818 case 'node':
12819 return nodeVerify$1(curve, hashAlgo, signature, message, publicKey);
12820 }
12821 }
12822 const digest = (typeof hashAlgo === 'undefined') ? message : hashed;
12823 return ellipticVerify(curve, signature, digest, publicKey);
12824}
12825
12826/**
12827 * Validate ECDSA parameters
12828 * @param {module:type/oid} oid - Elliptic curve object identifier
12829 * @param {Uint8Array} Q - ECDSA public point
12830 * @param {Uint8Array} d - ECDSA secret scalar
12831 * @returns {Promise<Boolean>} Whether params are valid.
12832 * @async
12833 */
12834async function validateParams$2(oid, Q, d) {
12835 const curve = new Curve(oid);
12836 // Reject curves x25519 and ed25519
12837 if (curve.keyType !== enums.publicKey.ecdsa) {
12838 return false;
12839 }
12840
12841 // To speed up the validation, we try to use node- or webcrypto when available
12842 // and sign + verify a random message
12843 switch (curve.type) {
12844 case 'web':
12845 case 'node': {
12846 const message = await getRandomBytes(8);
12847 const hashAlgo = enums.hash.sha256;
12848 const hashed = await hash.digest(hashAlgo, message);
12849 try {
12850 const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed);
12851 return await verify$1(oid, hashAlgo, signature, message, Q, hashed);
12852 } catch (err) {
12853 return false;
12854 }
12855 }
12856 default:
12857 return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
12858 }
12859}
12860
12861
12862//////////////////////////
12863// //
12864// Helper functions //
12865// //
12866//////////////////////////
12867
12868async function ellipticSign(curve, hashed, privateKey) {
12869 const indutnyCurve = await getIndutnyCurve(curve.name);
12870 const key = keyFromPrivate(indutnyCurve, privateKey);
12871 const signature = key.sign(hashed);
12872 return {
12873 r: signature.r.toArrayLike(Uint8Array),
12874 s: signature.s.toArrayLike(Uint8Array)
12875 };
12876}
12877
12878async function ellipticVerify(curve, signature, digest, publicKey) {
12879 const indutnyCurve = await getIndutnyCurve(curve.name);
12880 const key = keyFromPublic(indutnyCurve, publicKey);
12881 return key.verify(digest, signature);
12882}
12883
12884async function webSign$1(curve, hashAlgo, message, keyPair) {
12885 const len = curve.payloadSize;
12886 const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
12887 const key = await webCrypto$3.importKey(
12888 'jwk',
12889 jwk,
12890 {
12891 'name': 'ECDSA',
12892 'namedCurve': webCurves[curve.name],
12893 'hash': { name: enums.read(enums.webHash, curve.hash) }
12894 },
12895 false,
12896 ['sign']
12897 );
12898
12899 const signature = new Uint8Array(await webCrypto$3.sign(
12900 {
12901 'name': 'ECDSA',
12902 'namedCurve': webCurves[curve.name],
12903 'hash': { name: enums.read(enums.webHash, hashAlgo) }
12904 },
12905 key,
12906 message
12907 ));
12908
12909 return {
12910 r: signature.slice(0, len),
12911 s: signature.slice(len, len << 1)
12912 };
12913}
12914
12915async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
12916 const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);
12917 const key = await webCrypto$3.importKey(
12918 'jwk',
12919 jwk,
12920 {
12921 'name': 'ECDSA',
12922 'namedCurve': webCurves[curve.name],
12923 'hash': { name: enums.read(enums.webHash, curve.hash) }
12924 },
12925 false,
12926 ['verify']
12927 );
12928
12929 const signature = util.concatUint8Array([r, s]).buffer;
12930
12931 return webCrypto$3.verify(
12932 {
12933 'name': 'ECDSA',
12934 'namedCurve': webCurves[curve.name],
12935 'hash': { name: enums.read(enums.webHash, hashAlgo) }
12936 },
12937 key,
12938 signature,
12939 message
12940 );
12941}
12942
12943async function nodeSign$1(curve, hashAlgo, message, keyPair) {
12944 const sign = nodeCrypto$4.createSign(enums.read(enums.hash, hashAlgo));
12945 sign.write(message);
12946 sign.end();
12947 const key = ECPrivateKey.encode({
12948 version: 1,
12949 parameters: curve.oid,
12950 privateKey: Array.from(keyPair.privateKey),
12951 publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
12952 }, 'pem', {
12953 label: 'EC PRIVATE KEY'
12954 });
12955
12956 return ECDSASignature.decode(sign.sign(key), 'der');
12957}
12958
12959async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
12960 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12961
12962 const verify = nodeCrypto$4.createVerify(enums.read(enums.hash, hashAlgo));
12963 verify.write(message);
12964 verify.end();
12965 const key = SubjectPublicKeyInfo.encode({
12966 algorithm: {
12967 algorithm: [1, 2, 840, 10045, 2, 1],
12968 parameters: curve.oid
12969 },
12970 subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
12971 }, 'pem', {
12972 label: 'PUBLIC KEY'
12973 });
12974 const signature = ECDSASignature.encode({
12975 r: new BN(r), s: new BN(s)
12976 }, 'der');
12977
12978 try {
12979 return verify.verify(key, signature);
12980 } catch (err) {
12981 return false;
12982 }
12983}
12984
12985// Originally written by Owen Smith https://github.com/omsmith
12986// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
12987
12988/* eslint-disable no-invalid-this */
12989
12990const asn1$1 = nodeCrypto$4 ? asn1__default['default'] : undefined;
12991
12992const ECDSASignature = nodeCrypto$4 ?
12993 asn1$1.define('ECDSASignature', function() {
12994 this.seq().obj(
12995 this.key('r').int(),
12996 this.key('s').int()
12997 );
12998 }) : undefined;
12999
13000const ECPrivateKey = nodeCrypto$4 ?
13001 asn1$1.define('ECPrivateKey', function() {
13002 this.seq().obj(
13003 this.key('version').int(),
13004 this.key('privateKey').octstr(),
13005 this.key('parameters').explicit(0).optional().any(),
13006 this.key('publicKey').explicit(1).optional().bitstr()
13007 );
13008 }) : undefined;
13009
13010const AlgorithmIdentifier = nodeCrypto$4 ?
13011 asn1$1.define('AlgorithmIdentifier', function() {
13012 this.seq().obj(
13013 this.key('algorithm').objid(),
13014 this.key('parameters').optional().any()
13015 );
13016 }) : undefined;
13017
13018const SubjectPublicKeyInfo = nodeCrypto$4 ?
13019 asn1$1.define('SubjectPublicKeyInfo', function() {
13020 this.seq().obj(
13021 this.key('algorithm').use(AlgorithmIdentifier),
13022 this.key('subjectPublicKey').bitstr()
13023 );
13024 }) : undefined;
13025
13026var ecdsa = /*#__PURE__*/Object.freeze({
13027 __proto__: null,
13028 sign: sign$1,
13029 verify: verify$1,
13030 validateParams: validateParams$2
13031});
13032
13033// OpenPGP.js - An OpenPGP implementation in javascript
13034
13035naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
13036
13037/**
13038 * Sign a message using the provided key
13039 * @param {module:type/oid} oid - Elliptic curve object identifier
13040 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
13041 * @param {Uint8Array} message - Message to sign
13042 * @param {Uint8Array} publicKey - Public key
13043 * @param {Uint8Array} privateKey - Private key used to sign the message
13044 * @param {Uint8Array} hashed - The hashed message
13045 * @returns {Promise<{
13046 * r: Uint8Array,
13047 * s: Uint8Array
13048 * }>} Signature of the message
13049 * @async
13050 */
13051async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) {
13052 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {
13053 // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
13054 throw new Error('Hash algorithm too weak: sha256 or stronger is required for EdDSA.');
13055 }
13056 const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);
13057 const signature = naclFastLight.sign.detached(hashed, secretKey);
13058 // EdDSA signature params are returned in little-endian format
13059 return {
13060 r: signature.subarray(0, 32),
13061 s: signature.subarray(32)
13062 };
13063}
13064
13065/**
13066 * Verifies if a signature is valid for a message
13067 * @param {module:type/oid} oid - Elliptic curve object identifier
13068 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
13069 * @param {{r: Uint8Array,
13070 s: Uint8Array}} signature Signature to verify the message
13071 * @param {Uint8Array} m - Message to verify
13072 * @param {Uint8Array} publicKey - Public key used to verify the message
13073 * @param {Uint8Array} hashed - The hashed message
13074 * @returns {Boolean}
13075 * @async
13076 */
13077async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) {
13078 const signature = util.concatUint8Array([r, s]);
13079 return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1));
13080}
13081/**
13082 * Validate EdDSA parameters
13083 * @param {module:type/oid} oid - Elliptic curve object identifier
13084 * @param {Uint8Array} Q - EdDSA public point
13085 * @param {Uint8Array} k - EdDSA secret seed
13086 * @returns {Promise<Boolean>} Whether params are valid.
13087 * @async
13088 */
13089async function validateParams$3(oid, Q, k) {
13090 // Check whether the given curve is supported
13091 if (oid.getName() !== 'ed25519') {
13092 return false;
13093 }
13094
13095 /**
13096 * Derive public point Q' = dG from private key
13097 * and expect Q == Q'
13098 */
13099 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k);
13100 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
13101 return util.equalsUint8Array(Q, dG);
13102}
13103
13104var eddsa = /*#__PURE__*/Object.freeze({
13105 __proto__: null,
13106 sign: sign$2,
13107 verify: verify$2,
13108 validateParams: validateParams$3
13109});
13110
13111// OpenPGP.js - An OpenPGP implementation in javascript
13112
13113/**
13114 * AES key wrap
13115 * @function
13116 * @param {Uint8Array} key
13117 * @param {Uint8Array} data
13118 * @returns {Uint8Array}
13119 */
13120function wrap(key, data) {
13121 const aes = new cipher['aes' + (key.length * 8)](key);
13122 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13123 const P = unpack(data);
13124 let A = IV;
13125 const R = P;
13126 const n = P.length / 2;
13127 const t = new Uint32Array([0, 0]);
13128 let B = new Uint32Array(4);
13129 for (let j = 0; j <= 5; ++j) {
13130 for (let i = 0; i < n; ++i) {
13131 t[1] = n * j + (1 + i);
13132 // B = A
13133 B[0] = A[0];
13134 B[1] = A[1];
13135 // B = A || R[i]
13136 B[2] = R[2 * i];
13137 B[3] = R[2 * i + 1];
13138 // B = AES(K, B)
13139 B = unpack(aes.encrypt(pack(B)));
13140 // A = MSB(64, B) ^ t
13141 A = B.subarray(0, 2);
13142 A[0] ^= t[0];
13143 A[1] ^= t[1];
13144 // R[i] = LSB(64, B)
13145 R[2 * i] = B[2];
13146 R[2 * i + 1] = B[3];
13147 }
13148 }
13149 return pack(A, R);
13150}
13151
13152/**
13153 * AES key unwrap
13154 * @function
13155 * @param {String} key
13156 * @param {String} data
13157 * @returns {Uint8Array}
13158 * @throws {Error}
13159 */
13160function unwrap(key, data) {
13161 const aes = new cipher['aes' + (key.length * 8)](key);
13162 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13163 const C = unpack(data);
13164 let A = C.subarray(0, 2);
13165 const R = C.subarray(2);
13166 const n = C.length / 2 - 1;
13167 const t = new Uint32Array([0, 0]);
13168 let B = new Uint32Array(4);
13169 for (let j = 5; j >= 0; --j) {
13170 for (let i = n - 1; i >= 0; --i) {
13171 t[1] = n * j + (i + 1);
13172 // B = A ^ t
13173 B[0] = A[0] ^ t[0];
13174 B[1] = A[1] ^ t[1];
13175 // B = (A ^ t) || R[i]
13176 B[2] = R[2 * i];
13177 B[3] = R[2 * i + 1];
13178 // B = AES-1(B)
13179 B = unpack(aes.decrypt(pack(B)));
13180 // A = MSB(64, B)
13181 A = B.subarray(0, 2);
13182 // R[i] = LSB(64, B)
13183 R[2 * i] = B[2];
13184 R[2 * i + 1] = B[3];
13185 }
13186 }
13187 if (A[0] === IV[0] && A[1] === IV[1]) {
13188 return pack(R);
13189 }
13190 throw new Error('Key Data Integrity failed');
13191}
13192
13193function createArrayBuffer(data) {
13194 if (util.isString(data)) {
13195 const { length } = data;
13196 const buffer = new ArrayBuffer(length);
13197 const view = new Uint8Array(buffer);
13198 for (let j = 0; j < length; ++j) {
13199 view[j] = data.charCodeAt(j);
13200 }
13201 return buffer;
13202 }
13203 return new Uint8Array(data).buffer;
13204}
13205
13206function unpack(data) {
13207 const { length } = data;
13208 const buffer = createArrayBuffer(data);
13209 const view = new DataView(buffer);
13210 const arr = new Uint32Array(length / 4);
13211 for (let i = 0; i < length / 4; ++i) {
13212 arr[i] = view.getUint32(4 * i);
13213 }
13214 return arr;
13215}
13216
13217function pack() {
13218 let length = 0;
13219 for (let k = 0; k < arguments.length; ++k) {
13220 length += 4 * arguments[k].length;
13221 }
13222 const buffer = new ArrayBuffer(length);
13223 const view = new DataView(buffer);
13224 let offset = 0;
13225 for (let i = 0; i < arguments.length; ++i) {
13226 for (let j = 0; j < arguments[i].length; ++j) {
13227 view.setUint32(offset + 4 * j, arguments[i][j]);
13228 }
13229 offset += 4 * arguments[i].length;
13230 }
13231 return new Uint8Array(buffer);
13232}
13233
13234var aesKW = /*#__PURE__*/Object.freeze({
13235 __proto__: null,
13236 wrap: wrap,
13237 unwrap: unwrap
13238});
13239
13240// OpenPGP.js - An OpenPGP implementation in javascript
13241
13242/**
13243 * @fileoverview Functions to add and remove PKCS5 padding
13244 * @see PublicKeyEncryptedSessionKeyPacket
13245 * @module crypto/pkcs5
13246 * @private
13247 */
13248
13249/**
13250 * Add pkcs5 padding to a message
13251 * @param {Uint8Array} message - message to pad
13252 * @returns {Uint8Array} Padded message.
13253 */
13254function encode$1(message) {
13255 const c = 8 - (message.length % 8);
13256 const padded = new Uint8Array(message.length + c).fill(c);
13257 padded.set(message);
13258 return padded;
13259}
13260
13261/**
13262 * Remove pkcs5 padding from a message
13263 * @param {Uint8Array} message - message to remove padding from
13264 * @returns {Uint8Array} Message without padding.
13265 */
13266function decode$1(message) {
13267 const len = message.length;
13268 if (len > 0) {
13269 const c = message[len - 1];
13270 if (c >= 1) {
13271 const provided = message.subarray(len - c);
13272 const computed = new Uint8Array(c).fill(c);
13273 if (util.equalsUint8Array(provided, computed)) {
13274 return message.subarray(0, len - c);
13275 }
13276 }
13277 }
13278 throw new Error('Invalid padding');
13279}
13280
13281var pkcs5 = /*#__PURE__*/Object.freeze({
13282 __proto__: null,
13283 encode: encode$1,
13284 decode: decode$1
13285});
13286
13287// OpenPGP.js - An OpenPGP implementation in javascript
13288
13289const webCrypto$4 = util.getWebCrypto();
13290const nodeCrypto$5 = util.getNodeCrypto();
13291
13292/**
13293 * Validate ECDH parameters
13294 * @param {module:type/oid} oid - Elliptic curve object identifier
13295 * @param {Uint8Array} Q - ECDH public point
13296 * @param {Uint8Array} d - ECDH secret scalar
13297 * @returns {Promise<Boolean>} Whether params are valid.
13298 * @async
13299 */
13300async function validateParams$4(oid, Q, d) {
13301 return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
13302}
13303
13304// Build Param for ECDH algorithm (RFC 6637)
13305function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
13306 return util.concatUint8Array([
13307 oid.write(),
13308 new Uint8Array([public_algo]),
13309 kdfParams.write(),
13310 util.stringToUint8Array('Anonymous Sender '),
13311 fingerprint.subarray(0, 20)
13312 ]);
13313}
13314
13315// Key Derivation Function (RFC 6637)
13316async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {
13317 // Note: X is little endian for Curve25519, big-endian for all others.
13318 // This is not ideal, but the RFC's are unclear
13319 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
13320 let i;
13321 if (stripLeading) {
13322 // Work around old go crypto bug
13323 for (i = 0; i < X.length && X[i] === 0; i++);
13324 X = X.subarray(i);
13325 }
13326 if (stripTrailing) {
13327 // Work around old OpenPGP.js bug
13328 for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
13329 X = X.subarray(0, i + 1);
13330 }
13331 const digest = await hash.digest(hashAlgo, util.concatUint8Array([
13332 new Uint8Array([0, 0, 0, 1]),
13333 X,
13334 param
13335 ]));
13336 return digest.subarray(0, length);
13337}
13338
13339/**
13340 * Generate ECDHE ephemeral key and secret from public key
13341 *
13342 * @param {Curve} curve - Elliptic curve object
13343 * @param {Uint8Array} Q - Recipient public key
13344 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13345 * @async
13346 */
13347async function genPublicEphemeralKey(curve, Q) {
13348 switch (curve.type) {
13349 case 'curve25519': {
13350 const d = await getRandomBytes(32);
13351 const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);
13352 let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey);
13353 publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
13354 return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
13355 }
13356 case 'web':
13357 if (curve.web && util.getWebCrypto()) {
13358 try {
13359 return await webPublicEphemeralKey(curve, Q);
13360 } catch (err) {
13361 util.printDebugError(err);
13362 }
13363 }
13364 break;
13365 case 'node':
13366 return nodePublicEphemeralKey(curve, Q);
13367 }
13368 return ellipticPublicEphemeralKey(curve, Q);
13369}
13370
13371/**
13372 * Encrypt and wrap a session key
13373 *
13374 * @param {module:type/oid} oid - Elliptic curve object identifier
13375 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
13376 * @param {Uint8Array} data - Unpadded session key data
13377 * @param {Uint8Array} Q - Recipient public key
13378 * @param {Uint8Array} fingerprint - Recipient fingerprint
13379 * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
13380 * @async
13381 */
13382async function encrypt$2(oid, kdfParams, data, Q, fingerprint) {
13383 const m = encode$1(data);
13384
13385 const curve = new Curve(oid);
13386 const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
13387 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
13388 const { keySize } = getCipher(kdfParams.cipher);
13389 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);
13390 const wrappedKey = wrap(Z, m);
13391 return { publicKey, wrappedKey };
13392}
13393
13394/**
13395 * Generate ECDHE secret from private key and public part of ephemeral key
13396 *
13397 * @param {Curve} curve - Elliptic curve object
13398 * @param {Uint8Array} V - Public part of ephemeral key
13399 * @param {Uint8Array} Q - Recipient public key
13400 * @param {Uint8Array} d - Recipient private key
13401 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13402 * @async
13403 */
13404async function genPrivateEphemeralKey(curve, V, Q, d) {
13405 if (d.length !== curve.payloadSize) {
13406 const privateKey = new Uint8Array(curve.payloadSize);
13407 privateKey.set(d, curve.payloadSize - d.length);
13408 d = privateKey;
13409 }
13410 switch (curve.type) {
13411 case 'curve25519': {
13412 const secretKey = d.slice().reverse();
13413 const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1));
13414 return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
13415 }
13416 case 'web':
13417 if (curve.web && util.getWebCrypto()) {
13418 try {
13419 return await webPrivateEphemeralKey(curve, V, Q, d);
13420 } catch (err) {
13421 util.printDebugError(err);
13422 }
13423 }
13424 break;
13425 case 'node':
13426 return nodePrivateEphemeralKey(curve, V, d);
13427 }
13428 return ellipticPrivateEphemeralKey(curve, V, d);
13429}
13430
13431/**
13432 * Decrypt and unwrap the value derived from session key
13433 *
13434 * @param {module:type/oid} oid - Elliptic curve object identifier
13435 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
13436 * @param {Uint8Array} V - Public part of ephemeral key
13437 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
13438 * @param {Uint8Array} Q - Recipient public key
13439 * @param {Uint8Array} d - Recipient private key
13440 * @param {Uint8Array} fingerprint - Recipient fingerprint
13441 * @returns {Promise<Uint8Array>} Value derived from session key.
13442 * @async
13443 */
13444async function decrypt$2(oid, kdfParams, V, C, Q, d, fingerprint) {
13445 const curve = new Curve(oid);
13446 const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
13447 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
13448 const { keySize } = getCipher(kdfParams.cipher);
13449 let err;
13450 for (let i = 0; i < 3; i++) {
13451 try {
13452 // Work around old go crypto bug and old OpenPGP.js bug, respectively.
13453 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);
13454 return decode$1(unwrap(Z, C));
13455 } catch (e) {
13456 err = e;
13457 }
13458 }
13459 throw err;
13460}
13461
13462/**
13463 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
13464 *
13465 * @param {Curve} curve - Elliptic curve object
13466 * @param {Uint8Array} V - Public part of ephemeral key
13467 * @param {Uint8Array} Q - Recipient public key
13468 * @param {Uint8Array} d - Recipient private key
13469 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13470 * @async
13471 */
13472async function webPrivateEphemeralKey(curve, V, Q, d) {
13473 const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d);
13474 let privateKey = webCrypto$4.importKey(
13475 'jwk',
13476 recipient,
13477 {
13478 name: 'ECDH',
13479 namedCurve: curve.web.web
13480 },
13481 true,
13482 ['deriveKey', 'deriveBits']
13483 );
13484 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);
13485 let sender = webCrypto$4.importKey(
13486 'jwk',
13487 jwk,
13488 {
13489 name: 'ECDH',
13490 namedCurve: curve.web.web
13491 },
13492 true,
13493 []
13494 );
13495 [privateKey, sender] = await Promise.all([privateKey, sender]);
13496 let S = webCrypto$4.deriveBits(
13497 {
13498 name: 'ECDH',
13499 namedCurve: curve.web.web,
13500 public: sender
13501 },
13502 privateKey,
13503 curve.web.sharedSize
13504 );
13505 let secret = webCrypto$4.exportKey(
13506 'jwk',
13507 privateKey
13508 );
13509 [S, secret] = await Promise.all([S, secret]);
13510 const sharedKey = new Uint8Array(S);
13511 const secretKey = b64ToUint8Array(secret.d);
13512 return { secretKey, sharedKey };
13513}
13514
13515/**
13516 * Generate ECDHE ephemeral key and secret from public key using webCrypto
13517 *
13518 * @param {Curve} curve - Elliptic curve object
13519 * @param {Uint8Array} Q - Recipient public key
13520 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13521 * @async
13522 */
13523async function webPublicEphemeralKey(curve, Q) {
13524 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);
13525 let keyPair = webCrypto$4.generateKey(
13526 {
13527 name: 'ECDH',
13528 namedCurve: curve.web.web
13529 },
13530 true,
13531 ['deriveKey', 'deriveBits']
13532 );
13533 let recipient = webCrypto$4.importKey(
13534 'jwk',
13535 jwk,
13536 {
13537 name: 'ECDH',
13538 namedCurve: curve.web.web
13539 },
13540 false,
13541 []
13542 );
13543 [keyPair, recipient] = await Promise.all([keyPair, recipient]);
13544 let s = webCrypto$4.deriveBits(
13545 {
13546 name: 'ECDH',
13547 namedCurve: curve.web.web,
13548 public: recipient
13549 },
13550 keyPair.privateKey,
13551 curve.web.sharedSize
13552 );
13553 let p = webCrypto$4.exportKey(
13554 'jwk',
13555 keyPair.publicKey
13556 );
13557 [s, p] = await Promise.all([s, p]);
13558 const sharedKey = new Uint8Array(s);
13559 const publicKey = new Uint8Array(jwkToRawPublic(p));
13560 return { publicKey, sharedKey };
13561}
13562
13563/**
13564 * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
13565 *
13566 * @param {Curve} curve - Elliptic curve object
13567 * @param {Uint8Array} V - Public part of ephemeral key
13568 * @param {Uint8Array} d - Recipient private key
13569 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13570 * @async
13571 */
13572async function ellipticPrivateEphemeralKey(curve, V, d) {
13573 const indutnyCurve = await getIndutnyCurve(curve.name);
13574 V = keyFromPublic(indutnyCurve, V);
13575 d = keyFromPrivate(indutnyCurve, d);
13576 const secretKey = new Uint8Array(d.getPrivate());
13577 const S = d.derive(V.getPublic());
13578 const len = indutnyCurve.curve.p.byteLength();
13579 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
13580 return { secretKey, sharedKey };
13581}
13582
13583/**
13584 * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
13585 *
13586 * @param {Curve} curve - Elliptic curve object
13587 * @param {Uint8Array} Q - Recipient public key
13588 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13589 * @async
13590 */
13591async function ellipticPublicEphemeralKey(curve, Q) {
13592 const indutnyCurve = await getIndutnyCurve(curve.name);
13593 const v = await curve.genKeyPair();
13594 Q = keyFromPublic(indutnyCurve, Q);
13595 const V = keyFromPrivate(indutnyCurve, v.privateKey);
13596 const publicKey = v.publicKey;
13597 const S = V.derive(Q.getPublic());
13598 const len = indutnyCurve.curve.p.byteLength();
13599 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
13600 return { publicKey, sharedKey };
13601}
13602
13603/**
13604 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
13605 *
13606 * @param {Curve} curve - Elliptic curve object
13607 * @param {Uint8Array} V - Public part of ephemeral key
13608 * @param {Uint8Array} d - Recipient private key
13609 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
13610 * @async
13611 */
13612async function nodePrivateEphemeralKey(curve, V, d) {
13613 const recipient = nodeCrypto$5.createECDH(curve.node.node);
13614 recipient.setPrivateKey(d);
13615 const sharedKey = new Uint8Array(recipient.computeSecret(V));
13616 const secretKey = new Uint8Array(recipient.getPrivateKey());
13617 return { secretKey, sharedKey };
13618}
13619
13620/**
13621 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
13622 *
13623 * @param {Curve} curve - Elliptic curve object
13624 * @param {Uint8Array} Q - Recipient public key
13625 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
13626 * @async
13627 */
13628async function nodePublicEphemeralKey(curve, Q) {
13629 const sender = nodeCrypto$5.createECDH(curve.node.node);
13630 sender.generateKeys();
13631 const sharedKey = new Uint8Array(sender.computeSecret(Q));
13632 const publicKey = new Uint8Array(sender.getPublicKey());
13633 return { publicKey, sharedKey };
13634}
13635
13636var ecdh = /*#__PURE__*/Object.freeze({
13637 __proto__: null,
13638 validateParams: validateParams$4,
13639 encrypt: encrypt$2,
13640 decrypt: decrypt$2
13641});
13642
13643// OpenPGP.js - An OpenPGP implementation in javascript
13644
13645var elliptic = /*#__PURE__*/Object.freeze({
13646 __proto__: null,
13647 Curve: Curve,
13648 ecdh: ecdh,
13649 ecdsa: ecdsa,
13650 eddsa: eddsa,
13651 generate: generate$1,
13652 getPreferredHashAlgo: getPreferredHashAlgo
13653});
13654
13655// GPG4Browsers - An OpenPGP implementation in javascript
13656
13657/*
13658 TODO regarding the hash function, read:
13659 https://tools.ietf.org/html/rfc4880#section-13.6
13660 https://tools.ietf.org/html/rfc4880#section-14
13661*/
13662
13663/**
13664 * DSA Sign function
13665 * @param {Integer} hashAlgo
13666 * @param {Uint8Array} hashed
13667 * @param {Uint8Array} g
13668 * @param {Uint8Array} p
13669 * @param {Uint8Array} q
13670 * @param {Uint8Array} x
13671 * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}
13672 * @async
13673 */
13674async function sign$3(hashAlgo, hashed, g, p, q, x) {
13675 const BigInteger = await util.getBigInteger();
13676 const one = new BigInteger(1);
13677 p = new BigInteger(p);
13678 q = new BigInteger(q);
13679 g = new BigInteger(g);
13680 x = new BigInteger(x);
13681
13682 let k;
13683 let r;
13684 let s;
13685 let t;
13686 g = g.mod(p);
13687 x = x.mod(q);
13688 // If the output size of the chosen hash is larger than the number of
13689 // bits of q, the hash result is truncated to fit by taking the number
13690 // of leftmost bits equal to the number of bits of q. This (possibly
13691 // truncated) hash function result is treated as a number and used
13692 // directly in the DSA signature algorithm.
13693 const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);
13694 // FIPS-186-4, section 4.6:
13695 // The values of r and s shall be checked to determine if r = 0 or s = 0.
13696 // If either r = 0 or s = 0, a new value of k shall be generated, and the
13697 // signature shall be recalculated. It is extremely unlikely that r = 0
13698 // or s = 0 if signatures are generated properly.
13699 while (true) {
13700 // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
13701 k = await getRandomBigInteger(one, q); // returns in [1, q-1]
13702 r = g.modExp(k, p).imod(q); // (g**k mod p) mod q
13703 if (r.isZero()) {
13704 continue;
13705 }
13706 const xr = x.mul(r).imod(q);
13707 t = h.add(xr).imod(q); // H(m) + x*r mod q
13708 s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q
13709 if (s.isZero()) {
13710 continue;
13711 }
13712 break;
13713 }
13714 return {
13715 r: r.toUint8Array('be', q.byteLength()),
13716 s: s.toUint8Array('be', q.byteLength())
13717 };
13718}
13719
13720/**
13721 * DSA Verify function
13722 * @param {Integer} hashAlgo
13723 * @param {Uint8Array} r
13724 * @param {Uint8Array} s
13725 * @param {Uint8Array} hashed
13726 * @param {Uint8Array} g
13727 * @param {Uint8Array} p
13728 * @param {Uint8Array} q
13729 * @param {Uint8Array} y
13730 * @returns {boolean}
13731 * @async
13732 */
13733async function verify$3(hashAlgo, r, s, hashed, g, p, q, y) {
13734 const BigInteger = await util.getBigInteger();
13735 const zero = new BigInteger(0);
13736 r = new BigInteger(r);
13737 s = new BigInteger(s);
13738
13739 p = new BigInteger(p);
13740 q = new BigInteger(q);
13741 g = new BigInteger(g);
13742 y = new BigInteger(y);
13743
13744 if (r.lte(zero) || r.gte(q) ||
13745 s.lte(zero) || s.gte(q)) {
13746 util.printDebug('invalid DSA Signature');
13747 return false;
13748 }
13749 const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);
13750 const w = s.modInv(q); // s**-1 mod q
13751 if (w.isZero()) {
13752 util.printDebug('invalid DSA Signature');
13753 return false;
13754 }
13755
13756 g = g.mod(p);
13757 y = y.mod(p);
13758 const u1 = h.mul(w).imod(q); // H(m) * w mod q
13759 const u2 = r.mul(w).imod(q); // r * w mod q
13760 const t1 = g.modExp(u1, p); // g**u1 mod p
13761 const t2 = y.modExp(u2, p); // y**u2 mod p
13762 const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q
13763 return v.equal(r);
13764}
13765
13766/**
13767 * Validate DSA parameters
13768 * @param {Uint8Array} p - DSA prime
13769 * @param {Uint8Array} q - DSA group order
13770 * @param {Uint8Array} g - DSA sub-group generator
13771 * @param {Uint8Array} y - DSA public key
13772 * @param {Uint8Array} x - DSA private key
13773 * @returns {Promise<Boolean>} Whether params are valid.
13774 * @async
13775 */
13776async function validateParams$5(p, q, g, y, x) {
13777 const BigInteger = await util.getBigInteger();
13778 p = new BigInteger(p);
13779 q = new BigInteger(q);
13780 g = new BigInteger(g);
13781 y = new BigInteger(y);
13782 const one = new BigInteger(1);
13783 // Check that 1 < g < p
13784 if (g.lte(one) || g.gte(p)) {
13785 return false;
13786 }
13787
13788 /**
13789 * Check that subgroup order q divides p-1
13790 */
13791 if (!p.dec().mod(q).isZero()) {
13792 return false;
13793 }
13794
13795 /**
13796 * g has order q
13797 * Check that g ** q = 1 mod p
13798 */
13799 if (!g.modExp(q, p).isOne()) {
13800 return false;
13801 }
13802
13803 /**
13804 * Check q is large and probably prime (we mainly want to avoid small factors)
13805 */
13806 const qSize = new BigInteger(q.bitLength());
13807 const n150 = new BigInteger(150);
13808 if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {
13809 return false;
13810 }
13811
13812 /**
13813 * Re-derive public key y' = g ** x mod p
13814 * Expect y == y'
13815 *
13816 * Blinded exponentiation computes g**{rq + x} to compare to y
13817 */
13818 x = new BigInteger(x);
13819 const two = new BigInteger(2);
13820 const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q
13821 const rqx = q.mul(r).add(x);
13822 if (!y.equal(g.modExp(rqx, p))) {
13823 return false;
13824 }
13825
13826 return true;
13827}
13828
13829var dsa = /*#__PURE__*/Object.freeze({
13830 __proto__: null,
13831 sign: sign$3,
13832 verify: verify$3,
13833 validateParams: validateParams$5
13834});
13835
13836/**
13837 * @fileoverview Asymmetric cryptography functions
13838 * @module crypto/public_key
13839 * @private
13840 */
13841
13842var publicKey = {
13843 /** @see module:crypto/public_key/rsa */
13844 rsa: rsa,
13845 /** @see module:crypto/public_key/elgamal */
13846 elgamal: elgamal,
13847 /** @see module:crypto/public_key/elliptic */
13848 elliptic: elliptic,
13849 /** @see module:crypto/public_key/dsa */
13850 dsa: dsa,
13851 /** @see tweetnacl */
13852 nacl: naclFastLight
13853};
13854
13855// OpenPGP.js - An OpenPGP implementation in javascript
13856
13857class ECDHSymmetricKey {
13858 constructor(data) {
13859 if (typeof data === 'undefined') {
13860 data = new Uint8Array([]);
13861 } else if (util.isString(data)) {
13862 data = util.stringToUint8Array(data);
13863 } else {
13864 data = new Uint8Array(data);
13865 }
13866 this.data = data;
13867 }
13868
13869 /**
13870 * Read an ECDHSymmetricKey from an Uint8Array
13871 * @param {Uint8Array} input - Where to read the encoded symmetric key from
13872 * @returns {Number} Number of read bytes.
13873 */
13874 read(input) {
13875 if (input.length >= 1) {
13876 const length = input[0];
13877 if (input.length >= 1 + length) {
13878 this.data = input.subarray(1, 1 + length);
13879 return 1 + this.data.length;
13880 }
13881 }
13882 throw new Error('Invalid symmetric key');
13883 }
13884
13885 /**
13886 * Write an ECDHSymmetricKey as an Uint8Array
13887 * @returns {Uint8Array} An array containing the value
13888 */
13889 write() {
13890 return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
13891 }
13892}
13893
13894// OpenPGP.js - An OpenPGP implementation in javascript
13895// Copyright (C) 2015-2016 Decentral
13896//
13897// This library is free software; you can redistribute it and/or
13898// modify it under the terms of the GNU Lesser General Public
13899// License as published by the Free Software Foundation; either
13900// version 3.0 of the License, or (at your option) any later version.
13901//
13902// This library is distributed in the hope that it will be useful,
13903// but WITHOUT ANY WARRANTY; without even the implied warranty of
13904// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13905// Lesser General Public License for more details.
13906//
13907// You should have received a copy of the GNU Lesser General Public
13908// License along with this library; if not, write to the Free Software
13909// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
13910
13911/**
13912 * Implementation of type KDF parameters
13913 *
13914 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
13915 * A key derivation function (KDF) is necessary to implement the EC
13916 * encryption. The Concatenation Key Derivation Function (Approved
13917 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
13918 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
13919 * @module type/kdf_params
13920 * @private
13921 */
13922
13923class KDFParams {
13924 /**
13925 * @param {enums.hash} hash - Hash algorithm
13926 * @param {enums.symmetric} cipher - Symmetric algorithm
13927 */
13928 constructor(data) {
13929 if (data) {
13930 const { hash, cipher } = data;
13931 this.hash = hash;
13932 this.cipher = cipher;
13933 } else {
13934 this.hash = null;
13935 this.cipher = null;
13936 }
13937 }
13938
13939 /**
13940 * Read KDFParams from an Uint8Array
13941 * @param {Uint8Array} input - Where to read the KDFParams from
13942 * @returns {Number} Number of read bytes.
13943 */
13944 read(input) {
13945 if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
13946 throw new Error('Cannot read KDFParams');
13947 }
13948 this.hash = input[2];
13949 this.cipher = input[3];
13950 return 4;
13951 }
13952
13953 /**
13954 * Write KDFParams to an Uint8Array
13955 * @returns {Uint8Array} Array with the KDFParams value
13956 */
13957 write() {
13958 return new Uint8Array([3, 1, this.hash, this.cipher]);
13959 }
13960}
13961
13962// GPG4Browsers - An OpenPGP implementation in javascript
13963
13964/**
13965 * Encrypts data using specified algorithm and public key parameters.
13966 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
13967 * @param {module:enums.publicKey} algo - Public key algorithm
13968 * @param {Object} publicParams - Algorithm-specific public key parameters
13969 * @param {Uint8Array} data - Data to be encrypted
13970 * @param {Uint8Array} fingerprint - Recipient fingerprint
13971 * @returns {Promise<Object>} Encrypted session key parameters.
13972 * @async
13973 */
13974async function publicKeyEncrypt(algo, publicParams, data, fingerprint) {
13975 switch (algo) {
13976 case enums.publicKey.rsaEncrypt:
13977 case enums.publicKey.rsaEncryptSign: {
13978 const { n, e } = publicParams;
13979 const c = await publicKey.rsa.encrypt(data, n, e);
13980 return { c };
13981 }
13982 case enums.publicKey.elgamal: {
13983 const { p, g, y } = publicParams;
13984 return publicKey.elgamal.encrypt(data, p, g, y);
13985 }
13986 case enums.publicKey.ecdh: {
13987 const { oid, Q, kdfParams } = publicParams;
13988 const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(
13989 oid, kdfParams, data, Q, fingerprint);
13990 return { V, C: new ECDHSymmetricKey(C) };
13991 }
13992 default:
13993 return [];
13994 }
13995}
13996
13997/**
13998 * Decrypts data using specified algorithm and private key parameters.
13999 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
14000 * @param {module:enums.publicKey} algo - Public key algorithm
14001 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
14002 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
14003 * @param {Object} sessionKeyParams - Encrypted session key parameters
14004 * @param {Uint8Array} fingerprint - Recipient fingerprint
14005 * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing
14006 * (needed for constant-time processing in RSA and ElGamal)
14007 * @returns {Promise<Uint8Array>} Decrypted data.
14008 * @throws {Error} on sensitive decryption error, unless `randomPayload` is given
14009 * @async
14010 */
14011async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {
14012 switch (algo) {
14013 case enums.publicKey.rsaEncryptSign:
14014 case enums.publicKey.rsaEncrypt: {
14015 const { c } = sessionKeyParams;
14016 const { n, e } = publicKeyParams;
14017 const { d, p, q, u } = privateKeyParams;
14018 return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);
14019 }
14020 case enums.publicKey.elgamal: {
14021 const { c1, c2 } = sessionKeyParams;
14022 const p = publicKeyParams.p;
14023 const x = privateKeyParams.x;
14024 return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);
14025 }
14026 case enums.publicKey.ecdh: {
14027 const { oid, Q, kdfParams } = publicKeyParams;
14028 const { d } = privateKeyParams;
14029 const { V, C } = sessionKeyParams;
14030 return publicKey.elliptic.ecdh.decrypt(
14031 oid, kdfParams, V, C.data, Q, d, fingerprint);
14032 }
14033 default:
14034 throw new Error('Unknown public key encryption algorithm.');
14035 }
14036}
14037
14038/**
14039 * Parse public key material in binary form to get the key parameters
14040 * @param {module:enums.publicKey} algo - The key algorithm
14041 * @param {Uint8Array} bytes - The key material to parse
14042 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
14043 */
14044function parsePublicKeyParams(algo, bytes) {
14045 let read = 0;
14046 switch (algo) {
14047 case enums.publicKey.rsaEncrypt:
14048 case enums.publicKey.rsaEncryptSign:
14049 case enums.publicKey.rsaSign: {
14050 const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;
14051 const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;
14052 return { read, publicParams: { n, e } };
14053 }
14054 case enums.publicKey.dsa: {
14055 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14056 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14057 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14058 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14059 return { read, publicParams: { p, q, g, y } };
14060 }
14061 case enums.publicKey.elgamal: {
14062 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14063 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14064 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14065 return { read, publicParams: { p, g, y } };
14066 }
14067 case enums.publicKey.ecdsa: {
14068 const oid = new OID(); read += oid.read(bytes);
14069 checkSupportedCurve(oid);
14070 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14071 return { read: read, publicParams: { oid, Q } };
14072 }
14073 case enums.publicKey.eddsa: {
14074 const oid = new OID(); read += oid.read(bytes);
14075 checkSupportedCurve(oid);
14076 let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14077 Q = util.leftPad(Q, 33);
14078 return { read: read, publicParams: { oid, Q } };
14079 }
14080 case enums.publicKey.ecdh: {
14081 const oid = new OID(); read += oid.read(bytes);
14082 checkSupportedCurve(oid);
14083 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14084 const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));
14085 return { read: read, publicParams: { oid, Q, kdfParams } };
14086 }
14087 default:
14088 throw new UnsupportedError('Unknown public key encryption algorithm.');
14089 }
14090}
14091
14092/**
14093 * Parse private key material in binary form to get the key parameters
14094 * @param {module:enums.publicKey} algo - The key algorithm
14095 * @param {Uint8Array} bytes - The key material to parse
14096 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
14097 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
14098 */
14099function parsePrivateKeyParams(algo, bytes, publicParams) {
14100 let read = 0;
14101 switch (algo) {
14102 case enums.publicKey.rsaEncrypt:
14103 case enums.publicKey.rsaEncryptSign:
14104 case enums.publicKey.rsaSign: {
14105 const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14106 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14107 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14108 const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;
14109 return { read, privateParams: { d, p, q, u } };
14110 }
14111 case enums.publicKey.dsa:
14112 case enums.publicKey.elgamal: {
14113 const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;
14114 return { read, privateParams: { x } };
14115 }
14116 case enums.publicKey.ecdsa:
14117 case enums.publicKey.ecdh: {
14118 const curve = new Curve(publicParams.oid);
14119 let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14120 d = util.leftPad(d, curve.payloadSize);
14121 return { read, privateParams: { d } };
14122 }
14123 case enums.publicKey.eddsa: {
14124 const curve = new Curve(publicParams.oid);
14125 let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;
14126 seed = util.leftPad(seed, curve.payloadSize);
14127 return { read, privateParams: { seed } };
14128 }
14129 default:
14130 throw new UnsupportedError('Unknown public key encryption algorithm.');
14131 }
14132}
14133
14134/** Returns the types comprising the encrypted session key of an algorithm
14135 * @param {module:enums.publicKey} algo - The key algorithm
14136 * @param {Uint8Array} bytes - The key material to parse
14137 * @returns {Object} The session key parameters referenced by name.
14138 */
14139function parseEncSessionKeyParams(algo, bytes) {
14140 let read = 0;
14141 switch (algo) {
14142 // Algorithm-Specific Fields for RSA encrypted session keys:
14143 // - MPI of RSA encrypted value m**e mod n.
14144 case enums.publicKey.rsaEncrypt:
14145 case enums.publicKey.rsaEncryptSign: {
14146 const c = util.readMPI(bytes.subarray(read));
14147 return { c };
14148 }
14149
14150 // Algorithm-Specific Fields for Elgamal encrypted session keys:
14151 // - MPI of Elgamal value g**k mod p
14152 // - MPI of Elgamal value m * y**k mod p
14153 case enums.publicKey.elgamal: {
14154 const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;
14155 const c2 = util.readMPI(bytes.subarray(read));
14156 return { c1, c2 };
14157 }
14158 // Algorithm-Specific Fields for ECDH encrypted session keys:
14159 // - MPI containing the ephemeral key used to establish the shared secret
14160 // - ECDH Symmetric Key
14161 case enums.publicKey.ecdh: {
14162 const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;
14163 const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read));
14164 return { V, C };
14165 }
14166 default:
14167 throw new UnsupportedError('Unknown public key encryption algorithm.');
14168 }
14169}
14170
14171/**
14172 * Convert params to MPI and serializes them in the proper order
14173 * @param {module:enums.publicKey} algo - The public key algorithm
14174 * @param {Object} params - The key parameters indexed by name
14175 * @returns {Uint8Array} The array containing the MPIs.
14176 */
14177function serializeParams(algo, params) {
14178 const orderedParams = Object.keys(params).map(name => {
14179 const param = params[name];
14180 return util.isUint8Array(param) ? util.uint8ArrayToMPI(param) : param.write();
14181 });
14182 return util.concatUint8Array(orderedParams);
14183}
14184
14185/**
14186 * Generate algorithm-specific key parameters
14187 * @param {module:enums.publicKey} algo - The public key algorithm
14188 * @param {Integer} bits - Bit length for RSA keys
14189 * @param {module:type/oid} oid - Object identifier for ECC keys
14190 * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.
14191 * @async
14192 */
14193function generateParams(algo, bits, oid) {
14194 switch (algo) {
14195 case enums.publicKey.rsaEncrypt:
14196 case enums.publicKey.rsaEncryptSign:
14197 case enums.publicKey.rsaSign: {
14198 return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({
14199 privateParams: { d, p, q, u },
14200 publicParams: { n, e }
14201 }));
14202 }
14203 case enums.publicKey.ecdsa:
14204 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
14205 privateParams: { d: secret },
14206 publicParams: { oid: new OID(oid), Q }
14207 }));
14208 case enums.publicKey.eddsa:
14209 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
14210 privateParams: { seed: secret },
14211 publicParams: { oid: new OID(oid), Q }
14212 }));
14213 case enums.publicKey.ecdh:
14214 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({
14215 privateParams: { d: secret },
14216 publicParams: {
14217 oid: new OID(oid),
14218 Q,
14219 kdfParams: new KDFParams({ hash, cipher })
14220 }
14221 }));
14222 case enums.publicKey.dsa:
14223 case enums.publicKey.elgamal:
14224 throw new Error('Unsupported algorithm for key generation.');
14225 default:
14226 throw new Error('Unknown public key algorithm.');
14227 }
14228}
14229
14230/**
14231 * Validate algorithm-specific key parameters
14232 * @param {module:enums.publicKey} algo - The public key algorithm
14233 * @param {Object} publicParams - Algorithm-specific public key parameters
14234 * @param {Object} privateParams - Algorithm-specific private key parameters
14235 * @returns {Promise<Boolean>} Whether the parameters are valid.
14236 * @async
14237 */
14238async function validateParams$6(algo, publicParams, privateParams) {
14239 if (!publicParams || !privateParams) {
14240 throw new Error('Missing key parameters');
14241 }
14242 switch (algo) {
14243 case enums.publicKey.rsaEncrypt:
14244 case enums.publicKey.rsaEncryptSign:
14245 case enums.publicKey.rsaSign: {
14246 const { n, e } = publicParams;
14247 const { d, p, q, u } = privateParams;
14248 return publicKey.rsa.validateParams(n, e, d, p, q, u);
14249 }
14250 case enums.publicKey.dsa: {
14251 const { p, q, g, y } = publicParams;
14252 const { x } = privateParams;
14253 return publicKey.dsa.validateParams(p, q, g, y, x);
14254 }
14255 case enums.publicKey.elgamal: {
14256 const { p, g, y } = publicParams;
14257 const { x } = privateParams;
14258 return publicKey.elgamal.validateParams(p, g, y, x);
14259 }
14260 case enums.publicKey.ecdsa:
14261 case enums.publicKey.ecdh: {
14262 const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];
14263 const { oid, Q } = publicParams;
14264 const { d } = privateParams;
14265 return algoModule.validateParams(oid, Q, d);
14266 }
14267 case enums.publicKey.eddsa: {
14268 const { oid, Q } = publicParams;
14269 const { seed } = privateParams;
14270 return publicKey.elliptic.eddsa.validateParams(oid, Q, seed);
14271 }
14272 default:
14273 throw new Error('Unknown public key algorithm.');
14274 }
14275}
14276
14277/**
14278 * Generates a random byte prefix for the specified algorithm
14279 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
14280 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
14281 * @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
14282 * @async
14283 */
14284async function getPrefixRandom(algo) {
14285 const { blockSize } = getCipher(algo);
14286 const prefixrandom = await getRandomBytes(blockSize);
14287 const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
14288 return util.concat([prefixrandom, repeat]);
14289}
14290
14291/**
14292 * Generating a session key for the specified symmetric algorithm
14293 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
14294 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
14295 * @returns {Promise<Uint8Array>} Random bytes as a string to be used as a key.
14296 * @async
14297 */
14298function generateSessionKey(algo) {
14299 const { keySize } = getCipher(algo);
14300 return getRandomBytes(keySize);
14301}
14302
14303/**
14304 * Get implementation of the given AEAD mode
14305 * @param {enums.aead} algo
14306 * @returns {Object}
14307 * @throws {Error} on invalid algo
14308 */
14309function getAEADMode(algo) {
14310 const algoName = enums.read(enums.aead, algo);
14311 return mode[algoName];
14312}
14313
14314/**
14315 * Get implementation of the given cipher
14316 * @param {enums.symmetric} algo
14317 * @returns {Object}
14318 * @throws {Error} on invalid algo
14319 */
14320function getCipher(algo) {
14321 const algoName = enums.read(enums.symmetric, algo);
14322 return cipher[algoName];
14323}
14324
14325/**
14326 * Check whether the given curve OID is supported
14327 * @param {module:type/oid} oid - EC object identifier
14328 * @throws {UnsupportedError} if curve is not supported
14329 */
14330function checkSupportedCurve(oid) {
14331 try {
14332 oid.getName();
14333 } catch (e) {
14334 throw new UnsupportedError('Unknown curve OID');
14335 }
14336}
14337
14338var crypto$1 = /*#__PURE__*/Object.freeze({
14339 __proto__: null,
14340 publicKeyEncrypt: publicKeyEncrypt,
14341 publicKeyDecrypt: publicKeyDecrypt,
14342 parsePublicKeyParams: parsePublicKeyParams,
14343 parsePrivateKeyParams: parsePrivateKeyParams,
14344 parseEncSessionKeyParams: parseEncSessionKeyParams,
14345 serializeParams: serializeParams,
14346 generateParams: generateParams,
14347 validateParams: validateParams$6,
14348 getPrefixRandom: getPrefixRandom,
14349 generateSessionKey: generateSessionKey,
14350 getAEADMode: getAEADMode,
14351 getCipher: getCipher
14352});
14353
14354// Modified by ProtonTech AG
14355
14356const webCrypto$5 = util.getWebCrypto();
14357const nodeCrypto$6 = util.getNodeCrypto();
14358
14359const knownAlgos = nodeCrypto$6 ? nodeCrypto$6.getCiphers() : [];
14360const nodeAlgos = {
14361 idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
14362 tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
14363 cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
14364 blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
14365 aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
14366 aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
14367 aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
14368 /* twofish is not implemented in OpenSSL */
14369};
14370
14371/**
14372 * CFB encryption
14373 * @param {enums.symmetric} algo - block cipher algorithm
14374 * @param {Uint8Array} key
14375 * @param {MaybeStream<Uint8Array>} plaintext
14376 * @param {Uint8Array} iv
14377 * @param {Object} config - full configuration, defaults to openpgp.config
14378 * @returns MaybeStream<Uint8Array>
14379 */
14380async function encrypt$3(algo, key, plaintext, iv, config) {
14381 const algoName = enums.read(enums.symmetric, algo);
14382 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
14383 return nodeEncrypt$1(algo, key, plaintext, iv);
14384 }
14385 if (algoName.substr(0, 3) === 'aes') {
14386 return aesEncrypt(algo, key, plaintext, iv, config);
14387 }
14388
14389 const cipherfn = new cipher[algoName](key);
14390 const block_size = cipherfn.blockSize;
14391
14392 const blockc = iv.slice();
14393 let pt = new Uint8Array();
14394 const process = chunk => {
14395 if (chunk) {
14396 pt = util.concatUint8Array([pt, chunk]);
14397 }
14398 const ciphertext = new Uint8Array(pt.length);
14399 let i;
14400 let j = 0;
14401 while (chunk ? pt.length >= block_size : pt.length) {
14402 const encblock = cipherfn.encrypt(blockc);
14403 for (i = 0; i < block_size; i++) {
14404 blockc[i] = pt[i] ^ encblock[i];
14405 ciphertext[j++] = blockc[i];
14406 }
14407 pt = pt.subarray(block_size);
14408 }
14409 return ciphertext.subarray(0, j);
14410 };
14411 return transform(plaintext, process, process);
14412}
14413
14414/**
14415 * CFB decryption
14416 * @param {enums.symmetric} algo - block cipher algorithm
14417 * @param {Uint8Array} key
14418 * @param {MaybeStream<Uint8Array>} ciphertext
14419 * @param {Uint8Array} iv
14420 * @returns MaybeStream<Uint8Array>
14421 */
14422async function decrypt$3(algo, key, ciphertext, iv) {
14423 const algoName = enums.read(enums.symmetric, algo);
14424 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
14425 return nodeDecrypt$1(algo, key, ciphertext, iv);
14426 }
14427 if (algoName.substr(0, 3) === 'aes') {
14428 return aesDecrypt(algo, key, ciphertext, iv);
14429 }
14430
14431 const cipherfn = new cipher[algoName](key);
14432 const block_size = cipherfn.blockSize;
14433
14434 let blockp = iv;
14435 let ct = new Uint8Array();
14436 const process = chunk => {
14437 if (chunk) {
14438 ct = util.concatUint8Array([ct, chunk]);
14439 }
14440 const plaintext = new Uint8Array(ct.length);
14441 let i;
14442 let j = 0;
14443 while (chunk ? ct.length >= block_size : ct.length) {
14444 const decblock = cipherfn.encrypt(blockp);
14445 blockp = ct;
14446 for (i = 0; i < block_size; i++) {
14447 plaintext[j++] = blockp[i] ^ decblock[i];
14448 }
14449 ct = ct.subarray(block_size);
14450 }
14451 return plaintext.subarray(0, j);
14452 };
14453 return transform(ciphertext, process, process);
14454}
14455
14456function aesEncrypt(algo, key, pt, iv, config) {
14457 if (
14458 util.getWebCrypto() &&
14459 key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
14460 !util.isStream(pt) &&
14461 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
14462 ) { // Web Crypto
14463 return webEncrypt(algo, key, pt, iv);
14464 }
14465 // asm.js fallback
14466 const cfb = new AES_CFB(key, iv);
14467 return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
14468}
14469
14470function aesDecrypt(algo, key, ct, iv) {
14471 if (util.isStream(ct)) {
14472 const cfb = new AES_CFB(key, iv);
14473 return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
14474 }
14475 return AES_CFB.decrypt(ct, key, iv);
14476}
14477
14478function xorMut(a, b) {
14479 for (let i = 0; i < a.length; i++) {
14480 a[i] = a[i] ^ b[i];
14481 }
14482}
14483
14484async function webEncrypt(algo, key, pt, iv) {
14485 const ALGO = 'AES-CBC';
14486 const _key = await webCrypto$5.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
14487 const { blockSize } = getCipher(algo);
14488 const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);
14489 const ct = new Uint8Array(await webCrypto$5.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);
14490 xorMut(ct, pt);
14491 return ct;
14492}
14493
14494function nodeEncrypt$1(algo, key, pt, iv) {
14495 const algoName = enums.read(enums.symmetric, algo);
14496 const cipherObj = new nodeCrypto$6.createCipheriv(nodeAlgos[algoName], key, iv);
14497 return transform(pt, value => new Uint8Array(cipherObj.update(value)));
14498}
14499
14500function nodeDecrypt$1(algo, key, ct, iv) {
14501 const algoName = enums.read(enums.symmetric, algo);
14502 const decipherObj = new nodeCrypto$6.createDecipheriv(nodeAlgos[algoName], key, iv);
14503 return transform(ct, value => new Uint8Array(decipherObj.update(value)));
14504}
14505
14506var cfb = /*#__PURE__*/Object.freeze({
14507 __proto__: null,
14508 encrypt: encrypt$3,
14509 decrypt: decrypt$3
14510});
14511
14512class AES_CTR {
14513 static encrypt(data, key, nonce) {
14514 return new AES_CTR(key, nonce).encrypt(data);
14515 }
14516 static decrypt(data, key, nonce) {
14517 return new AES_CTR(key, nonce).encrypt(data);
14518 }
14519 constructor(key, nonce, aes) {
14520 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
14521 delete this.aes.padding;
14522 this.AES_CTR_set_options(nonce);
14523 }
14524 encrypt(data) {
14525 const r1 = this.aes.AES_Encrypt_process(data);
14526 const r2 = this.aes.AES_Encrypt_finish();
14527 return joinBytes(r1, r2);
14528 }
14529 decrypt(data) {
14530 const r1 = this.aes.AES_Encrypt_process(data);
14531 const r2 = this.aes.AES_Encrypt_finish();
14532 return joinBytes(r1, r2);
14533 }
14534 AES_CTR_set_options(nonce, counter, size) {
14535 let { asm } = this.aes.acquire_asm();
14536 if (size !== undefined) {
14537 if (size < 8 || size > 48)
14538 throw new IllegalArgumentError('illegal counter size');
14539 let mask = Math.pow(2, size) - 1;
14540 asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);
14541 }
14542 else {
14543 size = 48;
14544 asm.set_mask(0, 0, 0xffff, 0xffffffff);
14545 }
14546 if (nonce !== undefined) {
14547 let len = nonce.length;
14548 if (!len || len > 16)
14549 throw new IllegalArgumentError('illegal nonce size');
14550 let view = new DataView(new ArrayBuffer(16));
14551 new Uint8Array(view.buffer).set(nonce);
14552 asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
14553 }
14554 else {
14555 throw new Error('nonce is required');
14556 }
14557 if (counter !== undefined) {
14558 if (counter < 0 || counter >= Math.pow(2, size))
14559 throw new IllegalArgumentError('illegal counter value');
14560 asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);
14561 }
14562 }
14563}
14564
14565class AES_CBC {
14566 static encrypt(data, key, padding = true, iv) {
14567 return new AES_CBC(key, iv, padding).encrypt(data);
14568 }
14569 static decrypt(data, key, padding = true, iv) {
14570 return new AES_CBC(key, iv, padding).decrypt(data);
14571 }
14572 constructor(key, iv, padding = true, aes) {
14573 this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');
14574 }
14575 encrypt(data) {
14576 const r1 = this.aes.AES_Encrypt_process(data);
14577 const r2 = this.aes.AES_Encrypt_finish();
14578 return joinBytes(r1, r2);
14579 }
14580 decrypt(data) {
14581 const r1 = this.aes.AES_Decrypt_process(data);
14582 const r2 = this.aes.AES_Decrypt_finish();
14583 return joinBytes(r1, r2);
14584 }
14585}
14586
14587/**
14588 * @fileoverview This module implements AES-CMAC on top of
14589 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
14590 * @module crypto/cmac
14591 * @private
14592 */
14593
14594const webCrypto$6 = util.getWebCrypto();
14595const nodeCrypto$7 = util.getNodeCrypto();
14596
14597
14598/**
14599 * This implementation of CMAC is based on the description of OMAC in
14600 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
14601 * document:
14602 *
14603 * We have made a small modification to the OMAC algorithm as it was
14604 * originally presented, changing one of its two constants.
14605 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
14606 * multiplicative inverse of 2) in the original definition of OMAC [14].
14607 * The OMAC authors indicate that they will promulgate this modification
14608 * [15], which slightly simplifies implementations.
14609 */
14610
14611const blockLength = 16;
14612
14613
14614/**
14615 * xor `padding` into the end of `data`. This function implements "the
14616 * operation xor→ [which] xors the shorter string into the end of longer
14617 * one". Since data is always as least as long as padding, we can
14618 * simplify the implementation.
14619 * @param {Uint8Array} data
14620 * @param {Uint8Array} padding
14621 */
14622function rightXORMut(data, padding) {
14623 const offset = data.length - blockLength;
14624 for (let i = 0; i < blockLength; i++) {
14625 data[i + offset] ^= padding[i];
14626 }
14627 return data;
14628}
14629
14630function pad(data, padding, padding2) {
14631 // if |M| in {n, 2n, 3n, ...}
14632 if (data.length && data.length % blockLength === 0) {
14633 // then return M xor→ B,
14634 return rightXORMut(data, padding);
14635 }
14636 // else return (M || 10^(n−1−(|M| mod n))) xor→ P
14637 const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength));
14638 padded.set(data);
14639 padded[data.length] = 0b10000000;
14640 return rightXORMut(padded, padding2);
14641}
14642
14643const zeroBlock = new Uint8Array(blockLength);
14644
14645async function CMAC(key) {
14646 const cbc = await CBC(key);
14647
14648 // L ← E_K(0^n); B ← 2L; P ← 4L
14649 const padding = util.double(await cbc(zeroBlock));
14650 const padding2 = util.double(padding);
14651
14652 return async function(data) {
14653 // return CBC_K(pad(M; B, P))
14654 return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
14655 };
14656}
14657
14658async function CBC(key) {
14659 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
14660 key = await webCrypto$6.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
14661 return async function(pt) {
14662 const ct = await webCrypto$6.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
14663 return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
14664 };
14665 }
14666 if (util.getNodeCrypto()) { // Node crypto library
14667 return async function(pt) {
14668 const en = new nodeCrypto$7.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
14669 const ct = en.update(pt);
14670 return new Uint8Array(ct);
14671 };
14672 }
14673 // asm.js fallback
14674 return async function(pt) {
14675 return AES_CBC.encrypt(pt, key, false, zeroBlock);
14676 };
14677}
14678
14679// OpenPGP.js - An OpenPGP implementation in javascript
14680
14681const webCrypto$7 = util.getWebCrypto();
14682const nodeCrypto$8 = util.getNodeCrypto();
14683const Buffer$1 = util.getNodeBuffer();
14684
14685
14686const blockLength$1 = 16;
14687const ivLength = blockLength$1;
14688const tagLength = blockLength$1;
14689
14690const zero = new Uint8Array(blockLength$1);
14691const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1;
14692const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2;
14693
14694async function OMAC(key) {
14695 const cmac = await CMAC(key);
14696 return function(t, message) {
14697 return cmac(util.concatUint8Array([t, message]));
14698 };
14699}
14700
14701async function CTR(key) {
14702 if (
14703 util.getWebCrypto() &&
14704 key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
14705 ) {
14706 key = await webCrypto$7.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
14707 return async function(pt, iv) {
14708 const ct = await webCrypto$7.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt);
14709 return new Uint8Array(ct);
14710 };
14711 }
14712 if (util.getNodeCrypto()) { // Node crypto library
14713 return async function(pt, iv) {
14714 const en = new nodeCrypto$8.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
14715 const ct = Buffer$1.concat([en.update(pt), en.final()]);
14716 return new Uint8Array(ct);
14717 };
14718 }
14719 // asm.js fallback
14720 return async function(pt, iv) {
14721 return AES_CTR.encrypt(pt, key, iv);
14722 };
14723}
14724
14725
14726/**
14727 * Class to en/decrypt using EAX mode.
14728 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
14729 * @param {Uint8Array} key - The encryption key
14730 */
14731async function EAX(cipher, key) {
14732 if (cipher !== enums.symmetric.aes128 &&
14733 cipher !== enums.symmetric.aes192 &&
14734 cipher !== enums.symmetric.aes256) {
14735 throw new Error('EAX mode supports only AES cipher');
14736 }
14737
14738 const [
14739 omac,
14740 ctr
14741 ] = await Promise.all([
14742 OMAC(key),
14743 CTR(key)
14744 ]);
14745
14746 return {
14747 /**
14748 * Encrypt plaintext input.
14749 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
14750 * @param {Uint8Array} nonce - The nonce (16 bytes)
14751 * @param {Uint8Array} adata - Associated data to sign
14752 * @returns {Promise<Uint8Array>} The ciphertext output.
14753 */
14754 encrypt: async function(plaintext, nonce, adata) {
14755 const [
14756 omacNonce,
14757 omacAdata
14758 ] = await Promise.all([
14759 omac(zero, nonce),
14760 omac(one, adata)
14761 ]);
14762 const ciphered = await ctr(plaintext, omacNonce);
14763 const omacCiphered = await omac(two, ciphered);
14764 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
14765 for (let i = 0; i < tagLength; i++) {
14766 tag[i] ^= omacAdata[i] ^ omacNonce[i];
14767 }
14768 return util.concatUint8Array([ciphered, tag]);
14769 },
14770
14771 /**
14772 * Decrypt ciphertext input.
14773 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
14774 * @param {Uint8Array} nonce - The nonce (16 bytes)
14775 * @param {Uint8Array} adata - Associated data to verify
14776 * @returns {Promise<Uint8Array>} The plaintext output.
14777 */
14778 decrypt: async function(ciphertext, nonce, adata) {
14779 if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
14780 const ciphered = ciphertext.subarray(0, -tagLength);
14781 const ctTag = ciphertext.subarray(-tagLength);
14782 const [
14783 omacNonce,
14784 omacAdata,
14785 omacCiphered
14786 ] = await Promise.all([
14787 omac(zero, nonce),
14788 omac(one, adata),
14789 omac(two, ciphered)
14790 ]);
14791 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
14792 for (let i = 0; i < tagLength; i++) {
14793 tag[i] ^= omacAdata[i] ^ omacNonce[i];
14794 }
14795 if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
14796 const plaintext = await ctr(ciphered, omacNonce);
14797 return plaintext;
14798 }
14799 };
14800}
14801
14802
14803/**
14804 * 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}.
14805 * @param {Uint8Array} iv - The initialization vector (16 bytes)
14806 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
14807 */
14808EAX.getNonce = function(iv, chunkIndex) {
14809 const nonce = iv.slice();
14810 for (let i = 0; i < chunkIndex.length; i++) {
14811 nonce[8 + i] ^= chunkIndex[i];
14812 }
14813 return nonce;
14814};
14815
14816EAX.blockLength = blockLength$1;
14817EAX.ivLength = ivLength;
14818EAX.tagLength = tagLength;
14819
14820// OpenPGP.js - An OpenPGP implementation in javascript
14821
14822const blockLength$2 = 16;
14823const ivLength$1 = 15;
14824
14825// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
14826// While OCB [RFC7253] allows the authentication tag length to be of any
14827// number up to 128 bits long, this document requires a fixed
14828// authentication tag length of 128 bits (16 octets) for simplicity.
14829const tagLength$1 = 16;
14830
14831
14832function ntz(n) {
14833 let ntz = 0;
14834 for (let i = 1; (n & i) === 0; i <<= 1) {
14835 ntz++;
14836 }
14837 return ntz;
14838}
14839
14840function xorMut$1(S, T) {
14841 for (let i = 0; i < S.length; i++) {
14842 S[i] ^= T[i];
14843 }
14844 return S;
14845}
14846
14847function xor(S, T) {
14848 return xorMut$1(S.slice(), T);
14849}
14850
14851const zeroBlock$1 = new Uint8Array(blockLength$2);
14852const one$1 = new Uint8Array([1]);
14853
14854/**
14855 * Class to en/decrypt using OCB mode.
14856 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
14857 * @param {Uint8Array} key - The encryption key
14858 */
14859async function OCB(cipher$1, key) {
14860
14861 let maxNtz = 0;
14862 let encipher;
14863 let decipher;
14864 let mask;
14865
14866 constructKeyVariables(cipher$1, key);
14867
14868 function constructKeyVariables(cipher$1, key) {
14869 const cipherName = enums.read(enums.symmetric, cipher$1);
14870 const aes = new cipher[cipherName](key);
14871 encipher = aes.encrypt.bind(aes);
14872 decipher = aes.decrypt.bind(aes);
14873
14874 const mask_x = encipher(zeroBlock$1);
14875 const mask_$ = util.double(mask_x);
14876 mask = [];
14877 mask[0] = util.double(mask_$);
14878
14879
14880 mask.x = mask_x;
14881 mask.$ = mask_$;
14882 }
14883
14884 function extendKeyVariables(text, adata) {
14885 const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1;
14886 for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
14887 mask[i] = util.double(mask[i - 1]);
14888 }
14889 maxNtz = newMaxNtz;
14890 }
14891
14892 function hash(adata) {
14893 if (!adata.length) {
14894 // Fast path
14895 return zeroBlock$1;
14896 }
14897
14898 //
14899 // Consider A as a sequence of 128-bit blocks
14900 //
14901 const m = adata.length / blockLength$2 | 0;
14902
14903 const offset = new Uint8Array(blockLength$2);
14904 const sum = new Uint8Array(blockLength$2);
14905 for (let i = 0; i < m; i++) {
14906 xorMut$1(offset, mask[ntz(i + 1)]);
14907 xorMut$1(sum, encipher(xor(offset, adata)));
14908 adata = adata.subarray(blockLength$2);
14909 }
14910
14911 //
14912 // Process any final partial block; compute final hash value
14913 //
14914 if (adata.length) {
14915 xorMut$1(offset, mask.x);
14916
14917 const cipherInput = new Uint8Array(blockLength$2);
14918 cipherInput.set(adata, 0);
14919 cipherInput[adata.length] = 0b10000000;
14920 xorMut$1(cipherInput, offset);
14921
14922 xorMut$1(sum, encipher(cipherInput));
14923 }
14924
14925 return sum;
14926 }
14927
14928 /**
14929 * Encrypt/decrypt data.
14930 * @param {encipher|decipher} fn - Encryption/decryption block cipher function
14931 * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
14932 * @param {Uint8Array} nonce - The nonce (15 bytes)
14933 * @param {Uint8Array} adata - Associated data to sign
14934 * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases.
14935 */
14936 function crypt(fn, text, nonce, adata) {
14937 //
14938 // Consider P as a sequence of 128-bit blocks
14939 //
14940 const m = text.length / blockLength$2 | 0;
14941
14942 //
14943 // Key-dependent variables
14944 //
14945 extendKeyVariables(text, adata);
14946
14947 //
14948 // Nonce-dependent and per-encryption variables
14949 //
14950 // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
14951 // Note: We assume here that tagLength mod 16 == 0.
14952 const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]);
14953 // bottom = str2num(Nonce[123..128])
14954 const bottom = paddedNonce[blockLength$2 - 1] & 0b111111;
14955 // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
14956 paddedNonce[blockLength$2 - 1] &= 0b11000000;
14957 const kTop = encipher(paddedNonce);
14958 // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
14959 const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
14960 // Offset_0 = Stretch[1+bottom..128+bottom]
14961 const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
14962 // Checksum_0 = zeros(128)
14963 const checksum = new Uint8Array(blockLength$2);
14964
14965 const ct = new Uint8Array(text.length + tagLength$1);
14966
14967 //
14968 // Process any whole blocks
14969 //
14970 let i;
14971 let pos = 0;
14972 for (i = 0; i < m; i++) {
14973 // Offset_i = Offset_{i-1} xor L_{ntz(i)}
14974 xorMut$1(offset, mask[ntz(i + 1)]);
14975 // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
14976 // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
14977 ct.set(xorMut$1(fn(xor(offset, text)), offset), pos);
14978 // Checksum_i = Checksum_{i-1} xor P_i
14979 xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos));
14980
14981 text = text.subarray(blockLength$2);
14982 pos += blockLength$2;
14983 }
14984
14985 //
14986 // Process any final partial block and compute raw tag
14987 //
14988 if (text.length) {
14989 // Offset_* = Offset_m xor L_*
14990 xorMut$1(offset, mask.x);
14991 // Pad = ENCIPHER(K, Offset_*)
14992 const padding = encipher(offset);
14993 // C_* = P_* xor Pad[1..bitlen(P_*)]
14994 ct.set(xor(text, padding), pos);
14995
14996 // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
14997 const xorInput = new Uint8Array(blockLength$2);
14998 xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0);
14999 xorInput[text.length] = 0b10000000;
15000 xorMut$1(checksum, xorInput);
15001 pos += text.length;
15002 }
15003 // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
15004 const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata));
15005
15006 //
15007 // Assemble ciphertext
15008 //
15009 // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
15010 ct.set(tag, pos);
15011 return ct;
15012 }
15013
15014
15015 return {
15016 /**
15017 * Encrypt plaintext input.
15018 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
15019 * @param {Uint8Array} nonce - The nonce (15 bytes)
15020 * @param {Uint8Array} adata - Associated data to sign
15021 * @returns {Promise<Uint8Array>} The ciphertext output.
15022 */
15023 encrypt: async function(plaintext, nonce, adata) {
15024 return crypt(encipher, plaintext, nonce, adata);
15025 },
15026
15027 /**
15028 * Decrypt ciphertext input.
15029 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
15030 * @param {Uint8Array} nonce - The nonce (15 bytes)
15031 * @param {Uint8Array} adata - Associated data to sign
15032 * @returns {Promise<Uint8Array>} The ciphertext output.
15033 */
15034 decrypt: async function(ciphertext, nonce, adata) {
15035 if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext');
15036
15037 const tag = ciphertext.subarray(-tagLength$1);
15038 ciphertext = ciphertext.subarray(0, -tagLength$1);
15039
15040 const crypted = crypt(decipher, ciphertext, nonce, adata);
15041 // if (Tag[1..TAGLEN] == T)
15042 if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) {
15043 return crypted.subarray(0, -tagLength$1);
15044 }
15045 throw new Error('Authentication tag mismatch');
15046 }
15047 };
15048}
15049
15050
15051/**
15052 * 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}.
15053 * @param {Uint8Array} iv - The initialization vector (15 bytes)
15054 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
15055 */
15056OCB.getNonce = function(iv, chunkIndex) {
15057 const nonce = iv.slice();
15058 for (let i = 0; i < chunkIndex.length; i++) {
15059 nonce[7 + i] ^= chunkIndex[i];
15060 }
15061 return nonce;
15062};
15063
15064OCB.blockLength = blockLength$2;
15065OCB.ivLength = ivLength$1;
15066OCB.tagLength = tagLength$1;
15067
15068const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
15069class AES_GCM {
15070 constructor(key, nonce, adata, tagSize = 16, aes) {
15071 this.tagSize = tagSize;
15072 this.gamma0 = 0;
15073 this.counter = 1;
15074 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
15075 let { asm, heap } = this.aes.acquire_asm();
15076 // Init GCM
15077 asm.gcm_init();
15078 // Tag size
15079 if (this.tagSize < 4 || this.tagSize > 16)
15080 throw new IllegalArgumentError('illegal tagSize value');
15081 // Nonce
15082 const noncelen = nonce.length || 0;
15083 const noncebuf = new Uint8Array(16);
15084 if (noncelen !== 12) {
15085 this._gcm_mac_process(nonce);
15086 heap[0] = 0;
15087 heap[1] = 0;
15088 heap[2] = 0;
15089 heap[3] = 0;
15090 heap[4] = 0;
15091 heap[5] = 0;
15092 heap[6] = 0;
15093 heap[7] = 0;
15094 heap[8] = 0;
15095 heap[9] = 0;
15096 heap[10] = 0;
15097 heap[11] = noncelen >>> 29;
15098 heap[12] = (noncelen >>> 21) & 255;
15099 heap[13] = (noncelen >>> 13) & 255;
15100 heap[14] = (noncelen >>> 5) & 255;
15101 heap[15] = (noncelen << 3) & 255;
15102 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15103 asm.get_iv(AES_asm.HEAP_DATA);
15104 asm.set_iv(0, 0, 0, 0);
15105 noncebuf.set(heap.subarray(0, 16));
15106 }
15107 else {
15108 noncebuf.set(nonce);
15109 noncebuf[15] = 1;
15110 }
15111 const nonceview = new DataView(noncebuf.buffer);
15112 this.gamma0 = nonceview.getUint32(12);
15113 asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
15114 asm.set_mask(0, 0, 0, 0xffffffff);
15115 // Associated data
15116 if (adata !== undefined) {
15117 if (adata.length > _AES_GCM_data_maxLength)
15118 throw new IllegalArgumentError('illegal adata length');
15119 if (adata.length) {
15120 this.adata = adata;
15121 this._gcm_mac_process(adata);
15122 }
15123 else {
15124 this.adata = undefined;
15125 }
15126 }
15127 else {
15128 this.adata = undefined;
15129 }
15130 // Counter
15131 if (this.counter < 1 || this.counter > 0xffffffff)
15132 throw new RangeError('counter must be a positive 32-bit integer');
15133 asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);
15134 }
15135 static encrypt(cleartext, key, nonce, adata, tagsize) {
15136 return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
15137 }
15138 static decrypt(ciphertext, key, nonce, adata, tagsize) {
15139 return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
15140 }
15141 encrypt(data) {
15142 return this.AES_GCM_encrypt(data);
15143 }
15144 decrypt(data) {
15145 return this.AES_GCM_decrypt(data);
15146 }
15147 AES_GCM_Encrypt_process(data) {
15148 let dpos = 0;
15149 let dlen = data.length || 0;
15150 let { asm, heap } = this.aes.acquire_asm();
15151 let counter = this.counter;
15152 let pos = this.aes.pos;
15153 let len = this.aes.len;
15154 let rpos = 0;
15155 let rlen = (len + dlen) & -16;
15156 let wlen = 0;
15157 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
15158 throw new RangeError('counter overflow');
15159 const result = new Uint8Array(rlen);
15160 while (dlen > 0) {
15161 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
15162 len += wlen;
15163 dpos += wlen;
15164 dlen -= wlen;
15165 wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);
15166 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
15167 if (wlen)
15168 result.set(heap.subarray(pos, pos + wlen), rpos);
15169 counter += wlen >>> 4;
15170 rpos += wlen;
15171 if (wlen < len) {
15172 pos += wlen;
15173 len -= wlen;
15174 }
15175 else {
15176 pos = 0;
15177 len = 0;
15178 }
15179 }
15180 this.counter = counter;
15181 this.aes.pos = pos;
15182 this.aes.len = len;
15183 return result;
15184 }
15185 AES_GCM_Encrypt_finish() {
15186 let { asm, heap } = this.aes.acquire_asm();
15187 let counter = this.counter;
15188 let tagSize = this.tagSize;
15189 let adata = this.adata;
15190 let pos = this.aes.pos;
15191 let len = this.aes.len;
15192 const result = new Uint8Array(len + tagSize);
15193 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);
15194 if (len)
15195 result.set(heap.subarray(pos, pos + len));
15196 let i = len;
15197 for (; i & 15; i++)
15198 heap[pos + i] = 0;
15199 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
15200 const alen = adata !== undefined ? adata.length : 0;
15201 const clen = ((counter - 1) << 4) + len;
15202 heap[0] = 0;
15203 heap[1] = 0;
15204 heap[2] = 0;
15205 heap[3] = alen >>> 29;
15206 heap[4] = alen >>> 21;
15207 heap[5] = (alen >>> 13) & 255;
15208 heap[6] = (alen >>> 5) & 255;
15209 heap[7] = (alen << 3) & 255;
15210 heap[8] = heap[9] = heap[10] = 0;
15211 heap[11] = clen >>> 29;
15212 heap[12] = (clen >>> 21) & 255;
15213 heap[13] = (clen >>> 13) & 255;
15214 heap[14] = (clen >>> 5) & 255;
15215 heap[15] = (clen << 3) & 255;
15216 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15217 asm.get_iv(AES_asm.HEAP_DATA);
15218 asm.set_counter(0, 0, 0, this.gamma0);
15219 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
15220 result.set(heap.subarray(0, tagSize), len);
15221 this.counter = 1;
15222 this.aes.pos = 0;
15223 this.aes.len = 0;
15224 return result;
15225 }
15226 AES_GCM_Decrypt_process(data) {
15227 let dpos = 0;
15228 let dlen = data.length || 0;
15229 let { asm, heap } = this.aes.acquire_asm();
15230 let counter = this.counter;
15231 let tagSize = this.tagSize;
15232 let pos = this.aes.pos;
15233 let len = this.aes.len;
15234 let rpos = 0;
15235 let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;
15236 let tlen = len + dlen - rlen;
15237 let wlen = 0;
15238 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
15239 throw new RangeError('counter overflow');
15240 const result = new Uint8Array(rlen);
15241 while (dlen > tlen) {
15242 wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);
15243 len += wlen;
15244 dpos += wlen;
15245 dlen -= wlen;
15246 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
15247 wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);
15248 if (wlen)
15249 result.set(heap.subarray(pos, pos + wlen), rpos);
15250 counter += wlen >>> 4;
15251 rpos += wlen;
15252 pos = 0;
15253 len = 0;
15254 }
15255 if (dlen > 0) {
15256 len += _heap_write(heap, 0, data, dpos, dlen);
15257 }
15258 this.counter = counter;
15259 this.aes.pos = pos;
15260 this.aes.len = len;
15261 return result;
15262 }
15263 AES_GCM_Decrypt_finish() {
15264 let { asm, heap } = this.aes.acquire_asm();
15265 let tagSize = this.tagSize;
15266 let adata = this.adata;
15267 let counter = this.counter;
15268 let pos = this.aes.pos;
15269 let len = this.aes.len;
15270 let rlen = len - tagSize;
15271 if (len < tagSize)
15272 throw new IllegalStateError('authentication tag not found');
15273 const result = new Uint8Array(rlen);
15274 const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
15275 let i = rlen;
15276 for (; i & 15; i++)
15277 heap[pos + i] = 0;
15278 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
15279 asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);
15280 if (rlen)
15281 result.set(heap.subarray(pos, pos + rlen));
15282 const alen = adata !== undefined ? adata.length : 0;
15283 const clen = ((counter - 1) << 4) + len - tagSize;
15284 heap[0] = 0;
15285 heap[1] = 0;
15286 heap[2] = 0;
15287 heap[3] = alen >>> 29;
15288 heap[4] = alen >>> 21;
15289 heap[5] = (alen >>> 13) & 255;
15290 heap[6] = (alen >>> 5) & 255;
15291 heap[7] = (alen << 3) & 255;
15292 heap[8] = heap[9] = heap[10] = 0;
15293 heap[11] = clen >>> 29;
15294 heap[12] = (clen >>> 21) & 255;
15295 heap[13] = (clen >>> 13) & 255;
15296 heap[14] = (clen >>> 5) & 255;
15297 heap[15] = (clen << 3) & 255;
15298 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
15299 asm.get_iv(AES_asm.HEAP_DATA);
15300 asm.set_counter(0, 0, 0, this.gamma0);
15301 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
15302 let acheck = 0;
15303 for (let i = 0; i < tagSize; ++i)
15304 acheck |= atag[i] ^ heap[i];
15305 if (acheck)
15306 throw new SecurityError('data integrity check failed');
15307 this.counter = 1;
15308 this.aes.pos = 0;
15309 this.aes.len = 0;
15310 return result;
15311 }
15312 AES_GCM_decrypt(data) {
15313 const result1 = this.AES_GCM_Decrypt_process(data);
15314 const result2 = this.AES_GCM_Decrypt_finish();
15315 const result = new Uint8Array(result1.length + result2.length);
15316 if (result1.length)
15317 result.set(result1);
15318 if (result2.length)
15319 result.set(result2, result1.length);
15320 return result;
15321 }
15322 AES_GCM_encrypt(data) {
15323 const result1 = this.AES_GCM_Encrypt_process(data);
15324 const result2 = this.AES_GCM_Encrypt_finish();
15325 const result = new Uint8Array(result1.length + result2.length);
15326 if (result1.length)
15327 result.set(result1);
15328 if (result2.length)
15329 result.set(result2, result1.length);
15330 return result;
15331 }
15332 _gcm_mac_process(data) {
15333 let { asm, heap } = this.aes.acquire_asm();
15334 let dpos = 0;
15335 let dlen = data.length || 0;
15336 let wlen = 0;
15337 while (dlen > 0) {
15338 wlen = _heap_write(heap, 0, data, dpos, dlen);
15339 dpos += wlen;
15340 dlen -= wlen;
15341 while (wlen & 15)
15342 heap[wlen++] = 0;
15343 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);
15344 }
15345 }
15346}
15347
15348// OpenPGP.js - An OpenPGP implementation in javascript
15349
15350const webCrypto$8 = util.getWebCrypto();
15351const nodeCrypto$9 = util.getNodeCrypto();
15352const Buffer$2 = util.getNodeBuffer();
15353
15354const blockLength$3 = 16;
15355const ivLength$2 = 12; // size of the IV in bytes
15356const tagLength$2 = 16; // size of the tag in bytes
15357const ALGO = 'AES-GCM';
15358
15359/**
15360 * Class to en/decrypt using GCM mode.
15361 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
15362 * @param {Uint8Array} key - The encryption key
15363 */
15364async function GCM(cipher, key) {
15365 if (cipher !== enums.symmetric.aes128 &&
15366 cipher !== enums.symmetric.aes192 &&
15367 cipher !== enums.symmetric.aes256) {
15368 throw new Error('GCM mode supports only AES cipher');
15369 }
15370
15371 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
15372 const _key = await webCrypto$8.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
15373
15374 return {
15375 encrypt: async function(pt, iv, adata = new Uint8Array()) {
15376 if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages
15377 return AES_GCM.encrypt(pt, key, iv, adata);
15378 }
15379 const ct = await webCrypto$8.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt);
15380 return new Uint8Array(ct);
15381 },
15382
15383 decrypt: async function(ct, iv, adata = new Uint8Array()) {
15384 if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages
15385 return AES_GCM.decrypt(ct, key, iv, adata);
15386 }
15387 const pt = await webCrypto$8.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct);
15388 return new Uint8Array(pt);
15389 }
15390 };
15391 }
15392
15393 if (util.getNodeCrypto()) { // Node crypto library
15394 return {
15395 encrypt: async function(pt, iv, adata = new Uint8Array()) {
15396 const en = new nodeCrypto$9.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
15397 en.setAAD(adata);
15398 const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
15399 return new Uint8Array(ct);
15400 },
15401
15402 decrypt: async function(ct, iv, adata = new Uint8Array()) {
15403 const de = new nodeCrypto$9.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
15404 de.setAAD(adata);
15405 de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext
15406 const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]);
15407 return new Uint8Array(pt);
15408 }
15409 };
15410 }
15411
15412 return {
15413 encrypt: async function(pt, iv, adata) {
15414 return AES_GCM.encrypt(pt, key, iv, adata);
15415 },
15416
15417 decrypt: async function(ct, iv, adata) {
15418 return AES_GCM.decrypt(ct, key, iv, adata);
15419 }
15420 };
15421}
15422
15423
15424/**
15425 * Get GCM nonce. Note: this operation is not defined by the standard.
15426 * A future version of the standard may define GCM mode differently,
15427 * hopefully under a different ID (we use Private/Experimental algorithm
15428 * ID 100) so that we can maintain backwards compatibility.
15429 * @param {Uint8Array} iv - The initialization vector (12 bytes)
15430 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
15431 */
15432GCM.getNonce = function(iv, chunkIndex) {
15433 const nonce = iv.slice();
15434 for (let i = 0; i < chunkIndex.length; i++) {
15435 nonce[4 + i] ^= chunkIndex[i];
15436 }
15437 return nonce;
15438};
15439
15440GCM.blockLength = blockLength$3;
15441GCM.ivLength = ivLength$2;
15442GCM.tagLength = tagLength$2;
15443
15444/**
15445 * @fileoverview Cipher modes
15446 * @module crypto/mode
15447 * @private
15448 */
15449
15450var mode = {
15451 /** @see module:crypto/mode/cfb */
15452 cfb: cfb,
15453 /** @see module:crypto/mode/gcm */
15454 gcm: GCM,
15455 experimentalGCM: GCM,
15456 /** @see module:crypto/mode/eax */
15457 eax: EAX,
15458 /** @see module:crypto/mode/ocb */
15459 ocb: OCB
15460};
15461
15462/**
15463 * @fileoverview Provides functions for asymmetric signing and signature verification
15464 * @module crypto/signature
15465 * @private
15466 */
15467
15468/**
15469 * Parse signature in binary form to get the parameters.
15470 * The returned values are only padded for EdDSA, since in the other cases their expected length
15471 * depends on the key params, hence we delegate the padding to the signature verification function.
15472 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15473 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
15474 * @param {module:enums.publicKey} algo - Public key algorithm
15475 * @param {Uint8Array} signature - Data for which the signature was created
15476 * @returns {Promise<Object>} True if signature is valid.
15477 * @async
15478 */
15479function parseSignatureParams(algo, signature) {
15480 let read = 0;
15481 switch (algo) {
15482 // Algorithm-Specific Fields for RSA signatures:
15483 // - MPI of RSA signature value m**d mod n.
15484 case enums.publicKey.rsaEncryptSign:
15485 case enums.publicKey.rsaEncrypt:
15486 case enums.publicKey.rsaSign: {
15487 const s = util.readMPI(signature.subarray(read));
15488 // The signature needs to be the same length as the public key modulo n.
15489 // We pad s on signature verification, where we have access to n.
15490 return { s };
15491 }
15492 // Algorithm-Specific Fields for DSA or ECDSA signatures:
15493 // - MPI of DSA or ECDSA value r.
15494 // - MPI of DSA or ECDSA value s.
15495 case enums.publicKey.dsa:
15496 case enums.publicKey.ecdsa:
15497 {
15498 const r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15499 const s = util.readMPI(signature.subarray(read));
15500 return { r, s };
15501 }
15502 // Algorithm-Specific Fields for EdDSA signatures:
15503 // - MPI of an EC point r.
15504 // - EdDSA value s, in MPI, in the little endian representation
15505 case enums.publicKey.eddsa: {
15506 // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
15507 // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
15508 let r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15509 r = util.leftPad(r, 32);
15510 let s = util.readMPI(signature.subarray(read));
15511 s = util.leftPad(s, 32);
15512 return { r, s };
15513 }
15514 default:
15515 throw new UnsupportedError('Unknown signature algorithm.');
15516 }
15517}
15518
15519/**
15520 * Verifies the signature provided for data using specified algorithms and public key parameters.
15521 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15522 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15523 * for public key and hash algorithms.
15524 * @param {module:enums.publicKey} algo - Public key algorithm
15525 * @param {module:enums.hash} hashAlgo - Hash algorithm
15526 * @param {Object} signature - Named algorithm-specific signature parameters
15527 * @param {Object} publicParams - Algorithm-specific public key parameters
15528 * @param {Uint8Array} data - Data for which the signature was created
15529 * @param {Uint8Array} hashed - The hashed data
15530 * @returns {Promise<Boolean>} True if signature is valid.
15531 * @async
15532 */
15533async function verify$4(algo, hashAlgo, signature, publicParams, data, hashed) {
15534 switch (algo) {
15535 case enums.publicKey.rsaEncryptSign:
15536 case enums.publicKey.rsaEncrypt:
15537 case enums.publicKey.rsaSign: {
15538 const { n, e } = publicParams;
15539 const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
15540 return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);
15541 }
15542 case enums.publicKey.dsa: {
15543 const { g, p, q, y } = publicParams;
15544 const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
15545 return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);
15546 }
15547 case enums.publicKey.ecdsa: {
15548 const { oid, Q } = publicParams;
15549 const curveSize = new publicKey.elliptic.Curve(oid).payloadSize;
15550 // padding needed for webcrypto
15551 const r = util.leftPad(signature.r, curveSize);
15552 const s = util.leftPad(signature.s, curveSize);
15553 return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);
15554 }
15555 case enums.publicKey.eddsa: {
15556 const { oid, Q } = publicParams;
15557 // signature already padded on parsing
15558 return publicKey.elliptic.eddsa.verify(oid, hashAlgo, signature, data, Q, hashed);
15559 }
15560 default:
15561 throw new Error('Unknown signature algorithm.');
15562 }
15563}
15564
15565/**
15566 * Creates a signature on data using specified algorithms and private key parameters.
15567 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15568 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15569 * for public key and hash algorithms.
15570 * @param {module:enums.publicKey} algo - Public key algorithm
15571 * @param {module:enums.hash} hashAlgo - Hash algorithm
15572 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
15573 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
15574 * @param {Uint8Array} data - Data to be signed
15575 * @param {Uint8Array} hashed - The hashed data
15576 * @returns {Promise<Object>} Signature Object containing named signature parameters.
15577 * @async
15578 */
15579async function sign$4(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
15580 if (!publicKeyParams || !privateKeyParams) {
15581 throw new Error('Missing key parameters');
15582 }
15583 switch (algo) {
15584 case enums.publicKey.rsaEncryptSign:
15585 case enums.publicKey.rsaEncrypt:
15586 case enums.publicKey.rsaSign: {
15587 const { n, e } = publicKeyParams;
15588 const { d, p, q, u } = privateKeyParams;
15589 const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);
15590 return { s };
15591 }
15592 case enums.publicKey.dsa: {
15593 const { g, p, q } = publicKeyParams;
15594 const { x } = privateKeyParams;
15595 return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);
15596 }
15597 case enums.publicKey.elgamal: {
15598 throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
15599 }
15600 case enums.publicKey.ecdsa: {
15601 const { oid, Q } = publicKeyParams;
15602 const { d } = privateKeyParams;
15603 return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);
15604 }
15605 case enums.publicKey.eddsa: {
15606 const { oid, Q } = publicKeyParams;
15607 const { seed } = privateKeyParams;
15608 return publicKey.elliptic.eddsa.sign(oid, hashAlgo, data, Q, seed, hashed);
15609 }
15610 default:
15611 throw new Error('Unknown signature algorithm.');
15612 }
15613}
15614
15615var signature = /*#__PURE__*/Object.freeze({
15616 __proto__: null,
15617 parseSignatureParams: parseSignatureParams,
15618 verify: verify$4,
15619 sign: sign$4
15620});
15621
15622/**
15623 * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
15624 * @see module:crypto/crypto
15625 * @see module:crypto/signature
15626 * @see module:crypto/public_key
15627 * @see module:crypto/cipher
15628 * @see module:crypto/random
15629 * @see module:crypto/hash
15630 * @module crypto
15631 * @private
15632 */
15633
15634// TODO move cfb and gcm to cipher
15635const mod = {
15636 /** @see module:crypto/cipher */
15637 cipher: cipher,
15638 /** @see module:crypto/hash */
15639 hash: hash,
15640 /** @see module:crypto/mode */
15641 mode: mode,
15642 /** @see module:crypto/public_key */
15643 publicKey: publicKey,
15644 /** @see module:crypto/signature */
15645 signature: signature,
15646 /** @see module:crypto/random */
15647 random: random,
15648 /** @see module:crypto/pkcs1 */
15649 pkcs1: pkcs1,
15650 /** @see module:crypto/pkcs5 */
15651 pkcs5: pkcs5,
15652 /** @see module:crypto/aes_kw */
15653 aesKW: aesKW
15654};
15655
15656Object.assign(mod, crypto$1);
15657
15658var TYPED_OK = typeof Uint8Array !== "undefined" &&
15659 typeof Uint16Array !== "undefined" &&
15660 typeof Int32Array !== "undefined";
15661
15662
15663// reduce buffer size, avoiding mem copy
15664function shrinkBuf(buf, size) {
15665 if (buf.length === size) {
15666 return buf;
15667 }
15668 if (buf.subarray) {
15669 return buf.subarray(0, size);
15670 }
15671 buf.length = size;
15672 return buf;
15673}
15674
15675
15676const fnTyped = {
15677 arraySet: function (dest, src, src_offs, len, dest_offs) {
15678 if (src.subarray && dest.subarray) {
15679 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
15680 return;
15681 }
15682 // Fallback to ordinary array
15683 for (let i = 0; i < len; i++) {
15684 dest[dest_offs + i] = src[src_offs + i];
15685 }
15686 },
15687 // Join array of chunks to single array.
15688 flattenChunks: function (chunks) {
15689 let i, l, len, pos, chunk;
15690
15691 // calculate data length
15692 len = 0;
15693 for (i = 0, l = chunks.length; i < l; i++) {
15694 len += chunks[i].length;
15695 }
15696
15697 // join chunks
15698 const result = new Uint8Array(len);
15699 pos = 0;
15700 for (i = 0, l = chunks.length; i < l; i++) {
15701 chunk = chunks[i];
15702 result.set(chunk, pos);
15703 pos += chunk.length;
15704 }
15705
15706 return result;
15707 }
15708};
15709
15710const fnUntyped = {
15711 arraySet: function (dest, src, src_offs, len, dest_offs) {
15712 for (let i = 0; i < len; i++) {
15713 dest[dest_offs + i] = src[src_offs + i];
15714 }
15715 },
15716 // Join array of chunks to single array.
15717 flattenChunks: function (chunks) {
15718 return [].concat.apply([], chunks);
15719 }
15720};
15721
15722
15723// Enable/Disable typed arrays use, for testing
15724//
15725
15726let Buf8 = TYPED_OK ? Uint8Array : Array;
15727let Buf16 = TYPED_OK ? Uint16Array : Array;
15728let Buf32 = TYPED_OK ? Int32Array : Array;
15729let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;
15730let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;
15731
15732// (C) 1995-2013 Jean-loup Gailly and Mark Adler
15733// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15734//
15735// This software is provided 'as-is', without any express or implied
15736// warranty. In no event will the authors be held liable for any damages
15737// arising from the use of this software.
15738//
15739// Permission is granted to anyone to use this software for any purpose,
15740// including commercial applications, and to alter it and redistribute it
15741// freely, subject to the following restrictions:
15742//
15743// 1. The origin of this software must not be misrepresented; you must not
15744// claim that you wrote the original software. If you use this software
15745// in a product, an acknowledgment in the product documentation would be
15746// appreciated but is not required.
15747// 2. Altered source versions must be plainly marked as such, and must not be
15748// misrepresented as being the original software.
15749// 3. This notice may not be removed or altered from any source distribution.
15750
15751/* Allowed flush values; see deflate() and inflate() below for details */
15752const Z_NO_FLUSH = 0;
15753const Z_PARTIAL_FLUSH = 1;
15754const Z_SYNC_FLUSH = 2;
15755const Z_FULL_FLUSH = 3;
15756const Z_FINISH = 4;
15757const Z_BLOCK = 5;
15758const Z_TREES = 6;
15759
15760/* Return codes for the compression/decompression functions. Negative values
15761 * are errors, positive values are used for special but normal events.
15762 */
15763const Z_OK = 0;
15764const Z_STREAM_END = 1;
15765const Z_NEED_DICT = 2;
15766const Z_STREAM_ERROR = -2;
15767const Z_DATA_ERROR = -3;
15768//export const Z_MEM_ERROR = -4;
15769const Z_BUF_ERROR = -5;
15770const Z_DEFAULT_COMPRESSION = -1;
15771
15772
15773const Z_FILTERED = 1;
15774const Z_HUFFMAN_ONLY = 2;
15775const Z_RLE = 3;
15776const Z_FIXED = 4;
15777const Z_DEFAULT_STRATEGY = 0;
15778
15779/* Possible values of the data_type field (though see inflate()) */
15780const Z_BINARY = 0;
15781const Z_TEXT = 1;
15782//export const Z_ASCII = 1; // = Z_TEXT (deprecated)
15783const Z_UNKNOWN = 2;
15784
15785/* The deflate compression method */
15786const Z_DEFLATED = 8;
15787//export const Z_NULL = null // Use -1 or null inline, depending on var type
15788
15789/*============================================================================*/
15790
15791
15792function zero$1(buf) {
15793 let len = buf.length; while (--len >= 0) {
15794 buf[len] = 0;
15795 }
15796}
15797
15798// From zutil.h
15799
15800const STORED_BLOCK = 0;
15801const STATIC_TREES = 1;
15802const DYN_TREES = 2;
15803/* The three kinds of block type */
15804
15805const MIN_MATCH = 3;
15806const MAX_MATCH = 258;
15807/* The minimum and maximum match lengths */
15808
15809// From deflate.h
15810/* ===========================================================================
15811 * Internal compression state.
15812 */
15813
15814const LENGTH_CODES = 29;
15815/* number of length codes, not counting the special END_BLOCK code */
15816
15817const LITERALS = 256;
15818/* number of literal bytes 0..255 */
15819
15820const L_CODES = LITERALS + 1 + LENGTH_CODES;
15821/* number of Literal or Length codes, including the END_BLOCK code */
15822
15823const D_CODES = 30;
15824/* number of distance codes */
15825
15826const BL_CODES = 19;
15827/* number of codes used to transfer the bit lengths */
15828
15829const HEAP_SIZE = 2 * L_CODES + 1;
15830/* maximum heap size */
15831
15832const MAX_BITS = 15;
15833/* All codes must not exceed MAX_BITS bits */
15834
15835const Buf_size = 16;
15836/* size of bit buffer in bi_buf */
15837
15838
15839/* ===========================================================================
15840 * Constants
15841 */
15842
15843const MAX_BL_BITS = 7;
15844/* Bit length codes must not exceed MAX_BL_BITS bits */
15845
15846const END_BLOCK = 256;
15847/* end of block literal code */
15848
15849const REP_3_6 = 16;
15850/* repeat previous bit length 3-6 times (2 bits of repeat count) */
15851
15852const REPZ_3_10 = 17;
15853/* repeat a zero length 3-10 times (3 bits of repeat count) */
15854
15855const REPZ_11_138 = 18;
15856/* repeat a zero length 11-138 times (7 bits of repeat count) */
15857
15858/* eslint-disable comma-spacing,array-bracket-spacing */
15859const extra_lbits = /* extra bits for each length code */
15860 [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];
15861
15862const extra_dbits = /* extra bits for each distance code */
15863 [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];
15864
15865const extra_blbits = /* extra bits for each bit length code */
15866 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
15867
15868const bl_order =
15869 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
15870/* eslint-enable comma-spacing,array-bracket-spacing */
15871
15872/* The lengths of the bit length codes are sent in order of decreasing
15873 * probability, to avoid transmitting the lengths for unused bit length codes.
15874 */
15875
15876/* ===========================================================================
15877 * Local data. These are initialized only once.
15878 */
15879
15880// We pre-fill arrays with 0 to avoid uninitialized gaps
15881
15882const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
15883
15884// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
15885const static_ltree = new Array((L_CODES + 2) * 2);
15886zero$1(static_ltree);
15887/* The static literal tree. Since the bit lengths are imposed, there is no
15888 * need for the L_CODES extra codes used during heap construction. However
15889 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
15890 * below).
15891 */
15892
15893const static_dtree = new Array(D_CODES * 2);
15894zero$1(static_dtree);
15895/* The static distance tree. (Actually a trivial tree since all codes use
15896 * 5 bits.)
15897 */
15898
15899const _dist_code = new Array(DIST_CODE_LEN);
15900zero$1(_dist_code);
15901/* Distance codes. The first 256 values correspond to the distances
15902 * 3 .. 258, the last 256 values correspond to the top 8 bits of
15903 * the 15 bit distances.
15904 */
15905
15906const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
15907zero$1(_length_code);
15908/* length code for each normalized match length (0 == MIN_MATCH) */
15909
15910const base_length = new Array(LENGTH_CODES);
15911zero$1(base_length);
15912/* First normalized length for each code (0 = MIN_MATCH) */
15913
15914const base_dist = new Array(D_CODES);
15915zero$1(base_dist);
15916/* First normalized distance for each code (0 = distance of 1) */
15917
15918
15919function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
15920
15921 this.static_tree = static_tree; /* static tree or NULL */
15922 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
15923 this.extra_base = extra_base; /* base index for extra_bits */
15924 this.elems = elems; /* max number of elements in the tree */
15925 this.max_length = max_length; /* max bit length for the codes */
15926
15927 // show if `static_tree` has data or dummy - needed for monomorphic objects
15928 this.has_stree = static_tree && static_tree.length;
15929}
15930
15931
15932let static_l_desc;
15933let static_d_desc;
15934let static_bl_desc;
15935
15936
15937function TreeDesc(dyn_tree, stat_desc) {
15938 this.dyn_tree = dyn_tree; /* the dynamic tree */
15939 this.max_code = 0; /* largest code with non zero frequency */
15940 this.stat_desc = stat_desc; /* the corresponding static tree */
15941}
15942
15943
15944
15945function d_code(dist) {
15946 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
15947}
15948
15949
15950/* ===========================================================================
15951 * Output a short LSB first on the stream.
15952 * IN assertion: there is enough room in pendingBuf.
15953 */
15954function put_short(s, w) {
15955// put_byte(s, (uch)((w) & 0xff));
15956// put_byte(s, (uch)((ush)(w) >> 8));
15957 s.pending_buf[s.pending++] = w & 0xff;
15958 s.pending_buf[s.pending++] = w >>> 8 & 0xff;
15959}
15960
15961
15962/* ===========================================================================
15963 * Send a value on a given number of bits.
15964 * IN assertion: length <= 16 and value fits in length bits.
15965 */
15966function send_bits(s, value, length) {
15967 if (s.bi_valid > Buf_size - length) {
15968 s.bi_buf |= value << s.bi_valid & 0xffff;
15969 put_short(s, s.bi_buf);
15970 s.bi_buf = value >> Buf_size - s.bi_valid;
15971 s.bi_valid += length - Buf_size;
15972 } else {
15973 s.bi_buf |= value << s.bi_valid & 0xffff;
15974 s.bi_valid += length;
15975 }
15976}
15977
15978
15979function send_code(s, c, tree) {
15980 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
15981}
15982
15983
15984/* ===========================================================================
15985 * Reverse the first len bits of a code, using straightforward code (a faster
15986 * method would use a table)
15987 * IN assertion: 1 <= len <= 15
15988 */
15989function bi_reverse(code, len) {
15990 let res = 0;
15991 do {
15992 res |= code & 1;
15993 code >>>= 1;
15994 res <<= 1;
15995 } while (--len > 0);
15996 return res >>> 1;
15997}
15998
15999
16000/* ===========================================================================
16001 * Flush the bit buffer, keeping at most 7 bits in it.
16002 */
16003function bi_flush(s) {
16004 if (s.bi_valid === 16) {
16005 put_short(s, s.bi_buf);
16006 s.bi_buf = 0;
16007 s.bi_valid = 0;
16008
16009 } else if (s.bi_valid >= 8) {
16010 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
16011 s.bi_buf >>= 8;
16012 s.bi_valid -= 8;
16013 }
16014}
16015
16016
16017/* ===========================================================================
16018 * Compute the optimal bit lengths for a tree and update the total bit length
16019 * for the current block.
16020 * IN assertion: the fields freq and dad are set, heap[heap_max] and
16021 * above are the tree nodes sorted by increasing frequency.
16022 * OUT assertions: the field len is set to the optimal bit length, the
16023 * array bl_count contains the frequencies for each bit length.
16024 * The length opt_len is updated; static_len is also updated if stree is
16025 * not null.
16026 */
16027function gen_bitlen(s, desc)
16028// deflate_state *s;
16029// tree_desc *desc; /* the tree descriptor */
16030{
16031 const tree = desc.dyn_tree;
16032 const max_code = desc.max_code;
16033 const stree = desc.stat_desc.static_tree;
16034 const has_stree = desc.stat_desc.has_stree;
16035 const extra = desc.stat_desc.extra_bits;
16036 const base = desc.stat_desc.extra_base;
16037 const max_length = desc.stat_desc.max_length;
16038 let h; /* heap index */
16039 let n, m; /* iterate over the tree elements */
16040 let bits; /* bit length */
16041 let xbits; /* extra bits */
16042 let f; /* frequency */
16043 let overflow = 0; /* number of elements with bit length too large */
16044
16045 for (bits = 0; bits <= MAX_BITS; bits++) {
16046 s.bl_count[bits] = 0;
16047 }
16048
16049 /* In a first pass, compute the optimal bit lengths (which may
16050 * overflow in the case of the bit length tree).
16051 */
16052 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
16053
16054 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
16055 n = s.heap[h];
16056 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
16057 if (bits > max_length) {
16058 bits = max_length;
16059 overflow++;
16060 }
16061 tree[n * 2 + 1]/*.Len*/ = bits;
16062 /* We overwrite tree[n].Dad which is no longer needed */
16063
16064 if (n > max_code) {
16065 continue;
16066 } /* not a leaf node */
16067
16068 s.bl_count[bits]++;
16069 xbits = 0;
16070 if (n >= base) {
16071 xbits = extra[n - base];
16072 }
16073 f = tree[n * 2]/*.Freq*/;
16074 s.opt_len += f * (bits + xbits);
16075 if (has_stree) {
16076 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
16077 }
16078 }
16079 if (overflow === 0) {
16080 return;
16081 }
16082
16083 // Trace((stderr,"\nbit length overflow\n"));
16084 /* This happens for example on obj2 and pic of the Calgary corpus */
16085
16086 /* Find the first bit length which could increase: */
16087 do {
16088 bits = max_length - 1;
16089 while (s.bl_count[bits] === 0) {
16090 bits--;
16091 }
16092 s.bl_count[bits]--; /* move one leaf down the tree */
16093 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
16094 s.bl_count[max_length]--;
16095 /* The brother of the overflow item also moves one step up,
16096 * but this does not affect bl_count[max_length]
16097 */
16098 overflow -= 2;
16099 } while (overflow > 0);
16100
16101 /* Now recompute all bit lengths, scanning in increasing frequency.
16102 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
16103 * lengths instead of fixing only the wrong ones. This idea is taken
16104 * from 'ar' written by Haruhiko Okumura.)
16105 */
16106 for (bits = max_length; bits !== 0; bits--) {
16107 n = s.bl_count[bits];
16108 while (n !== 0) {
16109 m = s.heap[--h];
16110 if (m > max_code) {
16111 continue;
16112 }
16113 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
16114 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
16115 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
16116 tree[m * 2 + 1]/*.Len*/ = bits;
16117 }
16118 n--;
16119 }
16120 }
16121}
16122
16123
16124/* ===========================================================================
16125 * Generate the codes for a given tree and bit counts (which need not be
16126 * optimal).
16127 * IN assertion: the array bl_count contains the bit length statistics for
16128 * the given tree and the field len is set for all tree elements.
16129 * OUT assertion: the field code is set for all tree elements of non
16130 * zero code length.
16131 */
16132function gen_codes(tree, max_code, bl_count)
16133// ct_data *tree; /* the tree to decorate */
16134// int max_code; /* largest code with non zero frequency */
16135// ushf *bl_count; /* number of codes at each bit length */
16136{
16137 const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
16138 let code = 0; /* running code value */
16139 let bits; /* bit index */
16140 let n; /* code index */
16141
16142 /* The distribution counts are first used to generate the code values
16143 * without bit reversal.
16144 */
16145 for (bits = 1; bits <= MAX_BITS; bits++) {
16146 next_code[bits] = code = code + bl_count[bits - 1] << 1;
16147 }
16148 /* Check that the bit counts in bl_count are consistent. The last code
16149 * must be all ones.
16150 */
16151 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
16152 // "inconsistent bit counts");
16153 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
16154
16155 for (n = 0; n <= max_code; n++) {
16156 const len = tree[n * 2 + 1]/*.Len*/;
16157 if (len === 0) {
16158 continue;
16159 }
16160 /* Now reverse the bits */
16161 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
16162
16163 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
16164 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
16165 }
16166}
16167
16168
16169/* ===========================================================================
16170 * Initialize the various 'constant' tables.
16171 */
16172function tr_static_init() {
16173 let n; /* iterates over tree elements */
16174 let bits; /* bit counter */
16175 let length; /* length value */
16176 let code; /* code value */
16177 let dist; /* distance index */
16178 const bl_count = new Array(MAX_BITS + 1);
16179 /* number of codes at each bit length for an optimal tree */
16180
16181 // do check in _tr_init()
16182 //if (static_init_done) return;
16183
16184 /* For some embedded targets, global variables are not initialized: */
16185 /*#ifdef NO_INIT_GLOBAL_POINTERS
16186 static_l_desc.static_tree = static_ltree;
16187 static_l_desc.extra_bits = extra_lbits;
16188 static_d_desc.static_tree = static_dtree;
16189 static_d_desc.extra_bits = extra_dbits;
16190 static_bl_desc.extra_bits = extra_blbits;
16191#endif*/
16192
16193 /* Initialize the mapping length (0..255) -> length code (0..28) */
16194 length = 0;
16195 for (code = 0; code < LENGTH_CODES - 1; code++) {
16196 base_length[code] = length;
16197 for (n = 0; n < 1 << extra_lbits[code]; n++) {
16198 _length_code[length++] = code;
16199 }
16200 }
16201 //Assert (length == 256, "tr_static_init: length != 256");
16202 /* Note that the length 255 (match length 258) can be represented
16203 * in two different ways: code 284 + 5 bits or code 285, so we
16204 * overwrite length_code[255] to use the best encoding:
16205 */
16206 _length_code[length - 1] = code;
16207
16208 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
16209 dist = 0;
16210 for (code = 0; code < 16; code++) {
16211 base_dist[code] = dist;
16212 for (n = 0; n < 1 << extra_dbits[code]; n++) {
16213 _dist_code[dist++] = code;
16214 }
16215 }
16216 //Assert (dist == 256, "tr_static_init: dist != 256");
16217 dist >>= 7; /* from now on, all distances are divided by 128 */
16218 for (; code < D_CODES; code++) {
16219 base_dist[code] = dist << 7;
16220 for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
16221 _dist_code[256 + dist++] = code;
16222 }
16223 }
16224 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
16225
16226 /* Construct the codes of the static literal tree */
16227 for (bits = 0; bits <= MAX_BITS; bits++) {
16228 bl_count[bits] = 0;
16229 }
16230
16231 n = 0;
16232 while (n <= 143) {
16233 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16234 n++;
16235 bl_count[8]++;
16236 }
16237 while (n <= 255) {
16238 static_ltree[n * 2 + 1]/*.Len*/ = 9;
16239 n++;
16240 bl_count[9]++;
16241 }
16242 while (n <= 279) {
16243 static_ltree[n * 2 + 1]/*.Len*/ = 7;
16244 n++;
16245 bl_count[7]++;
16246 }
16247 while (n <= 287) {
16248 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16249 n++;
16250 bl_count[8]++;
16251 }
16252 /* Codes 286 and 287 do not exist, but we must include them in the
16253 * tree construction to get a canonical Huffman tree (longest code
16254 * all ones)
16255 */
16256 gen_codes(static_ltree, L_CODES + 1, bl_count);
16257
16258 /* The static distance tree is trivial: */
16259 for (n = 0; n < D_CODES; n++) {
16260 static_dtree[n * 2 + 1]/*.Len*/ = 5;
16261 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
16262 }
16263
16264 // Now data ready and we can init static trees
16265 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
16266 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
16267 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
16268
16269 //static_init_done = true;
16270}
16271
16272
16273/* ===========================================================================
16274 * Initialize a new block.
16275 */
16276function init_block(s) {
16277 let n; /* iterates over tree elements */
16278
16279 /* Initialize the trees. */
16280 for (n = 0; n < L_CODES; n++) {
16281 s.dyn_ltree[n * 2]/*.Freq*/ = 0;
16282 }
16283 for (n = 0; n < D_CODES; n++) {
16284 s.dyn_dtree[n * 2]/*.Freq*/ = 0;
16285 }
16286 for (n = 0; n < BL_CODES; n++) {
16287 s.bl_tree[n * 2]/*.Freq*/ = 0;
16288 }
16289
16290 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
16291 s.opt_len = s.static_len = 0;
16292 s.last_lit = s.matches = 0;
16293}
16294
16295
16296/* ===========================================================================
16297 * Flush the bit buffer and align the output on a byte boundary
16298 */
16299function bi_windup(s) {
16300 if (s.bi_valid > 8) {
16301 put_short(s, s.bi_buf);
16302 } else if (s.bi_valid > 0) {
16303 //put_byte(s, (Byte)s->bi_buf);
16304 s.pending_buf[s.pending++] = s.bi_buf;
16305 }
16306 s.bi_buf = 0;
16307 s.bi_valid = 0;
16308}
16309
16310/* ===========================================================================
16311 * Copy a stored block, storing first the length and its
16312 * one's complement if requested.
16313 */
16314function copy_block(s, buf, len, header)
16315//DeflateState *s;
16316//charf *buf; /* the input data */
16317//unsigned len; /* its length */
16318//int header; /* true if block header must be written */
16319{
16320 bi_windup(s); /* align on byte boundary */
16321
16322 if (header) {
16323 put_short(s, len);
16324 put_short(s, ~len);
16325 }
16326 // while (len--) {
16327 // put_byte(s, *buf++);
16328 // }
16329 arraySet(s.pending_buf, s.window, buf, len, s.pending);
16330 s.pending += len;
16331}
16332
16333/* ===========================================================================
16334 * Compares to subtrees, using the tree depth as tie breaker when
16335 * the subtrees have equal frequency. This minimizes the worst case length.
16336 */
16337function smaller(tree, n, m, depth) {
16338 const _n2 = n * 2;
16339 const _m2 = m * 2;
16340 return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
16341 tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];
16342}
16343
16344/* ===========================================================================
16345 * Restore the heap property by moving down the tree starting at node k,
16346 * exchanging a node with the smallest of its two sons if necessary, stopping
16347 * when the heap property is re-established (each father smaller than its
16348 * two sons).
16349 */
16350function pqdownheap(s, tree, k)
16351// deflate_state *s;
16352// ct_data *tree; /* the tree to restore */
16353// int k; /* node to move down */
16354{
16355 const v = s.heap[k];
16356 let j = k << 1; /* left son of k */
16357 while (j <= s.heap_len) {
16358 /* Set j to the smallest of the two sons: */
16359 if (j < s.heap_len &&
16360 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
16361 j++;
16362 }
16363 /* Exit if v is smaller than both sons */
16364 if (smaller(tree, v, s.heap[j], s.depth)) {
16365 break;
16366 }
16367
16368 /* Exchange v with the smallest son */
16369 s.heap[k] = s.heap[j];
16370 k = j;
16371
16372 /* And continue down the tree, setting j to the left son of k */
16373 j <<= 1;
16374 }
16375 s.heap[k] = v;
16376}
16377
16378
16379// inlined manually
16380// var SMALLEST = 1;
16381
16382/* ===========================================================================
16383 * Send the block data compressed using the given Huffman trees
16384 */
16385function compress_block(s, ltree, dtree)
16386// deflate_state *s;
16387// const ct_data *ltree; /* literal tree */
16388// const ct_data *dtree; /* distance tree */
16389{
16390 let dist; /* distance of matched string */
16391 let lc; /* match length or unmatched char (if dist == 0) */
16392 let lx = 0; /* running index in l_buf */
16393 let code; /* the code to send */
16394 let extra; /* number of extra bits to send */
16395
16396 if (s.last_lit !== 0) {
16397 do {
16398 dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
16399 lc = s.pending_buf[s.l_buf + lx];
16400 lx++;
16401
16402 if (dist === 0) {
16403 send_code(s, lc, ltree); /* send a literal byte */
16404 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
16405 } else {
16406 /* Here, lc is the match length - MIN_MATCH */
16407 code = _length_code[lc];
16408 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
16409 extra = extra_lbits[code];
16410 if (extra !== 0) {
16411 lc -= base_length[code];
16412 send_bits(s, lc, extra); /* send the extra length bits */
16413 }
16414 dist--; /* dist is now the match distance - 1 */
16415 code = d_code(dist);
16416 //Assert (code < D_CODES, "bad d_code");
16417
16418 send_code(s, code, dtree); /* send the distance code */
16419 extra = extra_dbits[code];
16420 if (extra !== 0) {
16421 dist -= base_dist[code];
16422 send_bits(s, dist, extra); /* send the extra distance bits */
16423 }
16424 } /* literal or match pair ? */
16425
16426 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
16427 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
16428 // "pendingBuf overflow");
16429
16430 } while (lx < s.last_lit);
16431 }
16432
16433 send_code(s, END_BLOCK, ltree);
16434}
16435
16436
16437/* ===========================================================================
16438 * Construct one Huffman tree and assigns the code bit strings and lengths.
16439 * Update the total bit length for the current block.
16440 * IN assertion: the field freq is set for all tree elements.
16441 * OUT assertions: the fields len and code are set to the optimal bit length
16442 * and corresponding code. The length opt_len is updated; static_len is
16443 * also updated if stree is not null. The field max_code is set.
16444 */
16445function build_tree(s, desc)
16446// deflate_state *s;
16447// tree_desc *desc; /* the tree descriptor */
16448{
16449 const tree = desc.dyn_tree;
16450 const stree = desc.stat_desc.static_tree;
16451 const has_stree = desc.stat_desc.has_stree;
16452 const elems = desc.stat_desc.elems;
16453 let n, m; /* iterate over heap elements */
16454 let max_code = -1; /* largest code with non zero frequency */
16455 let node; /* new node being created */
16456
16457 /* Construct the initial heap, with least frequent element in
16458 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
16459 * heap[0] is not used.
16460 */
16461 s.heap_len = 0;
16462 s.heap_max = HEAP_SIZE;
16463
16464 for (n = 0; n < elems; n++) {
16465 if (tree[n * 2]/*.Freq*/ !== 0) {
16466 s.heap[++s.heap_len] = max_code = n;
16467 s.depth[n] = 0;
16468
16469 } else {
16470 tree[n * 2 + 1]/*.Len*/ = 0;
16471 }
16472 }
16473
16474 /* The pkzip format requires that at least one distance code exists,
16475 * and that at least one bit should be sent even if there is only one
16476 * possible code. So to avoid special checks later on we force at least
16477 * two codes of non zero frequency.
16478 */
16479 while (s.heap_len < 2) {
16480 node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
16481 tree[node * 2]/*.Freq*/ = 1;
16482 s.depth[node] = 0;
16483 s.opt_len--;
16484
16485 if (has_stree) {
16486 s.static_len -= stree[node * 2 + 1]/*.Len*/;
16487 }
16488 /* node is 0 or 1 so it does not have extra bits */
16489 }
16490 desc.max_code = max_code;
16491
16492 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
16493 * establish sub-heaps of increasing lengths:
16494 */
16495 for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {
16496 pqdownheap(s, tree, n);
16497 }
16498
16499 /* Construct the Huffman tree by repeatedly combining the least two
16500 * frequent nodes.
16501 */
16502 node = elems; /* next internal node of the tree */
16503 do {
16504 //pqremove(s, tree, n); /* n = node of least frequency */
16505 /*** pqremove ***/
16506 n = s.heap[1/*SMALLEST*/];
16507 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
16508 pqdownheap(s, tree, 1/*SMALLEST*/);
16509 /***/
16510
16511 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
16512
16513 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
16514 s.heap[--s.heap_max] = m;
16515
16516 /* Create a new node father of n and m */
16517 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
16518 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
16519 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
16520
16521 /* and insert the new node in the heap */
16522 s.heap[1/*SMALLEST*/] = node++;
16523 pqdownheap(s, tree, 1/*SMALLEST*/);
16524
16525 } while (s.heap_len >= 2);
16526
16527 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
16528
16529 /* At this point, the fields freq and dad are set. We can now
16530 * generate the bit lengths.
16531 */
16532 gen_bitlen(s, desc);
16533
16534 /* The field len is now set, we can generate the bit codes */
16535 gen_codes(tree, max_code, s.bl_count);
16536}
16537
16538
16539/* ===========================================================================
16540 * Scan a literal or distance tree to determine the frequencies of the codes
16541 * in the bit length tree.
16542 */
16543function scan_tree(s, tree, max_code)
16544// deflate_state *s;
16545// ct_data *tree; /* the tree to be scanned */
16546// int max_code; /* and its largest code of non zero frequency */
16547{
16548 let n; /* iterates over all tree elements */
16549 let prevlen = -1; /* last emitted length */
16550 let curlen; /* length of current code */
16551
16552 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16553
16554 let count = 0; /* repeat count of the current code */
16555 let max_count = 7; /* max repeat count */
16556 let min_count = 4; /* min repeat count */
16557
16558 if (nextlen === 0) {
16559 max_count = 138;
16560 min_count = 3;
16561 }
16562 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
16563
16564 for (n = 0; n <= max_code; n++) {
16565 curlen = nextlen;
16566 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16567
16568 if (++count < max_count && curlen === nextlen) {
16569 continue;
16570
16571 } else if (count < min_count) {
16572 s.bl_tree[curlen * 2]/*.Freq*/ += count;
16573
16574 } else if (curlen !== 0) {
16575
16576 if (curlen !== prevlen) {
16577 s.bl_tree[curlen * 2]/*.Freq*/++;
16578 }
16579 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
16580
16581 } else if (count <= 10) {
16582 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
16583
16584 } else {
16585 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
16586 }
16587
16588 count = 0;
16589 prevlen = curlen;
16590
16591 if (nextlen === 0) {
16592 max_count = 138;
16593 min_count = 3;
16594
16595 } else if (curlen === nextlen) {
16596 max_count = 6;
16597 min_count = 3;
16598
16599 } else {
16600 max_count = 7;
16601 min_count = 4;
16602 }
16603 }
16604}
16605
16606
16607/* ===========================================================================
16608 * Send a literal or distance tree in compressed form, using the codes in
16609 * bl_tree.
16610 */
16611function send_tree(s, tree, max_code)
16612// deflate_state *s;
16613// ct_data *tree; /* the tree to be scanned */
16614// int max_code; /* and its largest code of non zero frequency */
16615{
16616 let n; /* iterates over all tree elements */
16617 let prevlen = -1; /* last emitted length */
16618 let curlen; /* length of current code */
16619
16620 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16621
16622 let count = 0; /* repeat count of the current code */
16623 let max_count = 7; /* max repeat count */
16624 let min_count = 4; /* min repeat count */
16625
16626 /* tree[max_code+1].Len = -1; */ /* guard already set */
16627 if (nextlen === 0) {
16628 max_count = 138;
16629 min_count = 3;
16630 }
16631
16632 for (n = 0; n <= max_code; n++) {
16633 curlen = nextlen;
16634 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16635
16636 if (++count < max_count && curlen === nextlen) {
16637 continue;
16638
16639 } else if (count < min_count) {
16640 do {
16641 send_code(s, curlen, s.bl_tree);
16642 } while (--count !== 0);
16643
16644 } else if (curlen !== 0) {
16645 if (curlen !== prevlen) {
16646 send_code(s, curlen, s.bl_tree);
16647 count--;
16648 }
16649 //Assert(count >= 3 && count <= 6, " 3_6?");
16650 send_code(s, REP_3_6, s.bl_tree);
16651 send_bits(s, count - 3, 2);
16652
16653 } else if (count <= 10) {
16654 send_code(s, REPZ_3_10, s.bl_tree);
16655 send_bits(s, count - 3, 3);
16656
16657 } else {
16658 send_code(s, REPZ_11_138, s.bl_tree);
16659 send_bits(s, count - 11, 7);
16660 }
16661
16662 count = 0;
16663 prevlen = curlen;
16664 if (nextlen === 0) {
16665 max_count = 138;
16666 min_count = 3;
16667
16668 } else if (curlen === nextlen) {
16669 max_count = 6;
16670 min_count = 3;
16671
16672 } else {
16673 max_count = 7;
16674 min_count = 4;
16675 }
16676 }
16677}
16678
16679
16680/* ===========================================================================
16681 * Construct the Huffman tree for the bit lengths and return the index in
16682 * bl_order of the last bit length code to send.
16683 */
16684function build_bl_tree(s) {
16685 let max_blindex; /* index of last bit length code of non zero freq */
16686
16687 /* Determine the bit length frequencies for literal and distance trees */
16688 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
16689 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
16690
16691 /* Build the bit length tree: */
16692 build_tree(s, s.bl_desc);
16693 /* opt_len now includes the length of the tree representations, except
16694 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
16695 */
16696
16697 /* Determine the number of bit length codes to send. The pkzip format
16698 * requires that at least 4 bit length codes be sent. (appnote.txt says
16699 * 3 but the actual value used is 4.)
16700 */
16701 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
16702 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
16703 break;
16704 }
16705 }
16706 /* Update opt_len to include the bit length tree and counts */
16707 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
16708 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
16709 // s->opt_len, s->static_len));
16710
16711 return max_blindex;
16712}
16713
16714
16715/* ===========================================================================
16716 * Send the header for a block using dynamic Huffman trees: the counts, the
16717 * lengths of the bit length codes, the literal tree and the distance tree.
16718 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
16719 */
16720function send_all_trees(s, lcodes, dcodes, blcodes)
16721// deflate_state *s;
16722// int lcodes, dcodes, blcodes; /* number of codes for each tree */
16723{
16724 let rank; /* index in bl_order */
16725
16726 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
16727 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
16728 // "too many codes");
16729 //Tracev((stderr, "\nbl counts: "));
16730 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
16731 send_bits(s, dcodes - 1, 5);
16732 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
16733 for (rank = 0; rank < blcodes; rank++) {
16734 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
16735 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
16736 }
16737 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
16738
16739 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
16740 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
16741
16742 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
16743 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
16744}
16745
16746
16747/* ===========================================================================
16748 * Check if the data type is TEXT or BINARY, using the following algorithm:
16749 * - TEXT if the two conditions below are satisfied:
16750 * a) There are no non-portable control characters belonging to the
16751 * "black list" (0..6, 14..25, 28..31).
16752 * b) There is at least one printable character belonging to the
16753 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
16754 * - BINARY otherwise.
16755 * - The following partially-portable control characters form a
16756 * "gray list" that is ignored in this detection algorithm:
16757 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
16758 * IN assertion: the fields Freq of dyn_ltree are set.
16759 */
16760function detect_data_type(s) {
16761 /* black_mask is the bit mask of black-listed bytes
16762 * set bits 0..6, 14..25, and 28..31
16763 * 0xf3ffc07f = binary 11110011111111111100000001111111
16764 */
16765 let black_mask = 0xf3ffc07f;
16766 let n;
16767
16768 /* Check for non-textual ("black-listed") bytes. */
16769 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
16770 if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16771 return Z_BINARY;
16772 }
16773 }
16774
16775 /* Check for textual ("white-listed") bytes. */
16776 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
16777 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
16778 return Z_TEXT;
16779 }
16780 for (n = 32; n < LITERALS; n++) {
16781 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16782 return Z_TEXT;
16783 }
16784 }
16785
16786 /* There are no "black-listed" or "white-listed" bytes:
16787 * this stream either is empty or has tolerated ("gray-listed") bytes only.
16788 */
16789 return Z_BINARY;
16790}
16791
16792
16793let static_init_done = false;
16794
16795/* ===========================================================================
16796 * Initialize the tree data structures for a new zlib stream.
16797 */
16798function _tr_init(s) {
16799
16800 if (!static_init_done) {
16801 tr_static_init();
16802 static_init_done = true;
16803 }
16804
16805 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
16806 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
16807 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
16808
16809 s.bi_buf = 0;
16810 s.bi_valid = 0;
16811
16812 /* Initialize the first block of the first file: */
16813 init_block(s);
16814}
16815
16816
16817/* ===========================================================================
16818 * Send a stored block
16819 */
16820function _tr_stored_block(s, buf, stored_len, last)
16821//DeflateState *s;
16822//charf *buf; /* input block */
16823//ulg stored_len; /* length of input block */
16824//int last; /* one if this is the last block for a file */
16825{
16826 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
16827 copy_block(s, buf, stored_len, true); /* with header */
16828}
16829
16830
16831/* ===========================================================================
16832 * Send one empty static block to give enough lookahead for inflate.
16833 * This takes 10 bits, of which 7 may remain in the bit buffer.
16834 */
16835function _tr_align(s) {
16836 send_bits(s, STATIC_TREES << 1, 3);
16837 send_code(s, END_BLOCK, static_ltree);
16838 bi_flush(s);
16839}
16840
16841
16842/* ===========================================================================
16843 * Determine the best encoding for the current block: dynamic trees, static
16844 * trees or store, and output the encoded block to the zip file.
16845 */
16846function _tr_flush_block(s, buf, stored_len, last)
16847//DeflateState *s;
16848//charf *buf; /* input block, or NULL if too old */
16849//ulg stored_len; /* length of input block */
16850//int last; /* one if this is the last block for a file */
16851{
16852 let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
16853 let max_blindex = 0; /* index of last bit length code of non zero freq */
16854
16855 /* Build the Huffman trees unless a stored block is forced */
16856 if (s.level > 0) {
16857
16858 /* Check if the file is binary or text */
16859 if (s.strm.data_type === Z_UNKNOWN) {
16860 s.strm.data_type = detect_data_type(s);
16861 }
16862
16863 /* Construct the literal and distance trees */
16864 build_tree(s, s.l_desc);
16865 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
16866 // s->static_len));
16867
16868 build_tree(s, s.d_desc);
16869 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
16870 // s->static_len));
16871 /* At this point, opt_len and static_len are the total bit lengths of
16872 * the compressed block data, excluding the tree representations.
16873 */
16874
16875 /* Build the bit length tree for the above two trees, and get the index
16876 * in bl_order of the last bit length code to send.
16877 */
16878 max_blindex = build_bl_tree(s);
16879
16880 /* Determine the best encoding. Compute the block lengths in bytes. */
16881 opt_lenb = s.opt_len + 3 + 7 >>> 3;
16882 static_lenb = s.static_len + 3 + 7 >>> 3;
16883
16884 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
16885 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
16886 // s->last_lit));
16887
16888 if (static_lenb <= opt_lenb) {
16889 opt_lenb = static_lenb;
16890 }
16891
16892 } else {
16893 // Assert(buf != (char*)0, "lost buf");
16894 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
16895 }
16896
16897 if (stored_len + 4 <= opt_lenb && buf !== -1) {
16898 /* 4: two words for the lengths */
16899
16900 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
16901 * Otherwise we can't have processed more than WSIZE input bytes since
16902 * the last block flush, because compression would have been
16903 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
16904 * transform a block into a stored block.
16905 */
16906 _tr_stored_block(s, buf, stored_len, last);
16907
16908 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
16909
16910 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
16911 compress_block(s, static_ltree, static_dtree);
16912
16913 } else {
16914 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
16915 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
16916 compress_block(s, s.dyn_ltree, s.dyn_dtree);
16917 }
16918 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
16919 /* The above check is made mod 2^32, for files larger than 512 MB
16920 * and uLong implemented on 32 bits.
16921 */
16922 init_block(s);
16923
16924 if (last) {
16925 bi_windup(s);
16926 }
16927 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
16928 // s->compressed_len-7*last));
16929}
16930
16931/* ===========================================================================
16932 * Save the match info and tally the frequency counts. Return true if
16933 * the current block must be flushed.
16934 */
16935function _tr_tally(s, dist, lc)
16936// deflate_state *s;
16937// unsigned dist; /* distance of matched string */
16938// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
16939{
16940 //var out_length, in_length, dcode;
16941
16942 s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
16943 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
16944
16945 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
16946 s.last_lit++;
16947
16948 if (dist === 0) {
16949 /* lc is the unmatched char */
16950 s.dyn_ltree[lc * 2]/*.Freq*/++;
16951 } else {
16952 s.matches++;
16953 /* Here, lc is the match length - MIN_MATCH */
16954 dist--; /* dist = match distance - 1 */
16955 //Assert((ush)dist < (ush)MAX_DIST(s) &&
16956 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
16957 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
16958
16959 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
16960 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
16961 }
16962
16963 // (!) This block is disabled in zlib defaults,
16964 // don't enable it for binary compatibility
16965
16966 //#ifdef TRUNCATE_BLOCK
16967 // /* Try to guess if it is profitable to stop the current block here */
16968 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
16969 // /* Compute an upper bound for the compressed length */
16970 // out_length = s.last_lit*8;
16971 // in_length = s.strstart - s.block_start;
16972 //
16973 // for (dcode = 0; dcode < D_CODES; dcode++) {
16974 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
16975 // }
16976 // out_length >>>= 3;
16977 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
16978 // // s->last_lit, in_length, out_length,
16979 // // 100L - out_length*100L/in_length));
16980 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
16981 // return true;
16982 // }
16983 // }
16984 //#endif
16985
16986 return s.last_lit === s.lit_bufsize - 1;
16987 /* We avoid equality with lit_bufsize because of wraparound at 64K
16988 * on 16 bit machines and because stored blocks are restricted to
16989 * 64K-1 bytes.
16990 */
16991}
16992
16993// Note: adler32 takes 12% for level 0 and 2% for level 6.
16994// It isn't worth it to make additional optimizations as in original.
16995// Small size is preferable.
16996
16997// (C) 1995-2013 Jean-loup Gailly and Mark Adler
16998// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16999//
17000// This software is provided 'as-is', without any express or implied
17001// warranty. In no event will the authors be held liable for any damages
17002// arising from the use of this software.
17003//
17004// Permission is granted to anyone to use this software for any purpose,
17005// including commercial applications, and to alter it and redistribute it
17006// freely, subject to the following restrictions:
17007//
17008// 1. The origin of this software must not be misrepresented; you must not
17009// claim that you wrote the original software. If you use this software
17010// in a product, an acknowledgment in the product documentation would be
17011// appreciated but is not required.
17012// 2. Altered source versions must be plainly marked as such, and must not be
17013// misrepresented as being the original software.
17014// 3. This notice may not be removed or altered from any source distribution.
17015
17016function adler32(adler, buf, len, pos) {
17017 let s1 = adler & 0xffff |0,
17018 s2 = adler >>> 16 & 0xffff |0,
17019 n = 0;
17020
17021 while (len !== 0) {
17022 // Set limit ~ twice less than 5552, to keep
17023 // s2 in 31-bits, because we force signed ints.
17024 // in other case %= will fail.
17025 n = len > 2000 ? 2000 : len;
17026 len -= n;
17027
17028 do {
17029 s1 = s1 + buf[pos++] |0;
17030 s2 = s2 + s1 |0;
17031 } while (--n);
17032
17033 s1 %= 65521;
17034 s2 %= 65521;
17035 }
17036
17037 return s1 | s2 << 16 |0;
17038}
17039
17040// Note: we can't get significant speed boost here.
17041// So write code to minimize size - no pregenerated tables
17042// and array tools dependencies.
17043
17044// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17045// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17046//
17047// This software is provided 'as-is', without any express or implied
17048// warranty. In no event will the authors be held liable for any damages
17049// arising from the use of this software.
17050//
17051// Permission is granted to anyone to use this software for any purpose,
17052// including commercial applications, and to alter it and redistribute it
17053// freely, subject to the following restrictions:
17054//
17055// 1. The origin of this software must not be misrepresented; you must not
17056// claim that you wrote the original software. If you use this software
17057// in a product, an acknowledgment in the product documentation would be
17058// appreciated but is not required.
17059// 2. Altered source versions must be plainly marked as such, and must not be
17060// misrepresented as being the original software.
17061// 3. This notice may not be removed or altered from any source distribution.
17062
17063// Use ordinary array, since untyped makes no boost here
17064function makeTable() {
17065 let c;
17066 const table = [];
17067
17068 for (let n = 0; n < 256; n++) {
17069 c = n;
17070 for (let k = 0; k < 8; k++) {
17071 c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
17072 }
17073 table[n] = c;
17074 }
17075
17076 return table;
17077}
17078
17079// Create table on load. Just 255 signed longs. Not a problem.
17080const crcTable = makeTable();
17081
17082
17083function crc32(crc, buf, len, pos) {
17084 const t = crcTable,
17085 end = pos + len;
17086
17087 crc ^= -1;
17088
17089 for (let i = pos; i < end; i++) {
17090 crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
17091 }
17092
17093 return crc ^ -1; // >>> 0;
17094}
17095
17096// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17097// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17098//
17099// This software is provided 'as-is', without any express or implied
17100// warranty. In no event will the authors be held liable for any damages
17101// arising from the use of this software.
17102//
17103// Permission is granted to anyone to use this software for any purpose,
17104// including commercial applications, and to alter it and redistribute it
17105// freely, subject to the following restrictions:
17106//
17107// 1. The origin of this software must not be misrepresented; you must not
17108// claim that you wrote the original software. If you use this software
17109// in a product, an acknowledgment in the product documentation would be
17110// appreciated but is not required.
17111// 2. Altered source versions must be plainly marked as such, and must not be
17112// misrepresented as being the original software.
17113// 3. This notice may not be removed or altered from any source distribution.
17114
17115var msg = {
17116 2: "need dictionary", /* Z_NEED_DICT 2 */
17117 1: "stream end", /* Z_STREAM_END 1 */
17118 0: "", /* Z_OK 0 */
17119 "-1": "file error", /* Z_ERRNO (-1) */
17120 "-2": "stream error", /* Z_STREAM_ERROR (-2) */
17121 "-3": "data error", /* Z_DATA_ERROR (-3) */
17122 "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */
17123 "-5": "buffer error", /* Z_BUF_ERROR (-5) */
17124 "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */
17125};
17126
17127/*============================================================================*/
17128
17129
17130const MAX_MEM_LEVEL = 9;
17131
17132
17133const LENGTH_CODES$1 = 29;
17134/* number of length codes, not counting the special END_BLOCK code */
17135const LITERALS$1 = 256;
17136/* number of literal bytes 0..255 */
17137const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
17138/* number of Literal or Length codes, including the END_BLOCK code */
17139const D_CODES$1 = 30;
17140/* number of distance codes */
17141const BL_CODES$1 = 19;
17142/* number of codes used to transfer the bit lengths */
17143const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
17144/* maximum heap size */
17145const MAX_BITS$1 = 15;
17146/* All codes must not exceed MAX_BITS bits */
17147
17148const MIN_MATCH$1 = 3;
17149const MAX_MATCH$1 = 258;
17150const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
17151
17152const PRESET_DICT = 0x20;
17153
17154const INIT_STATE = 42;
17155const EXTRA_STATE = 69;
17156const NAME_STATE = 73;
17157const COMMENT_STATE = 91;
17158const HCRC_STATE = 103;
17159const BUSY_STATE = 113;
17160const FINISH_STATE = 666;
17161
17162const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
17163const BS_BLOCK_DONE = 2; /* block flush performed */
17164const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
17165const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
17166
17167const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
17168
17169function err(strm, errorCode) {
17170 strm.msg = msg[errorCode];
17171 return errorCode;
17172}
17173
17174function rank(f) {
17175 return ((f) << 1) - ((f) > 4 ? 9 : 0);
17176}
17177
17178function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
17179
17180
17181/* =========================================================================
17182 * Flush as much pending output as possible. All deflate() output goes
17183 * through this function so some applications may wish to modify it
17184 * to avoid allocating a large strm->output buffer and copying into it.
17185 * (See also read_buf()).
17186 */
17187function flush_pending(strm) {
17188 const s = strm.state;
17189
17190 //_tr_flush_bits(s);
17191 let len = s.pending;
17192 if (len > strm.avail_out) {
17193 len = strm.avail_out;
17194 }
17195 if (len === 0) { return; }
17196
17197 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
17198 strm.next_out += len;
17199 s.pending_out += len;
17200 strm.total_out += len;
17201 strm.avail_out -= len;
17202 s.pending -= len;
17203 if (s.pending === 0) {
17204 s.pending_out = 0;
17205 }
17206}
17207
17208
17209function flush_block_only(s, last) {
17210 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
17211 s.block_start = s.strstart;
17212 flush_pending(s.strm);
17213}
17214
17215
17216function put_byte(s, b) {
17217 s.pending_buf[s.pending++] = b;
17218}
17219
17220
17221/* =========================================================================
17222 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
17223 * IN assertion: the stream state is correct and there is enough room in
17224 * pending_buf.
17225 */
17226function putShortMSB(s, b) {
17227 // put_byte(s, (Byte)(b >> 8));
17228 // put_byte(s, (Byte)(b & 0xff));
17229 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
17230 s.pending_buf[s.pending++] = b & 0xff;
17231}
17232
17233
17234/* ===========================================================================
17235 * Read a new buffer from the current input stream, update the adler32
17236 * and total number of bytes read. All deflate() input goes through
17237 * this function so some applications may wish to modify it to avoid
17238 * allocating a large strm->input buffer and copying from it.
17239 * (See also flush_pending()).
17240 */
17241function read_buf(strm, buf, start, size) {
17242 let len = strm.avail_in;
17243
17244 if (len > size) { len = size; }
17245 if (len === 0) { return 0; }
17246
17247 strm.avail_in -= len;
17248
17249 // zmemcpy(buf, strm->next_in, len);
17250 arraySet(buf, strm.input, strm.next_in, len, start);
17251 if (strm.state.wrap === 1) {
17252 strm.adler = adler32(strm.adler, buf, len, start);
17253 }
17254
17255 else if (strm.state.wrap === 2) {
17256 strm.adler = crc32(strm.adler, buf, len, start);
17257 }
17258
17259 strm.next_in += len;
17260 strm.total_in += len;
17261
17262 return len;
17263}
17264
17265
17266/* ===========================================================================
17267 * Set match_start to the longest match starting at the given string and
17268 * return its length. Matches shorter or equal to prev_length are discarded,
17269 * in which case the result is equal to prev_length and match_start is
17270 * garbage.
17271 * IN assertions: cur_match is the head of the hash chain for the current
17272 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
17273 * OUT assertion: the match length is not greater than s->lookahead.
17274 */
17275function longest_match(s, cur_match) {
17276 let chain_length = s.max_chain_length; /* max hash chain length */
17277 let scan = s.strstart; /* current string */
17278 let match; /* matched string */
17279 let len; /* length of current match */
17280 let best_len = s.prev_length; /* best match length so far */
17281 let nice_match = s.nice_match; /* stop if match long enough */
17282 const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
17283 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
17284
17285 const _win = s.window; // shortcut
17286
17287 const wmask = s.w_mask;
17288 const prev = s.prev;
17289
17290 /* Stop when cur_match becomes <= limit. To simplify the code,
17291 * we prevent matches with the string of window index 0.
17292 */
17293
17294 const strend = s.strstart + MAX_MATCH$1;
17295 let scan_end1 = _win[scan + best_len - 1];
17296 let scan_end = _win[scan + best_len];
17297
17298 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
17299 * It is easy to get rid of this optimization if necessary.
17300 */
17301 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
17302
17303 /* Do not waste too much time if we already have a good match: */
17304 if (s.prev_length >= s.good_match) {
17305 chain_length >>= 2;
17306 }
17307 /* Do not look for matches beyond the end of the input. This is necessary
17308 * to make deflate deterministic.
17309 */
17310 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
17311
17312 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
17313
17314 do {
17315 // Assert(cur_match < s->strstart, "no future");
17316 match = cur_match;
17317
17318 /* Skip to next match if the match length cannot increase
17319 * or if the match length is less than 2. Note that the checks below
17320 * for insufficient lookahead only occur occasionally for performance
17321 * reasons. Therefore uninitialized memory will be accessed, and
17322 * conditional jumps will be made that depend on those values.
17323 * However the length of the match is limited to the lookahead, so
17324 * the output of deflate is not affected by the uninitialized values.
17325 */
17326
17327 if (_win[match + best_len] !== scan_end ||
17328 _win[match + best_len - 1] !== scan_end1 ||
17329 _win[match] !== _win[scan] ||
17330 _win[++match] !== _win[scan + 1]) {
17331 continue;
17332 }
17333
17334 /* The check at best_len-1 can be removed because it will be made
17335 * again later. (This heuristic is not always a win.)
17336 * It is not necessary to compare scan[2] and match[2] since they
17337 * are always equal when the other bytes match, given that
17338 * the hash keys are equal and that HASH_BITS >= 8.
17339 */
17340 scan += 2;
17341 match++;
17342 // Assert(*scan == *match, "match[2]?");
17343
17344 /* We check for insufficient lookahead only every 8th comparison;
17345 * the 256th check will be made at strstart+258.
17346 */
17347 do {
17348 /*jshint noempty:false*/
17349 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17350 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17351 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17352 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17353 scan < strend);
17354
17355 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
17356
17357 len = MAX_MATCH$1 - (strend - scan);
17358 scan = strend - MAX_MATCH$1;
17359
17360 if (len > best_len) {
17361 s.match_start = cur_match;
17362 best_len = len;
17363 if (len >= nice_match) {
17364 break;
17365 }
17366 scan_end1 = _win[scan + best_len - 1];
17367 scan_end = _win[scan + best_len];
17368 }
17369 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
17370
17371 if (best_len <= s.lookahead) {
17372 return best_len;
17373 }
17374 return s.lookahead;
17375}
17376
17377
17378/* ===========================================================================
17379 * Fill the window when the lookahead becomes insufficient.
17380 * Updates strstart and lookahead.
17381 *
17382 * IN assertion: lookahead < MIN_LOOKAHEAD
17383 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
17384 * At least one byte has been read, or avail_in == 0; reads are
17385 * performed for at least two bytes (required for the zip translate_eol
17386 * option -- not supported here).
17387 */
17388function fill_window(s) {
17389 const _w_size = s.w_size;
17390 let p, n, m, more, str;
17391
17392 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
17393
17394 do {
17395 more = s.window_size - s.lookahead - s.strstart;
17396
17397 // JS ints have 32 bit, block below not needed
17398 /* Deal with !@#$% 64K limit: */
17399 //if (sizeof(int) <= 2) {
17400 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
17401 // more = wsize;
17402 //
17403 // } else if (more == (unsigned)(-1)) {
17404 // /* Very unlikely, but possible on 16 bit machine if
17405 // * strstart == 0 && lookahead == 1 (input done a byte at time)
17406 // */
17407 // more--;
17408 // }
17409 //}
17410
17411
17412 /* If the window is almost full and there is insufficient lookahead,
17413 * move the upper half to the lower one to make room in the upper half.
17414 */
17415 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
17416
17417 arraySet(s.window, s.window, _w_size, _w_size, 0);
17418 s.match_start -= _w_size;
17419 s.strstart -= _w_size;
17420 /* we now have strstart >= MAX_DIST */
17421 s.block_start -= _w_size;
17422
17423 /* Slide the hash table (could be avoided with 32 bit values
17424 at the expense of memory usage). We slide even when level == 0
17425 to keep the hash table consistent if we switch back to level > 0
17426 later. (Using level 0 permanently is not an optimal usage of
17427 zlib, so we don't care about this pathological case.)
17428 */
17429
17430 n = s.hash_size;
17431 p = n;
17432 do {
17433 m = s.head[--p];
17434 s.head[p] = (m >= _w_size ? m - _w_size : 0);
17435 } while (--n);
17436
17437 n = _w_size;
17438 p = n;
17439 do {
17440 m = s.prev[--p];
17441 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
17442 /* If n is not on any hash chain, prev[n] is garbage but
17443 * its value will never be used.
17444 */
17445 } while (--n);
17446
17447 more += _w_size;
17448 }
17449 if (s.strm.avail_in === 0) {
17450 break;
17451 }
17452
17453 /* If there was no sliding:
17454 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
17455 * more == window_size - lookahead - strstart
17456 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
17457 * => more >= window_size - 2*WSIZE + 2
17458 * In the BIG_MEM or MMAP case (not yet supported),
17459 * window_size == input_size + MIN_LOOKAHEAD &&
17460 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
17461 * Otherwise, window_size == 2*WSIZE so more >= 2.
17462 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
17463 */
17464 //Assert(more >= 2, "more < 2");
17465 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
17466 s.lookahead += n;
17467
17468 /* Initialize the hash value now that we have some input: */
17469 if (s.lookahead + s.insert >= MIN_MATCH$1) {
17470 str = s.strstart - s.insert;
17471 s.ins_h = s.window[str];
17472
17473 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
17474 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
17475 //#if MIN_MATCH != 3
17476 // Call update_hash() MIN_MATCH-3 more times
17477 //#endif
17478 while (s.insert) {
17479 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
17480 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
17481
17482 s.prev[str & s.w_mask] = s.head[s.ins_h];
17483 s.head[s.ins_h] = str;
17484 str++;
17485 s.insert--;
17486 if (s.lookahead + s.insert < MIN_MATCH$1) {
17487 break;
17488 }
17489 }
17490 }
17491 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
17492 * but this is not important since only literal bytes will be emitted.
17493 */
17494
17495 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
17496
17497 /* If the WIN_INIT bytes after the end of the current data have never been
17498 * written, then zero those bytes in order to avoid memory check reports of
17499 * the use of uninitialized (or uninitialised as Julian writes) bytes by
17500 * the longest match routines. Update the high water mark for the next
17501 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
17502 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
17503 */
17504 // if (s.high_water < s.window_size) {
17505 // var curr = s.strstart + s.lookahead;
17506 // var init = 0;
17507 //
17508 // if (s.high_water < curr) {
17509 // /* Previous high water mark below current data -- zero WIN_INIT
17510 // * bytes or up to end of window, whichever is less.
17511 // */
17512 // init = s.window_size - curr;
17513 // if (init > WIN_INIT)
17514 // init = WIN_INIT;
17515 // zmemzero(s->window + curr, (unsigned)init);
17516 // s->high_water = curr + init;
17517 // }
17518 // else if (s->high_water < (ulg)curr + WIN_INIT) {
17519 // /* High water mark at or above current data, but below current data
17520 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
17521 // * to end of window, whichever is less.
17522 // */
17523 // init = (ulg)curr + WIN_INIT - s->high_water;
17524 // if (init > s->window_size - s->high_water)
17525 // init = s->window_size - s->high_water;
17526 // zmemzero(s->window + s->high_water, (unsigned)init);
17527 // s->high_water += init;
17528 // }
17529 // }
17530 //
17531 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
17532 // "not enough room for search");
17533}
17534
17535/* ===========================================================================
17536 * Copy without compression as much as possible from the input stream, return
17537 * the current block state.
17538 * This function does not insert new strings in the dictionary since
17539 * uncompressible data is probably not useful. This function is used
17540 * only for the level=0 compression option.
17541 * NOTE: this function should be optimized to avoid extra copying from
17542 * window to pending_buf.
17543 */
17544function deflate_stored(s, flush) {
17545 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
17546 * to pending_buf_size, and each stored block has a 5 byte header:
17547 */
17548 let max_block_size = 0xffff;
17549
17550 if (max_block_size > s.pending_buf_size - 5) {
17551 max_block_size = s.pending_buf_size - 5;
17552 }
17553
17554 /* Copy as much as possible from input to output: */
17555 for (; ;) {
17556 /* Fill the window as much as possible: */
17557 if (s.lookahead <= 1) {
17558
17559 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
17560 // s->block_start >= (long)s->w_size, "slide too late");
17561 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
17562 // s.block_start >= s.w_size)) {
17563 // throw new Error("slide too late");
17564 // }
17565
17566 fill_window(s);
17567 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
17568 return BS_NEED_MORE;
17569 }
17570
17571 if (s.lookahead === 0) {
17572 break;
17573 }
17574 /* flush the current block */
17575 }
17576 //Assert(s->block_start >= 0L, "block gone");
17577 // if (s.block_start < 0) throw new Error("block gone");
17578
17579 s.strstart += s.lookahead;
17580 s.lookahead = 0;
17581
17582 /* Emit a stored block if pending_buf will be full: */
17583 const max_start = s.block_start + max_block_size;
17584
17585 if (s.strstart === 0 || s.strstart >= max_start) {
17586 /* strstart == 0 is possible when wraparound on 16-bit machine */
17587 s.lookahead = s.strstart - max_start;
17588 s.strstart = max_start;
17589 /*** FLUSH_BLOCK(s, 0); ***/
17590 flush_block_only(s, false);
17591 if (s.strm.avail_out === 0) {
17592 return BS_NEED_MORE;
17593 }
17594 /***/
17595
17596
17597 }
17598 /* Flush if we may have to slide, otherwise block_start may become
17599 * negative and the data will be gone:
17600 */
17601 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
17602 /*** FLUSH_BLOCK(s, 0); ***/
17603 flush_block_only(s, false);
17604 if (s.strm.avail_out === 0) {
17605 return BS_NEED_MORE;
17606 }
17607 /***/
17608 }
17609 }
17610
17611 s.insert = 0;
17612
17613 if (flush === Z_FINISH) {
17614 /*** FLUSH_BLOCK(s, 1); ***/
17615 flush_block_only(s, true);
17616 if (s.strm.avail_out === 0) {
17617 return BS_FINISH_STARTED;
17618 }
17619 /***/
17620 return BS_FINISH_DONE;
17621 }
17622
17623 if (s.strstart > s.block_start) {
17624 /*** FLUSH_BLOCK(s, 0); ***/
17625 flush_block_only(s, false);
17626 if (s.strm.avail_out === 0) {
17627 return BS_NEED_MORE;
17628 }
17629 /***/
17630 }
17631
17632 return BS_NEED_MORE;
17633}
17634
17635/* ===========================================================================
17636 * Compress as much as possible from the input stream, return the current
17637 * block state.
17638 * This function does not perform lazy evaluation of matches and inserts
17639 * new strings in the dictionary only for unmatched strings or for short
17640 * matches. It is used only for the fast compression options.
17641 */
17642function deflate_fast(s, flush) {
17643 let hash_head; /* head of the hash chain */
17644 let bflush; /* set if current block must be flushed */
17645
17646 for (; ;) {
17647 /* Make sure that we always have enough lookahead, except
17648 * at the end of the input file. We need MAX_MATCH bytes
17649 * for the next match, plus MIN_MATCH bytes to insert the
17650 * string following the next match.
17651 */
17652 if (s.lookahead < MIN_LOOKAHEAD) {
17653 fill_window(s);
17654 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17655 return BS_NEED_MORE;
17656 }
17657 if (s.lookahead === 0) {
17658 break; /* flush the current block */
17659 }
17660 }
17661
17662 /* Insert the string window[strstart .. strstart+2] in the
17663 * dictionary, and set hash_head to the head of the hash chain:
17664 */
17665 hash_head = 0/*NIL*/;
17666 if (s.lookahead >= MIN_MATCH$1) {
17667 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17668 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17669 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17670 s.head[s.ins_h] = s.strstart;
17671 /***/
17672 }
17673
17674 /* Find the longest match, discarding those <= prev_length.
17675 * At this point we have always match_length < MIN_MATCH
17676 */
17677 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
17678 /* To simplify the code, we prevent matches with the string
17679 * of window index 0 (in particular we have to avoid a match
17680 * of the string with itself at the start of the input file).
17681 */
17682 s.match_length = longest_match(s, hash_head);
17683 /* longest_match() sets match_start */
17684 }
17685 if (s.match_length >= MIN_MATCH$1) {
17686 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
17687
17688 /*** _tr_tally_dist(s, s.strstart - s.match_start,
17689 s.match_length - MIN_MATCH, bflush); ***/
17690 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
17691
17692 s.lookahead -= s.match_length;
17693
17694 /* Insert new strings in the hash table only if the match length
17695 * is not too large. This saves time but degrades compression.
17696 */
17697 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
17698 s.match_length--; /* string at strstart already in table */
17699 do {
17700 s.strstart++;
17701 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17702 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17703 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17704 s.head[s.ins_h] = s.strstart;
17705 /***/
17706 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
17707 * always MIN_MATCH bytes ahead.
17708 */
17709 } while (--s.match_length !== 0);
17710 s.strstart++;
17711 } else {
17712 s.strstart += s.match_length;
17713 s.match_length = 0;
17714 s.ins_h = s.window[s.strstart];
17715 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
17716 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
17717
17718 //#if MIN_MATCH != 3
17719 // Call UPDATE_HASH() MIN_MATCH-3 more times
17720 //#endif
17721 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
17722 * matter since it will be recomputed at next deflate call.
17723 */
17724 }
17725 } else {
17726 /* No match, output a literal byte */
17727 //Tracevv((stderr,"%c", s.window[s.strstart]));
17728 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17729 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17730
17731 s.lookahead--;
17732 s.strstart++;
17733 }
17734 if (bflush) {
17735 /*** FLUSH_BLOCK(s, 0); ***/
17736 flush_block_only(s, false);
17737 if (s.strm.avail_out === 0) {
17738 return BS_NEED_MORE;
17739 }
17740 /***/
17741 }
17742 }
17743 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
17744 if (flush === Z_FINISH) {
17745 /*** FLUSH_BLOCK(s, 1); ***/
17746 flush_block_only(s, true);
17747 if (s.strm.avail_out === 0) {
17748 return BS_FINISH_STARTED;
17749 }
17750 /***/
17751 return BS_FINISH_DONE;
17752 }
17753 if (s.last_lit) {
17754 /*** FLUSH_BLOCK(s, 0); ***/
17755 flush_block_only(s, false);
17756 if (s.strm.avail_out === 0) {
17757 return BS_NEED_MORE;
17758 }
17759 /***/
17760 }
17761 return BS_BLOCK_DONE;
17762}
17763
17764/* ===========================================================================
17765 * Same as above, but achieves better compression. We use a lazy
17766 * evaluation for matches: a match is finally adopted only if there is
17767 * no better match at the next window position.
17768 */
17769function deflate_slow(s, flush) {
17770 let hash_head; /* head of hash chain */
17771 let bflush; /* set if current block must be flushed */
17772
17773 let max_insert;
17774
17775 /* Process the input block. */
17776 for (; ;) {
17777 /* Make sure that we always have enough lookahead, except
17778 * at the end of the input file. We need MAX_MATCH bytes
17779 * for the next match, plus MIN_MATCH bytes to insert the
17780 * string following the next match.
17781 */
17782 if (s.lookahead < MIN_LOOKAHEAD) {
17783 fill_window(s);
17784 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17785 return BS_NEED_MORE;
17786 }
17787 if (s.lookahead === 0) { break; } /* flush the current block */
17788 }
17789
17790 /* Insert the string window[strstart .. strstart+2] in the
17791 * dictionary, and set hash_head to the head of the hash chain:
17792 */
17793 hash_head = 0/*NIL*/;
17794 if (s.lookahead >= MIN_MATCH$1) {
17795 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17796 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17797 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17798 s.head[s.ins_h] = s.strstart;
17799 /***/
17800 }
17801
17802 /* Find the longest match, discarding those <= prev_length.
17803 */
17804 s.prev_length = s.match_length;
17805 s.prev_match = s.match_start;
17806 s.match_length = MIN_MATCH$1 - 1;
17807
17808 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
17809 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
17810 /* To simplify the code, we prevent matches with the string
17811 * of window index 0 (in particular we have to avoid a match
17812 * of the string with itself at the start of the input file).
17813 */
17814 s.match_length = longest_match(s, hash_head);
17815 /* longest_match() sets match_start */
17816
17817 if (s.match_length <= 5 &&
17818 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
17819
17820 /* If prev_match is also MIN_MATCH, match_start is garbage
17821 * but we will ignore the current match anyway.
17822 */
17823 s.match_length = MIN_MATCH$1 - 1;
17824 }
17825 }
17826 /* If there was a match at the previous step and the current
17827 * match is not better, output the previous match:
17828 */
17829 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
17830 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
17831 /* Do not insert strings in hash table beyond this. */
17832
17833 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
17834
17835 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
17836 s.prev_length - MIN_MATCH, bflush);***/
17837 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
17838 /* Insert in hash table all strings up to the end of the match.
17839 * strstart-1 and strstart are already inserted. If there is not
17840 * enough lookahead, the last two strings are not inserted in
17841 * the hash table.
17842 */
17843 s.lookahead -= s.prev_length - 1;
17844 s.prev_length -= 2;
17845 do {
17846 if (++s.strstart <= max_insert) {
17847 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17848 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17849 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17850 s.head[s.ins_h] = s.strstart;
17851 /***/
17852 }
17853 } while (--s.prev_length !== 0);
17854 s.match_available = 0;
17855 s.match_length = MIN_MATCH$1 - 1;
17856 s.strstart++;
17857
17858 if (bflush) {
17859 /*** FLUSH_BLOCK(s, 0); ***/
17860 flush_block_only(s, false);
17861 if (s.strm.avail_out === 0) {
17862 return BS_NEED_MORE;
17863 }
17864 /***/
17865 }
17866
17867 } else if (s.match_available) {
17868 /* If there was no match at the previous position, output a
17869 * single literal. If there was a match but the current match
17870 * is longer, truncate the previous match to a single literal.
17871 */
17872 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17873 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17874 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17875
17876 if (bflush) {
17877 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
17878 flush_block_only(s, false);
17879 /***/
17880 }
17881 s.strstart++;
17882 s.lookahead--;
17883 if (s.strm.avail_out === 0) {
17884 return BS_NEED_MORE;
17885 }
17886 } else {
17887 /* There is no previous match to compare with, wait for
17888 * the next step to decide.
17889 */
17890 s.match_available = 1;
17891 s.strstart++;
17892 s.lookahead--;
17893 }
17894 }
17895 //Assert (flush != Z_NO_FLUSH, "no flush?");
17896 if (s.match_available) {
17897 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17898 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17899 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17900
17901 s.match_available = 0;
17902 }
17903 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
17904 if (flush === Z_FINISH) {
17905 /*** FLUSH_BLOCK(s, 1); ***/
17906 flush_block_only(s, true);
17907 if (s.strm.avail_out === 0) {
17908 return BS_FINISH_STARTED;
17909 }
17910 /***/
17911 return BS_FINISH_DONE;
17912 }
17913 if (s.last_lit) {
17914 /*** FLUSH_BLOCK(s, 0); ***/
17915 flush_block_only(s, false);
17916 if (s.strm.avail_out === 0) {
17917 return BS_NEED_MORE;
17918 }
17919 /***/
17920 }
17921
17922 return BS_BLOCK_DONE;
17923}
17924
17925
17926/* ===========================================================================
17927 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
17928 * one. Do not maintain a hash table. (It will be regenerated if this run of
17929 * deflate switches away from Z_RLE.)
17930 */
17931function deflate_rle(s, flush) {
17932 let bflush; /* set if current block must be flushed */
17933 let prev; /* byte at distance one to match */
17934 let scan, strend; /* scan goes up to strend for length of run */
17935
17936 const _win = s.window;
17937
17938 for (; ;) {
17939 /* Make sure that we always have enough lookahead, except
17940 * at the end of the input file. We need MAX_MATCH bytes
17941 * for the longest run, plus one for the unrolled loop.
17942 */
17943 if (s.lookahead <= MAX_MATCH$1) {
17944 fill_window(s);
17945 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
17946 return BS_NEED_MORE;
17947 }
17948 if (s.lookahead === 0) { break; } /* flush the current block */
17949 }
17950
17951 /* See how many times the previous byte repeats */
17952 s.match_length = 0;
17953 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
17954 scan = s.strstart - 1;
17955 prev = _win[scan];
17956 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
17957 strend = s.strstart + MAX_MATCH$1;
17958 do {
17959 /*jshint noempty:false*/
17960 } while (prev === _win[++scan] && prev === _win[++scan] &&
17961 prev === _win[++scan] && prev === _win[++scan] &&
17962 prev === _win[++scan] && prev === _win[++scan] &&
17963 prev === _win[++scan] && prev === _win[++scan] &&
17964 scan < strend);
17965 s.match_length = MAX_MATCH$1 - (strend - scan);
17966 if (s.match_length > s.lookahead) {
17967 s.match_length = s.lookahead;
17968 }
17969 }
17970 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
17971 }
17972
17973 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
17974 if (s.match_length >= MIN_MATCH$1) {
17975 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
17976
17977 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
17978 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
17979
17980 s.lookahead -= s.match_length;
17981 s.strstart += s.match_length;
17982 s.match_length = 0;
17983 } else {
17984 /* No match, output a literal byte */
17985 //Tracevv((stderr,"%c", s->window[s->strstart]));
17986 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17987 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17988
17989 s.lookahead--;
17990 s.strstart++;
17991 }
17992 if (bflush) {
17993 /*** FLUSH_BLOCK(s, 0); ***/
17994 flush_block_only(s, false);
17995 if (s.strm.avail_out === 0) {
17996 return BS_NEED_MORE;
17997 }
17998 /***/
17999 }
18000 }
18001 s.insert = 0;
18002 if (flush === Z_FINISH) {
18003 /*** FLUSH_BLOCK(s, 1); ***/
18004 flush_block_only(s, true);
18005 if (s.strm.avail_out === 0) {
18006 return BS_FINISH_STARTED;
18007 }
18008 /***/
18009 return BS_FINISH_DONE;
18010 }
18011 if (s.last_lit) {
18012 /*** FLUSH_BLOCK(s, 0); ***/
18013 flush_block_only(s, false);
18014 if (s.strm.avail_out === 0) {
18015 return BS_NEED_MORE;
18016 }
18017 /***/
18018 }
18019 return BS_BLOCK_DONE;
18020}
18021
18022/* ===========================================================================
18023 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
18024 * (It will be regenerated if this run of deflate switches away from Huffman.)
18025 */
18026function deflate_huff(s, flush) {
18027 let bflush; /* set if current block must be flushed */
18028
18029 for (; ;) {
18030 /* Make sure that we have a literal to write. */
18031 if (s.lookahead === 0) {
18032 fill_window(s);
18033 if (s.lookahead === 0) {
18034 if (flush === Z_NO_FLUSH) {
18035 return BS_NEED_MORE;
18036 }
18037 break; /* flush the current block */
18038 }
18039 }
18040
18041 /* Output a literal byte */
18042 s.match_length = 0;
18043 //Tracevv((stderr,"%c", s->window[s->strstart]));
18044 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
18045 bflush = _tr_tally(s, 0, s.window[s.strstart]);
18046 s.lookahead--;
18047 s.strstart++;
18048 if (bflush) {
18049 /*** FLUSH_BLOCK(s, 0); ***/
18050 flush_block_only(s, false);
18051 if (s.strm.avail_out === 0) {
18052 return BS_NEED_MORE;
18053 }
18054 /***/
18055 }
18056 }
18057 s.insert = 0;
18058 if (flush === Z_FINISH) {
18059 /*** FLUSH_BLOCK(s, 1); ***/
18060 flush_block_only(s, true);
18061 if (s.strm.avail_out === 0) {
18062 return BS_FINISH_STARTED;
18063 }
18064 /***/
18065 return BS_FINISH_DONE;
18066 }
18067 if (s.last_lit) {
18068 /*** FLUSH_BLOCK(s, 0); ***/
18069 flush_block_only(s, false);
18070 if (s.strm.avail_out === 0) {
18071 return BS_NEED_MORE;
18072 }
18073 /***/
18074 }
18075 return BS_BLOCK_DONE;
18076}
18077
18078/* Values for max_lazy_match, good_match and max_chain_length, depending on
18079 * the desired pack level (0..9). The values given below have been tuned to
18080 * exclude worst case performance for pathological files. Better values may be
18081 * found for specific files.
18082 */
18083class Config {
18084 constructor(good_length, max_lazy, nice_length, max_chain, func) {
18085 this.good_length = good_length;
18086 this.max_lazy = max_lazy;
18087 this.nice_length = nice_length;
18088 this.max_chain = max_chain;
18089 this.func = func;
18090 }
18091}
18092const configuration_table = [
18093 /* good lazy nice chain */
18094 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
18095 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
18096 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
18097 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
18098
18099 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
18100 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
18101 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
18102 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
18103 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
18104 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
18105];
18106
18107
18108/* ===========================================================================
18109 * Initialize the "longest match" routines for a new zlib stream
18110 */
18111function lm_init(s) {
18112 s.window_size = 2 * s.w_size;
18113
18114 /*** CLEAR_HASH(s); ***/
18115 zero$2(s.head); // Fill with NIL (= 0);
18116
18117 /* Set the default configuration parameters:
18118 */
18119 s.max_lazy_match = configuration_table[s.level].max_lazy;
18120 s.good_match = configuration_table[s.level].good_length;
18121 s.nice_match = configuration_table[s.level].nice_length;
18122 s.max_chain_length = configuration_table[s.level].max_chain;
18123
18124 s.strstart = 0;
18125 s.block_start = 0;
18126 s.lookahead = 0;
18127 s.insert = 0;
18128 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18129 s.match_available = 0;
18130 s.ins_h = 0;
18131}
18132
18133class DeflateState {
18134 constructor() {
18135 this.strm = null; /* pointer back to this zlib stream */
18136 this.status = 0; /* as the name implies */
18137 this.pending_buf = null; /* output still pending */
18138 this.pending_buf_size = 0; /* size of pending_buf */
18139 this.pending_out = 0; /* next pending byte to output to the stream */
18140 this.pending = 0; /* nb of bytes in the pending buffer */
18141 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
18142 this.gzhead = null; /* gzip header information to write */
18143 this.gzindex = 0; /* where in extra, name, or comment */
18144 this.method = Z_DEFLATED; /* can only be DEFLATED */
18145 this.last_flush = -1; /* value of flush param for previous deflate call */
18146
18147 this.w_size = 0; /* LZ77 window size (32K by default) */
18148 this.w_bits = 0; /* log2(w_size) (8..16) */
18149 this.w_mask = 0; /* w_size - 1 */
18150
18151 this.window = null;
18152 /* Sliding window. Input bytes are read into the second half of the window,
18153 * and move to the first half later to keep a dictionary of at least wSize
18154 * bytes. With this organization, matches are limited to a distance of
18155 * wSize-MAX_MATCH bytes, but this ensures that IO is always
18156 * performed with a length multiple of the block size.
18157 */
18158
18159 this.window_size = 0;
18160 /* Actual size of window: 2*wSize, except when the user input buffer
18161 * is directly used as sliding window.
18162 */
18163
18164 this.prev = null;
18165 /* Link to older string with same hash index. To limit the size of this
18166 * array to 64K, this link is maintained only for the last 32K strings.
18167 * An index in this array is thus a window index modulo 32K.
18168 */
18169
18170 this.head = null; /* Heads of the hash chains or NIL. */
18171
18172 this.ins_h = 0; /* hash index of string to be inserted */
18173 this.hash_size = 0; /* number of elements in hash table */
18174 this.hash_bits = 0; /* log2(hash_size) */
18175 this.hash_mask = 0; /* hash_size-1 */
18176
18177 this.hash_shift = 0;
18178 /* Number of bits by which ins_h must be shifted at each input
18179 * step. It must be such that after MIN_MATCH steps, the oldest
18180 * byte no longer takes part in the hash key, that is:
18181 * hash_shift * MIN_MATCH >= hash_bits
18182 */
18183
18184 this.block_start = 0;
18185 /* Window position at the beginning of the current output block. Gets
18186 * negative when the window is moved backwards.
18187 */
18188
18189 this.match_length = 0; /* length of best match */
18190 this.prev_match = 0; /* previous match */
18191 this.match_available = 0; /* set if previous match exists */
18192 this.strstart = 0; /* start of string to insert */
18193 this.match_start = 0; /* start of matching string */
18194 this.lookahead = 0; /* number of valid bytes ahead in window */
18195
18196 this.prev_length = 0;
18197 /* Length of the best match at previous step. Matches not greater than this
18198 * are discarded. This is used in the lazy match evaluation.
18199 */
18200
18201 this.max_chain_length = 0;
18202 /* To speed up deflation, hash chains are never searched beyond this
18203 * length. A higher limit improves compression ratio but degrades the
18204 * speed.
18205 */
18206
18207 this.max_lazy_match = 0;
18208 /* Attempt to find a better match only when the current match is strictly
18209 * smaller than this value. This mechanism is used only for compression
18210 * levels >= 4.
18211 */
18212 // That's alias to max_lazy_match, don't use directly
18213 //this.max_insert_length = 0;
18214 /* Insert new strings in the hash table only if the match length is not
18215 * greater than this length. This saves time but degrades compression.
18216 * max_insert_length is used only for compression levels <= 3.
18217 */
18218
18219 this.level = 0; /* compression level (1..9) */
18220 this.strategy = 0; /* favor or force Huffman coding*/
18221
18222 this.good_match = 0;
18223 /* Use a faster search when the previous match is longer than this */
18224
18225 this.nice_match = 0; /* Stop searching when current match exceeds this */
18226
18227 /* used by trees.c: */
18228
18229 /* Didn't use ct_data typedef below to suppress compiler warning */
18230
18231 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
18232 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
18233 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
18234
18235 // Use flat array of DOUBLE size, with interleaved fata,
18236 // because JS does not support effective
18237 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
18238 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
18239 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
18240 zero$2(this.dyn_ltree);
18241 zero$2(this.dyn_dtree);
18242 zero$2(this.bl_tree);
18243
18244 this.l_desc = null; /* desc. for literal tree */
18245 this.d_desc = null; /* desc. for distance tree */
18246 this.bl_desc = null; /* desc. for bit length tree */
18247
18248 //ush bl_count[MAX_BITS+1];
18249 this.bl_count = new Buf16(MAX_BITS$1 + 1);
18250 /* number of codes at each bit length for an optimal tree */
18251
18252 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
18253 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
18254 zero$2(this.heap);
18255
18256 this.heap_len = 0; /* number of elements in the heap */
18257 this.heap_max = 0; /* element of largest frequency */
18258 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
18259 * The same heap array is used to build all trees.
18260 */
18261
18262 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
18263 zero$2(this.depth);
18264 /* Depth of each subtree used as tie breaker for trees of equal frequency
18265 */
18266
18267 this.l_buf = 0; /* buffer index for literals or lengths */
18268
18269 this.lit_bufsize = 0;
18270 /* Size of match buffer for literals/lengths. There are 4 reasons for
18271 * limiting lit_bufsize to 64K:
18272 * - frequencies can be kept in 16 bit counters
18273 * - if compression is not successful for the first block, all input
18274 * data is still in the window so we can still emit a stored block even
18275 * when input comes from standard input. (This can also be done for
18276 * all blocks if lit_bufsize is not greater than 32K.)
18277 * - if compression is not successful for a file smaller than 64K, we can
18278 * even emit a stored file instead of a stored block (saving 5 bytes).
18279 * This is applicable only for zip (not gzip or zlib).
18280 * - creating new Huffman trees less frequently may not provide fast
18281 * adaptation to changes in the input data statistics. (Take for
18282 * example a binary file with poorly compressible code followed by
18283 * a highly compressible string table.) Smaller buffer sizes give
18284 * fast adaptation but have of course the overhead of transmitting
18285 * trees more frequently.
18286 * - I can't count above 4
18287 */
18288
18289 this.last_lit = 0; /* running index in l_buf */
18290
18291 this.d_buf = 0;
18292 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
18293 * the same number of elements. To use different lengths, an extra flag
18294 * array would be necessary.
18295 */
18296
18297 this.opt_len = 0; /* bit length of current block with optimal trees */
18298 this.static_len = 0; /* bit length of current block with static trees */
18299 this.matches = 0; /* number of string matches in current block */
18300 this.insert = 0; /* bytes at end of window left to insert */
18301
18302
18303 this.bi_buf = 0;
18304 /* Output buffer. bits are inserted starting at the bottom (least
18305 * significant bits).
18306 */
18307 this.bi_valid = 0;
18308 /* Number of valid bits in bi_buf. All bits above the last valid bit
18309 * are always zero.
18310 */
18311
18312 // Used for window memory init. We safely ignore it for JS. That makes
18313 // sense only for pointers and memory check tools.
18314 //this.high_water = 0;
18315 /* High water mark offset in window for initialized bytes -- bytes above
18316 * this are set to zero in order to avoid memory check warnings when
18317 * longest match routines access bytes past the input. This is then
18318 * updated to the new high water mark.
18319 */
18320 }
18321}
18322
18323function deflateResetKeep(strm) {
18324 let s;
18325
18326 if (!strm || !strm.state) {
18327 return err(strm, Z_STREAM_ERROR);
18328 }
18329
18330 strm.total_in = strm.total_out = 0;
18331 strm.data_type = Z_UNKNOWN;
18332
18333 s = strm.state;
18334 s.pending = 0;
18335 s.pending_out = 0;
18336
18337 if (s.wrap < 0) {
18338 s.wrap = -s.wrap;
18339 /* was made negative by deflate(..., Z_FINISH); */
18340 }
18341 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
18342 strm.adler = (s.wrap === 2) ?
18343 0 // crc32(0, Z_NULL, 0)
18344 :
18345 1; // adler32(0, Z_NULL, 0)
18346 s.last_flush = Z_NO_FLUSH;
18347 _tr_init(s);
18348 return Z_OK;
18349}
18350
18351
18352function deflateReset(strm) {
18353 const ret = deflateResetKeep(strm);
18354 if (ret === Z_OK) {
18355 lm_init(strm.state);
18356 }
18357 return ret;
18358}
18359
18360
18361function deflateSetHeader(strm, head) {
18362 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18363 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
18364 strm.state.gzhead = head;
18365 return Z_OK;
18366}
18367
18368
18369function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
18370 if (!strm) { // === Z_NULL
18371 return Z_STREAM_ERROR;
18372 }
18373 let wrap = 1;
18374
18375 if (level === Z_DEFAULT_COMPRESSION) {
18376 level = 6;
18377 }
18378
18379 if (windowBits < 0) { /* suppress zlib wrapper */
18380 wrap = 0;
18381 windowBits = -windowBits;
18382 }
18383
18384 else if (windowBits > 15) {
18385 wrap = 2; /* write gzip wrapper instead */
18386 windowBits -= 16;
18387 }
18388
18389
18390 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
18391 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
18392 strategy < 0 || strategy > Z_FIXED) {
18393 return err(strm, Z_STREAM_ERROR);
18394 }
18395
18396
18397 if (windowBits === 8) {
18398 windowBits = 9;
18399 }
18400 /* until 256-byte window bug fixed */
18401
18402 const s = new DeflateState();
18403
18404 strm.state = s;
18405 s.strm = strm;
18406
18407 s.wrap = wrap;
18408 s.gzhead = null;
18409 s.w_bits = windowBits;
18410 s.w_size = 1 << s.w_bits;
18411 s.w_mask = s.w_size - 1;
18412
18413 s.hash_bits = memLevel + 7;
18414 s.hash_size = 1 << s.hash_bits;
18415 s.hash_mask = s.hash_size - 1;
18416 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
18417 s.window = new Buf8(s.w_size * 2);
18418 s.head = new Buf16(s.hash_size);
18419 s.prev = new Buf16(s.w_size);
18420
18421 // Don't need mem init magic for JS.
18422 //s.high_water = 0; /* nothing written to s->window yet */
18423
18424 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
18425
18426 s.pending_buf_size = s.lit_bufsize * 4;
18427
18428 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
18429 //s->pending_buf = (uchf *) overlay;
18430 s.pending_buf = new Buf8(s.pending_buf_size);
18431
18432 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
18433 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
18434 s.d_buf = 1 * s.lit_bufsize;
18435
18436 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
18437 s.l_buf = (1 + 2) * s.lit_bufsize;
18438
18439 s.level = level;
18440 s.strategy = strategy;
18441 s.method = method;
18442
18443 return deflateReset(strm);
18444}
18445
18446
18447function deflate(strm, flush) {
18448 let old_flush, s;
18449 let beg, val; // for gzip header write only
18450
18451 if (!strm || !strm.state ||
18452 flush > Z_BLOCK || flush < 0) {
18453 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
18454 }
18455
18456 s = strm.state;
18457
18458 if (!strm.output ||
18459 (!strm.input && strm.avail_in !== 0) ||
18460 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
18461 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
18462 }
18463
18464 s.strm = strm; /* just in case */
18465 old_flush = s.last_flush;
18466 s.last_flush = flush;
18467
18468 /* Write the header */
18469 if (s.status === INIT_STATE) {
18470
18471 if (s.wrap === 2) { // GZIP header
18472 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18473 put_byte(s, 31);
18474 put_byte(s, 139);
18475 put_byte(s, 8);
18476 if (!s.gzhead) { // s->gzhead == Z_NULL
18477 put_byte(s, 0);
18478 put_byte(s, 0);
18479 put_byte(s, 0);
18480 put_byte(s, 0);
18481 put_byte(s, 0);
18482 put_byte(s, s.level === 9 ? 2 :
18483 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18484 4 : 0));
18485 put_byte(s, OS_CODE);
18486 s.status = BUSY_STATE;
18487 }
18488 else {
18489 put_byte(s, (s.gzhead.text ? 1 : 0) +
18490 (s.gzhead.hcrc ? 2 : 0) +
18491 (!s.gzhead.extra ? 0 : 4) +
18492 (!s.gzhead.name ? 0 : 8) +
18493 (!s.gzhead.comment ? 0 : 16)
18494 );
18495 put_byte(s, s.gzhead.time & 0xff);
18496 put_byte(s, (s.gzhead.time >> 8) & 0xff);
18497 put_byte(s, (s.gzhead.time >> 16) & 0xff);
18498 put_byte(s, (s.gzhead.time >> 24) & 0xff);
18499 put_byte(s, s.level === 9 ? 2 :
18500 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18501 4 : 0));
18502 put_byte(s, s.gzhead.os & 0xff);
18503 if (s.gzhead.extra && s.gzhead.extra.length) {
18504 put_byte(s, s.gzhead.extra.length & 0xff);
18505 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
18506 }
18507 if (s.gzhead.hcrc) {
18508 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
18509 }
18510 s.gzindex = 0;
18511 s.status = EXTRA_STATE;
18512 }
18513 }
18514 else // DEFLATE header
18515 {
18516 let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
18517 let level_flags = -1;
18518
18519 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
18520 level_flags = 0;
18521 } else if (s.level < 6) {
18522 level_flags = 1;
18523 } else if (s.level === 6) {
18524 level_flags = 2;
18525 } else {
18526 level_flags = 3;
18527 }
18528 header |= (level_flags << 6);
18529 if (s.strstart !== 0) { header |= PRESET_DICT; }
18530 header += 31 - (header % 31);
18531
18532 s.status = BUSY_STATE;
18533 putShortMSB(s, header);
18534
18535 /* Save the adler32 of the preset dictionary: */
18536 if (s.strstart !== 0) {
18537 putShortMSB(s, strm.adler >>> 16);
18538 putShortMSB(s, strm.adler & 0xffff);
18539 }
18540 strm.adler = 1; // adler32(0L, Z_NULL, 0);
18541 }
18542 }
18543
18544 //#ifdef GZIP
18545 if (s.status === EXTRA_STATE) {
18546 if (s.gzhead.extra/* != Z_NULL*/) {
18547 beg = s.pending; /* start of bytes to update crc */
18548
18549 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
18550 if (s.pending === s.pending_buf_size) {
18551 if (s.gzhead.hcrc && s.pending > beg) {
18552 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18553 }
18554 flush_pending(strm);
18555 beg = s.pending;
18556 if (s.pending === s.pending_buf_size) {
18557 break;
18558 }
18559 }
18560 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
18561 s.gzindex++;
18562 }
18563 if (s.gzhead.hcrc && s.pending > beg) {
18564 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18565 }
18566 if (s.gzindex === s.gzhead.extra.length) {
18567 s.gzindex = 0;
18568 s.status = NAME_STATE;
18569 }
18570 }
18571 else {
18572 s.status = NAME_STATE;
18573 }
18574 }
18575 if (s.status === NAME_STATE) {
18576 if (s.gzhead.name/* != Z_NULL*/) {
18577 beg = s.pending; /* start of bytes to update crc */
18578 //int val;
18579
18580 do {
18581 if (s.pending === s.pending_buf_size) {
18582 if (s.gzhead.hcrc && s.pending > beg) {
18583 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18584 }
18585 flush_pending(strm);
18586 beg = s.pending;
18587 if (s.pending === s.pending_buf_size) {
18588 val = 1;
18589 break;
18590 }
18591 }
18592 // JS specific: little magic to add zero terminator to end of string
18593 if (s.gzindex < s.gzhead.name.length) {
18594 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
18595 } else {
18596 val = 0;
18597 }
18598 put_byte(s, val);
18599 } while (val !== 0);
18600
18601 if (s.gzhead.hcrc && s.pending > beg) {
18602 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18603 }
18604 if (val === 0) {
18605 s.gzindex = 0;
18606 s.status = COMMENT_STATE;
18607 }
18608 }
18609 else {
18610 s.status = COMMENT_STATE;
18611 }
18612 }
18613 if (s.status === COMMENT_STATE) {
18614 if (s.gzhead.comment/* != Z_NULL*/) {
18615 beg = s.pending; /* start of bytes to update crc */
18616 //int val;
18617
18618 do {
18619 if (s.pending === s.pending_buf_size) {
18620 if (s.gzhead.hcrc && s.pending > beg) {
18621 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18622 }
18623 flush_pending(strm);
18624 beg = s.pending;
18625 if (s.pending === s.pending_buf_size) {
18626 val = 1;
18627 break;
18628 }
18629 }
18630 // JS specific: little magic to add zero terminator to end of string
18631 if (s.gzindex < s.gzhead.comment.length) {
18632 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
18633 } else {
18634 val = 0;
18635 }
18636 put_byte(s, val);
18637 } while (val !== 0);
18638
18639 if (s.gzhead.hcrc && s.pending > beg) {
18640 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18641 }
18642 if (val === 0) {
18643 s.status = HCRC_STATE;
18644 }
18645 }
18646 else {
18647 s.status = HCRC_STATE;
18648 }
18649 }
18650 if (s.status === HCRC_STATE) {
18651 if (s.gzhead.hcrc) {
18652 if (s.pending + 2 > s.pending_buf_size) {
18653 flush_pending(strm);
18654 }
18655 if (s.pending + 2 <= s.pending_buf_size) {
18656 put_byte(s, strm.adler & 0xff);
18657 put_byte(s, (strm.adler >> 8) & 0xff);
18658 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18659 s.status = BUSY_STATE;
18660 }
18661 }
18662 else {
18663 s.status = BUSY_STATE;
18664 }
18665 }
18666 //#endif
18667
18668 /* Flush as much pending output as possible */
18669 if (s.pending !== 0) {
18670 flush_pending(strm);
18671 if (strm.avail_out === 0) {
18672 /* Since avail_out is 0, deflate will be called again with
18673 * more output space, but possibly with both pending and
18674 * avail_in equal to zero. There won't be anything to do,
18675 * but this is not an error situation so make sure we
18676 * return OK instead of BUF_ERROR at next call of deflate:
18677 */
18678 s.last_flush = -1;
18679 return Z_OK;
18680 }
18681
18682 /* Make sure there is something to do and avoid duplicate consecutive
18683 * flushes. For repeated and useless calls with Z_FINISH, we keep
18684 * returning Z_STREAM_END instead of Z_BUF_ERROR.
18685 */
18686 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
18687 flush !== Z_FINISH) {
18688 return err(strm, Z_BUF_ERROR);
18689 }
18690
18691 /* User must not provide more input after the first FINISH: */
18692 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
18693 return err(strm, Z_BUF_ERROR);
18694 }
18695
18696 /* Start a new block or continue the current one.
18697 */
18698 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
18699 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
18700 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
18701 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
18702 configuration_table[s.level].func(s, flush));
18703
18704 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
18705 s.status = FINISH_STATE;
18706 }
18707 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
18708 if (strm.avail_out === 0) {
18709 s.last_flush = -1;
18710 /* avoid BUF_ERROR next call, see above */
18711 }
18712 return Z_OK;
18713 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
18714 * of deflate should use the same flush parameter to make sure
18715 * that the flush is complete. So we don't have to output an
18716 * empty block here, this will be done at next call. This also
18717 * ensures that for a very small output buffer, we emit at most
18718 * one empty block.
18719 */
18720 }
18721 if (bstate === BS_BLOCK_DONE) {
18722 if (flush === Z_PARTIAL_FLUSH) {
18723 _tr_align(s);
18724 }
18725 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
18726
18727 _tr_stored_block(s, 0, 0, false);
18728 /* For a full flush, this empty block will be recognized
18729 * as a special marker by inflate_sync().
18730 */
18731 if (flush === Z_FULL_FLUSH) {
18732 /*** CLEAR_HASH(s); ***/ /* forget history */
18733 zero$2(s.head); // Fill with NIL (= 0);
18734
18735 if (s.lookahead === 0) {
18736 s.strstart = 0;
18737 s.block_start = 0;
18738 s.insert = 0;
18739 }
18740 }
18741 }
18742 flush_pending(strm);
18743 if (strm.avail_out === 0) {
18744 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
18745 return Z_OK;
18746 }
18747 }
18748 }
18749 //Assert(strm->avail_out > 0, "bug2");
18750 //if (strm.avail_out <= 0) { throw new Error("bug2");}
18751
18752 if (flush !== Z_FINISH) { return Z_OK; }
18753 if (s.wrap <= 0) { return Z_STREAM_END; }
18754
18755 /* Write the trailer */
18756 if (s.wrap === 2) {
18757 put_byte(s, strm.adler & 0xff);
18758 put_byte(s, (strm.adler >> 8) & 0xff);
18759 put_byte(s, (strm.adler >> 16) & 0xff);
18760 put_byte(s, (strm.adler >> 24) & 0xff);
18761 put_byte(s, strm.total_in & 0xff);
18762 put_byte(s, (strm.total_in >> 8) & 0xff);
18763 put_byte(s, (strm.total_in >> 16) & 0xff);
18764 put_byte(s, (strm.total_in >> 24) & 0xff);
18765 }
18766 else {
18767 putShortMSB(s, strm.adler >>> 16);
18768 putShortMSB(s, strm.adler & 0xffff);
18769 }
18770
18771 flush_pending(strm);
18772 /* If avail_out is zero, the application will call deflate again
18773 * to flush the rest.
18774 */
18775 if (s.wrap > 0) { s.wrap = -s.wrap; }
18776 /* write the trailer only once! */
18777 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
18778}
18779
18780function deflateEnd(strm) {
18781 let status;
18782
18783 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18784 return Z_STREAM_ERROR;
18785 }
18786
18787 status = strm.state.status;
18788 if (status !== INIT_STATE &&
18789 status !== EXTRA_STATE &&
18790 status !== NAME_STATE &&
18791 status !== COMMENT_STATE &&
18792 status !== HCRC_STATE &&
18793 status !== BUSY_STATE &&
18794 status !== FINISH_STATE
18795 ) {
18796 return err(strm, Z_STREAM_ERROR);
18797 }
18798
18799 strm.state = null;
18800
18801 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
18802}
18803
18804
18805/* =========================================================================
18806 * Initializes the compression dictionary from the given byte
18807 * sequence without producing any compressed output.
18808 */
18809function deflateSetDictionary(strm, dictionary) {
18810 let dictLength = dictionary.length;
18811
18812 let s;
18813 let str, n;
18814 let wrap;
18815 let avail;
18816 let next;
18817 let input;
18818 let tmpDict;
18819
18820 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18821 return Z_STREAM_ERROR;
18822 }
18823
18824 s = strm.state;
18825 wrap = s.wrap;
18826
18827 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
18828 return Z_STREAM_ERROR;
18829 }
18830
18831 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
18832 if (wrap === 1) {
18833 /* adler32(strm->adler, dictionary, dictLength); */
18834 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
18835 }
18836
18837 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
18838
18839 /* if dictionary would fill window, just replace the history */
18840 if (dictLength >= s.w_size) {
18841 if (wrap === 0) { /* already empty otherwise */
18842 /*** CLEAR_HASH(s); ***/
18843 zero$2(s.head); // Fill with NIL (= 0);
18844 s.strstart = 0;
18845 s.block_start = 0;
18846 s.insert = 0;
18847 }
18848 /* use the tail */
18849 // dictionary = dictionary.slice(dictLength - s.w_size);
18850 tmpDict = new Buf8(s.w_size);
18851 arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
18852 dictionary = tmpDict;
18853 dictLength = s.w_size;
18854 }
18855 /* insert dictionary into window and hash */
18856 avail = strm.avail_in;
18857 next = strm.next_in;
18858 input = strm.input;
18859 strm.avail_in = dictLength;
18860 strm.next_in = 0;
18861 strm.input = dictionary;
18862 fill_window(s);
18863 while (s.lookahead >= MIN_MATCH$1) {
18864 str = s.strstart;
18865 n = s.lookahead - (MIN_MATCH$1 - 1);
18866 do {
18867 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
18868 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
18869
18870 s.prev[str & s.w_mask] = s.head[s.ins_h];
18871
18872 s.head[s.ins_h] = str;
18873 str++;
18874 } while (--n);
18875 s.strstart = str;
18876 s.lookahead = MIN_MATCH$1 - 1;
18877 fill_window(s);
18878 }
18879 s.strstart += s.lookahead;
18880 s.block_start = s.strstart;
18881 s.insert = s.lookahead;
18882 s.lookahead = 0;
18883 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18884 s.match_available = 0;
18885 strm.next_in = next;
18886 strm.input = input;
18887 strm.avail_in = avail;
18888 s.wrap = wrap;
18889 return Z_OK;
18890}
18891
18892/* Not implemented
18893exports.deflateBound = deflateBound;
18894exports.deflateCopy = deflateCopy;
18895exports.deflateParams = deflateParams;
18896exports.deflatePending = deflatePending;
18897exports.deflatePrime = deflatePrime;
18898exports.deflateTune = deflateTune;
18899*/
18900
18901// String encode/decode helpers
18902
18903try {
18904 String.fromCharCode.apply(null, [ 0 ]);
18905} catch (__) {
18906}
18907try {
18908 String.fromCharCode.apply(null, new Uint8Array(1));
18909} catch (__) {
18910}
18911
18912
18913// Table with utf8 lengths (calculated by first byte of sequence)
18914// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
18915// because max possible codepoint is 0x10ffff
18916const _utf8len = new Buf8(256);
18917for (let q = 0; q < 256; q++) {
18918 _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
18919}
18920_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
18921
18922
18923// convert string to array (typed, when possible)
18924function string2buf (str) {
18925 let c, c2, m_pos, i, buf_len = 0;
18926 const str_len = str.length;
18927
18928 // count binary size
18929 for (m_pos = 0; m_pos < str_len; m_pos++) {
18930 c = str.charCodeAt(m_pos);
18931 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18932 c2 = str.charCodeAt(m_pos + 1);
18933 if ((c2 & 0xfc00) === 0xdc00) {
18934 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18935 m_pos++;
18936 }
18937 }
18938 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
18939 }
18940
18941 // allocate buffer
18942 const buf = new Buf8(buf_len);
18943
18944 // convert
18945 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
18946 c = str.charCodeAt(m_pos);
18947 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18948 c2 = str.charCodeAt(m_pos + 1);
18949 if ((c2 & 0xfc00) === 0xdc00) {
18950 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18951 m_pos++;
18952 }
18953 }
18954 if (c < 0x80) {
18955 /* one byte */
18956 buf[i++] = c;
18957 } else if (c < 0x800) {
18958 /* two bytes */
18959 buf[i++] = 0xC0 | c >>> 6;
18960 buf[i++] = 0x80 | c & 0x3f;
18961 } else if (c < 0x10000) {
18962 /* three bytes */
18963 buf[i++] = 0xE0 | c >>> 12;
18964 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18965 buf[i++] = 0x80 | c & 0x3f;
18966 } else {
18967 /* four bytes */
18968 buf[i++] = 0xf0 | c >>> 18;
18969 buf[i++] = 0x80 | c >>> 12 & 0x3f;
18970 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18971 buf[i++] = 0x80 | c & 0x3f;
18972 }
18973 }
18974
18975 return buf;
18976}
18977
18978
18979// Convert binary string (typed, when possible)
18980function binstring2buf (str) {
18981 const buf = new Buf8(str.length);
18982 for (let i = 0, len = buf.length; i < len; i++) {
18983 buf[i] = str.charCodeAt(i);
18984 }
18985 return buf;
18986}
18987
18988// (C) 1995-2013 Jean-loup Gailly and Mark Adler
18989// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18990//
18991// This software is provided 'as-is', without any express or implied
18992// warranty. In no event will the authors be held liable for any damages
18993// arising from the use of this software.
18994//
18995// Permission is granted to anyone to use this software for any purpose,
18996// including commercial applications, and to alter it and redistribute it
18997// freely, subject to the following restrictions:
18998//
18999// 1. The origin of this software must not be misrepresented; you must not
19000// claim that you wrote the original software. If you use this software
19001// in a product, an acknowledgment in the product documentation would be
19002// appreciated but is not required.
19003// 2. Altered source versions must be plainly marked as such, and must not be
19004// misrepresented as being the original software.
19005// 3. This notice may not be removed or altered from any source distribution.
19006
19007class ZStream {
19008 constructor() {
19009 /* next input byte */
19010 this.input = null; // JS specific, because we have no pointers
19011 this.next_in = 0;
19012 /* number of bytes available at input */
19013 this.avail_in = 0;
19014 /* total number of input bytes read so far */
19015 this.total_in = 0;
19016 /* next output byte should be put there */
19017 this.output = null; // JS specific, because we have no pointers
19018 this.next_out = 0;
19019 /* remaining free space at output */
19020 this.avail_out = 0;
19021 /* total number of bytes output so far */
19022 this.total_out = 0;
19023 /* last error message, NULL if no error */
19024 this.msg = ''/*Z_NULL*/;
19025 /* not visible by applications */
19026 this.state = null;
19027 /* best guess about the data type: binary or text */
19028 this.data_type = 2/*Z_UNKNOWN*/;
19029 /* adler32 value of the uncompressed data */
19030 this.adler = 0;
19031 }
19032}
19033
19034/* ===========================================================================*/
19035
19036
19037/**
19038 * class Deflate
19039 *
19040 * Generic JS-style wrapper for zlib calls. If you don't need
19041 * streaming behaviour - use more simple functions: [[deflate]],
19042 * [[deflateRaw]] and [[gzip]].
19043 **/
19044
19045/* internal
19046 * Deflate.chunks -> Array
19047 *
19048 * Chunks of output data, if [[Deflate#onData]] not overridden.
19049 **/
19050
19051/**
19052 * Deflate.result -> Uint8Array|Array
19053 *
19054 * Compressed result, generated by default [[Deflate#onData]]
19055 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
19056 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
19057 * push a chunk with explicit flush (call [[Deflate#push]] with
19058 * `Z_SYNC_FLUSH` param).
19059 **/
19060
19061/**
19062 * Deflate.err -> Number
19063 *
19064 * Error code after deflate finished. 0 (Z_OK) on success.
19065 * You will not need it in real life, because deflate errors
19066 * are possible only on wrong options or bad `onData` / `onEnd`
19067 * custom handlers.
19068 **/
19069
19070/**
19071 * Deflate.msg -> String
19072 *
19073 * Error message, if [[Deflate.err]] != 0
19074 **/
19075
19076
19077/**
19078 * new Deflate(options)
19079 * - options (Object): zlib deflate options.
19080 *
19081 * Creates new deflator instance with specified params. Throws exception
19082 * on bad params. Supported options:
19083 *
19084 * - `level`
19085 * - `windowBits`
19086 * - `memLevel`
19087 * - `strategy`
19088 * - `dictionary`
19089 *
19090 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
19091 * for more information on these.
19092 *
19093 * Additional options, for internal needs:
19094 *
19095 * - `chunkSize` - size of generated data chunks (16K by default)
19096 * - `raw` (Boolean) - do raw deflate
19097 * - `gzip` (Boolean) - create gzip wrapper
19098 * - `to` (String) - if equal to 'string', then result will be "binary string"
19099 * (each char code [0..255])
19100 * - `header` (Object) - custom header for gzip
19101 * - `text` (Boolean) - true if compressed data believed to be text
19102 * - `time` (Number) - modification time, unix timestamp
19103 * - `os` (Number) - operation system code
19104 * - `extra` (Array) - array of bytes with extra data (max 65536)
19105 * - `name` (String) - file name (binary string)
19106 * - `comment` (String) - comment (binary string)
19107 * - `hcrc` (Boolean) - true if header crc should be added
19108 *
19109 * ##### Example:
19110 *
19111 * ```javascript
19112 * var pako = require('pako')
19113 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
19114 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
19115 *
19116 * var deflate = new pako.Deflate({ level: 3});
19117 *
19118 * deflate.push(chunk1, false);
19119 * deflate.push(chunk2, true); // true -> last chunk
19120 *
19121 * if (deflate.err) { throw new Error(deflate.err); }
19122 *
19123 * console.log(deflate.result);
19124 * ```
19125 **/
19126
19127class Deflate {
19128 constructor(options) {
19129 this.options = {
19130 level: Z_DEFAULT_COMPRESSION,
19131 method: Z_DEFLATED,
19132 chunkSize: 16384,
19133 windowBits: 15,
19134 memLevel: 8,
19135 strategy: Z_DEFAULT_STRATEGY,
19136 ...(options || {})
19137 };
19138
19139 const opt = this.options;
19140
19141 if (opt.raw && (opt.windowBits > 0)) {
19142 opt.windowBits = -opt.windowBits;
19143 }
19144
19145 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
19146 opt.windowBits += 16;
19147 }
19148
19149 this.err = 0; // error code, if happens (0 = Z_OK)
19150 this.msg = ''; // error message
19151 this.ended = false; // used to avoid multiple onEnd() calls
19152 this.chunks = []; // chunks of compressed data
19153
19154 this.strm = new ZStream();
19155 this.strm.avail_out = 0;
19156
19157 var status = deflateInit2(
19158 this.strm,
19159 opt.level,
19160 opt.method,
19161 opt.windowBits,
19162 opt.memLevel,
19163 opt.strategy
19164 );
19165
19166 if (status !== Z_OK) {
19167 throw new Error(msg[status]);
19168 }
19169
19170 if (opt.header) {
19171 deflateSetHeader(this.strm, opt.header);
19172 }
19173
19174 if (opt.dictionary) {
19175 let dict;
19176 // Convert data if needed
19177 if (typeof opt.dictionary === 'string') {
19178 // If we need to compress text, change encoding to utf8.
19179 dict = string2buf(opt.dictionary);
19180 } else if (opt.dictionary instanceof ArrayBuffer) {
19181 dict = new Uint8Array(opt.dictionary);
19182 } else {
19183 dict = opt.dictionary;
19184 }
19185
19186 status = deflateSetDictionary(this.strm, dict);
19187
19188 if (status !== Z_OK) {
19189 throw new Error(msg[status]);
19190 }
19191
19192 this._dict_set = true;
19193 }
19194 }
19195
19196 /**
19197 * Deflate#push(data[, mode]) -> Boolean
19198 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
19199 * converted to utf8 byte sequence.
19200 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
19201 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
19202 *
19203 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
19204 * new compressed chunks. Returns `true` on success. The last data block must have
19205 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
19206 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
19207 * can use mode Z_SYNC_FLUSH, keeping the compression context.
19208 *
19209 * On fail call [[Deflate#onEnd]] with error code and return false.
19210 *
19211 * We strongly recommend to use `Uint8Array` on input for best speed (output
19212 * array format is detected automatically). Also, don't skip last param and always
19213 * use the same type in your code (boolean or number). That will improve JS speed.
19214 *
19215 * For regular `Array`-s make sure all elements are [0..255].
19216 *
19217 * ##### Example
19218 *
19219 * ```javascript
19220 * push(chunk, false); // push one of data chunks
19221 * ...
19222 * push(chunk, true); // push last chunk
19223 * ```
19224 **/
19225 push(data, mode) {
19226 const { strm, options: { chunkSize } } = this;
19227 var status, _mode;
19228
19229 if (this.ended) { return false; }
19230
19231 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
19232
19233 // Convert data if needed
19234 if (typeof data === 'string') {
19235 // If we need to compress text, change encoding to utf8.
19236 strm.input = string2buf(data);
19237 } else if (data instanceof ArrayBuffer) {
19238 strm.input = new Uint8Array(data);
19239 } else {
19240 strm.input = data;
19241 }
19242
19243 strm.next_in = 0;
19244 strm.avail_in = strm.input.length;
19245
19246 do {
19247 if (strm.avail_out === 0) {
19248 strm.output = new Buf8(chunkSize);
19249 strm.next_out = 0;
19250 strm.avail_out = chunkSize;
19251 }
19252 status = deflate(strm, _mode); /* no bad return value */
19253
19254 if (status !== Z_STREAM_END && status !== Z_OK) {
19255 this.onEnd(status);
19256 this.ended = true;
19257 return false;
19258 }
19259 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
19260 this.onData(shrinkBuf(strm.output, strm.next_out));
19261 }
19262 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
19263
19264 // Finalize on the last chunk.
19265 if (_mode === Z_FINISH) {
19266 status = deflateEnd(this.strm);
19267 this.onEnd(status);
19268 this.ended = true;
19269 return status === Z_OK;
19270 }
19271
19272 // callback interim results if Z_SYNC_FLUSH.
19273 if (_mode === Z_SYNC_FLUSH) {
19274 this.onEnd(Z_OK);
19275 strm.avail_out = 0;
19276 return true;
19277 }
19278
19279 return true;
19280 };
19281 /**
19282 * Deflate#onData(chunk) -> Void
19283 * - chunk (Uint8Array|Array|String): output data. Type of array depends
19284 * on js engine support. When string output requested, each chunk
19285 * will be string.
19286 *
19287 * By default, stores data blocks in `chunks[]` property and glue
19288 * those in `onEnd`. Override this handler, if you need another behaviour.
19289 **/
19290 onData(chunk) {
19291 this.chunks.push(chunk);
19292 };
19293
19294 /**
19295 * Deflate#onEnd(status) -> Void
19296 * - status (Number): deflate status. 0 (Z_OK) on success,
19297 * other if not.
19298 *
19299 * Called once after you tell deflate that the input stream is
19300 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
19301 * or if an error happened. By default - join collected chunks,
19302 * free memory and fill `results` / `err` properties.
19303 **/
19304 onEnd(status) {
19305 // On success - join
19306 if (status === Z_OK) {
19307 this.result = flattenChunks(this.chunks);
19308 }
19309 this.chunks = [];
19310 this.err = status;
19311 this.msg = this.strm.msg;
19312 };
19313}
19314
19315// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19316// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19317//
19318// This software is provided 'as-is', without any express or implied
19319// warranty. In no event will the authors be held liable for any damages
19320// arising from the use of this software.
19321//
19322// Permission is granted to anyone to use this software for any purpose,
19323// including commercial applications, and to alter it and redistribute it
19324// freely, subject to the following restrictions:
19325//
19326// 1. The origin of this software must not be misrepresented; you must not
19327// claim that you wrote the original software. If you use this software
19328// in a product, an acknowledgment in the product documentation would be
19329// appreciated but is not required.
19330// 2. Altered source versions must be plainly marked as such, and must not be
19331// misrepresented as being the original software.
19332// 3. This notice may not be removed or altered from any source distribution.
19333
19334// See state defs from inflate.js
19335const BAD = 30; /* got a data error -- remain here until reset */
19336const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
19337
19338/*
19339 Decode literal, length, and distance codes and write out the resulting
19340 literal and match bytes until either not enough input or output is
19341 available, an end-of-block is encountered, or a data error is encountered.
19342 When large enough input and output buffers are supplied to inflate(), for
19343 example, a 16K input buffer and a 64K output buffer, more than 95% of the
19344 inflate execution time is spent in this routine.
19345
19346 Entry assumptions:
19347
19348 state.mode === LEN
19349 strm.avail_in >= 6
19350 strm.avail_out >= 258
19351 start >= strm.avail_out
19352 state.bits < 8
19353
19354 On return, state.mode is one of:
19355
19356 LEN -- ran out of enough output space or enough available input
19357 TYPE -- reached end of block code, inflate() to interpret next block
19358 BAD -- error in block data
19359
19360 Notes:
19361
19362 - The maximum input bits used by a length/distance pair is 15 bits for the
19363 length code, 5 bits for the length extra, 15 bits for the distance code,
19364 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
19365 Therefore if strm.avail_in >= 6, then there is enough input to avoid
19366 checking for available input while decoding.
19367
19368 - The maximum bytes that a single length/distance pair can output is 258
19369 bytes, which is the maximum length that can be coded. inflate_fast()
19370 requires strm.avail_out >= 258 for each loop to avoid checking for
19371 output space.
19372 */
19373function inflate_fast(strm, start) {
19374 let _in; /* local strm.input */
19375 let _out; /* local strm.output */
19376 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
19377 let hold; /* local strm.hold */
19378 let bits; /* local strm.bits */
19379 let here; /* retrieved table entry */
19380 let op; /* code bits, operation, extra bits, or */
19381 /* window position, window bytes to copy */
19382 let len; /* match length, unused bytes */
19383 let dist; /* match distance */
19384 let from; /* where to copy match from */
19385 let from_source;
19386
19387
19388
19389 /* copy state to local variables */
19390 const state = strm.state;
19391 //here = state.here;
19392 _in = strm.next_in;
19393 const input = strm.input;
19394 const last = _in + (strm.avail_in - 5);
19395 _out = strm.next_out;
19396 const output = strm.output;
19397 const beg = _out - (start - strm.avail_out);
19398 const end = _out + (strm.avail_out - 257);
19399 //#ifdef INFLATE_STRICT
19400 const dmax = state.dmax;
19401 //#endif
19402 const wsize = state.wsize;
19403 const whave = state.whave;
19404 const wnext = state.wnext;
19405 const s_window = state.window;
19406 hold = state.hold;
19407 bits = state.bits;
19408 const lcode = state.lencode;
19409 const dcode = state.distcode;
19410 const lmask = (1 << state.lenbits) - 1;
19411 const dmask = (1 << state.distbits) - 1;
19412
19413
19414 /* decode literals and length/distances until end-of-block or not enough
19415 input data or output space */
19416
19417 top:
19418 do {
19419 if (bits < 15) {
19420 hold += input[_in++] << bits;
19421 bits += 8;
19422 hold += input[_in++] << bits;
19423 bits += 8;
19424 }
19425
19426 here = lcode[hold & lmask];
19427
19428 dolen:
19429 for (;;) { // Goto emulation
19430 op = here >>> 24/*here.bits*/;
19431 hold >>>= op;
19432 bits -= op;
19433 op = here >>> 16 & 0xff/*here.op*/;
19434 if (op === 0) { /* literal */
19435 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
19436 // "inflate: literal '%c'\n" :
19437 // "inflate: literal 0x%02x\n", here.val));
19438 output[_out++] = here & 0xffff/*here.val*/;
19439 } else if (op & 16) { /* length base */
19440 len = here & 0xffff/*here.val*/;
19441 op &= 15; /* number of extra bits */
19442 if (op) {
19443 if (bits < op) {
19444 hold += input[_in++] << bits;
19445 bits += 8;
19446 }
19447 len += hold & (1 << op) - 1;
19448 hold >>>= op;
19449 bits -= op;
19450 }
19451 //Tracevv((stderr, "inflate: length %u\n", len));
19452 if (bits < 15) {
19453 hold += input[_in++] << bits;
19454 bits += 8;
19455 hold += input[_in++] << bits;
19456 bits += 8;
19457 }
19458 here = dcode[hold & dmask];
19459
19460 dodist:
19461 for (;;) { // goto emulation
19462 op = here >>> 24/*here.bits*/;
19463 hold >>>= op;
19464 bits -= op;
19465 op = here >>> 16 & 0xff/*here.op*/;
19466
19467 if (op & 16) { /* distance base */
19468 dist = here & 0xffff/*here.val*/;
19469 op &= 15; /* number of extra bits */
19470 if (bits < op) {
19471 hold += input[_in++] << bits;
19472 bits += 8;
19473 if (bits < op) {
19474 hold += input[_in++] << bits;
19475 bits += 8;
19476 }
19477 }
19478 dist += hold & (1 << op) - 1;
19479 //#ifdef INFLATE_STRICT
19480 if (dist > dmax) {
19481 strm.msg = "invalid distance too far back";
19482 state.mode = BAD;
19483 break top;
19484 }
19485 //#endif
19486 hold >>>= op;
19487 bits -= op;
19488 //Tracevv((stderr, "inflate: distance %u\n", dist));
19489 op = _out - beg; /* max distance in output */
19490 if (dist > op) { /* see if copy from window */
19491 op = dist - op; /* distance back in window */
19492 if (op > whave) {
19493 if (state.sane) {
19494 strm.msg = "invalid distance too far back";
19495 state.mode = BAD;
19496 break top;
19497 }
19498
19499 // (!) This block is disabled in zlib defaults,
19500 // don't enable it for binary compatibility
19501 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
19502 // if (len <= op - whave) {
19503 // do {
19504 // output[_out++] = 0;
19505 // } while (--len);
19506 // continue top;
19507 // }
19508 // len -= op - whave;
19509 // do {
19510 // output[_out++] = 0;
19511 // } while (--op > whave);
19512 // if (op === 0) {
19513 // from = _out - dist;
19514 // do {
19515 // output[_out++] = output[from++];
19516 // } while (--len);
19517 // continue top;
19518 // }
19519 //#endif
19520 }
19521 from = 0; // window index
19522 from_source = s_window;
19523 if (wnext === 0) { /* very common case */
19524 from += wsize - op;
19525 if (op < len) { /* some from window */
19526 len -= op;
19527 do {
19528 output[_out++] = s_window[from++];
19529 } while (--op);
19530 from = _out - dist; /* rest from output */
19531 from_source = output;
19532 }
19533 } else if (wnext < op) { /* wrap around window */
19534 from += wsize + wnext - op;
19535 op -= wnext;
19536 if (op < len) { /* some from end of window */
19537 len -= op;
19538 do {
19539 output[_out++] = s_window[from++];
19540 } while (--op);
19541 from = 0;
19542 if (wnext < len) { /* some from start of window */
19543 op = wnext;
19544 len -= op;
19545 do {
19546 output[_out++] = s_window[from++];
19547 } while (--op);
19548 from = _out - dist; /* rest from output */
19549 from_source = output;
19550 }
19551 }
19552 } else { /* contiguous in window */
19553 from += wnext - op;
19554 if (op < len) { /* some from window */
19555 len -= op;
19556 do {
19557 output[_out++] = s_window[from++];
19558 } while (--op);
19559 from = _out - dist; /* rest from output */
19560 from_source = output;
19561 }
19562 }
19563 while (len > 2) {
19564 output[_out++] = from_source[from++];
19565 output[_out++] = from_source[from++];
19566 output[_out++] = from_source[from++];
19567 len -= 3;
19568 }
19569 if (len) {
19570 output[_out++] = from_source[from++];
19571 if (len > 1) {
19572 output[_out++] = from_source[from++];
19573 }
19574 }
19575 } else {
19576 from = _out - dist; /* copy direct from output */
19577 do { /* minimum length is three */
19578 output[_out++] = output[from++];
19579 output[_out++] = output[from++];
19580 output[_out++] = output[from++];
19581 len -= 3;
19582 } while (len > 2);
19583 if (len) {
19584 output[_out++] = output[from++];
19585 if (len > 1) {
19586 output[_out++] = output[from++];
19587 }
19588 }
19589 }
19590 } else if ((op & 64) === 0) { /* 2nd level distance code */
19591 here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19592 continue dodist;
19593 } else {
19594 strm.msg = "invalid distance code";
19595 state.mode = BAD;
19596 break top;
19597 }
19598
19599 break; // need to emulate goto via "continue"
19600 }
19601 } else if ((op & 64) === 0) { /* 2nd level length code */
19602 here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19603 continue dolen;
19604 } else if (op & 32) { /* end-of-block */
19605 //Tracevv((stderr, "inflate: end of block\n"));
19606 state.mode = TYPE;
19607 break top;
19608 } else {
19609 strm.msg = "invalid literal/length code";
19610 state.mode = BAD;
19611 break top;
19612 }
19613
19614 break; // need to emulate goto via "continue"
19615 }
19616 } while (_in < last && _out < end);
19617
19618 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
19619 len = bits >> 3;
19620 _in -= len;
19621 bits -= len << 3;
19622 hold &= (1 << bits) - 1;
19623
19624 /* update state and return */
19625 strm.next_in = _in;
19626 strm.next_out = _out;
19627 strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
19628 strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
19629 state.hold = hold;
19630 state.bits = bits;
19631 return;
19632}
19633
19634const MAXBITS = 15;
19635const ENOUGH_LENS = 852;
19636const ENOUGH_DISTS = 592;
19637//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
19638
19639const CODES = 0;
19640const LENS = 1;
19641const DISTS = 2;
19642
19643const lbase = [ /* Length codes 257..285 base */
19644 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
19645 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
19646];
19647
19648const lext = [ /* Length codes 257..285 extra */
19649 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19650 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
19651];
19652
19653const dbase = [ /* Distance codes 0..29 base */
19654 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
19655 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
19656 8193, 12289, 16385, 24577, 0, 0
19657];
19658
19659const dext = [ /* Distance codes 0..29 extra */
19660 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
19661 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
19662 28, 28, 29, 29, 64, 64
19663];
19664
19665function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
19666 const bits = opts.bits;
19667 //here = opts.here; /* table entry for duplication */
19668
19669 let len = 0; /* a code's length in bits */
19670 let sym = 0; /* index of code symbols */
19671 let min = 0, max = 0; /* minimum and maximum code lengths */
19672 let root = 0; /* number of index bits for root table */
19673 let curr = 0; /* number of index bits for current table */
19674 let drop = 0; /* code bits to drop for sub-table */
19675 let left = 0; /* number of prefix codes available */
19676 let used = 0; /* code entries in table used */
19677 let huff = 0; /* Huffman code */
19678 let incr; /* for incrementing code, index */
19679 let fill; /* index for replicating entries */
19680 let low; /* low bits for current root entry */
19681 let next; /* next available space in table */
19682 let base = null; /* base value table to use */
19683 let base_index = 0;
19684 // var shoextra; /* extra bits table to use */
19685 let end; /* use base and extra for symbol > end */
19686 const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
19687 const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
19688 let extra = null;
19689 let extra_index = 0;
19690
19691 let here_bits, here_op, here_val;
19692
19693 /*
19694 Process a set of code lengths to create a canonical Huffman code. The
19695 code lengths are lens[0..codes-1]. Each length corresponds to the
19696 symbols 0..codes-1. The Huffman code is generated by first sorting the
19697 symbols by length from short to long, and retaining the symbol order
19698 for codes with equal lengths. Then the code starts with all zero bits
19699 for the first code of the shortest length, and the codes are integer
19700 increments for the same length, and zeros are appended as the length
19701 increases. For the deflate format, these bits are stored backwards
19702 from their more natural integer increment ordering, and so when the
19703 decoding tables are built in the large loop below, the integer codes
19704 are incremented backwards.
19705
19706 This routine assumes, but does not check, that all of the entries in
19707 lens[] are in the range 0..MAXBITS. The caller must assure this.
19708 1..MAXBITS is interpreted as that code length. zero means that that
19709 symbol does not occur in this code.
19710
19711 The codes are sorted by computing a count of codes for each length,
19712 creating from that a table of starting indices for each length in the
19713 sorted table, and then entering the symbols in order in the sorted
19714 table. The sorted table is work[], with that space being provided by
19715 the caller.
19716
19717 The length counts are used for other purposes as well, i.e. finding
19718 the minimum and maximum length codes, determining if there are any
19719 codes at all, checking for a valid set of lengths, and looking ahead
19720 at length counts to determine sub-table sizes when building the
19721 decoding tables.
19722 */
19723
19724 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
19725 for (len = 0; len <= MAXBITS; len++) {
19726 count[len] = 0;
19727 }
19728 for (sym = 0; sym < codes; sym++) {
19729 count[lens[lens_index + sym]]++;
19730 }
19731
19732 /* bound code lengths, force root to be within code lengths */
19733 root = bits;
19734 for (max = MAXBITS; max >= 1; max--) {
19735 if (count[max] !== 0) {
19736 break;
19737 }
19738 }
19739 if (root > max) {
19740 root = max;
19741 }
19742 if (max === 0) { /* no symbols to code at all */
19743 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
19744 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
19745 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
19746 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19747
19748
19749 //table.op[opts.table_index] = 64;
19750 //table.bits[opts.table_index] = 1;
19751 //table.val[opts.table_index++] = 0;
19752 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19753
19754 opts.bits = 1;
19755 return 0; /* no symbols, but wait for decoding to report error */
19756 }
19757 for (min = 1; min < max; min++) {
19758 if (count[min] !== 0) {
19759 break;
19760 }
19761 }
19762 if (root < min) {
19763 root = min;
19764 }
19765
19766 /* check for an over-subscribed or incomplete set of lengths */
19767 left = 1;
19768 for (len = 1; len <= MAXBITS; len++) {
19769 left <<= 1;
19770 left -= count[len];
19771 if (left < 0) {
19772 return -1;
19773 } /* over-subscribed */
19774 }
19775 if (left > 0 && (type === CODES || max !== 1)) {
19776 return -1; /* incomplete set */
19777 }
19778
19779 /* generate offsets into symbol table for each length for sorting */
19780 offs[1] = 0;
19781 for (len = 1; len < MAXBITS; len++) {
19782 offs[len + 1] = offs[len] + count[len];
19783 }
19784
19785 /* sort symbols by length, by symbol order within each length */
19786 for (sym = 0; sym < codes; sym++) {
19787 if (lens[lens_index + sym] !== 0) {
19788 work[offs[lens[lens_index + sym]]++] = sym;
19789 }
19790 }
19791
19792 /*
19793 Create and fill in decoding tables. In this loop, the table being
19794 filled is at next and has curr index bits. The code being used is huff
19795 with length len. That code is converted to an index by dropping drop
19796 bits off of the bottom. For codes where len is less than drop + curr,
19797 those top drop + curr - len bits are incremented through all values to
19798 fill the table with replicated entries.
19799
19800 root is the number of index bits for the root table. When len exceeds
19801 root, sub-tables are created pointed to by the root entry with an index
19802 of the low root bits of huff. This is saved in low to check for when a
19803 new sub-table should be started. drop is zero when the root table is
19804 being filled, and drop is root when sub-tables are being filled.
19805
19806 When a new sub-table is needed, it is necessary to look ahead in the
19807 code lengths to determine what size sub-table is needed. The length
19808 counts are used for this, and so count[] is decremented as codes are
19809 entered in the tables.
19810
19811 used keeps track of how many table entries have been allocated from the
19812 provided *table space. It is checked for LENS and DIST tables against
19813 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
19814 the initial root table size constants. See the comments in inftrees.h
19815 for more information.
19816
19817 sym increments through all symbols, and the loop terminates when
19818 all codes of length max, i.e. all codes, have been processed. This
19819 routine permits incomplete codes, so another loop after this one fills
19820 in the rest of the decoding tables with invalid code markers.
19821 */
19822
19823 /* set up for code type */
19824 // poor man optimization - use if-else instead of switch,
19825 // to avoid deopts in old v8
19826 if (type === CODES) {
19827 base = extra = work; /* dummy value--not used */
19828 end = 19;
19829
19830 } else if (type === LENS) {
19831 base = lbase;
19832 base_index -= 257;
19833 extra = lext;
19834 extra_index -= 257;
19835 end = 256;
19836
19837 } else { /* DISTS */
19838 base = dbase;
19839 extra = dext;
19840 end = -1;
19841 }
19842
19843 /* initialize opts for loop */
19844 huff = 0; /* starting code */
19845 sym = 0; /* starting code symbol */
19846 len = min; /* starting code length */
19847 next = table_index; /* current table to fill in */
19848 curr = root; /* current table index bits */
19849 drop = 0; /* current bits to drop from code for index */
19850 low = -1; /* trigger new sub-table when len > root */
19851 used = 1 << root; /* use root table entries */
19852 const mask = used - 1; /* mask for comparing low */
19853
19854 /* check available table space */
19855 if (type === LENS && used > ENOUGH_LENS ||
19856 type === DISTS && used > ENOUGH_DISTS) {
19857 return 1;
19858 }
19859
19860 /* process all codes and make table entries */
19861 for (;;) {
19862 /* create table entry */
19863 here_bits = len - drop;
19864 if (work[sym] < end) {
19865 here_op = 0;
19866 here_val = work[sym];
19867 } else if (work[sym] > end) {
19868 here_op = extra[extra_index + work[sym]];
19869 here_val = base[base_index + work[sym]];
19870 } else {
19871 here_op = 32 + 64; /* end of block */
19872 here_val = 0;
19873 }
19874
19875 /* replicate for those indices with low len bits equal to huff */
19876 incr = 1 << len - drop;
19877 fill = 1 << curr;
19878 min = fill; /* save offset to next table */
19879 do {
19880 fill -= incr;
19881 table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;
19882 } while (fill !== 0);
19883
19884 /* backwards increment the len-bit code huff */
19885 incr = 1 << len - 1;
19886 while (huff & incr) {
19887 incr >>= 1;
19888 }
19889 if (incr !== 0) {
19890 huff &= incr - 1;
19891 huff += incr;
19892 } else {
19893 huff = 0;
19894 }
19895
19896 /* go to next symbol, update count, len */
19897 sym++;
19898 if (--count[len] === 0) {
19899 if (len === max) {
19900 break;
19901 }
19902 len = lens[lens_index + work[sym]];
19903 }
19904
19905 /* create new sub-table if needed */
19906 if (len > root && (huff & mask) !== low) {
19907 /* if first time, transition to sub-tables */
19908 if (drop === 0) {
19909 drop = root;
19910 }
19911
19912 /* increment past last table */
19913 next += min; /* here min is 1 << curr */
19914
19915 /* determine length of next table */
19916 curr = len - drop;
19917 left = 1 << curr;
19918 while (curr + drop < max) {
19919 left -= count[curr + drop];
19920 if (left <= 0) {
19921 break;
19922 }
19923 curr++;
19924 left <<= 1;
19925 }
19926
19927 /* check for enough space */
19928 used += 1 << curr;
19929 if (type === LENS && used > ENOUGH_LENS ||
19930 type === DISTS && used > ENOUGH_DISTS) {
19931 return 1;
19932 }
19933
19934 /* point entry in root table to sub-table */
19935 low = huff & mask;
19936 /*table.op[low] = curr;
19937 table.bits[low] = root;
19938 table.val[low] = next - opts.table_index;*/
19939 table[low] = root << 24 | curr << 16 | next - table_index |0;
19940 }
19941 }
19942
19943 /* fill in remaining table entry if code is incomplete (guaranteed to have
19944 at most one remaining entry, since if the code is incomplete, the
19945 maximum code length that was allowed to get this far is one bit) */
19946 if (huff !== 0) {
19947 //table.op[next + huff] = 64; /* invalid code marker */
19948 //table.bits[next + huff] = len - drop;
19949 //table.val[next + huff] = 0;
19950 table[next + huff] = len - drop << 24 | 64 << 16 |0;
19951 }
19952
19953 /* set return parameters */
19954 //opts.table_index += used;
19955 opts.bits = root;
19956 return 0;
19957}
19958
19959const CODES$1 = 0;
19960const LENS$1 = 1;
19961const DISTS$1 = 2;
19962
19963/* STATES ====================================================================*/
19964/* ===========================================================================*/
19965
19966
19967const HEAD = 1; /* i: waiting for magic header */
19968const FLAGS = 2; /* i: waiting for method and flags (gzip) */
19969const TIME = 3; /* i: waiting for modification time (gzip) */
19970const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
19971const EXLEN = 5; /* i: waiting for extra length (gzip) */
19972const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
19973const NAME = 7; /* i: waiting for end of file name (gzip) */
19974const COMMENT = 8; /* i: waiting for end of comment (gzip) */
19975const HCRC = 9; /* i: waiting for header crc (gzip) */
19976const DICTID = 10; /* i: waiting for dictionary check value */
19977const DICT = 11; /* waiting for inflateSetDictionary() call */
19978const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
19979const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
19980const STORED = 14; /* i: waiting for stored size (length and complement) */
19981const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
19982const COPY = 16; /* i/o: waiting for input or output to copy stored block */
19983const TABLE = 17; /* i: waiting for dynamic block table lengths */
19984const LENLENS = 18; /* i: waiting for code length code lengths */
19985const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
19986const LEN_ = 20; /* i: same as LEN below, but only first time in */
19987const LEN = 21; /* i: waiting for length/lit/eob code */
19988const LENEXT = 22; /* i: waiting for length extra bits */
19989const DIST = 23; /* i: waiting for distance code */
19990const DISTEXT = 24; /* i: waiting for distance extra bits */
19991const MATCH = 25; /* o: waiting for output space to copy string */
19992const LIT = 26; /* o: waiting for output space to write literal */
19993const CHECK = 27; /* i: waiting for 32-bit check value */
19994const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
19995const DONE = 29; /* finished check, done -- remain here until reset */
19996const BAD$1 = 30; /* got a data error -- remain here until reset */
19997//const MEM = 31; /* got an inflate() memory error -- remain here until reset */
19998const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
19999
20000/* ===========================================================================*/
20001
20002
20003
20004const ENOUGH_LENS$1 = 852;
20005const ENOUGH_DISTS$1 = 592;
20006
20007
20008function zswap32(q) {
20009 return (((q >>> 24) & 0xff) +
20010 ((q >>> 8) & 0xff00) +
20011 ((q & 0xff00) << 8) +
20012 ((q & 0xff) << 24));
20013}
20014
20015
20016class InflateState {
20017 constructor() {
20018 this.mode = 0; /* current inflate mode */
20019 this.last = false; /* true if processing last block */
20020 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
20021 this.havedict = false; /* true if dictionary provided */
20022 this.flags = 0; /* gzip header method and flags (0 if zlib) */
20023 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
20024 this.check = 0; /* protected copy of check value */
20025 this.total = 0; /* protected copy of output count */
20026 // TODO: may be {}
20027 this.head = null; /* where to save gzip header information */
20028
20029 /* sliding window */
20030 this.wbits = 0; /* log base 2 of requested window size */
20031 this.wsize = 0; /* window size or zero if not using window */
20032 this.whave = 0; /* valid bytes in the window */
20033 this.wnext = 0; /* window write index */
20034 this.window = null; /* allocated sliding window, if needed */
20035
20036 /* bit accumulator */
20037 this.hold = 0; /* input bit accumulator */
20038 this.bits = 0; /* number of bits in "in" */
20039
20040 /* for string and stored block copying */
20041 this.length = 0; /* literal or length of data to copy */
20042 this.offset = 0; /* distance back to copy string from */
20043
20044 /* for table and code decoding */
20045 this.extra = 0; /* extra bits needed */
20046
20047 /* fixed and dynamic code tables */
20048 this.lencode = null; /* starting table for length/literal codes */
20049 this.distcode = null; /* starting table for distance codes */
20050 this.lenbits = 0; /* index bits for lencode */
20051 this.distbits = 0; /* index bits for distcode */
20052
20053 /* dynamic table building */
20054 this.ncode = 0; /* number of code length code lengths */
20055 this.nlen = 0; /* number of length code lengths */
20056 this.ndist = 0; /* number of distance code lengths */
20057 this.have = 0; /* number of code lengths in lens[] */
20058 this.next = null; /* next available space in codes[] */
20059
20060 this.lens = new Buf16(320); /* temporary storage for code lengths */
20061 this.work = new Buf16(288); /* work area for code table building */
20062
20063 /*
20064 because we don't have pointers in js, we use lencode and distcode directly
20065 as buffers so we don't need codes
20066 */
20067 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
20068 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
20069 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
20070 this.sane = 0; /* if false, allow invalid distance too far */
20071 this.back = 0; /* bits back of last unprocessed length/lit */
20072 this.was = 0; /* initial length of match */
20073 }
20074}
20075
20076function inflateResetKeep(strm) {
20077 let state;
20078
20079 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20080 state = strm.state;
20081 strm.total_in = strm.total_out = state.total = 0;
20082 strm.msg = ''; /*Z_NULL*/
20083 if (state.wrap) { /* to support ill-conceived Java test suite */
20084 strm.adler = state.wrap & 1;
20085 }
20086 state.mode = HEAD;
20087 state.last = 0;
20088 state.havedict = 0;
20089 state.dmax = 32768;
20090 state.head = null/*Z_NULL*/;
20091 state.hold = 0;
20092 state.bits = 0;
20093 //state.lencode = state.distcode = state.next = state.codes;
20094 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
20095 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
20096
20097 state.sane = 1;
20098 state.back = -1;
20099 //Tracev((stderr, "inflate: reset\n"));
20100 return Z_OK;
20101}
20102
20103function inflateReset(strm) {
20104 let state;
20105
20106 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20107 state = strm.state;
20108 state.wsize = 0;
20109 state.whave = 0;
20110 state.wnext = 0;
20111 return inflateResetKeep(strm);
20112
20113}
20114
20115function inflateReset2(strm, windowBits) {
20116 let wrap;
20117 let state;
20118
20119 /* get the state */
20120 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20121 state = strm.state;
20122
20123 /* extract wrap request from windowBits parameter */
20124 if (windowBits < 0) {
20125 wrap = 0;
20126 windowBits = -windowBits;
20127 }
20128 else {
20129 wrap = (windowBits >> 4) + 1;
20130 if (windowBits < 48) {
20131 windowBits &= 15;
20132 }
20133 }
20134
20135 /* set number of window bits, free window if different */
20136 if (windowBits && (windowBits < 8 || windowBits > 15)) {
20137 return Z_STREAM_ERROR;
20138 }
20139 if (state.window !== null && state.wbits !== windowBits) {
20140 state.window = null;
20141 }
20142
20143 /* update state and reset the rest of it */
20144 state.wrap = wrap;
20145 state.wbits = windowBits;
20146 return inflateReset(strm);
20147}
20148
20149function inflateInit2(strm, windowBits) {
20150 let ret;
20151 let state;
20152
20153 if (!strm) { return Z_STREAM_ERROR; }
20154 //strm.msg = Z_NULL; /* in case we return an error */
20155
20156 state = new InflateState();
20157
20158 //if (state === Z_NULL) return Z_MEM_ERROR;
20159 //Tracev((stderr, "inflate: allocated\n"));
20160 strm.state = state;
20161 state.window = null/*Z_NULL*/;
20162 ret = inflateReset2(strm, windowBits);
20163 if (ret !== Z_OK) {
20164 strm.state = null/*Z_NULL*/;
20165 }
20166 return ret;
20167}
20168
20169
20170/*
20171 Return state with length and distance decoding tables and index sizes set to
20172 fixed code decoding. Normally this returns fixed tables from inffixed.h.
20173 If BUILDFIXED is defined, then instead this routine builds the tables the
20174 first time it's called, and returns those tables the first time and
20175 thereafter. This reduces the size of the code by about 2K bytes, in
20176 exchange for a little execution time. However, BUILDFIXED should not be
20177 used for threaded applications, since the rewriting of the tables and virgin
20178 may not be thread-safe.
20179 */
20180let virgin = true;
20181
20182let lenfix, distfix; // We have no pointers in JS, so keep tables separate
20183
20184function fixedtables(state) {
20185 /* build fixed huffman tables if first call (may not be thread safe) */
20186 if (virgin) {
20187 let sym;
20188
20189 lenfix = new Buf32(512);
20190 distfix = new Buf32(32);
20191
20192 /* literal/length table */
20193 sym = 0;
20194 while (sym < 144) { state.lens[sym++] = 8; }
20195 while (sym < 256) { state.lens[sym++] = 9; }
20196 while (sym < 280) { state.lens[sym++] = 7; }
20197 while (sym < 288) { state.lens[sym++] = 8; }
20198
20199 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
20200
20201 /* distance table */
20202 sym = 0;
20203 while (sym < 32) { state.lens[sym++] = 5; }
20204
20205 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
20206
20207 /* do this just once */
20208 virgin = false;
20209 }
20210
20211 state.lencode = lenfix;
20212 state.lenbits = 9;
20213 state.distcode = distfix;
20214 state.distbits = 5;
20215}
20216
20217
20218/*
20219 Update the window with the last wsize (normally 32K) bytes written before
20220 returning. If window does not exist yet, create it. This is only called
20221 when a window is already in use, or when output has been written during this
20222 inflate call, but the end of the deflate stream has not been reached yet.
20223 It is also called to create a window for dictionary data when a dictionary
20224 is loaded.
20225
20226 Providing output buffers larger than 32K to inflate() should provide a speed
20227 advantage, since only the last 32K of output is copied to the sliding window
20228 upon return from inflate(), and since all distances after the first 32K of
20229 output will fall in the output data, making match copies simpler and faster.
20230 The advantage may be dependent on the size of the processor's data caches.
20231 */
20232function updatewindow(strm, src, end, copy) {
20233 let dist;
20234 const state = strm.state;
20235
20236 /* if it hasn't been done already, allocate space for the window */
20237 if (state.window === null) {
20238 state.wsize = 1 << state.wbits;
20239 state.wnext = 0;
20240 state.whave = 0;
20241
20242 state.window = new Buf8(state.wsize);
20243 }
20244
20245 /* copy state->wsize or less output bytes into the circular window */
20246 if (copy >= state.wsize) {
20247 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
20248 state.wnext = 0;
20249 state.whave = state.wsize;
20250 }
20251 else {
20252 dist = state.wsize - state.wnext;
20253 if (dist > copy) {
20254 dist = copy;
20255 }
20256 //zmemcpy(state->window + state->wnext, end - copy, dist);
20257 arraySet(state.window, src, end - copy, dist, state.wnext);
20258 copy -= dist;
20259 if (copy) {
20260 //zmemcpy(state->window, end - copy, copy);
20261 arraySet(state.window, src, end - copy, copy, 0);
20262 state.wnext = copy;
20263 state.whave = state.wsize;
20264 }
20265 else {
20266 state.wnext += dist;
20267 if (state.wnext === state.wsize) { state.wnext = 0; }
20268 if (state.whave < state.wsize) { state.whave += dist; }
20269 }
20270 }
20271 return 0;
20272}
20273
20274function inflate(strm, flush) {
20275 let state;
20276 let input, output; // input/output buffers
20277 let next; /* next input INDEX */
20278 let put; /* next output INDEX */
20279 let have, left; /* available input and output */
20280 let hold; /* bit buffer */
20281 let bits; /* bits in bit buffer */
20282 let _in, _out; /* save starting available input and output */
20283 let copy; /* number of stored or match bytes to copy */
20284 let from; /* where to copy match bytes from */
20285 let from_source;
20286 let here = 0; /* current decoding table entry */
20287 let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
20288 //var last; /* parent table entry */
20289 let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
20290 let len; /* length to copy for repeats, bits to drop */
20291 let ret; /* return code */
20292 let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
20293 let opts;
20294
20295 let n; // temporary var for NEED_BITS
20296
20297 const order = /* permutation of code lengths */
20298 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
20299
20300
20301 if (!strm || !strm.state || !strm.output ||
20302 (!strm.input && strm.avail_in !== 0)) {
20303 return Z_STREAM_ERROR;
20304 }
20305
20306 state = strm.state;
20307 if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */
20308
20309
20310 //--- LOAD() ---
20311 put = strm.next_out;
20312 output = strm.output;
20313 left = strm.avail_out;
20314 next = strm.next_in;
20315 input = strm.input;
20316 have = strm.avail_in;
20317 hold = state.hold;
20318 bits = state.bits;
20319 //---
20320
20321 _in = have;
20322 _out = left;
20323 ret = Z_OK;
20324
20325 inf_leave: // goto emulation
20326 for (;;) {
20327 switch (state.mode) {
20328 case HEAD:
20329 if (state.wrap === 0) {
20330 state.mode = TYPEDO;
20331 break;
20332 }
20333 //=== NEEDBITS(16);
20334 while (bits < 16) {
20335 if (have === 0) { break inf_leave; }
20336 have--;
20337 hold += input[next++] << bits;
20338 bits += 8;
20339 }
20340 //===//
20341 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
20342 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
20343 //=== CRC2(state.check, hold);
20344 hbuf[0] = hold & 0xff;
20345 hbuf[1] = (hold >>> 8) & 0xff;
20346 state.check = crc32(state.check, hbuf, 2, 0);
20347 //===//
20348
20349 //=== INITBITS();
20350 hold = 0;
20351 bits = 0;
20352 //===//
20353 state.mode = FLAGS;
20354 break;
20355 }
20356 state.flags = 0; /* expect zlib header */
20357 if (state.head) {
20358 state.head.done = false;
20359 }
20360 if (!(state.wrap & 1) || /* check if zlib header allowed */
20361 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
20362 strm.msg = 'incorrect header check';
20363 state.mode = BAD$1;
20364 break;
20365 }
20366 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
20367 strm.msg = 'unknown compression method';
20368 state.mode = BAD$1;
20369 break;
20370 }
20371 //--- DROPBITS(4) ---//
20372 hold >>>= 4;
20373 bits -= 4;
20374 //---//
20375 len = (hold & 0x0f)/*BITS(4)*/ + 8;
20376 if (state.wbits === 0) {
20377 state.wbits = len;
20378 }
20379 else if (len > state.wbits) {
20380 strm.msg = 'invalid window size';
20381 state.mode = BAD$1;
20382 break;
20383 }
20384 state.dmax = 1 << len;
20385 //Tracev((stderr, "inflate: zlib header ok\n"));
20386 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20387 state.mode = hold & 0x200 ? DICTID : TYPE$1;
20388 //=== INITBITS();
20389 hold = 0;
20390 bits = 0;
20391 //===//
20392 break;
20393 case FLAGS:
20394 //=== NEEDBITS(16); */
20395 while (bits < 16) {
20396 if (have === 0) { break inf_leave; }
20397 have--;
20398 hold += input[next++] << bits;
20399 bits += 8;
20400 }
20401 //===//
20402 state.flags = hold;
20403 if ((state.flags & 0xff) !== Z_DEFLATED) {
20404 strm.msg = 'unknown compression method';
20405 state.mode = BAD$1;
20406 break;
20407 }
20408 if (state.flags & 0xe000) {
20409 strm.msg = 'unknown header flags set';
20410 state.mode = BAD$1;
20411 break;
20412 }
20413 if (state.head) {
20414 state.head.text = ((hold >> 8) & 1);
20415 }
20416 if (state.flags & 0x0200) {
20417 //=== CRC2(state.check, hold);
20418 hbuf[0] = hold & 0xff;
20419 hbuf[1] = (hold >>> 8) & 0xff;
20420 state.check = crc32(state.check, hbuf, 2, 0);
20421 //===//
20422 }
20423 //=== INITBITS();
20424 hold = 0;
20425 bits = 0;
20426 //===//
20427 state.mode = TIME;
20428 /* falls through */
20429 case TIME:
20430 //=== NEEDBITS(32); */
20431 while (bits < 32) {
20432 if (have === 0) { break inf_leave; }
20433 have--;
20434 hold += input[next++] << bits;
20435 bits += 8;
20436 }
20437 //===//
20438 if (state.head) {
20439 state.head.time = hold;
20440 }
20441 if (state.flags & 0x0200) {
20442 //=== CRC4(state.check, hold)
20443 hbuf[0] = hold & 0xff;
20444 hbuf[1] = (hold >>> 8) & 0xff;
20445 hbuf[2] = (hold >>> 16) & 0xff;
20446 hbuf[3] = (hold >>> 24) & 0xff;
20447 state.check = crc32(state.check, hbuf, 4, 0);
20448 //===
20449 }
20450 //=== INITBITS();
20451 hold = 0;
20452 bits = 0;
20453 //===//
20454 state.mode = OS;
20455 /* falls through */
20456 case OS:
20457 //=== NEEDBITS(16); */
20458 while (bits < 16) {
20459 if (have === 0) { break inf_leave; }
20460 have--;
20461 hold += input[next++] << bits;
20462 bits += 8;
20463 }
20464 //===//
20465 if (state.head) {
20466 state.head.xflags = (hold & 0xff);
20467 state.head.os = (hold >> 8);
20468 }
20469 if (state.flags & 0x0200) {
20470 //=== CRC2(state.check, hold);
20471 hbuf[0] = hold & 0xff;
20472 hbuf[1] = (hold >>> 8) & 0xff;
20473 state.check = crc32(state.check, hbuf, 2, 0);
20474 //===//
20475 }
20476 //=== INITBITS();
20477 hold = 0;
20478 bits = 0;
20479 //===//
20480 state.mode = EXLEN;
20481 /* falls through */
20482 case EXLEN:
20483 if (state.flags & 0x0400) {
20484 //=== NEEDBITS(16); */
20485 while (bits < 16) {
20486 if (have === 0) { break inf_leave; }
20487 have--;
20488 hold += input[next++] << bits;
20489 bits += 8;
20490 }
20491 //===//
20492 state.length = hold;
20493 if (state.head) {
20494 state.head.extra_len = hold;
20495 }
20496 if (state.flags & 0x0200) {
20497 //=== CRC2(state.check, hold);
20498 hbuf[0] = hold & 0xff;
20499 hbuf[1] = (hold >>> 8) & 0xff;
20500 state.check = crc32(state.check, hbuf, 2, 0);
20501 //===//
20502 }
20503 //=== INITBITS();
20504 hold = 0;
20505 bits = 0;
20506 //===//
20507 }
20508 else if (state.head) {
20509 state.head.extra = null/*Z_NULL*/;
20510 }
20511 state.mode = EXTRA;
20512 /* falls through */
20513 case EXTRA:
20514 if (state.flags & 0x0400) {
20515 copy = state.length;
20516 if (copy > have) { copy = have; }
20517 if (copy) {
20518 if (state.head) {
20519 len = state.head.extra_len - state.length;
20520 if (!state.head.extra) {
20521 // Use untyped array for more convenient processing later
20522 state.head.extra = new Array(state.head.extra_len);
20523 }
20524 arraySet(
20525 state.head.extra,
20526 input,
20527 next,
20528 // extra field is limited to 65536 bytes
20529 // - no need for additional size check
20530 copy,
20531 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
20532 len
20533 );
20534 //zmemcpy(state.head.extra + len, next,
20535 // len + copy > state.head.extra_max ?
20536 // state.head.extra_max - len : copy);
20537 }
20538 if (state.flags & 0x0200) {
20539 state.check = crc32(state.check, input, copy, next);
20540 }
20541 have -= copy;
20542 next += copy;
20543 state.length -= copy;
20544 }
20545 if (state.length) { break inf_leave; }
20546 }
20547 state.length = 0;
20548 state.mode = NAME;
20549 /* falls through */
20550 case NAME:
20551 if (state.flags & 0x0800) {
20552 if (have === 0) { break inf_leave; }
20553 copy = 0;
20554 do {
20555 // TODO: 2 or 1 bytes?
20556 len = input[next + copy++];
20557 /* use constant limit because in js we should not preallocate memory */
20558 if (state.head && len &&
20559 (state.length < 65536 /*state.head.name_max*/)) {
20560 state.head.name += String.fromCharCode(len);
20561 }
20562 } while (len && copy < have);
20563
20564 if (state.flags & 0x0200) {
20565 state.check = crc32(state.check, input, copy, next);
20566 }
20567 have -= copy;
20568 next += copy;
20569 if (len) { break inf_leave; }
20570 }
20571 else if (state.head) {
20572 state.head.name = null;
20573 }
20574 state.length = 0;
20575 state.mode = COMMENT;
20576 /* falls through */
20577 case COMMENT:
20578 if (state.flags & 0x1000) {
20579 if (have === 0) { break inf_leave; }
20580 copy = 0;
20581 do {
20582 len = input[next + copy++];
20583 /* use constant limit because in js we should not preallocate memory */
20584 if (state.head && len &&
20585 (state.length < 65536 /*state.head.comm_max*/)) {
20586 state.head.comment += String.fromCharCode(len);
20587 }
20588 } while (len && copy < have);
20589 if (state.flags & 0x0200) {
20590 state.check = crc32(state.check, input, copy, next);
20591 }
20592 have -= copy;
20593 next += copy;
20594 if (len) { break inf_leave; }
20595 }
20596 else if (state.head) {
20597 state.head.comment = null;
20598 }
20599 state.mode = HCRC;
20600 /* falls through */
20601 case HCRC:
20602 if (state.flags & 0x0200) {
20603 //=== NEEDBITS(16); */
20604 while (bits < 16) {
20605 if (have === 0) { break inf_leave; }
20606 have--;
20607 hold += input[next++] << bits;
20608 bits += 8;
20609 }
20610 //===//
20611 if (hold !== (state.check & 0xffff)) {
20612 strm.msg = 'header crc mismatch';
20613 state.mode = BAD$1;
20614 break;
20615 }
20616 //=== INITBITS();
20617 hold = 0;
20618 bits = 0;
20619 //===//
20620 }
20621 if (state.head) {
20622 state.head.hcrc = ((state.flags >> 9) & 1);
20623 state.head.done = true;
20624 }
20625 strm.adler = state.check = 0;
20626 state.mode = TYPE$1;
20627 break;
20628 case DICTID:
20629 //=== NEEDBITS(32); */
20630 while (bits < 32) {
20631 if (have === 0) { break inf_leave; }
20632 have--;
20633 hold += input[next++] << bits;
20634 bits += 8;
20635 }
20636 //===//
20637 strm.adler = state.check = zswap32(hold);
20638 //=== INITBITS();
20639 hold = 0;
20640 bits = 0;
20641 //===//
20642 state.mode = DICT;
20643 /* falls through */
20644 case DICT:
20645 if (state.havedict === 0) {
20646 //--- RESTORE() ---
20647 strm.next_out = put;
20648 strm.avail_out = left;
20649 strm.next_in = next;
20650 strm.avail_in = have;
20651 state.hold = hold;
20652 state.bits = bits;
20653 //---
20654 return Z_NEED_DICT;
20655 }
20656 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20657 state.mode = TYPE$1;
20658 /* falls through */
20659 case TYPE$1:
20660 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
20661 /* falls through */
20662 case TYPEDO:
20663 if (state.last) {
20664 //--- BYTEBITS() ---//
20665 hold >>>= bits & 7;
20666 bits -= bits & 7;
20667 //---//
20668 state.mode = CHECK;
20669 break;
20670 }
20671 //=== NEEDBITS(3); */
20672 while (bits < 3) {
20673 if (have === 0) { break inf_leave; }
20674 have--;
20675 hold += input[next++] << bits;
20676 bits += 8;
20677 }
20678 //===//
20679 state.last = (hold & 0x01)/*BITS(1)*/;
20680 //--- DROPBITS(1) ---//
20681 hold >>>= 1;
20682 bits -= 1;
20683 //---//
20684
20685 switch ((hold & 0x03)/*BITS(2)*/) {
20686 case 0: /* stored block */
20687 //Tracev((stderr, "inflate: stored block%s\n",
20688 // state.last ? " (last)" : ""));
20689 state.mode = STORED;
20690 break;
20691 case 1: /* fixed block */
20692 fixedtables(state);
20693 //Tracev((stderr, "inflate: fixed codes block%s\n",
20694 // state.last ? " (last)" : ""));
20695 state.mode = LEN_; /* decode codes */
20696 if (flush === Z_TREES) {
20697 //--- DROPBITS(2) ---//
20698 hold >>>= 2;
20699 bits -= 2;
20700 //---//
20701 break inf_leave;
20702 }
20703 break;
20704 case 2: /* dynamic block */
20705 //Tracev((stderr, "inflate: dynamic codes block%s\n",
20706 // state.last ? " (last)" : ""));
20707 state.mode = TABLE;
20708 break;
20709 case 3:
20710 strm.msg = 'invalid block type';
20711 state.mode = BAD$1;
20712 }
20713 //--- DROPBITS(2) ---//
20714 hold >>>= 2;
20715 bits -= 2;
20716 //---//
20717 break;
20718 case STORED:
20719 //--- BYTEBITS() ---// /* go to byte boundary */
20720 hold >>>= bits & 7;
20721 bits -= bits & 7;
20722 //---//
20723 //=== NEEDBITS(32); */
20724 while (bits < 32) {
20725 if (have === 0) { break inf_leave; }
20726 have--;
20727 hold += input[next++] << bits;
20728 bits += 8;
20729 }
20730 //===//
20731 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
20732 strm.msg = 'invalid stored block lengths';
20733 state.mode = BAD$1;
20734 break;
20735 }
20736 state.length = hold & 0xffff;
20737 //Tracev((stderr, "inflate: stored length %u\n",
20738 // state.length));
20739 //=== INITBITS();
20740 hold = 0;
20741 bits = 0;
20742 //===//
20743 state.mode = COPY_;
20744 if (flush === Z_TREES) { break inf_leave; }
20745 /* falls through */
20746 case COPY_:
20747 state.mode = COPY;
20748 /* falls through */
20749 case COPY:
20750 copy = state.length;
20751 if (copy) {
20752 if (copy > have) { copy = have; }
20753 if (copy > left) { copy = left; }
20754 if (copy === 0) { break inf_leave; }
20755 //--- zmemcpy(put, next, copy); ---
20756 arraySet(output, input, next, copy, put);
20757 //---//
20758 have -= copy;
20759 next += copy;
20760 left -= copy;
20761 put += copy;
20762 state.length -= copy;
20763 break;
20764 }
20765 //Tracev((stderr, "inflate: stored end\n"));
20766 state.mode = TYPE$1;
20767 break;
20768 case TABLE:
20769 //=== NEEDBITS(14); */
20770 while (bits < 14) {
20771 if (have === 0) { break inf_leave; }
20772 have--;
20773 hold += input[next++] << bits;
20774 bits += 8;
20775 }
20776 //===//
20777 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
20778 //--- DROPBITS(5) ---//
20779 hold >>>= 5;
20780 bits -= 5;
20781 //---//
20782 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
20783 //--- DROPBITS(5) ---//
20784 hold >>>= 5;
20785 bits -= 5;
20786 //---//
20787 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
20788 //--- DROPBITS(4) ---//
20789 hold >>>= 4;
20790 bits -= 4;
20791 //---//
20792//#ifndef PKZIP_BUG_WORKAROUND
20793 if (state.nlen > 286 || state.ndist > 30) {
20794 strm.msg = 'too many length or distance symbols';
20795 state.mode = BAD$1;
20796 break;
20797 }
20798//#endif
20799 //Tracev((stderr, "inflate: table sizes ok\n"));
20800 state.have = 0;
20801 state.mode = LENLENS;
20802 /* falls through */
20803 case LENLENS:
20804 while (state.have < state.ncode) {
20805 //=== NEEDBITS(3);
20806 while (bits < 3) {
20807 if (have === 0) { break inf_leave; }
20808 have--;
20809 hold += input[next++] << bits;
20810 bits += 8;
20811 }
20812 //===//
20813 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
20814 //--- DROPBITS(3) ---//
20815 hold >>>= 3;
20816 bits -= 3;
20817 //---//
20818 }
20819 while (state.have < 19) {
20820 state.lens[order[state.have++]] = 0;
20821 }
20822 // We have separate tables & no pointers. 2 commented lines below not needed.
20823 //state.next = state.codes;
20824 //state.lencode = state.next;
20825 // Switch to use dynamic table
20826 state.lencode = state.lendyn;
20827 state.lenbits = 7;
20828
20829 opts = { bits: state.lenbits };
20830 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
20831 state.lenbits = opts.bits;
20832
20833 if (ret) {
20834 strm.msg = 'invalid code lengths set';
20835 state.mode = BAD$1;
20836 break;
20837 }
20838 //Tracev((stderr, "inflate: code lengths ok\n"));
20839 state.have = 0;
20840 state.mode = CODELENS;
20841 /* falls through */
20842 case CODELENS:
20843 while (state.have < state.nlen + state.ndist) {
20844 for (;;) {
20845 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
20846 here_bits = here >>> 24;
20847 here_op = (here >>> 16) & 0xff;
20848 here_val = here & 0xffff;
20849
20850 if ((here_bits) <= bits) { break; }
20851 //--- PULLBYTE() ---//
20852 if (have === 0) { break inf_leave; }
20853 have--;
20854 hold += input[next++] << bits;
20855 bits += 8;
20856 //---//
20857 }
20858 if (here_val < 16) {
20859 //--- DROPBITS(here.bits) ---//
20860 hold >>>= here_bits;
20861 bits -= here_bits;
20862 //---//
20863 state.lens[state.have++] = here_val;
20864 }
20865 else {
20866 if (here_val === 16) {
20867 //=== NEEDBITS(here.bits + 2);
20868 n = here_bits + 2;
20869 while (bits < n) {
20870 if (have === 0) { break inf_leave; }
20871 have--;
20872 hold += input[next++] << bits;
20873 bits += 8;
20874 }
20875 //===//
20876 //--- DROPBITS(here.bits) ---//
20877 hold >>>= here_bits;
20878 bits -= here_bits;
20879 //---//
20880 if (state.have === 0) {
20881 strm.msg = 'invalid bit length repeat';
20882 state.mode = BAD$1;
20883 break;
20884 }
20885 len = state.lens[state.have - 1];
20886 copy = 3 + (hold & 0x03);//BITS(2);
20887 //--- DROPBITS(2) ---//
20888 hold >>>= 2;
20889 bits -= 2;
20890 //---//
20891 }
20892 else if (here_val === 17) {
20893 //=== NEEDBITS(here.bits + 3);
20894 n = here_bits + 3;
20895 while (bits < n) {
20896 if (have === 0) { break inf_leave; }
20897 have--;
20898 hold += input[next++] << bits;
20899 bits += 8;
20900 }
20901 //===//
20902 //--- DROPBITS(here.bits) ---//
20903 hold >>>= here_bits;
20904 bits -= here_bits;
20905 //---//
20906 len = 0;
20907 copy = 3 + (hold & 0x07);//BITS(3);
20908 //--- DROPBITS(3) ---//
20909 hold >>>= 3;
20910 bits -= 3;
20911 //---//
20912 }
20913 else {
20914 //=== NEEDBITS(here.bits + 7);
20915 n = here_bits + 7;
20916 while (bits < n) {
20917 if (have === 0) { break inf_leave; }
20918 have--;
20919 hold += input[next++] << bits;
20920 bits += 8;
20921 }
20922 //===//
20923 //--- DROPBITS(here.bits) ---//
20924 hold >>>= here_bits;
20925 bits -= here_bits;
20926 //---//
20927 len = 0;
20928 copy = 11 + (hold & 0x7f);//BITS(7);
20929 //--- DROPBITS(7) ---//
20930 hold >>>= 7;
20931 bits -= 7;
20932 //---//
20933 }
20934 if (state.have + copy > state.nlen + state.ndist) {
20935 strm.msg = 'invalid bit length repeat';
20936 state.mode = BAD$1;
20937 break;
20938 }
20939 while (copy--) {
20940 state.lens[state.have++] = len;
20941 }
20942 }
20943 }
20944
20945 /* handle error breaks in while */
20946 if (state.mode === BAD$1) { break; }
20947
20948 /* check for end-of-block code (better have one) */
20949 if (state.lens[256] === 0) {
20950 strm.msg = 'invalid code -- missing end-of-block';
20951 state.mode = BAD$1;
20952 break;
20953 }
20954
20955 /* build code tables -- note: do not change the lenbits or distbits
20956 values here (9 and 6) without reading the comments in inftrees.h
20957 concerning the ENOUGH constants, which depend on those values */
20958 state.lenbits = 9;
20959
20960 opts = { bits: state.lenbits };
20961 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
20962 // We have separate tables & no pointers. 2 commented lines below not needed.
20963 // state.next_index = opts.table_index;
20964 state.lenbits = opts.bits;
20965 // state.lencode = state.next;
20966
20967 if (ret) {
20968 strm.msg = 'invalid literal/lengths set';
20969 state.mode = BAD$1;
20970 break;
20971 }
20972
20973 state.distbits = 6;
20974 //state.distcode.copy(state.codes);
20975 // Switch to use dynamic table
20976 state.distcode = state.distdyn;
20977 opts = { bits: state.distbits };
20978 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
20979 // We have separate tables & no pointers. 2 commented lines below not needed.
20980 // state.next_index = opts.table_index;
20981 state.distbits = opts.bits;
20982 // state.distcode = state.next;
20983
20984 if (ret) {
20985 strm.msg = 'invalid distances set';
20986 state.mode = BAD$1;
20987 break;
20988 }
20989 //Tracev((stderr, 'inflate: codes ok\n'));
20990 state.mode = LEN_;
20991 if (flush === Z_TREES) { break inf_leave; }
20992 /* falls through */
20993 case LEN_:
20994 state.mode = LEN;
20995 /* falls through */
20996 case LEN:
20997 if (have >= 6 && left >= 258) {
20998 //--- RESTORE() ---
20999 strm.next_out = put;
21000 strm.avail_out = left;
21001 strm.next_in = next;
21002 strm.avail_in = have;
21003 state.hold = hold;
21004 state.bits = bits;
21005 //---
21006 inflate_fast(strm, _out);
21007 //--- LOAD() ---
21008 put = strm.next_out;
21009 output = strm.output;
21010 left = strm.avail_out;
21011 next = strm.next_in;
21012 input = strm.input;
21013 have = strm.avail_in;
21014 hold = state.hold;
21015 bits = state.bits;
21016 //---
21017
21018 if (state.mode === TYPE$1) {
21019 state.back = -1;
21020 }
21021 break;
21022 }
21023 state.back = 0;
21024 for (;;) {
21025 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
21026 here_bits = here >>> 24;
21027 here_op = (here >>> 16) & 0xff;
21028 here_val = here & 0xffff;
21029
21030 if (here_bits <= bits) { break; }
21031 //--- PULLBYTE() ---//
21032 if (have === 0) { break inf_leave; }
21033 have--;
21034 hold += input[next++] << bits;
21035 bits += 8;
21036 //---//
21037 }
21038 if (here_op && (here_op & 0xf0) === 0) {
21039 last_bits = here_bits;
21040 last_op = here_op;
21041 last_val = here_val;
21042 for (;;) {
21043 here = state.lencode[last_val +
21044 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21045 here_bits = here >>> 24;
21046 here_op = (here >>> 16) & 0xff;
21047 here_val = here & 0xffff;
21048
21049 if ((last_bits + here_bits) <= bits) { break; }
21050 //--- PULLBYTE() ---//
21051 if (have === 0) { break inf_leave; }
21052 have--;
21053 hold += input[next++] << bits;
21054 bits += 8;
21055 //---//
21056 }
21057 //--- DROPBITS(last.bits) ---//
21058 hold >>>= last_bits;
21059 bits -= last_bits;
21060 //---//
21061 state.back += last_bits;
21062 }
21063 //--- DROPBITS(here.bits) ---//
21064 hold >>>= here_bits;
21065 bits -= here_bits;
21066 //---//
21067 state.back += here_bits;
21068 state.length = here_val;
21069 if (here_op === 0) {
21070 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
21071 // "inflate: literal '%c'\n" :
21072 // "inflate: literal 0x%02x\n", here.val));
21073 state.mode = LIT;
21074 break;
21075 }
21076 if (here_op & 32) {
21077 //Tracevv((stderr, "inflate: end of block\n"));
21078 state.back = -1;
21079 state.mode = TYPE$1;
21080 break;
21081 }
21082 if (here_op & 64) {
21083 strm.msg = 'invalid literal/length code';
21084 state.mode = BAD$1;
21085 break;
21086 }
21087 state.extra = here_op & 15;
21088 state.mode = LENEXT;
21089 /* falls through */
21090 case LENEXT:
21091 if (state.extra) {
21092 //=== NEEDBITS(state.extra);
21093 n = state.extra;
21094 while (bits < n) {
21095 if (have === 0) { break inf_leave; }
21096 have--;
21097 hold += input[next++] << bits;
21098 bits += 8;
21099 }
21100 //===//
21101 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21102 //--- DROPBITS(state.extra) ---//
21103 hold >>>= state.extra;
21104 bits -= state.extra;
21105 //---//
21106 state.back += state.extra;
21107 }
21108 //Tracevv((stderr, "inflate: length %u\n", state.length));
21109 state.was = state.length;
21110 state.mode = DIST;
21111 /* falls through */
21112 case DIST:
21113 for (;;) {
21114 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
21115 here_bits = here >>> 24;
21116 here_op = (here >>> 16) & 0xff;
21117 here_val = here & 0xffff;
21118
21119 if ((here_bits) <= bits) { break; }
21120 //--- PULLBYTE() ---//
21121 if (have === 0) { break inf_leave; }
21122 have--;
21123 hold += input[next++] << bits;
21124 bits += 8;
21125 //---//
21126 }
21127 if ((here_op & 0xf0) === 0) {
21128 last_bits = here_bits;
21129 last_op = here_op;
21130 last_val = here_val;
21131 for (;;) {
21132 here = state.distcode[last_val +
21133 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21134 here_bits = here >>> 24;
21135 here_op = (here >>> 16) & 0xff;
21136 here_val = here & 0xffff;
21137
21138 if ((last_bits + here_bits) <= bits) { break; }
21139 //--- PULLBYTE() ---//
21140 if (have === 0) { break inf_leave; }
21141 have--;
21142 hold += input[next++] << bits;
21143 bits += 8;
21144 //---//
21145 }
21146 //--- DROPBITS(last.bits) ---//
21147 hold >>>= last_bits;
21148 bits -= last_bits;
21149 //---//
21150 state.back += last_bits;
21151 }
21152 //--- DROPBITS(here.bits) ---//
21153 hold >>>= here_bits;
21154 bits -= here_bits;
21155 //---//
21156 state.back += here_bits;
21157 if (here_op & 64) {
21158 strm.msg = 'invalid distance code';
21159 state.mode = BAD$1;
21160 break;
21161 }
21162 state.offset = here_val;
21163 state.extra = (here_op) & 15;
21164 state.mode = DISTEXT;
21165 /* falls through */
21166 case DISTEXT:
21167 if (state.extra) {
21168 //=== NEEDBITS(state.extra);
21169 n = state.extra;
21170 while (bits < n) {
21171 if (have === 0) { break inf_leave; }
21172 have--;
21173 hold += input[next++] << bits;
21174 bits += 8;
21175 }
21176 //===//
21177 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21178 //--- DROPBITS(state.extra) ---//
21179 hold >>>= state.extra;
21180 bits -= state.extra;
21181 //---//
21182 state.back += state.extra;
21183 }
21184//#ifdef INFLATE_STRICT
21185 if (state.offset > state.dmax) {
21186 strm.msg = 'invalid distance too far back';
21187 state.mode = BAD$1;
21188 break;
21189 }
21190//#endif
21191 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
21192 state.mode = MATCH;
21193 /* falls through */
21194 case MATCH:
21195 if (left === 0) { break inf_leave; }
21196 copy = _out - left;
21197 if (state.offset > copy) { /* copy from window */
21198 copy = state.offset - copy;
21199 if (copy > state.whave) {
21200 if (state.sane) {
21201 strm.msg = 'invalid distance too far back';
21202 state.mode = BAD$1;
21203 break;
21204 }
21205// (!) This block is disabled in zlib defaults,
21206// don't enable it for binary compatibility
21207//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
21208// Trace((stderr, "inflate.c too far\n"));
21209// copy -= state.whave;
21210// if (copy > state.length) { copy = state.length; }
21211// if (copy > left) { copy = left; }
21212// left -= copy;
21213// state.length -= copy;
21214// do {
21215// output[put++] = 0;
21216// } while (--copy);
21217// if (state.length === 0) { state.mode = LEN; }
21218// break;
21219//#endif
21220 }
21221 if (copy > state.wnext) {
21222 copy -= state.wnext;
21223 from = state.wsize - copy;
21224 }
21225 else {
21226 from = state.wnext - copy;
21227 }
21228 if (copy > state.length) { copy = state.length; }
21229 from_source = state.window;
21230 }
21231 else { /* copy from output */
21232 from_source = output;
21233 from = put - state.offset;
21234 copy = state.length;
21235 }
21236 if (copy > left) { copy = left; }
21237 left -= copy;
21238 state.length -= copy;
21239 do {
21240 output[put++] = from_source[from++];
21241 } while (--copy);
21242 if (state.length === 0) { state.mode = LEN; }
21243 break;
21244 case LIT:
21245 if (left === 0) { break inf_leave; }
21246 output[put++] = state.length;
21247 left--;
21248 state.mode = LEN;
21249 break;
21250 case CHECK:
21251 if (state.wrap) {
21252 //=== NEEDBITS(32);
21253 while (bits < 32) {
21254 if (have === 0) { break inf_leave; }
21255 have--;
21256 // Use '|' instead of '+' to make sure that result is signed
21257 hold |= input[next++] << bits;
21258 bits += 8;
21259 }
21260 //===//
21261 _out -= left;
21262 strm.total_out += _out;
21263 state.total += _out;
21264 if (_out) {
21265 strm.adler = state.check =
21266 /*UPDATE(state.check, put - _out, _out);*/
21267 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
21268
21269 }
21270 _out = left;
21271 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
21272 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
21273 strm.msg = 'incorrect data check';
21274 state.mode = BAD$1;
21275 break;
21276 }
21277 //=== INITBITS();
21278 hold = 0;
21279 bits = 0;
21280 //===//
21281 //Tracev((stderr, "inflate: check matches trailer\n"));
21282 }
21283 state.mode = LENGTH;
21284 /* falls through */
21285 case LENGTH:
21286 if (state.wrap && state.flags) {
21287 //=== NEEDBITS(32);
21288 while (bits < 32) {
21289 if (have === 0) { break inf_leave; }
21290 have--;
21291 hold += input[next++] << bits;
21292 bits += 8;
21293 }
21294 //===//
21295 if (hold !== (state.total & 0xffffffff)) {
21296 strm.msg = 'incorrect length check';
21297 state.mode = BAD$1;
21298 break;
21299 }
21300 //=== INITBITS();
21301 hold = 0;
21302 bits = 0;
21303 //===//
21304 //Tracev((stderr, "inflate: length matches trailer\n"));
21305 }
21306 state.mode = DONE;
21307 /* falls through */
21308 case DONE:
21309 ret = Z_STREAM_END;
21310 break inf_leave;
21311 case BAD$1:
21312 ret = Z_DATA_ERROR;
21313 break inf_leave;
21314 // case MEM:
21315 // return Z_MEM_ERROR;
21316 case SYNC:
21317 /* falls through */
21318 default:
21319 return Z_STREAM_ERROR;
21320 }
21321 }
21322
21323 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
21324
21325 /*
21326 Return from inflate(), updating the total counts and the check value.
21327 If there was no progress during the inflate() call, return a buffer
21328 error. Call updatewindow() to create and/or update the window state.
21329 Note: a memory error from inflate() is non-recoverable.
21330 */
21331
21332 //--- RESTORE() ---
21333 strm.next_out = put;
21334 strm.avail_out = left;
21335 strm.next_in = next;
21336 strm.avail_in = have;
21337 state.hold = hold;
21338 state.bits = bits;
21339 //---
21340
21341 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
21342 (state.mode < CHECK || flush !== Z_FINISH))) {
21343 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
21344 }
21345 _in -= strm.avail_in;
21346 _out -= strm.avail_out;
21347 strm.total_in += _in;
21348 strm.total_out += _out;
21349 state.total += _out;
21350 if (state.wrap && _out) {
21351 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
21352 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
21353 }
21354 strm.data_type = state.bits + (state.last ? 64 : 0) +
21355 (state.mode === TYPE$1 ? 128 : 0) +
21356 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
21357 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
21358 ret = Z_BUF_ERROR;
21359 }
21360 return ret;
21361}
21362
21363function inflateEnd(strm) {
21364
21365 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
21366 return Z_STREAM_ERROR;
21367 }
21368
21369 const state = strm.state;
21370 if (state.window) {
21371 state.window = null;
21372 }
21373 strm.state = null;
21374 return Z_OK;
21375}
21376
21377function inflateGetHeader(strm, head) {
21378 let state;
21379
21380 /* check state */
21381 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
21382 state = strm.state;
21383 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
21384
21385 /* save header structure */
21386 state.head = head;
21387 head.done = false;
21388 return Z_OK;
21389}
21390
21391function inflateSetDictionary(strm, dictionary) {
21392 const dictLength = dictionary.length;
21393
21394 let state;
21395 let dictid;
21396
21397 /* check state */
21398 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
21399 state = strm.state;
21400
21401 if (state.wrap !== 0 && state.mode !== DICT) {
21402 return Z_STREAM_ERROR;
21403 }
21404
21405 /* check for correct dictionary identifier */
21406 if (state.mode === DICT) {
21407 dictid = 1; /* adler32(0, null, 0)*/
21408 /* dictid = adler32(dictid, dictionary, dictLength); */
21409 dictid = adler32(dictid, dictionary, dictLength, 0);
21410 if (dictid !== state.check) {
21411 return Z_DATA_ERROR;
21412 }
21413 }
21414 /* copy dictionary to window using updatewindow(), which will amend the
21415 existing dictionary if appropriate */
21416 updatewindow(strm, dictionary, dictLength, dictLength);
21417 // if (ret) {
21418 // state.mode = MEM;
21419 // return Z_MEM_ERROR;
21420 // }
21421 state.havedict = 1;
21422 // Tracev((stderr, "inflate: dictionary set\n"));
21423 return Z_OK;
21424}
21425
21426/* Not implemented
21427exports.inflateCopy = inflateCopy;
21428exports.inflateGetDictionary = inflateGetDictionary;
21429exports.inflateMark = inflateMark;
21430exports.inflatePrime = inflatePrime;
21431exports.inflateSync = inflateSync;
21432exports.inflateSyncPoint = inflateSyncPoint;
21433exports.inflateUndermine = inflateUndermine;
21434*/
21435
21436// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21437// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21438//
21439// This software is provided 'as-is', without any express or implied
21440// warranty. In no event will the authors be held liable for any damages
21441// arising from the use of this software.
21442//
21443// Permission is granted to anyone to use this software for any purpose,
21444// including commercial applications, and to alter it and redistribute it
21445// freely, subject to the following restrictions:
21446//
21447// 1. The origin of this software must not be misrepresented; you must not
21448// claim that you wrote the original software. If you use this software
21449// in a product, an acknowledgment in the product documentation would be
21450// appreciated but is not required.
21451// 2. Altered source versions must be plainly marked as such, and must not be
21452// misrepresented as being the original software.
21453// 3. This notice may not be removed or altered from any source distribution.
21454
21455class GZheader {
21456 constructor() {
21457 /* true if compressed data believed to be text */
21458 this.text = 0;
21459 /* modification time */
21460 this.time = 0;
21461 /* extra flags (not used when writing a gzip file) */
21462 this.xflags = 0;
21463 /* operating system */
21464 this.os = 0;
21465 /* pointer to extra field or Z_NULL if none */
21466 this.extra = null;
21467 /* extra field length (valid if extra != Z_NULL) */
21468 this.extra_len = 0; // Actually, we don't need it in JS,
21469 // but leave for few code modifications
21470
21471 //
21472 // Setup limits is not necessary because in js we should not preallocate memory
21473 // for inflate use constant limit in 65536 bytes
21474 //
21475
21476 /* space at extra (only when reading header) */
21477 // this.extra_max = 0;
21478 /* pointer to zero-terminated file name or Z_NULL */
21479 this.name = '';
21480 /* space at name (only when reading header) */
21481 // this.name_max = 0;
21482 /* pointer to zero-terminated comment or Z_NULL */
21483 this.comment = '';
21484 /* space at comment (only when reading header) */
21485 // this.comm_max = 0;
21486 /* true if there was or will be a header crc */
21487 this.hcrc = 0;
21488 /* true when done reading gzip header (not used when writing a gzip file) */
21489 this.done = false;
21490 }
21491}
21492
21493/**
21494 * class Inflate
21495 *
21496 * Generic JS-style wrapper for zlib calls. If you don't need
21497 * streaming behaviour - use more simple functions: [[inflate]]
21498 * and [[inflateRaw]].
21499 **/
21500
21501/* internal
21502 * inflate.chunks -> Array
21503 *
21504 * Chunks of output data, if [[Inflate#onData]] not overridden.
21505 **/
21506
21507/**
21508 * Inflate.result -> Uint8Array|Array|String
21509 *
21510 * Uncompressed result, generated by default [[Inflate#onData]]
21511 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
21512 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
21513 * push a chunk with explicit flush (call [[Inflate#push]] with
21514 * `Z_SYNC_FLUSH` param).
21515 **/
21516
21517/**
21518 * Inflate.err -> Number
21519 *
21520 * Error code after inflate finished. 0 (Z_OK) on success.
21521 * Should be checked if broken data possible.
21522 **/
21523
21524/**
21525 * Inflate.msg -> String
21526 *
21527 * Error message, if [[Inflate.err]] != 0
21528 **/
21529
21530
21531/**
21532 * new Inflate(options)
21533 * - options (Object): zlib inflate options.
21534 *
21535 * Creates new inflator instance with specified params. Throws exception
21536 * on bad params. Supported options:
21537 *
21538 * - `windowBits`
21539 * - `dictionary`
21540 *
21541 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
21542 * for more information on these.
21543 *
21544 * Additional options, for internal needs:
21545 *
21546 * - `chunkSize` - size of generated data chunks (16K by default)
21547 * - `raw` (Boolean) - do raw inflate
21548 * - `to` (String) - if equal to 'string', then result will be converted
21549 * from utf8 to utf16 (javascript) string. When string output requested,
21550 * chunk length can differ from `chunkSize`, depending on content.
21551 *
21552 * By default, when no options set, autodetect deflate/gzip data format via
21553 * wrapper header.
21554 *
21555 * ##### Example:
21556 *
21557 * ```javascript
21558 * var pako = require('pako')
21559 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
21560 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
21561 *
21562 * var inflate = new pako.Inflate({ level: 3});
21563 *
21564 * inflate.push(chunk1, false);
21565 * inflate.push(chunk2, true); // true -> last chunk
21566 *
21567 * if (inflate.err) { throw new Error(inflate.err); }
21568 *
21569 * console.log(inflate.result);
21570 * ```
21571 **/
21572class Inflate {
21573 constructor(options) {
21574 this.options = {
21575 chunkSize: 16384,
21576 windowBits: 0,
21577 ...(options || {})
21578 };
21579
21580 const opt = this.options;
21581
21582 // Force window size for `raw` data, if not set directly,
21583 // because we have no header for autodetect.
21584 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
21585 opt.windowBits = -opt.windowBits;
21586 if (opt.windowBits === 0) { opt.windowBits = -15; }
21587 }
21588
21589 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
21590 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
21591 !(options && options.windowBits)) {
21592 opt.windowBits += 32;
21593 }
21594
21595 // Gzip header has no info about windows size, we can do autodetect only
21596 // for deflate. So, if window size not set, force it to max when gzip possible
21597 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
21598 // bit 3 (16) -> gzipped data
21599 // bit 4 (32) -> autodetect gzip/deflate
21600 if ((opt.windowBits & 15) === 0) {
21601 opt.windowBits |= 15;
21602 }
21603 }
21604
21605 this.err = 0; // error code, if happens (0 = Z_OK)
21606 this.msg = ''; // error message
21607 this.ended = false; // used to avoid multiple onEnd() calls
21608 this.chunks = []; // chunks of compressed data
21609
21610 this.strm = new ZStream();
21611 this.strm.avail_out = 0;
21612
21613 let status = inflateInit2(
21614 this.strm,
21615 opt.windowBits
21616 );
21617
21618 if (status !== Z_OK) {
21619 throw new Error(msg[status]);
21620 }
21621
21622 this.header = new GZheader();
21623
21624 inflateGetHeader(this.strm, this.header);
21625
21626 // Setup dictionary
21627 if (opt.dictionary) {
21628 // Convert data if needed
21629 if (typeof opt.dictionary === 'string') {
21630 opt.dictionary = string2buf(opt.dictionary);
21631 } else if (opt.dictionary instanceof ArrayBuffer) {
21632 opt.dictionary = new Uint8Array(opt.dictionary);
21633 }
21634 if (opt.raw) { //In raw mode we need to set the dictionary early
21635 status = inflateSetDictionary(this.strm, opt.dictionary);
21636 if (status !== Z_OK) {
21637 throw new Error(msg[status]);
21638 }
21639 }
21640 }
21641 }
21642 /**
21643 * Inflate#push(data[, mode]) -> Boolean
21644 * - data (Uint8Array|Array|ArrayBuffer|String): input data
21645 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
21646 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
21647 *
21648 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
21649 * new output chunks. Returns `true` on success. The last data block must have
21650 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
21651 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
21652 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
21653 *
21654 * On fail call [[Inflate#onEnd]] with error code and return false.
21655 *
21656 * We strongly recommend to use `Uint8Array` on input for best speed (output
21657 * format is detected automatically). Also, don't skip last param and always
21658 * use the same type in your code (boolean or number). That will improve JS speed.
21659 *
21660 * For regular `Array`-s make sure all elements are [0..255].
21661 *
21662 * ##### Example
21663 *
21664 * ```javascript
21665 * push(chunk, false); // push one of data chunks
21666 * ...
21667 * push(chunk, true); // push last chunk
21668 * ```
21669 **/
21670 push(data, mode) {
21671 const { strm, options: { chunkSize, dictionary } } = this;
21672 let status, _mode;
21673
21674 // Flag to properly process Z_BUF_ERROR on testing inflate call
21675 // when we check that all output data was flushed.
21676 let allowBufError = false;
21677
21678 if (this.ended) { return false; }
21679 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
21680
21681 // Convert data if needed
21682 if (typeof data === 'string') {
21683 // Only binary strings can be decompressed on practice
21684 strm.input = binstring2buf(data);
21685 } else if (data instanceof ArrayBuffer) {
21686 strm.input = new Uint8Array(data);
21687 } else {
21688 strm.input = data;
21689 }
21690
21691 strm.next_in = 0;
21692 strm.avail_in = strm.input.length;
21693
21694 do {
21695 if (strm.avail_out === 0) {
21696 strm.output = new Buf8(chunkSize);
21697 strm.next_out = 0;
21698 strm.avail_out = chunkSize;
21699 }
21700
21701 status = inflate(strm, Z_NO_FLUSH); /* no bad return value */
21702
21703 if (status === Z_NEED_DICT && dictionary) {
21704 status = inflateSetDictionary(this.strm, dictionary);
21705 }
21706
21707 if (status === Z_BUF_ERROR && allowBufError === true) {
21708 status = Z_OK;
21709 allowBufError = false;
21710 }
21711
21712 if (status !== Z_STREAM_END && status !== Z_OK) {
21713 this.onEnd(status);
21714 this.ended = true;
21715 return false;
21716 }
21717
21718 if (strm.next_out) {
21719 if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
21720 this.onData(shrinkBuf(strm.output, strm.next_out));
21721 }
21722 }
21723
21724 // When no more input data, we should check that internal inflate buffers
21725 // are flushed. The only way to do it when avail_out = 0 - run one more
21726 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
21727 // Here we set flag to process this error properly.
21728 //
21729 // NOTE. Deflate does not return error in this case and does not needs such
21730 // logic.
21731 if (strm.avail_in === 0 && strm.avail_out === 0) {
21732 allowBufError = true;
21733 }
21734
21735 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
21736
21737 if (status === Z_STREAM_END) {
21738 _mode = Z_FINISH;
21739 }
21740
21741 // Finalize on the last chunk.
21742 if (_mode === Z_FINISH) {
21743 status = inflateEnd(this.strm);
21744 this.onEnd(status);
21745 this.ended = true;
21746 return status === Z_OK;
21747 }
21748
21749 // callback interim results if Z_SYNC_FLUSH.
21750 if (_mode === Z_SYNC_FLUSH) {
21751 this.onEnd(Z_OK);
21752 strm.avail_out = 0;
21753 return true;
21754 }
21755
21756 return true;
21757 };
21758
21759 /**
21760 * Inflate#onData(chunk) -> Void
21761 * - chunk (Uint8Array|Array|String): output data. Type of array depends
21762 * on js engine support. When string output requested, each chunk
21763 * will be string.
21764 *
21765 * By default, stores data blocks in `chunks[]` property and glue
21766 * those in `onEnd`. Override this handler, if you need another behaviour.
21767 **/
21768 onData(chunk) {
21769 this.chunks.push(chunk);
21770 };
21771
21772
21773
21774 /**
21775 * Inflate#onEnd(status) -> Void
21776 * - status (Number): inflate status. 0 (Z_OK) on success,
21777 * other if not.
21778 *
21779 * Called either after you tell inflate that the input stream is
21780 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
21781 * or if an error happened. By default - join collected chunks,
21782 * free memory and fill `results` / `err` properties.
21783 **/
21784 onEnd(status) {
21785 // On success - join
21786 if (status === Z_OK) {
21787 this.result = flattenChunks(this.chunks);
21788 }
21789 this.chunks = [];
21790 this.err = status;
21791 this.msg = this.strm.msg;
21792 };
21793}
21794
21795/*
21796node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
21797
21798Copyright (C) 2012 Eli Skeggs
21799
21800This library is free software; you can redistribute it and/or
21801modify it under the terms of the GNU Lesser General Public
21802License as published by the Free Software Foundation; either
21803version 2.1 of the License, or (at your option) any later version.
21804
21805This library is distributed in the hope that it will be useful,
21806but WITHOUT ANY WARRANTY; without even the implied warranty of
21807MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21808Lesser General Public License for more details.
21809
21810You should have received a copy of the GNU Lesser General Public
21811License along with this library; if not, see
21812http://www.gnu.org/licenses/lgpl-2.1.html
21813
21814Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
21815
21816Based on micro-bunzip by Rob Landley (rob@landley.net).
21817
21818Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21819which also acknowledges contributions by Mike Burrows, David Wheeler,
21820Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21821Robert Sedgewick, and Jon L. Bentley.
21822*/
21823
21824var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
21825
21826// offset in bytes
21827var BitReader = function(stream) {
21828 this.stream = stream;
21829 this.bitOffset = 0;
21830 this.curByte = 0;
21831 this.hasByte = false;
21832};
21833
21834BitReader.prototype._ensureByte = function() {
21835 if (!this.hasByte) {
21836 this.curByte = this.stream.readByte();
21837 this.hasByte = true;
21838 }
21839};
21840
21841// reads bits from the buffer
21842BitReader.prototype.read = function(bits) {
21843 var result = 0;
21844 while (bits > 0) {
21845 this._ensureByte();
21846 var remaining = 8 - this.bitOffset;
21847 // if we're in a byte
21848 if (bits >= remaining) {
21849 result <<= remaining;
21850 result |= BITMASK[remaining] & this.curByte;
21851 this.hasByte = false;
21852 this.bitOffset = 0;
21853 bits -= remaining;
21854 } else {
21855 result <<= bits;
21856 var shift = remaining - bits;
21857 result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;
21858 this.bitOffset += bits;
21859 bits = 0;
21860 }
21861 }
21862 return result;
21863};
21864
21865// seek to an arbitrary point in the buffer (expressed in bits)
21866BitReader.prototype.seek = function(pos) {
21867 var n_bit = pos % 8;
21868 var n_byte = (pos - n_bit) / 8;
21869 this.bitOffset = n_bit;
21870 this.stream.seek(n_byte);
21871 this.hasByte = false;
21872};
21873
21874// reads 6 bytes worth of data using the read method
21875BitReader.prototype.pi = function() {
21876 var buf = new Uint8Array(6), i;
21877 for (i = 0; i < buf.length; i++) {
21878 buf[i] = this.read(8);
21879 }
21880 return bufToHex(buf);
21881};
21882
21883function bufToHex(buf) {
21884 return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
21885}
21886
21887var bitreader = BitReader;
21888
21889/* very simple input/output stream interface */
21890var Stream = function() {
21891};
21892
21893// input streams //////////////
21894/** Returns the next byte, or -1 for EOF. */
21895Stream.prototype.readByte = function() {
21896 throw new Error("abstract method readByte() not implemented");
21897};
21898/** Attempts to fill the buffer; returns number of bytes read, or
21899 * -1 for EOF. */
21900Stream.prototype.read = function(buffer, bufOffset, length) {
21901 var bytesRead = 0;
21902 while (bytesRead < length) {
21903 var c = this.readByte();
21904 if (c < 0) { // EOF
21905 return (bytesRead===0) ? -1 : bytesRead;
21906 }
21907 buffer[bufOffset++] = c;
21908 bytesRead++;
21909 }
21910 return bytesRead;
21911};
21912Stream.prototype.seek = function(new_pos) {
21913 throw new Error("abstract method seek() not implemented");
21914};
21915
21916// output streams ///////////
21917Stream.prototype.writeByte = function(_byte) {
21918 throw new Error("abstract method readByte() not implemented");
21919};
21920Stream.prototype.write = function(buffer, bufOffset, length) {
21921 var i;
21922 for (i=0; i<length; i++) {
21923 this.writeByte(buffer[bufOffset++]);
21924 }
21925 return length;
21926};
21927Stream.prototype.flush = function() {
21928};
21929
21930var stream = Stream;
21931
21932/* CRC32, used in Bzip2 implementation.
21933 * This is a port of CRC32.java from the jbzip2 implementation at
21934 * https://code.google.com/p/jbzip2
21935 * which is:
21936 * Copyright (c) 2011 Matthew Francis
21937 *
21938 * Permission is hereby granted, free of charge, to any person
21939 * obtaining a copy of this software and associated documentation
21940 * files (the "Software"), to deal in the Software without
21941 * restriction, including without limitation the rights to use,
21942 * copy, modify, merge, publish, distribute, sublicense, and/or sell
21943 * copies of the Software, and to permit persons to whom the
21944 * Software is furnished to do so, subject to the following
21945 * conditions:
21946 *
21947 * The above copyright notice and this permission notice shall be
21948 * included in all copies or substantial portions of the Software.
21949 *
21950 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21951 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21952 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21953 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21954 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21955 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21956 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21957 * OTHER DEALINGS IN THE SOFTWARE.
21958 * This JavaScript implementation is:
21959 * Copyright (c) 2013 C. Scott Ananian
21960 * with the same licensing terms as Matthew Francis' original implementation.
21961 */
21962var crc32$1 = (function() {
21963
21964 /**
21965 * A static CRC lookup table
21966 */
21967 var crc32Lookup = new Uint32Array([
21968 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
21969 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
21970 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
21971 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
21972 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
21973 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
21974 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
21975 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
21976 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
21977 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
21978 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
21979 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
21980 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
21981 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
21982 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
21983 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
21984 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
21985 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
21986 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
21987 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
21988 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
21989 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
21990 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
21991 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
21992 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
21993 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
21994 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
21995 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
21996 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
21997 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
21998 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
21999 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
22000 ]);
22001
22002 var CRC32 = function() {
22003 /**
22004 * The current CRC
22005 */
22006 var crc = 0xffffffff;
22007
22008 /**
22009 * @return The current CRC
22010 */
22011 this.getCRC = function() {
22012 return (~crc) >>> 0; // return an unsigned value
22013 };
22014
22015 /**
22016 * Update the CRC with a single byte
22017 * @param value The value to update the CRC with
22018 */
22019 this.updateCRC = function(value) {
22020 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
22021 };
22022
22023 /**
22024 * Update the CRC with a sequence of identical bytes
22025 * @param value The value to update the CRC with
22026 * @param count The number of bytes
22027 */
22028 this.updateCRCRun = function(value, count) {
22029 while (count-- > 0) {
22030 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
22031 }
22032 };
22033 };
22034 return CRC32;
22035})();
22036
22037/*
22038seek-bzip - a pure-javascript module for seeking within bzip2 data
22039
22040Copyright (C) 2013 C. Scott Ananian
22041Copyright (C) 2012 Eli Skeggs
22042Copyright (C) 2011 Kevin Kwok
22043
22044This library is free software; you can redistribute it and/or
22045modify it under the terms of the GNU Lesser General Public
22046License as published by the Free Software Foundation; either
22047version 2.1 of the License, or (at your option) any later version.
22048
22049This library is distributed in the hope that it will be useful,
22050but WITHOUT ANY WARRANTY; without even the implied warranty of
22051MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22052Lesser General Public License for more details.
22053
22054You should have received a copy of the GNU Lesser General Public
22055License along with this library; if not, see
22056http://www.gnu.org/licenses/lgpl-2.1.html
22057
22058Adapted from node-bzip, copyright 2012 Eli Skeggs.
22059Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
22060
22061Based on micro-bunzip by Rob Landley (rob@landley.net).
22062
22063Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
22064which also acknowledges contributions by Mike Burrows, David Wheeler,
22065Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
22066Robert Sedgewick, and Jon L. Bentley.
22067*/
22068
22069
22070
22071
22072
22073var MAX_HUFCODE_BITS = 20;
22074var MAX_SYMBOLS = 258;
22075var SYMBOL_RUNA = 0;
22076var SYMBOL_RUNB = 1;
22077var MIN_GROUPS = 2;
22078var MAX_GROUPS = 6;
22079var GROUP_SIZE = 50;
22080
22081var WHOLEPI = "314159265359";
22082var SQRTPI = "177245385090";
22083
22084var mtf = function(array, index) {
22085 var src = array[index], i;
22086 for (i = index; i > 0; i--) {
22087 array[i] = array[i-1];
22088 }
22089 array[0] = src;
22090 return src;
22091};
22092
22093var Err = {
22094 OK: 0,
22095 LAST_BLOCK: -1,
22096 NOT_BZIP_DATA: -2,
22097 UNEXPECTED_INPUT_EOF: -3,
22098 UNEXPECTED_OUTPUT_EOF: -4,
22099 DATA_ERROR: -5,
22100 OUT_OF_MEMORY: -6,
22101 OBSOLETE_INPUT: -7,
22102 END_OF_BLOCK: -8
22103};
22104var ErrorMessages = {};
22105ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
22106ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
22107ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
22108ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
22109ErrorMessages[Err.DATA_ERROR] = "Data error";
22110ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
22111ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
22112
22113var _throw = function(status, optDetail) {
22114 var msg = ErrorMessages[status] || 'unknown error';
22115 if (optDetail) { msg += ': '+optDetail; }
22116 var e = new TypeError(msg);
22117 e.errorCode = status;
22118 throw e;
22119};
22120
22121var Bunzip = function(inputStream, outputStream) {
22122 this.writePos = this.writeCurrent = this.writeCount = 0;
22123
22124 this._start_bunzip(inputStream, outputStream);
22125};
22126Bunzip.prototype._init_block = function() {
22127 var moreBlocks = this._get_next_block();
22128 if ( !moreBlocks ) {
22129 this.writeCount = -1;
22130 return false; /* no more blocks */
22131 }
22132 this.blockCRC = new crc32$1();
22133 return true;
22134};
22135/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
22136Bunzip.prototype._start_bunzip = function(inputStream, outputStream) {
22137 /* Ensure that file starts with "BZh['1'-'9']." */
22138 var buf = new Uint8Array(4);
22139 if (inputStream.read(buf, 0, 4) !== 4 ||
22140 String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')
22141 _throw(Err.NOT_BZIP_DATA, 'bad magic');
22142
22143 var level = buf[3] - 0x30;
22144 if (level < 1 || level > 9)
22145 _throw(Err.NOT_BZIP_DATA, 'level out of range');
22146
22147 this.reader = new bitreader(inputStream);
22148
22149 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
22150 uncompressed data. Allocate intermediate buffer for block. */
22151 this.dbufSize = 100000 * level;
22152 this.nextoutput = 0;
22153 this.outputStream = outputStream;
22154 this.streamCRC = 0;
22155};
22156Bunzip.prototype._get_next_block = function() {
22157 var i, j, k;
22158 var reader = this.reader;
22159 // this is get_next_block() function from micro-bunzip:
22160 /* Read in header signature and CRC, then validate signature.
22161 (last block signature means CRC is for whole file, return now) */
22162 var h = reader.pi();
22163 if (h === SQRTPI) { // last block
22164 return false; /* no more blocks */
22165 }
22166 if (h !== WHOLEPI)
22167 _throw(Err.NOT_BZIP_DATA);
22168 this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
22169 this.streamCRC = (this.targetBlockCRC ^
22170 ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;
22171 /* We can add support for blockRandomised if anybody complains. There was
22172 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
22173 it didn't actually work. */
22174 if (reader.read(1))
22175 _throw(Err.OBSOLETE_INPUT);
22176 var origPointer = reader.read(24);
22177 if (origPointer > this.dbufSize)
22178 _throw(Err.DATA_ERROR, 'initial position out of bounds');
22179 /* mapping table: if some byte values are never used (encoding things
22180 like ascii text), the compression code removes the gaps to have fewer
22181 symbols to deal with, and writes a sparse bitfield indicating which
22182 values were present. We make a translation table to convert the symbols
22183 back to the corresponding bytes. */
22184 var t = reader.read(16);
22185 var symToByte = new Uint8Array(256), symTotal = 0;
22186 for (i = 0; i < 16; i++) {
22187 if (t & (1 << (0xF - i))) {
22188 var o = i * 16;
22189 k = reader.read(16);
22190 for (j = 0; j < 16; j++)
22191 if (k & (1 << (0xF - j)))
22192 symToByte[symTotal++] = o + j;
22193 }
22194 }
22195
22196 /* How many different huffman coding groups does this block use? */
22197 var groupCount = reader.read(3);
22198 if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)
22199 _throw(Err.DATA_ERROR);
22200 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
22201 group. Read in the group selector list, which is stored as MTF encoded
22202 bit runs. (MTF=Move To Front, as each value is used it's moved to the
22203 start of the list.) */
22204 var nSelectors = reader.read(15);
22205 if (nSelectors === 0)
22206 _throw(Err.DATA_ERROR);
22207
22208 var mtfSymbol = new Uint8Array(256);
22209 for (i = 0; i < groupCount; i++)
22210 mtfSymbol[i] = i;
22211
22212 var selectors = new Uint8Array(nSelectors); // was 32768...
22213
22214 for (i = 0; i < nSelectors; i++) {
22215 /* Get next value */
22216 for (j = 0; reader.read(1); j++)
22217 if (j >= groupCount) _throw(Err.DATA_ERROR);
22218 /* Decode MTF to get the next selector */
22219 selectors[i] = mtf(mtfSymbol, j);
22220 }
22221
22222 /* Read the huffman coding tables for each group, which code for symTotal
22223 literal symbols, plus two run symbols (RUNA, RUNB) */
22224 var symCount = symTotal + 2;
22225 var groups = [], hufGroup;
22226 for (j = 0; j < groupCount; j++) {
22227 var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
22228 /* Read huffman code lengths for each symbol. They're stored in
22229 a way similar to mtf; record a starting value for the first symbol,
22230 and an offset from the previous value for everys symbol after that. */
22231 t = reader.read(5); // lengths
22232 for (i = 0; i < symCount; i++) {
22233 for (;;) {
22234 if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
22235 /* If first bit is 0, stop. Else second bit indicates whether
22236 to increment or decrement the value. */
22237 if(!reader.read(1))
22238 break;
22239 if(!reader.read(1))
22240 t++;
22241 else
22242 t--;
22243 }
22244 length[i] = t;
22245 }
22246
22247 /* Find largest and smallest lengths in this group */
22248 var minLen, maxLen;
22249 minLen = maxLen = length[0];
22250 for (i = 1; i < symCount; i++) {
22251 if (length[i] > maxLen)
22252 maxLen = length[i];
22253 else if (length[i] < minLen)
22254 minLen = length[i];
22255 }
22256
22257 /* Calculate permute[], base[], and limit[] tables from length[].
22258 *
22259 * permute[] is the lookup table for converting huffman coded symbols
22260 * into decoded symbols. base[] is the amount to subtract from the
22261 * value of a huffman symbol of a given length when using permute[].
22262 *
22263 * limit[] indicates the largest numerical value a symbol with a given
22264 * number of bits can have. This is how the huffman codes can vary in
22265 * length: each code with a value>limit[length] needs another bit.
22266 */
22267 hufGroup = {};
22268 groups.push(hufGroup);
22269 hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
22270 hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
22271 hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
22272 hufGroup.minLen = minLen;
22273 hufGroup.maxLen = maxLen;
22274 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
22275 var pp = 0;
22276 for (i = minLen; i <= maxLen; i++) {
22277 temp[i] = hufGroup.limit[i] = 0;
22278 for (t = 0; t < symCount; t++)
22279 if (length[t] === i)
22280 hufGroup.permute[pp++] = t;
22281 }
22282 /* Count symbols coded for at each bit length */
22283 for (i = 0; i < symCount; i++)
22284 temp[length[i]]++;
22285 /* Calculate limit[] (the largest symbol-coding value at each bit
22286 * length, which is (previous limit<<1)+symbols at this level), and
22287 * base[] (number of symbols to ignore at each bit length, which is
22288 * limit minus the cumulative count of symbols coded for already). */
22289 pp = t = 0;
22290 for (i = minLen; i < maxLen; i++) {
22291 pp += temp[i];
22292 /* We read the largest possible symbol size and then unget bits
22293 after determining how many we need, and those extra bits could
22294 be set to anything. (They're noise from future symbols.) At
22295 each level we're really only interested in the first few bits,
22296 so here we set all the trailing to-be-ignored bits to 1 so they
22297 don't affect the value>limit[length] comparison. */
22298 hufGroup.limit[i] = pp - 1;
22299 pp <<= 1;
22300 t += temp[i];
22301 hufGroup.base[i + 1] = pp - t;
22302 }
22303 hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
22304 hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
22305 hufGroup.base[minLen] = 0;
22306 }
22307 /* We've finished reading and digesting the block header. Now read this
22308 block's huffman coded symbols from the file and undo the huffman coding
22309 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
22310
22311 /* Initialize symbol occurrence counters and symbol Move To Front table */
22312 var byteCount = new Uint32Array(256);
22313 for (i = 0; i < 256; i++)
22314 mtfSymbol[i] = i;
22315 /* Loop through compressed symbols. */
22316 var runPos = 0, dbufCount = 0, selector = 0, uc;
22317 var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
22318 symCount = 0;
22319 for (;;) {
22320 /* Determine which huffman coding group to use. */
22321 if (!(symCount--)) {
22322 symCount = GROUP_SIZE - 1;
22323 if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }
22324 hufGroup = groups[selectors[selector++]];
22325 }
22326 /* Read next huffman-coded symbol. */
22327 i = hufGroup.minLen;
22328 j = reader.read(i);
22329 for (;;i++) {
22330 if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }
22331 if (j <= hufGroup.limit[i])
22332 break;
22333 j = (j << 1) | reader.read(1);
22334 }
22335 /* Huffman decode value to get nextSym (with bounds checking) */
22336 j -= hufGroup.base[i];
22337 if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }
22338 var nextSym = hufGroup.permute[j];
22339 /* We have now decoded the symbol, which indicates either a new literal
22340 byte, or a repeated run of the most recent literal byte. First,
22341 check if nextSym indicates a repeated run, and if so loop collecting
22342 how many times to repeat the last literal. */
22343 if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
22344 /* If this is the start of a new run, zero out counter */
22345 if (!runPos){
22346 runPos = 1;
22347 t = 0;
22348 }
22349 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
22350 each bit position, add 1 or 2 instead. For example,
22351 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
22352 You can make any bit pattern that way using 1 less symbol than
22353 the basic or 0/1 method (except all bits 0, which would use no
22354 symbols, but a run of length 0 doesn't mean anything in this
22355 context). Thus space is saved. */
22356 if (nextSym === SYMBOL_RUNA)
22357 t += runPos;
22358 else
22359 t += 2 * runPos;
22360 runPos <<= 1;
22361 continue;
22362 }
22363 /* When we hit the first non-run symbol after a run, we now know
22364 how many times to repeat the last literal, so append that many
22365 copies to our buffer of decoded symbols (dbuf) now. (The last
22366 literal used is the one at the head of the mtfSymbol array.) */
22367 if (runPos){
22368 runPos = 0;
22369 if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }
22370 uc = symToByte[mtfSymbol[0]];
22371 byteCount[uc] += t;
22372 while (t--)
22373 dbuf[dbufCount++] = uc;
22374 }
22375 /* Is this the terminating symbol? */
22376 if (nextSym > symTotal)
22377 break;
22378 /* At this point, nextSym indicates a new literal character. Subtract
22379 one to get the position in the MTF array at which this literal is
22380 currently to be found. (Note that the result can't be -1 or 0,
22381 because 0 and 1 are RUNA and RUNB. But another instance of the
22382 first symbol in the mtf array, position 0, would have been handled
22383 as part of a run above. Therefore 1 unused mtf position minus
22384 2 non-literal nextSym values equals -1.) */
22385 if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }
22386 i = nextSym - 1;
22387 uc = mtf(mtfSymbol, i);
22388 uc = symToByte[uc];
22389 /* We have our literal byte. Save it into dbuf. */
22390 byteCount[uc]++;
22391 dbuf[dbufCount++] = uc;
22392 }
22393 /* At this point, we've read all the huffman-coded symbols (and repeated
22394 runs) for this block from the input stream, and decoded them into the
22395 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
22396 Now undo the Burrows-Wheeler transform on dbuf.
22397 See http://dogma.net/markn/articles/bwt/bwt.htm
22398 */
22399 if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }
22400 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
22401 j = 0;
22402 for (i = 0; i < 256; i++) {
22403 k = j + byteCount[i];
22404 byteCount[i] = j;
22405 j = k;
22406 }
22407 /* Figure out what order dbuf would be in if we sorted it. */
22408 for (i = 0; i < dbufCount; i++) {
22409 uc = dbuf[i] & 0xff;
22410 dbuf[byteCount[uc]] |= (i << 8);
22411 byteCount[uc]++;
22412 }
22413 /* Decode first byte by hand to initialize "previous" byte. Note that it
22414 doesn't get output, and if the first three characters are identical
22415 it doesn't qualify as a run (hence writeRunCountdown=5). */
22416 var pos = 0, current = 0, run = 0;
22417 if (dbufCount) {
22418 pos = dbuf[origPointer];
22419 current = (pos & 0xff);
22420 pos >>= 8;
22421 run = -1;
22422 }
22423 this.writePos = pos;
22424 this.writeCurrent = current;
22425 this.writeCount = dbufCount;
22426 this.writeRun = run;
22427
22428 return true; /* more blocks to come */
22429};
22430/* Undo burrows-wheeler transform on intermediate buffer to produce output.
22431 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
22432 data are written to outbuf. Return value is number of bytes written or
22433 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
22434 are ignored, data is written to out_fd and return is RETVAL_OK or error.
22435*/
22436Bunzip.prototype._read_bunzip = function(outputBuffer, len) {
22437 var copies, previous, outbyte;
22438 /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
22439 decoded, which results in this returning RETVAL_LAST_BLOCK, also
22440 equal to -1... Confusing, I'm returning 0 here to indicate no
22441 bytes written into the buffer */
22442 if (this.writeCount < 0) { return 0; }
22443 var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;
22444 var dbufCount = this.writeCount; this.outputsize;
22445 var run = this.writeRun;
22446
22447 while (dbufCount) {
22448 dbufCount--;
22449 previous = current;
22450 pos = dbuf[pos];
22451 current = pos & 0xff;
22452 pos >>= 8;
22453 if (run++ === 3){
22454 copies = current;
22455 outbyte = previous;
22456 current = -1;
22457 } else {
22458 copies = 1;
22459 outbyte = current;
22460 }
22461 this.blockCRC.updateCRCRun(outbyte, copies);
22462 while (copies--) {
22463 this.outputStream.writeByte(outbyte);
22464 this.nextoutput++;
22465 }
22466 if (current != previous)
22467 run = 0;
22468 }
22469 this.writeCount = dbufCount;
22470 // check CRC
22471 if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
22472 _throw(Err.DATA_ERROR, "Bad block CRC "+
22473 "(got "+this.blockCRC.getCRC().toString(16)+
22474 " expected "+this.targetBlockCRC.toString(16)+")");
22475 }
22476 return this.nextoutput;
22477};
22478
22479var coerceInputStream = function(input) {
22480 if ('readByte' in input) { return input; }
22481 var inputStream = new stream();
22482 inputStream.pos = 0;
22483 inputStream.readByte = function() { return input[this.pos++]; };
22484 inputStream.seek = function(pos) { this.pos = pos; };
22485 inputStream.eof = function() { return this.pos >= input.length; };
22486 return inputStream;
22487};
22488var coerceOutputStream = function(output) {
22489 var outputStream = new stream();
22490 var resizeOk = true;
22491 if (output) {
22492 if (typeof(output)==='number') {
22493 outputStream.buffer = new Uint8Array(output);
22494 resizeOk = false;
22495 } else if ('writeByte' in output) {
22496 return output;
22497 } else {
22498 outputStream.buffer = output;
22499 resizeOk = false;
22500 }
22501 } else {
22502 outputStream.buffer = new Uint8Array(16384);
22503 }
22504 outputStream.pos = 0;
22505 outputStream.writeByte = function(_byte) {
22506 if (resizeOk && this.pos >= this.buffer.length) {
22507 var newBuffer = new Uint8Array(this.buffer.length*2);
22508 newBuffer.set(this.buffer);
22509 this.buffer = newBuffer;
22510 }
22511 this.buffer[this.pos++] = _byte;
22512 };
22513 outputStream.getBuffer = function() {
22514 // trim buffer
22515 if (this.pos !== this.buffer.length) {
22516 if (!resizeOk)
22517 throw new TypeError('outputsize does not match decoded input');
22518 var newBuffer = new Uint8Array(this.pos);
22519 newBuffer.set(this.buffer.subarray(0, this.pos));
22520 this.buffer = newBuffer;
22521 }
22522 return this.buffer;
22523 };
22524 outputStream._coerced = true;
22525 return outputStream;
22526};
22527
22528/* Static helper functions */
22529// 'input' can be a stream or a buffer
22530// 'output' can be a stream or a buffer or a number (buffer size)
22531const decode$2 = function(input, output, multistream) {
22532 // make a stream from a buffer, if necessary
22533 var inputStream = coerceInputStream(input);
22534 var outputStream = coerceOutputStream(output);
22535
22536 var bz = new Bunzip(inputStream, outputStream);
22537 while (true) {
22538 if ('eof' in inputStream && inputStream.eof()) break;
22539 if (bz._init_block()) {
22540 bz._read_bunzip();
22541 } else {
22542 var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
22543 if (targetStreamCRC !== bz.streamCRC) {
22544 _throw(Err.DATA_ERROR, "Bad stream CRC "+
22545 "(got "+bz.streamCRC.toString(16)+
22546 " expected "+targetStreamCRC.toString(16)+")");
22547 }
22548 if (multistream &&
22549 'eof' in inputStream &&
22550 !inputStream.eof()) {
22551 // note that start_bunzip will also resync the bit reader to next byte
22552 bz._start_bunzip(inputStream, outputStream);
22553 } else break;
22554 }
22555 }
22556 if ('getBuffer' in outputStream)
22557 return outputStream.getBuffer();
22558};
22559const decodeBlock = function(input, pos, output) {
22560 // make a stream from a buffer, if necessary
22561 var inputStream = coerceInputStream(input);
22562 var outputStream = coerceOutputStream(output);
22563 var bz = new Bunzip(inputStream, outputStream);
22564 bz.reader.seek(pos);
22565 /* Fill the decode buffer for the block */
22566 var moreBlocks = bz._get_next_block();
22567 if (moreBlocks) {
22568 /* Init the CRC for writing */
22569 bz.blockCRC = new crc32$1();
22570
22571 /* Zero this so the current byte from before the seek is not written */
22572 bz.writeCopies = 0;
22573
22574 /* Decompress the block and write to stdout */
22575 bz._read_bunzip();
22576 // XXX keep writing?
22577 }
22578 if ('getBuffer' in outputStream)
22579 return outputStream.getBuffer();
22580};
22581/* Reads bzip2 file from stream or buffer `input`, and invoke
22582 * `callback(position, size)` once for each bzip2 block,
22583 * where position gives the starting position (in *bits*)
22584 * and size gives uncompressed size of the block (in *bytes*). */
22585const table = function(input, callback, multistream) {
22586 // make a stream from a buffer, if necessary
22587 var inputStream = new stream();
22588 inputStream.delegate = coerceInputStream(input);
22589 inputStream.pos = 0;
22590 inputStream.readByte = function() {
22591 this.pos++;
22592 return this.delegate.readByte();
22593 };
22594 if (inputStream.delegate.eof) {
22595 inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
22596 }
22597 var outputStream = new stream();
22598 outputStream.pos = 0;
22599 outputStream.writeByte = function() { this.pos++; };
22600
22601 var bz = new Bunzip(inputStream, outputStream);
22602 var blockSize = bz.dbufSize;
22603 while (true) {
22604 if ('eof' in inputStream && inputStream.eof()) break;
22605
22606 var position = inputStream.pos*8 + bz.reader.bitOffset;
22607 if (bz.reader.hasByte) { position -= 8; }
22608
22609 if (bz._init_block()) {
22610 var start = outputStream.pos;
22611 bz._read_bunzip();
22612 callback(position, outputStream.pos - start);
22613 } else {
22614 bz.reader.read(32); // (but we ignore the crc)
22615 if (multistream &&
22616 'eof' in inputStream &&
22617 !inputStream.eof()) {
22618 // note that start_bunzip will also resync the bit reader to next byte
22619 bz._start_bunzip(inputStream, outputStream);
22620 console.assert(bz.dbufSize === blockSize,
22621 "shouldn't change block size within multistream file");
22622 } else break;
22623 }
22624 }
22625};
22626
22627var lib = {
22628 Bunzip,
22629 Stream: stream,
22630 Err,
22631 decode: decode$2,
22632 decodeBlock,
22633 table
22634};
22635var lib_4 = lib.decode;
22636
22637// GPG4Browsers - An OpenPGP implementation in javascript
22638
22639/**
22640 * Implementation of the Literal Data Packet (Tag 11)
22641 *
22642 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
22643 * A Literal Data packet contains the body of a message; data that is not to be
22644 * further interpreted.
22645 */
22646class LiteralDataPacket {
22647 static get tag() {
22648 return enums.packet.literalData;
22649 }
22650
22651 /**
22652 * @param {Date} date - The creation date of the literal package
22653 */
22654 constructor(date = new Date()) {
22655 this.format = enums.literal.utf8; // default format for literal data packets
22656 this.date = util.normalizeDate(date);
22657 this.text = null; // textual data representation
22658 this.data = null; // literal data representation
22659 this.filename = '';
22660 }
22661
22662 /**
22663 * Set the packet data to a javascript native string, end of line
22664 * will be normalized to \r\n and by default text is converted to UTF8
22665 * @param {String | ReadableStream<String>} text - Any native javascript string
22666 * @param {enums.literal} [format] - The format of the string of bytes
22667 */
22668 setText(text, format = enums.literal.utf8) {
22669 this.format = format;
22670 this.text = text;
22671 this.data = null;
22672 }
22673
22674 /**
22675 * Returns literal data packets as native JavaScript string
22676 * with normalized end of line to \n
22677 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22678 * @returns {String | ReadableStream<String>} Literal data as text.
22679 */
22680 getText(clone = false) {
22681 if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
22682 this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));
22683 }
22684 return this.text;
22685 }
22686
22687 /**
22688 * Set the packet data to value represented by the provided string of bytes.
22689 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
22690 * @param {enums.literal} format - The format of the string of bytes
22691 */
22692 setBytes(bytes, format) {
22693 this.format = format;
22694 this.data = bytes;
22695 this.text = null;
22696 }
22697
22698
22699 /**
22700 * Get the byte sequence representing the literal packet data
22701 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22702 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
22703 */
22704 getBytes(clone = false) {
22705 if (this.data === null) {
22706 // encode UTF8 and normalize EOL to \r\n
22707 this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));
22708 }
22709 if (clone) {
22710 return passiveClone(this.data);
22711 }
22712 return this.data;
22713 }
22714
22715
22716 /**
22717 * Sets the filename of the literal packet data
22718 * @param {String} filename - Any native javascript string
22719 */
22720 setFilename(filename) {
22721 this.filename = filename;
22722 }
22723
22724
22725 /**
22726 * Get the filename of the literal packet data
22727 * @returns {String} Filename.
22728 */
22729 getFilename() {
22730 return this.filename;
22731 }
22732
22733 /**
22734 * Parsing function for a literal data packet (tag 11).
22735 *
22736 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
22737 * @returns {Promise<LiteralDataPacket>} Object representation.
22738 * @async
22739 */
22740 async read(bytes) {
22741 await parse(bytes, async reader => {
22742 // - A one-octet field that describes how the data is formatted.
22743 const format = await reader.readByte(); // enums.literal
22744
22745 const filename_len = await reader.readByte();
22746 this.filename = util.decodeUTF8(await reader.readBytes(filename_len));
22747
22748 this.date = util.readDate(await reader.readBytes(4));
22749
22750 let data = reader.remainder();
22751 if (isArrayStream(data)) data = await readToEnd(data);
22752 this.setBytes(data, format);
22753 });
22754 }
22755
22756 /**
22757 * Creates a Uint8Array representation of the packet, excluding the data
22758 *
22759 * @returns {Uint8Array} Uint8Array representation of the packet.
22760 */
22761 writeHeader() {
22762 const filename = util.encodeUTF8(this.filename);
22763 const filename_length = new Uint8Array([filename.length]);
22764
22765 const format = new Uint8Array([this.format]);
22766 const date = util.writeDate(this.date);
22767
22768 return util.concatUint8Array([format, filename_length, filename, date]);
22769 }
22770
22771 /**
22772 * Creates a Uint8Array representation of the packet
22773 *
22774 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
22775 */
22776 write() {
22777 const header = this.writeHeader();
22778 const data = this.getBytes();
22779
22780 return util.concat([header, data]);
22781 }
22782}
22783
22784// GPG4Browsers - An OpenPGP implementation in javascript
22785
22786// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.
22787const verified = Symbol('verified');
22788
22789// GPG puts the Issuer and Signature subpackets in the unhashed area.
22790// Tampering with those invalidates the signature, so we still trust them and parse them.
22791// All other unhashed subpackets are ignored.
22792const allowedUnhashedSubpackets = new Set([
22793 enums.signatureSubpacket.issuer,
22794 enums.signatureSubpacket.issuerFingerprint,
22795 enums.signatureSubpacket.embeddedSignature
22796]);
22797
22798/**
22799 * Implementation of the Signature Packet (Tag 2)
22800 *
22801 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
22802 * A Signature packet describes a binding between some public key and
22803 * some data. The most common signatures are a signature of a file or a
22804 * block of text, and a signature that is a certification of a User ID.
22805 */
22806class SignaturePacket {
22807 static get tag() {
22808 return enums.packet.signature;
22809 }
22810
22811 constructor() {
22812 this.version = null;
22813 /** @type {enums.signature} */
22814 this.signatureType = null;
22815 /** @type {enums.hash} */
22816 this.hashAlgorithm = null;
22817 /** @type {enums.publicKey} */
22818 this.publicKeyAlgorithm = null;
22819
22820 this.signatureData = null;
22821 this.unhashedSubpackets = [];
22822 this.signedHashValue = null;
22823
22824 this.created = null;
22825 this.signatureExpirationTime = null;
22826 this.signatureNeverExpires = true;
22827 this.exportable = null;
22828 this.trustLevel = null;
22829 this.trustAmount = null;
22830 this.regularExpression = null;
22831 this.revocable = null;
22832 this.keyExpirationTime = null;
22833 this.keyNeverExpires = null;
22834 this.preferredSymmetricAlgorithms = null;
22835 this.revocationKeyClass = null;
22836 this.revocationKeyAlgorithm = null;
22837 this.revocationKeyFingerprint = null;
22838 this.issuerKeyID = new KeyID();
22839 this.rawNotations = [];
22840 this.notations = {};
22841 this.preferredHashAlgorithms = null;
22842 this.preferredCompressionAlgorithms = null;
22843 this.keyServerPreferences = null;
22844 this.preferredKeyServer = null;
22845 this.isPrimaryUserID = null;
22846 this.policyURI = null;
22847 this.keyFlags = null;
22848 this.signersUserID = null;
22849 this.reasonForRevocationFlag = null;
22850 this.reasonForRevocationString = null;
22851 this.features = null;
22852 this.signatureTargetPublicKeyAlgorithm = null;
22853 this.signatureTargetHashAlgorithm = null;
22854 this.signatureTargetHash = null;
22855 this.embeddedSignature = null;
22856 this.issuerKeyVersion = null;
22857 this.issuerFingerprint = null;
22858 this.preferredAEADAlgorithms = null;
22859
22860 this.revoked = null;
22861 this[verified] = null;
22862 }
22863
22864 /**
22865 * parsing function for a signature packet (tag 2).
22866 * @param {String} bytes - Payload of a tag 2 packet
22867 * @returns {SignaturePacket} Object representation.
22868 */
22869 read(bytes) {
22870 let i = 0;
22871 this.version = bytes[i++];
22872
22873 if (this.version !== 4 && this.version !== 5) {
22874 throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);
22875 }
22876
22877 this.signatureType = bytes[i++];
22878 this.publicKeyAlgorithm = bytes[i++];
22879 this.hashAlgorithm = bytes[i++];
22880
22881 // hashed subpackets
22882 i += this.readSubPackets(bytes.subarray(i, bytes.length), true);
22883 if (!this.created) {
22884 throw new Error('Missing signature creation time subpacket.');
22885 }
22886
22887 // A V4 signature hashes the packet body
22888 // starting from its first field, the version number, through the end
22889 // of the hashed subpacket data. Thus, the fields hashed are the
22890 // signature version, the signature type, the public-key algorithm, the
22891 // hash algorithm, the hashed subpacket length, and the hashed
22892 // subpacket body.
22893 this.signatureData = bytes.subarray(0, i);
22894
22895 // unhashed subpackets
22896 i += this.readSubPackets(bytes.subarray(i, bytes.length), false);
22897
22898 // Two-octet field holding left 16 bits of signed hash value.
22899 this.signedHashValue = bytes.subarray(i, i + 2);
22900 i += 2;
22901
22902 this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));
22903 }
22904
22905 /**
22906 * @returns {Uint8Array | ReadableStream<Uint8Array>}
22907 */
22908 writeParams() {
22909 if (this.params instanceof Promise) {
22910 return fromAsync(
22911 async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params)
22912 );
22913 }
22914 return mod.serializeParams(this.publicKeyAlgorithm, this.params);
22915 }
22916
22917 write() {
22918 const arr = [];
22919 arr.push(this.signatureData);
22920 arr.push(this.writeUnhashedSubPackets());
22921 arr.push(this.signedHashValue);
22922 arr.push(this.writeParams());
22923 return util.concat(arr);
22924 }
22925
22926 /**
22927 * Signs provided data. This needs to be done prior to serialization.
22928 * @param {SecretKeyPacket} key - Private key used to sign the message.
22929 * @param {Object} data - Contains packets to be signed.
22930 * @param {Date} [date] - The signature creation time.
22931 * @param {Boolean} [detached] - Whether to create a detached signature
22932 * @throws {Error} if signing failed
22933 * @async
22934 */
22935 async sign(key, data, date = new Date(), detached = false) {
22936 if (key.version === 5) {
22937 this.version = 5;
22938 } else {
22939 this.version = 4;
22940 }
22941 const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];
22942
22943 this.created = util.normalizeDate(date);
22944 this.issuerKeyVersion = key.version;
22945 this.issuerFingerprint = key.getFingerprintBytes();
22946 this.issuerKeyID = key.getKeyID();
22947
22948 // Add hashed subpackets
22949 arr.push(this.writeHashedSubPackets());
22950
22951 // Remove unhashed subpackets, in case some allowed unhashed
22952 // subpackets existed, in order not to duplicate them (in both
22953 // the hashed and unhashed subpackets) when re-signing.
22954 this.unhashedSubpackets = [];
22955
22956 this.signatureData = util.concat(arr);
22957
22958 const toHash = this.toHash(this.signatureType, data, detached);
22959 const hash = await this.hash(this.signatureType, data, toHash, detached);
22960
22961 this.signedHashValue = slice(clone(hash), 0, 2);
22962 const signed = async () => mod.signature.sign(
22963 this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash)
22964 );
22965 if (util.isStream(hash)) {
22966 this.params = signed();
22967 } else {
22968 this.params = await signed();
22969
22970 // Store the fact that this signature is valid, e.g. for when we call `await
22971 // getLatestValidSignature(this.revocationSignatures, key, data)` later.
22972 // Note that this only holds up if the key and data passed to verify are the
22973 // same as the ones passed to sign.
22974 this[verified] = true;
22975 }
22976 }
22977
22978 /**
22979 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
22980 * @returns {Uint8Array} Subpacket data.
22981 */
22982 writeHashedSubPackets() {
22983 const sub = enums.signatureSubpacket;
22984 const arr = [];
22985 let bytes;
22986 if (this.created === null) {
22987 throw new Error('Missing signature creation time');
22988 }
22989 arr.push(writeSubPacket(sub.signatureCreationTime, util.writeDate(this.created)));
22990 if (this.signatureExpirationTime !== null) {
22991 arr.push(writeSubPacket(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4)));
22992 }
22993 if (this.exportable !== null) {
22994 arr.push(writeSubPacket(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0])));
22995 }
22996 if (this.trustLevel !== null) {
22997 bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
22998 arr.push(writeSubPacket(sub.trustSignature, bytes));
22999 }
23000 if (this.regularExpression !== null) {
23001 arr.push(writeSubPacket(sub.regularExpression, this.regularExpression));
23002 }
23003 if (this.revocable !== null) {
23004 arr.push(writeSubPacket(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
23005 }
23006 if (this.keyExpirationTime !== null) {
23007 arr.push(writeSubPacket(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4)));
23008 }
23009 if (this.preferredSymmetricAlgorithms !== null) {
23010 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));
23011 arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, bytes));
23012 }
23013 if (this.revocationKeyClass !== null) {
23014 bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
23015 bytes = util.concat([bytes, this.revocationKeyFingerprint]);
23016 arr.push(writeSubPacket(sub.revocationKey, bytes));
23017 }
23018 if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {
23019 // If the version of [the] key is greater than 4, this subpacket
23020 // MUST NOT be included in the signature.
23021 arr.push(writeSubPacket(sub.issuer, this.issuerKeyID.write()));
23022 }
23023 this.rawNotations.forEach(([{ name, value, humanReadable }]) => {
23024 bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
23025 // 2 octets of name length
23026 bytes.push(util.writeNumber(name.length, 2));
23027 // 2 octets of value length
23028 bytes.push(util.writeNumber(value.length, 2));
23029 bytes.push(util.stringToUint8Array(name));
23030 bytes.push(value);
23031 bytes = util.concat(bytes);
23032 arr.push(writeSubPacket(sub.notationData, bytes));
23033 });
23034 if (this.preferredHashAlgorithms !== null) {
23035 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));
23036 arr.push(writeSubPacket(sub.preferredHashAlgorithms, bytes));
23037 }
23038 if (this.preferredCompressionAlgorithms !== null) {
23039 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));
23040 arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, bytes));
23041 }
23042 if (this.keyServerPreferences !== null) {
23043 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));
23044 arr.push(writeSubPacket(sub.keyServerPreferences, bytes));
23045 }
23046 if (this.preferredKeyServer !== null) {
23047 arr.push(writeSubPacket(sub.preferredKeyServer, util.stringToUint8Array(this.preferredKeyServer)));
23048 }
23049 if (this.isPrimaryUserID !== null) {
23050 arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
23051 }
23052 if (this.policyURI !== null) {
23053 arr.push(writeSubPacket(sub.policyURI, util.stringToUint8Array(this.policyURI)));
23054 }
23055 if (this.keyFlags !== null) {
23056 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));
23057 arr.push(writeSubPacket(sub.keyFlags, bytes));
23058 }
23059 if (this.signersUserID !== null) {
23060 arr.push(writeSubPacket(sub.signersUserID, util.stringToUint8Array(this.signersUserID)));
23061 }
23062 if (this.reasonForRevocationFlag !== null) {
23063 bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
23064 arr.push(writeSubPacket(sub.reasonForRevocation, bytes));
23065 }
23066 if (this.features !== null) {
23067 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));
23068 arr.push(writeSubPacket(sub.features, bytes));
23069 }
23070 if (this.signatureTargetPublicKeyAlgorithm !== null) {
23071 bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
23072 bytes.push(util.stringToUint8Array(this.signatureTargetHash));
23073 bytes = util.concat(bytes);
23074 arr.push(writeSubPacket(sub.signatureTarget, bytes));
23075 }
23076 if (this.embeddedSignature !== null) {
23077 arr.push(writeSubPacket(sub.embeddedSignature, this.embeddedSignature.write()));
23078 }
23079 if (this.issuerFingerprint !== null) {
23080 bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
23081 bytes = util.concat(bytes);
23082 arr.push(writeSubPacket(sub.issuerFingerprint, bytes));
23083 }
23084 if (this.preferredAEADAlgorithms !== null) {
23085 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));
23086 arr.push(writeSubPacket(sub.preferredAEADAlgorithms, bytes));
23087 }
23088
23089 const result = util.concat(arr);
23090 const length = util.writeNumber(result.length, 2);
23091
23092 return util.concat([length, result]);
23093 }
23094
23095 /**
23096 * Creates an Uint8Array containing the unhashed subpackets
23097 * @returns {Uint8Array} Subpacket data.
23098 */
23099 writeUnhashedSubPackets() {
23100 const arr = [];
23101 this.unhashedSubpackets.forEach(data => {
23102 arr.push(writeSimpleLength(data.length));
23103 arr.push(data);
23104 });
23105
23106 const result = util.concat(arr);
23107 const length = util.writeNumber(result.length, 2);
23108
23109 return util.concat([length, result]);
23110 }
23111
23112 // V4 signature sub packets
23113 readSubPacket(bytes, hashed = true) {
23114 let mypos = 0;
23115
23116 // The leftmost bit denotes a "critical" packet
23117 const critical = bytes[mypos] & 0x80;
23118 const type = bytes[mypos] & 0x7F;
23119
23120 if (!hashed) {
23121 this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
23122 if (!allowedUnhashedSubpackets.has(type)) {
23123 return;
23124 }
23125 }
23126
23127 mypos++;
23128
23129 // subpacket type
23130 switch (type) {
23131 case enums.signatureSubpacket.signatureCreationTime:
23132 // Signature Creation Time
23133 this.created = util.readDate(bytes.subarray(mypos, bytes.length));
23134 break;
23135 case enums.signatureSubpacket.signatureExpirationTime: {
23136 // Signature Expiration Time in seconds
23137 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23138
23139 this.signatureNeverExpires = seconds === 0;
23140 this.signatureExpirationTime = seconds;
23141
23142 break;
23143 }
23144 case enums.signatureSubpacket.exportableCertification:
23145 // Exportable Certification
23146 this.exportable = bytes[mypos++] === 1;
23147 break;
23148 case enums.signatureSubpacket.trustSignature:
23149 // Trust Signature
23150 this.trustLevel = bytes[mypos++];
23151 this.trustAmount = bytes[mypos++];
23152 break;
23153 case enums.signatureSubpacket.regularExpression:
23154 // Regular Expression
23155 this.regularExpression = bytes[mypos];
23156 break;
23157 case enums.signatureSubpacket.revocable:
23158 // Revocable
23159 this.revocable = bytes[mypos++] === 1;
23160 break;
23161 case enums.signatureSubpacket.keyExpirationTime: {
23162 // Key Expiration Time in seconds
23163 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23164
23165 this.keyExpirationTime = seconds;
23166 this.keyNeverExpires = seconds === 0;
23167
23168 break;
23169 }
23170 case enums.signatureSubpacket.preferredSymmetricAlgorithms:
23171 // Preferred Symmetric Algorithms
23172 this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23173 break;
23174 case enums.signatureSubpacket.revocationKey:
23175 // Revocation Key
23176 // (1 octet of class, 1 octet of public-key algorithm ID, 20
23177 // octets of
23178 // fingerprint)
23179 this.revocationKeyClass = bytes[mypos++];
23180 this.revocationKeyAlgorithm = bytes[mypos++];
23181 this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
23182 break;
23183
23184 case enums.signatureSubpacket.issuer:
23185 // Issuer
23186 this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));
23187 break;
23188
23189 case enums.signatureSubpacket.notationData: {
23190 // Notation Data
23191 const humanReadable = !!(bytes[mypos] & 0x80);
23192
23193 // We extract key/value tuple from the byte stream.
23194 mypos += 4;
23195 const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
23196 mypos += 2;
23197 const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
23198 mypos += 2;
23199
23200 const name = util.uint8ArrayToString(bytes.subarray(mypos, mypos + m));
23201 const value = bytes.subarray(mypos + m, mypos + m + n);
23202
23203 this.rawNotations.push({ name, humanReadable, value, critical });
23204
23205 if (humanReadable) {
23206 this.notations[name] = util.uint8ArrayToString(value);
23207 }
23208 break;
23209 }
23210 case enums.signatureSubpacket.preferredHashAlgorithms:
23211 // Preferred Hash Algorithms
23212 this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23213 break;
23214 case enums.signatureSubpacket.preferredCompressionAlgorithms:
23215 // Preferred Compression Algorithms
23216 this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23217 break;
23218 case enums.signatureSubpacket.keyServerPreferences:
23219 // Key Server Preferences
23220 this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];
23221 break;
23222 case enums.signatureSubpacket.preferredKeyServer:
23223 // Preferred Key Server
23224 this.preferredKeyServer = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23225 break;
23226 case enums.signatureSubpacket.primaryUserID:
23227 // Primary User ID
23228 this.isPrimaryUserID = bytes[mypos++] !== 0;
23229 break;
23230 case enums.signatureSubpacket.policyURI:
23231 // Policy URI
23232 this.policyURI = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23233 break;
23234 case enums.signatureSubpacket.keyFlags:
23235 // Key Flags
23236 this.keyFlags = [...bytes.subarray(mypos, bytes.length)];
23237 break;
23238 case enums.signatureSubpacket.signersUserID:
23239 // Signer's User ID
23240 this.signersUserID = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23241 break;
23242 case enums.signatureSubpacket.reasonForRevocation:
23243 // Reason for Revocation
23244 this.reasonForRevocationFlag = bytes[mypos++];
23245 this.reasonForRevocationString = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23246 break;
23247 case enums.signatureSubpacket.features:
23248 // Features
23249 this.features = [...bytes.subarray(mypos, bytes.length)];
23250 break;
23251 case enums.signatureSubpacket.signatureTarget: {
23252 // Signature Target
23253 // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
23254 this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
23255 this.signatureTargetHashAlgorithm = bytes[mypos++];
23256
23257 const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm);
23258
23259 this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));
23260 break;
23261 }
23262 case enums.signatureSubpacket.embeddedSignature:
23263 // Embedded Signature
23264 this.embeddedSignature = new SignaturePacket();
23265 this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
23266 break;
23267 case enums.signatureSubpacket.issuerFingerprint:
23268 // Issuer Fingerprint
23269 this.issuerKeyVersion = bytes[mypos++];
23270 this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
23271 if (this.issuerKeyVersion === 5) {
23272 this.issuerKeyID.read(this.issuerFingerprint);
23273 } else {
23274 this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));
23275 }
23276 break;
23277 case enums.signatureSubpacket.preferredAEADAlgorithms:
23278 // Preferred AEAD Algorithms
23279 this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23280 break;
23281 default: {
23282 const err = new Error(`Unknown signature subpacket type ${type}`);
23283 if (critical) {
23284 throw err;
23285 } else {
23286 util.printDebug(err);
23287 }
23288 }
23289 }
23290 }
23291
23292 readSubPackets(bytes, trusted = true, config) {
23293 // Two-octet scalar octet count for following subpacket data.
23294 const subpacketLength = util.readNumber(bytes.subarray(0, 2));
23295
23296 let i = 2;
23297
23298 // subpacket data set (zero or more subpackets)
23299 while (i < 2 + subpacketLength) {
23300 const len = readSimpleLength(bytes.subarray(i, bytes.length));
23301 i += len.offset;
23302
23303 this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);
23304
23305 i += len.len;
23306 }
23307
23308 return i;
23309 }
23310
23311 // Produces data to produce signature on
23312 toSign(type, data) {
23313 const t = enums.signature;
23314
23315 switch (type) {
23316 case t.binary:
23317 if (data.text !== null) {
23318 return util.encodeUTF8(data.getText(true));
23319 }
23320 return data.getBytes(true);
23321
23322 case t.text: {
23323 const bytes = data.getBytes(true);
23324 // normalize EOL to \r\n
23325 return util.canonicalizeEOL(bytes);
23326 }
23327 case t.standalone:
23328 return new Uint8Array(0);
23329
23330 case t.certGeneric:
23331 case t.certPersona:
23332 case t.certCasual:
23333 case t.certPositive:
23334 case t.certRevocation: {
23335 let packet;
23336 let tag;
23337
23338 if (data.userID) {
23339 tag = 0xB4;
23340 packet = data.userID;
23341 } else if (data.userAttribute) {
23342 tag = 0xD1;
23343 packet = data.userAttribute;
23344 } else {
23345 throw new Error('Either a userID or userAttribute packet needs to be ' +
23346 'supplied for certification.');
23347 }
23348
23349 const bytes = packet.write();
23350
23351 return util.concat([this.toSign(t.key, data),
23352 new Uint8Array([tag]),
23353 util.writeNumber(bytes.length, 4),
23354 bytes]);
23355 }
23356 case t.subkeyBinding:
23357 case t.subkeyRevocation:
23358 case t.keyBinding:
23359 return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
23360 key: data.bind
23361 })]);
23362
23363 case t.key:
23364 if (data.key === undefined) {
23365 throw new Error('Key packet is required for this signature.');
23366 }
23367 return data.key.writeForHash(this.version);
23368
23369 case t.keyRevocation:
23370 return this.toSign(t.key, data);
23371 case t.timestamp:
23372 return new Uint8Array(0);
23373 case t.thirdParty:
23374 throw new Error('Not implemented');
23375 default:
23376 throw new Error('Unknown signature type.');
23377 }
23378 }
23379
23380 calculateTrailer(data, detached) {
23381 let length = 0;
23382 return transform(clone(this.signatureData), value => {
23383 length += value.length;
23384 }, () => {
23385 const arr = [];
23386 if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
23387 if (detached) {
23388 arr.push(new Uint8Array(6));
23389 } else {
23390 arr.push(data.writeHeader());
23391 }
23392 }
23393 arr.push(new Uint8Array([this.version, 0xFF]));
23394 if (this.version === 5) {
23395 arr.push(new Uint8Array(4));
23396 }
23397 arr.push(util.writeNumber(length, 4));
23398 // For v5, this should really be writeNumber(length, 8) rather than the
23399 // hardcoded 4 zero bytes above
23400 return util.concat(arr);
23401 });
23402 }
23403
23404 toHash(signatureType, data, detached = false) {
23405 const bytes = this.toSign(signatureType, data);
23406
23407 return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
23408 }
23409
23410 async hash(signatureType, data, toHash, detached = false) {
23411 if (!toHash) toHash = this.toHash(signatureType, data, detached);
23412 return mod.hash.digest(this.hashAlgorithm, toHash);
23413 }
23414
23415 /**
23416 * verifies the signature packet. Note: not all signature types are implemented
23417 * @param {PublicSubkeyPacket|PublicKeyPacket|
23418 * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature
23419 * @param {module:enums.signature} signatureType - Expected signature type
23420 * @param {Uint8Array|Object} data - Data which on the signature applies
23421 * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration
23422 * @param {Boolean} [detached] - Whether to verify a detached signature
23423 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23424 * @throws {Error} if signature validation failed
23425 * @async
23426 */
23427 async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {
23428 if (!this.issuerKeyID.equals(key.getKeyID())) {
23429 throw new Error('Signature was not issued by the given public key');
23430 }
23431 if (this.publicKeyAlgorithm !== key.algorithm) {
23432 throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
23433 }
23434
23435 const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;
23436 // Cryptographic validity is cached after one successful verification.
23437 // However, for message signatures, we always re-verify, since the passed `data` can change
23438 const skipVerify = this[verified] && !isMessageSignature;
23439 if (!skipVerify) {
23440 let toHash;
23441 let hash;
23442 if (this.hashed) {
23443 hash = await this.hashed;
23444 } else {
23445 toHash = this.toHash(signatureType, data, detached);
23446 hash = await this.hash(signatureType, data, toHash);
23447 }
23448 hash = await readToEnd(hash);
23449 if (this.signedHashValue[0] !== hash[0] ||
23450 this.signedHashValue[1] !== hash[1]) {
23451 throw new Error('Signed digest did not match');
23452 }
23453
23454 this.params = await this.params;
23455
23456 this[verified] = await mod.signature.verify(
23457 this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,
23458 toHash, hash
23459 );
23460
23461 if (!this[verified]) {
23462 throw new Error('Signature verification failed');
23463 }
23464 }
23465
23466 const normDate = util.normalizeDate(date);
23467 if (normDate && this.created > normDate) {
23468 throw new Error('Signature creation time is in the future');
23469 }
23470 if (normDate && normDate >= this.getExpirationTime()) {
23471 throw new Error('Signature is expired');
23472 }
23473 if (config.rejectHashAlgorithms.has(this.hashAlgorithm)) {
23474 throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23475 }
23476 if (config.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&
23477 [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
23478 throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23479 }
23480 this.rawNotations.forEach(({ name, critical }) => {
23481 if (critical && (config.knownNotations.indexOf(name) < 0)) {
23482 throw new Error(`Unknown critical notation: ${name}`);
23483 }
23484 });
23485 if (this.revocationKeyClass !== null) {
23486 throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
23487 }
23488 }
23489
23490 /**
23491 * Verifies signature expiration date
23492 * @param {Date} [date] - Use the given date for verification instead of the current time
23493 * @returns {Boolean} True if expired.
23494 */
23495 isExpired(date = new Date()) {
23496 const normDate = util.normalizeDate(date);
23497 if (normDate !== null) {
23498 return !(this.created <= normDate && normDate < this.getExpirationTime());
23499 }
23500 return false;
23501 }
23502
23503 /**
23504 * Returns the expiration time of the signature or Infinity if signature does not expire
23505 * @returns {Date | Infinity} Expiration time.
23506 */
23507 getExpirationTime() {
23508 return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);
23509 }
23510}
23511
23512/**
23513 * Creates a string representation of a sub signature packet
23514 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
23515 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
23516 * @param {Integer} type - Subpacket signature type.
23517 * @param {String} data - Data to be included
23518 * @returns {String} A string-representation of a sub signature packet.
23519 * @private
23520 */
23521function writeSubPacket(type, data) {
23522 const arr = [];
23523 arr.push(writeSimpleLength(data.length + 1));
23524 arr.push(new Uint8Array([type]));
23525 arr.push(data);
23526 return util.concat(arr);
23527}
23528
23529// GPG4Browsers - An OpenPGP implementation in javascript
23530
23531const VERSION = 3;
23532
23533/**
23534 * Implementation of the One-Pass Signature Packets (Tag 4)
23535 *
23536 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
23537 * The One-Pass Signature packet precedes the signed data and contains
23538 * enough information to allow the receiver to begin calculating any
23539 * hashes needed to verify the signature. It allows the Signature
23540 * packet to be placed at the end of the message, so that the signer
23541 * can compute the entire signed message in one pass.
23542 */
23543class OnePassSignaturePacket {
23544 static get tag() {
23545 return enums.packet.onePassSignature;
23546 }
23547
23548 constructor() {
23549 /** A one-octet version number. The current version is 3. */
23550 this.version = null;
23551 /**
23552 * A one-octet signature type.
23553 * Signature types are described in
23554 * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
23555 * @type {enums.signature}
23556
23557 */
23558 this.signatureType = null;
23559 /**
23560 * A one-octet number describing the hash algorithm used.
23561 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
23562 * @type {enums.hash}
23563 */
23564 this.hashAlgorithm = null;
23565 /**
23566 * A one-octet number describing the public-key algorithm used.
23567 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
23568 * @type {enums.publicKey}
23569 */
23570 this.publicKeyAlgorithm = null;
23571 /** An eight-octet number holding the Key ID of the signing key. */
23572 this.issuerKeyID = null;
23573 /**
23574 * A one-octet number holding a flag showing whether the signature is nested.
23575 * A zero value indicates that the next packet is another One-Pass Signature packet
23576 * that describes another signature to be applied to the same message data.
23577 */
23578 this.flags = null;
23579 }
23580
23581 /**
23582 * parsing function for a one-pass signature packet (tag 4).
23583 * @param {Uint8Array} bytes - Payload of a tag 4 packet
23584 * @returns {OnePassSignaturePacket} Object representation.
23585 */
23586 read(bytes) {
23587 let mypos = 0;
23588 // A one-octet version number. The current version is 3.
23589 this.version = bytes[mypos++];
23590 if (this.version !== VERSION) {
23591 throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);
23592 }
23593
23594 // A one-octet signature type. Signature types are described in
23595 // Section 5.2.1.
23596 this.signatureType = bytes[mypos++];
23597
23598 // A one-octet number describing the hash algorithm used.
23599 this.hashAlgorithm = bytes[mypos++];
23600
23601 // A one-octet number describing the public-key algorithm used.
23602 this.publicKeyAlgorithm = bytes[mypos++];
23603
23604 // An eight-octet number holding the Key ID of the signing key.
23605 this.issuerKeyID = new KeyID();
23606 this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));
23607 mypos += 8;
23608
23609 // A one-octet number holding a flag showing whether the signature
23610 // is nested. A zero value indicates that the next packet is
23611 // another One-Pass Signature packet that describes another
23612 // signature to be applied to the same message data.
23613 this.flags = bytes[mypos++];
23614 return this;
23615 }
23616
23617 /**
23618 * creates a string representation of a one-pass signature packet
23619 * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
23620 */
23621 write() {
23622 const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);
23623
23624 const end = new Uint8Array([this.flags]);
23625
23626 return util.concatUint8Array([start, this.issuerKeyID.write(), end]);
23627 }
23628
23629 calculateTrailer(...args) {
23630 return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
23631 }
23632
23633 async verify() {
23634 const correspondingSig = await this.correspondingSig;
23635 if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {
23636 throw new Error('Corresponding signature packet missing');
23637 }
23638 if (
23639 correspondingSig.signatureType !== this.signatureType ||
23640 correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
23641 correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
23642 !correspondingSig.issuerKeyID.equals(this.issuerKeyID)
23643 ) {
23644 throw new Error('Corresponding signature packet does not match one-pass signature packet');
23645 }
23646 correspondingSig.hashed = this.hashed;
23647 return correspondingSig.verify.apply(correspondingSig, arguments);
23648 }
23649}
23650
23651OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
23652OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
23653OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;
23654
23655/**
23656 * Instantiate a new packet given its tag
23657 * @function newPacketFromTag
23658 * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}
23659 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23660 * @returns {Object} New packet object with type based on tag
23661 * @throws {Error|UnsupportedError} for disallowed or unknown packets
23662 */
23663function newPacketFromTag(tag, allowedPackets) {
23664 if (!allowedPackets[tag]) {
23665 // distinguish between disallowed packets and unknown ones
23666 let packetType;
23667 try {
23668 packetType = enums.read(enums.packet, tag);
23669 } catch (e) {
23670 throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);
23671 }
23672 throw new Error(`Packet not allowed in this context: ${packetType}`);
23673 }
23674 return new allowedPackets[tag]();
23675}
23676
23677/**
23678 * This class represents a list of openpgp packets.
23679 * Take care when iterating over it - the packets themselves
23680 * are stored as numerical indices.
23681 * @extends Array
23682 */
23683class PacketList extends Array {
23684 /**
23685 * Parses the given binary data and returns a list of packets.
23686 * Equivalent to calling `read` on an empty PacketList instance.
23687 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23688 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23689 * @param {Object} [config] - full configuration, defaults to openpgp.config
23690 * @returns {PacketList} parsed list of packets
23691 * @throws on parsing errors
23692 * @async
23693 */
23694 static async fromBinary(bytes, allowedPackets, config = defaultConfig) {
23695 const packets = new PacketList();
23696 await packets.read(bytes, allowedPackets, config);
23697 return packets;
23698 }
23699
23700 /**
23701 * Reads a stream of binary data and interprets it as a list of packets.
23702 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23703 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23704 * @param {Object} [config] - full configuration, defaults to openpgp.config
23705 * @throws on parsing errors
23706 * @async
23707 */
23708 async read(bytes, allowedPackets, config = defaultConfig) {
23709 this.stream = transformPair(bytes, async (readable, writable) => {
23710 const writer = getWriter(writable);
23711 try {
23712 while (true) {
23713 await writer.ready;
23714 const done = await readPackets(readable, async parsed => {
23715 try {
23716 if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {
23717 // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:
23718 // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145
23719 // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10
23720 return;
23721 }
23722 const packet = newPacketFromTag(parsed.tag, allowedPackets);
23723 packet.packets = new PacketList();
23724 packet.fromStream = util.isStream(parsed.packet);
23725 await packet.read(parsed.packet, config);
23726 await writer.write(packet);
23727 } catch (e) {
23728 const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;
23729 const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);
23730 if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {
23731 // The packets that support streaming are the ones that contain message data.
23732 // Those are also the ones we want to be more strict about and throw on parse errors
23733 // (since we likely cannot process the message without these packets anyway).
23734 await writer.abort(e);
23735 } else {
23736 const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);
23737 await writer.write(unparsedPacket);
23738 }
23739 util.printDebugError(e);
23740 }
23741 });
23742 if (done) {
23743 await writer.ready;
23744 await writer.close();
23745 return;
23746 }
23747 }
23748 } catch (e) {
23749 await writer.abort(e);
23750 }
23751 });
23752
23753 // Wait until first few packets have been read
23754 const reader = getReader(this.stream);
23755 while (true) {
23756 const { done, value } = await reader.read();
23757 if (!done) {
23758 this.push(value);
23759 } else {
23760 this.stream = null;
23761 }
23762 if (done || supportsStreaming(value.constructor.tag)) {
23763 break;
23764 }
23765 }
23766 reader.releaseLock();
23767 }
23768
23769 /**
23770 * Creates a binary representation of openpgp objects contained within the
23771 * class instance.
23772 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
23773 */
23774 write() {
23775 const arr = [];
23776
23777 for (let i = 0; i < this.length; i++) {
23778 const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;
23779 const packetbytes = this[i].write();
23780 if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {
23781 let buffer = [];
23782 let bufferLength = 0;
23783 const minLength = 512;
23784 arr.push(writeTag(tag));
23785 arr.push(transform(packetbytes, value => {
23786 buffer.push(value);
23787 bufferLength += value.length;
23788 if (bufferLength >= minLength) {
23789 const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
23790 const chunkSize = 2 ** powerOf2;
23791 const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
23792 buffer = [bufferConcat.subarray(1 + chunkSize)];
23793 bufferLength = buffer[0].length;
23794 return bufferConcat.subarray(0, 1 + chunkSize);
23795 }
23796 }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
23797 } else {
23798 if (util.isStream(packetbytes)) {
23799 let length = 0;
23800 arr.push(transform(clone(packetbytes), value => {
23801 length += value.length;
23802 }, () => writeHeader(tag, length)));
23803 } else {
23804 arr.push(writeHeader(tag, packetbytes.length));
23805 }
23806 arr.push(packetbytes);
23807 }
23808 }
23809
23810 return util.concat(arr);
23811 }
23812
23813 /**
23814 * Creates a new PacketList with all packets matching the given tag(s)
23815 * @param {...module:enums.packet} tags - packet tags to look for
23816 * @returns {PacketList}
23817 */
23818 filterByTag(...tags) {
23819 const filtered = new PacketList();
23820
23821 const handle = tag => packetType => tag === packetType;
23822
23823 for (let i = 0; i < this.length; i++) {
23824 if (tags.some(handle(this[i].constructor.tag))) {
23825 filtered.push(this[i]);
23826 }
23827 }
23828
23829 return filtered;
23830 }
23831
23832 /**
23833 * Traverses packet list and returns first packet with matching tag
23834 * @param {module:enums.packet} tag - The packet tag
23835 * @returns {Packet|undefined}
23836 */
23837 findPacket(tag) {
23838 return this.find(packet => packet.constructor.tag === tag);
23839 }
23840
23841 /**
23842 * Find indices of packets with the given tag(s)
23843 * @param {...module:enums.packet} tags - packet tags to look for
23844 * @returns {Integer[]} packet indices
23845 */
23846 indexOfTag(...tags) {
23847 const tagIndex = [];
23848 const that = this;
23849
23850 const handle = tag => packetType => tag === packetType;
23851
23852 for (let i = 0; i < this.length; i++) {
23853 if (tags.some(handle(that[i].constructor.tag))) {
23854 tagIndex.push(i);
23855 }
23856 }
23857 return tagIndex;
23858 }
23859}
23860
23861// GPG4Browsers - An OpenPGP implementation in javascript
23862
23863// A Compressed Data packet can contain the following packet types
23864const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([
23865 LiteralDataPacket,
23866 OnePassSignaturePacket,
23867 SignaturePacket
23868]);
23869
23870/**
23871 * Implementation of the Compressed Data Packet (Tag 8)
23872 *
23873 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
23874 * The Compressed Data packet contains compressed data. Typically,
23875 * this packet is found as the contents of an encrypted packet, or following
23876 * a Signature or One-Pass Signature packet, and contains a literal data packet.
23877 */
23878class CompressedDataPacket {
23879 static get tag() {
23880 return enums.packet.compressedData;
23881 }
23882
23883 /**
23884 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23885 */
23886 constructor(config = defaultConfig) {
23887 /**
23888 * List of packets
23889 * @type {PacketList}
23890 */
23891 this.packets = null;
23892 /**
23893 * Compression algorithm
23894 * @type {enums.compression}
23895 */
23896 this.algorithm = config.preferredCompressionAlgorithm;
23897
23898 /**
23899 * Compressed packet data
23900 * @type {Uint8Array | ReadableStream<Uint8Array>}
23901 */
23902 this.compressed = null;
23903
23904 /**
23905 * zip/zlib compression level, between 1 and 9
23906 */
23907 this.deflateLevel = config.deflateLevel;
23908 }
23909
23910 /**
23911 * Parsing function for the packet.
23912 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
23913 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23914 */
23915 async read(bytes, config = defaultConfig) {
23916 await parse(bytes, async reader => {
23917
23918 // One octet that gives the algorithm used to compress the packet.
23919 this.algorithm = await reader.readByte();
23920
23921 // Compressed data, which makes up the remainder of the packet.
23922 this.compressed = reader.remainder();
23923
23924 await this.decompress(config);
23925 });
23926 }
23927
23928
23929 /**
23930 * Return the compressed packet.
23931 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
23932 */
23933 write() {
23934 if (this.compressed === null) {
23935 this.compress();
23936 }
23937
23938 return util.concat([new Uint8Array([this.algorithm]), this.compressed]);
23939 }
23940
23941
23942 /**
23943 * Decompression method for decompressing the compressed data
23944 * read by read_packet
23945 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23946 */
23947 async decompress(config = defaultConfig) {
23948 const compressionName = enums.read(enums.compression, this.algorithm);
23949 const decompressionFn = decompress_fns[compressionName];
23950 if (!decompressionFn) {
23951 throw new Error(`${compressionName} decompression not supported`);
23952 }
23953
23954 this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config);
23955 }
23956
23957 /**
23958 * Compress the packet data (member decompressedData)
23959 */
23960 compress() {
23961 const compressionName = enums.read(enums.compression, this.algorithm);
23962 const compressionFn = compress_fns[compressionName];
23963 if (!compressionFn) {
23964 throw new Error(`${compressionName} compression not supported`);
23965 }
23966
23967 this.compressed = compressionFn(this.packets.write(), this.deflateLevel);
23968 }
23969}
23970
23971//////////////////////////
23972// //
23973// Helper functions //
23974// //
23975//////////////////////////
23976
23977
23978const nodeZlib = util.getNodeZlib();
23979
23980function uncompressed(data) {
23981 return data;
23982}
23983
23984function node_zlib(func, create, options = {}) {
23985 return function (data) {
23986 if (!util.isStream(data) || isArrayStream(data)) {
23987 return fromAsync(() => readToEnd(data).then(data => {
23988 return new Promise((resolve, reject) => {
23989 func(data, options, (err, result) => {
23990 if (err) return reject(err);
23991 resolve(result);
23992 });
23993 });
23994 }));
23995 }
23996 return nodeToWeb(webToNode(data).pipe(create(options)));
23997 };
23998}
23999
24000function pako_zlib(constructor, options = {}) {
24001 return function(data) {
24002 const obj = new constructor(options);
24003 return transform(data, value => {
24004 if (value.length) {
24005 obj.push(value, Z_SYNC_FLUSH);
24006 return obj.result;
24007 }
24008 }, () => {
24009 if (constructor === Deflate) {
24010 obj.push([], Z_FINISH);
24011 return obj.result;
24012 }
24013 });
24014 };
24015}
24016
24017function bzip2(func) {
24018 return function(data) {
24019 return fromAsync(async () => func(await readToEnd(data)));
24020 };
24021}
24022
24023const compress_fns = nodeZlib ? {
24024 zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),
24025 zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)
24026} : {
24027 zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),
24028 zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)
24029};
24030
24031const decompress_fns = nodeZlib ? {
24032 uncompressed: uncompressed,
24033 zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),
24034 zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),
24035 bzip2: /*#__PURE__*/ bzip2(lib_4)
24036} : {
24037 uncompressed: uncompressed,
24038 zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),
24039 zlib: /*#__PURE__*/ pako_zlib(Inflate),
24040 bzip2: /*#__PURE__*/ bzip2(lib_4)
24041};
24042
24043// GPG4Browsers - An OpenPGP implementation in javascript
24044
24045// A SEIP packet can contain the following packet types
24046const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([
24047 LiteralDataPacket,
24048 CompressedDataPacket,
24049 OnePassSignaturePacket,
24050 SignaturePacket
24051]);
24052
24053const VERSION$1 = 1; // A one-octet version number of the data packet.
24054
24055/**
24056 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
24057 *
24058 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
24059 * The Symmetrically Encrypted Integrity Protected Data packet is
24060 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
24061 * created for OpenPGP that addresses the problem of detecting a modification to
24062 * encrypted data. It is used in combination with a Modification Detection Code
24063 * packet.
24064 */
24065class SymEncryptedIntegrityProtectedDataPacket {
24066 static get tag() {
24067 return enums.packet.symEncryptedIntegrityProtectedData;
24068 }
24069
24070 constructor() {
24071 this.version = VERSION$1;
24072 this.encrypted = null;
24073 this.packets = null;
24074 }
24075
24076 async read(bytes) {
24077 await parse(bytes, async reader => {
24078 const version = await reader.readByte();
24079 // - A one-octet version number. The only currently defined value is 1.
24080 if (version !== VERSION$1) {
24081 throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);
24082 }
24083
24084 // - Encrypted data, the output of the selected symmetric-key cipher
24085 // operating in Cipher Feedback mode with shift amount equal to the
24086 // block size of the cipher (CFB-n where n is the block size).
24087 this.encrypted = reader.remainder();
24088 });
24089 }
24090
24091 write() {
24092 return util.concat([new Uint8Array([VERSION$1]), this.encrypted]);
24093 }
24094
24095 /**
24096 * Encrypt the payload in the packet.
24097 * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use
24098 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24099 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24100 * @returns {Promise<Boolean>}
24101 * @throws {Error} on encryption failure
24102 * @async
24103 */
24104 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24105 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24106
24107 let bytes = this.packets.write();
24108 if (isArrayStream(bytes)) bytes = await readToEnd(bytes);
24109 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
24110 const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
24111
24112 const tohash = util.concat([prefix, bytes, mdc]);
24113 const hash = await mod.hash.sha1(passiveClone(tohash));
24114 const plaintext = util.concat([tohash, hash]);
24115
24116 this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config);
24117 return true;
24118 }
24119
24120 /**
24121 * Decrypts the encrypted data contained in the packet.
24122 * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used
24123 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24124 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24125 * @returns {Promise<Boolean>}
24126 * @throws {Error} on decryption failure
24127 * @async
24128 */
24129 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24130 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24131 let encrypted = clone(this.encrypted);
24132 if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted);
24133 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));
24134
24135 // there must be a modification detection code packet as the
24136 // last packet and everything gets hashed except the hash itself
24137 const realHash = slice(passiveClone(decrypted), -20);
24138 const tohash = slice(decrypted, 0, -20);
24139 const verifyHash = Promise.all([
24140 readToEnd(await mod.hash.sha1(passiveClone(tohash))),
24141 readToEnd(realHash)
24142 ]).then(([hash, mdc]) => {
24143 if (!util.equalsUint8Array(hash, mdc)) {
24144 throw new Error('Modification detected.');
24145 }
24146 return new Uint8Array();
24147 });
24148 const bytes = slice(tohash, blockSize + 2); // Remove random prefix
24149 let packetbytes = slice(bytes, 0, -2); // Remove MDC packet
24150 packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]);
24151 if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {
24152 packetbytes = await readToEnd(packetbytes);
24153 }
24154 this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config);
24155 return true;
24156 }
24157}
24158
24159// OpenPGP.js - An OpenPGP implementation in javascript
24160
24161// An AEAD-encrypted Data packet can contain the following packet types
24162const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([
24163 LiteralDataPacket,
24164 CompressedDataPacket,
24165 OnePassSignaturePacket,
24166 SignaturePacket
24167]);
24168
24169const VERSION$2 = 1; // A one-octet version number of the data packet.
24170
24171/**
24172 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
24173 * Additional Data (AEAD) Protected Data Packet
24174 *
24175 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
24176 * AEAD Protected Data Packet
24177 */
24178class AEADEncryptedDataPacket {
24179 static get tag() {
24180 return enums.packet.aeadEncryptedData;
24181 }
24182
24183 constructor() {
24184 this.version = VERSION$2;
24185 /** @type {enums.symmetric} */
24186 this.cipherAlgorithm = null;
24187 /** @type {enums.aead} */
24188 this.aeadAlgorithm = enums.aead.eax;
24189 this.chunkSizeByte = null;
24190 this.iv = null;
24191 this.encrypted = null;
24192 this.packets = null;
24193 }
24194
24195 /**
24196 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24197 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
24198 * @throws {Error} on parsing failure
24199 */
24200 async read(bytes) {
24201 await parse(bytes, async reader => {
24202 const version = await reader.readByte();
24203 if (version !== VERSION$2) { // The only currently defined value is 1.
24204 throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);
24205 }
24206 this.cipherAlgorithm = await reader.readByte();
24207 this.aeadAlgorithm = await reader.readByte();
24208 this.chunkSizeByte = await reader.readByte();
24209
24210 const mode = mod.getAEADMode(this.aeadAlgorithm);
24211 this.iv = await reader.readBytes(mode.ivLength);
24212 this.encrypted = reader.remainder();
24213 });
24214 }
24215
24216 /**
24217 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24218 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
24219 */
24220 write() {
24221 return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);
24222 }
24223
24224 /**
24225 * Decrypt the encrypted payload.
24226 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24227 * @param {Uint8Array} key - The session key used to encrypt the payload
24228 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24229 * @throws {Error} if decryption was not successful
24230 * @async
24231 */
24232 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24233 this.packets = await PacketList.fromBinary(
24234 await this.crypt('decrypt', key, clone(this.encrypted)),
24235 allowedPackets$2,
24236 config
24237 );
24238 }
24239
24240 /**
24241 * Encrypt the packet payload.
24242 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24243 * @param {Uint8Array} key - The session key used to encrypt the payload
24244 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24245 * @throws {Error} if encryption was not successful
24246 * @async
24247 */
24248 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24249 this.cipherAlgorithm = sessionKeyAlgorithm;
24250
24251 const { ivLength } = mod.getAEADMode(this.aeadAlgorithm);
24252 this.iv = await mod.random.getRandomBytes(ivLength); // generate new random IV
24253 this.chunkSizeByte = config.aeadChunkSizeByte;
24254 const data = this.packets.write();
24255 this.encrypted = await this.crypt('encrypt', key, data);
24256 }
24257
24258 /**
24259 * En/decrypt the payload.
24260 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
24261 * @param {Uint8Array} key - The session key used to en/decrypt the payload
24262 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
24263 * @returns {Promise<Uint8Array | ReadableStream<Uint8Array>>}
24264 * @async
24265 */
24266 async crypt(fn, key, data) {
24267 const mode = mod.getAEADMode(this.aeadAlgorithm);
24268 const modeInstance = await mode(this.cipherAlgorithm, key);
24269 const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
24270 const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
24271 const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
24272 const adataBuffer = new ArrayBuffer(21);
24273 const adataArray = new Uint8Array(adataBuffer, 0, 13);
24274 const adataTagArray = new Uint8Array(adataBuffer);
24275 const adataView = new DataView(adataBuffer);
24276 const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
24277 adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);
24278 let chunkIndex = 0;
24279 let latestPromise = Promise.resolve();
24280 let cryptedBytes = 0;
24281 let queuedBytes = 0;
24282 const iv = this.iv;
24283 return transformPair(data, async (readable, writable) => {
24284 if (util.isStream(readable) !== 'array') {
24285 const buffer = new TransformStream({}, {
24286 highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),
24287 size: array => array.length
24288 });
24289 pipe(buffer.readable, writable);
24290 writable = buffer.writable;
24291 }
24292 const reader = getReader(readable);
24293 const writer = getWriter(writable);
24294 try {
24295 while (true) {
24296 let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
24297 const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
24298 chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
24299 let cryptedPromise;
24300 let done;
24301 if (!chunkIndex || chunk.length) {
24302 reader.unshift(finalChunk);
24303 cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
24304 queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
24305 } else {
24306 // After the last chunk, we either encrypt a final, empty
24307 // data chunk to get the final authentication tag or
24308 // validate that final authentication tag.
24309 adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
24310 cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
24311 queuedBytes += tagLengthIfEncrypting;
24312 done = true;
24313 }
24314 cryptedBytes += chunk.length - tagLengthIfDecrypting;
24315 // eslint-disable-next-line no-loop-func
24316 latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
24317 await writer.ready;
24318 await writer.write(crypted);
24319 queuedBytes -= crypted.length;
24320 }).catch(err => writer.abort(err));
24321 if (done || queuedBytes > writer.desiredSize) {
24322 await latestPromise; // Respect backpressure
24323 }
24324 if (!done) {
24325 adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
24326 } else {
24327 await writer.close();
24328 break;
24329 }
24330 }
24331 } catch (e) {
24332 await writer.abort(e);
24333 }
24334 });
24335 }
24336}
24337
24338// GPG4Browsers - An OpenPGP implementation in javascript
24339
24340const VERSION$3 = 3;
24341
24342/**
24343 * Public-Key Encrypted Session Key Packets (Tag 1)
24344 *
24345 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
24346 * A Public-Key Encrypted Session Key packet holds the session key
24347 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
24348 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
24349 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
24350 * message is encrypted with the session key, and the session key is itself
24351 * encrypted and stored in the Encrypted Session Key packet(s). The
24352 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
24353 * Session Key packet for each OpenPGP key to which the message is encrypted.
24354 * The recipient of the message finds a session key that is encrypted to their
24355 * public key, decrypts the session key, and then uses the session key to
24356 * decrypt the message.
24357 */
24358class PublicKeyEncryptedSessionKeyPacket {
24359 static get tag() {
24360 return enums.packet.publicKeyEncryptedSessionKey;
24361 }
24362
24363 constructor() {
24364 this.version = 3;
24365
24366 this.publicKeyID = new KeyID();
24367 this.publicKeyAlgorithm = null;
24368
24369 this.sessionKey = null;
24370 /**
24371 * Algorithm to encrypt the message with
24372 * @type {enums.symmetric}
24373 */
24374 this.sessionKeyAlgorithm = null;
24375
24376 /** @type {Object} */
24377 this.encrypted = {};
24378 }
24379
24380 /**
24381 * Parsing function for a publickey encrypted session key packet (tag 1).
24382 *
24383 * @param {Uint8Array} bytes - Payload of a tag 1 packet
24384 */
24385 read(bytes) {
24386 this.version = bytes[0];
24387 if (this.version !== VERSION$3) {
24388 throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);
24389 }
24390 this.publicKeyID.read(bytes.subarray(1, bytes.length));
24391 this.publicKeyAlgorithm = bytes[9];
24392 this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(10));
24393 }
24394
24395 /**
24396 * Create a binary representation of a tag 1 packet
24397 *
24398 * @returns {Uint8Array} The Uint8Array representation.
24399 */
24400 write() {
24401 const arr = [
24402 new Uint8Array([this.version]),
24403 this.publicKeyID.write(),
24404 new Uint8Array([this.publicKeyAlgorithm]),
24405 mod.serializeParams(this.publicKeyAlgorithm, this.encrypted)
24406 ];
24407
24408 return util.concatUint8Array(arr);
24409 }
24410
24411 /**
24412 * Encrypt session key packet
24413 * @param {PublicKeyPacket} key - Public key
24414 * @throws {Error} if encryption failed
24415 * @async
24416 */
24417 async encrypt(key) {
24418 const data = util.concatUint8Array([
24419 new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]),
24420 this.sessionKey,
24421 util.writeChecksum(this.sessionKey)
24422 ]);
24423 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24424 this.encrypted = await mod.publicKeyEncrypt(
24425 algo, key.publicParams, data, key.getFingerprintBytes());
24426 }
24427
24428 /**
24429 * Decrypts the session key (only for public key encrypted session key packets (tag 1)
24430 * @param {SecretKeyPacket} key - decrypted private key
24431 * @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.
24432 * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }
24433 * @throws {Error} if decryption failed, unless `randomSessionKey` is given
24434 * @async
24435 */
24436 async decrypt(key, randomSessionKey) {
24437 // check that session key algo matches the secret key algo
24438 if (this.publicKeyAlgorithm !== key.algorithm) {
24439 throw new Error('Decryption error');
24440 }
24441
24442 const randomPayload = randomSessionKey ? util.concatUint8Array([
24443 new Uint8Array([randomSessionKey.sessionKeyAlgorithm]),
24444 randomSessionKey.sessionKey,
24445 util.writeChecksum(randomSessionKey.sessionKey)
24446 ]) : null;
24447 const decoded = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);
24448 const symmetricAlgoByte = decoded[0];
24449 const sessionKey = decoded.subarray(1, decoded.length - 2);
24450 const checksum = decoded.subarray(decoded.length - 2);
24451 const computedChecksum = util.writeChecksum(sessionKey);
24452 const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];
24453
24454 if (randomSessionKey) {
24455 // We must not leak info about the validity of the decrypted checksum or cipher algo.
24456 // 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.
24457 const isValidPayload = isValidChecksum & symmetricAlgoByte === randomSessionKey.sessionKeyAlgorithm & sessionKey.length === randomSessionKey.sessionKey.length;
24458 this.sessionKeyAlgorithm = util.selectUint8(isValidPayload, symmetricAlgoByte, randomSessionKey.sessionKeyAlgorithm);
24459 this.sessionKey = util.selectUint8Array(isValidPayload, sessionKey, randomSessionKey.sessionKey);
24460
24461 } else {
24462 const isValidPayload = isValidChecksum && enums.read(enums.symmetric, symmetricAlgoByte);
24463 if (isValidPayload) {
24464 this.sessionKey = sessionKey;
24465 this.sessionKeyAlgorithm = symmetricAlgoByte;
24466 } else {
24467 throw new Error('Decryption error');
24468 }
24469 }
24470 }
24471}
24472
24473// GPG4Browsers - An OpenPGP implementation in javascript
24474
24475class S2K {
24476 /**
24477 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24478 */
24479 constructor(config = defaultConfig) {
24480 /**
24481 * Hash function identifier, or 0 for gnu-dummy keys
24482 * @type {module:enums.hash | 0}
24483 */
24484 this.algorithm = enums.hash.sha256;
24485 /**
24486 * enums.s2k identifier or 'gnu-dummy'
24487 * @type {String}
24488 */
24489 this.type = 'iterated';
24490 /** @type {Integer} */
24491 this.c = config.s2kIterationCountByte;
24492 /** Eight bytes of salt in a binary string.
24493 * @type {Uint8Array}
24494 */
24495 this.salt = null;
24496 }
24497
24498 getCount() {
24499 // Exponent bias, defined in RFC4880
24500 const expbias = 6;
24501
24502 return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
24503 }
24504
24505 /**
24506 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
24507 * @param {Uint8Array} bytes - Payload of string-to-key specifier
24508 * @returns {Integer} Actual length of the object.
24509 */
24510 read(bytes) {
24511 let i = 0;
24512 this.type = enums.read(enums.s2k, bytes[i++]);
24513 this.algorithm = bytes[i++];
24514
24515 switch (this.type) {
24516 case 'simple':
24517 break;
24518
24519 case 'salted':
24520 this.salt = bytes.subarray(i, i + 8);
24521 i += 8;
24522 break;
24523
24524 case 'iterated':
24525 this.salt = bytes.subarray(i, i + 8);
24526 i += 8;
24527
24528 // Octet 10: count, a one-octet, coded value
24529 this.c = bytes[i++];
24530 break;
24531
24532 case 'gnu':
24533 if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {
24534 i += 3; // GNU
24535 const gnuExtType = 1000 + bytes[i++];
24536 if (gnuExtType === 1001) {
24537 this.type = 'gnu-dummy';
24538 // GnuPG extension mode 1001 -- don't write secret key at all
24539 } else {
24540 throw new Error('Unknown s2k gnu protection mode.');
24541 }
24542 } else {
24543 throw new Error('Unknown s2k type.');
24544 }
24545 break;
24546
24547 default:
24548 throw new Error('Unknown s2k type.');
24549 }
24550
24551 return i;
24552 }
24553
24554 /**
24555 * Serializes s2k information
24556 * @returns {Uint8Array} Binary representation of s2k.
24557 */
24558 write() {
24559 if (this.type === 'gnu-dummy') {
24560 return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);
24561 }
24562 const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];
24563
24564 switch (this.type) {
24565 case 'simple':
24566 break;
24567 case 'salted':
24568 arr.push(this.salt);
24569 break;
24570 case 'iterated':
24571 arr.push(this.salt);
24572 arr.push(new Uint8Array([this.c]));
24573 break;
24574 case 'gnu':
24575 throw new Error('GNU s2k type not supported.');
24576 default:
24577 throw new Error('Unknown s2k type.');
24578 }
24579
24580 return util.concatUint8Array(arr);
24581 }
24582
24583 /**
24584 * Produces a key using the specified passphrase and the defined
24585 * hashAlgorithm
24586 * @param {String} passphrase - Passphrase containing user input
24587 * @returns {Promise<Uint8Array>} Produced key with a length corresponding to.
24588 * hashAlgorithm hash length
24589 * @async
24590 */
24591 async produceKey(passphrase, numBytes) {
24592 passphrase = util.encodeUTF8(passphrase);
24593
24594 const arr = [];
24595 let rlength = 0;
24596
24597 let prefixlen = 0;
24598 while (rlength < numBytes) {
24599 let toHash;
24600 switch (this.type) {
24601 case 'simple':
24602 toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
24603 break;
24604 case 'salted':
24605 toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
24606 break;
24607 case 'iterated': {
24608 const data = util.concatUint8Array([this.salt, passphrase]);
24609 let datalen = data.length;
24610 const count = Math.max(this.getCount(), datalen);
24611 toHash = new Uint8Array(prefixlen + count);
24612 toHash.set(data, prefixlen);
24613 for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
24614 toHash.copyWithin(pos, prefixlen, pos);
24615 }
24616 break;
24617 }
24618 case 'gnu':
24619 throw new Error('GNU s2k type not supported.');
24620 default:
24621 throw new Error('Unknown s2k type.');
24622 }
24623 const result = await mod.hash.digest(this.algorithm, toHash);
24624 arr.push(result);
24625 rlength += result.length;
24626 prefixlen++;
24627 }
24628
24629 return util.concatUint8Array(arr).subarray(0, numBytes);
24630 }
24631}
24632
24633// GPG4Browsers - An OpenPGP implementation in javascript
24634
24635/**
24636 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
24637 *
24638 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
24639 * The Symmetric-Key Encrypted Session Key packet holds the
24640 * symmetric-key encryption of a session key used to encrypt a message.
24641 * Zero or more Public-Key Encrypted Session Key packets and/or
24642 * Symmetric-Key Encrypted Session Key packets may precede a
24643 * Symmetrically Encrypted Data packet that holds an encrypted message.
24644 * The message is encrypted with a session key, and the session key is
24645 * itself encrypted and stored in the Encrypted Session Key packet or
24646 * the Symmetric-Key Encrypted Session Key packet.
24647 */
24648class SymEncryptedSessionKeyPacket {
24649 static get tag() {
24650 return enums.packet.symEncryptedSessionKey;
24651 }
24652
24653 /**
24654 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24655 */
24656 constructor(config = defaultConfig) {
24657 this.version = config.aeadProtect ? 5 : 4;
24658 this.sessionKey = null;
24659 /**
24660 * Algorithm to encrypt the session key with
24661 * @type {enums.symmetric}
24662 */
24663 this.sessionKeyEncryptionAlgorithm = null;
24664 /**
24665 * Algorithm to encrypt the message with
24666 * @type {enums.symmetric}
24667 */
24668 this.sessionKeyAlgorithm = enums.symmetric.aes256;
24669 /**
24670 * AEAD mode to encrypt the session key with (if AEAD protection is enabled)
24671 * @type {enums.aead}
24672 */
24673 this.aeadAlgorithm = enums.write(enums.aead, config.preferredAEADAlgorithm);
24674 this.encrypted = null;
24675 this.s2k = null;
24676 this.iv = null;
24677 }
24678
24679 /**
24680 * Parsing function for a symmetric encrypted session key packet (tag 3).
24681 *
24682 * @param {Uint8Array} bytes - Payload of a tag 3 packet
24683 */
24684 read(bytes) {
24685 let offset = 0;
24686
24687 // A one-octet version number. The only currently defined version is 4.
24688 this.version = bytes[offset++];
24689 if (this.version !== 4 && this.version !== 5) {
24690 throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);
24691 }
24692
24693 // A one-octet number describing the symmetric algorithm used.
24694 const algo = bytes[offset++];
24695
24696 if (this.version === 5) {
24697 // A one-octet AEAD algorithm.
24698 this.aeadAlgorithm = bytes[offset++];
24699 }
24700
24701 // A string-to-key (S2K) specifier, length as defined above.
24702 this.s2k = new S2K();
24703 offset += this.s2k.read(bytes.subarray(offset, bytes.length));
24704
24705 if (this.version === 5) {
24706 const mode = mod.getAEADMode(this.aeadAlgorithm);
24707
24708 // A starting initialization vector of size specified by the AEAD
24709 // algorithm.
24710 this.iv = bytes.subarray(offset, offset += mode.ivLength);
24711 }
24712
24713 // The encrypted session key itself, which is decrypted with the
24714 // string-to-key object. This is optional in version 4.
24715 if (this.version === 5 || offset < bytes.length) {
24716 this.encrypted = bytes.subarray(offset, bytes.length);
24717 this.sessionKeyEncryptionAlgorithm = algo;
24718 } else {
24719 this.sessionKeyAlgorithm = algo;
24720 }
24721 }
24722
24723 /**
24724 * Create a binary representation of a tag 3 packet
24725 *
24726 * @returns {Uint8Array} The Uint8Array representation.
24727 */
24728 write() {
24729 const algo = this.encrypted === null ?
24730 this.sessionKeyAlgorithm :
24731 this.sessionKeyEncryptionAlgorithm;
24732
24733 let bytes;
24734
24735 if (this.version === 5) {
24736 bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);
24737 } else {
24738 bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);
24739
24740 if (this.encrypted !== null) {
24741 bytes = util.concatUint8Array([bytes, this.encrypted]);
24742 }
24743 }
24744
24745 return bytes;
24746 }
24747
24748 /**
24749 * Decrypts the session key with the given passphrase
24750 * @param {String} passphrase - The passphrase in string form
24751 * @throws {Error} if decryption was not successful
24752 * @async
24753 */
24754 async decrypt(passphrase) {
24755 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24756 this.sessionKeyEncryptionAlgorithm :
24757 this.sessionKeyAlgorithm;
24758
24759 const { blockSize, keySize } = mod.getCipher(algo);
24760 const key = await this.s2k.produceKey(passphrase, keySize);
24761
24762 if (this.version === 5) {
24763 const mode = mod.getAEADMode(this.aeadAlgorithm);
24764 const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
24765 const modeInstance = await mode(algo, key);
24766 this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
24767 } else if (this.encrypted !== null) {
24768 const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));
24769
24770 this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);
24771 this.sessionKey = decrypted.subarray(1, decrypted.length);
24772 } else {
24773 this.sessionKey = key;
24774 }
24775 }
24776
24777 /**
24778 * Encrypts the session key with the given passphrase
24779 * @param {String} passphrase - The passphrase in string form
24780 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24781 * @throws {Error} if encryption was not successful
24782 * @async
24783 */
24784 async encrypt(passphrase, config = defaultConfig) {
24785 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24786 this.sessionKeyEncryptionAlgorithm :
24787 this.sessionKeyAlgorithm;
24788
24789 this.sessionKeyEncryptionAlgorithm = algo;
24790
24791 this.s2k = new S2K(config);
24792 this.s2k.salt = await mod.random.getRandomBytes(8);
24793
24794 const { blockSize, keySize } = mod.getCipher(algo);
24795 const encryptionKey = await this.s2k.produceKey(passphrase, keySize);
24796
24797 if (this.sessionKey === null) {
24798 this.sessionKey = await mod.generateSessionKey(this.sessionKeyAlgorithm);
24799 }
24800
24801 if (this.version === 5) {
24802 const mode = mod.getAEADMode(this.aeadAlgorithm);
24803 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
24804 const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
24805 const modeInstance = await mode(algo, encryptionKey);
24806 this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);
24807 } else {
24808 const toEncrypt = util.concatUint8Array([
24809 new Uint8Array([this.sessionKeyAlgorithm]),
24810 this.sessionKey
24811 ]);
24812 this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config);
24813 }
24814 }
24815}
24816
24817// GPG4Browsers - An OpenPGP implementation in javascript
24818
24819/**
24820 * Implementation of the Key Material Packet (Tag 5,6,7,14)
24821 *
24822 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
24823 * A key material packet contains all the information about a public or
24824 * private key. There are four variants of this packet type, and two
24825 * major versions.
24826 *
24827 * A Public-Key packet starts a series of packets that forms an OpenPGP
24828 * key (sometimes called an OpenPGP certificate).
24829 */
24830class PublicKeyPacket {
24831 static get tag() {
24832 return enums.packet.publicKey;
24833 }
24834
24835 /**
24836 * @param {Date} [date] - Creation date
24837 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24838 */
24839 constructor(date = new Date(), config = defaultConfig) {
24840 /**
24841 * Packet version
24842 * @type {Integer}
24843 */
24844 this.version = config.v5Keys ? 5 : 4;
24845 /**
24846 * Key creation date.
24847 * @type {Date}
24848 */
24849 this.created = util.normalizeDate(date);
24850 /**
24851 * Public key algorithm.
24852 * @type {enums.publicKey}
24853 */
24854 this.algorithm = null;
24855 /**
24856 * Algorithm specific public params
24857 * @type {Object}
24858 */
24859 this.publicParams = null;
24860 /**
24861 * Time until expiration in days (V3 only)
24862 * @type {Integer}
24863 */
24864 this.expirationTimeV3 = 0;
24865 /**
24866 * Fingerprint bytes
24867 * @type {Uint8Array}
24868 */
24869 this.fingerprint = null;
24870 /**
24871 * KeyID
24872 * @type {module:type/keyid~KeyID}
24873 */
24874 this.keyID = null;
24875 }
24876
24877 /**
24878 * Create a PublicKeyPacket from a SecretKeyPacket
24879 * @param {SecretKeyPacket} secretKeyPacket - key packet to convert
24880 * @returns {PublicKeyPacket} public key packet
24881 * @static
24882 */
24883 static fromSecretKeyPacket(secretKeyPacket) {
24884 const keyPacket = new PublicKeyPacket();
24885 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;
24886 keyPacket.version = version;
24887 keyPacket.created = created;
24888 keyPacket.algorithm = algorithm;
24889 keyPacket.publicParams = publicParams;
24890 keyPacket.keyID = keyID;
24891 keyPacket.fingerprint = fingerprint;
24892 return keyPacket;
24893 }
24894
24895 /**
24896 * 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}
24897 * @param {Uint8Array} bytes - Input array to read the packet from
24898 * @returns {Object} This object with attributes set by the parser
24899 * @async
24900 */
24901 async read(bytes) {
24902 let pos = 0;
24903 // A one-octet version number (3, 4 or 5).
24904 this.version = bytes[pos++];
24905
24906 if (this.version === 4 || this.version === 5) {
24907 // - A four-octet number denoting the time that the key was created.
24908 this.created = util.readDate(bytes.subarray(pos, pos + 4));
24909 pos += 4;
24910
24911 // - A one-octet number denoting the public-key algorithm of this key.
24912 this.algorithm = bytes[pos++];
24913
24914 if (this.version === 5) {
24915 // - A four-octet scalar octet count for the following key material.
24916 pos += 4;
24917 }
24918
24919 // - A series of values comprising the key material.
24920 const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));
24921 this.publicParams = publicParams;
24922 pos += read;
24923
24924 // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor
24925 await this.computeFingerprintAndKeyID();
24926 return pos;
24927 }
24928 throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);
24929 }
24930
24931 /**
24932 * Creates an OpenPGP public key packet for the given key.
24933 * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
24934 */
24935 write() {
24936 const arr = [];
24937 // Version
24938 arr.push(new Uint8Array([this.version]));
24939 arr.push(util.writeDate(this.created));
24940 // A one-octet number denoting the public-key algorithm of this key
24941 arr.push(new Uint8Array([this.algorithm]));
24942
24943 const params = mod.serializeParams(this.algorithm, this.publicParams);
24944 if (this.version === 5) {
24945 // A four-octet scalar octet count for the following key material
24946 arr.push(util.writeNumber(params.length, 4));
24947 }
24948 // Algorithm-specific params
24949 arr.push(params);
24950 return util.concatUint8Array(arr);
24951 }
24952
24953 /**
24954 * Write packet in order to be hashed; either for a signature or a fingerprint
24955 * @param {Integer} version - target version of signature or key
24956 */
24957 writeForHash(version) {
24958 const bytes = this.writePublicKey();
24959
24960 if (version === 5) {
24961 return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);
24962 }
24963 return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);
24964 }
24965
24966 /**
24967 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
24968 * @returns {Boolean|null}
24969 */
24970 isDecrypted() {
24971 return null;
24972 }
24973
24974 /**
24975 * Returns the creation time of the key
24976 * @returns {Date}
24977 */
24978 getCreationTime() {
24979 return this.created;
24980 }
24981
24982 /**
24983 * Return the key ID of the key
24984 * @returns {module:type/keyid~KeyID} The 8-byte key ID
24985 */
24986 getKeyID() {
24987 return this.keyID;
24988 }
24989
24990 /**
24991 * Computes and set the key ID and fingerprint of the key
24992 * @async
24993 */
24994 async computeFingerprintAndKeyID() {
24995 await this.computeFingerprint();
24996 this.keyID = new KeyID();
24997
24998 if (this.version === 5) {
24999 this.keyID.read(this.fingerprint.subarray(0, 8));
25000 } else if (this.version === 4) {
25001 this.keyID.read(this.fingerprint.subarray(12, 20));
25002 } else {
25003 throw new Error('Unsupported key version');
25004 }
25005 }
25006
25007 /**
25008 * Computes and set the fingerprint of the key
25009 */
25010 async computeFingerprint() {
25011 const toHash = this.writeForHash(this.version);
25012
25013 if (this.version === 5) {
25014 this.fingerprint = await mod.hash.sha256(toHash);
25015 } else if (this.version === 4) {
25016 this.fingerprint = await mod.hash.sha1(toHash);
25017 } else {
25018 throw new Error('Unsupported key version');
25019 }
25020 }
25021
25022 /**
25023 * Returns the fingerprint of the key, as an array of bytes
25024 * @returns {Uint8Array} A Uint8Array containing the fingerprint
25025 */
25026 getFingerprintBytes() {
25027 return this.fingerprint;
25028 }
25029
25030 /**
25031 * Calculates and returns the fingerprint of the key, as a string
25032 * @returns {String} A string containing the fingerprint in lowercase hex
25033 */
25034 getFingerprint() {
25035 return util.uint8ArrayToHex(this.getFingerprintBytes());
25036 }
25037
25038 /**
25039 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
25040 * @returns {Boolean} Whether the two keys have the same version and public key data.
25041 */
25042 hasSameFingerprintAs(other) {
25043 return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
25044 }
25045
25046 /**
25047 * Returns algorithm information
25048 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
25049 */
25050 getAlgorithmInfo() {
25051 const result = {};
25052 result.algorithm = enums.read(enums.publicKey, this.algorithm);
25053 // RSA, DSA or ElGamal public modulo
25054 const modulo = this.publicParams.n || this.publicParams.p;
25055 if (modulo) {
25056 result.bits = util.uint8ArrayBitLength(modulo);
25057 } else {
25058 result.curve = this.publicParams.oid.getName();
25059 }
25060 return result;
25061 }
25062}
25063
25064/**
25065 * Alias of read()
25066 * @see PublicKeyPacket#read
25067 */
25068PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
25069
25070/**
25071 * Alias of write()
25072 * @see PublicKeyPacket#write
25073 */
25074PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;
25075
25076// GPG4Browsers - An OpenPGP implementation in javascript
25077
25078// A SE packet can contain the following packet types
25079const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([
25080 LiteralDataPacket,
25081 CompressedDataPacket,
25082 OnePassSignaturePacket,
25083 SignaturePacket
25084]);
25085
25086/**
25087 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
25088 *
25089 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
25090 * The Symmetrically Encrypted Data packet contains data encrypted with a
25091 * symmetric-key algorithm. When it has been decrypted, it contains other
25092 * packets (usually a literal data packet or compressed data packet, but in
25093 * theory other Symmetrically Encrypted Data packets or sequences of packets
25094 * that form whole OpenPGP messages).
25095 */
25096class SymmetricallyEncryptedDataPacket {
25097 static get tag() {
25098 return enums.packet.symmetricallyEncryptedData;
25099 }
25100
25101 constructor() {
25102 /**
25103 * Encrypted secret-key data
25104 */
25105 this.encrypted = null;
25106 /**
25107 * Decrypted packets contained within.
25108 * @type {PacketList}
25109 */
25110 this.packets = null;
25111 }
25112
25113 read(bytes) {
25114 this.encrypted = bytes;
25115 }
25116
25117 write() {
25118 return this.encrypted;
25119 }
25120
25121 /**
25122 * Decrypt the symmetrically-encrypted packet data
25123 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25124 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25125 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25126 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25127
25128 * @throws {Error} if decryption was not successful
25129 * @async
25130 */
25131 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
25132 // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
25133 if (!config.allowUnauthenticatedMessages) {
25134 throw new Error('Message is not authenticated.');
25135 }
25136
25137 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25138 const encrypted = await readToEnd(clone(this.encrypted));
25139 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key,
25140 encrypted.subarray(blockSize + 2),
25141 encrypted.subarray(2, blockSize + 2)
25142 );
25143
25144 this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config);
25145 }
25146
25147 /**
25148 * Encrypt the symmetrically-encrypted packet data
25149 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25150 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25151 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25152 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25153 * @throws {Error} if encryption was not successful
25154 * @async
25155 */
25156 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
25157 const data = this.packets.write();
25158 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25159
25160 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
25161 const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config);
25162 const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config);
25163 this.encrypted = util.concat([FRE, ciphertext]);
25164 }
25165}
25166
25167// GPG4Browsers - An OpenPGP implementation in javascript
25168
25169/**
25170 * Implementation of the strange "Marker packet" (Tag 10)
25171 *
25172 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
25173 * An experimental version of PGP used this packet as the Literal
25174 * packet, but no released version of PGP generated Literal packets with this
25175 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
25176 * the Marker packet.
25177 *
25178 * The body of this packet consists of:
25179 * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8).
25180 *
25181 * Such a packet MUST be ignored when received. It may be placed at the
25182 * beginning of a message that uses features not available in PGP
25183 * version 2.6 in order to cause that version to report that newer
25184 * software is necessary to process the message.
25185 */
25186class MarkerPacket {
25187 static get tag() {
25188 return enums.packet.marker;
25189 }
25190
25191 /**
25192 * Parsing function for a marker data packet (tag 10).
25193 * @param {Uint8Array} bytes - Payload of a tag 10 packet
25194 * @returns {Boolean} whether the packet payload contains "PGP"
25195 */
25196 read(bytes) {
25197 if (bytes[0] === 0x50 && // P
25198 bytes[1] === 0x47 && // G
25199 bytes[2] === 0x50) { // P
25200 return true;
25201 }
25202 return false;
25203 }
25204
25205 write() {
25206 return new Uint8Array([0x50, 0x47, 0x50]);
25207 }
25208}
25209
25210// GPG4Browsers - An OpenPGP implementation in javascript
25211
25212/**
25213 * A Public-Subkey packet (tag 14) has exactly the same format as a
25214 * Public-Key packet, but denotes a subkey. One or more subkeys may be
25215 * associated with a top-level key. By convention, the top-level key
25216 * provides signature services, and the subkeys provide encryption
25217 * services.
25218 * @extends PublicKeyPacket
25219 */
25220class PublicSubkeyPacket extends PublicKeyPacket {
25221 static get tag() {
25222 return enums.packet.publicSubkey;
25223 }
25224
25225 /**
25226 * @param {Date} [date] - Creation date
25227 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25228 */
25229 // eslint-disable-next-line no-useless-constructor
25230 constructor(date, config) {
25231 super(date, config);
25232 }
25233
25234 /**
25235 * Create a PublicSubkeyPacket from a SecretSubkeyPacket
25236 * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert
25237 * @returns {SecretSubkeyPacket} public key packet
25238 * @static
25239 */
25240 static fromSecretSubkeyPacket(secretSubkeyPacket) {
25241 const keyPacket = new PublicSubkeyPacket();
25242 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;
25243 keyPacket.version = version;
25244 keyPacket.created = created;
25245 keyPacket.algorithm = algorithm;
25246 keyPacket.publicParams = publicParams;
25247 keyPacket.keyID = keyID;
25248 keyPacket.fingerprint = fingerprint;
25249 return keyPacket;
25250 }
25251}
25252
25253// GPG4Browsers - An OpenPGP implementation in javascript
25254
25255/**
25256 * Implementation of the User Attribute Packet (Tag 17)
25257 *
25258 * The User Attribute packet is a variation of the User ID packet. It
25259 * is capable of storing more types of data than the User ID packet,
25260 * which is limited to text. Like the User ID packet, a User Attribute
25261 * packet may be certified by the key owner ("self-signed") or any other
25262 * key owner who cares to certify it. Except as noted, a User Attribute
25263 * packet may be used anywhere that a User ID packet may be used.
25264 *
25265 * While User Attribute packets are not a required part of the OpenPGP
25266 * standard, implementations SHOULD provide at least enough
25267 * compatibility to properly handle a certification signature on the
25268 * User Attribute packet. A simple way to do this is by treating the
25269 * User Attribute packet as a User ID packet with opaque contents, but
25270 * an implementation may use any method desired.
25271 */
25272class UserAttributePacket {
25273 static get tag() {
25274 return enums.packet.userAttribute;
25275 }
25276
25277 constructor() {
25278 this.attributes = [];
25279 }
25280
25281 /**
25282 * parsing function for a user attribute packet (tag 17).
25283 * @param {Uint8Array} input - Payload of a tag 17 packet
25284 */
25285 read(bytes) {
25286 let i = 0;
25287 while (i < bytes.length) {
25288 const len = readSimpleLength(bytes.subarray(i, bytes.length));
25289 i += len.offset;
25290
25291 this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));
25292 i += len.len;
25293 }
25294 }
25295
25296 /**
25297 * Creates a binary representation of the user attribute packet
25298 * @returns {Uint8Array} String representation.
25299 */
25300 write() {
25301 const arr = [];
25302 for (let i = 0; i < this.attributes.length; i++) {
25303 arr.push(writeSimpleLength(this.attributes[i].length));
25304 arr.push(util.stringToUint8Array(this.attributes[i]));
25305 }
25306 return util.concatUint8Array(arr);
25307 }
25308
25309 /**
25310 * Compare for equality
25311 * @param {UserAttributePacket} usrAttr
25312 * @returns {Boolean} True if equal.
25313 */
25314 equals(usrAttr) {
25315 if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
25316 return false;
25317 }
25318 return this.attributes.every(function(attr, index) {
25319 return attr === usrAttr.attributes[index];
25320 });
25321 }
25322}
25323
25324// GPG4Browsers - An OpenPGP implementation in javascript
25325
25326/**
25327 * A Secret-Key packet contains all the information that is found in a
25328 * Public-Key packet, including the public-key material, but also
25329 * includes the secret-key material after all the public-key fields.
25330 * @extends PublicKeyPacket
25331 */
25332class SecretKeyPacket extends PublicKeyPacket {
25333 static get tag() {
25334 return enums.packet.secretKey;
25335 }
25336
25337 /**
25338 * @param {Date} [date] - Creation date
25339 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25340 */
25341 constructor(date = new Date(), config = defaultConfig) {
25342 super(date, config);
25343 /**
25344 * Secret-key data
25345 */
25346 this.keyMaterial = null;
25347 /**
25348 * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
25349 */
25350 this.isEncrypted = null;
25351 /**
25352 * S2K usage
25353 * @type {enums.symmetric}
25354 */
25355 this.s2kUsage = 0;
25356 /**
25357 * S2K object
25358 * @type {type/s2k}
25359 */
25360 this.s2k = null;
25361 /**
25362 * Symmetric algorithm to encrypt the key with
25363 * @type {enums.symmetric}
25364 */
25365 this.symmetric = null;
25366 /**
25367 * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)
25368 * @type {enums.aead}
25369 */
25370 this.aead = null;
25371 /**
25372 * Decrypted private parameters, referenced by name
25373 * @type {Object}
25374 */
25375 this.privateParams = null;
25376 }
25377
25378 // 5.5.3. Secret-Key Packet Formats
25379
25380 /**
25381 * Internal parser for private keys as specified in
25382 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
25383 * @param {Uint8Array} bytes - Input string to read the packet from
25384 * @async
25385 */
25386 async read(bytes) {
25387 // - A Public-Key or Public-Subkey packet, as described above.
25388 let i = await this.readPublicKey(bytes);
25389
25390 // - One octet indicating string-to-key usage conventions. Zero
25391 // indicates that the secret-key data is not encrypted. 255 or 254
25392 // indicates that a string-to-key specifier is being given. Any
25393 // other value is a symmetric-key encryption algorithm identifier.
25394 this.s2kUsage = bytes[i++];
25395
25396 // - Only for a version 5 packet, a one-octet scalar octet count of
25397 // the next 4 optional fields.
25398 if (this.version === 5) {
25399 i++;
25400 }
25401
25402 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25403 // one-octet symmetric encryption algorithm.
25404 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25405 this.symmetric = bytes[i++];
25406
25407 // - [Optional] If string-to-key usage octet was 253, a one-octet
25408 // AEAD algorithm.
25409 if (this.s2kUsage === 253) {
25410 this.aead = bytes[i++];
25411 }
25412
25413 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25414 // string-to-key specifier. The length of the string-to-key
25415 // specifier is implied by its type, as described above.
25416 this.s2k = new S2K();
25417 i += this.s2k.read(bytes.subarray(i, bytes.length));
25418
25419 if (this.s2k.type === 'gnu-dummy') {
25420 return;
25421 }
25422 } else if (this.s2kUsage) {
25423 this.symmetric = this.s2kUsage;
25424 }
25425
25426 // - [Optional] If secret data is encrypted (string-to-key usage octet
25427 // not zero), an Initial Vector (IV) of the same length as the
25428 // cipher's block size.
25429 if (this.s2kUsage) {
25430 this.iv = bytes.subarray(
25431 i,
25432 i + mod.getCipher(this.symmetric).blockSize
25433 );
25434
25435 i += this.iv.length;
25436 }
25437
25438 // - Only for a version 5 packet, a four-octet scalar octet count for
25439 // the following key material.
25440 if (this.version === 5) {
25441 i += 4;
25442 }
25443
25444 // - Plain or encrypted multiprecision integers comprising the secret
25445 // key data. These algorithm-specific fields are as described
25446 // below.
25447 this.keyMaterial = bytes.subarray(i);
25448 this.isEncrypted = !!this.s2kUsage;
25449
25450 if (!this.isEncrypted) {
25451 const cleartext = this.keyMaterial.subarray(0, -2);
25452 if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
25453 throw new Error('Key checksum mismatch');
25454 }
25455 try {
25456 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
25457 this.privateParams = privateParams;
25458 } catch (err) {
25459 if (err instanceof UnsupportedError) throw err;
25460 // avoid throwing potentially sensitive errors
25461 throw new Error('Error reading MPIs');
25462 }
25463 }
25464 }
25465
25466 /**
25467 * Creates an OpenPGP key packet for the given key.
25468 * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
25469 */
25470 write() {
25471 const arr = [this.writePublicKey()];
25472
25473 arr.push(new Uint8Array([this.s2kUsage]));
25474
25475 const optionalFieldsArr = [];
25476 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25477 // one- octet symmetric encryption algorithm.
25478 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25479 optionalFieldsArr.push(this.symmetric);
25480
25481 // - [Optional] If string-to-key usage octet was 253, a one-octet
25482 // AEAD algorithm.
25483 if (this.s2kUsage === 253) {
25484 optionalFieldsArr.push(this.aead);
25485 }
25486
25487 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25488 // string-to-key specifier. The length of the string-to-key
25489 // specifier is implied by its type, as described above.
25490 optionalFieldsArr.push(...this.s2k.write());
25491 }
25492
25493 // - [Optional] If secret data is encrypted (string-to-key usage octet
25494 // not zero), an Initial Vector (IV) of the same length as the
25495 // cipher's block size.
25496 if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {
25497 optionalFieldsArr.push(...this.iv);
25498 }
25499
25500 if (this.version === 5) {
25501 arr.push(new Uint8Array([optionalFieldsArr.length]));
25502 }
25503 arr.push(new Uint8Array(optionalFieldsArr));
25504
25505 if (!this.isDummy()) {
25506 if (!this.s2kUsage) {
25507 this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams);
25508 }
25509
25510 if (this.version === 5) {
25511 arr.push(util.writeNumber(this.keyMaterial.length, 4));
25512 }
25513 arr.push(this.keyMaterial);
25514
25515 if (!this.s2kUsage) {
25516 arr.push(util.writeChecksum(this.keyMaterial));
25517 }
25518 }
25519
25520 return util.concatUint8Array(arr);
25521 }
25522
25523 /**
25524 * Check whether secret-key data is available in decrypted form.
25525 * Returns false for gnu-dummy keys and null for public keys.
25526 * @returns {Boolean|null}
25527 */
25528 isDecrypted() {
25529 return this.isEncrypted === false;
25530 }
25531
25532 /**
25533 * Check whether this is a gnu-dummy key
25534 * @returns {Boolean}
25535 */
25536 isDummy() {
25537 return !!(this.s2k && this.s2k.type === 'gnu-dummy');
25538 }
25539
25540 /**
25541 * Remove private key material, converting the key to a dummy one.
25542 * The resulting key cannot be used for signing/decrypting but can still verify signatures.
25543 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25544 */
25545 makeDummy(config = defaultConfig) {
25546 if (this.isDummy()) {
25547 return;
25548 }
25549 if (this.isDecrypted()) {
25550 this.clearPrivateParams();
25551 }
25552 this.isEncrypted = null;
25553 this.keyMaterial = null;
25554 this.s2k = new S2K(config);
25555 this.s2k.algorithm = 0;
25556 this.s2k.c = 0;
25557 this.s2k.type = 'gnu-dummy';
25558 this.s2kUsage = 254;
25559 this.symmetric = enums.symmetric.aes256;
25560 }
25561
25562 /**
25563 * Encrypt the payload. By default, we use aes256 and iterated, salted string
25564 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
25565 * and the passphrase is empty or undefined, the key will be set as not encrypted.
25566 * This can be used to remove passphrase protection after calling decrypt().
25567 * @param {String} passphrase
25568 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25569 * @throws {Error} if encryption was not successful
25570 * @async
25571 */
25572 async encrypt(passphrase, config = defaultConfig) {
25573 if (this.isDummy()) {
25574 return;
25575 }
25576
25577 if (!this.isDecrypted()) {
25578 throw new Error('Key packet is already encrypted');
25579 }
25580
25581 if (!passphrase) {
25582 throw new Error('A non-empty passphrase is required for key encryption.');
25583 }
25584
25585 this.s2k = new S2K(config);
25586 this.s2k.salt = await mod.random.getRandomBytes(8);
25587 const cleartext = mod.serializeParams(this.algorithm, this.privateParams);
25588 this.symmetric = enums.symmetric.aes256;
25589 const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25590
25591 const { blockSize } = mod.getCipher(this.symmetric);
25592 this.iv = await mod.random.getRandomBytes(blockSize);
25593
25594 if (config.aeadProtect) {
25595 this.s2kUsage = 253;
25596 this.aead = enums.aead.eax;
25597 const mode = mod.getAEADMode(this.aead);
25598 const modeInstance = await mode(this.symmetric, key);
25599 this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25600 } else {
25601 this.s2kUsage = 254;
25602 this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([
25603 cleartext,
25604 await mod.hash.sha1(cleartext, config)
25605 ]), this.iv, config);
25606 }
25607 }
25608
25609 /**
25610 * Decrypts the private key params which are needed to use the key.
25611 * Successful decryption does not imply key integrity, call validate() to confirm that.
25612 * {@link SecretKeyPacket.isDecrypted} should be false, as
25613 * otherwise calls to this function will throw an error.
25614 * @param {String} passphrase - The passphrase for this private key as string
25615 * @throws {Error} if the key is already decrypted, or if decryption was not successful
25616 * @async
25617 */
25618 async decrypt(passphrase) {
25619 if (this.isDummy()) {
25620 return false;
25621 }
25622
25623 if (this.isDecrypted()) {
25624 throw new Error('Key packet is already decrypted.');
25625 }
25626
25627 let key;
25628 if (this.s2kUsage === 254 || this.s2kUsage === 253) {
25629 key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25630 } else if (this.s2kUsage === 255) {
25631 throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
25632 } else {
25633 throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
25634 }
25635
25636 let cleartext;
25637 if (this.s2kUsage === 253) {
25638 const mode = mod.getAEADMode(this.aead);
25639 const modeInstance = await mode(this.symmetric, key);
25640 try {
25641 cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25642 } catch (err) {
25643 if (err.message === 'Authentication tag mismatch') {
25644 throw new Error('Incorrect key passphrase: ' + err.message);
25645 }
25646 throw err;
25647 }
25648 } else {
25649 const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
25650
25651 cleartext = cleartextWithHash.subarray(0, -20);
25652 const hash = await mod.hash.sha1(cleartext);
25653
25654 if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
25655 throw new Error('Incorrect key passphrase');
25656 }
25657 }
25658
25659 try {
25660 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
25661 this.privateParams = privateParams;
25662 } catch (err) {
25663 throw new Error('Error reading MPIs');
25664 }
25665 this.isEncrypted = false;
25666 this.keyMaterial = null;
25667 this.s2kUsage = 0;
25668 }
25669
25670 /**
25671 * Checks that the key parameters are consistent
25672 * @throws {Error} if validation was not successful
25673 * @async
25674 */
25675 async validate() {
25676 if (this.isDummy()) {
25677 return;
25678 }
25679
25680 if (!this.isDecrypted()) {
25681 throw new Error('Key is not decrypted');
25682 }
25683
25684 let validParams;
25685 try {
25686 // this can throw if some parameters are undefined
25687 validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams);
25688 } catch (_) {
25689 validParams = false;
25690 }
25691 if (!validParams) {
25692 throw new Error('Key is invalid');
25693 }
25694 }
25695
25696 async generate(bits, curve) {
25697 const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve);
25698 this.privateParams = privateParams;
25699 this.publicParams = publicParams;
25700 this.isEncrypted = false;
25701 }
25702
25703 /**
25704 * Clear private key parameters
25705 */
25706 clearPrivateParams() {
25707 if (this.isDummy()) {
25708 return;
25709 }
25710
25711 Object.keys(this.privateParams).forEach(name => {
25712 const param = this.privateParams[name];
25713 param.fill(0);
25714 delete this.privateParams[name];
25715 });
25716 this.privateParams = null;
25717 this.isEncrypted = true;
25718 }
25719}
25720
25721async function produceEncryptionKey(s2k, passphrase, algorithm) {
25722 const { keySize } = mod.getCipher(algorithm);
25723 return s2k.produceKey(passphrase, keySize);
25724}
25725
25726var emailAddresses = createCommonjsModule(function (module) {
25727// email-addresses.js - RFC 5322 email address parser
25728// v 3.1.0
25729//
25730// http://tools.ietf.org/html/rfc5322
25731//
25732// This library does not validate email addresses.
25733// emailAddresses attempts to parse addresses using the (fairly liberal)
25734// grammar specified in RFC 5322.
25735//
25736// email-addresses returns {
25737// ast: <an abstract syntax tree based on rfc5322>,
25738// addresses: [{
25739// node: <node in ast for this address>,
25740// name: <display-name>,
25741// address: <addr-spec>,
25742// local: <local-part>,
25743// domain: <domain>
25744// }, ...]
25745// }
25746//
25747// emailAddresses.parseOneAddress and emailAddresses.parseAddressList
25748// work as you might expect. Try it out.
25749//
25750// Many thanks to Dominic Sayers and his documentation on the is_email function,
25751// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
25752
25753(function (global) {
25754
25755function parse5322(opts) {
25756
25757 // tokenizing functions
25758
25759 function inStr() { return pos < len; }
25760 function curTok() { return parseString[pos]; }
25761 function getPos() { return pos; }
25762 function setPos(i) { pos = i; }
25763 function nextTok() { pos += 1; }
25764 function initialize() {
25765 pos = 0;
25766 len = parseString.length;
25767 }
25768
25769 // parser helper functions
25770
25771 function o(name, value) {
25772 return {
25773 name: name,
25774 tokens: value || "",
25775 semantic: value || "",
25776 children: []
25777 };
25778 }
25779
25780 function wrap(name, ast) {
25781 var n;
25782 if (ast === null) { return null; }
25783 n = o(name);
25784 n.tokens = ast.tokens;
25785 n.semantic = ast.semantic;
25786 n.children.push(ast);
25787 return n;
25788 }
25789
25790 function add(parent, child) {
25791 if (child !== null) {
25792 parent.tokens += child.tokens;
25793 parent.semantic += child.semantic;
25794 }
25795 parent.children.push(child);
25796 return parent;
25797 }
25798
25799 function compareToken(fxnCompare) {
25800 var tok;
25801 if (!inStr()) { return null; }
25802 tok = curTok();
25803 if (fxnCompare(tok)) {
25804 nextTok();
25805 return o('token', tok);
25806 }
25807 return null;
25808 }
25809
25810 function literal(lit) {
25811 return function literalFunc() {
25812 return wrap('literal', compareToken(function (tok) {
25813 return tok === lit;
25814 }));
25815 };
25816 }
25817
25818 function and() {
25819 var args = arguments;
25820 return function andFunc() {
25821 var i, s, result, start;
25822 start = getPos();
25823 s = o('and');
25824 for (i = 0; i < args.length; i += 1) {
25825 result = args[i]();
25826 if (result === null) {
25827 setPos(start);
25828 return null;
25829 }
25830 add(s, result);
25831 }
25832 return s;
25833 };
25834 }
25835
25836 function or() {
25837 var args = arguments;
25838 return function orFunc() {
25839 var i, result, start;
25840 start = getPos();
25841 for (i = 0; i < args.length; i += 1) {
25842 result = args[i]();
25843 if (result !== null) {
25844 return result;
25845 }
25846 setPos(start);
25847 }
25848 return null;
25849 };
25850 }
25851
25852 function opt(prod) {
25853 return function optFunc() {
25854 var result, start;
25855 start = getPos();
25856 result = prod();
25857 if (result !== null) {
25858 return result;
25859 }
25860 else {
25861 setPos(start);
25862 return o('opt');
25863 }
25864 };
25865 }
25866
25867 function invis(prod) {
25868 return function invisFunc() {
25869 var result = prod();
25870 if (result !== null) {
25871 result.semantic = "";
25872 }
25873 return result;
25874 };
25875 }
25876
25877 function colwsp(prod) {
25878 return function collapseSemanticWhitespace() {
25879 var result = prod();
25880 if (result !== null && result.semantic.length > 0) {
25881 result.semantic = " ";
25882 }
25883 return result;
25884 };
25885 }
25886
25887 function star(prod, minimum) {
25888 return function starFunc() {
25889 var s, result, count, start, min;
25890 start = getPos();
25891 s = o('star');
25892 count = 0;
25893 min = minimum === undefined ? 0 : minimum;
25894 while ((result = prod()) !== null) {
25895 count = count + 1;
25896 add(s, result);
25897 }
25898 if (count >= min) {
25899 return s;
25900 }
25901 else {
25902 setPos(start);
25903 return null;
25904 }
25905 };
25906 }
25907
25908 // One expects names to get normalized like this:
25909 // " First Last " -> "First Last"
25910 // "First Last" -> "First Last"
25911 // "First Last" -> "First Last"
25912 function collapseWhitespace(s) {
25913 return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
25914 }
25915
25916 // UTF-8 pseudo-production (RFC 6532)
25917 // RFC 6532 extends RFC 5322 productions to include UTF-8
25918 // using the following productions:
25919 // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
25920 // UTF8-2 = <Defined in Section 4 of RFC3629>
25921 // UTF8-3 = <Defined in Section 4 of RFC3629>
25922 // UTF8-4 = <Defined in Section 4 of RFC3629>
25923 //
25924 // For reference, the extended RFC 5322 productions are:
25925 // VCHAR =/ UTF8-non-ascii
25926 // ctext =/ UTF8-non-ascii
25927 // atext =/ UTF8-non-ascii
25928 // qtext =/ UTF8-non-ascii
25929 // dtext =/ UTF8-non-ascii
25930 function isUTF8NonAscii(tok) {
25931 // In JavaScript, we just deal directly with Unicode code points,
25932 // so we aren't checking individual bytes for UTF-8 encoding.
25933 // Just check that the character is non-ascii.
25934 return tok.charCodeAt(0) >= 128;
25935 }
25936
25937
25938 // common productions (RFC 5234)
25939 // http://tools.ietf.org/html/rfc5234
25940 // B.1. Core Rules
25941
25942 // CR = %x0D
25943 // ; carriage return
25944 function cr() { return wrap('cr', literal('\r')()); }
25945
25946 // CRLF = CR LF
25947 // ; Internet standard newline
25948 function crlf() { return wrap('crlf', and(cr, lf)()); }
25949
25950 // DQUOTE = %x22
25951 // ; " (Double Quote)
25952 function dquote() { return wrap('dquote', literal('"')()); }
25953
25954 // HTAB = %x09
25955 // ; horizontal tab
25956 function htab() { return wrap('htab', literal('\t')()); }
25957
25958 // LF = %x0A
25959 // ; linefeed
25960 function lf() { return wrap('lf', literal('\n')()); }
25961
25962 // SP = %x20
25963 function sp() { return wrap('sp', literal(' ')()); }
25964
25965 // VCHAR = %x21-7E
25966 // ; visible (printing) characters
25967 function vchar() {
25968 return wrap('vchar', compareToken(function vcharFunc(tok) {
25969 var code = tok.charCodeAt(0);
25970 var accept = (0x21 <= code && code <= 0x7E);
25971 if (opts.rfc6532) {
25972 accept = accept || isUTF8NonAscii(tok);
25973 }
25974 return accept;
25975 }));
25976 }
25977
25978 // WSP = SP / HTAB
25979 // ; white space
25980 function wsp() { return wrap('wsp', or(sp, htab)()); }
25981
25982
25983 // email productions (RFC 5322)
25984 // http://tools.ietf.org/html/rfc5322
25985 // 3.2.1. Quoted characters
25986
25987 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
25988 function quotedPair() {
25989 var qp = wrap('quoted-pair',
25990 or(
25991 and(literal('\\'), or(vchar, wsp)),
25992 obsQP
25993 )());
25994 if (qp === null) { return null; }
25995 // a quoted pair will be two characters, and the "\" character
25996 // should be semantically "invisible" (RFC 5322 3.2.1)
25997 qp.semantic = qp.semantic[1];
25998 return qp;
25999 }
26000
26001 // 3.2.2. Folding White Space and Comments
26002
26003 // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
26004 function fws() {
26005 return wrap('fws', or(
26006 obsFws,
26007 and(
26008 opt(and(
26009 star(wsp),
26010 invis(crlf)
26011 )),
26012 star(wsp, 1)
26013 )
26014 )());
26015 }
26016
26017 // ctext = %d33-39 / ; Printable US-ASCII
26018 // %d42-91 / ; characters not including
26019 // %d93-126 / ; "(", ")", or "\"
26020 // obs-ctext
26021 function ctext() {
26022 return wrap('ctext', or(
26023 function ctextFunc1() {
26024 return compareToken(function ctextFunc2(tok) {
26025 var code = tok.charCodeAt(0);
26026 var accept =
26027 (33 <= code && code <= 39) ||
26028 (42 <= code && code <= 91) ||
26029 (93 <= code && code <= 126);
26030 if (opts.rfc6532) {
26031 accept = accept || isUTF8NonAscii(tok);
26032 }
26033 return accept;
26034 });
26035 },
26036 obsCtext
26037 )());
26038 }
26039
26040 // ccontent = ctext / quoted-pair / comment
26041 function ccontent() {
26042 return wrap('ccontent', or(ctext, quotedPair, comment)());
26043 }
26044
26045 // comment = "(" *([FWS] ccontent) [FWS] ")"
26046 function comment() {
26047 return wrap('comment', and(
26048 literal('('),
26049 star(and(opt(fws), ccontent)),
26050 opt(fws),
26051 literal(')')
26052 )());
26053 }
26054
26055 // CFWS = (1*([FWS] comment) [FWS]) / FWS
26056 function cfws() {
26057 return wrap('cfws', or(
26058 and(
26059 star(
26060 and(opt(fws), comment),
26061 1
26062 ),
26063 opt(fws)
26064 ),
26065 fws
26066 )());
26067 }
26068
26069 // 3.2.3. Atom
26070
26071 //atext = ALPHA / DIGIT / ; Printable US-ASCII
26072 // "!" / "#" / ; characters not including
26073 // "$" / "%" / ; specials. Used for atoms.
26074 // "&" / "'" /
26075 // "*" / "+" /
26076 // "-" / "/" /
26077 // "=" / "?" /
26078 // "^" / "_" /
26079 // "`" / "{" /
26080 // "|" / "}" /
26081 // "~"
26082 function atext() {
26083 return wrap('atext', compareToken(function atextFunc(tok) {
26084 var accept =
26085 ('a' <= tok && tok <= 'z') ||
26086 ('A' <= tok && tok <= 'Z') ||
26087 ('0' <= tok && tok <= '9') ||
26088 (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
26089 '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
26090 if (opts.rfc6532) {
26091 accept = accept || isUTF8NonAscii(tok);
26092 }
26093 return accept;
26094 }));
26095 }
26096
26097 // atom = [CFWS] 1*atext [CFWS]
26098 function atom() {
26099 return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
26100 }
26101
26102 // dot-atom-text = 1*atext *("." 1*atext)
26103 function dotAtomText() {
26104 var s, maybeText;
26105 s = wrap('dot-atom-text', star(atext, 1)());
26106 if (s === null) { return s; }
26107 maybeText = star(and(literal('.'), star(atext, 1)))();
26108 if (maybeText !== null) {
26109 add(s, maybeText);
26110 }
26111 return s;
26112 }
26113
26114 // dot-atom = [CFWS] dot-atom-text [CFWS]
26115 function dotAtom() {
26116 return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
26117 }
26118
26119 // 3.2.4. Quoted Strings
26120
26121 // qtext = %d33 / ; Printable US-ASCII
26122 // %d35-91 / ; characters not including
26123 // %d93-126 / ; "\" or the quote character
26124 // obs-qtext
26125 function qtext() {
26126 return wrap('qtext', or(
26127 function qtextFunc1() {
26128 return compareToken(function qtextFunc2(tok) {
26129 var code = tok.charCodeAt(0);
26130 var accept =
26131 (33 === code) ||
26132 (35 <= code && code <= 91) ||
26133 (93 <= code && code <= 126);
26134 if (opts.rfc6532) {
26135 accept = accept || isUTF8NonAscii(tok);
26136 }
26137 return accept;
26138 });
26139 },
26140 obsQtext
26141 )());
26142 }
26143
26144 // qcontent = qtext / quoted-pair
26145 function qcontent() {
26146 return wrap('qcontent', or(qtext, quotedPair)());
26147 }
26148
26149 // quoted-string = [CFWS]
26150 // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
26151 // [CFWS]
26152 function quotedString() {
26153 return wrap('quoted-string', and(
26154 invis(opt(cfws)),
26155 invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
26156 invis(opt(cfws))
26157 )());
26158 }
26159
26160 // 3.2.5 Miscellaneous Tokens
26161
26162 // word = atom / quoted-string
26163 function word() {
26164 return wrap('word', or(atom, quotedString)());
26165 }
26166
26167 // phrase = 1*word / obs-phrase
26168 function phrase() {
26169 return wrap('phrase', or(obsPhrase, star(word, 1))());
26170 }
26171
26172 // 3.4. Address Specification
26173 // address = mailbox / group
26174 function address() {
26175 return wrap('address', or(mailbox, group)());
26176 }
26177
26178 // mailbox = name-addr / addr-spec
26179 function mailbox() {
26180 return wrap('mailbox', or(nameAddr, addrSpec)());
26181 }
26182
26183 // name-addr = [display-name] angle-addr
26184 function nameAddr() {
26185 return wrap('name-addr', and(opt(displayName), angleAddr)());
26186 }
26187
26188 // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
26189 // obs-angle-addr
26190 function angleAddr() {
26191 return wrap('angle-addr', or(
26192 and(
26193 invis(opt(cfws)),
26194 literal('<'),
26195 addrSpec,
26196 literal('>'),
26197 invis(opt(cfws))
26198 ),
26199 obsAngleAddr
26200 )());
26201 }
26202
26203 // group = display-name ":" [group-list] ";" [CFWS]
26204 function group() {
26205 return wrap('group', and(
26206 displayName,
26207 literal(':'),
26208 opt(groupList),
26209 literal(';'),
26210 invis(opt(cfws))
26211 )());
26212 }
26213
26214 // display-name = phrase
26215 function displayName() {
26216 return wrap('display-name', function phraseFixedSemantic() {
26217 var result = phrase();
26218 if (result !== null) {
26219 result.semantic = collapseWhitespace(result.semantic);
26220 }
26221 return result;
26222 }());
26223 }
26224
26225 // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
26226 function mailboxList() {
26227 return wrap('mailbox-list', or(
26228 and(
26229 mailbox,
26230 star(and(literal(','), mailbox))
26231 ),
26232 obsMboxList
26233 )());
26234 }
26235
26236 // address-list = (address *("," address)) / obs-addr-list
26237 function addressList() {
26238 return wrap('address-list', or(
26239 and(
26240 address,
26241 star(and(literal(','), address))
26242 ),
26243 obsAddrList
26244 )());
26245 }
26246
26247 // group-list = mailbox-list / CFWS / obs-group-list
26248 function groupList() {
26249 return wrap('group-list', or(
26250 mailboxList,
26251 invis(cfws),
26252 obsGroupList
26253 )());
26254 }
26255
26256 // 3.4.1 Addr-Spec Specification
26257
26258 // local-part = dot-atom / quoted-string / obs-local-part
26259 function localPart() {
26260 // note: quoted-string, dotAtom are proper subsets of obs-local-part
26261 // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
26262 return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
26263 }
26264
26265 // dtext = %d33-90 / ; Printable US-ASCII
26266 // %d94-126 / ; characters not including
26267 // obs-dtext ; "[", "]", or "\"
26268 function dtext() {
26269 return wrap('dtext', or(
26270 function dtextFunc1() {
26271 return compareToken(function dtextFunc2(tok) {
26272 var code = tok.charCodeAt(0);
26273 var accept =
26274 (33 <= code && code <= 90) ||
26275 (94 <= code && code <= 126);
26276 if (opts.rfc6532) {
26277 accept = accept || isUTF8NonAscii(tok);
26278 }
26279 return accept;
26280 });
26281 },
26282 obsDtext
26283 )()
26284 );
26285 }
26286
26287 // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
26288 function domainLiteral() {
26289 return wrap('domain-literal', and(
26290 invis(opt(cfws)),
26291 literal('['),
26292 star(and(opt(fws), dtext)),
26293 opt(fws),
26294 literal(']'),
26295 invis(opt(cfws))
26296 )());
26297 }
26298
26299 // domain = dot-atom / domain-literal / obs-domain
26300 function domain() {
26301 return wrap('domain', function domainCheckTLD() {
26302 var result = or(obsDomain, dotAtom, domainLiteral)();
26303 if (opts.rejectTLD) {
26304 if (result && result.semantic && result.semantic.indexOf('.') < 0) {
26305 return null;
26306 }
26307 }
26308 // strip all whitespace from domains
26309 if (result) {
26310 result.semantic = result.semantic.replace(/\s+/g, '');
26311 }
26312 return result;
26313 }());
26314 }
26315
26316 // addr-spec = local-part "@" domain
26317 function addrSpec() {
26318 return wrap('addr-spec', and(
26319 localPart, literal('@'), domain
26320 )());
26321 }
26322
26323 // 3.6.2 Originator Fields
26324 // Below we only parse the field body, not the name of the field
26325 // like "From:", "Sender:", or "Reply-To:". Other libraries that
26326 // parse email headers can parse those and defer to these productions
26327 // for the "RFC 5322" part.
26328
26329 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26330 // from = "From:" (mailbox-list / address-list) CRLF
26331 function fromSpec() {
26332 return wrap('from', or(
26333 mailboxList,
26334 addressList
26335 )());
26336 }
26337
26338 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26339 // sender = "Sender:" (mailbox / address) CRLF
26340 function senderSpec() {
26341 return wrap('sender', or(
26342 mailbox,
26343 address
26344 )());
26345 }
26346
26347 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26348 // reply-to = "Reply-To:" address-list CRLF
26349 function replyToSpec() {
26350 return wrap('reply-to', addressList());
26351 }
26352
26353 // 4.1. Miscellaneous Obsolete Tokens
26354
26355 // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
26356 // %d11 / ; characters that do not
26357 // %d12 / ; include the carriage
26358 // %d14-31 / ; return, line feed, and
26359 // %d127 ; white space characters
26360 function obsNoWsCtl() {
26361 return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
26362 var code = tok.charCodeAt(0);
26363 return ((1 <= code && code <= 8) ||
26364 (11 === code || 12 === code) ||
26365 (14 <= code && code <= 31) ||
26366 (127 === code));
26367 }));
26368 }
26369
26370 // obs-ctext = obs-NO-WS-CTL
26371 function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
26372
26373 // obs-qtext = obs-NO-WS-CTL
26374 function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
26375
26376 // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
26377 function obsQP() {
26378 return opts.strict ? null : wrap('obs-qp', and(
26379 literal('\\'),
26380 or(literal('\0'), obsNoWsCtl, lf, cr)
26381 )());
26382 }
26383
26384 // obs-phrase = word *(word / "." / CFWS)
26385 function obsPhrase() {
26386 if (opts.strict ) return null;
26387 return opts.atInDisplayName ? wrap('obs-phrase', and(
26388 word,
26389 star(or(word, literal('.'), literal('@'), colwsp(cfws)))
26390 )()) :
26391 wrap('obs-phrase', and(
26392 word,
26393 star(or(word, literal('.'), colwsp(cfws)))
26394 )());
26395 }
26396
26397 // 4.2. Obsolete Folding White Space
26398
26399 // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
26400 // obs-FWS = 1*([CRLF] WSP)
26401 function obsFws() {
26402 return opts.strict ? null : wrap('obs-FWS', star(
26403 and(invis(opt(crlf)), wsp),
26404 1
26405 )());
26406 }
26407
26408 // 4.4. Obsolete Addressing
26409
26410 // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
26411 function obsAngleAddr() {
26412 return opts.strict ? null : wrap('obs-angle-addr', and(
26413 invis(opt(cfws)),
26414 literal('<'),
26415 obsRoute,
26416 addrSpec,
26417 literal('>'),
26418 invis(opt(cfws))
26419 )());
26420 }
26421
26422 // obs-route = obs-domain-list ":"
26423 function obsRoute() {
26424 return opts.strict ? null : wrap('obs-route', and(
26425 obsDomainList,
26426 literal(':')
26427 )());
26428 }
26429
26430 // obs-domain-list = *(CFWS / ",") "@" domain
26431 // *("," [CFWS] ["@" domain])
26432 function obsDomainList() {
26433 return opts.strict ? null : wrap('obs-domain-list', and(
26434 star(or(invis(cfws), literal(','))),
26435 literal('@'),
26436 domain,
26437 star(and(
26438 literal(','),
26439 invis(opt(cfws)),
26440 opt(and(literal('@'), domain))
26441 ))
26442 )());
26443 }
26444
26445 // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
26446 function obsMboxList() {
26447 return opts.strict ? null : wrap('obs-mbox-list', and(
26448 star(and(
26449 invis(opt(cfws)),
26450 literal(',')
26451 )),
26452 mailbox,
26453 star(and(
26454 literal(','),
26455 opt(and(
26456 mailbox,
26457 invis(cfws)
26458 ))
26459 ))
26460 )());
26461 }
26462
26463 // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
26464 function obsAddrList() {
26465 return opts.strict ? null : wrap('obs-addr-list', and(
26466 star(and(
26467 invis(opt(cfws)),
26468 literal(',')
26469 )),
26470 address,
26471 star(and(
26472 literal(','),
26473 opt(and(
26474 address,
26475 invis(cfws)
26476 ))
26477 ))
26478 )());
26479 }
26480
26481 // obs-group-list = 1*([CFWS] ",") [CFWS]
26482 function obsGroupList() {
26483 return opts.strict ? null : wrap('obs-group-list', and(
26484 star(and(
26485 invis(opt(cfws)),
26486 literal(',')
26487 ), 1),
26488 invis(opt(cfws))
26489 )());
26490 }
26491
26492 // obs-local-part = word *("." word)
26493 function obsLocalPart() {
26494 return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
26495 }
26496
26497 // obs-domain = atom *("." atom)
26498 function obsDomain() {
26499 return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
26500 }
26501
26502 // obs-dtext = obs-NO-WS-CTL / quoted-pair
26503 function obsDtext() {
26504 return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
26505 }
26506
26507 /////////////////////////////////////////////////////
26508
26509 // ast analysis
26510
26511 function findNode(name, root) {
26512 var i, stack, node;
26513 if (root === null || root === undefined) { return null; }
26514 stack = [root];
26515 while (stack.length > 0) {
26516 node = stack.pop();
26517 if (node.name === name) {
26518 return node;
26519 }
26520 for (i = node.children.length - 1; i >= 0; i -= 1) {
26521 stack.push(node.children[i]);
26522 }
26523 }
26524 return null;
26525 }
26526
26527 function findAllNodes(name, root) {
26528 var i, stack, node, result;
26529 if (root === null || root === undefined) { return null; }
26530 stack = [root];
26531 result = [];
26532 while (stack.length > 0) {
26533 node = stack.pop();
26534 if (node.name === name) {
26535 result.push(node);
26536 }
26537 for (i = node.children.length - 1; i >= 0; i -= 1) {
26538 stack.push(node.children[i]);
26539 }
26540 }
26541 return result;
26542 }
26543
26544 function findAllNodesNoChildren(names, root) {
26545 var i, stack, node, result, namesLookup;
26546 if (root === null || root === undefined) { return null; }
26547 stack = [root];
26548 result = [];
26549 namesLookup = {};
26550 for (i = 0; i < names.length; i += 1) {
26551 namesLookup[names[i]] = true;
26552 }
26553
26554 while (stack.length > 0) {
26555 node = stack.pop();
26556 if (node.name in namesLookup) {
26557 result.push(node);
26558 // don't look at children (hence findAllNodesNoChildren)
26559 } else {
26560 for (i = node.children.length - 1; i >= 0; i -= 1) {
26561 stack.push(node.children[i]);
26562 }
26563 }
26564 }
26565 return result;
26566 }
26567
26568 function giveResult(ast) {
26569 var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
26570 if (ast === null) {
26571 return null;
26572 }
26573 addresses = [];
26574
26575 // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
26576 groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
26577 for (i = 0; i < groupsAndMailboxes.length; i += 1) {
26578 groupOrMailbox = groupsAndMailboxes[i];
26579 if (groupOrMailbox.name === 'group') {
26580 addresses.push(giveResultGroup(groupOrMailbox));
26581 } else if (groupOrMailbox.name === 'mailbox') {
26582 addresses.push(giveResultMailbox(groupOrMailbox));
26583 }
26584 }
26585
26586 result = {
26587 ast: ast,
26588 addresses: addresses,
26589 };
26590 if (opts.simple) {
26591 result = simplifyResult(result);
26592 }
26593 if (opts.oneResult) {
26594 return oneResult(result);
26595 }
26596 if (opts.simple) {
26597 return result && result.addresses;
26598 } else {
26599 return result;
26600 }
26601 }
26602
26603 function giveResultGroup(group) {
26604 var i;
26605 var groupName = findNode('display-name', group);
26606 var groupResultMailboxes = [];
26607 var mailboxes = findAllNodesNoChildren(['mailbox'], group);
26608 for (i = 0; i < mailboxes.length; i += 1) {
26609 groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
26610 }
26611 return {
26612 node: group,
26613 parts: {
26614 name: groupName,
26615 },
26616 type: group.name, // 'group'
26617 name: grabSemantic(groupName),
26618 addresses: groupResultMailboxes,
26619 };
26620 }
26621
26622 function giveResultMailbox(mailbox) {
26623 var name = findNode('display-name', mailbox);
26624 var aspec = findNode('addr-spec', mailbox);
26625 var cfws = findAllNodes('cfws', mailbox);
26626 var comments = findAllNodesNoChildren(['comment'], mailbox);
26627
26628
26629 var local = findNode('local-part', aspec);
26630 var domain = findNode('domain', aspec);
26631 return {
26632 node: mailbox,
26633 parts: {
26634 name: name,
26635 address: aspec,
26636 local: local,
26637 domain: domain,
26638 comments: cfws
26639 },
26640 type: mailbox.name, // 'mailbox'
26641 name: grabSemantic(name),
26642 address: grabSemantic(aspec),
26643 local: grabSemantic(local),
26644 domain: grabSemantic(domain),
26645 comments: concatComments(comments),
26646 groupName: grabSemantic(mailbox.groupName),
26647 };
26648 }
26649
26650 function grabSemantic(n) {
26651 return n !== null && n !== undefined ? n.semantic : null;
26652 }
26653
26654 function simplifyResult(result) {
26655 var i;
26656 if (result && result.addresses) {
26657 for (i = 0; i < result.addresses.length; i += 1) {
26658 delete result.addresses[i].node;
26659 }
26660 }
26661 return result;
26662 }
26663
26664 function concatComments(comments) {
26665 var result = '';
26666 if (comments) {
26667 for (var i = 0; i < comments.length; i += 1) {
26668 result += grabSemantic(comments[i]);
26669 }
26670 }
26671 return result;
26672 }
26673
26674 function oneResult(result) {
26675 if (!result) { return null; }
26676 if (!opts.partial && result.addresses.length > 1) { return null; }
26677 return result.addresses && result.addresses[0];
26678 }
26679
26680 /////////////////////////////////////////////////////
26681
26682 var parseString, pos, len, parsed, startProduction;
26683
26684 opts = handleOpts(opts, {});
26685 if (opts === null) { return null; }
26686
26687 parseString = opts.input;
26688
26689 startProduction = {
26690 'address': address,
26691 'address-list': addressList,
26692 'angle-addr': angleAddr,
26693 'from': fromSpec,
26694 'group': group,
26695 'mailbox': mailbox,
26696 'mailbox-list': mailboxList,
26697 'reply-to': replyToSpec,
26698 'sender': senderSpec,
26699 }[opts.startAt] || addressList;
26700
26701 if (!opts.strict) {
26702 initialize();
26703 opts.strict = true;
26704 parsed = startProduction(parseString);
26705 if (opts.partial || !inStr()) {
26706 return giveResult(parsed);
26707 }
26708 opts.strict = false;
26709 }
26710
26711 initialize();
26712 parsed = startProduction(parseString);
26713 if (!opts.partial && inStr()) { return null; }
26714 return giveResult(parsed);
26715}
26716
26717function parseOneAddressSimple(opts) {
26718 return parse5322(handleOpts(opts, {
26719 oneResult: true,
26720 rfc6532: true,
26721 simple: true,
26722 startAt: 'address-list',
26723 }));
26724}
26725
26726function parseAddressListSimple(opts) {
26727 return parse5322(handleOpts(opts, {
26728 rfc6532: true,
26729 simple: true,
26730 startAt: 'address-list',
26731 }));
26732}
26733
26734function parseFromSimple(opts) {
26735 return parse5322(handleOpts(opts, {
26736 rfc6532: true,
26737 simple: true,
26738 startAt: 'from',
26739 }));
26740}
26741
26742function parseSenderSimple(opts) {
26743 return parse5322(handleOpts(opts, {
26744 oneResult: true,
26745 rfc6532: true,
26746 simple: true,
26747 startAt: 'sender',
26748 }));
26749}
26750
26751function parseReplyToSimple(opts) {
26752 return parse5322(handleOpts(opts, {
26753 rfc6532: true,
26754 simple: true,
26755 startAt: 'reply-to',
26756 }));
26757}
26758
26759function handleOpts(opts, defs) {
26760 function isString(str) {
26761 return Object.prototype.toString.call(str) === '[object String]';
26762 }
26763
26764 function isObject(o) {
26765 return o === Object(o);
26766 }
26767
26768 function isNullUndef(o) {
26769 return o === null || o === undefined;
26770 }
26771
26772 var defaults, o;
26773
26774 if (isString(opts)) {
26775 opts = { input: opts };
26776 } else if (!isObject(opts)) {
26777 return null;
26778 }
26779
26780 if (!isString(opts.input)) { return null; }
26781 if (!defs) { return null; }
26782
26783 defaults = {
26784 oneResult: false,
26785 partial: false,
26786 rejectTLD: false,
26787 rfc6532: false,
26788 simple: false,
26789 startAt: 'address-list',
26790 strict: false,
26791 atInDisplayName: false
26792 };
26793
26794 for (o in defaults) {
26795 if (isNullUndef(opts[o])) {
26796 opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
26797 }
26798 }
26799 return opts;
26800}
26801
26802parse5322.parseOneAddress = parseOneAddressSimple;
26803parse5322.parseAddressList = parseAddressListSimple;
26804parse5322.parseFrom = parseFromSimple;
26805parse5322.parseSender = parseSenderSimple;
26806parse5322.parseReplyTo = parseReplyToSimple;
26807
26808{
26809 module.exports = parse5322;
26810}
26811
26812}());
26813});
26814
26815// GPG4Browsers - An OpenPGP implementation in javascript
26816
26817/**
26818 * Implementation of the User ID Packet (Tag 13)
26819 *
26820 * A User ID packet consists of UTF-8 text that is intended to represent
26821 * the name and email address of the key holder. By convention, it
26822 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
26823 * restrictions on its content. The packet length in the header
26824 * specifies the length of the User ID.
26825 */
26826class UserIDPacket {
26827 static get tag() {
26828 return enums.packet.userID;
26829 }
26830
26831 constructor() {
26832 /** A string containing the user id. Usually in the form
26833 * John Doe <john@example.com>
26834 * @type {String}
26835 */
26836 this.userID = '';
26837
26838 this.name = '';
26839 this.email = '';
26840 this.comment = '';
26841 }
26842
26843 /**
26844 * Create UserIDPacket instance from object
26845 * @param {Object} userID - Object specifying userID name, email and comment
26846 * @returns {UserIDPacket}
26847 * @static
26848 */
26849 static fromObject(userID) {
26850 if (util.isString(userID) ||
26851 (userID.name && !util.isString(userID.name)) ||
26852 (userID.email && !util.isEmailAddress(userID.email)) ||
26853 (userID.comment && !util.isString(userID.comment))) {
26854 throw new Error('Invalid user ID format');
26855 }
26856 const packet = new UserIDPacket();
26857 Object.assign(packet, userID);
26858 const components = [];
26859 if (packet.name) components.push(packet.name);
26860 if (packet.comment) components.push(`(${packet.comment})`);
26861 if (packet.email) components.push(`<${packet.email}>`);
26862 packet.userID = components.join(' ');
26863 return packet;
26864 }
26865
26866 /**
26867 * Parsing function for a user id packet (tag 13).
26868 * @param {Uint8Array} input - Payload of a tag 13 packet
26869 */
26870 read(bytes, config = defaultConfig) {
26871 const userID = util.decodeUTF8(bytes);
26872 if (userID.length > config.maxUserIDLength) {
26873 throw new Error('User ID string is too long');
26874 }
26875 try {
26876 const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });
26877 this.comment = comments.replace(/^\(|\)$/g, '');
26878 this.name = name;
26879 this.email = email;
26880 } catch (e) {}
26881 this.userID = userID;
26882 }
26883
26884 /**
26885 * Creates a binary representation of the user id packet
26886 * @returns {Uint8Array} Binary representation.
26887 */
26888 write() {
26889 return util.encodeUTF8(this.userID);
26890 }
26891
26892 equals(otherUserID) {
26893 return otherUserID && otherUserID.userID === this.userID;
26894 }
26895}
26896
26897// GPG4Browsers - An OpenPGP implementation in javascript
26898
26899/**
26900 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
26901 * Key packet and has exactly the same format.
26902 * @extends SecretKeyPacket
26903 */
26904class SecretSubkeyPacket extends SecretKeyPacket {
26905 static get tag() {
26906 return enums.packet.secretSubkey;
26907 }
26908
26909 /**
26910 * @param {Date} [date] - Creation date
26911 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26912 */
26913 constructor(date = new Date(), config = defaultConfig) {
26914 super(date, config);
26915 }
26916}
26917
26918/**
26919 * Implementation of the Trust Packet (Tag 12)
26920 *
26921 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
26922 * The Trust packet is used only within keyrings and is not normally
26923 * exported. Trust packets contain data that record the user's
26924 * specifications of which key holders are trustworthy introducers,
26925 * along with other information that implementing software uses for
26926 * trust information. The format of Trust packets is defined by a given
26927 * implementation.
26928 *
26929 * Trust packets SHOULD NOT be emitted to output streams that are
26930 * transferred to other users, and they SHOULD be ignored on any input
26931 * other than local keyring files.
26932 */
26933class TrustPacket {
26934 static get tag() {
26935 return enums.packet.trust;
26936 }
26937
26938 /**
26939 * Parsing function for a trust packet (tag 12).
26940 * Currently not implemented as we ignore trust packets
26941 */
26942 read() {
26943 throw new UnsupportedError('Trust packets are not supported');
26944 }
26945
26946 write() {
26947 throw new UnsupportedError('Trust packets are not supported');
26948 }
26949}
26950
26951// GPG4Browsers - An OpenPGP implementation in javascript
26952
26953// A Signature can contain the following packets
26954const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
26955
26956/**
26957 * Class that represents an OpenPGP signature.
26958 */
26959class Signature {
26960 /**
26961 * @param {PacketList} packetlist - The signature packets
26962 */
26963 constructor(packetlist) {
26964 this.packets = packetlist || new PacketList();
26965 }
26966
26967 /**
26968 * Returns binary encoded signature
26969 * @returns {ReadableStream<Uint8Array>} Binary signature.
26970 */
26971 write() {
26972 return this.packets.write();
26973 }
26974
26975 /**
26976 * Returns ASCII armored text of signature
26977 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26978 * @returns {ReadableStream<String>} ASCII armor.
26979 */
26980 armor(config = defaultConfig) {
26981 return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);
26982 }
26983
26984 /**
26985 * Returns an array of KeyIDs of all of the issuers who created this signature
26986 * @returns {Array<KeyID>} The Key IDs of the signing keys
26987 */
26988 getSigningKeyIDs() {
26989 return this.packets.map(packet => packet.issuerKeyID);
26990 }
26991}
26992
26993/**
26994 * reads an (optionally armored) OpenPGP signature and returns a signature object
26995 * @param {Object} options
26996 * @param {String} [options.armoredSignature] - Armored signature to be parsed
26997 * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed
26998 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
26999 * @returns {Promise<Signature>} New signature object.
27000 * @async
27001 * @static
27002 */
27003async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {
27004 config = { ...defaultConfig, ...config };
27005 let input = armoredSignature || binarySignature;
27006 if (!input) {
27007 throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
27008 }
27009 if (armoredSignature && !util.isString(armoredSignature)) {
27010 throw new Error('readSignature: options.armoredSignature must be a string');
27011 }
27012 if (binarySignature && !util.isUint8Array(binarySignature)) {
27013 throw new Error('readSignature: options.binarySignature must be a Uint8Array');
27014 }
27015 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
27016
27017 if (armoredSignature) {
27018 const { type, data } = await unarmor(input, config);
27019 if (type !== enums.armor.signature) {
27020 throw new Error('Armored text not of type signature');
27021 }
27022 input = data;
27023 }
27024 const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config);
27025 return new Signature(packetlist);
27026}
27027
27028/**
27029 * @fileoverview Provides helpers methods for key module
27030 * @module key/helper
27031 * @private
27032 */
27033
27034async function generateSecretSubkey(options, config) {
27035 const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
27036 secretSubkeyPacket.packets = null;
27037 secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27038 await secretSubkeyPacket.generate(options.rsaBits, options.curve);
27039 await secretSubkeyPacket.computeFingerprintAndKeyID();
27040 return secretSubkeyPacket;
27041}
27042
27043async function generateSecretKey(options, config) {
27044 const secretKeyPacket = new SecretKeyPacket(options.date, config);
27045 secretKeyPacket.packets = null;
27046 secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27047 await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
27048 await secretKeyPacket.computeFingerprintAndKeyID();
27049 return secretKeyPacket;
27050}
27051
27052/**
27053 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
27054 * @param {Array<SignaturePacket>} signatures - List of signatures
27055 * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature
27056 * @param {Date} date - Use the given date instead of the current time
27057 * @param {Object} config - full configuration
27058 * @returns {Promise<SignaturePacket>} The latest valid signature.
27059 * @async
27060 */
27061async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {
27062 let latestValid;
27063 let exception;
27064 for (let i = signatures.length - 1; i >= 0; i--) {
27065 try {
27066 if (
27067 (!latestValid || signatures[i].created >= latestValid.created)
27068 ) {
27069 await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);
27070 latestValid = signatures[i];
27071 }
27072 } catch (e) {
27073 exception = e;
27074 }
27075 }
27076 if (!latestValid) {
27077 throw util.wrapError(
27078 `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`
27079 .replace('certGeneric ', 'self-')
27080 .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase())
27081 , exception);
27082 }
27083 return latestValid;
27084}
27085
27086function isDataExpired(keyPacket, signature, date = new Date()) {
27087 const normDate = util.normalizeDate(date);
27088 if (normDate !== null) {
27089 const expirationTime = getKeyExpirationTime(keyPacket, signature);
27090 return !(keyPacket.created <= normDate && normDate < expirationTime);
27091 }
27092 return false;
27093}
27094
27095/**
27096 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
27097 * @param {SecretSubkeyPacket} subkey - Subkey key packet
27098 * @param {SecretKeyPacket} primaryKey - Primary key packet
27099 * @param {Object} options
27100 * @param {Object} config - Full configuration
27101 */
27102async function createBindingSignature(subkey, primaryKey, options, config) {
27103 const dataToSign = {};
27104 dataToSign.key = primaryKey;
27105 dataToSign.bind = subkey;
27106 const subkeySignaturePacket = new SignaturePacket();
27107 subkeySignaturePacket.signatureType = enums.signature.subkeyBinding;
27108 subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm;
27109 subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, subkey, undefined, undefined, config);
27110 if (options.sign) {
27111 subkeySignaturePacket.keyFlags = [enums.keyFlags.signData];
27112 subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
27113 signatureType: enums.signature.keyBinding
27114 }, options.date, undefined, undefined, config);
27115 } else {
27116 subkeySignaturePacket.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
27117 }
27118 if (options.keyExpirationTime > 0) {
27119 subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime;
27120 subkeySignaturePacket.keyNeverExpires = false;
27121 }
27122 await subkeySignaturePacket.sign(primaryKey, dataToSign, options.date);
27123 return subkeySignaturePacket;
27124}
27125
27126/**
27127 * Returns the preferred signature hash algorithm of a key
27128 * @param {Key} [key] - The key to get preferences from
27129 * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing
27130 * @param {Date} [date] - Use the given date for verification instead of the current time
27131 * @param {Object} [userID] - User ID
27132 * @param {Object} config - full configuration
27133 * @returns {Promise<enums.hash>}
27134 * @async
27135 */
27136async function getPreferredHashAlgo$1(key, keyPacket, date = new Date(), userID = {}, config) {
27137 let hashAlgo = config.preferredHashAlgorithm;
27138 let prefAlgo = hashAlgo;
27139 if (key) {
27140 const primaryUser = await key.getPrimaryUser(date, userID, config);
27141 if (primaryUser.selfCertification.preferredHashAlgorithms) {
27142 [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;
27143 hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27144 prefAlgo : hashAlgo;
27145 }
27146 }
27147 switch (Object.getPrototypeOf(keyPacket)) {
27148 case SecretKeyPacket.prototype:
27149 case PublicKeyPacket.prototype:
27150 case SecretSubkeyPacket.prototype:
27151 case PublicSubkeyPacket.prototype:
27152 switch (keyPacket.algorithm) {
27153 case enums.publicKey.ecdh:
27154 case enums.publicKey.ecdsa:
27155 case enums.publicKey.eddsa:
27156 prefAlgo = mod.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid);
27157 }
27158 }
27159 return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27160 prefAlgo : hashAlgo;
27161}
27162
27163/**
27164 * Returns the preferred symmetric/aead/compression algorithm for a set of keys
27165 * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return
27166 * @param {Array<Key>} [keys] - Set of keys
27167 * @param {Date} [date] - Use the given date for verification instead of the current time
27168 * @param {Array} [userIDs] - User IDs
27169 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27170 * @returns {Promise<module:enums.symmetric|aead|compression>} Preferred algorithm
27171 * @async
27172 */
27173async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {
27174 const defaultAlgo = { // these are all must-implement in rfc4880bis
27175 'symmetric': enums.symmetric.aes128,
27176 'aead': enums.aead.eax,
27177 'compression': enums.compression.uncompressed
27178 }[type];
27179 const preferredSenderAlgo = {
27180 'symmetric': config.preferredSymmetricAlgorithm,
27181 'aead': config.preferredAEADAlgorithm,
27182 'compression': config.preferredCompressionAlgorithm
27183 }[type];
27184 const prefPropertyName = {
27185 'symmetric': 'preferredSymmetricAlgorithms',
27186 'aead': 'preferredAEADAlgorithms',
27187 'compression': 'preferredCompressionAlgorithms'
27188 }[type];
27189
27190 // if preferredSenderAlgo appears in the prefs of all recipients, we pick it
27191 // otherwise we use the default algo
27192 // if no keys are available, preferredSenderAlgo is returned
27193 const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {
27194 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
27195 const recipientPrefs = primaryUser.selfCertification[prefPropertyName];
27196 return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;
27197 }));
27198 return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;
27199}
27200
27201/**
27202 * Create signature packet
27203 * @param {Object} dataToSign - Contains packets to be signed
27204 * @param {PrivateKey} privateKey - key to get preferences from
27205 * @param {SecretKeyPacket|
27206 * SecretSubkeyPacket} signingKeyPacket secret key packet for signing
27207 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
27208 * @param {Date} [date] - Override the creationtime of the signature
27209 * @param {Object} [userID] - User ID
27210 * @param {Object} [detached] - Whether to create a detached signature packet
27211 * @param {Object} config - full configuration
27212 * @returns {Promise<SignaturePacket>} Signature packet.
27213 */
27214async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, detached = false, config) {
27215 if (signingKeyPacket.isDummy()) {
27216 throw new Error('Cannot sign with a gnu-dummy key.');
27217 }
27218 if (!signingKeyPacket.isDecrypted()) {
27219 throw new Error('Signing key is not decrypted.');
27220 }
27221 const signaturePacket = new SignaturePacket();
27222 Object.assign(signaturePacket, signatureProperties);
27223 signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
27224 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(privateKey, signingKeyPacket, date, userID, config);
27225 await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);
27226 return signaturePacket;
27227}
27228
27229/**
27230 * Merges signatures from source[attr] to dest[attr]
27231 * @param {Object} source
27232 * @param {Object} dest
27233 * @param {String} attr
27234 * @param {Date} [date] - date to use for signature expiration check, instead of the current time
27235 * @param {Function} [checkFn] - signature only merged if true
27236 */
27237async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {
27238 source = source[attr];
27239 if (source) {
27240 if (!dest[attr].length) {
27241 dest[attr] = source;
27242 } else {
27243 await Promise.all(source.map(async function(sourceSig) {
27244 if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&
27245 !dest[attr].some(function(destSig) {
27246 return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());
27247 })) {
27248 dest[attr].push(sourceSig);
27249 }
27250 }));
27251 }
27252 }
27253}
27254
27255/**
27256 * Checks if a given certificate or binding signature is revoked
27257 * @param {SecretKeyPacket|
27258 * PublicKeyPacket} primaryKey The primary key packet
27259 * @param {Object} dataToVerify - The data to check
27260 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
27261 * @param {SignaturePacket} signature - The certificate or signature to check
27262 * @param {PublicSubkeyPacket|
27263 * SecretSubkeyPacket|
27264 * PublicKeyPacket|
27265 * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key
27266 * @param {Date} date - Use the given date instead of the current time
27267 * @param {Object} config - Full configuration
27268 * @returns {Promise<Boolean>} True if the signature revokes the data.
27269 * @async
27270 */
27271async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
27272 key = key || primaryKey;
27273 const revocationKeyIDs = [];
27274 await Promise.all(revocations.map(async function(revocationSignature) {
27275 try {
27276 if (
27277 // Note: a third-party revocation signature could legitimately revoke a
27278 // self-signature if the signature has an authorized revocation key.
27279 // However, we don't support passing authorized revocation keys, nor
27280 // verifying such revocation signatures. Instead, we indicate an error
27281 // when parsing a key with an authorized revocation key, and ignore
27282 // third-party revocation signatures here. (It could also be revoking a
27283 // third-party key certification, which should only affect
27284 // `verifyAllCertifications`.)
27285 !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)
27286 ) {
27287 await revocationSignature.verify(
27288 key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config
27289 );
27290
27291 // TODO get an identifier of the revoked object instead
27292 revocationKeyIDs.push(revocationSignature.issuerKeyID);
27293 }
27294 } catch (e) {}
27295 }));
27296 // TODO further verify that this is the signature that should be revoked
27297 if (signature) {
27298 signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :
27299 signature.revoked || false;
27300 return signature.revoked;
27301 }
27302 return revocationKeyIDs.length > 0;
27303}
27304
27305/**
27306 * Returns key expiration time based on the given certification signature.
27307 * The expiration time of the signature is ignored.
27308 * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check
27309 * @param {SignaturePacket} signature - signature to process
27310 * @returns {Date|Infinity} expiration time or infinity if the key does not expire
27311 */
27312function getKeyExpirationTime(keyPacket, signature) {
27313 let expirationTime;
27314 // check V4 expiration time
27315 if (signature.keyNeverExpires === false) {
27316 expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
27317 }
27318 return expirationTime ? new Date(expirationTime) : Infinity;
27319}
27320
27321/**
27322 * Returns whether aead is supported by all keys in the set
27323 * @param {Array<Key>} keys - Set of keys
27324 * @param {Date} [date] - Use the given date for verification instead of the current time
27325 * @param {Array} [userIDs] - User IDs
27326 * @param {Object} config - full configuration
27327 * @returns {Promise<Boolean>}
27328 * @async
27329 */
27330async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {
27331 let supported = true;
27332 // TODO replace when Promise.some or Promise.any are implemented
27333 await Promise.all(keys.map(async function(key, i) {
27334 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
27335 if (!primaryUser.selfCertification.features ||
27336 !(primaryUser.selfCertification.features[0] & enums.features.aead)) {
27337 supported = false;
27338 }
27339 }));
27340 return supported;
27341}
27342
27343function sanitizeKeyOptions(options, subkeyDefaults = {}) {
27344 options.type = options.type || subkeyDefaults.type;
27345 options.curve = options.curve || subkeyDefaults.curve;
27346 options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
27347 options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
27348 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
27349 options.date = options.date || subkeyDefaults.date;
27350
27351 options.sign = options.sign || false;
27352
27353 switch (options.type) {
27354 case 'ecc':
27355 try {
27356 options.curve = enums.write(enums.curve, options.curve);
27357 } catch (e) {
27358 throw new Error('Unknown curve');
27359 }
27360 if (options.curve === enums.curve.ed25519 || options.curve === enums.curve.curve25519) {
27361 options.curve = options.sign ? enums.curve.ed25519 : enums.curve.curve25519;
27362 }
27363 if (options.sign) {
27364 options.algorithm = options.curve === enums.curve.ed25519 ? enums.publicKey.eddsa : enums.publicKey.ecdsa;
27365 } else {
27366 options.algorithm = enums.publicKey.ecdh;
27367 }
27368 break;
27369 case 'rsa':
27370 options.algorithm = enums.publicKey.rsaEncryptSign;
27371 break;
27372 default:
27373 throw new Error(`Unsupported key type ${options.type}`);
27374 }
27375 return options;
27376}
27377
27378function isValidSigningKeyPacket(keyPacket, signature) {
27379 const keyAlgo = keyPacket.algorithm;
27380 return keyAlgo !== enums.publicKey.rsaEncrypt &&
27381 keyAlgo !== enums.publicKey.elgamal &&
27382 keyAlgo !== enums.publicKey.ecdh &&
27383 (!signature.keyFlags ||
27384 (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);
27385}
27386
27387function isValidEncryptionKeyPacket(keyPacket, signature) {
27388 const keyAlgo = keyPacket.algorithm;
27389 return keyAlgo !== enums.publicKey.dsa &&
27390 keyAlgo !== enums.publicKey.rsaSign &&
27391 keyAlgo !== enums.publicKey.ecdsa &&
27392 keyAlgo !== enums.publicKey.eddsa &&
27393 (!signature.keyFlags ||
27394 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27395 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);
27396}
27397
27398function isValidDecryptionKeyPacket(signature, config) {
27399 if (config.allowInsecureDecryptionWithSigningKeys) {
27400 // This is only relevant for RSA keys, all other signing algorithms cannot decrypt
27401 return true;
27402 }
27403
27404 return !signature.keyFlags ||
27405 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27406 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
27407}
27408
27409/**
27410 * Check key against blacklisted algorithms and minimum strength requirements.
27411 * @param {SecretKeyPacket|PublicKeyPacket|
27412 * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket
27413 * @param {Config} config
27414 * @throws {Error} if the key packet does not meet the requirements
27415 */
27416function checkKeyRequirements(keyPacket, config) {
27417 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27418 const algoInfo = keyPacket.getAlgorithmInfo();
27419 if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {
27420 throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);
27421 }
27422 switch (keyAlgo) {
27423 case enums.publicKey.rsaEncryptSign:
27424 case enums.publicKey.rsaSign:
27425 case enums.publicKey.rsaEncrypt:
27426 if (algoInfo.bits < config.minRSABits) {
27427 throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);
27428 }
27429 break;
27430 case enums.publicKey.ecdsa:
27431 case enums.publicKey.eddsa:
27432 case enums.publicKey.ecdh:
27433 if (config.rejectCurves.has(algoInfo.curve)) {
27434 throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);
27435 }
27436 break;
27437 }
27438}
27439
27440/**
27441 * @module key/User
27442 * @private
27443 */
27444
27445/**
27446 * Class that represents an user ID or attribute packet and the relevant signatures.
27447 * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info
27448 * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with
27449 */
27450class User {
27451 constructor(userPacket, mainKey) {
27452 this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;
27453 this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;
27454 this.selfCertifications = [];
27455 this.otherCertifications = [];
27456 this.revocationSignatures = [];
27457 this.mainKey = mainKey;
27458 }
27459
27460 /**
27461 * Transforms structured user data to packetlist
27462 * @returns {PacketList}
27463 */
27464 toPacketList() {
27465 const packetlist = new PacketList();
27466 packetlist.push(this.userID || this.userAttribute);
27467 packetlist.push(...this.revocationSignatures);
27468 packetlist.push(...this.selfCertifications);
27469 packetlist.push(...this.otherCertifications);
27470 return packetlist;
27471 }
27472
27473 /**
27474 * Shallow clone
27475 * @returns {User}
27476 */
27477 clone() {
27478 const user = new User(this.userID || this.userAttribute, this.mainKey);
27479 user.selfCertifications = [...this.selfCertifications];
27480 user.otherCertifications = [...this.otherCertifications];
27481 user.revocationSignatures = [...this.revocationSignatures];
27482 return user;
27483 }
27484
27485 /**
27486 * Generate third-party certifications over this user and its primary key
27487 * @param {Array<PrivateKey>} signingKeys - Decrypted private keys for signing
27488 * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time
27489 * @param {Object} config - Full configuration
27490 * @returns {Promise<User>} New user with new certifications.
27491 * @async
27492 */
27493 async certify(signingKeys, date, config) {
27494 const primaryKey = this.mainKey.keyPacket;
27495 const dataToSign = {
27496 userID: this.userID,
27497 userAttribute: this.userAttribute,
27498 key: primaryKey
27499 };
27500 const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
27501 user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {
27502 if (!privateKey.isPrivate()) {
27503 throw new Error('Need private key for signing');
27504 }
27505 if (privateKey.hasSameFingerprintAs(primaryKey)) {
27506 throw new Error("The user's own key can only be used for self-certifications");
27507 }
27508 const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);
27509 return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
27510 // Most OpenPGP implementations use generic certification (0x10)
27511 signatureType: enums.signature.certGeneric,
27512 keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
27513 }, date, undefined, undefined, config);
27514 }));
27515 await user.update(this, date, config);
27516 return user;
27517 }
27518
27519 /**
27520 * Checks if a given certificate of the user is revoked
27521 * @param {SignaturePacket} certificate - The certificate to verify
27522 * @param {PublicSubkeyPacket|
27523 * SecretSubkeyPacket|
27524 * PublicKeyPacket|
27525 * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key
27526 * @param {Date} [date] - Use the given date for verification instead of the current time
27527 * @param {Object} config - Full configuration
27528 * @returns {Promise<Boolean>} True if the certificate is revoked.
27529 * @async
27530 */
27531 async isRevoked(certificate, keyPacket, date = new Date(), config) {
27532 const primaryKey = this.mainKey.keyPacket;
27533 return isDataRevoked(primaryKey, enums.signature.certRevocation, {
27534 key: primaryKey,
27535 userID: this.userID,
27536 userAttribute: this.userAttribute
27537 }, this.revocationSignatures, certificate, keyPacket, date, config);
27538 }
27539
27540 /**
27541 * Verifies the user certificate.
27542 * @param {SignaturePacket} certificate - A certificate of this user
27543 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27544 * @param {Date} [date] - Use the given date instead of the current time
27545 * @param {Object} config - Full configuration
27546 * @returns {Promise<true|null>} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate
27547 * @throws if the user certificate is invalid.
27548 * @async
27549 */
27550 async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {
27551 const that = this;
27552 const primaryKey = this.mainKey.keyPacket;
27553 const dataToVerify = {
27554 userID: this.userID,
27555 userAttribute: this.userAttribute,
27556 key: primaryKey
27557 };
27558 const { issuerKeyID } = certificate;
27559 const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);
27560 if (issuerKeys.length === 0) {
27561 return null;
27562 }
27563 await Promise.all(issuerKeys.map(async key => {
27564 const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);
27565 if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {
27566 throw new Error('User certificate is revoked');
27567 }
27568 try {
27569 await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27570 } catch (e) {
27571 throw util.wrapError('User certificate is invalid', e);
27572 }
27573 }));
27574 return true;
27575 }
27576
27577 /**
27578 * Verifies all user certificates
27579 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27580 * @param {Date} [date] - Use the given date instead of the current time
27581 * @param {Object} config - Full configuration
27582 * @returns {Promise<Array<{
27583 * keyID: module:type/keyid~KeyID,
27584 * valid: Boolean | null
27585 * }>>} List of signer's keyID and validity of signature.
27586 * Signature validity is null if the verification keys do not correspond to the certificate.
27587 * @async
27588 */
27589 async verifyAllCertifications(verificationKeys, date = new Date(), config) {
27590 const that = this;
27591 const certifications = this.selfCertifications.concat(this.otherCertifications);
27592 return Promise.all(certifications.map(async certification => ({
27593 keyID: certification.issuerKeyID,
27594 valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)
27595 })));
27596 }
27597
27598 /**
27599 * Verify User. Checks for existence of self signatures, revocation signatures
27600 * and validity of self signature.
27601 * @param {Date} date - Use the given date instead of the current time
27602 * @param {Object} config - Full configuration
27603 * @returns {Promise<true>} Status of user.
27604 * @throws {Error} if there are no valid self signatures.
27605 * @async
27606 */
27607 async verify(date = new Date(), config) {
27608 if (!this.selfCertifications.length) {
27609 throw new Error('No self-certifications found');
27610 }
27611 const that = this;
27612 const primaryKey = this.mainKey.keyPacket;
27613 const dataToVerify = {
27614 userID: this.userID,
27615 userAttribute: this.userAttribute,
27616 key: primaryKey
27617 };
27618 // TODO replace when Promise.some or Promise.any are implemented
27619 let exception;
27620 for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
27621 try {
27622 const selfCertification = this.selfCertifications[i];
27623 if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {
27624 throw new Error('Self-certification is revoked');
27625 }
27626 try {
27627 await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27628 } catch (e) {
27629 throw util.wrapError('Self-certification is invalid', e);
27630 }
27631 return true;
27632 } catch (e) {
27633 exception = e;
27634 }
27635 }
27636 throw exception;
27637 }
27638
27639 /**
27640 * Update user with new components from specified user
27641 * @param {User} sourceUser - Source user to merge
27642 * @param {Date} date - Date to verify the validity of signatures
27643 * @param {Object} config - Full configuration
27644 * @returns {Promise<undefined>}
27645 * @async
27646 */
27647 async update(sourceUser, date, config) {
27648 const primaryKey = this.mainKey.keyPacket;
27649 const dataToVerify = {
27650 userID: this.userID,
27651 userAttribute: this.userAttribute,
27652 key: primaryKey
27653 };
27654 // self signatures
27655 await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {
27656 try {
27657 await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);
27658 return true;
27659 } catch (e) {
27660 return false;
27661 }
27662 });
27663 // other signatures
27664 await mergeSignatures(sourceUser, this, 'otherCertifications', date);
27665 // revocation signatures
27666 await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {
27667 return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27668 });
27669 }
27670}
27671
27672/**
27673 * @module key/Subkey
27674 * @private
27675 */
27676
27677/**
27678 * Class that represents a subkey packet and the relevant signatures.
27679 * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID
27680 * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint
27681 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs
27682 * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo
27683 * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime
27684 * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted
27685 */
27686class Subkey {
27687 /**
27688 * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey
27689 * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey
27690 */
27691 constructor(subkeyPacket, mainKey) {
27692 this.keyPacket = subkeyPacket;
27693 this.bindingSignatures = [];
27694 this.revocationSignatures = [];
27695 this.mainKey = mainKey;
27696 }
27697
27698 /**
27699 * Transforms structured subkey data to packetlist
27700 * @returns {PacketList}
27701 */
27702 toPacketList() {
27703 const packetlist = new PacketList();
27704 packetlist.push(this.keyPacket);
27705 packetlist.push(...this.revocationSignatures);
27706 packetlist.push(...this.bindingSignatures);
27707 return packetlist;
27708 }
27709
27710 /**
27711 * Shallow clone
27712 * @return {Subkey}
27713 */
27714 clone() {
27715 const subkey = new Subkey(this.keyPacket, this.mainKey);
27716 subkey.bindingSignatures = [...this.bindingSignatures];
27717 subkey.revocationSignatures = [...this.revocationSignatures];
27718 return subkey;
27719 }
27720
27721 /**
27722 * Checks if a binding signature of a subkey is revoked
27723 * @param {SignaturePacket} signature - The binding signature to verify
27724 * @param {PublicSubkeyPacket|
27725 * SecretSubkeyPacket|
27726 * PublicKeyPacket|
27727 * SecretKeyPacket} key, optional The key to verify the signature
27728 * @param {Date} [date] - Use the given date for verification instead of the current time
27729 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27730 * @returns {Promise<Boolean>} True if the binding signature is revoked.
27731 * @async
27732 */
27733 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
27734 const primaryKey = this.mainKey.keyPacket;
27735 return isDataRevoked(
27736 primaryKey, enums.signature.subkeyRevocation, {
27737 key: primaryKey,
27738 bind: this.keyPacket
27739 }, this.revocationSignatures, signature, key, date, config
27740 );
27741 }
27742
27743 /**
27744 * Verify subkey. Checks for revocation signatures, expiration time
27745 * and valid binding signature.
27746 * @param {Date} date - Use the given date instead of the current time
27747 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27748 * @returns {Promise<SignaturePacket>}
27749 * @throws {Error} if the subkey is invalid.
27750 * @async
27751 */
27752 async verify(date = new Date(), config = defaultConfig) {
27753 const primaryKey = this.mainKey.keyPacket;
27754 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27755 // check subkey binding signatures
27756 const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27757 // check binding signature is not revoked
27758 if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {
27759 throw new Error('Subkey is revoked');
27760 }
27761 // check for expiration time
27762 if (isDataExpired(this.keyPacket, bindingSignature, date)) {
27763 throw new Error('Subkey is expired');
27764 }
27765 return bindingSignature;
27766 }
27767
27768 /**
27769 * Returns the expiration time of the subkey or Infinity if key does not expire.
27770 * Returns null if the subkey is invalid.
27771 * @param {Date} date - Use the given date instead of the current time
27772 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27773 * @returns {Promise<Date | Infinity | null>}
27774 * @async
27775 */
27776 async getExpirationTime(date = new Date(), config = defaultConfig) {
27777 const primaryKey = this.mainKey.keyPacket;
27778 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27779 let bindingSignature;
27780 try {
27781 bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27782 } catch (e) {
27783 return null;
27784 }
27785 const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature);
27786 const sigExpiry = bindingSignature.getExpirationTime();
27787 return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
27788 }
27789
27790 /**
27791 * Update subkey with new components from specified subkey
27792 * @param {Subkey} subkey - Source subkey to merge
27793 * @param {Date} [date] - Date to verify validity of signatures
27794 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27795 * @throws {Error} if update failed
27796 * @async
27797 */
27798 async update(subkey, date = new Date(), config = defaultConfig) {
27799 const primaryKey = this.mainKey.keyPacket;
27800 if (!this.hasSameFingerprintAs(subkey)) {
27801 throw new Error('Subkey update method: fingerprints of subkeys not equal');
27802 }
27803 // key packet
27804 if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&
27805 subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {
27806 this.keyPacket = subkey.keyPacket;
27807 }
27808 // update missing binding signatures
27809 const that = this;
27810 const dataToVerify = { key: primaryKey, bind: that.keyPacket };
27811 await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {
27812 for (let i = 0; i < that.bindingSignatures.length; i++) {
27813 if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {
27814 if (srcBindSig.created > that.bindingSignatures[i].created) {
27815 that.bindingSignatures[i] = srcBindSig;
27816 }
27817 return false;
27818 }
27819 }
27820 try {
27821 await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);
27822 return true;
27823 } catch (e) {
27824 return false;
27825 }
27826 });
27827 // revocation signatures
27828 await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {
27829 return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27830 });
27831 }
27832
27833 /**
27834 * Revokes the subkey
27835 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
27836 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
27837 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
27838 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
27839 * @param {Date} date - optional, override the creationtime of the revocation signature
27840 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27841 * @returns {Promise<Subkey>} New subkey with revocation signature.
27842 * @async
27843 */
27844 async revoke(
27845 primaryKey,
27846 {
27847 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
27848 string: reasonForRevocationString = ''
27849 } = {},
27850 date = new Date(),
27851 config = defaultConfig
27852 ) {
27853 const dataToSign = { key: primaryKey, bind: this.keyPacket };
27854 const subkey = new Subkey(this.keyPacket, this.mainKey);
27855 subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
27856 signatureType: enums.signature.subkeyRevocation,
27857 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
27858 reasonForRevocationString
27859 }, date, undefined, false, config));
27860 await subkey.update(this);
27861 return subkey;
27862 }
27863
27864 hasSameFingerprintAs(other) {
27865 return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
27866 }
27867}
27868
27869['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
27870 Subkey.prototype[name] =
27871 function() {
27872 return this.keyPacket[name]();
27873 };
27874});
27875
27876// GPG4Browsers - An OpenPGP implementation in javascript
27877
27878// A key revocation certificate can contain the following packets
27879const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
27880const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);
27881const keyPacketTags = new Set([
27882 enums.packet.publicKey, enums.packet.privateKey,
27883 enums.packet.publicSubkey, enums.packet.privateSubkey
27884]);
27885
27886/**
27887 * Abstract class that represents an OpenPGP key. Must contain a primary key.
27888 * Can contain additional subkeys, signatures, user ids, user attributes.
27889 * @borrows PublicKeyPacket#getKeyID as Key#getKeyID
27890 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
27891 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
27892 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
27893 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
27894 */
27895class Key {
27896 /**
27897 * Transforms packetlist to structured key data
27898 * @param {PacketList} packetlist - The packets that form a key
27899 * @param {Set<enums.packet>} disallowedPackets - disallowed packet tags
27900 */
27901 packetListToStructure(packetlist, disallowedPackets = new Set()) {
27902 let user;
27903 let primaryKeyID;
27904 let subkey;
27905 let ignoreUntil;
27906
27907 for (const packet of packetlist) {
27908
27909 if (packet instanceof UnparseablePacket) {
27910 const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);
27911 if (isUnparseableKeyPacket && !ignoreUntil){
27912 // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must
27913 // discard all non-key packets that follow, until another (sub)key packet is found.
27914 if (mainKeyPacketTags.has(packet.tag)) {
27915 ignoreUntil = mainKeyPacketTags;
27916 } else {
27917 ignoreUntil = keyPacketTags;
27918 }
27919 }
27920 continue;
27921 }
27922
27923 const tag = packet.constructor.tag;
27924 if (ignoreUntil) {
27925 if (!ignoreUntil.has(tag)) continue;
27926 ignoreUntil = null;
27927 }
27928 if (disallowedPackets.has(tag)) {
27929 throw new Error(`Unexpected packet type: ${tag}`);
27930 }
27931 switch (tag) {
27932 case enums.packet.publicKey:
27933 case enums.packet.secretKey:
27934 if (this.keyPacket) {
27935 throw new Error('Key block contains multiple keys');
27936 }
27937 this.keyPacket = packet;
27938 primaryKeyID = this.getKeyID();
27939 if (!primaryKeyID) {
27940 throw new Error('Missing Key ID');
27941 }
27942 break;
27943 case enums.packet.userID:
27944 case enums.packet.userAttribute:
27945 user = new User(packet, this);
27946 this.users.push(user);
27947 break;
27948 case enums.packet.publicSubkey:
27949 case enums.packet.secretSubkey:
27950 user = null;
27951 subkey = new Subkey(packet, this);
27952 this.subkeys.push(subkey);
27953 break;
27954 case enums.packet.signature:
27955 switch (packet.signatureType) {
27956 case enums.signature.certGeneric:
27957 case enums.signature.certPersona:
27958 case enums.signature.certCasual:
27959 case enums.signature.certPositive:
27960 if (!user) {
27961 util.printDebug('Dropping certification signatures without preceding user packet');
27962 continue;
27963 }
27964 if (packet.issuerKeyID.equals(primaryKeyID)) {
27965 user.selfCertifications.push(packet);
27966 } else {
27967 user.otherCertifications.push(packet);
27968 }
27969 break;
27970 case enums.signature.certRevocation:
27971 if (user) {
27972 user.revocationSignatures.push(packet);
27973 } else {
27974 this.directSignatures.push(packet);
27975 }
27976 break;
27977 case enums.signature.key:
27978 this.directSignatures.push(packet);
27979 break;
27980 case enums.signature.subkeyBinding:
27981 if (!subkey) {
27982 util.printDebug('Dropping subkey binding signature without preceding subkey packet');
27983 continue;
27984 }
27985 subkey.bindingSignatures.push(packet);
27986 break;
27987 case enums.signature.keyRevocation:
27988 this.revocationSignatures.push(packet);
27989 break;
27990 case enums.signature.subkeyRevocation:
27991 if (!subkey) {
27992 util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
27993 continue;
27994 }
27995 subkey.revocationSignatures.push(packet);
27996 break;
27997 }
27998 break;
27999 }
28000 }
28001 }
28002
28003 /**
28004 * Transforms structured key data to packetlist
28005 * @returns {PacketList} The packets that form a key.
28006 */
28007 toPacketList() {
28008 const packetlist = new PacketList();
28009 packetlist.push(this.keyPacket);
28010 packetlist.push(...this.revocationSignatures);
28011 packetlist.push(...this.directSignatures);
28012 this.users.map(user => packetlist.push(...user.toPacketList()));
28013 this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));
28014 return packetlist;
28015 }
28016
28017 /**
28018 * Clones the key object
28019 * @param {Boolean} [deep=false] Whether to return a deep clone
28020 * @returns {Promise<Key>} Clone of the key.
28021 */
28022 clone(deep = false) {
28023 const key = new this.constructor(this.toPacketList());
28024 if (deep) {
28025 key.getKeys().forEach(k => {
28026 // shallow clone the key packets
28027 k.keyPacket = Object.create(
28028 Object.getPrototypeOf(k.keyPacket),
28029 Object.getOwnPropertyDescriptors(k.keyPacket)
28030 );
28031 if (!k.keyPacket.isDecrypted()) return;
28032 // deep clone the private params, which are cleared during encryption
28033 const privateParams = {};
28034 Object.keys(k.keyPacket.privateParams).forEach(name => {
28035 privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
28036 });
28037 k.keyPacket.privateParams = privateParams;
28038 });
28039 }
28040 return key;
28041 }
28042
28043 /**
28044 * Returns an array containing all public or private subkeys matching keyID;
28045 * If no keyID is given, returns all subkeys.
28046 * @param {type/keyID} [keyID] - key ID to look for
28047 * @returns {Array<Subkey>} array of subkeys
28048 */
28049 getSubkeys(keyID = null) {
28050 const subkeys = this.subkeys.filter(subkey => (
28051 !keyID || subkey.getKeyID().equals(keyID, true)
28052 ));
28053 return subkeys;
28054 }
28055
28056 /**
28057 * Returns an array containing all public or private keys matching keyID.
28058 * If no keyID is given, returns all keys, starting with the primary key.
28059 * @param {type/keyid~KeyID} [keyID] - key ID to look for
28060 * @returns {Array<Key|Subkey>} array of keys
28061 */
28062 getKeys(keyID = null) {
28063 const keys = [];
28064 if (!keyID || this.getKeyID().equals(keyID, true)) {
28065 keys.push(this);
28066 }
28067 return keys.concat(this.getSubkeys(keyID));
28068 }
28069
28070 /**
28071 * Returns key IDs of all keys
28072 * @returns {Array<module:type/keyid~KeyID>}
28073 */
28074 getKeyIDs() {
28075 return this.getKeys().map(key => key.getKeyID());
28076 }
28077
28078 /**
28079 * Returns userIDs
28080 * @returns {Array<string>} Array of userIDs.
28081 */
28082 getUserIDs() {
28083 return this.users.map(user => {
28084 return user.userID ? user.userID.userID : null;
28085 }).filter(userID => userID !== null);
28086 }
28087
28088 /**
28089 * Returns binary encoded key
28090 * @returns {Uint8Array} Binary key.
28091 */
28092 write() {
28093 return this.toPacketList().write();
28094 }
28095
28096 /**
28097 * Returns last created key or key by given keyID that is available for signing and verification
28098 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28099 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28100 * @param {Object} [userID] - filter keys for the given user ID
28101 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28102 * @returns {Promise<Key|Subkey>} signing key
28103 * @throws if no valid signing key was found
28104 * @async
28105 */
28106 async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {
28107 await this.verifyPrimaryKey(date, userID, config);
28108 const primaryKey = this.keyPacket;
28109 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28110 let exception;
28111 for (const subkey of subkeys) {
28112 if (!keyID || subkey.getKeyID().equals(keyID)) {
28113 try {
28114 await subkey.verify(date, config);
28115 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28116 const bindingSignature = await getLatestValidSignature(
28117 subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config
28118 );
28119 if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {
28120 continue;
28121 }
28122 if (!bindingSignature.embeddedSignature) {
28123 throw new Error('Missing embedded signature');
28124 }
28125 // verify embedded signature
28126 await getLatestValidSignature(
28127 [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config
28128 );
28129 checkKeyRequirements(subkey.keyPacket, config);
28130 return subkey;
28131 } catch (e) {
28132 exception = e;
28133 }
28134 }
28135 }
28136
28137 try {
28138 const primaryUser = await this.getPrimaryUser(date, userID, config);
28139 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28140 isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {
28141 checkKeyRequirements(primaryKey, config);
28142 return this;
28143 }
28144 } catch (e) {
28145 exception = e;
28146 }
28147 throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);
28148 }
28149
28150 /**
28151 * Returns last created key or key by given keyID that is available for encryption or decryption
28152 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28153 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28154 * @param {Object} [userID] - filter keys for the given user ID
28155 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28156 * @returns {Promise<Key|Subkey>} encryption key
28157 * @throws if no valid encryption key was found
28158 * @async
28159 */
28160 async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {
28161 await this.verifyPrimaryKey(date, userID, config);
28162 const primaryKey = this.keyPacket;
28163 // V4: by convention subkeys are preferred for encryption service
28164 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28165 let exception;
28166 for (const subkey of subkeys) {
28167 if (!keyID || subkey.getKeyID().equals(keyID)) {
28168 try {
28169 await subkey.verify(date, config);
28170 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28171 const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
28172 if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {
28173 checkKeyRequirements(subkey.keyPacket, config);
28174 return subkey;
28175 }
28176 } catch (e) {
28177 exception = e;
28178 }
28179 }
28180 }
28181
28182 try {
28183 // if no valid subkey for encryption, evaluate primary key
28184 const primaryUser = await this.getPrimaryUser(date, userID, config);
28185 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28186 isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
28187 checkKeyRequirements(primaryKey, config);
28188 return this;
28189 }
28190 } catch (e) {
28191 exception = e;
28192 }
28193 throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);
28194 }
28195
28196 /**
28197 * Checks if a signature on a key is revoked
28198 * @param {SignaturePacket} signature - The signature to verify
28199 * @param {PublicSubkeyPacket|
28200 * SecretSubkeyPacket|
28201 * PublicKeyPacket|
28202 * SecretKeyPacket} key, optional The key to verify the signature
28203 * @param {Date} [date] - Use the given date for verification, instead of the current time
28204 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28205 * @returns {Promise<Boolean>} True if the certificate is revoked.
28206 * @async
28207 */
28208 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
28209 return isDataRevoked(
28210 this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config
28211 );
28212 }
28213
28214 /**
28215 * Verify primary key. Checks for revocation signatures, expiration time
28216 * and valid self signature. Throws if the primary key is invalid.
28217 * @param {Date} [date] - Use the given date for verification instead of the current time
28218 * @param {Object} [userID] - User ID
28219 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28220 * @throws {Error} If key verification failed
28221 * @async
28222 */
28223 async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {
28224 const primaryKey = this.keyPacket;
28225 // check for key revocation signatures
28226 if (await this.isRevoked(null, null, date, config)) {
28227 throw new Error('Primary key is revoked');
28228 }
28229 // check for valid, unrevoked, unexpired self signature
28230 const { selfCertification } = await this.getPrimaryUser(date, userID, config);
28231 // check for expiration time in binding signatures
28232 if (isDataExpired(primaryKey, selfCertification, date)) {
28233 throw new Error('Primary key is expired');
28234 }
28235 // check for expiration time in direct signatures
28236 const directSignature = await getLatestValidSignature(
28237 this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config
28238 ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key
28239
28240 if (directSignature && isDataExpired(primaryKey, directSignature, date)) {
28241 throw new Error('Primary key is expired');
28242 }
28243 }
28244
28245 /**
28246 * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.
28247 * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.
28248 * @param {Object} [userID] - User ID to consider instead of the primary user
28249 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28250 * @returns {Promise<Date | Infinity | null>}
28251 * @async
28252 */
28253 async getExpirationTime(userID, config = defaultConfig) {
28254 let primaryKeyExpiry;
28255 try {
28256 const { selfCertification } = await this.getPrimaryUser(null, userID, config);
28257 const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification);
28258 const selfSigExpiry = selfCertification.getExpirationTime();
28259 const directSignature = await getLatestValidSignature(
28260 this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config
28261 ).catch(() => {});
28262 if (directSignature) {
28263 const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature);
28264 // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,
28265 // causing a discountinous validy period for the key
28266 primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);
28267 } else {
28268 primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;
28269 }
28270 } catch (e) {
28271 primaryKeyExpiry = null;
28272 }
28273
28274 return util.normalizeDate(primaryKeyExpiry);
28275 }
28276
28277
28278 /**
28279 * Returns primary user and most significant (latest valid) self signature
28280 * - if multiple primary users exist, returns the one with the latest self signature
28281 * - otherwise, returns the user with the latest self signature
28282 * @param {Date} [date] - Use the given date for verification instead of the current time
28283 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28284 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28285 * @returns {Promise<{
28286 * user: User,
28287 * selfCertification: SignaturePacket
28288 * }>} The primary user and the self signature
28289 * @async
28290 */
28291 async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {
28292 const primaryKey = this.keyPacket;
28293 const users = [];
28294 let exception;
28295 for (let i = 0; i < this.users.length; i++) {
28296 try {
28297 const user = this.users[i];
28298 if (!user.userID) {
28299 continue;
28300 }
28301 if (
28302 (userID.name !== undefined && user.userID.name !== userID.name) ||
28303 (userID.email !== undefined && user.userID.email !== userID.email) ||
28304 (userID.comment !== undefined && user.userID.comment !== userID.comment)
28305 ) {
28306 throw new Error('Could not find user that matches that user ID');
28307 }
28308 const dataToVerify = { userID: user.userID, key: primaryKey };
28309 const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);
28310 users.push({ index: i, user, selfCertification });
28311 } catch (e) {
28312 exception = e;
28313 }
28314 }
28315 if (!users.length) {
28316 throw exception || new Error('Could not find primary user');
28317 }
28318 await Promise.all(users.map(async function (a) {
28319 return a.user.revoked || a.user.isRevoked(a.selfCertification, null, date, config);
28320 }));
28321 // sort by primary user flag and signature creation time
28322 const primaryUser = users.sort(function(a, b) {
28323 const A = a.selfCertification;
28324 const B = b.selfCertification;
28325 return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
28326 }).pop();
28327 const { user, selfCertification: cert } = primaryUser;
28328 if (cert.revoked || await user.isRevoked(cert, null, date, config)) {
28329 throw new Error('Primary user is revoked');
28330 }
28331 return primaryUser;
28332 }
28333
28334 /**
28335 * Update key with new components from specified key with same key ID:
28336 * users, subkeys, certificates are merged into the destination key,
28337 * duplicates and expired signatures are ignored.
28338 *
28339 * If the source key is a private key and the destination key is public,
28340 * a private key is returned.
28341 * @param {Key} sourceKey - Source key to merge
28342 * @param {Date} [date] - Date to verify validity of signatures and keys
28343 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28344 * @returns {Promise<Key>} updated key
28345 * @async
28346 */
28347 async update(sourceKey, date = new Date(), config = defaultConfig) {
28348 if (!this.hasSameFingerprintAs(sourceKey)) {
28349 throw new Error('Primary key fingerprints must be equal to update the key');
28350 }
28351 if (!this.isPrivate() && sourceKey.isPrivate()) {
28352 // check for equal subkey packets
28353 const equal = (this.subkeys.length === sourceKey.subkeys.length) &&
28354 (this.subkeys.every(destSubkey => {
28355 return sourceKey.subkeys.some(srcSubkey => {
28356 return destSubkey.hasSameFingerprintAs(srcSubkey);
28357 });
28358 }));
28359 if (!equal) {
28360 throw new Error('Cannot update public key with private key if subkeys mismatch');
28361 }
28362
28363 return sourceKey.update(this, config);
28364 }
28365 // from here on, either:
28366 // - destination key is private, source key is public
28367 // - the keys are of the same type
28368 // hence we don't need to convert the destination key type
28369 const updatedKey = this.clone();
28370 // revocation signatures
28371 await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {
28372 return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);
28373 });
28374 // direct signatures
28375 await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);
28376 // update users
28377 await Promise.all(sourceKey.users.map(async srcUser => {
28378 // multiple users with the same ID/attribute are not explicitly disallowed by the spec
28379 // hence we support them, just in case
28380 const usersToUpdate = updatedKey.users.filter(dstUser => (
28381 (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||
28382 (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))
28383 ));
28384 if (usersToUpdate.length > 0) {
28385 await Promise.all(
28386 usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))
28387 );
28388 } else {
28389 const newUser = srcUser.clone();
28390 newUser.mainKey = updatedKey;
28391 updatedKey.users.push(newUser);
28392 }
28393 }));
28394 // update subkeys
28395 await Promise.all(sourceKey.subkeys.map(async srcSubkey => {
28396 // multiple subkeys with same fingerprint might be preset
28397 const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (
28398 dstSubkey.hasSameFingerprintAs(srcSubkey)
28399 ));
28400 if (subkeysToUpdate.length > 0) {
28401 await Promise.all(
28402 subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))
28403 );
28404 } else {
28405 const newSubkey = srcSubkey.clone();
28406 newSubkey.mainKey = updatedKey;
28407 updatedKey.subkeys.push(newSubkey);
28408 }
28409 }));
28410
28411 return updatedKey;
28412 }
28413
28414 /**
28415 * Get revocation certificate from a revoked key.
28416 * (To get a revocation certificate for an unrevoked key, call revoke() first.)
28417 * @param {Date} date - Use the given date instead of the current time
28418 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28419 * @returns {Promise<String>} Armored revocation certificate.
28420 * @async
28421 */
28422 async getRevocationCertificate(date = new Date(), config = defaultConfig) {
28423 const dataToVerify = { key: this.keyPacket };
28424 const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);
28425 const packetlist = new PacketList();
28426 packetlist.push(revocationSignature);
28427 return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');
28428 }
28429
28430 /**
28431 * Applies a revocation certificate to a key
28432 * This adds the first signature packet in the armored text to the key,
28433 * if it is a valid revocation signature.
28434 * @param {String} revocationCertificate - armored revocation certificate
28435 * @param {Date} [date] - Date to verify the certificate
28436 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28437 * @returns {Promise<Key>} Revoked key.
28438 * @async
28439 */
28440 async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {
28441 const input = await unarmor(revocationCertificate, config);
28442 const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);
28443 const revocationSignature = packetlist.findPacket(enums.packet.signature);
28444 if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
28445 throw new Error('Could not find revocation signature packet');
28446 }
28447 if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {
28448 throw new Error('Revocation signature does not match key');
28449 }
28450 try {
28451 await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);
28452 } catch (e) {
28453 throw util.wrapError('Could not verify revocation signature', e);
28454 }
28455 const key = this.clone();
28456 key.revocationSignatures.push(revocationSignature);
28457 return key;
28458 }
28459
28460 /**
28461 * Signs primary user of key
28462 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28463 * @param {Date} [date] - Use the given date for verification instead of the current time
28464 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28465 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28466 * @returns {Promise<Key>} Key with new certificate signature.
28467 * @async
28468 */
28469 async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {
28470 const { index, user } = await this.getPrimaryUser(date, userID, config);
28471 const userSign = await user.certify(privateKeys, date, config);
28472 const key = this.clone();
28473 key.users[index] = userSign;
28474 return key;
28475 }
28476
28477 /**
28478 * Signs all users of key
28479 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28480 * @param {Date} [date] - Use the given date for signing, instead of the current time
28481 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28482 * @returns {Promise<Key>} Key with new certificate signature.
28483 * @async
28484 */
28485 async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {
28486 const key = this.clone();
28487 key.users = await Promise.all(this.users.map(function(user) {
28488 return user.certify(privateKeys, date, config);
28489 }));
28490 return key;
28491 }
28492
28493 /**
28494 * Verifies primary user of key
28495 * - if no arguments are given, verifies the self certificates;
28496 * - otherwise, verifies all certificates signed with given keys.
28497 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key
28498 * @param {Date} [date] - Use the given date for verification instead of the current time
28499 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28500 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28501 * @returns {Promise<Array<{
28502 * keyID: module:type/keyid~KeyID,
28503 * valid: Boolean|null
28504 * }>>} List of signer's keyID and validity of signature.
28505 * Signature validity is null if the verification keys do not correspond to the certificate.
28506 * @async
28507 */
28508 async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {
28509 const primaryKey = this.keyPacket;
28510 const { user } = await this.getPrimaryUser(date, userID, config);
28511 const results = verificationKeys ?
28512 await user.verifyAllCertifications(verificationKeys, date, config) :
28513 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28514 return results;
28515 }
28516
28517 /**
28518 * Verifies all users of key
28519 * - if no arguments are given, verifies the self certificates;
28520 * - otherwise, verifies all certificates signed with given keys.
28521 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures
28522 * @param {Date} [date] - Use the given date for verification instead of the current time
28523 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28524 * @returns {Promise<Array<{
28525 * userID: String,
28526 * keyID: module:type/keyid~KeyID,
28527 * valid: Boolean|null
28528 * }>>} List of userID, signer's keyID and validity of signature.
28529 * Signature validity is null if the verification keys do not correspond to the certificate.
28530 * @async
28531 */
28532 async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {
28533 const primaryKey = this.keyPacket;
28534 const results = [];
28535 await Promise.all(this.users.map(async user => {
28536 const signatures = verificationKeys ?
28537 await user.verifyAllCertifications(verificationKeys, date, config) :
28538 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28539
28540 results.push(...signatures.map(
28541 signature => ({
28542 userID: user.userID.userID,
28543 keyID: signature.keyID,
28544 valid: signature.valid
28545 }))
28546 );
28547 }));
28548 return results;
28549 }
28550}
28551
28552['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
28553 Key.prototype[name] =
28554 Subkey.prototype[name];
28555});
28556
28557/**
28558 * Creates a PublicKey or PrivateKey depending on the packetlist in input
28559 * @param {PacketList} - packets to parse
28560 * @return {Key} parsed key
28561 * @throws if no key packet was found
28562 */
28563function createKey(packetlist) {
28564 for (const packet of packetlist) {
28565 switch (packet.constructor.tag) {
28566 case enums.packet.secretKey:
28567 return new PrivateKey(packetlist);
28568 case enums.packet.publicKey:
28569 return new PublicKey(packetlist);
28570 }
28571 }
28572 throw new Error('No key packet found');
28573}
28574
28575// This library is free software; you can redistribute it and/or
28576
28577/**
28578 * Class that represents an OpenPGP Public Key
28579 */
28580class PublicKey extends Key {
28581 /**
28582 * @param {PacketList} packetlist - The packets that form this key
28583 */
28584 constructor(packetlist) {
28585 super();
28586 this.keyPacket = null;
28587 this.revocationSignatures = [];
28588 this.directSignatures = [];
28589 this.users = [];
28590 this.subkeys = [];
28591 if (packetlist) {
28592 this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));
28593 if (!this.keyPacket) {
28594 throw new Error('Invalid key: missing public-key packet');
28595 }
28596 }
28597 }
28598
28599 /**
28600 * Returns true if this is a private key
28601 * @returns {false}
28602 */
28603 isPrivate() {
28604 return false;
28605 }
28606
28607 /**
28608 * Returns key as public key (shallow copy)
28609 * @returns {PublicKey} New public Key
28610 */
28611 toPublic() {
28612 return this;
28613 }
28614
28615 /**
28616 * Returns ASCII armored text of key
28617 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28618 * @returns {ReadableStream<String>} ASCII armor.
28619 */
28620 armor(config = defaultConfig) {
28621 return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28622 }
28623}
28624
28625/**
28626 * Class that represents an OpenPGP Private key
28627 */
28628class PrivateKey extends PublicKey {
28629 /**
28630 * @param {PacketList} packetlist - The packets that form this key
28631 */
28632 constructor(packetlist) {
28633 super();
28634 this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));
28635 if (!this.keyPacket) {
28636 throw new Error('Invalid key: missing private-key packet');
28637 }
28638 }
28639
28640 /**
28641 * Returns true if this is a private key
28642 * @returns {Boolean}
28643 */
28644 isPrivate() {
28645 return true;
28646 }
28647
28648 /**
28649 * Returns key as public key (shallow copy)
28650 * @returns {PublicKey} New public Key
28651 */
28652 toPublic() {
28653 const packetlist = new PacketList();
28654 const keyPackets = this.toPacketList();
28655 for (const keyPacket of keyPackets) {
28656 switch (keyPacket.constructor.tag) {
28657 case enums.packet.secretKey: {
28658 const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);
28659 packetlist.push(pubKeyPacket);
28660 break;
28661 }
28662 case enums.packet.secretSubkey: {
28663 const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);
28664 packetlist.push(pubSubkeyPacket);
28665 break;
28666 }
28667 default:
28668 packetlist.push(keyPacket);
28669 }
28670 }
28671 return new PublicKey(packetlist);
28672 }
28673
28674 /**
28675 * Returns ASCII armored text of key
28676 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28677 * @returns {ReadableStream<String>} ASCII armor.
28678 */
28679 armor(config = defaultConfig) {
28680 return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28681 }
28682
28683 /**
28684 * Returns all keys that are available for decryption, matching the keyID when given
28685 * This is useful to retrieve keys for session key decryption
28686 * @param {module:type/keyid~KeyID} keyID, optional
28687 * @param {Date} date, optional
28688 * @param {String} userID, optional
28689 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28690 * @returns {Promise<Array<Key|Subkey>>} Array of decryption keys.
28691 * @async
28692 */
28693 async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {
28694 const primaryKey = this.keyPacket;
28695 const keys = [];
28696 for (let i = 0; i < this.subkeys.length; i++) {
28697 if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {
28698 try {
28699 const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };
28700 const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
28701 if (isValidDecryptionKeyPacket(bindingSignature, config)) {
28702 keys.push(this.subkeys[i]);
28703 }
28704 } catch (e) {}
28705 }
28706 }
28707
28708 // evaluate primary key
28709 const primaryUser = await this.getPrimaryUser(date, userID, config);
28710 if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&
28711 isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {
28712 keys.push(this);
28713 }
28714
28715 return keys;
28716 }
28717
28718 /**
28719 * Returns true if the primary key or any subkey is decrypted.
28720 * A dummy key is considered encrypted.
28721 */
28722 isDecrypted() {
28723 return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
28724 }
28725
28726 /**
28727 * Check whether the private and public primary key parameters correspond
28728 * Together with verification of binding signatures, this guarantees key integrity
28729 * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
28730 * otherwise all encryption subkeys are validated
28731 * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
28732 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28733 * @throws {Error} if validation was not successful and the key cannot be trusted
28734 * @async
28735 */
28736 async validate(config = defaultConfig) {
28737 if (!this.isPrivate()) {
28738 throw new Error('Cannot validate a public key');
28739 }
28740
28741 let signingKeyPacket;
28742 if (!this.keyPacket.isDummy()) {
28743 signingKeyPacket = this.keyPacket;
28744 } else {
28745 /**
28746 * It is enough to validate any signing keys
28747 * since its binding signatures are also checked
28748 */
28749 const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });
28750 // This could again be a dummy key
28751 if (signingKey && !signingKey.keyPacket.isDummy()) {
28752 signingKeyPacket = signingKey.keyPacket;
28753 }
28754 }
28755
28756 if (signingKeyPacket) {
28757 return signingKeyPacket.validate();
28758 } else {
28759 const keys = this.getKeys();
28760 const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
28761 if (allDummies) {
28762 throw new Error('Cannot validate an all-gnu-dummy key');
28763 }
28764
28765 return Promise.all(keys.map(async key => key.keyPacket.validate()));
28766 }
28767 }
28768
28769 /**
28770 * Clear private key parameters
28771 */
28772 clearPrivateParams() {
28773 this.getKeys().forEach(({ keyPacket }) => {
28774 if (keyPacket.isDecrypted()) {
28775 keyPacket.clearPrivateParams();
28776 }
28777 });
28778 }
28779
28780 /**
28781 * Revokes the key
28782 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
28783 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
28784 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
28785 * @param {Date} date - optional, override the creationtime of the revocation signature
28786 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28787 * @returns {Promise<PrivateKey>} New key with revocation signature.
28788 * @async
28789 */
28790 async revoke(
28791 {
28792 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
28793 string: reasonForRevocationString = ''
28794 } = {},
28795 date = new Date(),
28796 config = defaultConfig
28797 ) {
28798 if (!this.isPrivate()) {
28799 throw new Error('Need private key for revoking');
28800 }
28801 const dataToSign = { key: this.keyPacket };
28802 const key = this.clone();
28803 key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, {
28804 signatureType: enums.signature.keyRevocation,
28805 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
28806 reasonForRevocationString
28807 }, date, undefined, undefined, config));
28808 return key;
28809 }
28810
28811
28812 /**
28813 * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
28814 * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
28815 * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA
28816 * @param {String} options.curve (optional) Elliptic curve for ECC keys
28817 * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys
28818 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28819 * @param {Date} options.date (optional) Override the creation date of the key and the key signatures
28820 * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
28821 * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}
28822 * @returns {Promise<PrivateKey>}
28823 * @async
28824 */
28825 async addSubkey(options = {}) {
28826 const config = { ...defaultConfig, ...options.config };
28827 if (options.passphrase) {
28828 throw new Error('Subkey could not be encrypted here, please encrypt whole key');
28829 }
28830 if (options.rsaBits < config.minRSABits) {
28831 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);
28832 }
28833 const secretKeyPacket = this.keyPacket;
28834 if (secretKeyPacket.isDummy()) {
28835 throw new Error('Cannot add subkey to gnu-dummy primary key');
28836 }
28837 if (!secretKeyPacket.isDecrypted()) {
28838 throw new Error('Key is not decrypted');
28839 }
28840 const defaultOptions = secretKeyPacket.getAlgorithmInfo();
28841 defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA
28842 defaultOptions.rsaBits = defaultOptions.bits || 4096;
28843 defaultOptions.curve = defaultOptions.curve || 'curve25519';
28844 options = sanitizeKeyOptions(options, defaultOptions);
28845 const keyPacket = await generateSecretSubkey(options);
28846 checkKeyRequirements(keyPacket, config);
28847 const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config);
28848 const packetList = this.toPacketList();
28849 packetList.push(keyPacket, bindingSignature);
28850 return new PrivateKey(packetList);
28851 }
28852}
28853
28854// OpenPGP.js - An OpenPGP implementation in javascript
28855
28856// A Key can contain the following packets
28857const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([
28858 PublicKeyPacket,
28859 PublicSubkeyPacket,
28860 SecretKeyPacket,
28861 SecretSubkeyPacket,
28862 UserIDPacket,
28863 UserAttributePacket,
28864 SignaturePacket
28865]);
28866
28867/**
28868 * Generates a new OpenPGP key. Supports RSA and ECC keys.
28869 * By default, primary and subkeys will be of same type.
28870 * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA
28871 * @param {String} options.curve Elliptic curve for ECC keys
28872 * @param {Integer} options.rsaBits Number of bits for RSA keys
28873 * @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' }
28874 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28875 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28876 * @param {Date} options.date Creation date of the key and the key signatures
28877 * @param {Object} config - Full configuration
28878 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28879 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
28880 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28881 * @async
28882 * @static
28883 * @private
28884 */
28885async function generate$2(options, config) {
28886 options.sign = true; // primary key is always a signing key
28887 options = sanitizeKeyOptions(options);
28888 options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
28889 let promises = [generateSecretKey(options, config)];
28890 promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
28891 const packets = await Promise.all(promises);
28892
28893 const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);
28894 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28895 key.revocationSignatures = [];
28896 return { key, revocationCertificate };
28897}
28898
28899/**
28900 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
28901 * @param {PrivateKey} options.privateKey The private key to reformat
28902 * @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' }
28903 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28904 * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires
28905 * @param {Date} options.date Override the creation date of the key signatures
28906 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28907 * @param {Object} config - Full configuration
28908 *
28909 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28910 * @async
28911 * @static
28912 * @private
28913 */
28914async function reformat(options, config) {
28915 options = sanitize(options);
28916 const { privateKey } = options;
28917
28918 if (!privateKey.isPrivate()) {
28919 throw new Error('Cannot reformat a public key');
28920 }
28921
28922 if (privateKey.keyPacket.isDummy()) {
28923 throw new Error('Cannot reformat a gnu-dummy primary key');
28924 }
28925
28926 const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
28927 if (!isDecrypted) {
28928 throw new Error('Key is not decrypted');
28929 }
28930
28931 const secretKeyPacket = privateKey.keyPacket;
28932
28933 if (!options.subkeys) {
28934 options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {
28935 const secretSubkeyPacket = subkey.keyPacket;
28936 const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };
28937 const bindingSignature = await (
28938 getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)
28939 ).catch(() => ({}));
28940 return {
28941 sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)
28942 };
28943 }));
28944 }
28945
28946 const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);
28947 if (options.subkeys.length !== secretSubkeyPackets.length) {
28948 throw new Error('Number of subkey options does not match number of subkeys');
28949 }
28950
28951 options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));
28952
28953 const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
28954 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28955 key.revocationSignatures = [];
28956 return { key, revocationCertificate };
28957
28958 function sanitize(options, subkeyDefaults = {}) {
28959 options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
28960 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
28961 options.date = options.date || subkeyDefaults.date;
28962
28963 return options;
28964 }
28965}
28966
28967/**
28968 * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection
28969 * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.
28970 * @param {SecretKeyPacket} secretKeyPacket
28971 * @param {SecretSubkeyPacket} secretSubkeyPackets
28972 * @param {Object} options
28973 * @param {Object} config - Full configuration
28974 * @returns {PrivateKey}
28975 */
28976async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
28977 // set passphrase protection
28978 if (options.passphrase) {
28979 await secretKeyPacket.encrypt(options.passphrase, config);
28980 }
28981
28982 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
28983 const subkeyPassphrase = options.subkeys[index].passphrase;
28984 if (subkeyPassphrase) {
28985 await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
28986 }
28987 }));
28988
28989 const packetlist = new PacketList();
28990 packetlist.push(secretKeyPacket);
28991
28992 await Promise.all(options.userIDs.map(async function(userID, index) {
28993 function createPreferredAlgos(algos, preferredAlgo) {
28994 return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];
28995 }
28996
28997 const userIDPacket = UserIDPacket.fromObject(userID);
28998 const dataToSign = {};
28999 dataToSign.userID = userIDPacket;
29000 dataToSign.key = secretKeyPacket;
29001 const signaturePacket = new SignaturePacket();
29002 signaturePacket.signatureType = enums.signature.certGeneric;
29003 signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
29004 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, secretKeyPacket, undefined, undefined, config);
29005 signaturePacket.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
29006 signaturePacket.preferredSymmetricAlgorithms = createPreferredAlgos([
29007 // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
29008 enums.symmetric.aes256,
29009 enums.symmetric.aes128,
29010 enums.symmetric.aes192
29011 ], config.preferredSymmetricAlgorithm);
29012 if (config.aeadProtect) {
29013 signaturePacket.preferredAEADAlgorithms = createPreferredAlgos([
29014 enums.aead.eax,
29015 enums.aead.ocb
29016 ], config.preferredAEADAlgorithm);
29017 }
29018 signaturePacket.preferredHashAlgorithms = createPreferredAlgos([
29019 // prefer fast asm.js implementations (SHA-256)
29020 enums.hash.sha256,
29021 enums.hash.sha512
29022 ], config.preferredHashAlgorithm);
29023 signaturePacket.preferredCompressionAlgorithms = createPreferredAlgos([
29024 enums.compression.zlib,
29025 enums.compression.zip,
29026 enums.compression.uncompressed
29027 ], config.preferredCompressionAlgorithm);
29028 if (index === 0) {
29029 signaturePacket.isPrimaryUserID = true;
29030 }
29031 // integrity protection always enabled
29032 signaturePacket.features = [0];
29033 signaturePacket.features[0] |= enums.features.modificationDetection;
29034 if (config.aeadProtect) {
29035 signaturePacket.features[0] |= enums.features.aead;
29036 }
29037 if (config.v5Keys) {
29038 signaturePacket.features[0] |= enums.features.v5Keys;
29039 }
29040 if (options.keyExpirationTime > 0) {
29041 signaturePacket.keyExpirationTime = options.keyExpirationTime;
29042 signaturePacket.keyNeverExpires = false;
29043 }
29044 await signaturePacket.sign(secretKeyPacket, dataToSign, options.date);
29045
29046 return { userIDPacket, signaturePacket };
29047 })).then(list => {
29048 list.forEach(({ userIDPacket, signaturePacket }) => {
29049 packetlist.push(userIDPacket);
29050 packetlist.push(signaturePacket);
29051 });
29052 });
29053
29054 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29055 const subkeyOptions = options.subkeys[index];
29056 const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
29057 return { secretSubkeyPacket, subkeySignaturePacket };
29058 })).then(packets => {
29059 packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
29060 packetlist.push(secretSubkeyPacket);
29061 packetlist.push(subkeySignaturePacket);
29062 });
29063 });
29064
29065 // Add revocation signature packet for creating a revocation certificate.
29066 // This packet should be removed before returning the key.
29067 const dataToSign = { key: secretKeyPacket };
29068 packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, {
29069 signatureType: enums.signature.keyRevocation,
29070 reasonForRevocationFlag: enums.reasonForRevocation.noReason,
29071 reasonForRevocationString: ''
29072 }, options.date, undefined, undefined, config));
29073
29074 if (options.passphrase) {
29075 secretKeyPacket.clearPrivateParams();
29076 }
29077
29078 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29079 const subkeyPassphrase = options.subkeys[index].passphrase;
29080 if (subkeyPassphrase) {
29081 secretSubkeyPacket.clearPrivateParams();
29082 }
29083 }));
29084
29085 return new PrivateKey(packetlist);
29086}
29087
29088/**
29089 * Reads an (optionally armored) OpenPGP key and returns a key object
29090 * @param {Object} options
29091 * @param {String} [options.armoredKey] - Armored key to be parsed
29092 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29093 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29094 * @returns {Promise<Key>} Key object.
29095 * @async
29096 * @static
29097 */
29098async function readKey({ armoredKey, binaryKey, config, ...rest }) {
29099 config = { ...defaultConfig, ...config };
29100 if (!armoredKey && !binaryKey) {
29101 throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
29102 }
29103 if (armoredKey && !util.isString(armoredKey)) {
29104 throw new Error('readKey: options.armoredKey must be a string');
29105 }
29106 if (binaryKey && !util.isUint8Array(binaryKey)) {
29107 throw new Error('readKey: options.binaryKey must be a Uint8Array');
29108 }
29109 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29110
29111 let input;
29112 if (armoredKey) {
29113 const { type, data } = await unarmor(armoredKey, config);
29114 if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
29115 throw new Error('Armored text not of type key');
29116 }
29117 input = data;
29118 } else {
29119 input = binaryKey;
29120 }
29121 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29122 return createKey(packetlist);
29123}
29124
29125/**
29126 * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object
29127 * @param {Object} options
29128 * @param {String} [options.armoredKey] - Armored key to be parsed
29129 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29130 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29131 * @returns {Promise<PrivateKey>} Key object.
29132 * @async
29133 * @static
29134 */
29135async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {
29136 config = { ...defaultConfig, ...config };
29137 if (!armoredKey && !binaryKey) {
29138 throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');
29139 }
29140 if (armoredKey && !util.isString(armoredKey)) {
29141 throw new Error('readPrivateKey: options.armoredKey must be a string');
29142 }
29143 if (binaryKey && !util.isUint8Array(binaryKey)) {
29144 throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');
29145 }
29146 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29147
29148 let input;
29149 if (armoredKey) {
29150 const { type, data } = await unarmor(armoredKey, config);
29151 if (!(type === enums.armor.privateKey)) {
29152 throw new Error('Armored text not of type private key');
29153 }
29154 input = data;
29155 } else {
29156 input = binaryKey;
29157 }
29158 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29159 return new PrivateKey(packetlist);
29160}
29161
29162/**
29163 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
29164 * @param {Object} options
29165 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29166 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29167 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29168 * @returns {Promise<Array<Key>>} Key objects.
29169 * @async
29170 * @static
29171 */
29172async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {
29173 config = { ...defaultConfig, ...config };
29174 let input = armoredKeys || binaryKeys;
29175 if (!input) {
29176 throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29177 }
29178 if (armoredKeys && !util.isString(armoredKeys)) {
29179 throw new Error('readKeys: options.armoredKeys must be a string');
29180 }
29181 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29182 throw new Error('readKeys: options.binaryKeys must be a Uint8Array');
29183 }
29184 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29185
29186 if (armoredKeys) {
29187 const { type, data } = await unarmor(armoredKeys, config);
29188 if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
29189 throw new Error('Armored text not of type key');
29190 }
29191 input = data;
29192 }
29193 const keys = [];
29194 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29195 const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
29196 if (keyIndex.length === 0) {
29197 throw new Error('No key packet found');
29198 }
29199 for (let i = 0; i < keyIndex.length; i++) {
29200 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29201 const newKey = createKey(oneKeyList);
29202 keys.push(newKey);
29203 }
29204 return keys;
29205}
29206
29207/**
29208 * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects
29209 * @param {Object} options
29210 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29211 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29212 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29213 * @returns {Promise<Array<PrivateKey>>} Key objects.
29214 * @async
29215 * @static
29216 */
29217async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {
29218 config = { ...defaultConfig, ...config };
29219 let input = armoredKeys || binaryKeys;
29220 if (!input) {
29221 throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29222 }
29223 if (armoredKeys && !util.isString(armoredKeys)) {
29224 throw new Error('readPrivateKeys: options.armoredKeys must be a string');
29225 }
29226 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29227 throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');
29228 }
29229 if (armoredKeys) {
29230 const { type, data } = await unarmor(armoredKeys, config);
29231 if (type !== enums.armor.privateKey) {
29232 throw new Error('Armored text not of type private key');
29233 }
29234 input = data;
29235 }
29236 const keys = [];
29237 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29238 const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);
29239 if (keyIndex.length === 0) {
29240 throw new Error('No secret key packet found');
29241 }
29242 for (let i = 0; i < keyIndex.length; i++) {
29243 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29244 const newKey = new PrivateKey(oneKeyList);
29245 keys.push(newKey);
29246 }
29247 return keys;
29248}
29249
29250// GPG4Browsers - An OpenPGP implementation in javascript
29251
29252// A Message can contain the following packets
29253const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([
29254 LiteralDataPacket,
29255 CompressedDataPacket,
29256 AEADEncryptedDataPacket,
29257 SymEncryptedIntegrityProtectedDataPacket,
29258 SymmetricallyEncryptedDataPacket,
29259 PublicKeyEncryptedSessionKeyPacket,
29260 SymEncryptedSessionKeyPacket,
29261 OnePassSignaturePacket,
29262 SignaturePacket
29263]);
29264// A SKESK packet can contain the following packets
29265const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);
29266// A detached signature can contain the following packets
29267const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
29268
29269/**
29270 * Class that represents an OpenPGP message.
29271 * Can be an encrypted message, signed message, compressed message or literal message
29272 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
29273 */
29274class Message {
29275 /**
29276 * @param {PacketList} packetlist - The packets that form this message
29277 */
29278 constructor(packetlist) {
29279 this.packets = packetlist || new PacketList();
29280 }
29281
29282 /**
29283 * Returns the key IDs of the keys to which the session key is encrypted
29284 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29285 */
29286 getEncryptionKeyIDs() {
29287 const keyIDs = [];
29288 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29289 pkESKeyPacketlist.forEach(function(packet) {
29290 keyIDs.push(packet.publicKeyID);
29291 });
29292 return keyIDs;
29293 }
29294
29295 /**
29296 * Returns the key IDs of the keys that signed the message
29297 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29298 */
29299 getSigningKeyIDs() {
29300 const msg = this.unwrapCompressed();
29301 // search for one pass signatures
29302 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
29303 if (onePassSigList.length > 0) {
29304 return onePassSigList.map(packet => packet.issuerKeyID);
29305 }
29306 // if nothing found look for signature packets
29307 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29308 return signatureList.map(packet => packet.issuerKeyID);
29309 }
29310
29311 /**
29312 * Decrypt the message. Either a private key, a session key, or a password must be specified.
29313 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29314 * @param {Array<String>} [passwords] - Passwords used to decrypt
29315 * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29316 * @param {Date} [date] - Use the given date for key verification instead of the current time
29317 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29318 * @returns {Promise<Message>} New message with decrypted content.
29319 * @async
29320 */
29321 async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {
29322 const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);
29323
29324 const symEncryptedPacketlist = this.packets.filterByTag(
29325 enums.packet.symmetricallyEncryptedData,
29326 enums.packet.symEncryptedIntegrityProtectedData,
29327 enums.packet.aeadEncryptedData
29328 );
29329
29330 if (symEncryptedPacketlist.length === 0) {
29331 throw new Error('No encrypted data found');
29332 }
29333
29334 const symEncryptedPacket = symEncryptedPacketlist[0];
29335 let exception = null;
29336 const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {
29337 if (!util.isUint8Array(data) || !util.isString(algorithmName)) {
29338 throw new Error('Invalid session key for decryption.');
29339 }
29340
29341 try {
29342 const algo = enums.write(enums.symmetric, algorithmName);
29343 await symEncryptedPacket.decrypt(algo, data, config);
29344 } catch (e) {
29345 util.printDebugError(e);
29346 exception = e;
29347 }
29348 }));
29349 // We don't await stream.cancel here because it only returns when the other copy is canceled too.
29350 cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
29351 symEncryptedPacket.encrypted = null;
29352 await decryptedPromise;
29353
29354 if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
29355 throw exception || new Error('Decryption failed.');
29356 }
29357
29358 const resultMsg = new Message(symEncryptedPacket.packets);
29359 symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
29360
29361 return resultMsg;
29362 }
29363
29364 /**
29365 * Decrypt encrypted session keys either with private keys or passwords.
29366 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29367 * @param {Array<String>} [passwords] - Passwords used to decrypt
29368 * @param {Date} [date] - Use the given date for key verification, instead of current time
29369 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29370 * @returns {Promise<Array<{
29371 * data: Uint8Array,
29372 * algorithm: String
29373 * }>>} array of object with potential sessionKey, algorithm pairs
29374 * @async
29375 */
29376 async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {
29377 let decryptedSessionKeyPackets = [];
29378
29379 let exception;
29380 if (passwords) {
29381 const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
29382 if (skeskPackets.length === 0) {
29383 throw new Error('No symmetrically encrypted session key packet found.');
29384 }
29385 await Promise.all(passwords.map(async function(password, i) {
29386 let packets;
29387 if (i) {
29388 packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config);
29389 } else {
29390 packets = skeskPackets;
29391 }
29392 await Promise.all(packets.map(async function(skeskPacket) {
29393 try {
29394 await skeskPacket.decrypt(password);
29395 decryptedSessionKeyPackets.push(skeskPacket);
29396 } catch (err) {
29397 util.printDebugError(err);
29398 }
29399 }));
29400 }));
29401 } else if (decryptionKeys) {
29402 const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29403 if (pkeskPackets.length === 0) {
29404 throw new Error('No public key encrypted session key packet found.');
29405 }
29406 await Promise.all(pkeskPackets.map(async function(pkeskPacket) {
29407 await Promise.all(decryptionKeys.map(async function(decryptionKey) {
29408 let algos = [
29409 enums.symmetric.aes256, // Old OpenPGP.js default fallback
29410 enums.symmetric.aes128, // RFC4880bis fallback
29411 enums.symmetric.tripledes, // RFC4880 fallback
29412 enums.symmetric.cast5 // Golang OpenPGP fallback
29413 ];
29414 try {
29415 const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.
29416 if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
29417 algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
29418 }
29419 } catch (e) {}
29420
29421 // do not check key expiration to allow decryption of old messages
29422 const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);
29423 await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {
29424 if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {
29425 return;
29426 }
29427 if (!decryptionKeyPacket.isDecrypted()) {
29428 throw new Error('Decryption key is not decrypted.');
29429 }
29430
29431 // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.
29432 const doConstantTimeDecryption = config.constantTimePKCS1Decryption && (
29433 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||
29434 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||
29435 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||
29436 pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal
29437 );
29438
29439 if (doConstantTimeDecryption) {
29440 // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,
29441 // either with the successfully decrypted session key, or with a randomly generated one.
29442 // 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
29443 // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:
29444 // - 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
29445 // randomly generated keys of the remaining key types.
29446 // - 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
29447 // generated session keys.
29448 // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.
29449
29450 const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times
29451 await Promise.all(Array.from(config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {
29452 const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();
29453 pkeskPacketCopy.read(serialisedPKESK);
29454 const randomSessionKey = {
29455 sessionKeyAlgorithm,
29456 sessionKey: await mod.generateSessionKey(sessionKeyAlgorithm)
29457 };
29458 try {
29459 await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);
29460 decryptedSessionKeyPackets.push(pkeskPacketCopy);
29461 } catch (err) {
29462 // `decrypt` can still throw some non-security-sensitive errors
29463 util.printDebugError(err);
29464 exception = err;
29465 }
29466 }));
29467
29468 } else {
29469 try {
29470 await pkeskPacket.decrypt(decryptionKeyPacket);
29471 if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {
29472 throw new Error('A non-preferred symmetric algorithm was used.');
29473 }
29474 decryptedSessionKeyPackets.push(pkeskPacket);
29475 } catch (err) {
29476 util.printDebugError(err);
29477 exception = err;
29478 }
29479 }
29480 }));
29481 }));
29482 cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.
29483 pkeskPacket.encrypted = null;
29484 }));
29485 } else {
29486 throw new Error('No key or password specified.');
29487 }
29488
29489 if (decryptedSessionKeyPackets.length > 0) {
29490 // Return only unique session keys
29491 if (decryptedSessionKeyPackets.length > 1) {
29492 const seen = new Set();
29493 decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {
29494 const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);
29495 if (seen.has(k)) {
29496 return false;
29497 }
29498 seen.add(k);
29499 return true;
29500 });
29501 }
29502
29503 return decryptedSessionKeyPackets.map(packet => ({
29504 data: packet.sessionKey,
29505 algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)
29506 }));
29507 }
29508 throw exception || new Error('Session key decryption failed.');
29509 }
29510
29511 /**
29512 * Get literal data that is the body of the message
29513 * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
29514 */
29515 getLiteralData() {
29516 const msg = this.unwrapCompressed();
29517 const literal = msg.packets.findPacket(enums.packet.literalData);
29518 return (literal && literal.getBytes()) || null;
29519 }
29520
29521 /**
29522 * Get filename from literal data packet
29523 * @returns {(String|null)} Filename of literal data packet as string.
29524 */
29525 getFilename() {
29526 const msg = this.unwrapCompressed();
29527 const literal = msg.packets.findPacket(enums.packet.literalData);
29528 return (literal && literal.getFilename()) || null;
29529 }
29530
29531 /**
29532 * Get literal data as text
29533 * @returns {(String|null)} Literal body of the message interpreted as text.
29534 */
29535 getText() {
29536 const msg = this.unwrapCompressed();
29537 const literal = msg.packets.findPacket(enums.packet.literalData);
29538 if (literal) {
29539 return literal.getText();
29540 }
29541 return null;
29542 }
29543
29544 /**
29545 * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.
29546 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) to select algorithm preferences for
29547 * @param {Date} [date] - Date to select algorithm preferences at
29548 * @param {Array<Object>} [userIDs] - User IDs to select algorithm preferences for
29549 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29550 * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.
29551 * @async
29552 */
29553 static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {
29554 const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config);
29555 const algorithmName = enums.read(enums.symmetric, algo);
29556 const aeadAlgorithmName = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?
29557 enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :
29558 undefined;
29559
29560 const sessionKeyData = await mod.generateSessionKey(algo);
29561 return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };
29562 }
29563
29564 /**
29565 * Encrypt the message either with public keys, passwords, or both at once.
29566 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29567 * @param {Array<String>} [passwords] - Password(s) for message encryption
29568 * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29569 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29570 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]
29571 * @param {Date} [date] - Override the creation date of the literal package
29572 * @param {Array<Object>} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29573 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29574 * @returns {Promise<Message>} New message with encrypted content.
29575 * @async
29576 */
29577 async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29578 if (sessionKey) {
29579 if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
29580 throw new Error('Invalid session key for encryption.');
29581 }
29582 } else if (encryptionKeys && encryptionKeys.length) {
29583 sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);
29584 } else if (passwords && passwords.length) {
29585 sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);
29586 } else {
29587 throw new Error('No keys, passwords, or session key provided.');
29588 }
29589
29590 const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;
29591
29592 const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);
29593
29594 let symEncryptedPacket;
29595 if (aeadAlgorithmName) {
29596 symEncryptedPacket = new AEADEncryptedDataPacket();
29597 symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);
29598 } else {
29599 symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();
29600 }
29601 symEncryptedPacket.packets = this.packets;
29602
29603 const algorithm = enums.write(enums.symmetric, algorithmName);
29604 await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);
29605
29606 msg.packets.push(symEncryptedPacket);
29607 symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
29608 return msg;
29609 }
29610
29611 /**
29612 * Encrypt a session key either with public keys, passwords, or both at once.
29613 * @param {Uint8Array} sessionKey - session key for encryption
29614 * @param {String} algorithmName - session key algorithm
29615 * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'
29616 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29617 * @param {Array<String>} [passwords] - For message encryption
29618 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29619 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
29620 * @param {Date} [date] - Override the date
29621 * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29622 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29623 * @returns {Promise<Message>} New message with encrypted content.
29624 * @async
29625 */
29626 static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29627 const packetlist = new PacketList();
29628 const algorithm = enums.write(enums.symmetric, algorithmName);
29629 const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);
29630
29631 if (encryptionKeys) {
29632 const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {
29633 const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);
29634 const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();
29635 pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();
29636 pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
29637 pkESKeyPacket.sessionKey = sessionKey;
29638 pkESKeyPacket.sessionKeyAlgorithm = algorithm;
29639 await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
29640 delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
29641 return pkESKeyPacket;
29642 }));
29643 packetlist.push(...results);
29644 }
29645 if (passwords) {
29646 const testDecrypt = async function(keyPacket, password) {
29647 try {
29648 await keyPacket.decrypt(password);
29649 return 1;
29650 } catch (e) {
29651 return 0;
29652 }
29653 };
29654
29655 const sum = (accumulator, currentValue) => accumulator + currentValue;
29656
29657 const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {
29658 const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);
29659 symEncryptedSessionKeyPacket.sessionKey = sessionKey;
29660 symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
29661 if (aeadAlgorithm) {
29662 symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
29663 }
29664 await symEncryptedSessionKeyPacket.encrypt(password, config);
29665
29666 if (config.passwordCollisionCheck) {
29667 const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
29668 if (results.reduce(sum) !== 1) {
29669 return encryptPassword(sessionKey, algorithm, password);
29670 }
29671 }
29672
29673 delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
29674 return symEncryptedSessionKeyPacket;
29675 };
29676
29677 const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));
29678 packetlist.push(...results);
29679 }
29680
29681 return new Message(packetlist);
29682 }
29683
29684 /**
29685 * Sign the message (the literal data packet of the message)
29686 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29687 * @param {Signature} [signature] - Any existing detached signature to add to the message
29688 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29689 * @param {Date} [date] - Override the creation time of the signature
29690 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29691 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29692 * @returns {Promise<Message>} New message with signed content.
29693 * @async
29694 */
29695 async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29696 const packetlist = new PacketList();
29697
29698 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29699 if (!literalDataPacket) {
29700 throw new Error('No literal data packet to sign.');
29701 }
29702
29703 let i;
29704 let existingSigPacketlist;
29705 // If data packet was created from Uint8Array, use binary, otherwise use text
29706 const signatureType = literalDataPacket.text === null ?
29707 enums.signature.binary : enums.signature.text;
29708
29709 if (signature) {
29710 existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29711 for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
29712 const signaturePacket = existingSigPacketlist[i];
29713 const onePassSig = new OnePassSignaturePacket();
29714 onePassSig.signatureType = signaturePacket.signatureType;
29715 onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
29716 onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
29717 onePassSig.issuerKeyID = signaturePacket.issuerKeyID;
29718 if (!signingKeys.length && i === 0) {
29719 onePassSig.flags = 1;
29720 }
29721 packetlist.push(onePassSig);
29722 }
29723 }
29724
29725 await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {
29726 if (!primaryKey.isPrivate()) {
29727 throw new Error('Need private key for signing');
29728 }
29729 const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];
29730 const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);
29731 const onePassSig = new OnePassSignaturePacket();
29732 onePassSig.signatureType = signatureType;
29733 onePassSig.hashAlgorithm = await getPreferredHashAlgo$1(primaryKey, signingKey.keyPacket, date, userIDs, config);
29734 onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
29735 onePassSig.issuerKeyID = signingKey.getKeyID();
29736 if (i === signingKeys.length - 1) {
29737 onePassSig.flags = 1;
29738 }
29739 return onePassSig;
29740 })).then(onePassSignatureList => {
29741 onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
29742 });
29743
29744 packetlist.push(literalDataPacket);
29745 packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, false, config)));
29746
29747 return new Message(packetlist);
29748 }
29749
29750 /**
29751 * Compresses the message (the literal and -if signed- signature data packets of the message)
29752 * @param {module:enums.compression} algo - compression algorithm
29753 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29754 * @returns {Message} New message with compressed content.
29755 */
29756 compress(algo, config = defaultConfig) {
29757 if (algo === enums.compression.uncompressed) {
29758 return this;
29759 }
29760
29761 const compressed = new CompressedDataPacket(config);
29762 compressed.algorithm = algo;
29763 compressed.packets = this.packets;
29764
29765 const packetList = new PacketList();
29766 packetList.push(compressed);
29767
29768 return new Message(packetList);
29769 }
29770
29771 /**
29772 * Create a detached signature for the message (the literal data packet of the message)
29773 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29774 * @param {Signature} [signature] - Any existing detached signature
29775 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29776 * @param {Date} [date] - Override the creation time of the signature
29777 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29778 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29779 * @returns {Promise<Signature>} New detached signature of message content.
29780 * @async
29781 */
29782 async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29783 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29784 if (!literalDataPacket) {
29785 throw new Error('No literal data packet to sign.');
29786 }
29787 return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, true, config));
29788 }
29789
29790 /**
29791 * Verify message signatures
29792 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29793 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29794 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29795 * @returns {Promise<Array<{
29796 * keyID: module:type/keyid~KeyID,
29797 * signature: Promise<Signature>,
29798 * verified: Promise<true>
29799 * }>>} List of signer's keyID and validity of signatures.
29800 * @async
29801 */
29802 async verify(verificationKeys, date = new Date(), config = defaultConfig) {
29803 const msg = this.unwrapCompressed();
29804 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29805 if (literalDataList.length !== 1) {
29806 throw new Error('Can only verify message with one literal data packet.');
29807 }
29808 if (isArrayStream(msg.packets.stream)) {
29809 msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || []));
29810 }
29811 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
29812 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29813 if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) {
29814 await Promise.all(onePassSigList.map(async onePassSig => {
29815 onePassSig.correspondingSig = new Promise((resolve, reject) => {
29816 onePassSig.correspondingSigResolve = resolve;
29817 onePassSig.correspondingSigReject = reject;
29818 });
29819 onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
29820 onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));
29821 onePassSig.hashed.catch(() => {});
29822 }));
29823 msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => {
29824 const reader = getReader(readable);
29825 const writer = getWriter(writable);
29826 try {
29827 for (let i = 0; i < onePassSigList.length; i++) {
29828 const { value: signature } = await reader.read();
29829 onePassSigList[i].correspondingSigResolve(signature);
29830 }
29831 await reader.readToEnd();
29832 await writer.ready;
29833 await writer.close();
29834 } catch (e) {
29835 onePassSigList.forEach(onePassSig => {
29836 onePassSig.correspondingSigReject(e);
29837 });
29838 await writer.abort(e);
29839 }
29840 });
29841 return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);
29842 }
29843 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);
29844 }
29845
29846 /**
29847 * Verify detached message signature
29848 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29849 * @param {Signature} signature
29850 * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29851 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29852 * @returns {Promise<Array<{
29853 * keyID: module:type/keyid~KeyID,
29854 * signature: Promise<Signature>,
29855 * verified: Promise<true>
29856 * }>>} List of signer's keyID and validity of signature.
29857 * @async
29858 */
29859 verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {
29860 const msg = this.unwrapCompressed();
29861 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29862 if (literalDataList.length !== 1) {
29863 throw new Error('Can only verify message with one literal data packet.');
29864 }
29865 const signatureList = signature.packets;
29866 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);
29867 }
29868
29869 /**
29870 * Unwrap compressed message
29871 * @returns {Message} Message Content of compressed message.
29872 */
29873 unwrapCompressed() {
29874 const compressed = this.packets.filterByTag(enums.packet.compressedData);
29875 if (compressed.length) {
29876 return new Message(compressed[0].packets);
29877 }
29878 return this;
29879 }
29880
29881 /**
29882 * Append signature to unencrypted message object
29883 * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
29884 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29885 */
29886 async appendSignature(detachedSignature, config = defaultConfig) {
29887 await this.packets.read(
29888 util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,
29889 allowedDetachedSignaturePackets,
29890 config
29891 );
29892 }
29893
29894 /**
29895 * Returns binary encoded message
29896 * @returns {ReadableStream<Uint8Array>} Binary message.
29897 */
29898 write() {
29899 return this.packets.write();
29900 }
29901
29902 /**
29903 * Returns ASCII armored text of message
29904 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29905 * @returns {ReadableStream<String>} ASCII armor.
29906 */
29907 armor(config = defaultConfig) {
29908 return armor(enums.armor.message, this.write(), null, null, null, config);
29909 }
29910}
29911
29912/**
29913 * Create signature packets for the message
29914 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
29915 * @param {Array<PrivateKey>} [signingKeys] - private keys with decrypted secret key data for signing
29916 * @param {Signature} [signature] - Any existing detached signature to append
29917 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29918 * @param {Date} [date] - Override the creationtime of the signature
29919 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29920 * @param {Boolean} [detached] - Whether to create detached signature packets
29921 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29922 * @returns {Promise<PacketList>} List of signature packets.
29923 * @async
29924 * @private
29925 */
29926async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], detached = false, config = defaultConfig) {
29927 const packetlist = new PacketList();
29928
29929 // If data packet was created from Uint8Array, use binary, otherwise use text
29930 const signatureType = literalDataPacket.text === null ?
29931 enums.signature.binary : enums.signature.text;
29932
29933 await Promise.all(signingKeys.map(async (primaryKey, i) => {
29934 const userID = userIDs[i];
29935 if (!primaryKey.isPrivate()) {
29936 throw new Error('Need private key for signing');
29937 }
29938 const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);
29939 return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, detached, config);
29940 })).then(signatureList => {
29941 packetlist.push(...signatureList);
29942 });
29943
29944 if (signature) {
29945 const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29946 packetlist.push(...existingSigPacketlist);
29947 }
29948 return packetlist;
29949}
29950
29951/**
29952 * Create object containing signer's keyID and validity of signature
29953 * @param {SignaturePacket} signature - Signature packet
29954 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
29955 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29956 * @param {Date} [date] - Check signature validity with respect to the given date
29957 * @param {Boolean} [detached] - Whether to verify detached signature packets
29958 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29959 * @returns {Promise<{
29960 * keyID: module:type/keyid~KeyID,
29961 * signature: Promise<Signature>,
29962 * verified: Promise<true>
29963 * }>} signer's keyID and validity of signature
29964 * @async
29965 * @private
29966 */
29967async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
29968 let primaryKey;
29969 let unverifiedSigningKey;
29970
29971 for (const key of verificationKeys) {
29972 const issuerKeys = key.getKeys(signature.issuerKeyID);
29973 if (issuerKeys.length > 0) {
29974 primaryKey = key;
29975 unverifiedSigningKey = issuerKeys[0];
29976 break;
29977 }
29978 }
29979
29980 const isOnePassSignature = signature instanceof OnePassSignaturePacket;
29981 const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;
29982
29983 const verifiedSig = {
29984 keyID: signature.issuerKeyID,
29985 verified: (async () => {
29986 if (!unverifiedSigningKey) {
29987 throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);
29988 }
29989
29990 await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);
29991 const signaturePacket = await signaturePacketPromise;
29992 if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {
29993 throw new Error('Key is newer than the signature');
29994 }
29995 // We pass the signature creation time to check whether the key was expired at the time of signing.
29996 // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before
29997 try {
29998 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);
29999 } catch (e) {
30000 // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,
30001 // making the key invalid at the time of signing.
30002 // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.
30003 // Note: we do not support the edge case of a key that was reformatted and it has expired.
30004 if (config.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {
30005 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config);
30006 } else {
30007 throw e;
30008 }
30009 }
30010 return true;
30011 })(),
30012 signature: (async () => {
30013 const signaturePacket = await signaturePacketPromise;
30014 const packetlist = new PacketList();
30015 signaturePacket && packetlist.push(signaturePacket);
30016 return new Signature(packetlist);
30017 })()
30018 };
30019
30020 // Mark potential promise rejections as "handled". This is needed because in
30021 // some cases, we reject them before the user has a reasonable chance to
30022 // handle them (e.g. `await readToEnd(result.data); await result.verified` and
30023 // the data stream errors).
30024 verifiedSig.signature.catch(() => {});
30025 verifiedSig.verified.catch(() => {});
30026
30027 return verifiedSig;
30028}
30029
30030/**
30031 * Create list of objects containing signer's keyID and validity of signature
30032 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
30033 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
30034 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30035 * @param {Date} date - Verify the signature against the given date,
30036 * i.e. check signature creation time < date < expiration time
30037 * @param {Boolean} [detached] - Whether to verify detached signature packets
30038 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30039 * @returns {Promise<Array<{
30040 * keyID: module:type/keyid~KeyID,
30041 * signature: Promise<Signature>,
30042 * verified: Promise<true>
30043 * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)
30044 * @async
30045 * @private
30046 */
30047async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
30048 return Promise.all(signatureList.filter(function(signature) {
30049 return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
30050 }).map(async function(signature) {
30051 return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);
30052 }));
30053}
30054
30055/**
30056 * Reads an (optionally armored) OpenPGP message and returns a Message object
30057 * @param {Object} options
30058 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
30059 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
30060 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30061 * @returns {Promise<Message>} New message object.
30062 * @async
30063 * @static
30064 */
30065async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {
30066 config = { ...defaultConfig, ...config };
30067 let input = armoredMessage || binaryMessage;
30068 if (!input) {
30069 throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
30070 }
30071 if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {
30072 throw new Error('readMessage: options.armoredMessage must be a string or stream');
30073 }
30074 if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {
30075 throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');
30076 }
30077 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30078
30079 const streamType = util.isStream(input);
30080 if (streamType) {
30081 await loadStreamsPonyfill();
30082 input = toStream(input);
30083 }
30084 if (armoredMessage) {
30085 const { type, data } = await unarmor(input, config);
30086 if (type !== enums.armor.message) {
30087 throw new Error('Armored text not of type message');
30088 }
30089 input = data;
30090 }
30091 const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);
30092 const message = new Message(packetlist);
30093 message.fromStream = streamType;
30094 return message;
30095}
30096
30097/**
30098 * Creates new message object from text or binary data.
30099 * @param {Object} options
30100 * @param {String | ReadableStream<String>} [options.text] - The text message contents
30101 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binary] - The binary message contents
30102 * @param {String} [options.filename=""] - Name of the file (if any)
30103 * @param {Date} [options.date=current date] - Date of the message, or modification date of the file
30104 * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type
30105 * @returns {Promise<Message>} New message object.
30106 * @async
30107 * @static
30108 */
30109async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {
30110 let input = text !== undefined ? text : binary;
30111 if (input === undefined) {
30112 throw new Error('createMessage: must pass options object containing `text` or `binary`');
30113 }
30114 if (text && !util.isString(text) && !util.isStream(text)) {
30115 throw new Error('createMessage: options.text must be a string or stream');
30116 }
30117 if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {
30118 throw new Error('createMessage: options.binary must be a Uint8Array or stream');
30119 }
30120 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30121
30122 const streamType = util.isStream(input);
30123 if (streamType) {
30124 await loadStreamsPonyfill();
30125 input = toStream(input);
30126 }
30127 const literalDataPacket = new LiteralDataPacket(date);
30128 if (text !== undefined) {
30129 literalDataPacket.setText(input, enums.write(enums.literal, format));
30130 } else {
30131 literalDataPacket.setBytes(input, enums.write(enums.literal, format));
30132 }
30133 if (filename !== undefined) {
30134 literalDataPacket.setFilename(filename);
30135 }
30136 const literalDataPacketlist = new PacketList();
30137 literalDataPacketlist.push(literalDataPacket);
30138 const message = new Message(literalDataPacketlist);
30139 message.fromStream = streamType;
30140 return message;
30141}
30142
30143// GPG4Browsers - An OpenPGP implementation in javascript
30144
30145// A Cleartext message can contain the following packets
30146const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
30147
30148/**
30149 * Class that represents an OpenPGP cleartext signed message.
30150 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
30151 */
30152class CleartextMessage {
30153 /**
30154 * @param {String} text - The cleartext of the signed message
30155 * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
30156 */
30157 constructor(text, signature) {
30158 // remove trailing whitespace and normalize EOL to canonical form <CR><LF>
30159 this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
30160 if (signature && !(signature instanceof Signature)) {
30161 throw new Error('Invalid signature input');
30162 }
30163 this.signature = signature || new Signature(new PacketList());
30164 }
30165
30166 /**
30167 * Returns the key IDs of the keys that signed the cleartext message
30168 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
30169 */
30170 getSigningKeyIDs() {
30171 const keyIDs = [];
30172 const signatureList = this.signature.packets;
30173 signatureList.forEach(function(packet) {
30174 keyIDs.push(packet.issuerKeyID);
30175 });
30176 return keyIDs;
30177 }
30178
30179 /**
30180 * Sign the cleartext message
30181 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
30182 * @param {Signature} [signature] - Any existing detached signature
30183 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
30184 * @param {Date} [date] - The creation time of the signature that should be created
30185 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30186 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30187 * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
30188 * @async
30189 */
30190 async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
30191 const literalDataPacket = new LiteralDataPacket();
30192 literalDataPacket.setText(this.text);
30193 const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, true, config));
30194 return new CleartextMessage(this.text, newSignature);
30195 }
30196
30197 /**
30198 * Verify signatures of cleartext signed message
30199 * @param {Array<Key>} keys - Array of keys to verify signatures
30200 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
30201 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30202 * @returns {Promise<Array<{
30203 * keyID: module:type/keyid~KeyID,
30204 * signature: Promise<Signature>,
30205 * verified: Promise<true>
30206 * }>>} List of signer's keyID and validity of signature.
30207 * @async
30208 */
30209 verify(keys, date = new Date(), config = defaultConfig) {
30210 const signatureList = this.signature.packets;
30211 const literalDataPacket = new LiteralDataPacket();
30212 // we assume that cleartext signature is generated based on UTF8 cleartext
30213 literalDataPacket.setText(this.text);
30214 return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);
30215 }
30216
30217 /**
30218 * Get cleartext
30219 * @returns {String} Cleartext of message.
30220 */
30221 getText() {
30222 // normalize end of line to \n
30223 return this.text.replace(/\r\n/g, '\n');
30224 }
30225
30226 /**
30227 * Returns ASCII armored text of cleartext signed message
30228 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30229 * @returns {String | ReadableStream<String>} ASCII armor.
30230 */
30231 armor(config = defaultConfig) {
30232 let hashes = this.signature.packets.map(function(packet) {
30233 return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();
30234 });
30235 hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });
30236 const body = {
30237 hash: hashes.join(),
30238 text: this.text,
30239 data: this.signature.packets.write()
30240 };
30241 return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
30242 }
30243}
30244
30245/**
30246 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
30247 * @param {Object} options
30248 * @param {String} options.cleartextMessage - Text to be parsed
30249 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30250 * @returns {Promise<CleartextMessage>} New cleartext message object.
30251 * @async
30252 * @static
30253 */
30254async function readCleartextMessage({ cleartextMessage, config, ...rest }) {
30255 config = { ...defaultConfig, ...config };
30256 if (!cleartextMessage) {
30257 throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
30258 }
30259 if (!util.isString(cleartextMessage)) {
30260 throw new Error('readCleartextMessage: options.cleartextMessage must be a string');
30261 }
30262 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30263
30264 const input = await unarmor(cleartextMessage);
30265 if (input.type !== enums.armor.signed) {
30266 throw new Error('No cleartext signed message.');
30267 }
30268 const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config);
30269 verifyHeaders$1(input.headers, packetlist);
30270 const signature = new Signature(packetlist);
30271 return new CleartextMessage(input.text, signature);
30272}
30273
30274/**
30275 * Compare hash algorithm specified in the armor header with signatures
30276 * @param {Array<String>} headers - Armor headers
30277 * @param {PacketList} packetlist - The packetlist with signature packets
30278 * @private
30279 */
30280function verifyHeaders$1(headers, packetlist) {
30281 const checkHashAlgos = function(hashAlgos) {
30282 const check = packet => algo => packet.hashAlgorithm === algo;
30283
30284 for (let i = 0; i < packetlist.length; i++) {
30285 if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
30286 return false;
30287 }
30288 }
30289 return true;
30290 };
30291
30292 let oneHeader = null;
30293 let hashAlgos = [];
30294 headers.forEach(function(header) {
30295 oneHeader = header.match(/Hash: (.+)/); // get header value
30296 if (oneHeader) {
30297 oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
30298 oneHeader = oneHeader.split(',');
30299 oneHeader = oneHeader.map(function(hash) {
30300 hash = hash.toLowerCase();
30301 try {
30302 return enums.write(enums.hash, hash);
30303 } catch (e) {
30304 throw new Error('Unknown hash algorithm in armor header: ' + hash);
30305 }
30306 });
30307 hashAlgos = hashAlgos.concat(oneHeader);
30308 } else {
30309 throw new Error('Only "Hash" header allowed in cleartext signed message');
30310 }
30311 });
30312
30313 if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
30314 throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
30315 } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
30316 throw new Error('Hash algorithm mismatch in armor header and signature');
30317 }
30318}
30319
30320/**
30321 * Creates a new CleartextMessage object from text
30322 * @param {Object} options
30323 * @param {String} options.text
30324 * @static
30325 * @async
30326 */
30327async function createCleartextMessage({ text, ...rest }) {
30328 if (!text) {
30329 throw new Error('createCleartextMessage: must pass options object containing `text`');
30330 }
30331 if (!util.isString(text)) {
30332 throw new Error('createCleartextMessage: options.text must be a string');
30333 }
30334 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30335
30336 return new CleartextMessage(text);
30337}
30338
30339// OpenPGP.js - An OpenPGP implementation in javascript
30340
30341
30342//////////////////////
30343// //
30344// Key handling //
30345// //
30346//////////////////////
30347
30348
30349/**
30350 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.
30351 * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.
30352 * @param {Object} options
30353 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30354 * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA
30355 * @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.
30356 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
30357 * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:
30358 * curve25519 (default), p256, p384, p521, secp256k1,
30359 * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
30360 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
30361 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30362 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`
30363 * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt
30364 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30365 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30366 * @returns {Promise<Object>} The generated key object in the form:
30367 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30368 * @async
30369 * @static
30370 */
30371async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {
30372 config = { ...defaultConfig, ...config }; checkConfig(config);
30373 userIDs = toArray$1(userIDs);
30374 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30375
30376 if (userIDs.length === 0) {
30377 throw new Error('UserIDs are required for key generation');
30378 }
30379 if (type === 'rsa' && rsaBits < config.minRSABits) {
30380 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);
30381 }
30382
30383 const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };
30384
30385 try {
30386 const { key, revocationCertificate } = await generate$2(options, config);
30387 key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));
30388
30389 return {
30390 privateKey: formatObject(key, format, config),
30391 publicKey: formatObject(key.toPublic(), format, config),
30392 revocationCertificate
30393 };
30394 } catch (err) {
30395 throw util.wrapError('Error generating keypair', err);
30396 }
30397}
30398
30399/**
30400 * Reformats signature packets for a key and rewraps key object.
30401 * @param {Object} options
30402 * @param {PrivateKey} options.privateKey - Private key to reformat
30403 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30404 * @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.
30405 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30406 * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended
30407 * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.
30408 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30409 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30410 * @returns {Promise<Object>} The generated key object in the form:
30411 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30412 * @async
30413 * @static
30414 */
30415async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {
30416 config = { ...defaultConfig, ...config }; checkConfig(config);
30417 userIDs = toArray$1(userIDs);
30418 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30419
30420 if (userIDs.length === 0) {
30421 throw new Error('UserIDs are required for key reformat');
30422 }
30423 const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };
30424
30425 try {
30426 const { key: reformattedKey, revocationCertificate } = await reformat(options, config);
30427
30428 return {
30429 privateKey: formatObject(reformattedKey, format, config),
30430 publicKey: formatObject(reformattedKey.toPublic(), format, config),
30431 revocationCertificate
30432 };
30433 } catch (err) {
30434 throw util.wrapError('Error reformatting keypair', err);
30435 }
30436}
30437
30438/**
30439 * Revokes a key. Requires either a private key or a revocation certificate.
30440 * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
30441 * @param {Object} options
30442 * @param {Key} options.key - Public or private key to revoke
30443 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
30444 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
30445 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
30446 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
30447 * @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
30448 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)
30449 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30450 * @returns {Promise<Object>} The revoked key in the form:
30451 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or
30452 * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise
30453 * @async
30454 * @static
30455 */
30456async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {
30457 config = { ...defaultConfig, ...config }; checkConfig(config);
30458 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30459
30460 try {
30461 const revokedKey = revocationCertificate ?
30462 await key.applyRevocationCertificate(revocationCertificate, date, config) :
30463 await key.revoke(reasonForRevocation, date, config);
30464
30465 return revokedKey.isPrivate() ? {
30466 privateKey: formatObject(revokedKey, format, config),
30467 publicKey: formatObject(revokedKey.toPublic(), format, config)
30468 } : {
30469 privateKey: null,
30470 publicKey: formatObject(revokedKey, format, config)
30471 };
30472 } catch (err) {
30473 throw util.wrapError('Error revoking key', err);
30474 }
30475}
30476
30477/**
30478 * Unlock a private key with the given passphrase.
30479 * This method does not change the original key.
30480 * @param {Object} options
30481 * @param {PrivateKey} options.privateKey - The private key to decrypt
30482 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
30483 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30484 * @returns {Promise<PrivateKey>} The unlocked key object.
30485 * @async
30486 */
30487async function decryptKey({ privateKey, passphrase, config, ...rest }) {
30488 config = { ...defaultConfig, ...config }; checkConfig(config);
30489 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30490
30491 if (!privateKey.isPrivate()) {
30492 throw new Error('Cannot decrypt a public key');
30493 }
30494 const clonedPrivateKey = privateKey.clone(true);
30495 const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];
30496
30497 try {
30498 await Promise.all(clonedPrivateKey.getKeys().map(key => (
30499 // try to decrypt each key with any of the given passphrases
30500 util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))
30501 )));
30502
30503 await clonedPrivateKey.validate(config);
30504 return clonedPrivateKey;
30505 } catch (err) {
30506 clonedPrivateKey.clearPrivateParams();
30507 throw util.wrapError('Error decrypting private key', err);
30508 }
30509}
30510
30511/**
30512 * Lock a private key with the given passphrase.
30513 * This method does not change the original key.
30514 * @param {Object} options
30515 * @param {PrivateKey} options.privateKey - The private key to encrypt
30516 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
30517 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30518 * @returns {Promise<PrivateKey>} The locked key object.
30519 * @async
30520 */
30521async function encryptKey({ privateKey, passphrase, config, ...rest }) {
30522 config = { ...defaultConfig, ...config }; checkConfig(config);
30523 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30524
30525 if (!privateKey.isPrivate()) {
30526 throw new Error('Cannot encrypt a public key');
30527 }
30528 const clonedPrivateKey = privateKey.clone(true);
30529
30530 const keys = clonedPrivateKey.getKeys();
30531 const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);
30532 if (passphrases.length !== keys.length) {
30533 throw new Error('Invalid number of passphrases given for key encryption');
30534 }
30535
30536 try {
30537 await Promise.all(keys.map(async (key, i) => {
30538 const { keyPacket } = key;
30539 await keyPacket.encrypt(passphrases[i], config);
30540 keyPacket.clearPrivateParams();
30541 }));
30542 return clonedPrivateKey;
30543 } catch (err) {
30544 clonedPrivateKey.clearPrivateParams();
30545 throw util.wrapError('Error encrypting private key', err);
30546 }
30547}
30548
30549
30550///////////////////////////////////////////
30551// //
30552// Message encryption and decryption //
30553// //
30554///////////////////////////////////////////
30555
30556
30557/**
30558 * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`
30559 * must be specified. If signing keys are specified, those will be used to sign the message.
30560 * @param {Object} options
30561 * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}
30562 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message
30563 * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed
30564 * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message
30565 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
30566 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30567 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
30568 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30569 * @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]`
30570 * @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]`
30571 * @param {Date} [options.date=current date] - Override the creation date of the message signature
30572 * @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' }]`
30573 * @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' }]`
30574 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30575 * @returns {Promise<MaybeStream<String>|MaybeStream<Uint8Array>>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30576 * @async
30577 * @static
30578 */
30579async function encrypt$4({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], config, ...rest }) {
30580 config = { ...defaultConfig, ...config }; checkConfig(config);
30581 checkMessage(message); checkOutputMessageFormat(format);
30582 encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords);
30583 signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30584 if (rest.detached) {
30585 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.");
30586 }
30587 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');
30588 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');
30589 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');
30590 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30591
30592 if (!signingKeys) {
30593 signingKeys = [];
30594 }
30595 const streaming = message.fromStream;
30596 try {
30597 if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified
30598 message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, config);
30599 }
30600 message = message.compress(
30601 await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),
30602 config
30603 );
30604 message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30605 if (format === 'object') return message;
30606 // serialize data
30607 const armor = format === 'armored';
30608 const data = armor ? message.armor(config) : message.write();
30609 return convertStream(data, streaming, armor ? 'utf8' : 'binary');
30610 } catch (err) {
30611 throw util.wrapError('Error encrypting message', err);
30612 }
30613}
30614
30615/**
30616 * Decrypts a message with the user's private key, a session key or a password.
30617 * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).
30618 * @param {Object} options
30619 * @param {Message} options.message - The message object with the encrypted data
30620 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key
30621 * @param {String|String[]} [options.passwords] - Passwords to decrypt the message
30622 * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
30623 * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures
30624 * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys
30625 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30626 * @param {Signature} [options.signature] - Detached signature for verification
30627 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30628 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30629 * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
30630 *
30631 * {
30632 * data: MaybeStream<String>, (if format was 'utf8', the default)
30633 * data: MaybeStream<Uint8Array>, (if format was 'binary')
30634 * filename: String,
30635 * signatures: [
30636 * {
30637 * keyID: module:type/keyid~KeyID,
30638 * verified: Promise<true>,
30639 * signature: Promise<Signature>
30640 * }, ...
30641 * ]
30642 * }
30643 *
30644 * where `signatures` contains a separate entry for each signature packet found in the input message.
30645 * @async
30646 * @static
30647 */
30648async function decrypt$4({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30649 config = { ...defaultConfig, ...config }; checkConfig(config);
30650 checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys);
30651 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');
30652 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');
30653 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30654
30655 try {
30656 const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);
30657 if (!verificationKeys) {
30658 verificationKeys = [];
30659 }
30660
30661 const result = {};
30662 result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);
30663 result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
30664 result.filename = decrypted.getFilename();
30665 linkStreams(result, message);
30666 if (expectSigned) {
30667 if (verificationKeys.length === 0) {
30668 throw new Error('Verification keys are required to verify message signatures');
30669 }
30670 if (result.signatures.length === 0) {
30671 throw new Error('Message is not signed');
30672 }
30673 result.data = concat([
30674 result.data,
30675 fromAsync(async () => {
30676 await util.anyPromise(result.signatures.map(sig => sig.verified));
30677 })
30678 ]);
30679 }
30680 result.data = await convertStream(result.data, message.fromStream, format);
30681 return result;
30682 } catch (err) {
30683 throw util.wrapError('Error decrypting message', err);
30684 }
30685}
30686
30687
30688//////////////////////////////////////////
30689// //
30690// Message signing and verification //
30691// //
30692//////////////////////////////////////////
30693
30694
30695/**
30696 * Signs a message.
30697 * @param {Object} options
30698 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
30699 * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext
30700 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30701 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
30702 * @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]
30703 * @param {Date} [options.date=current date] - Override the creation date of the signature
30704 * @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' }]`
30705 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30706 * @returns {Promise<MaybeStream<String|Uint8Array>>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30707 * @async
30708 * @static
30709 */
30710async function sign$5({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], config, ...rest }) {
30711 config = { ...defaultConfig, ...config }; checkConfig(config);
30712 checkCleartextOrMessage(message); checkOutputMessageFormat(format);
30713 signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs);
30714
30715 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');
30716 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');
30717 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30718
30719 if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');
30720 if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');
30721
30722 if (!signingKeys || signingKeys.length === 0) {
30723 throw new Error('No signing keys provided');
30724 }
30725
30726 try {
30727 let signature;
30728 if (detached) {
30729 signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30730 } else {
30731 signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30732 }
30733 if (format === 'object') return signature;
30734
30735 const armor = format === 'armored';
30736 signature = armor ? signature.armor(config) : signature.write();
30737 if (detached) {
30738 signature = transformPair(message.packets.write(), async (readable, writable) => {
30739 await Promise.all([
30740 pipe(signature, writable),
30741 readToEnd(readable).catch(() => {})
30742 ]);
30743 });
30744 }
30745 return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');
30746 } catch (err) {
30747 throw util.wrapError('Error signing message', err);
30748 }
30749}
30750
30751/**
30752 * Verifies signatures of cleartext signed message
30753 * @param {Object} options
30754 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
30755 * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures
30756 * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys
30757 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30758 * @param {Signature} [options.signature] - Detached signature for verification
30759 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30760 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30761 * @returns {Promise<Object>} Object containing verified message in the form:
30762 *
30763 * {
30764 * data: MaybeStream<String>, (if `message` was a CleartextMessage)
30765 * data: MaybeStream<Uint8Array>, (if `message` was a Message)
30766 * signatures: [
30767 * {
30768 * keyID: module:type/keyid~KeyID,
30769 * verified: Promise<true>,
30770 * signature: Promise<Signature>
30771 * }, ...
30772 * ]
30773 * }
30774 *
30775 * where `signatures` contains a separate entry for each signature packet found in the input message.
30776 * @async
30777 * @static
30778 */
30779async function verify$5({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30780 config = { ...defaultConfig, ...config }; checkConfig(config);
30781 checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys);
30782 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');
30783 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30784
30785 if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary");
30786 if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature");
30787
30788 try {
30789 const result = {};
30790 if (signature) {
30791 result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);
30792 } else {
30793 result.signatures = await message.verify(verificationKeys, date, config);
30794 }
30795 result.data = format === 'binary' ? message.getLiteralData() : message.getText();
30796 if (message.fromStream) linkStreams(result, message);
30797 if (expectSigned) {
30798 if (result.signatures.length === 0) {
30799 throw new Error('Message is not signed');
30800 }
30801 result.data = concat([
30802 result.data,
30803 fromAsync(async () => {
30804 await util.anyPromise(result.signatures.map(sig => sig.verified));
30805 })
30806 ]);
30807 }
30808 result.data = await convertStream(result.data, message.fromStream, format);
30809 return result;
30810 } catch (err) {
30811 throw util.wrapError('Error verifying signed message', err);
30812 }
30813}
30814
30815
30816///////////////////////////////////////////////
30817// //
30818// Session key encryption and decryption //
30819// //
30820///////////////////////////////////////////////
30821
30822/**
30823 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account.
30824 * @param {Object} options
30825 * @param {PublicKey|PublicKey[]} options.encryptionKeys - Array of public keys or single key used to select algorithm preferences for
30826 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
30827 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for
30828 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30829 * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.
30830 * @async
30831 * @static
30832 */
30833async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30834 config = { ...defaultConfig, ...config }; checkConfig(config);
30835 encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs);
30836 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');
30837 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30838
30839 try {
30840 const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);
30841 return sessionKeys;
30842 } catch (err) {
30843 throw util.wrapError('Error generating session key', err);
30844 }
30845}
30846
30847/**
30848 * Encrypt a symmetric session key with public keys, passwords, or both at once.
30849 * At least one of `encryptionKeys` or `passwords` must be specified.
30850 * @param {Object} options
30851 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
30852 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
30853 * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
30854 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key
30855 * @param {String|String[]} [options.passwords] - Passwords for the message
30856 * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value
30857 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30858 * @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]
30859 * @param {Date} [options.date=current date] - Override the date
30860 * @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' }]`
30861 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30862 * @returns {Promise<String|Uint8Array>} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
30863 * @async
30864 * @static
30865 */
30866async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30867 config = { ...defaultConfig, ...config }; checkConfig(config);
30868 checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);
30869 encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30870 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');
30871 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30872
30873 if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {
30874 throw new Error('No encryption keys or passwords provided.');
30875 }
30876
30877 try {
30878 const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30879 return formatObject(message, format, config);
30880 } catch (err) {
30881 throw util.wrapError('Error encrypting session key', err);
30882 }
30883}
30884
30885/**
30886 * Decrypt symmetric session keys using private keys or passwords (not both).
30887 * One of `decryptionKeys` or `passwords` must be specified.
30888 * @param {Object} options
30889 * @param {Message} options.message - A message object containing the encrypted session key packets
30890 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data
30891 * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key
30892 * @param {Date} [options.date] - Date to use for key verification instead of the current time
30893 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30894 * @returns {Promise<Object[]>} Array of decrypted session key, algorithm pairs in the form:
30895 * { data:Uint8Array, algorithm:String }
30896 * @throws if no session key could be found or decrypted
30897 * @async
30898 * @static
30899 */
30900async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {
30901 config = { ...defaultConfig, ...config }; checkConfig(config);
30902 checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords);
30903 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');
30904 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30905
30906 try {
30907 const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);
30908 return sessionKeys;
30909 } catch (err) {
30910 throw util.wrapError('Error decrypting session keys', err);
30911 }
30912}
30913
30914
30915//////////////////////////
30916// //
30917// Helper functions //
30918// //
30919//////////////////////////
30920
30921
30922/**
30923 * Input validation
30924 * @private
30925 */
30926function checkString(data, name) {
30927 if (!util.isString(data)) {
30928 throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
30929 }
30930}
30931function checkBinary(data, name) {
30932 if (!util.isUint8Array(data)) {
30933 throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
30934 }
30935}
30936function checkMessage(message) {
30937 if (!(message instanceof Message)) {
30938 throw new Error('Parameter [message] needs to be of type Message');
30939 }
30940}
30941function checkCleartextOrMessage(message) {
30942 if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
30943 throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
30944 }
30945}
30946function checkOutputMessageFormat(format) {
30947 if (format !== 'armored' && format !== 'binary' && format !== 'object') {
30948 throw new Error(`Unsupported format ${format}`);
30949 }
30950}
30951const defaultConfigPropsCount = Object.keys(defaultConfig).length;
30952function checkConfig(config) {
30953 const inputConfigProps = Object.keys(config);
30954 if (inputConfigProps.length !== defaultConfigPropsCount) {
30955 for (const inputProp of inputConfigProps) {
30956 if (defaultConfig[inputProp] === undefined) {
30957 throw new Error(`Unknown config property: ${inputProp}`);
30958 }
30959 }
30960 }
30961}
30962
30963/**
30964 * Normalize parameter to an array if it is not undefined.
30965 * @param {Object} param - the parameter to be normalized
30966 * @returns {Array<Object>|undefined} The resulting array or undefined.
30967 * @private
30968 */
30969function toArray$1(param) {
30970 if (param && !util.isArray(param)) {
30971 param = [param];
30972 }
30973 return param;
30974}
30975
30976/**
30977 * Convert data to or from Stream
30978 * @param {Object} data - the data to convert
30979 * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type
30980 * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams
30981 * @returns {Promise<Object>} The data in the respective format.
30982 * @async
30983 * @private
30984 */
30985async function convertStream(data, streaming, encoding = 'utf8') {
30986 const streamType = util.isStream(data);
30987 if (streamType === 'array') {
30988 return readToEnd(data);
30989 }
30990 if (streaming === 'node') {
30991 data = webToNode(data);
30992 if (encoding !== 'binary') data.setEncoding(encoding);
30993 return data;
30994 }
30995 if (streaming === 'web' && streamType === 'ponyfill') {
30996 return toNativeReadable(data);
30997 }
30998 return data;
30999}
31000
31001/**
31002 * Link result.data to the message stream for cancellation.
31003 * Also, forward errors in the message to result.data.
31004 * @param {Object} result - the data to convert
31005 * @param {Message} message - message object
31006 * @returns {Object}
31007 * @private
31008 */
31009function linkStreams(result, message) {
31010 result.data = transformPair(message.packets.stream, async (readable, writable) => {
31011 await pipe(result.data, writable, {
31012 preventClose: true
31013 });
31014 const writer = getWriter(writable);
31015 try {
31016 // Forward errors in the message stream to result.data.
31017 await readToEnd(readable, _ => _);
31018 await writer.close();
31019 } catch (e) {
31020 await writer.abort(e);
31021 }
31022 });
31023}
31024
31025/**
31026 * Convert the object to the given format
31027 * @param {Key|Message} object
31028 * @param {'armored'|'binary'|'object'} format
31029 * @param {Object} config - Full configuration
31030 * @returns {String|Uint8Array|Object}
31031 */
31032function formatObject(object, format, config) {
31033 switch (format) {
31034 case 'object':
31035 return object;
31036 case 'armored':
31037 return object.armor(config);
31038 case 'binary':
31039 return object.write();
31040 default:
31041 throw new Error(`Unsupported format ${format}`);
31042 }
31043}
31044
31045/**
31046 * web-streams-polyfill v3.0.3
31047 */
31048/// <reference lib="es2015.symbol" />
31049const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
31050 Symbol :
31051 description => `Symbol(${description})`;
31052
31053/// <reference lib="dom" />
31054function noop() {
31055 return undefined;
31056}
31057function getGlobals() {
31058 if (typeof self !== 'undefined') {
31059 return self;
31060 }
31061 else if (typeof window !== 'undefined') {
31062 return window;
31063 }
31064 else if (typeof global !== 'undefined') {
31065 return global;
31066 }
31067 return undefined;
31068}
31069const globals = getGlobals();
31070
31071function typeIsObject(x) {
31072 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31073}
31074const rethrowAssertionErrorRejection = noop;
31075
31076const originalPromise = Promise;
31077const originalPromiseThen = Promise.prototype.then;
31078const originalPromiseResolve = Promise.resolve.bind(originalPromise);
31079const originalPromiseReject = Promise.reject.bind(originalPromise);
31080function newPromise(executor) {
31081 return new originalPromise(executor);
31082}
31083function promiseResolvedWith(value) {
31084 return originalPromiseResolve(value);
31085}
31086function promiseRejectedWith(reason) {
31087 return originalPromiseReject(reason);
31088}
31089function PerformPromiseThen(promise, onFulfilled, onRejected) {
31090 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
31091 // approximation.
31092 return originalPromiseThen.call(promise, onFulfilled, onRejected);
31093}
31094function uponPromise(promise, onFulfilled, onRejected) {
31095 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
31096}
31097function uponFulfillment(promise, onFulfilled) {
31098 uponPromise(promise, onFulfilled);
31099}
31100function uponRejection(promise, onRejected) {
31101 uponPromise(promise, undefined, onRejected);
31102}
31103function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
31104 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
31105}
31106function setPromiseIsHandledToTrue(promise) {
31107 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
31108}
31109const queueMicrotask = (() => {
31110 const globalQueueMicrotask = globals && globals.queueMicrotask;
31111 if (typeof globalQueueMicrotask === 'function') {
31112 return globalQueueMicrotask;
31113 }
31114 const resolvedPromise = promiseResolvedWith(undefined);
31115 return (fn) => PerformPromiseThen(resolvedPromise, fn);
31116})();
31117function reflectCall(F, V, args) {
31118 if (typeof F !== 'function') {
31119 throw new TypeError('Argument is not a function');
31120 }
31121 return Function.prototype.apply.call(F, V, args);
31122}
31123function promiseCall(F, V, args) {
31124 try {
31125 return promiseResolvedWith(reflectCall(F, V, args));
31126 }
31127 catch (value) {
31128 return promiseRejectedWith(value);
31129 }
31130}
31131
31132// Original from Chromium
31133// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
31134const QUEUE_MAX_ARRAY_SIZE = 16384;
31135/**
31136 * Simple queue structure.
31137 *
31138 * Avoids scalability issues with using a packed array directly by using
31139 * multiple arrays in a linked list and keeping the array size bounded.
31140 */
31141class SimpleQueue {
31142 constructor() {
31143 this._cursor = 0;
31144 this._size = 0;
31145 // _front and _back are always defined.
31146 this._front = {
31147 _elements: [],
31148 _next: undefined
31149 };
31150 this._back = this._front;
31151 // The cursor is used to avoid calling Array.shift().
31152 // It contains the index of the front element of the array inside the
31153 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
31154 this._cursor = 0;
31155 // When there is only one node, size === elements.length - cursor.
31156 this._size = 0;
31157 }
31158 get length() {
31159 return this._size;
31160 }
31161 // For exception safety, this method is structured in order:
31162 // 1. Read state
31163 // 2. Calculate required state mutations
31164 // 3. Perform state mutations
31165 push(element) {
31166 const oldBack = this._back;
31167 let newBack = oldBack;
31168 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
31169 newBack = {
31170 _elements: [],
31171 _next: undefined
31172 };
31173 }
31174 // push() is the mutation most likely to throw an exception, so it
31175 // goes first.
31176 oldBack._elements.push(element);
31177 if (newBack !== oldBack) {
31178 this._back = newBack;
31179 oldBack._next = newBack;
31180 }
31181 ++this._size;
31182 }
31183 // Like push(), shift() follows the read -> calculate -> mutate pattern for
31184 // exception safety.
31185 shift() { // must not be called on an empty queue
31186 const oldFront = this._front;
31187 let newFront = oldFront;
31188 const oldCursor = this._cursor;
31189 let newCursor = oldCursor + 1;
31190 const elements = oldFront._elements;
31191 const element = elements[oldCursor];
31192 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
31193 newFront = oldFront._next;
31194 newCursor = 0;
31195 }
31196 // No mutations before this point.
31197 --this._size;
31198 this._cursor = newCursor;
31199 if (oldFront !== newFront) {
31200 this._front = newFront;
31201 }
31202 // Permit shifted element to be garbage collected.
31203 elements[oldCursor] = undefined;
31204 return element;
31205 }
31206 // The tricky thing about forEach() is that it can be called
31207 // re-entrantly. The queue may be mutated inside the callback. It is easy to
31208 // see that push() within the callback has no negative effects since the end
31209 // of the queue is checked for on every iteration. If shift() is called
31210 // repeatedly within the callback then the next iteration may return an
31211 // element that has been removed. In this case the callback will be called
31212 // with undefined values until we either "catch up" with elements that still
31213 // exist or reach the back of the queue.
31214 forEach(callback) {
31215 let i = this._cursor;
31216 let node = this._front;
31217 let elements = node._elements;
31218 while (i !== elements.length || node._next !== undefined) {
31219 if (i === elements.length) {
31220 node = node._next;
31221 elements = node._elements;
31222 i = 0;
31223 if (elements.length === 0) {
31224 break;
31225 }
31226 }
31227 callback(elements[i]);
31228 ++i;
31229 }
31230 }
31231 // Return the element that would be returned if shift() was called now,
31232 // without modifying the queue.
31233 peek() { // must not be called on an empty queue
31234 const front = this._front;
31235 const cursor = this._cursor;
31236 return front._elements[cursor];
31237 }
31238}
31239
31240function ReadableStreamReaderGenericInitialize(reader, stream) {
31241 reader._ownerReadableStream = stream;
31242 stream._reader = reader;
31243 if (stream._state === 'readable') {
31244 defaultReaderClosedPromiseInitialize(reader);
31245 }
31246 else if (stream._state === 'closed') {
31247 defaultReaderClosedPromiseInitializeAsResolved(reader);
31248 }
31249 else {
31250 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
31251 }
31252}
31253// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
31254// check.
31255function ReadableStreamReaderGenericCancel(reader, reason) {
31256 const stream = reader._ownerReadableStream;
31257 return ReadableStreamCancel(stream, reason);
31258}
31259function ReadableStreamReaderGenericRelease(reader) {
31260 if (reader._ownerReadableStream._state === 'readable') {
31261 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31262 }
31263 else {
31264 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31265 }
31266 reader._ownerReadableStream._reader = undefined;
31267 reader._ownerReadableStream = undefined;
31268}
31269// Helper functions for the readers.
31270function readerLockException(name) {
31271 return new TypeError('Cannot ' + name + ' a stream using a released reader');
31272}
31273// Helper functions for the ReadableStreamDefaultReader.
31274function defaultReaderClosedPromiseInitialize(reader) {
31275 reader._closedPromise = newPromise((resolve, reject) => {
31276 reader._closedPromise_resolve = resolve;
31277 reader._closedPromise_reject = reject;
31278 });
31279}
31280function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
31281 defaultReaderClosedPromiseInitialize(reader);
31282 defaultReaderClosedPromiseReject(reader, reason);
31283}
31284function defaultReaderClosedPromiseInitializeAsResolved(reader) {
31285 defaultReaderClosedPromiseInitialize(reader);
31286 defaultReaderClosedPromiseResolve(reader);
31287}
31288function defaultReaderClosedPromiseReject(reader, reason) {
31289 if (reader._closedPromise_reject === undefined) {
31290 return;
31291 }
31292 setPromiseIsHandledToTrue(reader._closedPromise);
31293 reader._closedPromise_reject(reason);
31294 reader._closedPromise_resolve = undefined;
31295 reader._closedPromise_reject = undefined;
31296}
31297function defaultReaderClosedPromiseResetToRejected(reader, reason) {
31298 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
31299}
31300function defaultReaderClosedPromiseResolve(reader) {
31301 if (reader._closedPromise_resolve === undefined) {
31302 return;
31303 }
31304 reader._closedPromise_resolve(undefined);
31305 reader._closedPromise_resolve = undefined;
31306 reader._closedPromise_reject = undefined;
31307}
31308
31309const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
31310const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
31311const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
31312const PullSteps = SymbolPolyfill('[[PullSteps]]');
31313
31314/// <reference lib="es2015.core" />
31315// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
31316const NumberIsFinite = Number.isFinite || function (x) {
31317 return typeof x === 'number' && isFinite(x);
31318};
31319
31320/// <reference lib="es2015.core" />
31321// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
31322const MathTrunc = Math.trunc || function (v) {
31323 return v < 0 ? Math.ceil(v) : Math.floor(v);
31324};
31325
31326// https://heycam.github.io/webidl/#idl-dictionaries
31327function isDictionary(x) {
31328 return typeof x === 'object' || typeof x === 'function';
31329}
31330function assertDictionary(obj, context) {
31331 if (obj !== undefined && !isDictionary(obj)) {
31332 throw new TypeError(`${context} is not an object.`);
31333 }
31334}
31335// https://heycam.github.io/webidl/#idl-callback-functions
31336function assertFunction(x, context) {
31337 if (typeof x !== 'function') {
31338 throw new TypeError(`${context} is not a function.`);
31339 }
31340}
31341// https://heycam.github.io/webidl/#idl-object
31342function isObject(x) {
31343 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31344}
31345function assertObject(x, context) {
31346 if (!isObject(x)) {
31347 throw new TypeError(`${context} is not an object.`);
31348 }
31349}
31350function assertRequiredArgument(x, position, context) {
31351 if (x === undefined) {
31352 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
31353 }
31354}
31355function assertRequiredField(x, field, context) {
31356 if (x === undefined) {
31357 throw new TypeError(`${field} is required in '${context}'.`);
31358 }
31359}
31360// https://heycam.github.io/webidl/#idl-unrestricted-double
31361function convertUnrestrictedDouble(value) {
31362 return Number(value);
31363}
31364function censorNegativeZero(x) {
31365 return x === 0 ? 0 : x;
31366}
31367function integerPart(x) {
31368 return censorNegativeZero(MathTrunc(x));
31369}
31370// https://heycam.github.io/webidl/#idl-unsigned-long-long
31371function convertUnsignedLongLongWithEnforceRange(value, context) {
31372 const lowerBound = 0;
31373 const upperBound = Number.MAX_SAFE_INTEGER;
31374 let x = Number(value);
31375 x = censorNegativeZero(x);
31376 if (!NumberIsFinite(x)) {
31377 throw new TypeError(`${context} is not a finite number`);
31378 }
31379 x = integerPart(x);
31380 if (x < lowerBound || x > upperBound) {
31381 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
31382 }
31383 if (!NumberIsFinite(x) || x === 0) {
31384 return 0;
31385 }
31386 // TODO Use BigInt if supported?
31387 // let xBigInt = BigInt(integerPart(x));
31388 // xBigInt = BigInt.asUintN(64, xBigInt);
31389 // return Number(xBigInt);
31390 return x;
31391}
31392
31393function assertReadableStream(x, context) {
31394 if (!IsReadableStream(x)) {
31395 throw new TypeError(`${context} is not a ReadableStream.`);
31396 }
31397}
31398
31399// Abstract operations for the ReadableStream.
31400function AcquireReadableStreamDefaultReader(stream) {
31401 return new ReadableStreamDefaultReader(stream);
31402}
31403// ReadableStream API exposed for controllers.
31404function ReadableStreamAddReadRequest(stream, readRequest) {
31405 stream._reader._readRequests.push(readRequest);
31406}
31407function ReadableStreamFulfillReadRequest(stream, chunk, done) {
31408 const reader = stream._reader;
31409 const readRequest = reader._readRequests.shift();
31410 if (done) {
31411 readRequest._closeSteps();
31412 }
31413 else {
31414 readRequest._chunkSteps(chunk);
31415 }
31416}
31417function ReadableStreamGetNumReadRequests(stream) {
31418 return stream._reader._readRequests.length;
31419}
31420function ReadableStreamHasDefaultReader(stream) {
31421 const reader = stream._reader;
31422 if (reader === undefined) {
31423 return false;
31424 }
31425 if (!IsReadableStreamDefaultReader(reader)) {
31426 return false;
31427 }
31428 return true;
31429}
31430/**
31431 * A default reader vended by a {@link ReadableStream}.
31432 *
31433 * @public
31434 */
31435class ReadableStreamDefaultReader {
31436 constructor(stream) {
31437 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
31438 assertReadableStream(stream, 'First parameter');
31439 if (IsReadableStreamLocked(stream)) {
31440 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
31441 }
31442 ReadableStreamReaderGenericInitialize(this, stream);
31443 this._readRequests = new SimpleQueue();
31444 }
31445 /**
31446 * Returns a promise that will be fulfilled when the stream becomes closed,
31447 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
31448 */
31449 get closed() {
31450 if (!IsReadableStreamDefaultReader(this)) {
31451 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
31452 }
31453 return this._closedPromise;
31454 }
31455 /**
31456 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
31457 */
31458 cancel(reason = undefined) {
31459 if (!IsReadableStreamDefaultReader(this)) {
31460 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
31461 }
31462 if (this._ownerReadableStream === undefined) {
31463 return promiseRejectedWith(readerLockException('cancel'));
31464 }
31465 return ReadableStreamReaderGenericCancel(this, reason);
31466 }
31467 /**
31468 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
31469 *
31470 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
31471 */
31472 read() {
31473 if (!IsReadableStreamDefaultReader(this)) {
31474 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
31475 }
31476 if (this._ownerReadableStream === undefined) {
31477 return promiseRejectedWith(readerLockException('read from'));
31478 }
31479 let resolvePromise;
31480 let rejectPromise;
31481 const promise = newPromise((resolve, reject) => {
31482 resolvePromise = resolve;
31483 rejectPromise = reject;
31484 });
31485 const readRequest = {
31486 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
31487 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
31488 _errorSteps: e => rejectPromise(e)
31489 };
31490 ReadableStreamDefaultReaderRead(this, readRequest);
31491 return promise;
31492 }
31493 /**
31494 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
31495 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
31496 * from now on; otherwise, the reader will appear closed.
31497 *
31498 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
31499 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
31500 * do so will throw a `TypeError` and leave the reader locked to the stream.
31501 */
31502 releaseLock() {
31503 if (!IsReadableStreamDefaultReader(this)) {
31504 throw defaultReaderBrandCheckException('releaseLock');
31505 }
31506 if (this._ownerReadableStream === undefined) {
31507 return;
31508 }
31509 if (this._readRequests.length > 0) {
31510 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
31511 }
31512 ReadableStreamReaderGenericRelease(this);
31513 }
31514}
31515Object.defineProperties(ReadableStreamDefaultReader.prototype, {
31516 cancel: { enumerable: true },
31517 read: { enumerable: true },
31518 releaseLock: { enumerable: true },
31519 closed: { enumerable: true }
31520});
31521if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31522 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
31523 value: 'ReadableStreamDefaultReader',
31524 configurable: true
31525 });
31526}
31527// Abstract operations for the readers.
31528function IsReadableStreamDefaultReader(x) {
31529 if (!typeIsObject(x)) {
31530 return false;
31531 }
31532 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
31533 return false;
31534 }
31535 return true;
31536}
31537function ReadableStreamDefaultReaderRead(reader, readRequest) {
31538 const stream = reader._ownerReadableStream;
31539 stream._disturbed = true;
31540 if (stream._state === 'closed') {
31541 readRequest._closeSteps();
31542 }
31543 else if (stream._state === 'errored') {
31544 readRequest._errorSteps(stream._storedError);
31545 }
31546 else {
31547 stream._readableStreamController[PullSteps](readRequest);
31548 }
31549}
31550// Helper functions for the ReadableStreamDefaultReader.
31551function defaultReaderBrandCheckException(name) {
31552 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
31553}
31554
31555/// <reference lib="es2018.asynciterable" />
31556let AsyncIteratorPrototype;
31557if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
31558 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
31559 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
31560 AsyncIteratorPrototype = {
31561 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
31562 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
31563 [SymbolPolyfill.asyncIterator]() {
31564 return this;
31565 }
31566 };
31567 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
31568}
31569
31570/// <reference lib="es2018.asynciterable" />
31571class ReadableStreamAsyncIteratorImpl {
31572 constructor(reader, preventCancel) {
31573 this._ongoingPromise = undefined;
31574 this._isFinished = false;
31575 this._reader = reader;
31576 this._preventCancel = preventCancel;
31577 }
31578 next() {
31579 const nextSteps = () => this._nextSteps();
31580 this._ongoingPromise = this._ongoingPromise ?
31581 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
31582 nextSteps();
31583 return this._ongoingPromise;
31584 }
31585 return(value) {
31586 const returnSteps = () => this._returnSteps(value);
31587 return this._ongoingPromise ?
31588 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
31589 returnSteps();
31590 }
31591 _nextSteps() {
31592 if (this._isFinished) {
31593 return Promise.resolve({ value: undefined, done: true });
31594 }
31595 const reader = this._reader;
31596 if (reader._ownerReadableStream === undefined) {
31597 return promiseRejectedWith(readerLockException('iterate'));
31598 }
31599 let resolvePromise;
31600 let rejectPromise;
31601 const promise = newPromise((resolve, reject) => {
31602 resolvePromise = resolve;
31603 rejectPromise = reject;
31604 });
31605 const readRequest = {
31606 _chunkSteps: chunk => {
31607 this._ongoingPromise = undefined;
31608 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
31609 // FIXME Is this a bug in the specification, or in the test?
31610 queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
31611 },
31612 _closeSteps: () => {
31613 this._ongoingPromise = undefined;
31614 this._isFinished = true;
31615 ReadableStreamReaderGenericRelease(reader);
31616 resolvePromise({ value: undefined, done: true });
31617 },
31618 _errorSteps: reason => {
31619 this._ongoingPromise = undefined;
31620 this._isFinished = true;
31621 ReadableStreamReaderGenericRelease(reader);
31622 rejectPromise(reason);
31623 }
31624 };
31625 ReadableStreamDefaultReaderRead(reader, readRequest);
31626 return promise;
31627 }
31628 _returnSteps(value) {
31629 if (this._isFinished) {
31630 return Promise.resolve({ value, done: true });
31631 }
31632 this._isFinished = true;
31633 const reader = this._reader;
31634 if (reader._ownerReadableStream === undefined) {
31635 return promiseRejectedWith(readerLockException('finish iterating'));
31636 }
31637 if (!this._preventCancel) {
31638 const result = ReadableStreamReaderGenericCancel(reader, value);
31639 ReadableStreamReaderGenericRelease(reader);
31640 return transformPromiseWith(result, () => ({ value, done: true }));
31641 }
31642 ReadableStreamReaderGenericRelease(reader);
31643 return promiseResolvedWith({ value, done: true });
31644 }
31645}
31646const ReadableStreamAsyncIteratorPrototype = {
31647 next() {
31648 if (!IsReadableStreamAsyncIterator(this)) {
31649 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
31650 }
31651 return this._asyncIteratorImpl.next();
31652 },
31653 return(value) {
31654 if (!IsReadableStreamAsyncIterator(this)) {
31655 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
31656 }
31657 return this._asyncIteratorImpl.return(value);
31658 }
31659};
31660if (AsyncIteratorPrototype !== undefined) {
31661 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
31662}
31663// Abstract operations for the ReadableStream.
31664function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
31665 const reader = AcquireReadableStreamDefaultReader(stream);
31666 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
31667 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
31668 iterator._asyncIteratorImpl = impl;
31669 return iterator;
31670}
31671function IsReadableStreamAsyncIterator(x) {
31672 if (!typeIsObject(x)) {
31673 return false;
31674 }
31675 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
31676 return false;
31677 }
31678 return true;
31679}
31680// Helper functions for the ReadableStream.
31681function streamAsyncIteratorBrandCheckException(name) {
31682 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
31683}
31684
31685/// <reference lib="es2015.core" />
31686// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
31687const NumberIsNaN = Number.isNaN || function (x) {
31688 // eslint-disable-next-line no-self-compare
31689 return x !== x;
31690};
31691
31692function IsFiniteNonNegativeNumber(v) {
31693 if (!IsNonNegativeNumber(v)) {
31694 return false;
31695 }
31696 if (v === Infinity) {
31697 return false;
31698 }
31699 return true;
31700}
31701function IsNonNegativeNumber(v) {
31702 if (typeof v !== 'number') {
31703 return false;
31704 }
31705 if (NumberIsNaN(v)) {
31706 return false;
31707 }
31708 if (v < 0) {
31709 return false;
31710 }
31711 return true;
31712}
31713
31714function DequeueValue(container) {
31715 const pair = container._queue.shift();
31716 container._queueTotalSize -= pair.size;
31717 if (container._queueTotalSize < 0) {
31718 container._queueTotalSize = 0;
31719 }
31720 return pair.value;
31721}
31722function EnqueueValueWithSize(container, value, size) {
31723 size = Number(size);
31724 if (!IsFiniteNonNegativeNumber(size)) {
31725 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
31726 }
31727 container._queue.push({ value, size });
31728 container._queueTotalSize += size;
31729}
31730function PeekQueueValue(container) {
31731 const pair = container._queue.peek();
31732 return pair.value;
31733}
31734function ResetQueue(container) {
31735 container._queue = new SimpleQueue();
31736 container._queueTotalSize = 0;
31737}
31738
31739function CreateArrayFromList(elements) {
31740 // We use arrays to represent lists, so this is basically a no-op.
31741 // Do a slice though just in case we happen to depend on the unique-ness.
31742 return elements.slice();
31743}
31744function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
31745 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
31746}
31747// Not implemented correctly
31748function TransferArrayBuffer(O) {
31749 return O;
31750}
31751// Not implemented correctly
31752function IsDetachedBuffer(O) {
31753 return false;
31754}
31755
31756/**
31757 * A pull-into request in a {@link ReadableByteStreamController}.
31758 *
31759 * @public
31760 */
31761class ReadableStreamBYOBRequest {
31762 constructor() {
31763 throw new TypeError('Illegal constructor');
31764 }
31765 /**
31766 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
31767 */
31768 get view() {
31769 if (!IsReadableStreamBYOBRequest(this)) {
31770 throw byobRequestBrandCheckException('view');
31771 }
31772 return this._view;
31773 }
31774 respond(bytesWritten) {
31775 if (!IsReadableStreamBYOBRequest(this)) {
31776 throw byobRequestBrandCheckException('respond');
31777 }
31778 assertRequiredArgument(bytesWritten, 1, 'respond');
31779 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
31780 if (this._associatedReadableByteStreamController === undefined) {
31781 throw new TypeError('This BYOB request has been invalidated');
31782 }
31783 if (IsDetachedBuffer(this._view.buffer)) ;
31784 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
31785 }
31786 respondWithNewView(view) {
31787 if (!IsReadableStreamBYOBRequest(this)) {
31788 throw byobRequestBrandCheckException('respondWithNewView');
31789 }
31790 assertRequiredArgument(view, 1, 'respondWithNewView');
31791 if (!ArrayBuffer.isView(view)) {
31792 throw new TypeError('You can only respond with array buffer views');
31793 }
31794 if (view.byteLength === 0) {
31795 throw new TypeError('chunk must have non-zero byteLength');
31796 }
31797 if (view.buffer.byteLength === 0) {
31798 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31799 }
31800 if (this._associatedReadableByteStreamController === undefined) {
31801 throw new TypeError('This BYOB request has been invalidated');
31802 }
31803 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
31804 }
31805}
31806Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
31807 respond: { enumerable: true },
31808 respondWithNewView: { enumerable: true },
31809 view: { enumerable: true }
31810});
31811if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31812 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
31813 value: 'ReadableStreamBYOBRequest',
31814 configurable: true
31815 });
31816}
31817/**
31818 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
31819 *
31820 * @public
31821 */
31822class ReadableByteStreamController {
31823 constructor() {
31824 throw new TypeError('Illegal constructor');
31825 }
31826 /**
31827 * Returns the current BYOB pull request, or `null` if there isn't one.
31828 */
31829 get byobRequest() {
31830 if (!IsReadableByteStreamController(this)) {
31831 throw byteStreamControllerBrandCheckException('byobRequest');
31832 }
31833 if (this._byobRequest === null && this._pendingPullIntos.length > 0) {
31834 const firstDescriptor = this._pendingPullIntos.peek();
31835 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
31836 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
31837 SetUpReadableStreamBYOBRequest(byobRequest, this, view);
31838 this._byobRequest = byobRequest;
31839 }
31840 return this._byobRequest;
31841 }
31842 /**
31843 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
31844 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
31845 */
31846 get desiredSize() {
31847 if (!IsReadableByteStreamController(this)) {
31848 throw byteStreamControllerBrandCheckException('desiredSize');
31849 }
31850 return ReadableByteStreamControllerGetDesiredSize(this);
31851 }
31852 /**
31853 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
31854 * the stream, but once those are read, the stream will become closed.
31855 */
31856 close() {
31857 if (!IsReadableByteStreamController(this)) {
31858 throw byteStreamControllerBrandCheckException('close');
31859 }
31860 if (this._closeRequested) {
31861 throw new TypeError('The stream has already been closed; do not close it again!');
31862 }
31863 const state = this._controlledReadableByteStream._state;
31864 if (state !== 'readable') {
31865 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
31866 }
31867 ReadableByteStreamControllerClose(this);
31868 }
31869 enqueue(chunk) {
31870 if (!IsReadableByteStreamController(this)) {
31871 throw byteStreamControllerBrandCheckException('enqueue');
31872 }
31873 assertRequiredArgument(chunk, 1, 'enqueue');
31874 if (!ArrayBuffer.isView(chunk)) {
31875 throw new TypeError('chunk must be an array buffer view');
31876 }
31877 if (chunk.byteLength === 0) {
31878 throw new TypeError('chunk must have non-zero byteLength');
31879 }
31880 if (chunk.buffer.byteLength === 0) {
31881 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31882 }
31883 if (this._closeRequested) {
31884 throw new TypeError('stream is closed or draining');
31885 }
31886 const state = this._controlledReadableByteStream._state;
31887 if (state !== 'readable') {
31888 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
31889 }
31890 ReadableByteStreamControllerEnqueue(this, chunk);
31891 }
31892 /**
31893 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
31894 */
31895 error(e = undefined) {
31896 if (!IsReadableByteStreamController(this)) {
31897 throw byteStreamControllerBrandCheckException('error');
31898 }
31899 ReadableByteStreamControllerError(this, e);
31900 }
31901 /** @internal */
31902 [CancelSteps](reason) {
31903 if (this._pendingPullIntos.length > 0) {
31904 const firstDescriptor = this._pendingPullIntos.peek();
31905 firstDescriptor.bytesFilled = 0;
31906 }
31907 ResetQueue(this);
31908 const result = this._cancelAlgorithm(reason);
31909 ReadableByteStreamControllerClearAlgorithms(this);
31910 return result;
31911 }
31912 /** @internal */
31913 [PullSteps](readRequest) {
31914 const stream = this._controlledReadableByteStream;
31915 if (this._queueTotalSize > 0) {
31916 const entry = this._queue.shift();
31917 this._queueTotalSize -= entry.byteLength;
31918 ReadableByteStreamControllerHandleQueueDrain(this);
31919 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
31920 readRequest._chunkSteps(view);
31921 return;
31922 }
31923 const autoAllocateChunkSize = this._autoAllocateChunkSize;
31924 if (autoAllocateChunkSize !== undefined) {
31925 let buffer;
31926 try {
31927 buffer = new ArrayBuffer(autoAllocateChunkSize);
31928 }
31929 catch (bufferE) {
31930 readRequest._errorSteps(bufferE);
31931 return;
31932 }
31933 const pullIntoDescriptor = {
31934 buffer,
31935 byteOffset: 0,
31936 byteLength: autoAllocateChunkSize,
31937 bytesFilled: 0,
31938 elementSize: 1,
31939 viewConstructor: Uint8Array,
31940 readerType: 'default'
31941 };
31942 this._pendingPullIntos.push(pullIntoDescriptor);
31943 }
31944 ReadableStreamAddReadRequest(stream, readRequest);
31945 ReadableByteStreamControllerCallPullIfNeeded(this);
31946 }
31947}
31948Object.defineProperties(ReadableByteStreamController.prototype, {
31949 close: { enumerable: true },
31950 enqueue: { enumerable: true },
31951 error: { enumerable: true },
31952 byobRequest: { enumerable: true },
31953 desiredSize: { enumerable: true }
31954});
31955if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31956 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
31957 value: 'ReadableByteStreamController',
31958 configurable: true
31959 });
31960}
31961// Abstract operations for the ReadableByteStreamController.
31962function IsReadableByteStreamController(x) {
31963 if (!typeIsObject(x)) {
31964 return false;
31965 }
31966 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
31967 return false;
31968 }
31969 return true;
31970}
31971function IsReadableStreamBYOBRequest(x) {
31972 if (!typeIsObject(x)) {
31973 return false;
31974 }
31975 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
31976 return false;
31977 }
31978 return true;
31979}
31980function ReadableByteStreamControllerCallPullIfNeeded(controller) {
31981 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
31982 if (!shouldPull) {
31983 return;
31984 }
31985 if (controller._pulling) {
31986 controller._pullAgain = true;
31987 return;
31988 }
31989 controller._pulling = true;
31990 // TODO: Test controller argument
31991 const pullPromise = controller._pullAlgorithm();
31992 uponPromise(pullPromise, () => {
31993 controller._pulling = false;
31994 if (controller._pullAgain) {
31995 controller._pullAgain = false;
31996 ReadableByteStreamControllerCallPullIfNeeded(controller);
31997 }
31998 }, e => {
31999 ReadableByteStreamControllerError(controller, e);
32000 });
32001}
32002function ReadableByteStreamControllerClearPendingPullIntos(controller) {
32003 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32004 controller._pendingPullIntos = new SimpleQueue();
32005}
32006function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
32007 let done = false;
32008 if (stream._state === 'closed') {
32009 done = true;
32010 }
32011 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
32012 if (pullIntoDescriptor.readerType === 'default') {
32013 ReadableStreamFulfillReadRequest(stream, filledView, done);
32014 }
32015 else {
32016 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
32017 }
32018}
32019function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
32020 const bytesFilled = pullIntoDescriptor.bytesFilled;
32021 const elementSize = pullIntoDescriptor.elementSize;
32022 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
32023}
32024function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
32025 controller._queue.push({ buffer, byteOffset, byteLength });
32026 controller._queueTotalSize += byteLength;
32027}
32028function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
32029 const elementSize = pullIntoDescriptor.elementSize;
32030 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
32031 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
32032 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
32033 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
32034 let totalBytesToCopyRemaining = maxBytesToCopy;
32035 let ready = false;
32036 if (maxAlignedBytes > currentAlignedBytes) {
32037 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
32038 ready = true;
32039 }
32040 const queue = controller._queue;
32041 while (totalBytesToCopyRemaining > 0) {
32042 const headOfQueue = queue.peek();
32043 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
32044 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32045 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
32046 if (headOfQueue.byteLength === bytesToCopy) {
32047 queue.shift();
32048 }
32049 else {
32050 headOfQueue.byteOffset += bytesToCopy;
32051 headOfQueue.byteLength -= bytesToCopy;
32052 }
32053 controller._queueTotalSize -= bytesToCopy;
32054 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
32055 totalBytesToCopyRemaining -= bytesToCopy;
32056 }
32057 return ready;
32058}
32059function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
32060 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32061 pullIntoDescriptor.bytesFilled += size;
32062}
32063function ReadableByteStreamControllerHandleQueueDrain(controller) {
32064 if (controller._queueTotalSize === 0 && controller._closeRequested) {
32065 ReadableByteStreamControllerClearAlgorithms(controller);
32066 ReadableStreamClose(controller._controlledReadableByteStream);
32067 }
32068 else {
32069 ReadableByteStreamControllerCallPullIfNeeded(controller);
32070 }
32071}
32072function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
32073 if (controller._byobRequest === null) {
32074 return;
32075 }
32076 controller._byobRequest._associatedReadableByteStreamController = undefined;
32077 controller._byobRequest._view = null;
32078 controller._byobRequest = null;
32079}
32080function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
32081 while (controller._pendingPullIntos.length > 0) {
32082 if (controller._queueTotalSize === 0) {
32083 return;
32084 }
32085 const pullIntoDescriptor = controller._pendingPullIntos.peek();
32086 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32087 ReadableByteStreamControllerShiftPendingPullInto(controller);
32088 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32089 }
32090 }
32091}
32092function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
32093 const stream = controller._controlledReadableByteStream;
32094 let elementSize = 1;
32095 if (view.constructor !== DataView) {
32096 elementSize = view.constructor.BYTES_PER_ELEMENT;
32097 }
32098 const ctor = view.constructor;
32099 const buffer = TransferArrayBuffer(view.buffer);
32100 const pullIntoDescriptor = {
32101 buffer,
32102 byteOffset: view.byteOffset,
32103 byteLength: view.byteLength,
32104 bytesFilled: 0,
32105 elementSize,
32106 viewConstructor: ctor,
32107 readerType: 'byob'
32108 };
32109 if (controller._pendingPullIntos.length > 0) {
32110 controller._pendingPullIntos.push(pullIntoDescriptor);
32111 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
32112 // - No change happens on desiredSize
32113 // - The source has already been notified of that there's at least 1 pending read(view)
32114 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32115 return;
32116 }
32117 if (stream._state === 'closed') {
32118 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
32119 readIntoRequest._closeSteps(emptyView);
32120 return;
32121 }
32122 if (controller._queueTotalSize > 0) {
32123 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32124 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
32125 ReadableByteStreamControllerHandleQueueDrain(controller);
32126 readIntoRequest._chunkSteps(filledView);
32127 return;
32128 }
32129 if (controller._closeRequested) {
32130 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32131 ReadableByteStreamControllerError(controller, e);
32132 readIntoRequest._errorSteps(e);
32133 return;
32134 }
32135 }
32136 controller._pendingPullIntos.push(pullIntoDescriptor);
32137 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32138 ReadableByteStreamControllerCallPullIfNeeded(controller);
32139}
32140function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
32141 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
32142 const stream = controller._controlledReadableByteStream;
32143 if (ReadableStreamHasBYOBReader(stream)) {
32144 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32145 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
32146 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
32147 }
32148 }
32149}
32150function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
32151 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
32152 throw new RangeError('bytesWritten out of range');
32153 }
32154 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
32155 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
32156 // TODO: Figure out whether we should detach the buffer or not here.
32157 return;
32158 }
32159 ReadableByteStreamControllerShiftPendingPullInto(controller);
32160 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
32161 if (remainderSize > 0) {
32162 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32163 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
32164 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
32165 }
32166 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
32167 pullIntoDescriptor.bytesFilled -= remainderSize;
32168 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32169 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32170}
32171function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
32172 const firstDescriptor = controller._pendingPullIntos.peek();
32173 const state = controller._controlledReadableByteStream._state;
32174 if (state === 'closed') {
32175 if (bytesWritten !== 0) {
32176 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
32177 }
32178 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
32179 }
32180 else {
32181 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
32182 }
32183 ReadableByteStreamControllerCallPullIfNeeded(controller);
32184}
32185function ReadableByteStreamControllerShiftPendingPullInto(controller) {
32186 const descriptor = controller._pendingPullIntos.shift();
32187 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32188 return descriptor;
32189}
32190function ReadableByteStreamControllerShouldCallPull(controller) {
32191 const stream = controller._controlledReadableByteStream;
32192 if (stream._state !== 'readable') {
32193 return false;
32194 }
32195 if (controller._closeRequested) {
32196 return false;
32197 }
32198 if (!controller._started) {
32199 return false;
32200 }
32201 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
32202 return true;
32203 }
32204 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32205 return true;
32206 }
32207 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
32208 if (desiredSize > 0) {
32209 return true;
32210 }
32211 return false;
32212}
32213function ReadableByteStreamControllerClearAlgorithms(controller) {
32214 controller._pullAlgorithm = undefined;
32215 controller._cancelAlgorithm = undefined;
32216}
32217// A client of ReadableByteStreamController may use these functions directly to bypass state check.
32218function ReadableByteStreamControllerClose(controller) {
32219 const stream = controller._controlledReadableByteStream;
32220 if (controller._closeRequested || stream._state !== 'readable') {
32221 return;
32222 }
32223 if (controller._queueTotalSize > 0) {
32224 controller._closeRequested = true;
32225 return;
32226 }
32227 if (controller._pendingPullIntos.length > 0) {
32228 const firstPendingPullInto = controller._pendingPullIntos.peek();
32229 if (firstPendingPullInto.bytesFilled > 0) {
32230 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32231 ReadableByteStreamControllerError(controller, e);
32232 throw e;
32233 }
32234 }
32235 ReadableByteStreamControllerClearAlgorithms(controller);
32236 ReadableStreamClose(stream);
32237}
32238function ReadableByteStreamControllerEnqueue(controller, chunk) {
32239 const stream = controller._controlledReadableByteStream;
32240 if (controller._closeRequested || stream._state !== 'readable') {
32241 return;
32242 }
32243 const buffer = chunk.buffer;
32244 const byteOffset = chunk.byteOffset;
32245 const byteLength = chunk.byteLength;
32246 const transferredBuffer = TransferArrayBuffer(buffer);
32247 if (ReadableStreamHasDefaultReader(stream)) {
32248 if (ReadableStreamGetNumReadRequests(stream) === 0) {
32249 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32250 }
32251 else {
32252 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
32253 ReadableStreamFulfillReadRequest(stream, transferredView, false);
32254 }
32255 }
32256 else if (ReadableStreamHasBYOBReader(stream)) {
32257 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
32258 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32259 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32260 }
32261 else {
32262 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32263 }
32264 ReadableByteStreamControllerCallPullIfNeeded(controller);
32265}
32266function ReadableByteStreamControllerError(controller, e) {
32267 const stream = controller._controlledReadableByteStream;
32268 if (stream._state !== 'readable') {
32269 return;
32270 }
32271 ReadableByteStreamControllerClearPendingPullIntos(controller);
32272 ResetQueue(controller);
32273 ReadableByteStreamControllerClearAlgorithms(controller);
32274 ReadableStreamError(stream, e);
32275}
32276function ReadableByteStreamControllerGetDesiredSize(controller) {
32277 const state = controller._controlledReadableByteStream._state;
32278 if (state === 'errored') {
32279 return null;
32280 }
32281 if (state === 'closed') {
32282 return 0;
32283 }
32284 return controller._strategyHWM - controller._queueTotalSize;
32285}
32286function ReadableByteStreamControllerRespond(controller, bytesWritten) {
32287 bytesWritten = Number(bytesWritten);
32288 if (!IsFiniteNonNegativeNumber(bytesWritten)) {
32289 throw new RangeError('bytesWritten must be a finite');
32290 }
32291 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
32292}
32293function ReadableByteStreamControllerRespondWithNewView(controller, view) {
32294 const firstDescriptor = controller._pendingPullIntos.peek();
32295 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
32296 throw new RangeError('The region specified by view does not match byobRequest');
32297 }
32298 if (firstDescriptor.byteLength !== view.byteLength) {
32299 throw new RangeError('The buffer of view has different capacity than byobRequest');
32300 }
32301 firstDescriptor.buffer = view.buffer;
32302 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
32303}
32304function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
32305 controller._controlledReadableByteStream = stream;
32306 controller._pullAgain = false;
32307 controller._pulling = false;
32308 controller._byobRequest = null;
32309 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
32310 controller._queue = controller._queueTotalSize = undefined;
32311 ResetQueue(controller);
32312 controller._closeRequested = false;
32313 controller._started = false;
32314 controller._strategyHWM = highWaterMark;
32315 controller._pullAlgorithm = pullAlgorithm;
32316 controller._cancelAlgorithm = cancelAlgorithm;
32317 controller._autoAllocateChunkSize = autoAllocateChunkSize;
32318 controller._pendingPullIntos = new SimpleQueue();
32319 stream._readableStreamController = controller;
32320 const startResult = startAlgorithm();
32321 uponPromise(promiseResolvedWith(startResult), () => {
32322 controller._started = true;
32323 ReadableByteStreamControllerCallPullIfNeeded(controller);
32324 }, r => {
32325 ReadableByteStreamControllerError(controller, r);
32326 });
32327}
32328function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
32329 const controller = Object.create(ReadableByteStreamController.prototype);
32330 let startAlgorithm = () => undefined;
32331 let pullAlgorithm = () => promiseResolvedWith(undefined);
32332 let cancelAlgorithm = () => promiseResolvedWith(undefined);
32333 if (underlyingByteSource.start !== undefined) {
32334 startAlgorithm = () => underlyingByteSource.start(controller);
32335 }
32336 if (underlyingByteSource.pull !== undefined) {
32337 pullAlgorithm = () => underlyingByteSource.pull(controller);
32338 }
32339 if (underlyingByteSource.cancel !== undefined) {
32340 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
32341 }
32342 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
32343 if (autoAllocateChunkSize === 0) {
32344 throw new TypeError('autoAllocateChunkSize must be greater than 0');
32345 }
32346 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
32347}
32348function SetUpReadableStreamBYOBRequest(request, controller, view) {
32349 request._associatedReadableByteStreamController = controller;
32350 request._view = view;
32351}
32352// Helper functions for the ReadableStreamBYOBRequest.
32353function byobRequestBrandCheckException(name) {
32354 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
32355}
32356// Helper functions for the ReadableByteStreamController.
32357function byteStreamControllerBrandCheckException(name) {
32358 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
32359}
32360
32361// Abstract operations for the ReadableStream.
32362function AcquireReadableStreamBYOBReader(stream) {
32363 return new ReadableStreamBYOBReader(stream);
32364}
32365// ReadableStream API exposed for controllers.
32366function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
32367 stream._reader._readIntoRequests.push(readIntoRequest);
32368}
32369function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
32370 const reader = stream._reader;
32371 const readIntoRequest = reader._readIntoRequests.shift();
32372 if (done) {
32373 readIntoRequest._closeSteps(chunk);
32374 }
32375 else {
32376 readIntoRequest._chunkSteps(chunk);
32377 }
32378}
32379function ReadableStreamGetNumReadIntoRequests(stream) {
32380 return stream._reader._readIntoRequests.length;
32381}
32382function ReadableStreamHasBYOBReader(stream) {
32383 const reader = stream._reader;
32384 if (reader === undefined) {
32385 return false;
32386 }
32387 if (!IsReadableStreamBYOBReader(reader)) {
32388 return false;
32389 }
32390 return true;
32391}
32392/**
32393 * A BYOB reader vended by a {@link ReadableStream}.
32394 *
32395 * @public
32396 */
32397class ReadableStreamBYOBReader {
32398 constructor(stream) {
32399 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
32400 assertReadableStream(stream, 'First parameter');
32401 if (IsReadableStreamLocked(stream)) {
32402 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
32403 }
32404 if (!IsReadableByteStreamController(stream._readableStreamController)) {
32405 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
32406 'source');
32407 }
32408 ReadableStreamReaderGenericInitialize(this, stream);
32409 this._readIntoRequests = new SimpleQueue();
32410 }
32411 /**
32412 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32413 * the reader's lock is released before the stream finishes closing.
32414 */
32415 get closed() {
32416 if (!IsReadableStreamBYOBReader(this)) {
32417 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
32418 }
32419 return this._closedPromise;
32420 }
32421 /**
32422 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
32423 */
32424 cancel(reason = undefined) {
32425 if (!IsReadableStreamBYOBReader(this)) {
32426 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
32427 }
32428 if (this._ownerReadableStream === undefined) {
32429 return promiseRejectedWith(readerLockException('cancel'));
32430 }
32431 return ReadableStreamReaderGenericCancel(this, reason);
32432 }
32433 /**
32434 * Attempts to reads bytes into view, and returns a promise resolved with the result.
32435 *
32436 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
32437 */
32438 read(view) {
32439 if (!IsReadableStreamBYOBReader(this)) {
32440 return promiseRejectedWith(byobReaderBrandCheckException('read'));
32441 }
32442 if (!ArrayBuffer.isView(view)) {
32443 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
32444 }
32445 if (view.byteLength === 0) {
32446 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
32447 }
32448 if (view.buffer.byteLength === 0) {
32449 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
32450 }
32451 if (this._ownerReadableStream === undefined) {
32452 return promiseRejectedWith(readerLockException('read from'));
32453 }
32454 let resolvePromise;
32455 let rejectPromise;
32456 const promise = newPromise((resolve, reject) => {
32457 resolvePromise = resolve;
32458 rejectPromise = reject;
32459 });
32460 const readIntoRequest = {
32461 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
32462 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
32463 _errorSteps: e => rejectPromise(e)
32464 };
32465 ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
32466 return promise;
32467 }
32468 /**
32469 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
32470 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
32471 * from now on; otherwise, the reader will appear closed.
32472 *
32473 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
32474 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
32475 * do so will throw a `TypeError` and leave the reader locked to the stream.
32476 */
32477 releaseLock() {
32478 if (!IsReadableStreamBYOBReader(this)) {
32479 throw byobReaderBrandCheckException('releaseLock');
32480 }
32481 if (this._ownerReadableStream === undefined) {
32482 return;
32483 }
32484 if (this._readIntoRequests.length > 0) {
32485 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
32486 }
32487 ReadableStreamReaderGenericRelease(this);
32488 }
32489}
32490Object.defineProperties(ReadableStreamBYOBReader.prototype, {
32491 cancel: { enumerable: true },
32492 read: { enumerable: true },
32493 releaseLock: { enumerable: true },
32494 closed: { enumerable: true }
32495});
32496if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32497 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
32498 value: 'ReadableStreamBYOBReader',
32499 configurable: true
32500 });
32501}
32502// Abstract operations for the readers.
32503function IsReadableStreamBYOBReader(x) {
32504 if (!typeIsObject(x)) {
32505 return false;
32506 }
32507 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
32508 return false;
32509 }
32510 return true;
32511}
32512function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
32513 const stream = reader._ownerReadableStream;
32514 stream._disturbed = true;
32515 if (stream._state === 'errored') {
32516 readIntoRequest._errorSteps(stream._storedError);
32517 }
32518 else {
32519 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
32520 }
32521}
32522// Helper functions for the ReadableStreamBYOBReader.
32523function byobReaderBrandCheckException(name) {
32524 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
32525}
32526
32527function ExtractHighWaterMark(strategy, defaultHWM) {
32528 const { highWaterMark } = strategy;
32529 if (highWaterMark === undefined) {
32530 return defaultHWM;
32531 }
32532 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
32533 throw new RangeError('Invalid highWaterMark');
32534 }
32535 return highWaterMark;
32536}
32537function ExtractSizeAlgorithm(strategy) {
32538 const { size } = strategy;
32539 if (!size) {
32540 return () => 1;
32541 }
32542 return size;
32543}
32544
32545function convertQueuingStrategy(init, context) {
32546 assertDictionary(init, context);
32547 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
32548 const size = init === null || init === void 0 ? void 0 : init.size;
32549 return {
32550 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
32551 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
32552 };
32553}
32554function convertQueuingStrategySize(fn, context) {
32555 assertFunction(fn, context);
32556 return chunk => convertUnrestrictedDouble(fn(chunk));
32557}
32558
32559function convertUnderlyingSink(original, context) {
32560 assertDictionary(original, context);
32561 const abort = original === null || original === void 0 ? void 0 : original.abort;
32562 const close = original === null || original === void 0 ? void 0 : original.close;
32563 const start = original === null || original === void 0 ? void 0 : original.start;
32564 const type = original === null || original === void 0 ? void 0 : original.type;
32565 const write = original === null || original === void 0 ? void 0 : original.write;
32566 return {
32567 abort: abort === undefined ?
32568 undefined :
32569 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
32570 close: close === undefined ?
32571 undefined :
32572 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
32573 start: start === undefined ?
32574 undefined :
32575 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
32576 write: write === undefined ?
32577 undefined :
32578 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
32579 type
32580 };
32581}
32582function convertUnderlyingSinkAbortCallback(fn, original, context) {
32583 assertFunction(fn, context);
32584 return (reason) => promiseCall(fn, original, [reason]);
32585}
32586function convertUnderlyingSinkCloseCallback(fn, original, context) {
32587 assertFunction(fn, context);
32588 return () => promiseCall(fn, original, []);
32589}
32590function convertUnderlyingSinkStartCallback(fn, original, context) {
32591 assertFunction(fn, context);
32592 return (controller) => reflectCall(fn, original, [controller]);
32593}
32594function convertUnderlyingSinkWriteCallback(fn, original, context) {
32595 assertFunction(fn, context);
32596 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
32597}
32598
32599function assertWritableStream(x, context) {
32600 if (!IsWritableStream(x)) {
32601 throw new TypeError(`${context} is not a WritableStream.`);
32602 }
32603}
32604
32605/**
32606 * A writable stream represents a destination for data, into which you can write.
32607 *
32608 * @public
32609 */
32610class WritableStream$1 {
32611 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
32612 if (rawUnderlyingSink === undefined) {
32613 rawUnderlyingSink = null;
32614 }
32615 else {
32616 assertObject(rawUnderlyingSink, 'First parameter');
32617 }
32618 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
32619 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
32620 InitializeWritableStream(this);
32621 const type = underlyingSink.type;
32622 if (type !== undefined) {
32623 throw new RangeError('Invalid type is specified');
32624 }
32625 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
32626 const highWaterMark = ExtractHighWaterMark(strategy, 1);
32627 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
32628 }
32629 /**
32630 * Returns whether or not the writable stream is locked to a writer.
32631 */
32632 get locked() {
32633 if (!IsWritableStream(this)) {
32634 throw streamBrandCheckException$2('locked');
32635 }
32636 return IsWritableStreamLocked(this);
32637 }
32638 /**
32639 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
32640 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
32641 * mechanism of the underlying sink.
32642 *
32643 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
32644 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
32645 * the stream) if the stream is currently locked.
32646 */
32647 abort(reason = undefined) {
32648 if (!IsWritableStream(this)) {
32649 return promiseRejectedWith(streamBrandCheckException$2('abort'));
32650 }
32651 if (IsWritableStreamLocked(this)) {
32652 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
32653 }
32654 return WritableStreamAbort(this, reason);
32655 }
32656 /**
32657 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
32658 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
32659 *
32660 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
32661 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
32662 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
32663 */
32664 close() {
32665 if (!IsWritableStream(this)) {
32666 return promiseRejectedWith(streamBrandCheckException$2('close'));
32667 }
32668 if (IsWritableStreamLocked(this)) {
32669 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
32670 }
32671 if (WritableStreamCloseQueuedOrInFlight(this)) {
32672 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
32673 }
32674 return WritableStreamClose(this);
32675 }
32676 /**
32677 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
32678 * is locked, no other writer can be acquired until this one is released.
32679 *
32680 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
32681 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
32682 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
32683 */
32684 getWriter() {
32685 if (!IsWritableStream(this)) {
32686 throw streamBrandCheckException$2('getWriter');
32687 }
32688 return AcquireWritableStreamDefaultWriter(this);
32689 }
32690}
32691Object.defineProperties(WritableStream$1.prototype, {
32692 abort: { enumerable: true },
32693 close: { enumerable: true },
32694 getWriter: { enumerable: true },
32695 locked: { enumerable: true }
32696});
32697if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32698 Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, {
32699 value: 'WritableStream',
32700 configurable: true
32701 });
32702}
32703// Abstract operations for the WritableStream.
32704function AcquireWritableStreamDefaultWriter(stream) {
32705 return new WritableStreamDefaultWriter(stream);
32706}
32707// Throws if and only if startAlgorithm throws.
32708function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
32709 const stream = Object.create(WritableStream$1.prototype);
32710 InitializeWritableStream(stream);
32711 const controller = Object.create(WritableStreamDefaultController.prototype);
32712 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
32713 return stream;
32714}
32715function InitializeWritableStream(stream) {
32716 stream._state = 'writable';
32717 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
32718 // 'erroring' or 'errored'. May be set to an undefined value.
32719 stream._storedError = undefined;
32720 stream._writer = undefined;
32721 // Initialize to undefined first because the constructor of the controller checks this
32722 // variable to validate the caller.
32723 stream._writableStreamController = undefined;
32724 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
32725 // producer without waiting for the queued writes to finish.
32726 stream._writeRequests = new SimpleQueue();
32727 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
32728 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
32729 stream._inFlightWriteRequest = undefined;
32730 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
32731 // has been detached.
32732 stream._closeRequest = undefined;
32733 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
32734 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
32735 stream._inFlightCloseRequest = undefined;
32736 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
32737 stream._pendingAbortRequest = undefined;
32738 // The backpressure signal set by the controller.
32739 stream._backpressure = false;
32740}
32741function IsWritableStream(x) {
32742 if (!typeIsObject(x)) {
32743 return false;
32744 }
32745 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
32746 return false;
32747 }
32748 return true;
32749}
32750function IsWritableStreamLocked(stream) {
32751 if (stream._writer === undefined) {
32752 return false;
32753 }
32754 return true;
32755}
32756function WritableStreamAbort(stream, reason) {
32757 const state = stream._state;
32758 if (state === 'closed' || state === 'errored') {
32759 return promiseResolvedWith(undefined);
32760 }
32761 if (stream._pendingAbortRequest !== undefined) {
32762 return stream._pendingAbortRequest._promise;
32763 }
32764 let wasAlreadyErroring = false;
32765 if (state === 'erroring') {
32766 wasAlreadyErroring = true;
32767 // reason will not be used, so don't keep a reference to it.
32768 reason = undefined;
32769 }
32770 const promise = newPromise((resolve, reject) => {
32771 stream._pendingAbortRequest = {
32772 _promise: undefined,
32773 _resolve: resolve,
32774 _reject: reject,
32775 _reason: reason,
32776 _wasAlreadyErroring: wasAlreadyErroring
32777 };
32778 });
32779 stream._pendingAbortRequest._promise = promise;
32780 if (!wasAlreadyErroring) {
32781 WritableStreamStartErroring(stream, reason);
32782 }
32783 return promise;
32784}
32785function WritableStreamClose(stream) {
32786 const state = stream._state;
32787 if (state === 'closed' || state === 'errored') {
32788 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
32789 }
32790 const promise = newPromise((resolve, reject) => {
32791 const closeRequest = {
32792 _resolve: resolve,
32793 _reject: reject
32794 };
32795 stream._closeRequest = closeRequest;
32796 });
32797 const writer = stream._writer;
32798 if (writer !== undefined && stream._backpressure && state === 'writable') {
32799 defaultWriterReadyPromiseResolve(writer);
32800 }
32801 WritableStreamDefaultControllerClose(stream._writableStreamController);
32802 return promise;
32803}
32804// WritableStream API exposed for controllers.
32805function WritableStreamAddWriteRequest(stream) {
32806 const promise = newPromise((resolve, reject) => {
32807 const writeRequest = {
32808 _resolve: resolve,
32809 _reject: reject
32810 };
32811 stream._writeRequests.push(writeRequest);
32812 });
32813 return promise;
32814}
32815function WritableStreamDealWithRejection(stream, error) {
32816 const state = stream._state;
32817 if (state === 'writable') {
32818 WritableStreamStartErroring(stream, error);
32819 return;
32820 }
32821 WritableStreamFinishErroring(stream);
32822}
32823function WritableStreamStartErroring(stream, reason) {
32824 const controller = stream._writableStreamController;
32825 stream._state = 'erroring';
32826 stream._storedError = reason;
32827 const writer = stream._writer;
32828 if (writer !== undefined) {
32829 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
32830 }
32831 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
32832 WritableStreamFinishErroring(stream);
32833 }
32834}
32835function WritableStreamFinishErroring(stream) {
32836 stream._state = 'errored';
32837 stream._writableStreamController[ErrorSteps]();
32838 const storedError = stream._storedError;
32839 stream._writeRequests.forEach(writeRequest => {
32840 writeRequest._reject(storedError);
32841 });
32842 stream._writeRequests = new SimpleQueue();
32843 if (stream._pendingAbortRequest === undefined) {
32844 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32845 return;
32846 }
32847 const abortRequest = stream._pendingAbortRequest;
32848 stream._pendingAbortRequest = undefined;
32849 if (abortRequest._wasAlreadyErroring) {
32850 abortRequest._reject(storedError);
32851 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32852 return;
32853 }
32854 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
32855 uponPromise(promise, () => {
32856 abortRequest._resolve();
32857 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32858 }, (reason) => {
32859 abortRequest._reject(reason);
32860 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32861 });
32862}
32863function WritableStreamFinishInFlightWrite(stream) {
32864 stream._inFlightWriteRequest._resolve(undefined);
32865 stream._inFlightWriteRequest = undefined;
32866}
32867function WritableStreamFinishInFlightWriteWithError(stream, error) {
32868 stream._inFlightWriteRequest._reject(error);
32869 stream._inFlightWriteRequest = undefined;
32870 WritableStreamDealWithRejection(stream, error);
32871}
32872function WritableStreamFinishInFlightClose(stream) {
32873 stream._inFlightCloseRequest._resolve(undefined);
32874 stream._inFlightCloseRequest = undefined;
32875 const state = stream._state;
32876 if (state === 'erroring') {
32877 // The error was too late to do anything, so it is ignored.
32878 stream._storedError = undefined;
32879 if (stream._pendingAbortRequest !== undefined) {
32880 stream._pendingAbortRequest._resolve();
32881 stream._pendingAbortRequest = undefined;
32882 }
32883 }
32884 stream._state = 'closed';
32885 const writer = stream._writer;
32886 if (writer !== undefined) {
32887 defaultWriterClosedPromiseResolve(writer);
32888 }
32889}
32890function WritableStreamFinishInFlightCloseWithError(stream, error) {
32891 stream._inFlightCloseRequest._reject(error);
32892 stream._inFlightCloseRequest = undefined;
32893 // Never execute sink abort() after sink close().
32894 if (stream._pendingAbortRequest !== undefined) {
32895 stream._pendingAbortRequest._reject(error);
32896 stream._pendingAbortRequest = undefined;
32897 }
32898 WritableStreamDealWithRejection(stream, error);
32899}
32900// TODO(ricea): Fix alphabetical order.
32901function WritableStreamCloseQueuedOrInFlight(stream) {
32902 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
32903 return false;
32904 }
32905 return true;
32906}
32907function WritableStreamHasOperationMarkedInFlight(stream) {
32908 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
32909 return false;
32910 }
32911 return true;
32912}
32913function WritableStreamMarkCloseRequestInFlight(stream) {
32914 stream._inFlightCloseRequest = stream._closeRequest;
32915 stream._closeRequest = undefined;
32916}
32917function WritableStreamMarkFirstWriteRequestInFlight(stream) {
32918 stream._inFlightWriteRequest = stream._writeRequests.shift();
32919}
32920function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
32921 if (stream._closeRequest !== undefined) {
32922 stream._closeRequest._reject(stream._storedError);
32923 stream._closeRequest = undefined;
32924 }
32925 const writer = stream._writer;
32926 if (writer !== undefined) {
32927 defaultWriterClosedPromiseReject(writer, stream._storedError);
32928 }
32929}
32930function WritableStreamUpdateBackpressure(stream, backpressure) {
32931 const writer = stream._writer;
32932 if (writer !== undefined && backpressure !== stream._backpressure) {
32933 if (backpressure) {
32934 defaultWriterReadyPromiseReset(writer);
32935 }
32936 else {
32937 defaultWriterReadyPromiseResolve(writer);
32938 }
32939 }
32940 stream._backpressure = backpressure;
32941}
32942/**
32943 * A default writer vended by a {@link WritableStream}.
32944 *
32945 * @public
32946 */
32947class WritableStreamDefaultWriter {
32948 constructor(stream) {
32949 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
32950 assertWritableStream(stream, 'First parameter');
32951 if (IsWritableStreamLocked(stream)) {
32952 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
32953 }
32954 this._ownerWritableStream = stream;
32955 stream._writer = this;
32956 const state = stream._state;
32957 if (state === 'writable') {
32958 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
32959 defaultWriterReadyPromiseInitialize(this);
32960 }
32961 else {
32962 defaultWriterReadyPromiseInitializeAsResolved(this);
32963 }
32964 defaultWriterClosedPromiseInitialize(this);
32965 }
32966 else if (state === 'erroring') {
32967 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
32968 defaultWriterClosedPromiseInitialize(this);
32969 }
32970 else if (state === 'closed') {
32971 defaultWriterReadyPromiseInitializeAsResolved(this);
32972 defaultWriterClosedPromiseInitializeAsResolved(this);
32973 }
32974 else {
32975 const storedError = stream._storedError;
32976 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
32977 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
32978 }
32979 }
32980 /**
32981 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32982 * the writer’s lock is released before the stream finishes closing.
32983 */
32984 get closed() {
32985 if (!IsWritableStreamDefaultWriter(this)) {
32986 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
32987 }
32988 return this._closedPromise;
32989 }
32990 /**
32991 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
32992 * A producer can use this information to determine the right amount of data to write.
32993 *
32994 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
32995 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
32996 * the writer’s lock is released.
32997 */
32998 get desiredSize() {
32999 if (!IsWritableStreamDefaultWriter(this)) {
33000 throw defaultWriterBrandCheckException('desiredSize');
33001 }
33002 if (this._ownerWritableStream === undefined) {
33003 throw defaultWriterLockException('desiredSize');
33004 }
33005 return WritableStreamDefaultWriterGetDesiredSize(this);
33006 }
33007 /**
33008 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
33009 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
33010 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
33011 *
33012 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
33013 * rejected.
33014 */
33015 get ready() {
33016 if (!IsWritableStreamDefaultWriter(this)) {
33017 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
33018 }
33019 return this._readyPromise;
33020 }
33021 /**
33022 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
33023 */
33024 abort(reason = undefined) {
33025 if (!IsWritableStreamDefaultWriter(this)) {
33026 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
33027 }
33028 if (this._ownerWritableStream === undefined) {
33029 return promiseRejectedWith(defaultWriterLockException('abort'));
33030 }
33031 return WritableStreamDefaultWriterAbort(this, reason);
33032 }
33033 /**
33034 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
33035 */
33036 close() {
33037 if (!IsWritableStreamDefaultWriter(this)) {
33038 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
33039 }
33040 const stream = this._ownerWritableStream;
33041 if (stream === undefined) {
33042 return promiseRejectedWith(defaultWriterLockException('close'));
33043 }
33044 if (WritableStreamCloseQueuedOrInFlight(stream)) {
33045 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
33046 }
33047 return WritableStreamDefaultWriterClose(this);
33048 }
33049 /**
33050 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
33051 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
33052 * now on; otherwise, the writer will appear closed.
33053 *
33054 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
33055 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
33056 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
33057 * other producers from writing in an interleaved manner.
33058 */
33059 releaseLock() {
33060 if (!IsWritableStreamDefaultWriter(this)) {
33061 throw defaultWriterBrandCheckException('releaseLock');
33062 }
33063 const stream = this._ownerWritableStream;
33064 if (stream === undefined) {
33065 return;
33066 }
33067 WritableStreamDefaultWriterRelease(this);
33068 }
33069 write(chunk = undefined) {
33070 if (!IsWritableStreamDefaultWriter(this)) {
33071 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
33072 }
33073 if (this._ownerWritableStream === undefined) {
33074 return promiseRejectedWith(defaultWriterLockException('write to'));
33075 }
33076 return WritableStreamDefaultWriterWrite(this, chunk);
33077 }
33078}
33079Object.defineProperties(WritableStreamDefaultWriter.prototype, {
33080 abort: { enumerable: true },
33081 close: { enumerable: true },
33082 releaseLock: { enumerable: true },
33083 write: { enumerable: true },
33084 closed: { enumerable: true },
33085 desiredSize: { enumerable: true },
33086 ready: { enumerable: true }
33087});
33088if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33089 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
33090 value: 'WritableStreamDefaultWriter',
33091 configurable: true
33092 });
33093}
33094// Abstract operations for the WritableStreamDefaultWriter.
33095function IsWritableStreamDefaultWriter(x) {
33096 if (!typeIsObject(x)) {
33097 return false;
33098 }
33099 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
33100 return false;
33101 }
33102 return true;
33103}
33104// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
33105function WritableStreamDefaultWriterAbort(writer, reason) {
33106 const stream = writer._ownerWritableStream;
33107 return WritableStreamAbort(stream, reason);
33108}
33109function WritableStreamDefaultWriterClose(writer) {
33110 const stream = writer._ownerWritableStream;
33111 return WritableStreamClose(stream);
33112}
33113function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
33114 const stream = writer._ownerWritableStream;
33115 const state = stream._state;
33116 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33117 return promiseResolvedWith(undefined);
33118 }
33119 if (state === 'errored') {
33120 return promiseRejectedWith(stream._storedError);
33121 }
33122 return WritableStreamDefaultWriterClose(writer);
33123}
33124function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
33125 if (writer._closedPromiseState === 'pending') {
33126 defaultWriterClosedPromiseReject(writer, error);
33127 }
33128 else {
33129 defaultWriterClosedPromiseResetToRejected(writer, error);
33130 }
33131}
33132function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
33133 if (writer._readyPromiseState === 'pending') {
33134 defaultWriterReadyPromiseReject(writer, error);
33135 }
33136 else {
33137 defaultWriterReadyPromiseResetToRejected(writer, error);
33138 }
33139}
33140function WritableStreamDefaultWriterGetDesiredSize(writer) {
33141 const stream = writer._ownerWritableStream;
33142 const state = stream._state;
33143 if (state === 'errored' || state === 'erroring') {
33144 return null;
33145 }
33146 if (state === 'closed') {
33147 return 0;
33148 }
33149 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
33150}
33151function WritableStreamDefaultWriterRelease(writer) {
33152 const stream = writer._ownerWritableStream;
33153 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
33154 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
33155 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
33156 // rejected until afterwards. This means that simply testing state will not work.
33157 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
33158 stream._writer = undefined;
33159 writer._ownerWritableStream = undefined;
33160}
33161function WritableStreamDefaultWriterWrite(writer, chunk) {
33162 const stream = writer._ownerWritableStream;
33163 const controller = stream._writableStreamController;
33164 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
33165 if (stream !== writer._ownerWritableStream) {
33166 return promiseRejectedWith(defaultWriterLockException('write to'));
33167 }
33168 const state = stream._state;
33169 if (state === 'errored') {
33170 return promiseRejectedWith(stream._storedError);
33171 }
33172 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33173 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
33174 }
33175 if (state === 'erroring') {
33176 return promiseRejectedWith(stream._storedError);
33177 }
33178 const promise = WritableStreamAddWriteRequest(stream);
33179 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
33180 return promise;
33181}
33182const closeSentinel = {};
33183/**
33184 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
33185 *
33186 * @public
33187 */
33188class WritableStreamDefaultController {
33189 constructor() {
33190 throw new TypeError('Illegal constructor');
33191 }
33192 /**
33193 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
33194 *
33195 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
33196 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
33197 * normal lifecycle of interactions with the underlying sink.
33198 */
33199 error(e = undefined) {
33200 if (!IsWritableStreamDefaultController(this)) {
33201 throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
33202 }
33203 const state = this._controlledWritableStream._state;
33204 if (state !== 'writable') {
33205 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
33206 // just treat it as a no-op.
33207 return;
33208 }
33209 WritableStreamDefaultControllerError(this, e);
33210 }
33211 /** @internal */
33212 [AbortSteps](reason) {
33213 const result = this._abortAlgorithm(reason);
33214 WritableStreamDefaultControllerClearAlgorithms(this);
33215 return result;
33216 }
33217 /** @internal */
33218 [ErrorSteps]() {
33219 ResetQueue(this);
33220 }
33221}
33222Object.defineProperties(WritableStreamDefaultController.prototype, {
33223 error: { enumerable: true }
33224});
33225if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33226 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33227 value: 'WritableStreamDefaultController',
33228 configurable: true
33229 });
33230}
33231// Abstract operations implementing interface required by the WritableStream.
33232function IsWritableStreamDefaultController(x) {
33233 if (!typeIsObject(x)) {
33234 return false;
33235 }
33236 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
33237 return false;
33238 }
33239 return true;
33240}
33241function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
33242 controller._controlledWritableStream = stream;
33243 stream._writableStreamController = controller;
33244 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
33245 controller._queue = undefined;
33246 controller._queueTotalSize = undefined;
33247 ResetQueue(controller);
33248 controller._started = false;
33249 controller._strategySizeAlgorithm = sizeAlgorithm;
33250 controller._strategyHWM = highWaterMark;
33251 controller._writeAlgorithm = writeAlgorithm;
33252 controller._closeAlgorithm = closeAlgorithm;
33253 controller._abortAlgorithm = abortAlgorithm;
33254 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33255 WritableStreamUpdateBackpressure(stream, backpressure);
33256 const startResult = startAlgorithm();
33257 const startPromise = promiseResolvedWith(startResult);
33258 uponPromise(startPromise, () => {
33259 controller._started = true;
33260 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33261 }, r => {
33262 controller._started = true;
33263 WritableStreamDealWithRejection(stream, r);
33264 });
33265}
33266function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
33267 const controller = Object.create(WritableStreamDefaultController.prototype);
33268 let startAlgorithm = () => undefined;
33269 let writeAlgorithm = () => promiseResolvedWith(undefined);
33270 let closeAlgorithm = () => promiseResolvedWith(undefined);
33271 let abortAlgorithm = () => promiseResolvedWith(undefined);
33272 if (underlyingSink.start !== undefined) {
33273 startAlgorithm = () => underlyingSink.start(controller);
33274 }
33275 if (underlyingSink.write !== undefined) {
33276 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
33277 }
33278 if (underlyingSink.close !== undefined) {
33279 closeAlgorithm = () => underlyingSink.close();
33280 }
33281 if (underlyingSink.abort !== undefined) {
33282 abortAlgorithm = reason => underlyingSink.abort(reason);
33283 }
33284 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
33285}
33286// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
33287function WritableStreamDefaultControllerClearAlgorithms(controller) {
33288 controller._writeAlgorithm = undefined;
33289 controller._closeAlgorithm = undefined;
33290 controller._abortAlgorithm = undefined;
33291 controller._strategySizeAlgorithm = undefined;
33292}
33293function WritableStreamDefaultControllerClose(controller) {
33294 EnqueueValueWithSize(controller, closeSentinel, 0);
33295 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33296}
33297function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
33298 try {
33299 return controller._strategySizeAlgorithm(chunk);
33300 }
33301 catch (chunkSizeE) {
33302 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
33303 return 1;
33304 }
33305}
33306function WritableStreamDefaultControllerGetDesiredSize(controller) {
33307 return controller._strategyHWM - controller._queueTotalSize;
33308}
33309function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
33310 try {
33311 EnqueueValueWithSize(controller, chunk, chunkSize);
33312 }
33313 catch (enqueueE) {
33314 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
33315 return;
33316 }
33317 const stream = controller._controlledWritableStream;
33318 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
33319 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33320 WritableStreamUpdateBackpressure(stream, backpressure);
33321 }
33322 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33323}
33324// Abstract operations for the WritableStreamDefaultController.
33325function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
33326 const stream = controller._controlledWritableStream;
33327 if (!controller._started) {
33328 return;
33329 }
33330 if (stream._inFlightWriteRequest !== undefined) {
33331 return;
33332 }
33333 const state = stream._state;
33334 if (state === 'erroring') {
33335 WritableStreamFinishErroring(stream);
33336 return;
33337 }
33338 if (controller._queue.length === 0) {
33339 return;
33340 }
33341 const value = PeekQueueValue(controller);
33342 if (value === closeSentinel) {
33343 WritableStreamDefaultControllerProcessClose(controller);
33344 }
33345 else {
33346 WritableStreamDefaultControllerProcessWrite(controller, value);
33347 }
33348}
33349function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
33350 if (controller._controlledWritableStream._state === 'writable') {
33351 WritableStreamDefaultControllerError(controller, error);
33352 }
33353}
33354function WritableStreamDefaultControllerProcessClose(controller) {
33355 const stream = controller._controlledWritableStream;
33356 WritableStreamMarkCloseRequestInFlight(stream);
33357 DequeueValue(controller);
33358 const sinkClosePromise = controller._closeAlgorithm();
33359 WritableStreamDefaultControllerClearAlgorithms(controller);
33360 uponPromise(sinkClosePromise, () => {
33361 WritableStreamFinishInFlightClose(stream);
33362 }, reason => {
33363 WritableStreamFinishInFlightCloseWithError(stream, reason);
33364 });
33365}
33366function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
33367 const stream = controller._controlledWritableStream;
33368 WritableStreamMarkFirstWriteRequestInFlight(stream);
33369 const sinkWritePromise = controller._writeAlgorithm(chunk);
33370 uponPromise(sinkWritePromise, () => {
33371 WritableStreamFinishInFlightWrite(stream);
33372 const state = stream._state;
33373 DequeueValue(controller);
33374 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
33375 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33376 WritableStreamUpdateBackpressure(stream, backpressure);
33377 }
33378 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33379 }, reason => {
33380 if (stream._state === 'writable') {
33381 WritableStreamDefaultControllerClearAlgorithms(controller);
33382 }
33383 WritableStreamFinishInFlightWriteWithError(stream, reason);
33384 });
33385}
33386function WritableStreamDefaultControllerGetBackpressure(controller) {
33387 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
33388 return desiredSize <= 0;
33389}
33390// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
33391function WritableStreamDefaultControllerError(controller, error) {
33392 const stream = controller._controlledWritableStream;
33393 WritableStreamDefaultControllerClearAlgorithms(controller);
33394 WritableStreamStartErroring(stream, error);
33395}
33396// Helper functions for the WritableStream.
33397function streamBrandCheckException$2(name) {
33398 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
33399}
33400// Helper functions for the WritableStreamDefaultWriter.
33401function defaultWriterBrandCheckException(name) {
33402 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
33403}
33404function defaultWriterLockException(name) {
33405 return new TypeError('Cannot ' + name + ' a stream using a released writer');
33406}
33407function defaultWriterClosedPromiseInitialize(writer) {
33408 writer._closedPromise = newPromise((resolve, reject) => {
33409 writer._closedPromise_resolve = resolve;
33410 writer._closedPromise_reject = reject;
33411 writer._closedPromiseState = 'pending';
33412 });
33413}
33414function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
33415 defaultWriterClosedPromiseInitialize(writer);
33416 defaultWriterClosedPromiseReject(writer, reason);
33417}
33418function defaultWriterClosedPromiseInitializeAsResolved(writer) {
33419 defaultWriterClosedPromiseInitialize(writer);
33420 defaultWriterClosedPromiseResolve(writer);
33421}
33422function defaultWriterClosedPromiseReject(writer, reason) {
33423 if (writer._closedPromise_reject === undefined) {
33424 return;
33425 }
33426 setPromiseIsHandledToTrue(writer._closedPromise);
33427 writer._closedPromise_reject(reason);
33428 writer._closedPromise_resolve = undefined;
33429 writer._closedPromise_reject = undefined;
33430 writer._closedPromiseState = 'rejected';
33431}
33432function defaultWriterClosedPromiseResetToRejected(writer, reason) {
33433 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
33434}
33435function defaultWriterClosedPromiseResolve(writer) {
33436 if (writer._closedPromise_resolve === undefined) {
33437 return;
33438 }
33439 writer._closedPromise_resolve(undefined);
33440 writer._closedPromise_resolve = undefined;
33441 writer._closedPromise_reject = undefined;
33442 writer._closedPromiseState = 'resolved';
33443}
33444function defaultWriterReadyPromiseInitialize(writer) {
33445 writer._readyPromise = newPromise((resolve, reject) => {
33446 writer._readyPromise_resolve = resolve;
33447 writer._readyPromise_reject = reject;
33448 });
33449 writer._readyPromiseState = 'pending';
33450}
33451function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
33452 defaultWriterReadyPromiseInitialize(writer);
33453 defaultWriterReadyPromiseReject(writer, reason);
33454}
33455function defaultWriterReadyPromiseInitializeAsResolved(writer) {
33456 defaultWriterReadyPromiseInitialize(writer);
33457 defaultWriterReadyPromiseResolve(writer);
33458}
33459function defaultWriterReadyPromiseReject(writer, reason) {
33460 if (writer._readyPromise_reject === undefined) {
33461 return;
33462 }
33463 setPromiseIsHandledToTrue(writer._readyPromise);
33464 writer._readyPromise_reject(reason);
33465 writer._readyPromise_resolve = undefined;
33466 writer._readyPromise_reject = undefined;
33467 writer._readyPromiseState = 'rejected';
33468}
33469function defaultWriterReadyPromiseReset(writer) {
33470 defaultWriterReadyPromiseInitialize(writer);
33471}
33472function defaultWriterReadyPromiseResetToRejected(writer, reason) {
33473 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
33474}
33475function defaultWriterReadyPromiseResolve(writer) {
33476 if (writer._readyPromise_resolve === undefined) {
33477 return;
33478 }
33479 writer._readyPromise_resolve(undefined);
33480 writer._readyPromise_resolve = undefined;
33481 writer._readyPromise_reject = undefined;
33482 writer._readyPromiseState = 'fulfilled';
33483}
33484
33485function isAbortSignal(value) {
33486 if (typeof value !== 'object' || value === null) {
33487 return false;
33488 }
33489 try {
33490 return typeof value.aborted === 'boolean';
33491 }
33492 catch (_a) {
33493 // AbortSignal.prototype.aborted throws if its brand check fails
33494 return false;
33495 }
33496}
33497
33498/// <reference lib="dom" />
33499const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
33500
33501/// <reference types="node" />
33502function isDOMExceptionConstructor(ctor) {
33503 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
33504 return false;
33505 }
33506 try {
33507 new ctor();
33508 return true;
33509 }
33510 catch (_a) {
33511 return false;
33512 }
33513}
33514function createDOMExceptionPolyfill() {
33515 // eslint-disable-next-line no-shadow
33516 const ctor = function DOMException(message, name) {
33517 this.message = message || '';
33518 this.name = name || 'Error';
33519 if (Error.captureStackTrace) {
33520 Error.captureStackTrace(this, this.constructor);
33521 }
33522 };
33523 ctor.prototype = Object.create(Error.prototype);
33524 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
33525 return ctor;
33526}
33527// eslint-disable-next-line no-redeclare
33528const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
33529
33530function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
33531 const reader = AcquireReadableStreamDefaultReader(source);
33532 const writer = AcquireWritableStreamDefaultWriter(dest);
33533 source._disturbed = true;
33534 let shuttingDown = false;
33535 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
33536 let currentWrite = promiseResolvedWith(undefined);
33537 return newPromise((resolve, reject) => {
33538 let abortAlgorithm;
33539 if (signal !== undefined) {
33540 abortAlgorithm = () => {
33541 const error = new DOMException$1('Aborted', 'AbortError');
33542 const actions = [];
33543 if (!preventAbort) {
33544 actions.push(() => {
33545 if (dest._state === 'writable') {
33546 return WritableStreamAbort(dest, error);
33547 }
33548 return promiseResolvedWith(undefined);
33549 });
33550 }
33551 if (!preventCancel) {
33552 actions.push(() => {
33553 if (source._state === 'readable') {
33554 return ReadableStreamCancel(source, error);
33555 }
33556 return promiseResolvedWith(undefined);
33557 });
33558 }
33559 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
33560 };
33561 if (signal.aborted) {
33562 abortAlgorithm();
33563 return;
33564 }
33565 signal.addEventListener('abort', abortAlgorithm);
33566 }
33567 // Using reader and writer, read all chunks from this and write them to dest
33568 // - Backpressure must be enforced
33569 // - Shutdown must stop all activity
33570 function pipeLoop() {
33571 return newPromise((resolveLoop, rejectLoop) => {
33572 function next(done) {
33573 if (done) {
33574 resolveLoop();
33575 }
33576 else {
33577 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
33578 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
33579 PerformPromiseThen(pipeStep(), next, rejectLoop);
33580 }
33581 }
33582 next(false);
33583 });
33584 }
33585 function pipeStep() {
33586 if (shuttingDown) {
33587 return promiseResolvedWith(true);
33588 }
33589 return PerformPromiseThen(writer._readyPromise, () => {
33590 return newPromise((resolveRead, rejectRead) => {
33591 ReadableStreamDefaultReaderRead(reader, {
33592 _chunkSteps: chunk => {
33593 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
33594 resolveRead(false);
33595 },
33596 _closeSteps: () => resolveRead(true),
33597 _errorSteps: rejectRead
33598 });
33599 });
33600 });
33601 }
33602 // Errors must be propagated forward
33603 isOrBecomesErrored(source, reader._closedPromise, storedError => {
33604 if (!preventAbort) {
33605 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
33606 }
33607 else {
33608 shutdown(true, storedError);
33609 }
33610 });
33611 // Errors must be propagated backward
33612 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
33613 if (!preventCancel) {
33614 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
33615 }
33616 else {
33617 shutdown(true, storedError);
33618 }
33619 });
33620 // Closing must be propagated forward
33621 isOrBecomesClosed(source, reader._closedPromise, () => {
33622 if (!preventClose) {
33623 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
33624 }
33625 else {
33626 shutdown();
33627 }
33628 });
33629 // Closing must be propagated backward
33630 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
33631 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
33632 if (!preventCancel) {
33633 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
33634 }
33635 else {
33636 shutdown(true, destClosed);
33637 }
33638 }
33639 setPromiseIsHandledToTrue(pipeLoop());
33640 function waitForWritesToFinish() {
33641 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
33642 // for that too.
33643 const oldCurrentWrite = currentWrite;
33644 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
33645 }
33646 function isOrBecomesErrored(stream, promise, action) {
33647 if (stream._state === 'errored') {
33648 action(stream._storedError);
33649 }
33650 else {
33651 uponRejection(promise, action);
33652 }
33653 }
33654 function isOrBecomesClosed(stream, promise, action) {
33655 if (stream._state === 'closed') {
33656 action();
33657 }
33658 else {
33659 uponFulfillment(promise, action);
33660 }
33661 }
33662 function shutdownWithAction(action, originalIsError, originalError) {
33663 if (shuttingDown) {
33664 return;
33665 }
33666 shuttingDown = true;
33667 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33668 uponFulfillment(waitForWritesToFinish(), doTheRest);
33669 }
33670 else {
33671 doTheRest();
33672 }
33673 function doTheRest() {
33674 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
33675 }
33676 }
33677 function shutdown(isError, error) {
33678 if (shuttingDown) {
33679 return;
33680 }
33681 shuttingDown = true;
33682 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33683 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
33684 }
33685 else {
33686 finalize(isError, error);
33687 }
33688 }
33689 function finalize(isError, error) {
33690 WritableStreamDefaultWriterRelease(writer);
33691 ReadableStreamReaderGenericRelease(reader);
33692 if (signal !== undefined) {
33693 signal.removeEventListener('abort', abortAlgorithm);
33694 }
33695 if (isError) {
33696 reject(error);
33697 }
33698 else {
33699 resolve(undefined);
33700 }
33701 }
33702 });
33703}
33704
33705/**
33706 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
33707 *
33708 * @public
33709 */
33710class ReadableStreamDefaultController {
33711 constructor() {
33712 throw new TypeError('Illegal constructor');
33713 }
33714 /**
33715 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
33716 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
33717 */
33718 get desiredSize() {
33719 if (!IsReadableStreamDefaultController(this)) {
33720 throw defaultControllerBrandCheckException$1('desiredSize');
33721 }
33722 return ReadableStreamDefaultControllerGetDesiredSize(this);
33723 }
33724 /**
33725 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
33726 * the stream, but once those are read, the stream will become closed.
33727 */
33728 close() {
33729 if (!IsReadableStreamDefaultController(this)) {
33730 throw defaultControllerBrandCheckException$1('close');
33731 }
33732 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33733 throw new TypeError('The stream is not in a state that permits close');
33734 }
33735 ReadableStreamDefaultControllerClose(this);
33736 }
33737 enqueue(chunk = undefined) {
33738 if (!IsReadableStreamDefaultController(this)) {
33739 throw defaultControllerBrandCheckException$1('enqueue');
33740 }
33741 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33742 throw new TypeError('The stream is not in a state that permits enqueue');
33743 }
33744 return ReadableStreamDefaultControllerEnqueue(this, chunk);
33745 }
33746 /**
33747 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
33748 */
33749 error(e = undefined) {
33750 if (!IsReadableStreamDefaultController(this)) {
33751 throw defaultControllerBrandCheckException$1('error');
33752 }
33753 ReadableStreamDefaultControllerError(this, e);
33754 }
33755 /** @internal */
33756 [CancelSteps](reason) {
33757 ResetQueue(this);
33758 const result = this._cancelAlgorithm(reason);
33759 ReadableStreamDefaultControllerClearAlgorithms(this);
33760 return result;
33761 }
33762 /** @internal */
33763 [PullSteps](readRequest) {
33764 const stream = this._controlledReadableStream;
33765 if (this._queue.length > 0) {
33766 const chunk = DequeueValue(this);
33767 if (this._closeRequested && this._queue.length === 0) {
33768 ReadableStreamDefaultControllerClearAlgorithms(this);
33769 ReadableStreamClose(stream);
33770 }
33771 else {
33772 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33773 }
33774 readRequest._chunkSteps(chunk);
33775 }
33776 else {
33777 ReadableStreamAddReadRequest(stream, readRequest);
33778 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33779 }
33780 }
33781}
33782Object.defineProperties(ReadableStreamDefaultController.prototype, {
33783 close: { enumerable: true },
33784 enqueue: { enumerable: true },
33785 error: { enumerable: true },
33786 desiredSize: { enumerable: true }
33787});
33788if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33789 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33790 value: 'ReadableStreamDefaultController',
33791 configurable: true
33792 });
33793}
33794// Abstract operations for the ReadableStreamDefaultController.
33795function IsReadableStreamDefaultController(x) {
33796 if (!typeIsObject(x)) {
33797 return false;
33798 }
33799 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
33800 return false;
33801 }
33802 return true;
33803}
33804function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
33805 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
33806 if (!shouldPull) {
33807 return;
33808 }
33809 if (controller._pulling) {
33810 controller._pullAgain = true;
33811 return;
33812 }
33813 controller._pulling = true;
33814 const pullPromise = controller._pullAlgorithm();
33815 uponPromise(pullPromise, () => {
33816 controller._pulling = false;
33817 if (controller._pullAgain) {
33818 controller._pullAgain = false;
33819 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33820 }
33821 }, e => {
33822 ReadableStreamDefaultControllerError(controller, e);
33823 });
33824}
33825function ReadableStreamDefaultControllerShouldCallPull(controller) {
33826 const stream = controller._controlledReadableStream;
33827 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33828 return false;
33829 }
33830 if (!controller._started) {
33831 return false;
33832 }
33833 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33834 return true;
33835 }
33836 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
33837 if (desiredSize > 0) {
33838 return true;
33839 }
33840 return false;
33841}
33842function ReadableStreamDefaultControllerClearAlgorithms(controller) {
33843 controller._pullAlgorithm = undefined;
33844 controller._cancelAlgorithm = undefined;
33845 controller._strategySizeAlgorithm = undefined;
33846}
33847// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
33848function ReadableStreamDefaultControllerClose(controller) {
33849 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33850 return;
33851 }
33852 const stream = controller._controlledReadableStream;
33853 controller._closeRequested = true;
33854 if (controller._queue.length === 0) {
33855 ReadableStreamDefaultControllerClearAlgorithms(controller);
33856 ReadableStreamClose(stream);
33857 }
33858}
33859function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
33860 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33861 return;
33862 }
33863 const stream = controller._controlledReadableStream;
33864 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33865 ReadableStreamFulfillReadRequest(stream, chunk, false);
33866 }
33867 else {
33868 let chunkSize;
33869 try {
33870 chunkSize = controller._strategySizeAlgorithm(chunk);
33871 }
33872 catch (chunkSizeE) {
33873 ReadableStreamDefaultControllerError(controller, chunkSizeE);
33874 throw chunkSizeE;
33875 }
33876 try {
33877 EnqueueValueWithSize(controller, chunk, chunkSize);
33878 }
33879 catch (enqueueE) {
33880 ReadableStreamDefaultControllerError(controller, enqueueE);
33881 throw enqueueE;
33882 }
33883 }
33884 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33885}
33886function ReadableStreamDefaultControllerError(controller, e) {
33887 const stream = controller._controlledReadableStream;
33888 if (stream._state !== 'readable') {
33889 return;
33890 }
33891 ResetQueue(controller);
33892 ReadableStreamDefaultControllerClearAlgorithms(controller);
33893 ReadableStreamError(stream, e);
33894}
33895function ReadableStreamDefaultControllerGetDesiredSize(controller) {
33896 const state = controller._controlledReadableStream._state;
33897 if (state === 'errored') {
33898 return null;
33899 }
33900 if (state === 'closed') {
33901 return 0;
33902 }
33903 return controller._strategyHWM - controller._queueTotalSize;
33904}
33905// This is used in the implementation of TransformStream.
33906function ReadableStreamDefaultControllerHasBackpressure(controller) {
33907 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
33908 return false;
33909 }
33910 return true;
33911}
33912function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
33913 const state = controller._controlledReadableStream._state;
33914 if (!controller._closeRequested && state === 'readable') {
33915 return true;
33916 }
33917 return false;
33918}
33919function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
33920 controller._controlledReadableStream = stream;
33921 controller._queue = undefined;
33922 controller._queueTotalSize = undefined;
33923 ResetQueue(controller);
33924 controller._started = false;
33925 controller._closeRequested = false;
33926 controller._pullAgain = false;
33927 controller._pulling = false;
33928 controller._strategySizeAlgorithm = sizeAlgorithm;
33929 controller._strategyHWM = highWaterMark;
33930 controller._pullAlgorithm = pullAlgorithm;
33931 controller._cancelAlgorithm = cancelAlgorithm;
33932 stream._readableStreamController = controller;
33933 const startResult = startAlgorithm();
33934 uponPromise(promiseResolvedWith(startResult), () => {
33935 controller._started = true;
33936 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33937 }, r => {
33938 ReadableStreamDefaultControllerError(controller, r);
33939 });
33940}
33941function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
33942 const controller = Object.create(ReadableStreamDefaultController.prototype);
33943 let startAlgorithm = () => undefined;
33944 let pullAlgorithm = () => promiseResolvedWith(undefined);
33945 let cancelAlgorithm = () => promiseResolvedWith(undefined);
33946 if (underlyingSource.start !== undefined) {
33947 startAlgorithm = () => underlyingSource.start(controller);
33948 }
33949 if (underlyingSource.pull !== undefined) {
33950 pullAlgorithm = () => underlyingSource.pull(controller);
33951 }
33952 if (underlyingSource.cancel !== undefined) {
33953 cancelAlgorithm = reason => underlyingSource.cancel(reason);
33954 }
33955 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
33956}
33957// Helper functions for the ReadableStreamDefaultController.
33958function defaultControllerBrandCheckException$1(name) {
33959 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
33960}
33961
33962function ReadableStreamTee(stream, cloneForBranch2) {
33963 const reader = AcquireReadableStreamDefaultReader(stream);
33964 let reading = false;
33965 let canceled1 = false;
33966 let canceled2 = false;
33967 let reason1;
33968 let reason2;
33969 let branch1;
33970 let branch2;
33971 let resolveCancelPromise;
33972 const cancelPromise = newPromise(resolve => {
33973 resolveCancelPromise = resolve;
33974 });
33975 function pullAlgorithm() {
33976 if (reading) {
33977 return promiseResolvedWith(undefined);
33978 }
33979 reading = true;
33980 const readRequest = {
33981 _chunkSteps: value => {
33982 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
33983 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
33984 // successful synchronously-available reads get ahead of asynchronously-available errors.
33985 queueMicrotask(() => {
33986 reading = false;
33987 const value1 = value;
33988 const value2 = value;
33989 // There is no way to access the cloning code right now in the reference implementation.
33990 // If we add one then we'll need an implementation for serializable objects.
33991 // if (!canceled2 && cloneForBranch2) {
33992 // value2 = StructuredDeserialize(StructuredSerialize(value2));
33993 // }
33994 if (!canceled1) {
33995 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
33996 }
33997 if (!canceled2) {
33998 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
33999 }
34000 });
34001 },
34002 _closeSteps: () => {
34003 reading = false;
34004 if (!canceled1) {
34005 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
34006 }
34007 if (!canceled2) {
34008 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
34009 }
34010 if (!canceled1 || !canceled2) {
34011 resolveCancelPromise(undefined);
34012 }
34013 },
34014 _errorSteps: () => {
34015 reading = false;
34016 }
34017 };
34018 ReadableStreamDefaultReaderRead(reader, readRequest);
34019 return promiseResolvedWith(undefined);
34020 }
34021 function cancel1Algorithm(reason) {
34022 canceled1 = true;
34023 reason1 = reason;
34024 if (canceled2) {
34025 const compositeReason = CreateArrayFromList([reason1, reason2]);
34026 const cancelResult = ReadableStreamCancel(stream, compositeReason);
34027 resolveCancelPromise(cancelResult);
34028 }
34029 return cancelPromise;
34030 }
34031 function cancel2Algorithm(reason) {
34032 canceled2 = true;
34033 reason2 = reason;
34034 if (canceled1) {
34035 const compositeReason = CreateArrayFromList([reason1, reason2]);
34036 const cancelResult = ReadableStreamCancel(stream, compositeReason);
34037 resolveCancelPromise(cancelResult);
34038 }
34039 return cancelPromise;
34040 }
34041 function startAlgorithm() {
34042 // do nothing
34043 }
34044 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
34045 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
34046 uponRejection(reader._closedPromise, (r) => {
34047 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
34048 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
34049 if (!canceled1 || !canceled2) {
34050 resolveCancelPromise(undefined);
34051 }
34052 });
34053 return [branch1, branch2];
34054}
34055
34056function convertUnderlyingDefaultOrByteSource(source, context) {
34057 assertDictionary(source, context);
34058 const original = source;
34059 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
34060 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
34061 const pull = original === null || original === void 0 ? void 0 : original.pull;
34062 const start = original === null || original === void 0 ? void 0 : original.start;
34063 const type = original === null || original === void 0 ? void 0 : original.type;
34064 return {
34065 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
34066 undefined :
34067 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
34068 cancel: cancel === undefined ?
34069 undefined :
34070 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
34071 pull: pull === undefined ?
34072 undefined :
34073 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
34074 start: start === undefined ?
34075 undefined :
34076 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
34077 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
34078 };
34079}
34080function convertUnderlyingSourceCancelCallback(fn, original, context) {
34081 assertFunction(fn, context);
34082 return (reason) => promiseCall(fn, original, [reason]);
34083}
34084function convertUnderlyingSourcePullCallback(fn, original, context) {
34085 assertFunction(fn, context);
34086 return (controller) => promiseCall(fn, original, [controller]);
34087}
34088function convertUnderlyingSourceStartCallback(fn, original, context) {
34089 assertFunction(fn, context);
34090 return (controller) => reflectCall(fn, original, [controller]);
34091}
34092function convertReadableStreamType(type, context) {
34093 type = `${type}`;
34094 if (type !== 'bytes') {
34095 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
34096 }
34097 return type;
34098}
34099
34100function convertReaderOptions(options, context) {
34101 assertDictionary(options, context);
34102 const mode = options === null || options === void 0 ? void 0 : options.mode;
34103 return {
34104 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
34105 };
34106}
34107function convertReadableStreamReaderMode(mode, context) {
34108 mode = `${mode}`;
34109 if (mode !== 'byob') {
34110 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
34111 }
34112 return mode;
34113}
34114
34115function convertIteratorOptions(options, context) {
34116 assertDictionary(options, context);
34117 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34118 return { preventCancel: Boolean(preventCancel) };
34119}
34120
34121function convertPipeOptions(options, context) {
34122 assertDictionary(options, context);
34123 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
34124 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34125 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
34126 const signal = options === null || options === void 0 ? void 0 : options.signal;
34127 if (signal !== undefined) {
34128 assertAbortSignal(signal, `${context} has member 'signal' that`);
34129 }
34130 return {
34131 preventAbort: Boolean(preventAbort),
34132 preventCancel: Boolean(preventCancel),
34133 preventClose: Boolean(preventClose),
34134 signal
34135 };
34136}
34137function assertAbortSignal(signal, context) {
34138 if (!isAbortSignal(signal)) {
34139 throw new TypeError(`${context} is not an AbortSignal.`);
34140 }
34141}
34142
34143function convertReadableWritablePair(pair, context) {
34144 assertDictionary(pair, context);
34145 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
34146 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
34147 assertReadableStream(readable, `${context} has member 'readable' that`);
34148 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
34149 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
34150 assertWritableStream(writable, `${context} has member 'writable' that`);
34151 return { readable, writable };
34152}
34153
34154/**
34155 * A readable stream represents a source of data, from which you can read.
34156 *
34157 * @public
34158 */
34159class ReadableStream$1 {
34160 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
34161 if (rawUnderlyingSource === undefined) {
34162 rawUnderlyingSource = null;
34163 }
34164 else {
34165 assertObject(rawUnderlyingSource, 'First parameter');
34166 }
34167 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
34168 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
34169 InitializeReadableStream(this);
34170 if (underlyingSource.type === 'bytes') {
34171 if (strategy.size !== undefined) {
34172 throw new RangeError('The strategy for a byte stream cannot have a size function');
34173 }
34174 const highWaterMark = ExtractHighWaterMark(strategy, 0);
34175 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
34176 }
34177 else {
34178 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
34179 const highWaterMark = ExtractHighWaterMark(strategy, 1);
34180 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
34181 }
34182 }
34183 /**
34184 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
34185 */
34186 get locked() {
34187 if (!IsReadableStream(this)) {
34188 throw streamBrandCheckException$1('locked');
34189 }
34190 return IsReadableStreamLocked(this);
34191 }
34192 /**
34193 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
34194 *
34195 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
34196 * method, which might or might not use it.
34197 */
34198 cancel(reason = undefined) {
34199 if (!IsReadableStream(this)) {
34200 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
34201 }
34202 if (IsReadableStreamLocked(this)) {
34203 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
34204 }
34205 return ReadableStreamCancel(this, reason);
34206 }
34207 getReader(rawOptions = undefined) {
34208 if (!IsReadableStream(this)) {
34209 throw streamBrandCheckException$1('getReader');
34210 }
34211 const options = convertReaderOptions(rawOptions, 'First parameter');
34212 if (options.mode === undefined) {
34213 return AcquireReadableStreamDefaultReader(this);
34214 }
34215 return AcquireReadableStreamBYOBReader(this);
34216 }
34217 pipeThrough(rawTransform, rawOptions = {}) {
34218 if (!IsReadableStream(this)) {
34219 throw streamBrandCheckException$1('pipeThrough');
34220 }
34221 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
34222 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
34223 const options = convertPipeOptions(rawOptions, 'Second parameter');
34224 if (IsReadableStreamLocked(this)) {
34225 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
34226 }
34227 if (IsWritableStreamLocked(transform.writable)) {
34228 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
34229 }
34230 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34231 setPromiseIsHandledToTrue(promise);
34232 return transform.readable;
34233 }
34234 pipeTo(destination, rawOptions = {}) {
34235 if (!IsReadableStream(this)) {
34236 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
34237 }
34238 if (destination === undefined) {
34239 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
34240 }
34241 if (!IsWritableStream(destination)) {
34242 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
34243 }
34244 let options;
34245 try {
34246 options = convertPipeOptions(rawOptions, 'Second parameter');
34247 }
34248 catch (e) {
34249 return promiseRejectedWith(e);
34250 }
34251 if (IsReadableStreamLocked(this)) {
34252 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
34253 }
34254 if (IsWritableStreamLocked(destination)) {
34255 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
34256 }
34257 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34258 }
34259 /**
34260 * Tees this readable stream, returning a two-element array containing the two resulting branches as
34261 * new {@link ReadableStream} instances.
34262 *
34263 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
34264 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
34265 * propagated to the stream's underlying source.
34266 *
34267 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
34268 * this could allow interference between the two branches.
34269 */
34270 tee() {
34271 if (!IsReadableStream(this)) {
34272 throw streamBrandCheckException$1('tee');
34273 }
34274 const branches = ReadableStreamTee(this);
34275 return CreateArrayFromList(branches);
34276 }
34277 values(rawOptions = undefined) {
34278 if (!IsReadableStream(this)) {
34279 throw streamBrandCheckException$1('values');
34280 }
34281 const options = convertIteratorOptions(rawOptions, 'First parameter');
34282 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
34283 }
34284}
34285Object.defineProperties(ReadableStream$1.prototype, {
34286 cancel: { enumerable: true },
34287 getReader: { enumerable: true },
34288 pipeThrough: { enumerable: true },
34289 pipeTo: { enumerable: true },
34290 tee: { enumerable: true },
34291 values: { enumerable: true },
34292 locked: { enumerable: true }
34293});
34294if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34295 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, {
34296 value: 'ReadableStream',
34297 configurable: true
34298 });
34299}
34300if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
34301 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, {
34302 value: ReadableStream$1.prototype.values,
34303 writable: true,
34304 configurable: true
34305 });
34306}
34307// Abstract operations for the ReadableStream.
34308// Throws if and only if startAlgorithm throws.
34309function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
34310 const stream = Object.create(ReadableStream$1.prototype);
34311 InitializeReadableStream(stream);
34312 const controller = Object.create(ReadableStreamDefaultController.prototype);
34313 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
34314 return stream;
34315}
34316function InitializeReadableStream(stream) {
34317 stream._state = 'readable';
34318 stream._reader = undefined;
34319 stream._storedError = undefined;
34320 stream._disturbed = false;
34321}
34322function IsReadableStream(x) {
34323 if (!typeIsObject(x)) {
34324 return false;
34325 }
34326 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
34327 return false;
34328 }
34329 return true;
34330}
34331function IsReadableStreamLocked(stream) {
34332 if (stream._reader === undefined) {
34333 return false;
34334 }
34335 return true;
34336}
34337// ReadableStream API exposed for controllers.
34338function ReadableStreamCancel(stream, reason) {
34339 stream._disturbed = true;
34340 if (stream._state === 'closed') {
34341 return promiseResolvedWith(undefined);
34342 }
34343 if (stream._state === 'errored') {
34344 return promiseRejectedWith(stream._storedError);
34345 }
34346 ReadableStreamClose(stream);
34347 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
34348 return transformPromiseWith(sourceCancelPromise, noop);
34349}
34350function ReadableStreamClose(stream) {
34351 stream._state = 'closed';
34352 const reader = stream._reader;
34353 if (reader === undefined) {
34354 return;
34355 }
34356 defaultReaderClosedPromiseResolve(reader);
34357 if (IsReadableStreamDefaultReader(reader)) {
34358 reader._readRequests.forEach(readRequest => {
34359 readRequest._closeSteps();
34360 });
34361 reader._readRequests = new SimpleQueue();
34362 }
34363}
34364function ReadableStreamError(stream, e) {
34365 stream._state = 'errored';
34366 stream._storedError = e;
34367 const reader = stream._reader;
34368 if (reader === undefined) {
34369 return;
34370 }
34371 defaultReaderClosedPromiseReject(reader, e);
34372 if (IsReadableStreamDefaultReader(reader)) {
34373 reader._readRequests.forEach(readRequest => {
34374 readRequest._errorSteps(e);
34375 });
34376 reader._readRequests = new SimpleQueue();
34377 }
34378 else {
34379 reader._readIntoRequests.forEach(readIntoRequest => {
34380 readIntoRequest._errorSteps(e);
34381 });
34382 reader._readIntoRequests = new SimpleQueue();
34383 }
34384}
34385// Helper functions for the ReadableStream.
34386function streamBrandCheckException$1(name) {
34387 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
34388}
34389
34390function convertQueuingStrategyInit(init, context) {
34391 assertDictionary(init, context);
34392 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
34393 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
34394 return {
34395 highWaterMark: convertUnrestrictedDouble(highWaterMark)
34396 };
34397}
34398
34399const byteLengthSizeFunction = function size(chunk) {
34400 return chunk.byteLength;
34401};
34402/**
34403 * A queuing strategy that counts the number of bytes in each chunk.
34404 *
34405 * @public
34406 */
34407class ByteLengthQueuingStrategy {
34408 constructor(options) {
34409 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
34410 options = convertQueuingStrategyInit(options, 'First parameter');
34411 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
34412 }
34413 /**
34414 * Returns the high water mark provided to the constructor.
34415 */
34416 get highWaterMark() {
34417 if (!IsByteLengthQueuingStrategy(this)) {
34418 throw byteLengthBrandCheckException('highWaterMark');
34419 }
34420 return this._byteLengthQueuingStrategyHighWaterMark;
34421 }
34422 /**
34423 * Measures the size of `chunk` by returning the value of its `byteLength` property.
34424 */
34425 get size() {
34426 if (!IsByteLengthQueuingStrategy(this)) {
34427 throw byteLengthBrandCheckException('size');
34428 }
34429 return byteLengthSizeFunction;
34430 }
34431}
34432Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
34433 highWaterMark: { enumerable: true },
34434 size: { enumerable: true }
34435});
34436if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34437 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34438 value: 'ByteLengthQueuingStrategy',
34439 configurable: true
34440 });
34441}
34442// Helper functions for the ByteLengthQueuingStrategy.
34443function byteLengthBrandCheckException(name) {
34444 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
34445}
34446function IsByteLengthQueuingStrategy(x) {
34447 if (!typeIsObject(x)) {
34448 return false;
34449 }
34450 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
34451 return false;
34452 }
34453 return true;
34454}
34455
34456const countSizeFunction = function size() {
34457 return 1;
34458};
34459/**
34460 * A queuing strategy that counts the number of chunks.
34461 *
34462 * @public
34463 */
34464class CountQueuingStrategy {
34465 constructor(options) {
34466 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
34467 options = convertQueuingStrategyInit(options, 'First parameter');
34468 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
34469 }
34470 /**
34471 * Returns the high water mark provided to the constructor.
34472 */
34473 get highWaterMark() {
34474 if (!IsCountQueuingStrategy(this)) {
34475 throw countBrandCheckException('highWaterMark');
34476 }
34477 return this._countQueuingStrategyHighWaterMark;
34478 }
34479 /**
34480 * Measures the size of `chunk` by always returning 1.
34481 * This ensures that the total queue size is a count of the number of chunks in the queue.
34482 */
34483 get size() {
34484 if (!IsCountQueuingStrategy(this)) {
34485 throw countBrandCheckException('size');
34486 }
34487 return countSizeFunction;
34488 }
34489}
34490Object.defineProperties(CountQueuingStrategy.prototype, {
34491 highWaterMark: { enumerable: true },
34492 size: { enumerable: true }
34493});
34494if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34495 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34496 value: 'CountQueuingStrategy',
34497 configurable: true
34498 });
34499}
34500// Helper functions for the CountQueuingStrategy.
34501function countBrandCheckException(name) {
34502 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
34503}
34504function IsCountQueuingStrategy(x) {
34505 if (!typeIsObject(x)) {
34506 return false;
34507 }
34508 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
34509 return false;
34510 }
34511 return true;
34512}
34513
34514function convertTransformer(original, context) {
34515 assertDictionary(original, context);
34516 const flush = original === null || original === void 0 ? void 0 : original.flush;
34517 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
34518 const start = original === null || original === void 0 ? void 0 : original.start;
34519 const transform = original === null || original === void 0 ? void 0 : original.transform;
34520 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
34521 return {
34522 flush: flush === undefined ?
34523 undefined :
34524 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
34525 readableType,
34526 start: start === undefined ?
34527 undefined :
34528 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
34529 transform: transform === undefined ?
34530 undefined :
34531 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
34532 writableType
34533 };
34534}
34535function convertTransformerFlushCallback(fn, original, context) {
34536 assertFunction(fn, context);
34537 return (controller) => promiseCall(fn, original, [controller]);
34538}
34539function convertTransformerStartCallback(fn, original, context) {
34540 assertFunction(fn, context);
34541 return (controller) => reflectCall(fn, original, [controller]);
34542}
34543function convertTransformerTransformCallback(fn, original, context) {
34544 assertFunction(fn, context);
34545 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
34546}
34547
34548// Class TransformStream
34549/**
34550 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
34551 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
34552 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
34553 * made available for reading from the readable side.
34554 *
34555 * @public
34556 */
34557class TransformStream$1 {
34558 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
34559 if (rawTransformer === undefined) {
34560 rawTransformer = null;
34561 }
34562 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
34563 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
34564 const transformer = convertTransformer(rawTransformer, 'First parameter');
34565 if (transformer.readableType !== undefined) {
34566 throw new RangeError('Invalid readableType specified');
34567 }
34568 if (transformer.writableType !== undefined) {
34569 throw new RangeError('Invalid writableType specified');
34570 }
34571 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
34572 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
34573 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
34574 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
34575 let startPromise_resolve;
34576 const startPromise = newPromise(resolve => {
34577 startPromise_resolve = resolve;
34578 });
34579 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34580 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
34581 if (transformer.start !== undefined) {
34582 startPromise_resolve(transformer.start(this._transformStreamController));
34583 }
34584 else {
34585 startPromise_resolve(undefined);
34586 }
34587 }
34588 /**
34589 * The readable side of the transform stream.
34590 */
34591 get readable() {
34592 if (!IsTransformStream(this)) {
34593 throw streamBrandCheckException('readable');
34594 }
34595 return this._readable;
34596 }
34597 /**
34598 * The writable side of the transform stream.
34599 */
34600 get writable() {
34601 if (!IsTransformStream(this)) {
34602 throw streamBrandCheckException('writable');
34603 }
34604 return this._writable;
34605 }
34606}
34607Object.defineProperties(TransformStream$1.prototype, {
34608 readable: { enumerable: true },
34609 writable: { enumerable: true }
34610});
34611if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34612 Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, {
34613 value: 'TransformStream',
34614 configurable: true
34615 });
34616}
34617function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
34618 function startAlgorithm() {
34619 return startPromise;
34620 }
34621 function writeAlgorithm(chunk) {
34622 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
34623 }
34624 function abortAlgorithm(reason) {
34625 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
34626 }
34627 function closeAlgorithm() {
34628 return TransformStreamDefaultSinkCloseAlgorithm(stream);
34629 }
34630 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
34631 function pullAlgorithm() {
34632 return TransformStreamDefaultSourcePullAlgorithm(stream);
34633 }
34634 function cancelAlgorithm(reason) {
34635 TransformStreamErrorWritableAndUnblockWrite(stream, reason);
34636 return promiseResolvedWith(undefined);
34637 }
34638 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34639 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
34640 stream._backpressure = undefined;
34641 stream._backpressureChangePromise = undefined;
34642 stream._backpressureChangePromise_resolve = undefined;
34643 TransformStreamSetBackpressure(stream, true);
34644 stream._transformStreamController = undefined;
34645}
34646function IsTransformStream(x) {
34647 if (!typeIsObject(x)) {
34648 return false;
34649 }
34650 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
34651 return false;
34652 }
34653 return true;
34654}
34655// This is a no-op if both sides are already errored.
34656function TransformStreamError(stream, e) {
34657 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
34658 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34659}
34660function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
34661 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
34662 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
34663 if (stream._backpressure) {
34664 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
34665 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
34666 // _backpressure is set.
34667 TransformStreamSetBackpressure(stream, false);
34668 }
34669}
34670function TransformStreamSetBackpressure(stream, backpressure) {
34671 // Passes also when called during construction.
34672 if (stream._backpressureChangePromise !== undefined) {
34673 stream._backpressureChangePromise_resolve();
34674 }
34675 stream._backpressureChangePromise = newPromise(resolve => {
34676 stream._backpressureChangePromise_resolve = resolve;
34677 });
34678 stream._backpressure = backpressure;
34679}
34680// Class TransformStreamDefaultController
34681/**
34682 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
34683 *
34684 * @public
34685 */
34686class TransformStreamDefaultController {
34687 constructor() {
34688 throw new TypeError('Illegal constructor');
34689 }
34690 /**
34691 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
34692 */
34693 get desiredSize() {
34694 if (!IsTransformStreamDefaultController(this)) {
34695 throw defaultControllerBrandCheckException('desiredSize');
34696 }
34697 const readableController = this._controlledTransformStream._readable._readableStreamController;
34698 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
34699 }
34700 enqueue(chunk = undefined) {
34701 if (!IsTransformStreamDefaultController(this)) {
34702 throw defaultControllerBrandCheckException('enqueue');
34703 }
34704 TransformStreamDefaultControllerEnqueue(this, chunk);
34705 }
34706 /**
34707 * Errors both the readable side and the writable side of the controlled transform stream, making all future
34708 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
34709 */
34710 error(reason = undefined) {
34711 if (!IsTransformStreamDefaultController(this)) {
34712 throw defaultControllerBrandCheckException('error');
34713 }
34714 TransformStreamDefaultControllerError(this, reason);
34715 }
34716 /**
34717 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
34718 * transformer only needs to consume a portion of the chunks written to the writable side.
34719 */
34720 terminate() {
34721 if (!IsTransformStreamDefaultController(this)) {
34722 throw defaultControllerBrandCheckException('terminate');
34723 }
34724 TransformStreamDefaultControllerTerminate(this);
34725 }
34726}
34727Object.defineProperties(TransformStreamDefaultController.prototype, {
34728 enqueue: { enumerable: true },
34729 error: { enumerable: true },
34730 terminate: { enumerable: true },
34731 desiredSize: { enumerable: true }
34732});
34733if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34734 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
34735 value: 'TransformStreamDefaultController',
34736 configurable: true
34737 });
34738}
34739// Transform Stream Default Controller Abstract Operations
34740function IsTransformStreamDefaultController(x) {
34741 if (!typeIsObject(x)) {
34742 return false;
34743 }
34744 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
34745 return false;
34746 }
34747 return true;
34748}
34749function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
34750 controller._controlledTransformStream = stream;
34751 stream._transformStreamController = controller;
34752 controller._transformAlgorithm = transformAlgorithm;
34753 controller._flushAlgorithm = flushAlgorithm;
34754}
34755function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
34756 const controller = Object.create(TransformStreamDefaultController.prototype);
34757 let transformAlgorithm = (chunk) => {
34758 try {
34759 TransformStreamDefaultControllerEnqueue(controller, chunk);
34760 return promiseResolvedWith(undefined);
34761 }
34762 catch (transformResultE) {
34763 return promiseRejectedWith(transformResultE);
34764 }
34765 };
34766 let flushAlgorithm = () => promiseResolvedWith(undefined);
34767 if (transformer.transform !== undefined) {
34768 transformAlgorithm = chunk => transformer.transform(chunk, controller);
34769 }
34770 if (transformer.flush !== undefined) {
34771 flushAlgorithm = () => transformer.flush(controller);
34772 }
34773 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
34774}
34775function TransformStreamDefaultControllerClearAlgorithms(controller) {
34776 controller._transformAlgorithm = undefined;
34777 controller._flushAlgorithm = undefined;
34778}
34779function TransformStreamDefaultControllerEnqueue(controller, chunk) {
34780 const stream = controller._controlledTransformStream;
34781 const readableController = stream._readable._readableStreamController;
34782 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
34783 throw new TypeError('Readable side is not in a state that permits enqueue');
34784 }
34785 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
34786 // accept TransformStreamDefaultControllerEnqueue() calls.
34787 try {
34788 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
34789 }
34790 catch (e) {
34791 // This happens when readableStrategy.size() throws.
34792 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34793 throw stream._readable._storedError;
34794 }
34795 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
34796 if (backpressure !== stream._backpressure) {
34797 TransformStreamSetBackpressure(stream, true);
34798 }
34799}
34800function TransformStreamDefaultControllerError(controller, e) {
34801 TransformStreamError(controller._controlledTransformStream, e);
34802}
34803function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
34804 const transformPromise = controller._transformAlgorithm(chunk);
34805 return transformPromiseWith(transformPromise, undefined, r => {
34806 TransformStreamError(controller._controlledTransformStream, r);
34807 throw r;
34808 });
34809}
34810function TransformStreamDefaultControllerTerminate(controller) {
34811 const stream = controller._controlledTransformStream;
34812 const readableController = stream._readable._readableStreamController;
34813 ReadableStreamDefaultControllerClose(readableController);
34814 const error = new TypeError('TransformStream terminated');
34815 TransformStreamErrorWritableAndUnblockWrite(stream, error);
34816}
34817// TransformStreamDefaultSink Algorithms
34818function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
34819 const controller = stream._transformStreamController;
34820 if (stream._backpressure) {
34821 const backpressureChangePromise = stream._backpressureChangePromise;
34822 return transformPromiseWith(backpressureChangePromise, () => {
34823 const writable = stream._writable;
34824 const state = writable._state;
34825 if (state === 'erroring') {
34826 throw writable._storedError;
34827 }
34828 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34829 });
34830 }
34831 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34832}
34833function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
34834 // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
34835 // errored.
34836 TransformStreamError(stream, reason);
34837 return promiseResolvedWith(undefined);
34838}
34839function TransformStreamDefaultSinkCloseAlgorithm(stream) {
34840 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
34841 const readable = stream._readable;
34842 const controller = stream._transformStreamController;
34843 const flushPromise = controller._flushAlgorithm();
34844 TransformStreamDefaultControllerClearAlgorithms(controller);
34845 // Return a promise that is fulfilled with undefined on success.
34846 return transformPromiseWith(flushPromise, () => {
34847 if (readable._state === 'errored') {
34848 throw readable._storedError;
34849 }
34850 ReadableStreamDefaultControllerClose(readable._readableStreamController);
34851 }, r => {
34852 TransformStreamError(stream, r);
34853 throw readable._storedError;
34854 });
34855}
34856// TransformStreamDefaultSource Algorithms
34857function TransformStreamDefaultSourcePullAlgorithm(stream) {
34858 // Invariant. Enforced by the promises returned by start() and pull().
34859 TransformStreamSetBackpressure(stream, false);
34860 // Prevent the next pull() call until there is backpressure.
34861 return stream._backpressureChangePromise;
34862}
34863// Helper functions for the TransformStreamDefaultController.
34864function defaultControllerBrandCheckException(name) {
34865 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
34866}
34867// Helper functions for the TransformStream.
34868function streamBrandCheckException(name) {
34869 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
34870}
34871
34872var ponyfill_es6 = /*#__PURE__*/Object.freeze({
34873 __proto__: null,
34874 ByteLengthQueuingStrategy: ByteLengthQueuingStrategy,
34875 CountQueuingStrategy: CountQueuingStrategy,
34876 ReadableByteStreamController: ReadableByteStreamController,
34877 ReadableStream: ReadableStream$1,
34878 ReadableStreamBYOBReader: ReadableStreamBYOBReader,
34879 ReadableStreamBYOBRequest: ReadableStreamBYOBRequest,
34880 ReadableStreamDefaultController: ReadableStreamDefaultController,
34881 ReadableStreamDefaultReader: ReadableStreamDefaultReader,
34882 TransformStream: TransformStream$1,
34883 TransformStreamDefaultController: TransformStreamDefaultController,
34884 WritableStream: WritableStream$1,
34885 WritableStreamDefaultController: WritableStreamDefaultController,
34886 WritableStreamDefaultWriter: WritableStreamDefaultWriter
34887});
34888
34889/*! *****************************************************************************
34890Copyright (c) Microsoft Corporation.
34891
34892Permission to use, copy, modify, and/or distribute this software for any
34893purpose with or without fee is hereby granted.
34894
34895THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
34896REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
34897AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
34898INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
34899LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34900OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
34901PERFORMANCE OF THIS SOFTWARE.
34902***************************************************************************** */
34903/* global Reflect, Promise */
34904
34905var extendStatics = function(d, b) {
34906 extendStatics = Object.setPrototypeOf ||
34907 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34908 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
34909 return extendStatics(d, b);
34910};
34911
34912function __extends(d, b) {
34913 if (typeof b !== "function" && b !== null)
34914 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
34915 extendStatics(d, b);
34916 function __() { this.constructor = d; }
34917 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34918}
34919
34920function assert$1(test) {
34921 if (!test) {
34922 throw new TypeError('Assertion failed');
34923 }
34924}
34925
34926function noop$1() {
34927 return;
34928}
34929function typeIsObject$1(x) {
34930 return (typeof x === 'object' && x !== null) || typeof x === 'function';
34931}
34932
34933function isStreamConstructor(ctor) {
34934 if (typeof ctor !== 'function') {
34935 return false;
34936 }
34937 var startCalled = false;
34938 try {
34939 new ctor({
34940 start: function () {
34941 startCalled = true;
34942 }
34943 });
34944 }
34945 catch (e) {
34946 // ignore
34947 }
34948 return startCalled;
34949}
34950function isReadableStream(readable) {
34951 if (!typeIsObject$1(readable)) {
34952 return false;
34953 }
34954 if (typeof readable.getReader !== 'function') {
34955 return false;
34956 }
34957 return true;
34958}
34959function isReadableStreamConstructor(ctor) {
34960 if (!isStreamConstructor(ctor)) {
34961 return false;
34962 }
34963 if (!isReadableStream(new ctor())) {
34964 return false;
34965 }
34966 return true;
34967}
34968function isWritableStream(writable) {
34969 if (!typeIsObject$1(writable)) {
34970 return false;
34971 }
34972 if (typeof writable.getWriter !== 'function') {
34973 return false;
34974 }
34975 return true;
34976}
34977function isWritableStreamConstructor(ctor) {
34978 if (!isStreamConstructor(ctor)) {
34979 return false;
34980 }
34981 if (!isWritableStream(new ctor())) {
34982 return false;
34983 }
34984 return true;
34985}
34986function isTransformStream(transform) {
34987 if (!typeIsObject$1(transform)) {
34988 return false;
34989 }
34990 if (!isReadableStream(transform.readable)) {
34991 return false;
34992 }
34993 if (!isWritableStream(transform.writable)) {
34994 return false;
34995 }
34996 return true;
34997}
34998function isTransformStreamConstructor(ctor) {
34999 if (!isStreamConstructor(ctor)) {
35000 return false;
35001 }
35002 if (!isTransformStream(new ctor())) {
35003 return false;
35004 }
35005 return true;
35006}
35007function supportsByobReader(readable) {
35008 try {
35009 var reader = readable.getReader({ mode: 'byob' });
35010 reader.releaseLock();
35011 return true;
35012 }
35013 catch (_a) {
35014 return false;
35015 }
35016}
35017function supportsByteSource(ctor) {
35018 try {
35019 new ctor({ type: 'bytes' });
35020 return true;
35021 }
35022 catch (_a) {
35023 return false;
35024 }
35025}
35026
35027function createReadableStreamWrapper(ctor) {
35028 assert$1(isReadableStreamConstructor(ctor));
35029 var byteSourceSupported = supportsByteSource(ctor);
35030 return function (readable, _a) {
35031 var _b = _a === void 0 ? {} : _a, type = _b.type;
35032 type = parseReadableType(type);
35033 if (type === 'bytes' && !byteSourceSupported) {
35034 type = undefined;
35035 }
35036 if (readable.constructor === ctor) {
35037 if (type !== 'bytes' || supportsByobReader(readable)) {
35038 return readable;
35039 }
35040 }
35041 if (type === 'bytes') {
35042 var source = createWrappingReadableSource(readable, { type: type });
35043 return new ctor(source);
35044 }
35045 else {
35046 var source = createWrappingReadableSource(readable);
35047 return new ctor(source);
35048 }
35049 };
35050}
35051function createWrappingReadableSource(readable, _a) {
35052 var _b = _a === void 0 ? {} : _a, type = _b.type;
35053 assert$1(isReadableStream(readable));
35054 assert$1(readable.locked === false);
35055 type = parseReadableType(type);
35056 var source;
35057 if (type === 'bytes') {
35058 source = new WrappingReadableByteStreamSource(readable);
35059 }
35060 else {
35061 source = new WrappingReadableStreamDefaultSource(readable);
35062 }
35063 return source;
35064}
35065function parseReadableType(type) {
35066 var typeString = String(type);
35067 if (typeString === 'bytes') {
35068 return typeString;
35069 }
35070 else if (type === undefined) {
35071 return type;
35072 }
35073 else {
35074 throw new RangeError('Invalid type is specified');
35075 }
35076}
35077var AbstractWrappingReadableStreamSource = /** @class */ (function () {
35078 function AbstractWrappingReadableStreamSource(underlyingStream) {
35079 this._underlyingReader = undefined;
35080 this._readerMode = undefined;
35081 this._readableStreamController = undefined;
35082 this._pendingRead = undefined;
35083 this._underlyingStream = underlyingStream;
35084 // always keep a reader attached to detect close/error
35085 this._attachDefaultReader();
35086 }
35087 AbstractWrappingReadableStreamSource.prototype.start = function (controller) {
35088 this._readableStreamController = controller;
35089 };
35090 AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {
35091 assert$1(this._underlyingReader !== undefined);
35092 return this._underlyingReader.cancel(reason);
35093 };
35094 AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {
35095 if (this._readerMode === "default" /* DEFAULT */) {
35096 return;
35097 }
35098 this._detachReader();
35099 var reader = this._underlyingStream.getReader();
35100 this._readerMode = "default" /* DEFAULT */;
35101 this._attachReader(reader);
35102 };
35103 AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {
35104 var _this = this;
35105 assert$1(this._underlyingReader === undefined);
35106 this._underlyingReader = reader;
35107 var closed = this._underlyingReader.closed;
35108 if (!closed) {
35109 return;
35110 }
35111 closed
35112 .then(function () { return _this._finishPendingRead(); })
35113 .then(function () {
35114 if (reader === _this._underlyingReader) {
35115 _this._readableStreamController.close();
35116 }
35117 }, function (reason) {
35118 if (reader === _this._underlyingReader) {
35119 _this._readableStreamController.error(reason);
35120 }
35121 })
35122 .catch(noop$1);
35123 };
35124 AbstractWrappingReadableStreamSource.prototype._detachReader = function () {
35125 if (this._underlyingReader === undefined) {
35126 return;
35127 }
35128 this._underlyingReader.releaseLock();
35129 this._underlyingReader = undefined;
35130 this._readerMode = undefined;
35131 };
35132 AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {
35133 var _this = this;
35134 this._attachDefaultReader();
35135 // TODO Backpressure?
35136 var read = this._underlyingReader.read()
35137 .then(function (result) {
35138 var controller = _this._readableStreamController;
35139 if (result.done) {
35140 _this._tryClose();
35141 }
35142 else {
35143 controller.enqueue(result.value);
35144 }
35145 });
35146 this._setPendingRead(read);
35147 return read;
35148 };
35149 AbstractWrappingReadableStreamSource.prototype._tryClose = function () {
35150 try {
35151 this._readableStreamController.close();
35152 }
35153 catch (_a) {
35154 // already errored or closed
35155 }
35156 };
35157 AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {
35158 var _this = this;
35159 var pendingRead;
35160 var finishRead = function () {
35161 if (_this._pendingRead === pendingRead) {
35162 _this._pendingRead = undefined;
35163 }
35164 };
35165 this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);
35166 };
35167 AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {
35168 var _this = this;
35169 if (!this._pendingRead) {
35170 return undefined;
35171 }
35172 var afterRead = function () { return _this._finishPendingRead(); };
35173 return this._pendingRead.then(afterRead, afterRead);
35174 };
35175 return AbstractWrappingReadableStreamSource;
35176}());
35177var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {
35178 __extends(WrappingReadableStreamDefaultSource, _super);
35179 function WrappingReadableStreamDefaultSource() {
35180 return _super !== null && _super.apply(this, arguments) || this;
35181 }
35182 WrappingReadableStreamDefaultSource.prototype.pull = function () {
35183 return this._pullWithDefaultReader();
35184 };
35185 return WrappingReadableStreamDefaultSource;
35186}(AbstractWrappingReadableStreamSource));
35187function toUint8Array(view) {
35188 return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
35189}
35190function copyArrayBufferView(from, to) {
35191 var fromArray = toUint8Array(from);
35192 var toArray = toUint8Array(to);
35193 toArray.set(fromArray, 0);
35194}
35195var WrappingReadableByteStreamSource = /** @class */ (function (_super) {
35196 __extends(WrappingReadableByteStreamSource, _super);
35197 function WrappingReadableByteStreamSource(underlyingStream) {
35198 var _this = this;
35199 var supportsByob = supportsByobReader(underlyingStream);
35200 _this = _super.call(this, underlyingStream) || this;
35201 _this._supportsByob = supportsByob;
35202 return _this;
35203 }
35204 Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", {
35205 get: function () {
35206 return 'bytes';
35207 },
35208 enumerable: false,
35209 configurable: true
35210 });
35211 WrappingReadableByteStreamSource.prototype._attachByobReader = function () {
35212 if (this._readerMode === "byob" /* BYOB */) {
35213 return;
35214 }
35215 assert$1(this._supportsByob);
35216 this._detachReader();
35217 var reader = this._underlyingStream.getReader({ mode: 'byob' });
35218 this._readerMode = "byob" /* BYOB */;
35219 this._attachReader(reader);
35220 };
35221 WrappingReadableByteStreamSource.prototype.pull = function () {
35222 if (this._supportsByob) {
35223 var byobRequest = this._readableStreamController.byobRequest;
35224 if (byobRequest) {
35225 return this._pullWithByobRequest(byobRequest);
35226 }
35227 }
35228 return this._pullWithDefaultReader();
35229 };
35230 WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {
35231 var _this = this;
35232 this._attachByobReader();
35233 // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly
35234 // create a separate buffer to read into, then copy that to byobRequest.view
35235 var buffer = new Uint8Array(byobRequest.view.byteLength);
35236 // TODO Backpressure?
35237 var read = this._underlyingReader.read(buffer)
35238 .then(function (result) {
35239 _this._readableStreamController;
35240 if (result.done) {
35241 _this._tryClose();
35242 byobRequest.respond(0);
35243 }
35244 else {
35245 copyArrayBufferView(result.value, byobRequest.view);
35246 byobRequest.respond(result.value.byteLength);
35247 }
35248 });
35249 this._setPendingRead(read);
35250 return read;
35251 };
35252 return WrappingReadableByteStreamSource;
35253}(AbstractWrappingReadableStreamSource));
35254
35255function createWritableStreamWrapper(ctor) {
35256 assert$1(isWritableStreamConstructor(ctor));
35257 return function (writable) {
35258 if (writable.constructor === ctor) {
35259 return writable;
35260 }
35261 var sink = createWrappingWritableSink(writable);
35262 return new ctor(sink);
35263 };
35264}
35265function createWrappingWritableSink(writable) {
35266 assert$1(isWritableStream(writable));
35267 assert$1(writable.locked === false);
35268 var writer = writable.getWriter();
35269 return new WrappingWritableStreamSink(writer);
35270}
35271var WrappingWritableStreamSink = /** @class */ (function () {
35272 function WrappingWritableStreamSink(underlyingWriter) {
35273 var _this = this;
35274 this._writableStreamController = undefined;
35275 this._pendingWrite = undefined;
35276 this._state = "writable" /* WRITABLE */;
35277 this._storedError = undefined;
35278 this._underlyingWriter = underlyingWriter;
35279 this._errorPromise = new Promise(function (resolve, reject) {
35280 _this._errorPromiseReject = reject;
35281 });
35282 this._errorPromise.catch(noop$1);
35283 }
35284 WrappingWritableStreamSink.prototype.start = function (controller) {
35285 var _this = this;
35286 this._writableStreamController = controller;
35287 this._underlyingWriter.closed
35288 .then(function () {
35289 _this._state = "closed" /* CLOSED */;
35290 })
35291 .catch(function (reason) { return _this._finishErroring(reason); });
35292 };
35293 WrappingWritableStreamSink.prototype.write = function (chunk) {
35294 var _this = this;
35295 var writer = this._underlyingWriter;
35296 // Detect past errors
35297 if (writer.desiredSize === null) {
35298 return writer.ready;
35299 }
35300 var writeRequest = writer.write(chunk);
35301 // Detect future errors
35302 writeRequest.catch(function (reason) { return _this._finishErroring(reason); });
35303 writer.ready.catch(function (reason) { return _this._startErroring(reason); });
35304 // Reject write when errored
35305 var write = Promise.race([writeRequest, this._errorPromise]);
35306 this._setPendingWrite(write);
35307 return write;
35308 };
35309 WrappingWritableStreamSink.prototype.close = function () {
35310 var _this = this;
35311 if (this._pendingWrite === undefined) {
35312 return this._underlyingWriter.close();
35313 }
35314 return this._finishPendingWrite().then(function () { return _this.close(); });
35315 };
35316 WrappingWritableStreamSink.prototype.abort = function (reason) {
35317 if (this._state === "errored" /* ERRORED */) {
35318 return undefined;
35319 }
35320 var writer = this._underlyingWriter;
35321 return writer.abort(reason);
35322 };
35323 WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {
35324 var _this = this;
35325 var pendingWrite;
35326 var finishWrite = function () {
35327 if (_this._pendingWrite === pendingWrite) {
35328 _this._pendingWrite = undefined;
35329 }
35330 };
35331 this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);
35332 };
35333 WrappingWritableStreamSink.prototype._finishPendingWrite = function () {
35334 var _this = this;
35335 if (this._pendingWrite === undefined) {
35336 return Promise.resolve();
35337 }
35338 var afterWrite = function () { return _this._finishPendingWrite(); };
35339 return this._pendingWrite.then(afterWrite, afterWrite);
35340 };
35341 WrappingWritableStreamSink.prototype._startErroring = function (reason) {
35342 var _this = this;
35343 if (this._state === "writable" /* WRITABLE */) {
35344 this._state = "erroring" /* ERRORING */;
35345 this._storedError = reason;
35346 var afterWrite = function () { return _this._finishErroring(reason); };
35347 if (this._pendingWrite === undefined) {
35348 afterWrite();
35349 }
35350 else {
35351 this._finishPendingWrite().then(afterWrite, afterWrite);
35352 }
35353 this._writableStreamController.error(reason);
35354 }
35355 };
35356 WrappingWritableStreamSink.prototype._finishErroring = function (reason) {
35357 if (this._state === "writable" /* WRITABLE */) {
35358 this._startErroring(reason);
35359 }
35360 if (this._state === "erroring" /* ERRORING */) {
35361 this._state = "errored" /* ERRORED */;
35362 this._errorPromiseReject(this._storedError);
35363 }
35364 };
35365 return WrappingWritableStreamSink;
35366}());
35367
35368function createTransformStreamWrapper(ctor) {
35369 assert$1(isTransformStreamConstructor(ctor));
35370 return function (transform) {
35371 if (transform.constructor === ctor) {
35372 return transform;
35373 }
35374 var transformer = createWrappingTransformer(transform);
35375 return new ctor(transformer);
35376 };
35377}
35378function createWrappingTransformer(transform) {
35379 assert$1(isTransformStream(transform));
35380 var readable = transform.readable, writable = transform.writable;
35381 assert$1(readable.locked === false);
35382 assert$1(writable.locked === false);
35383 var reader = readable.getReader();
35384 var writer;
35385 try {
35386 writer = writable.getWriter();
35387 }
35388 catch (e) {
35389 reader.releaseLock(); // do not leak reader
35390 throw e;
35391 }
35392 return new WrappingTransformStreamTransformer(reader, writer);
35393}
35394var WrappingTransformStreamTransformer = /** @class */ (function () {
35395 function WrappingTransformStreamTransformer(reader, writer) {
35396 var _this = this;
35397 this._transformStreamController = undefined;
35398 this._onRead = function (result) {
35399 if (result.done) {
35400 return;
35401 }
35402 _this._transformStreamController.enqueue(result.value);
35403 return _this._reader.read().then(_this._onRead);
35404 };
35405 this._onError = function (reason) {
35406 _this._flushReject(reason);
35407 _this._transformStreamController.error(reason);
35408 _this._reader.cancel(reason).catch(noop$1);
35409 _this._writer.abort(reason).catch(noop$1);
35410 };
35411 this._onTerminate = function () {
35412 _this._flushResolve();
35413 _this._transformStreamController.terminate();
35414 var error = new TypeError('TransformStream terminated');
35415 _this._writer.abort(error).catch(noop$1);
35416 };
35417 this._reader = reader;
35418 this._writer = writer;
35419 this._flushPromise = new Promise(function (resolve, reject) {
35420 _this._flushResolve = resolve;
35421 _this._flushReject = reject;
35422 });
35423 }
35424 WrappingTransformStreamTransformer.prototype.start = function (controller) {
35425 this._transformStreamController = controller;
35426 this._reader.read()
35427 .then(this._onRead)
35428 .then(this._onTerminate, this._onError);
35429 var readerClosed = this._reader.closed;
35430 if (readerClosed) {
35431 readerClosed
35432 .then(this._onTerminate, this._onError);
35433 }
35434 };
35435 WrappingTransformStreamTransformer.prototype.transform = function (chunk) {
35436 return this._writer.write(chunk);
35437 };
35438 WrappingTransformStreamTransformer.prototype.flush = function () {
35439 var _this = this;
35440 return this._writer.close()
35441 .then(function () { return _this._flushPromise; });
35442 };
35443 return WrappingTransformStreamTransformer;
35444}());
35445
35446var webStreamsAdapter = /*#__PURE__*/Object.freeze({
35447 __proto__: null,
35448 createReadableStreamWrapper: createReadableStreamWrapper,
35449 createTransformStreamWrapper: createTransformStreamWrapper,
35450 createWrappingReadableSource: createWrappingReadableSource,
35451 createWrappingTransformer: createWrappingTransformer,
35452 createWrappingWritableSink: createWrappingWritableSink,
35453 createWritableStreamWrapper: createWritableStreamWrapper
35454});
35455
35456var bn = createCommonjsModule(function (module) {
35457(function (module, exports) {
35458
35459 // Utils
35460 function assert (val, msg) {
35461 if (!val) throw new Error(msg || 'Assertion failed');
35462 }
35463
35464 // Could use `inherits` module, but don't want to move from single file
35465 // architecture yet.
35466 function inherits (ctor, superCtor) {
35467 ctor.super_ = superCtor;
35468 var TempCtor = function () {};
35469 TempCtor.prototype = superCtor.prototype;
35470 ctor.prototype = new TempCtor();
35471 ctor.prototype.constructor = ctor;
35472 }
35473
35474 // BN
35475
35476 function BN (number, base, endian) {
35477 if (BN.isBN(number)) {
35478 return number;
35479 }
35480
35481 this.negative = 0;
35482 this.words = null;
35483 this.length = 0;
35484
35485 // Reduction context
35486 this.red = null;
35487
35488 if (number !== null) {
35489 if (base === 'le' || base === 'be') {
35490 endian = base;
35491 base = 10;
35492 }
35493
35494 this._init(number || 0, base || 10, endian || 'be');
35495 }
35496 }
35497 if (typeof module === 'object') {
35498 module.exports = BN;
35499 } else {
35500 exports.BN = BN;
35501 }
35502
35503 BN.BN = BN;
35504 BN.wordSize = 26;
35505
35506 var Buffer;
35507 try {
35508 Buffer = buffer__default['default'].Buffer;
35509 } catch (e) {
35510 }
35511
35512 BN.isBN = function isBN (num) {
35513 if (num instanceof BN) {
35514 return true;
35515 }
35516
35517 return num !== null && typeof num === 'object' &&
35518 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
35519 };
35520
35521 BN.max = function max (left, right) {
35522 if (left.cmp(right) > 0) return left;
35523 return right;
35524 };
35525
35526 BN.min = function min (left, right) {
35527 if (left.cmp(right) < 0) return left;
35528 return right;
35529 };
35530
35531 BN.prototype._init = function init (number, base, endian) {
35532 if (typeof number === 'number') {
35533 return this._initNumber(number, base, endian);
35534 }
35535
35536 if (typeof number === 'object') {
35537 return this._initArray(number, base, endian);
35538 }
35539
35540 if (base === 'hex') {
35541 base = 16;
35542 }
35543 assert(base === (base | 0) && base >= 2 && base <= 36);
35544
35545 number = number.toString().replace(/\s+/g, '');
35546 var start = 0;
35547 if (number[0] === '-') {
35548 start++;
35549 }
35550
35551 if (base === 16) {
35552 this._parseHex(number, start);
35553 } else {
35554 this._parseBase(number, base, start);
35555 }
35556
35557 if (number[0] === '-') {
35558 this.negative = 1;
35559 }
35560
35561 this.strip();
35562
35563 if (endian !== 'le') return;
35564
35565 this._initArray(this.toArray(), base, endian);
35566 };
35567
35568 BN.prototype._initNumber = function _initNumber (number, base, endian) {
35569 if (number < 0) {
35570 this.negative = 1;
35571 number = -number;
35572 }
35573 if (number < 0x4000000) {
35574 this.words = [ number & 0x3ffffff ];
35575 this.length = 1;
35576 } else if (number < 0x10000000000000) {
35577 this.words = [
35578 number & 0x3ffffff,
35579 (number / 0x4000000) & 0x3ffffff
35580 ];
35581 this.length = 2;
35582 } else {
35583 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
35584 this.words = [
35585 number & 0x3ffffff,
35586 (number / 0x4000000) & 0x3ffffff,
35587 1
35588 ];
35589 this.length = 3;
35590 }
35591
35592 if (endian !== 'le') return;
35593
35594 // Reverse the bytes
35595 this._initArray(this.toArray(), base, endian);
35596 };
35597
35598 BN.prototype._initArray = function _initArray (number, base, endian) {
35599 // Perhaps a Uint8Array
35600 assert(typeof number.length === 'number');
35601 if (number.length <= 0) {
35602 this.words = [ 0 ];
35603 this.length = 1;
35604 return this;
35605 }
35606
35607 this.length = Math.ceil(number.length / 3);
35608 this.words = new Array(this.length);
35609 for (var i = 0; i < this.length; i++) {
35610 this.words[i] = 0;
35611 }
35612
35613 var j, w;
35614 var off = 0;
35615 if (endian === 'be') {
35616 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
35617 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
35618 this.words[j] |= (w << off) & 0x3ffffff;
35619 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35620 off += 24;
35621 if (off >= 26) {
35622 off -= 26;
35623 j++;
35624 }
35625 }
35626 } else if (endian === 'le') {
35627 for (i = 0, j = 0; i < number.length; i += 3) {
35628 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
35629 this.words[j] |= (w << off) & 0x3ffffff;
35630 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35631 off += 24;
35632 if (off >= 26) {
35633 off -= 26;
35634 j++;
35635 }
35636 }
35637 }
35638 return this.strip();
35639 };
35640
35641 function parseHex (str, start, end) {
35642 var r = 0;
35643 var len = Math.min(str.length, end);
35644 for (var i = start; i < len; i++) {
35645 var c = str.charCodeAt(i) - 48;
35646
35647 r <<= 4;
35648
35649 // 'a' - 'f'
35650 if (c >= 49 && c <= 54) {
35651 r |= c - 49 + 0xa;
35652
35653 // 'A' - 'F'
35654 } else if (c >= 17 && c <= 22) {
35655 r |= c - 17 + 0xa;
35656
35657 // '0' - '9'
35658 } else {
35659 r |= c & 0xf;
35660 }
35661 }
35662 return r;
35663 }
35664
35665 BN.prototype._parseHex = function _parseHex (number, start) {
35666 // Create possibly bigger array to ensure that it fits the number
35667 this.length = Math.ceil((number.length - start) / 6);
35668 this.words = new Array(this.length);
35669 for (var i = 0; i < this.length; i++) {
35670 this.words[i] = 0;
35671 }
35672
35673 var j, w;
35674 // Scan 24-bit chunks and add them to the number
35675 var off = 0;
35676 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
35677 w = parseHex(number, i, i + 6);
35678 this.words[j] |= (w << off) & 0x3ffffff;
35679 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
35680 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35681 off += 24;
35682 if (off >= 26) {
35683 off -= 26;
35684 j++;
35685 }
35686 }
35687 if (i + 6 !== start) {
35688 w = parseHex(number, start, i + 6);
35689 this.words[j] |= (w << off) & 0x3ffffff;
35690 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35691 }
35692 this.strip();
35693 };
35694
35695 function parseBase (str, start, end, mul) {
35696 var r = 0;
35697 var len = Math.min(str.length, end);
35698 for (var i = start; i < len; i++) {
35699 var c = str.charCodeAt(i) - 48;
35700
35701 r *= mul;
35702
35703 // 'a'
35704 if (c >= 49) {
35705 r += c - 49 + 0xa;
35706
35707 // 'A'
35708 } else if (c >= 17) {
35709 r += c - 17 + 0xa;
35710
35711 // '0' - '9'
35712 } else {
35713 r += c;
35714 }
35715 }
35716 return r;
35717 }
35718
35719 BN.prototype._parseBase = function _parseBase (number, base, start) {
35720 // Initialize as zero
35721 this.words = [ 0 ];
35722 this.length = 1;
35723
35724 // Find length of limb in base
35725 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
35726 limbLen++;
35727 }
35728 limbLen--;
35729 limbPow = (limbPow / base) | 0;
35730
35731 var total = number.length - start;
35732 var mod = total % limbLen;
35733 var end = Math.min(total, total - mod) + start;
35734
35735 var word = 0;
35736 for (var i = start; i < end; i += limbLen) {
35737 word = parseBase(number, i, i + limbLen, base);
35738
35739 this.imuln(limbPow);
35740 if (this.words[0] + word < 0x4000000) {
35741 this.words[0] += word;
35742 } else {
35743 this._iaddn(word);
35744 }
35745 }
35746
35747 if (mod !== 0) {
35748 var pow = 1;
35749 word = parseBase(number, i, number.length, base);
35750
35751 for (i = 0; i < mod; i++) {
35752 pow *= base;
35753 }
35754
35755 this.imuln(pow);
35756 if (this.words[0] + word < 0x4000000) {
35757 this.words[0] += word;
35758 } else {
35759 this._iaddn(word);
35760 }
35761 }
35762 };
35763
35764 BN.prototype.copy = function copy (dest) {
35765 dest.words = new Array(this.length);
35766 for (var i = 0; i < this.length; i++) {
35767 dest.words[i] = this.words[i];
35768 }
35769 dest.length = this.length;
35770 dest.negative = this.negative;
35771 dest.red = this.red;
35772 };
35773
35774 BN.prototype.clone = function clone () {
35775 var r = new BN(null);
35776 this.copy(r);
35777 return r;
35778 };
35779
35780 BN.prototype._expand = function _expand (size) {
35781 while (this.length < size) {
35782 this.words[this.length++] = 0;
35783 }
35784 return this;
35785 };
35786
35787 // Remove leading `0` from `this`
35788 BN.prototype.strip = function strip () {
35789 while (this.length > 1 && this.words[this.length - 1] === 0) {
35790 this.length--;
35791 }
35792 return this._normSign();
35793 };
35794
35795 BN.prototype._normSign = function _normSign () {
35796 // -0 = 0
35797 if (this.length === 1 && this.words[0] === 0) {
35798 this.negative = 0;
35799 }
35800 return this;
35801 };
35802
35803 BN.prototype.inspect = function inspect () {
35804 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
35805 };
35806
35807 /*
35808
35809 var zeros = [];
35810 var groupSizes = [];
35811 var groupBases = [];
35812
35813 var s = '';
35814 var i = -1;
35815 while (++i < BN.wordSize) {
35816 zeros[i] = s;
35817 s += '0';
35818 }
35819 groupSizes[0] = 0;
35820 groupSizes[1] = 0;
35821 groupBases[0] = 0;
35822 groupBases[1] = 0;
35823 var base = 2 - 1;
35824 while (++base < 36 + 1) {
35825 var groupSize = 0;
35826 var groupBase = 1;
35827 while (groupBase < (1 << BN.wordSize) / base) {
35828 groupBase *= base;
35829 groupSize += 1;
35830 }
35831 groupSizes[base] = groupSize;
35832 groupBases[base] = groupBase;
35833 }
35834
35835 */
35836
35837 var zeros = [
35838 '',
35839 '0',
35840 '00',
35841 '000',
35842 '0000',
35843 '00000',
35844 '000000',
35845 '0000000',
35846 '00000000',
35847 '000000000',
35848 '0000000000',
35849 '00000000000',
35850 '000000000000',
35851 '0000000000000',
35852 '00000000000000',
35853 '000000000000000',
35854 '0000000000000000',
35855 '00000000000000000',
35856 '000000000000000000',
35857 '0000000000000000000',
35858 '00000000000000000000',
35859 '000000000000000000000',
35860 '0000000000000000000000',
35861 '00000000000000000000000',
35862 '000000000000000000000000',
35863 '0000000000000000000000000'
35864 ];
35865
35866 var groupSizes = [
35867 0, 0,
35868 25, 16, 12, 11, 10, 9, 8,
35869 8, 7, 7, 7, 7, 6, 6,
35870 6, 6, 6, 6, 6, 5, 5,
35871 5, 5, 5, 5, 5, 5, 5,
35872 5, 5, 5, 5, 5, 5, 5
35873 ];
35874
35875 var groupBases = [
35876 0, 0,
35877 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
35878 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
35879 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
35880 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
35881 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
35882 ];
35883
35884 BN.prototype.toString = function toString (base, padding) {
35885 base = base || 10;
35886 padding = padding | 0 || 1;
35887
35888 var out;
35889 if (base === 16 || base === 'hex') {
35890 out = '';
35891 var off = 0;
35892 var carry = 0;
35893 for (var i = 0; i < this.length; i++) {
35894 var w = this.words[i];
35895 var word = (((w << off) | carry) & 0xffffff).toString(16);
35896 carry = (w >>> (24 - off)) & 0xffffff;
35897 if (carry !== 0 || i !== this.length - 1) {
35898 out = zeros[6 - word.length] + word + out;
35899 } else {
35900 out = word + out;
35901 }
35902 off += 2;
35903 if (off >= 26) {
35904 off -= 26;
35905 i--;
35906 }
35907 }
35908 if (carry !== 0) {
35909 out = carry.toString(16) + out;
35910 }
35911 while (out.length % padding !== 0) {
35912 out = '0' + out;
35913 }
35914 if (this.negative !== 0) {
35915 out = '-' + out;
35916 }
35917 return out;
35918 }
35919
35920 if (base === (base | 0) && base >= 2 && base <= 36) {
35921 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
35922 var groupSize = groupSizes[base];
35923 // var groupBase = Math.pow(base, groupSize);
35924 var groupBase = groupBases[base];
35925 out = '';
35926 var c = this.clone();
35927 c.negative = 0;
35928 while (!c.isZero()) {
35929 var r = c.modn(groupBase).toString(base);
35930 c = c.idivn(groupBase);
35931
35932 if (!c.isZero()) {
35933 out = zeros[groupSize - r.length] + r + out;
35934 } else {
35935 out = r + out;
35936 }
35937 }
35938 if (this.isZero()) {
35939 out = '0' + out;
35940 }
35941 while (out.length % padding !== 0) {
35942 out = '0' + out;
35943 }
35944 if (this.negative !== 0) {
35945 out = '-' + out;
35946 }
35947 return out;
35948 }
35949
35950 assert(false, 'Base should be between 2 and 36');
35951 };
35952
35953 BN.prototype.toNumber = function toNumber () {
35954 var ret = this.words[0];
35955 if (this.length === 2) {
35956 ret += this.words[1] * 0x4000000;
35957 } else if (this.length === 3 && this.words[2] === 0x01) {
35958 // NOTE: at this stage it is known that the top bit is set
35959 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
35960 } else if (this.length > 2) {
35961 assert(false, 'Number can only safely store up to 53 bits');
35962 }
35963 return (this.negative !== 0) ? -ret : ret;
35964 };
35965
35966 BN.prototype.toJSON = function toJSON () {
35967 return this.toString(16);
35968 };
35969
35970 BN.prototype.toBuffer = function toBuffer (endian, length) {
35971 assert(typeof Buffer !== 'undefined');
35972 return this.toArrayLike(Buffer, endian, length);
35973 };
35974
35975 BN.prototype.toArray = function toArray (endian, length) {
35976 return this.toArrayLike(Array, endian, length);
35977 };
35978
35979 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
35980 var byteLength = this.byteLength();
35981 var reqLength = length || Math.max(1, byteLength);
35982 assert(byteLength <= reqLength, 'byte array longer than desired length');
35983 assert(reqLength > 0, 'Requested array length <= 0');
35984
35985 this.strip();
35986 var littleEndian = endian === 'le';
35987 var res = new ArrayType(reqLength);
35988
35989 var b, i;
35990 var q = this.clone();
35991 if (!littleEndian) {
35992 // Assume big-endian
35993 for (i = 0; i < reqLength - byteLength; i++) {
35994 res[i] = 0;
35995 }
35996
35997 for (i = 0; !q.isZero(); i++) {
35998 b = q.andln(0xff);
35999 q.iushrn(8);
36000
36001 res[reqLength - i - 1] = b;
36002 }
36003 } else {
36004 for (i = 0; !q.isZero(); i++) {
36005 b = q.andln(0xff);
36006 q.iushrn(8);
36007
36008 res[i] = b;
36009 }
36010
36011 for (; i < reqLength; i++) {
36012 res[i] = 0;
36013 }
36014 }
36015
36016 return res;
36017 };
36018
36019 if (Math.clz32) {
36020 BN.prototype._countBits = function _countBits (w) {
36021 return 32 - Math.clz32(w);
36022 };
36023 } else {
36024 BN.prototype._countBits = function _countBits (w) {
36025 var t = w;
36026 var r = 0;
36027 if (t >= 0x1000) {
36028 r += 13;
36029 t >>>= 13;
36030 }
36031 if (t >= 0x40) {
36032 r += 7;
36033 t >>>= 7;
36034 }
36035 if (t >= 0x8) {
36036 r += 4;
36037 t >>>= 4;
36038 }
36039 if (t >= 0x02) {
36040 r += 2;
36041 t >>>= 2;
36042 }
36043 return r + t;
36044 };
36045 }
36046
36047 BN.prototype._zeroBits = function _zeroBits (w) {
36048 // Short-cut
36049 if (w === 0) return 26;
36050
36051 var t = w;
36052 var r = 0;
36053 if ((t & 0x1fff) === 0) {
36054 r += 13;
36055 t >>>= 13;
36056 }
36057 if ((t & 0x7f) === 0) {
36058 r += 7;
36059 t >>>= 7;
36060 }
36061 if ((t & 0xf) === 0) {
36062 r += 4;
36063 t >>>= 4;
36064 }
36065 if ((t & 0x3) === 0) {
36066 r += 2;
36067 t >>>= 2;
36068 }
36069 if ((t & 0x1) === 0) {
36070 r++;
36071 }
36072 return r;
36073 };
36074
36075 // Return number of used bits in a BN
36076 BN.prototype.bitLength = function bitLength () {
36077 var w = this.words[this.length - 1];
36078 var hi = this._countBits(w);
36079 return (this.length - 1) * 26 + hi;
36080 };
36081
36082 function toBitArray (num) {
36083 var w = new Array(num.bitLength());
36084
36085 for (var bit = 0; bit < w.length; bit++) {
36086 var off = (bit / 26) | 0;
36087 var wbit = bit % 26;
36088
36089 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
36090 }
36091
36092 return w;
36093 }
36094
36095 // Number of trailing zero bits
36096 BN.prototype.zeroBits = function zeroBits () {
36097 if (this.isZero()) return 0;
36098
36099 var r = 0;
36100 for (var i = 0; i < this.length; i++) {
36101 var b = this._zeroBits(this.words[i]);
36102 r += b;
36103 if (b !== 26) break;
36104 }
36105 return r;
36106 };
36107
36108 BN.prototype.byteLength = function byteLength () {
36109 return Math.ceil(this.bitLength() / 8);
36110 };
36111
36112 BN.prototype.toTwos = function toTwos (width) {
36113 if (this.negative !== 0) {
36114 return this.abs().inotn(width).iaddn(1);
36115 }
36116 return this.clone();
36117 };
36118
36119 BN.prototype.fromTwos = function fromTwos (width) {
36120 if (this.testn(width - 1)) {
36121 return this.notn(width).iaddn(1).ineg();
36122 }
36123 return this.clone();
36124 };
36125
36126 BN.prototype.isNeg = function isNeg () {
36127 return this.negative !== 0;
36128 };
36129
36130 // Return negative clone of `this`
36131 BN.prototype.neg = function neg () {
36132 return this.clone().ineg();
36133 };
36134
36135 BN.prototype.ineg = function ineg () {
36136 if (!this.isZero()) {
36137 this.negative ^= 1;
36138 }
36139
36140 return this;
36141 };
36142
36143 // Or `num` with `this` in-place
36144 BN.prototype.iuor = function iuor (num) {
36145 while (this.length < num.length) {
36146 this.words[this.length++] = 0;
36147 }
36148
36149 for (var i = 0; i < num.length; i++) {
36150 this.words[i] = this.words[i] | num.words[i];
36151 }
36152
36153 return this.strip();
36154 };
36155
36156 BN.prototype.ior = function ior (num) {
36157 assert((this.negative | num.negative) === 0);
36158 return this.iuor(num);
36159 };
36160
36161 // Or `num` with `this`
36162 BN.prototype.or = function or (num) {
36163 if (this.length > num.length) return this.clone().ior(num);
36164 return num.clone().ior(this);
36165 };
36166
36167 BN.prototype.uor = function uor (num) {
36168 if (this.length > num.length) return this.clone().iuor(num);
36169 return num.clone().iuor(this);
36170 };
36171
36172 // And `num` with `this` in-place
36173 BN.prototype.iuand = function iuand (num) {
36174 // b = min-length(num, this)
36175 var b;
36176 if (this.length > num.length) {
36177 b = num;
36178 } else {
36179 b = this;
36180 }
36181
36182 for (var i = 0; i < b.length; i++) {
36183 this.words[i] = this.words[i] & num.words[i];
36184 }
36185
36186 this.length = b.length;
36187
36188 return this.strip();
36189 };
36190
36191 BN.prototype.iand = function iand (num) {
36192 assert((this.negative | num.negative) === 0);
36193 return this.iuand(num);
36194 };
36195
36196 // And `num` with `this`
36197 BN.prototype.and = function and (num) {
36198 if (this.length > num.length) return this.clone().iand(num);
36199 return num.clone().iand(this);
36200 };
36201
36202 BN.prototype.uand = function uand (num) {
36203 if (this.length > num.length) return this.clone().iuand(num);
36204 return num.clone().iuand(this);
36205 };
36206
36207 // Xor `num` with `this` in-place
36208 BN.prototype.iuxor = function iuxor (num) {
36209 // a.length > b.length
36210 var a;
36211 var b;
36212 if (this.length > num.length) {
36213 a = this;
36214 b = num;
36215 } else {
36216 a = num;
36217 b = this;
36218 }
36219
36220 for (var i = 0; i < b.length; i++) {
36221 this.words[i] = a.words[i] ^ b.words[i];
36222 }
36223
36224 if (this !== a) {
36225 for (; i < a.length; i++) {
36226 this.words[i] = a.words[i];
36227 }
36228 }
36229
36230 this.length = a.length;
36231
36232 return this.strip();
36233 };
36234
36235 BN.prototype.ixor = function ixor (num) {
36236 assert((this.negative | num.negative) === 0);
36237 return this.iuxor(num);
36238 };
36239
36240 // Xor `num` with `this`
36241 BN.prototype.xor = function xor (num) {
36242 if (this.length > num.length) return this.clone().ixor(num);
36243 return num.clone().ixor(this);
36244 };
36245
36246 BN.prototype.uxor = function uxor (num) {
36247 if (this.length > num.length) return this.clone().iuxor(num);
36248 return num.clone().iuxor(this);
36249 };
36250
36251 // Not ``this`` with ``width`` bitwidth
36252 BN.prototype.inotn = function inotn (width) {
36253 assert(typeof width === 'number' && width >= 0);
36254
36255 var bytesNeeded = Math.ceil(width / 26) | 0;
36256 var bitsLeft = width % 26;
36257
36258 // Extend the buffer with leading zeroes
36259 this._expand(bytesNeeded);
36260
36261 if (bitsLeft > 0) {
36262 bytesNeeded--;
36263 }
36264
36265 // Handle complete words
36266 for (var i = 0; i < bytesNeeded; i++) {
36267 this.words[i] = ~this.words[i] & 0x3ffffff;
36268 }
36269
36270 // Handle the residue
36271 if (bitsLeft > 0) {
36272 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
36273 }
36274
36275 // And remove leading zeroes
36276 return this.strip();
36277 };
36278
36279 BN.prototype.notn = function notn (width) {
36280 return this.clone().inotn(width);
36281 };
36282
36283 // Set `bit` of `this`
36284 BN.prototype.setn = function setn (bit, val) {
36285 assert(typeof bit === 'number' && bit >= 0);
36286
36287 var off = (bit / 26) | 0;
36288 var wbit = bit % 26;
36289
36290 this._expand(off + 1);
36291
36292 if (val) {
36293 this.words[off] = this.words[off] | (1 << wbit);
36294 } else {
36295 this.words[off] = this.words[off] & ~(1 << wbit);
36296 }
36297
36298 return this.strip();
36299 };
36300
36301 // Add `num` to `this` in-place
36302 BN.prototype.iadd = function iadd (num) {
36303 var r;
36304
36305 // negative + positive
36306 if (this.negative !== 0 && num.negative === 0) {
36307 this.negative = 0;
36308 r = this.isub(num);
36309 this.negative ^= 1;
36310 return this._normSign();
36311
36312 // positive + negative
36313 } else if (this.negative === 0 && num.negative !== 0) {
36314 num.negative = 0;
36315 r = this.isub(num);
36316 num.negative = 1;
36317 return r._normSign();
36318 }
36319
36320 // a.length > b.length
36321 var a, b;
36322 if (this.length > num.length) {
36323 a = this;
36324 b = num;
36325 } else {
36326 a = num;
36327 b = this;
36328 }
36329
36330 var carry = 0;
36331 for (var i = 0; i < b.length; i++) {
36332 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
36333 this.words[i] = r & 0x3ffffff;
36334 carry = r >>> 26;
36335 }
36336 for (; carry !== 0 && i < a.length; i++) {
36337 r = (a.words[i] | 0) + carry;
36338 this.words[i] = r & 0x3ffffff;
36339 carry = r >>> 26;
36340 }
36341
36342 this.length = a.length;
36343 if (carry !== 0) {
36344 this.words[this.length] = carry;
36345 this.length++;
36346 // Copy the rest of the words
36347 } else if (a !== this) {
36348 for (; i < a.length; i++) {
36349 this.words[i] = a.words[i];
36350 }
36351 }
36352
36353 return this;
36354 };
36355
36356 // Add `num` to `this`
36357 BN.prototype.add = function add (num) {
36358 var res;
36359 if (num.negative !== 0 && this.negative === 0) {
36360 num.negative = 0;
36361 res = this.sub(num);
36362 num.negative ^= 1;
36363 return res;
36364 } else if (num.negative === 0 && this.negative !== 0) {
36365 this.negative = 0;
36366 res = num.sub(this);
36367 this.negative = 1;
36368 return res;
36369 }
36370
36371 if (this.length > num.length) return this.clone().iadd(num);
36372
36373 return num.clone().iadd(this);
36374 };
36375
36376 // Subtract `num` from `this` in-place
36377 BN.prototype.isub = function isub (num) {
36378 // this - (-num) = this + num
36379 if (num.negative !== 0) {
36380 num.negative = 0;
36381 var r = this.iadd(num);
36382 num.negative = 1;
36383 return r._normSign();
36384
36385 // -this - num = -(this + num)
36386 } else if (this.negative !== 0) {
36387 this.negative = 0;
36388 this.iadd(num);
36389 this.negative = 1;
36390 return this._normSign();
36391 }
36392
36393 // At this point both numbers are positive
36394 var cmp = this.cmp(num);
36395
36396 // Optimization - zeroify
36397 if (cmp === 0) {
36398 this.negative = 0;
36399 this.length = 1;
36400 this.words[0] = 0;
36401 return this;
36402 }
36403
36404 // a > b
36405 var a, b;
36406 if (cmp > 0) {
36407 a = this;
36408 b = num;
36409 } else {
36410 a = num;
36411 b = this;
36412 }
36413
36414 var carry = 0;
36415 for (var i = 0; i < b.length; i++) {
36416 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
36417 carry = r >> 26;
36418 this.words[i] = r & 0x3ffffff;
36419 }
36420 for (; carry !== 0 && i < a.length; i++) {
36421 r = (a.words[i] | 0) + carry;
36422 carry = r >> 26;
36423 this.words[i] = r & 0x3ffffff;
36424 }
36425
36426 // Copy rest of the words
36427 if (carry === 0 && i < a.length && a !== this) {
36428 for (; i < a.length; i++) {
36429 this.words[i] = a.words[i];
36430 }
36431 }
36432
36433 this.length = Math.max(this.length, i);
36434
36435 if (a !== this) {
36436 this.negative = 1;
36437 }
36438
36439 return this.strip();
36440 };
36441
36442 // Subtract `num` from `this`
36443 BN.prototype.sub = function sub (num) {
36444 return this.clone().isub(num);
36445 };
36446
36447 function smallMulTo (self, num, out) {
36448 out.negative = num.negative ^ self.negative;
36449 var len = (self.length + num.length) | 0;
36450 out.length = len;
36451 len = (len - 1) | 0;
36452
36453 // Peel one iteration (compiler can't do it, because of code complexity)
36454 var a = self.words[0] | 0;
36455 var b = num.words[0] | 0;
36456 var r = a * b;
36457
36458 var lo = r & 0x3ffffff;
36459 var carry = (r / 0x4000000) | 0;
36460 out.words[0] = lo;
36461
36462 for (var k = 1; k < len; k++) {
36463 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
36464 // note that ncarry could be >= 0x3ffffff
36465 var ncarry = carry >>> 26;
36466 var rword = carry & 0x3ffffff;
36467 var maxJ = Math.min(k, num.length - 1);
36468 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
36469 var i = (k - j) | 0;
36470 a = self.words[i] | 0;
36471 b = num.words[j] | 0;
36472 r = a * b + rword;
36473 ncarry += (r / 0x4000000) | 0;
36474 rword = r & 0x3ffffff;
36475 }
36476 out.words[k] = rword | 0;
36477 carry = ncarry | 0;
36478 }
36479 if (carry !== 0) {
36480 out.words[k] = carry | 0;
36481 } else {
36482 out.length--;
36483 }
36484
36485 return out.strip();
36486 }
36487
36488 // TODO(indutny): it may be reasonable to omit it for users who don't need
36489 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
36490 // multiplication (like elliptic secp256k1).
36491 var comb10MulTo = function comb10MulTo (self, num, out) {
36492 var a = self.words;
36493 var b = num.words;
36494 var o = out.words;
36495 var c = 0;
36496 var lo;
36497 var mid;
36498 var hi;
36499 var a0 = a[0] | 0;
36500 var al0 = a0 & 0x1fff;
36501 var ah0 = a0 >>> 13;
36502 var a1 = a[1] | 0;
36503 var al1 = a1 & 0x1fff;
36504 var ah1 = a1 >>> 13;
36505 var a2 = a[2] | 0;
36506 var al2 = a2 & 0x1fff;
36507 var ah2 = a2 >>> 13;
36508 var a3 = a[3] | 0;
36509 var al3 = a3 & 0x1fff;
36510 var ah3 = a3 >>> 13;
36511 var a4 = a[4] | 0;
36512 var al4 = a4 & 0x1fff;
36513 var ah4 = a4 >>> 13;
36514 var a5 = a[5] | 0;
36515 var al5 = a5 & 0x1fff;
36516 var ah5 = a5 >>> 13;
36517 var a6 = a[6] | 0;
36518 var al6 = a6 & 0x1fff;
36519 var ah6 = a6 >>> 13;
36520 var a7 = a[7] | 0;
36521 var al7 = a7 & 0x1fff;
36522 var ah7 = a7 >>> 13;
36523 var a8 = a[8] | 0;
36524 var al8 = a8 & 0x1fff;
36525 var ah8 = a8 >>> 13;
36526 var a9 = a[9] | 0;
36527 var al9 = a9 & 0x1fff;
36528 var ah9 = a9 >>> 13;
36529 var b0 = b[0] | 0;
36530 var bl0 = b0 & 0x1fff;
36531 var bh0 = b0 >>> 13;
36532 var b1 = b[1] | 0;
36533 var bl1 = b1 & 0x1fff;
36534 var bh1 = b1 >>> 13;
36535 var b2 = b[2] | 0;
36536 var bl2 = b2 & 0x1fff;
36537 var bh2 = b2 >>> 13;
36538 var b3 = b[3] | 0;
36539 var bl3 = b3 & 0x1fff;
36540 var bh3 = b3 >>> 13;
36541 var b4 = b[4] | 0;
36542 var bl4 = b4 & 0x1fff;
36543 var bh4 = b4 >>> 13;
36544 var b5 = b[5] | 0;
36545 var bl5 = b5 & 0x1fff;
36546 var bh5 = b5 >>> 13;
36547 var b6 = b[6] | 0;
36548 var bl6 = b6 & 0x1fff;
36549 var bh6 = b6 >>> 13;
36550 var b7 = b[7] | 0;
36551 var bl7 = b7 & 0x1fff;
36552 var bh7 = b7 >>> 13;
36553 var b8 = b[8] | 0;
36554 var bl8 = b8 & 0x1fff;
36555 var bh8 = b8 >>> 13;
36556 var b9 = b[9] | 0;
36557 var bl9 = b9 & 0x1fff;
36558 var bh9 = b9 >>> 13;
36559
36560 out.negative = self.negative ^ num.negative;
36561 out.length = 19;
36562 /* k = 0 */
36563 lo = Math.imul(al0, bl0);
36564 mid = Math.imul(al0, bh0);
36565 mid = (mid + Math.imul(ah0, bl0)) | 0;
36566 hi = Math.imul(ah0, bh0);
36567 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36568 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
36569 w0 &= 0x3ffffff;
36570 /* k = 1 */
36571 lo = Math.imul(al1, bl0);
36572 mid = Math.imul(al1, bh0);
36573 mid = (mid + Math.imul(ah1, bl0)) | 0;
36574 hi = Math.imul(ah1, bh0);
36575 lo = (lo + Math.imul(al0, bl1)) | 0;
36576 mid = (mid + Math.imul(al0, bh1)) | 0;
36577 mid = (mid + Math.imul(ah0, bl1)) | 0;
36578 hi = (hi + Math.imul(ah0, bh1)) | 0;
36579 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36580 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
36581 w1 &= 0x3ffffff;
36582 /* k = 2 */
36583 lo = Math.imul(al2, bl0);
36584 mid = Math.imul(al2, bh0);
36585 mid = (mid + Math.imul(ah2, bl0)) | 0;
36586 hi = Math.imul(ah2, bh0);
36587 lo = (lo + Math.imul(al1, bl1)) | 0;
36588 mid = (mid + Math.imul(al1, bh1)) | 0;
36589 mid = (mid + Math.imul(ah1, bl1)) | 0;
36590 hi = (hi + Math.imul(ah1, bh1)) | 0;
36591 lo = (lo + Math.imul(al0, bl2)) | 0;
36592 mid = (mid + Math.imul(al0, bh2)) | 0;
36593 mid = (mid + Math.imul(ah0, bl2)) | 0;
36594 hi = (hi + Math.imul(ah0, bh2)) | 0;
36595 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36596 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
36597 w2 &= 0x3ffffff;
36598 /* k = 3 */
36599 lo = Math.imul(al3, bl0);
36600 mid = Math.imul(al3, bh0);
36601 mid = (mid + Math.imul(ah3, bl0)) | 0;
36602 hi = Math.imul(ah3, bh0);
36603 lo = (lo + Math.imul(al2, bl1)) | 0;
36604 mid = (mid + Math.imul(al2, bh1)) | 0;
36605 mid = (mid + Math.imul(ah2, bl1)) | 0;
36606 hi = (hi + Math.imul(ah2, bh1)) | 0;
36607 lo = (lo + Math.imul(al1, bl2)) | 0;
36608 mid = (mid + Math.imul(al1, bh2)) | 0;
36609 mid = (mid + Math.imul(ah1, bl2)) | 0;
36610 hi = (hi + Math.imul(ah1, bh2)) | 0;
36611 lo = (lo + Math.imul(al0, bl3)) | 0;
36612 mid = (mid + Math.imul(al0, bh3)) | 0;
36613 mid = (mid + Math.imul(ah0, bl3)) | 0;
36614 hi = (hi + Math.imul(ah0, bh3)) | 0;
36615 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36616 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
36617 w3 &= 0x3ffffff;
36618 /* k = 4 */
36619 lo = Math.imul(al4, bl0);
36620 mid = Math.imul(al4, bh0);
36621 mid = (mid + Math.imul(ah4, bl0)) | 0;
36622 hi = Math.imul(ah4, bh0);
36623 lo = (lo + Math.imul(al3, bl1)) | 0;
36624 mid = (mid + Math.imul(al3, bh1)) | 0;
36625 mid = (mid + Math.imul(ah3, bl1)) | 0;
36626 hi = (hi + Math.imul(ah3, bh1)) | 0;
36627 lo = (lo + Math.imul(al2, bl2)) | 0;
36628 mid = (mid + Math.imul(al2, bh2)) | 0;
36629 mid = (mid + Math.imul(ah2, bl2)) | 0;
36630 hi = (hi + Math.imul(ah2, bh2)) | 0;
36631 lo = (lo + Math.imul(al1, bl3)) | 0;
36632 mid = (mid + Math.imul(al1, bh3)) | 0;
36633 mid = (mid + Math.imul(ah1, bl3)) | 0;
36634 hi = (hi + Math.imul(ah1, bh3)) | 0;
36635 lo = (lo + Math.imul(al0, bl4)) | 0;
36636 mid = (mid + Math.imul(al0, bh4)) | 0;
36637 mid = (mid + Math.imul(ah0, bl4)) | 0;
36638 hi = (hi + Math.imul(ah0, bh4)) | 0;
36639 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36640 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
36641 w4 &= 0x3ffffff;
36642 /* k = 5 */
36643 lo = Math.imul(al5, bl0);
36644 mid = Math.imul(al5, bh0);
36645 mid = (mid + Math.imul(ah5, bl0)) | 0;
36646 hi = Math.imul(ah5, bh0);
36647 lo = (lo + Math.imul(al4, bl1)) | 0;
36648 mid = (mid + Math.imul(al4, bh1)) | 0;
36649 mid = (mid + Math.imul(ah4, bl1)) | 0;
36650 hi = (hi + Math.imul(ah4, bh1)) | 0;
36651 lo = (lo + Math.imul(al3, bl2)) | 0;
36652 mid = (mid + Math.imul(al3, bh2)) | 0;
36653 mid = (mid + Math.imul(ah3, bl2)) | 0;
36654 hi = (hi + Math.imul(ah3, bh2)) | 0;
36655 lo = (lo + Math.imul(al2, bl3)) | 0;
36656 mid = (mid + Math.imul(al2, bh3)) | 0;
36657 mid = (mid + Math.imul(ah2, bl3)) | 0;
36658 hi = (hi + Math.imul(ah2, bh3)) | 0;
36659 lo = (lo + Math.imul(al1, bl4)) | 0;
36660 mid = (mid + Math.imul(al1, bh4)) | 0;
36661 mid = (mid + Math.imul(ah1, bl4)) | 0;
36662 hi = (hi + Math.imul(ah1, bh4)) | 0;
36663 lo = (lo + Math.imul(al0, bl5)) | 0;
36664 mid = (mid + Math.imul(al0, bh5)) | 0;
36665 mid = (mid + Math.imul(ah0, bl5)) | 0;
36666 hi = (hi + Math.imul(ah0, bh5)) | 0;
36667 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36668 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
36669 w5 &= 0x3ffffff;
36670 /* k = 6 */
36671 lo = Math.imul(al6, bl0);
36672 mid = Math.imul(al6, bh0);
36673 mid = (mid + Math.imul(ah6, bl0)) | 0;
36674 hi = Math.imul(ah6, bh0);
36675 lo = (lo + Math.imul(al5, bl1)) | 0;
36676 mid = (mid + Math.imul(al5, bh1)) | 0;
36677 mid = (mid + Math.imul(ah5, bl1)) | 0;
36678 hi = (hi + Math.imul(ah5, bh1)) | 0;
36679 lo = (lo + Math.imul(al4, bl2)) | 0;
36680 mid = (mid + Math.imul(al4, bh2)) | 0;
36681 mid = (mid + Math.imul(ah4, bl2)) | 0;
36682 hi = (hi + Math.imul(ah4, bh2)) | 0;
36683 lo = (lo + Math.imul(al3, bl3)) | 0;
36684 mid = (mid + Math.imul(al3, bh3)) | 0;
36685 mid = (mid + Math.imul(ah3, bl3)) | 0;
36686 hi = (hi + Math.imul(ah3, bh3)) | 0;
36687 lo = (lo + Math.imul(al2, bl4)) | 0;
36688 mid = (mid + Math.imul(al2, bh4)) | 0;
36689 mid = (mid + Math.imul(ah2, bl4)) | 0;
36690 hi = (hi + Math.imul(ah2, bh4)) | 0;
36691 lo = (lo + Math.imul(al1, bl5)) | 0;
36692 mid = (mid + Math.imul(al1, bh5)) | 0;
36693 mid = (mid + Math.imul(ah1, bl5)) | 0;
36694 hi = (hi + Math.imul(ah1, bh5)) | 0;
36695 lo = (lo + Math.imul(al0, bl6)) | 0;
36696 mid = (mid + Math.imul(al0, bh6)) | 0;
36697 mid = (mid + Math.imul(ah0, bl6)) | 0;
36698 hi = (hi + Math.imul(ah0, bh6)) | 0;
36699 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36700 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
36701 w6 &= 0x3ffffff;
36702 /* k = 7 */
36703 lo = Math.imul(al7, bl0);
36704 mid = Math.imul(al7, bh0);
36705 mid = (mid + Math.imul(ah7, bl0)) | 0;
36706 hi = Math.imul(ah7, bh0);
36707 lo = (lo + Math.imul(al6, bl1)) | 0;
36708 mid = (mid + Math.imul(al6, bh1)) | 0;
36709 mid = (mid + Math.imul(ah6, bl1)) | 0;
36710 hi = (hi + Math.imul(ah6, bh1)) | 0;
36711 lo = (lo + Math.imul(al5, bl2)) | 0;
36712 mid = (mid + Math.imul(al5, bh2)) | 0;
36713 mid = (mid + Math.imul(ah5, bl2)) | 0;
36714 hi = (hi + Math.imul(ah5, bh2)) | 0;
36715 lo = (lo + Math.imul(al4, bl3)) | 0;
36716 mid = (mid + Math.imul(al4, bh3)) | 0;
36717 mid = (mid + Math.imul(ah4, bl3)) | 0;
36718 hi = (hi + Math.imul(ah4, bh3)) | 0;
36719 lo = (lo + Math.imul(al3, bl4)) | 0;
36720 mid = (mid + Math.imul(al3, bh4)) | 0;
36721 mid = (mid + Math.imul(ah3, bl4)) | 0;
36722 hi = (hi + Math.imul(ah3, bh4)) | 0;
36723 lo = (lo + Math.imul(al2, bl5)) | 0;
36724 mid = (mid + Math.imul(al2, bh5)) | 0;
36725 mid = (mid + Math.imul(ah2, bl5)) | 0;
36726 hi = (hi + Math.imul(ah2, bh5)) | 0;
36727 lo = (lo + Math.imul(al1, bl6)) | 0;
36728 mid = (mid + Math.imul(al1, bh6)) | 0;
36729 mid = (mid + Math.imul(ah1, bl6)) | 0;
36730 hi = (hi + Math.imul(ah1, bh6)) | 0;
36731 lo = (lo + Math.imul(al0, bl7)) | 0;
36732 mid = (mid + Math.imul(al0, bh7)) | 0;
36733 mid = (mid + Math.imul(ah0, bl7)) | 0;
36734 hi = (hi + Math.imul(ah0, bh7)) | 0;
36735 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36736 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
36737 w7 &= 0x3ffffff;
36738 /* k = 8 */
36739 lo = Math.imul(al8, bl0);
36740 mid = Math.imul(al8, bh0);
36741 mid = (mid + Math.imul(ah8, bl0)) | 0;
36742 hi = Math.imul(ah8, bh0);
36743 lo = (lo + Math.imul(al7, bl1)) | 0;
36744 mid = (mid + Math.imul(al7, bh1)) | 0;
36745 mid = (mid + Math.imul(ah7, bl1)) | 0;
36746 hi = (hi + Math.imul(ah7, bh1)) | 0;
36747 lo = (lo + Math.imul(al6, bl2)) | 0;
36748 mid = (mid + Math.imul(al6, bh2)) | 0;
36749 mid = (mid + Math.imul(ah6, bl2)) | 0;
36750 hi = (hi + Math.imul(ah6, bh2)) | 0;
36751 lo = (lo + Math.imul(al5, bl3)) | 0;
36752 mid = (mid + Math.imul(al5, bh3)) | 0;
36753 mid = (mid + Math.imul(ah5, bl3)) | 0;
36754 hi = (hi + Math.imul(ah5, bh3)) | 0;
36755 lo = (lo + Math.imul(al4, bl4)) | 0;
36756 mid = (mid + Math.imul(al4, bh4)) | 0;
36757 mid = (mid + Math.imul(ah4, bl4)) | 0;
36758 hi = (hi + Math.imul(ah4, bh4)) | 0;
36759 lo = (lo + Math.imul(al3, bl5)) | 0;
36760 mid = (mid + Math.imul(al3, bh5)) | 0;
36761 mid = (mid + Math.imul(ah3, bl5)) | 0;
36762 hi = (hi + Math.imul(ah3, bh5)) | 0;
36763 lo = (lo + Math.imul(al2, bl6)) | 0;
36764 mid = (mid + Math.imul(al2, bh6)) | 0;
36765 mid = (mid + Math.imul(ah2, bl6)) | 0;
36766 hi = (hi + Math.imul(ah2, bh6)) | 0;
36767 lo = (lo + Math.imul(al1, bl7)) | 0;
36768 mid = (mid + Math.imul(al1, bh7)) | 0;
36769 mid = (mid + Math.imul(ah1, bl7)) | 0;
36770 hi = (hi + Math.imul(ah1, bh7)) | 0;
36771 lo = (lo + Math.imul(al0, bl8)) | 0;
36772 mid = (mid + Math.imul(al0, bh8)) | 0;
36773 mid = (mid + Math.imul(ah0, bl8)) | 0;
36774 hi = (hi + Math.imul(ah0, bh8)) | 0;
36775 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36776 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
36777 w8 &= 0x3ffffff;
36778 /* k = 9 */
36779 lo = Math.imul(al9, bl0);
36780 mid = Math.imul(al9, bh0);
36781 mid = (mid + Math.imul(ah9, bl0)) | 0;
36782 hi = Math.imul(ah9, bh0);
36783 lo = (lo + Math.imul(al8, bl1)) | 0;
36784 mid = (mid + Math.imul(al8, bh1)) | 0;
36785 mid = (mid + Math.imul(ah8, bl1)) | 0;
36786 hi = (hi + Math.imul(ah8, bh1)) | 0;
36787 lo = (lo + Math.imul(al7, bl2)) | 0;
36788 mid = (mid + Math.imul(al7, bh2)) | 0;
36789 mid = (mid + Math.imul(ah7, bl2)) | 0;
36790 hi = (hi + Math.imul(ah7, bh2)) | 0;
36791 lo = (lo + Math.imul(al6, bl3)) | 0;
36792 mid = (mid + Math.imul(al6, bh3)) | 0;
36793 mid = (mid + Math.imul(ah6, bl3)) | 0;
36794 hi = (hi + Math.imul(ah6, bh3)) | 0;
36795 lo = (lo + Math.imul(al5, bl4)) | 0;
36796 mid = (mid + Math.imul(al5, bh4)) | 0;
36797 mid = (mid + Math.imul(ah5, bl4)) | 0;
36798 hi = (hi + Math.imul(ah5, bh4)) | 0;
36799 lo = (lo + Math.imul(al4, bl5)) | 0;
36800 mid = (mid + Math.imul(al4, bh5)) | 0;
36801 mid = (mid + Math.imul(ah4, bl5)) | 0;
36802 hi = (hi + Math.imul(ah4, bh5)) | 0;
36803 lo = (lo + Math.imul(al3, bl6)) | 0;
36804 mid = (mid + Math.imul(al3, bh6)) | 0;
36805 mid = (mid + Math.imul(ah3, bl6)) | 0;
36806 hi = (hi + Math.imul(ah3, bh6)) | 0;
36807 lo = (lo + Math.imul(al2, bl7)) | 0;
36808 mid = (mid + Math.imul(al2, bh7)) | 0;
36809 mid = (mid + Math.imul(ah2, bl7)) | 0;
36810 hi = (hi + Math.imul(ah2, bh7)) | 0;
36811 lo = (lo + Math.imul(al1, bl8)) | 0;
36812 mid = (mid + Math.imul(al1, bh8)) | 0;
36813 mid = (mid + Math.imul(ah1, bl8)) | 0;
36814 hi = (hi + Math.imul(ah1, bh8)) | 0;
36815 lo = (lo + Math.imul(al0, bl9)) | 0;
36816 mid = (mid + Math.imul(al0, bh9)) | 0;
36817 mid = (mid + Math.imul(ah0, bl9)) | 0;
36818 hi = (hi + Math.imul(ah0, bh9)) | 0;
36819 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36820 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
36821 w9 &= 0x3ffffff;
36822 /* k = 10 */
36823 lo = Math.imul(al9, bl1);
36824 mid = Math.imul(al9, bh1);
36825 mid = (mid + Math.imul(ah9, bl1)) | 0;
36826 hi = Math.imul(ah9, bh1);
36827 lo = (lo + Math.imul(al8, bl2)) | 0;
36828 mid = (mid + Math.imul(al8, bh2)) | 0;
36829 mid = (mid + Math.imul(ah8, bl2)) | 0;
36830 hi = (hi + Math.imul(ah8, bh2)) | 0;
36831 lo = (lo + Math.imul(al7, bl3)) | 0;
36832 mid = (mid + Math.imul(al7, bh3)) | 0;
36833 mid = (mid + Math.imul(ah7, bl3)) | 0;
36834 hi = (hi + Math.imul(ah7, bh3)) | 0;
36835 lo = (lo + Math.imul(al6, bl4)) | 0;
36836 mid = (mid + Math.imul(al6, bh4)) | 0;
36837 mid = (mid + Math.imul(ah6, bl4)) | 0;
36838 hi = (hi + Math.imul(ah6, bh4)) | 0;
36839 lo = (lo + Math.imul(al5, bl5)) | 0;
36840 mid = (mid + Math.imul(al5, bh5)) | 0;
36841 mid = (mid + Math.imul(ah5, bl5)) | 0;
36842 hi = (hi + Math.imul(ah5, bh5)) | 0;
36843 lo = (lo + Math.imul(al4, bl6)) | 0;
36844 mid = (mid + Math.imul(al4, bh6)) | 0;
36845 mid = (mid + Math.imul(ah4, bl6)) | 0;
36846 hi = (hi + Math.imul(ah4, bh6)) | 0;
36847 lo = (lo + Math.imul(al3, bl7)) | 0;
36848 mid = (mid + Math.imul(al3, bh7)) | 0;
36849 mid = (mid + Math.imul(ah3, bl7)) | 0;
36850 hi = (hi + Math.imul(ah3, bh7)) | 0;
36851 lo = (lo + Math.imul(al2, bl8)) | 0;
36852 mid = (mid + Math.imul(al2, bh8)) | 0;
36853 mid = (mid + Math.imul(ah2, bl8)) | 0;
36854 hi = (hi + Math.imul(ah2, bh8)) | 0;
36855 lo = (lo + Math.imul(al1, bl9)) | 0;
36856 mid = (mid + Math.imul(al1, bh9)) | 0;
36857 mid = (mid + Math.imul(ah1, bl9)) | 0;
36858 hi = (hi + Math.imul(ah1, bh9)) | 0;
36859 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36860 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
36861 w10 &= 0x3ffffff;
36862 /* k = 11 */
36863 lo = Math.imul(al9, bl2);
36864 mid = Math.imul(al9, bh2);
36865 mid = (mid + Math.imul(ah9, bl2)) | 0;
36866 hi = Math.imul(ah9, bh2);
36867 lo = (lo + Math.imul(al8, bl3)) | 0;
36868 mid = (mid + Math.imul(al8, bh3)) | 0;
36869 mid = (mid + Math.imul(ah8, bl3)) | 0;
36870 hi = (hi + Math.imul(ah8, bh3)) | 0;
36871 lo = (lo + Math.imul(al7, bl4)) | 0;
36872 mid = (mid + Math.imul(al7, bh4)) | 0;
36873 mid = (mid + Math.imul(ah7, bl4)) | 0;
36874 hi = (hi + Math.imul(ah7, bh4)) | 0;
36875 lo = (lo + Math.imul(al6, bl5)) | 0;
36876 mid = (mid + Math.imul(al6, bh5)) | 0;
36877 mid = (mid + Math.imul(ah6, bl5)) | 0;
36878 hi = (hi + Math.imul(ah6, bh5)) | 0;
36879 lo = (lo + Math.imul(al5, bl6)) | 0;
36880 mid = (mid + Math.imul(al5, bh6)) | 0;
36881 mid = (mid + Math.imul(ah5, bl6)) | 0;
36882 hi = (hi + Math.imul(ah5, bh6)) | 0;
36883 lo = (lo + Math.imul(al4, bl7)) | 0;
36884 mid = (mid + Math.imul(al4, bh7)) | 0;
36885 mid = (mid + Math.imul(ah4, bl7)) | 0;
36886 hi = (hi + Math.imul(ah4, bh7)) | 0;
36887 lo = (lo + Math.imul(al3, bl8)) | 0;
36888 mid = (mid + Math.imul(al3, bh8)) | 0;
36889 mid = (mid + Math.imul(ah3, bl8)) | 0;
36890 hi = (hi + Math.imul(ah3, bh8)) | 0;
36891 lo = (lo + Math.imul(al2, bl9)) | 0;
36892 mid = (mid + Math.imul(al2, bh9)) | 0;
36893 mid = (mid + Math.imul(ah2, bl9)) | 0;
36894 hi = (hi + Math.imul(ah2, bh9)) | 0;
36895 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36896 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
36897 w11 &= 0x3ffffff;
36898 /* k = 12 */
36899 lo = Math.imul(al9, bl3);
36900 mid = Math.imul(al9, bh3);
36901 mid = (mid + Math.imul(ah9, bl3)) | 0;
36902 hi = Math.imul(ah9, bh3);
36903 lo = (lo + Math.imul(al8, bl4)) | 0;
36904 mid = (mid + Math.imul(al8, bh4)) | 0;
36905 mid = (mid + Math.imul(ah8, bl4)) | 0;
36906 hi = (hi + Math.imul(ah8, bh4)) | 0;
36907 lo = (lo + Math.imul(al7, bl5)) | 0;
36908 mid = (mid + Math.imul(al7, bh5)) | 0;
36909 mid = (mid + Math.imul(ah7, bl5)) | 0;
36910 hi = (hi + Math.imul(ah7, bh5)) | 0;
36911 lo = (lo + Math.imul(al6, bl6)) | 0;
36912 mid = (mid + Math.imul(al6, bh6)) | 0;
36913 mid = (mid + Math.imul(ah6, bl6)) | 0;
36914 hi = (hi + Math.imul(ah6, bh6)) | 0;
36915 lo = (lo + Math.imul(al5, bl7)) | 0;
36916 mid = (mid + Math.imul(al5, bh7)) | 0;
36917 mid = (mid + Math.imul(ah5, bl7)) | 0;
36918 hi = (hi + Math.imul(ah5, bh7)) | 0;
36919 lo = (lo + Math.imul(al4, bl8)) | 0;
36920 mid = (mid + Math.imul(al4, bh8)) | 0;
36921 mid = (mid + Math.imul(ah4, bl8)) | 0;
36922 hi = (hi + Math.imul(ah4, bh8)) | 0;
36923 lo = (lo + Math.imul(al3, bl9)) | 0;
36924 mid = (mid + Math.imul(al3, bh9)) | 0;
36925 mid = (mid + Math.imul(ah3, bl9)) | 0;
36926 hi = (hi + Math.imul(ah3, bh9)) | 0;
36927 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36928 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
36929 w12 &= 0x3ffffff;
36930 /* k = 13 */
36931 lo = Math.imul(al9, bl4);
36932 mid = Math.imul(al9, bh4);
36933 mid = (mid + Math.imul(ah9, bl4)) | 0;
36934 hi = Math.imul(ah9, bh4);
36935 lo = (lo + Math.imul(al8, bl5)) | 0;
36936 mid = (mid + Math.imul(al8, bh5)) | 0;
36937 mid = (mid + Math.imul(ah8, bl5)) | 0;
36938 hi = (hi + Math.imul(ah8, bh5)) | 0;
36939 lo = (lo + Math.imul(al7, bl6)) | 0;
36940 mid = (mid + Math.imul(al7, bh6)) | 0;
36941 mid = (mid + Math.imul(ah7, bl6)) | 0;
36942 hi = (hi + Math.imul(ah7, bh6)) | 0;
36943 lo = (lo + Math.imul(al6, bl7)) | 0;
36944 mid = (mid + Math.imul(al6, bh7)) | 0;
36945 mid = (mid + Math.imul(ah6, bl7)) | 0;
36946 hi = (hi + Math.imul(ah6, bh7)) | 0;
36947 lo = (lo + Math.imul(al5, bl8)) | 0;
36948 mid = (mid + Math.imul(al5, bh8)) | 0;
36949 mid = (mid + Math.imul(ah5, bl8)) | 0;
36950 hi = (hi + Math.imul(ah5, bh8)) | 0;
36951 lo = (lo + Math.imul(al4, bl9)) | 0;
36952 mid = (mid + Math.imul(al4, bh9)) | 0;
36953 mid = (mid + Math.imul(ah4, bl9)) | 0;
36954 hi = (hi + Math.imul(ah4, bh9)) | 0;
36955 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36956 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
36957 w13 &= 0x3ffffff;
36958 /* k = 14 */
36959 lo = Math.imul(al9, bl5);
36960 mid = Math.imul(al9, bh5);
36961 mid = (mid + Math.imul(ah9, bl5)) | 0;
36962 hi = Math.imul(ah9, bh5);
36963 lo = (lo + Math.imul(al8, bl6)) | 0;
36964 mid = (mid + Math.imul(al8, bh6)) | 0;
36965 mid = (mid + Math.imul(ah8, bl6)) | 0;
36966 hi = (hi + Math.imul(ah8, bh6)) | 0;
36967 lo = (lo + Math.imul(al7, bl7)) | 0;
36968 mid = (mid + Math.imul(al7, bh7)) | 0;
36969 mid = (mid + Math.imul(ah7, bl7)) | 0;
36970 hi = (hi + Math.imul(ah7, bh7)) | 0;
36971 lo = (lo + Math.imul(al6, bl8)) | 0;
36972 mid = (mid + Math.imul(al6, bh8)) | 0;
36973 mid = (mid + Math.imul(ah6, bl8)) | 0;
36974 hi = (hi + Math.imul(ah6, bh8)) | 0;
36975 lo = (lo + Math.imul(al5, bl9)) | 0;
36976 mid = (mid + Math.imul(al5, bh9)) | 0;
36977 mid = (mid + Math.imul(ah5, bl9)) | 0;
36978 hi = (hi + Math.imul(ah5, bh9)) | 0;
36979 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36980 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
36981 w14 &= 0x3ffffff;
36982 /* k = 15 */
36983 lo = Math.imul(al9, bl6);
36984 mid = Math.imul(al9, bh6);
36985 mid = (mid + Math.imul(ah9, bl6)) | 0;
36986 hi = Math.imul(ah9, bh6);
36987 lo = (lo + Math.imul(al8, bl7)) | 0;
36988 mid = (mid + Math.imul(al8, bh7)) | 0;
36989 mid = (mid + Math.imul(ah8, bl7)) | 0;
36990 hi = (hi + Math.imul(ah8, bh7)) | 0;
36991 lo = (lo + Math.imul(al7, bl8)) | 0;
36992 mid = (mid + Math.imul(al7, bh8)) | 0;
36993 mid = (mid + Math.imul(ah7, bl8)) | 0;
36994 hi = (hi + Math.imul(ah7, bh8)) | 0;
36995 lo = (lo + Math.imul(al6, bl9)) | 0;
36996 mid = (mid + Math.imul(al6, bh9)) | 0;
36997 mid = (mid + Math.imul(ah6, bl9)) | 0;
36998 hi = (hi + Math.imul(ah6, bh9)) | 0;
36999 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37000 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
37001 w15 &= 0x3ffffff;
37002 /* k = 16 */
37003 lo = Math.imul(al9, bl7);
37004 mid = Math.imul(al9, bh7);
37005 mid = (mid + Math.imul(ah9, bl7)) | 0;
37006 hi = Math.imul(ah9, bh7);
37007 lo = (lo + Math.imul(al8, bl8)) | 0;
37008 mid = (mid + Math.imul(al8, bh8)) | 0;
37009 mid = (mid + Math.imul(ah8, bl8)) | 0;
37010 hi = (hi + Math.imul(ah8, bh8)) | 0;
37011 lo = (lo + Math.imul(al7, bl9)) | 0;
37012 mid = (mid + Math.imul(al7, bh9)) | 0;
37013 mid = (mid + Math.imul(ah7, bl9)) | 0;
37014 hi = (hi + Math.imul(ah7, bh9)) | 0;
37015 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37016 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
37017 w16 &= 0x3ffffff;
37018 /* k = 17 */
37019 lo = Math.imul(al9, bl8);
37020 mid = Math.imul(al9, bh8);
37021 mid = (mid + Math.imul(ah9, bl8)) | 0;
37022 hi = Math.imul(ah9, bh8);
37023 lo = (lo + Math.imul(al8, bl9)) | 0;
37024 mid = (mid + Math.imul(al8, bh9)) | 0;
37025 mid = (mid + Math.imul(ah8, bl9)) | 0;
37026 hi = (hi + Math.imul(ah8, bh9)) | 0;
37027 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37028 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
37029 w17 &= 0x3ffffff;
37030 /* k = 18 */
37031 lo = Math.imul(al9, bl9);
37032 mid = Math.imul(al9, bh9);
37033 mid = (mid + Math.imul(ah9, bl9)) | 0;
37034 hi = Math.imul(ah9, bh9);
37035 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37036 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
37037 w18 &= 0x3ffffff;
37038 o[0] = w0;
37039 o[1] = w1;
37040 o[2] = w2;
37041 o[3] = w3;
37042 o[4] = w4;
37043 o[5] = w5;
37044 o[6] = w6;
37045 o[7] = w7;
37046 o[8] = w8;
37047 o[9] = w9;
37048 o[10] = w10;
37049 o[11] = w11;
37050 o[12] = w12;
37051 o[13] = w13;
37052 o[14] = w14;
37053 o[15] = w15;
37054 o[16] = w16;
37055 o[17] = w17;
37056 o[18] = w18;
37057 if (c !== 0) {
37058 o[19] = c;
37059 out.length++;
37060 }
37061 return out;
37062 };
37063
37064 // Polyfill comb
37065 if (!Math.imul) {
37066 comb10MulTo = smallMulTo;
37067 }
37068
37069 function bigMulTo (self, num, out) {
37070 out.negative = num.negative ^ self.negative;
37071 out.length = self.length + num.length;
37072
37073 var carry = 0;
37074 var hncarry = 0;
37075 for (var k = 0; k < out.length - 1; k++) {
37076 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
37077 // note that ncarry could be >= 0x3ffffff
37078 var ncarry = hncarry;
37079 hncarry = 0;
37080 var rword = carry & 0x3ffffff;
37081 var maxJ = Math.min(k, num.length - 1);
37082 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
37083 var i = k - j;
37084 var a = self.words[i] | 0;
37085 var b = num.words[j] | 0;
37086 var r = a * b;
37087
37088 var lo = r & 0x3ffffff;
37089 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
37090 lo = (lo + rword) | 0;
37091 rword = lo & 0x3ffffff;
37092 ncarry = (ncarry + (lo >>> 26)) | 0;
37093
37094 hncarry += ncarry >>> 26;
37095 ncarry &= 0x3ffffff;
37096 }
37097 out.words[k] = rword;
37098 carry = ncarry;
37099 ncarry = hncarry;
37100 }
37101 if (carry !== 0) {
37102 out.words[k] = carry;
37103 } else {
37104 out.length--;
37105 }
37106
37107 return out.strip();
37108 }
37109
37110 function jumboMulTo (self, num, out) {
37111 var fftm = new FFTM();
37112 return fftm.mulp(self, num, out);
37113 }
37114
37115 BN.prototype.mulTo = function mulTo (num, out) {
37116 var res;
37117 var len = this.length + num.length;
37118 if (this.length === 10 && num.length === 10) {
37119 res = comb10MulTo(this, num, out);
37120 } else if (len < 63) {
37121 res = smallMulTo(this, num, out);
37122 } else if (len < 1024) {
37123 res = bigMulTo(this, num, out);
37124 } else {
37125 res = jumboMulTo(this, num, out);
37126 }
37127
37128 return res;
37129 };
37130
37131 // Cooley-Tukey algorithm for FFT
37132 // slightly revisited to rely on looping instead of recursion
37133
37134 function FFTM (x, y) {
37135 this.x = x;
37136 this.y = y;
37137 }
37138
37139 FFTM.prototype.makeRBT = function makeRBT (N) {
37140 var t = new Array(N);
37141 var l = BN.prototype._countBits(N) - 1;
37142 for (var i = 0; i < N; i++) {
37143 t[i] = this.revBin(i, l, N);
37144 }
37145
37146 return t;
37147 };
37148
37149 // Returns binary-reversed representation of `x`
37150 FFTM.prototype.revBin = function revBin (x, l, N) {
37151 if (x === 0 || x === N - 1) return x;
37152
37153 var rb = 0;
37154 for (var i = 0; i < l; i++) {
37155 rb |= (x & 1) << (l - i - 1);
37156 x >>= 1;
37157 }
37158
37159 return rb;
37160 };
37161
37162 // Performs "tweedling" phase, therefore 'emulating'
37163 // behaviour of the recursive algorithm
37164 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
37165 for (var i = 0; i < N; i++) {
37166 rtws[i] = rws[rbt[i]];
37167 itws[i] = iws[rbt[i]];
37168 }
37169 };
37170
37171 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
37172 this.permute(rbt, rws, iws, rtws, itws, N);
37173
37174 for (var s = 1; s < N; s <<= 1) {
37175 var l = s << 1;
37176
37177 var rtwdf = Math.cos(2 * Math.PI / l);
37178 var itwdf = Math.sin(2 * Math.PI / l);
37179
37180 for (var p = 0; p < N; p += l) {
37181 var rtwdf_ = rtwdf;
37182 var itwdf_ = itwdf;
37183
37184 for (var j = 0; j < s; j++) {
37185 var re = rtws[p + j];
37186 var ie = itws[p + j];
37187
37188 var ro = rtws[p + j + s];
37189 var io = itws[p + j + s];
37190
37191 var rx = rtwdf_ * ro - itwdf_ * io;
37192
37193 io = rtwdf_ * io + itwdf_ * ro;
37194 ro = rx;
37195
37196 rtws[p + j] = re + ro;
37197 itws[p + j] = ie + io;
37198
37199 rtws[p + j + s] = re - ro;
37200 itws[p + j + s] = ie - io;
37201
37202 /* jshint maxdepth : false */
37203 if (j !== l) {
37204 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
37205
37206 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
37207 rtwdf_ = rx;
37208 }
37209 }
37210 }
37211 }
37212 };
37213
37214 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
37215 var N = Math.max(m, n) | 1;
37216 var odd = N & 1;
37217 var i = 0;
37218 for (N = N / 2 | 0; N; N = N >>> 1) {
37219 i++;
37220 }
37221
37222 return 1 << i + 1 + odd;
37223 };
37224
37225 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
37226 if (N <= 1) return;
37227
37228 for (var i = 0; i < N / 2; i++) {
37229 var t = rws[i];
37230
37231 rws[i] = rws[N - i - 1];
37232 rws[N - i - 1] = t;
37233
37234 t = iws[i];
37235
37236 iws[i] = -iws[N - i - 1];
37237 iws[N - i - 1] = -t;
37238 }
37239 };
37240
37241 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
37242 var carry = 0;
37243 for (var i = 0; i < N / 2; i++) {
37244 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
37245 Math.round(ws[2 * i] / N) +
37246 carry;
37247
37248 ws[i] = w & 0x3ffffff;
37249
37250 if (w < 0x4000000) {
37251 carry = 0;
37252 } else {
37253 carry = w / 0x4000000 | 0;
37254 }
37255 }
37256
37257 return ws;
37258 };
37259
37260 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
37261 var carry = 0;
37262 for (var i = 0; i < len; i++) {
37263 carry = carry + (ws[i] | 0);
37264
37265 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
37266 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
37267 }
37268
37269 // Pad with zeroes
37270 for (i = 2 * len; i < N; ++i) {
37271 rws[i] = 0;
37272 }
37273
37274 assert(carry === 0);
37275 assert((carry & ~0x1fff) === 0);
37276 };
37277
37278 FFTM.prototype.stub = function stub (N) {
37279 var ph = new Array(N);
37280 for (var i = 0; i < N; i++) {
37281 ph[i] = 0;
37282 }
37283
37284 return ph;
37285 };
37286
37287 FFTM.prototype.mulp = function mulp (x, y, out) {
37288 var N = 2 * this.guessLen13b(x.length, y.length);
37289
37290 var rbt = this.makeRBT(N);
37291
37292 var _ = this.stub(N);
37293
37294 var rws = new Array(N);
37295 var rwst = new Array(N);
37296 var iwst = new Array(N);
37297
37298 var nrws = new Array(N);
37299 var nrwst = new Array(N);
37300 var niwst = new Array(N);
37301
37302 var rmws = out.words;
37303 rmws.length = N;
37304
37305 this.convert13b(x.words, x.length, rws, N);
37306 this.convert13b(y.words, y.length, nrws, N);
37307
37308 this.transform(rws, _, rwst, iwst, N, rbt);
37309 this.transform(nrws, _, nrwst, niwst, N, rbt);
37310
37311 for (var i = 0; i < N; i++) {
37312 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
37313 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
37314 rwst[i] = rx;
37315 }
37316
37317 this.conjugate(rwst, iwst, N);
37318 this.transform(rwst, iwst, rmws, _, N, rbt);
37319 this.conjugate(rmws, _, N);
37320 this.normalize13b(rmws, N);
37321
37322 out.negative = x.negative ^ y.negative;
37323 out.length = x.length + y.length;
37324 return out.strip();
37325 };
37326
37327 // Multiply `this` by `num`
37328 BN.prototype.mul = function mul (num) {
37329 var out = new BN(null);
37330 out.words = new Array(this.length + num.length);
37331 return this.mulTo(num, out);
37332 };
37333
37334 // Multiply employing FFT
37335 BN.prototype.mulf = function mulf (num) {
37336 var out = new BN(null);
37337 out.words = new Array(this.length + num.length);
37338 return jumboMulTo(this, num, out);
37339 };
37340
37341 // In-place Multiplication
37342 BN.prototype.imul = function imul (num) {
37343 return this.clone().mulTo(num, this);
37344 };
37345
37346 BN.prototype.imuln = function imuln (num) {
37347 assert(typeof num === 'number');
37348 assert(num < 0x4000000);
37349
37350 // Carry
37351 var carry = 0;
37352 for (var i = 0; i < this.length; i++) {
37353 var w = (this.words[i] | 0) * num;
37354 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
37355 carry >>= 26;
37356 carry += (w / 0x4000000) | 0;
37357 // NOTE: lo is 27bit maximum
37358 carry += lo >>> 26;
37359 this.words[i] = lo & 0x3ffffff;
37360 }
37361
37362 if (carry !== 0) {
37363 this.words[i] = carry;
37364 this.length++;
37365 }
37366
37367 return this;
37368 };
37369
37370 BN.prototype.muln = function muln (num) {
37371 return this.clone().imuln(num);
37372 };
37373
37374 // `this` * `this`
37375 BN.prototype.sqr = function sqr () {
37376 return this.mul(this);
37377 };
37378
37379 // `this` * `this` in-place
37380 BN.prototype.isqr = function isqr () {
37381 return this.imul(this.clone());
37382 };
37383
37384 // Math.pow(`this`, `num`)
37385 BN.prototype.pow = function pow (num) {
37386 var w = toBitArray(num);
37387 if (w.length === 0) return new BN(1);
37388
37389 // Skip leading zeroes
37390 var res = this;
37391 for (var i = 0; i < w.length; i++, res = res.sqr()) {
37392 if (w[i] !== 0) break;
37393 }
37394
37395 if (++i < w.length) {
37396 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
37397 if (w[i] === 0) continue;
37398
37399 res = res.mul(q);
37400 }
37401 }
37402
37403 return res;
37404 };
37405
37406 // Shift-left in-place
37407 BN.prototype.iushln = function iushln (bits) {
37408 assert(typeof bits === 'number' && bits >= 0);
37409 var r = bits % 26;
37410 var s = (bits - r) / 26;
37411 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
37412 var i;
37413
37414 if (r !== 0) {
37415 var carry = 0;
37416
37417 for (i = 0; i < this.length; i++) {
37418 var newCarry = this.words[i] & carryMask;
37419 var c = ((this.words[i] | 0) - newCarry) << r;
37420 this.words[i] = c | carry;
37421 carry = newCarry >>> (26 - r);
37422 }
37423
37424 if (carry) {
37425 this.words[i] = carry;
37426 this.length++;
37427 }
37428 }
37429
37430 if (s !== 0) {
37431 for (i = this.length - 1; i >= 0; i--) {
37432 this.words[i + s] = this.words[i];
37433 }
37434
37435 for (i = 0; i < s; i++) {
37436 this.words[i] = 0;
37437 }
37438
37439 this.length += s;
37440 }
37441
37442 return this.strip();
37443 };
37444
37445 BN.prototype.ishln = function ishln (bits) {
37446 // TODO(indutny): implement me
37447 assert(this.negative === 0);
37448 return this.iushln(bits);
37449 };
37450
37451 // Shift-right in-place
37452 // NOTE: `hint` is a lowest bit before trailing zeroes
37453 // NOTE: if `extended` is present - it will be filled with destroyed bits
37454 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
37455 assert(typeof bits === 'number' && bits >= 0);
37456 var h;
37457 if (hint) {
37458 h = (hint - (hint % 26)) / 26;
37459 } else {
37460 h = 0;
37461 }
37462
37463 var r = bits % 26;
37464 var s = Math.min((bits - r) / 26, this.length);
37465 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37466 var maskedWords = extended;
37467
37468 h -= s;
37469 h = Math.max(0, h);
37470
37471 // Extended mode, copy masked part
37472 if (maskedWords) {
37473 for (var i = 0; i < s; i++) {
37474 maskedWords.words[i] = this.words[i];
37475 }
37476 maskedWords.length = s;
37477 }
37478
37479 if (s === 0) ; else if (this.length > s) {
37480 this.length -= s;
37481 for (i = 0; i < this.length; i++) {
37482 this.words[i] = this.words[i + s];
37483 }
37484 } else {
37485 this.words[0] = 0;
37486 this.length = 1;
37487 }
37488
37489 var carry = 0;
37490 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
37491 var word = this.words[i] | 0;
37492 this.words[i] = (carry << (26 - r)) | (word >>> r);
37493 carry = word & mask;
37494 }
37495
37496 // Push carried bits as a mask
37497 if (maskedWords && carry !== 0) {
37498 maskedWords.words[maskedWords.length++] = carry;
37499 }
37500
37501 if (this.length === 0) {
37502 this.words[0] = 0;
37503 this.length = 1;
37504 }
37505
37506 return this.strip();
37507 };
37508
37509 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
37510 // TODO(indutny): implement me
37511 assert(this.negative === 0);
37512 return this.iushrn(bits, hint, extended);
37513 };
37514
37515 // Shift-left
37516 BN.prototype.shln = function shln (bits) {
37517 return this.clone().ishln(bits);
37518 };
37519
37520 BN.prototype.ushln = function ushln (bits) {
37521 return this.clone().iushln(bits);
37522 };
37523
37524 // Shift-right
37525 BN.prototype.shrn = function shrn (bits) {
37526 return this.clone().ishrn(bits);
37527 };
37528
37529 BN.prototype.ushrn = function ushrn (bits) {
37530 return this.clone().iushrn(bits);
37531 };
37532
37533 // Test if n bit is set
37534 BN.prototype.testn = function testn (bit) {
37535 assert(typeof bit === 'number' && bit >= 0);
37536 var r = bit % 26;
37537 var s = (bit - r) / 26;
37538 var q = 1 << r;
37539
37540 // Fast case: bit is much higher than all existing words
37541 if (this.length <= s) return false;
37542
37543 // Check bit and return
37544 var w = this.words[s];
37545
37546 return !!(w & q);
37547 };
37548
37549 // Return only lowers bits of number (in-place)
37550 BN.prototype.imaskn = function imaskn (bits) {
37551 assert(typeof bits === 'number' && bits >= 0);
37552 var r = bits % 26;
37553 var s = (bits - r) / 26;
37554
37555 assert(this.negative === 0, 'imaskn works only with positive numbers');
37556
37557 if (this.length <= s) {
37558 return this;
37559 }
37560
37561 if (r !== 0) {
37562 s++;
37563 }
37564 this.length = Math.min(s, this.length);
37565
37566 if (r !== 0) {
37567 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37568 this.words[this.length - 1] &= mask;
37569 }
37570
37571 return this.strip();
37572 };
37573
37574 // Return only lowers bits of number
37575 BN.prototype.maskn = function maskn (bits) {
37576 return this.clone().imaskn(bits);
37577 };
37578
37579 // Add plain number `num` to `this`
37580 BN.prototype.iaddn = function iaddn (num) {
37581 assert(typeof num === 'number');
37582 assert(num < 0x4000000);
37583 if (num < 0) return this.isubn(-num);
37584
37585 // Possible sign change
37586 if (this.negative !== 0) {
37587 if (this.length === 1 && (this.words[0] | 0) < num) {
37588 this.words[0] = num - (this.words[0] | 0);
37589 this.negative = 0;
37590 return this;
37591 }
37592
37593 this.negative = 0;
37594 this.isubn(num);
37595 this.negative = 1;
37596 return this;
37597 }
37598
37599 // Add without checks
37600 return this._iaddn(num);
37601 };
37602
37603 BN.prototype._iaddn = function _iaddn (num) {
37604 this.words[0] += num;
37605
37606 // Carry
37607 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
37608 this.words[i] -= 0x4000000;
37609 if (i === this.length - 1) {
37610 this.words[i + 1] = 1;
37611 } else {
37612 this.words[i + 1]++;
37613 }
37614 }
37615 this.length = Math.max(this.length, i + 1);
37616
37617 return this;
37618 };
37619
37620 // Subtract plain number `num` from `this`
37621 BN.prototype.isubn = function isubn (num) {
37622 assert(typeof num === 'number');
37623 assert(num < 0x4000000);
37624 if (num < 0) return this.iaddn(-num);
37625
37626 if (this.negative !== 0) {
37627 this.negative = 0;
37628 this.iaddn(num);
37629 this.negative = 1;
37630 return this;
37631 }
37632
37633 this.words[0] -= num;
37634
37635 if (this.length === 1 && this.words[0] < 0) {
37636 this.words[0] = -this.words[0];
37637 this.negative = 1;
37638 } else {
37639 // Carry
37640 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
37641 this.words[i] += 0x4000000;
37642 this.words[i + 1] -= 1;
37643 }
37644 }
37645
37646 return this.strip();
37647 };
37648
37649 BN.prototype.addn = function addn (num) {
37650 return this.clone().iaddn(num);
37651 };
37652
37653 BN.prototype.subn = function subn (num) {
37654 return this.clone().isubn(num);
37655 };
37656
37657 BN.prototype.iabs = function iabs () {
37658 this.negative = 0;
37659
37660 return this;
37661 };
37662
37663 BN.prototype.abs = function abs () {
37664 return this.clone().iabs();
37665 };
37666
37667 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
37668 var len = num.length + shift;
37669 var i;
37670
37671 this._expand(len);
37672
37673 var w;
37674 var carry = 0;
37675 for (i = 0; i < num.length; i++) {
37676 w = (this.words[i + shift] | 0) + carry;
37677 var right = (num.words[i] | 0) * mul;
37678 w -= right & 0x3ffffff;
37679 carry = (w >> 26) - ((right / 0x4000000) | 0);
37680 this.words[i + shift] = w & 0x3ffffff;
37681 }
37682 for (; i < this.length - shift; i++) {
37683 w = (this.words[i + shift] | 0) + carry;
37684 carry = w >> 26;
37685 this.words[i + shift] = w & 0x3ffffff;
37686 }
37687
37688 if (carry === 0) return this.strip();
37689
37690 // Subtraction overflow
37691 assert(carry === -1);
37692 carry = 0;
37693 for (i = 0; i < this.length; i++) {
37694 w = -(this.words[i] | 0) + carry;
37695 carry = w >> 26;
37696 this.words[i] = w & 0x3ffffff;
37697 }
37698 this.negative = 1;
37699
37700 return this.strip();
37701 };
37702
37703 BN.prototype._wordDiv = function _wordDiv (num, mode) {
37704 var shift = this.length - num.length;
37705
37706 var a = this.clone();
37707 var b = num;
37708
37709 // Normalize
37710 var bhi = b.words[b.length - 1] | 0;
37711 var bhiBits = this._countBits(bhi);
37712 shift = 26 - bhiBits;
37713 if (shift !== 0) {
37714 b = b.ushln(shift);
37715 a.iushln(shift);
37716 bhi = b.words[b.length - 1] | 0;
37717 }
37718
37719 // Initialize quotient
37720 var m = a.length - b.length;
37721 var q;
37722
37723 if (mode !== 'mod') {
37724 q = new BN(null);
37725 q.length = m + 1;
37726 q.words = new Array(q.length);
37727 for (var i = 0; i < q.length; i++) {
37728 q.words[i] = 0;
37729 }
37730 }
37731
37732 var diff = a.clone()._ishlnsubmul(b, 1, m);
37733 if (diff.negative === 0) {
37734 a = diff;
37735 if (q) {
37736 q.words[m] = 1;
37737 }
37738 }
37739
37740 for (var j = m - 1; j >= 0; j--) {
37741 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
37742 (a.words[b.length + j - 1] | 0);
37743
37744 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
37745 // (0x7ffffff)
37746 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
37747
37748 a._ishlnsubmul(b, qj, j);
37749 while (a.negative !== 0) {
37750 qj--;
37751 a.negative = 0;
37752 a._ishlnsubmul(b, 1, j);
37753 if (!a.isZero()) {
37754 a.negative ^= 1;
37755 }
37756 }
37757 if (q) {
37758 q.words[j] = qj;
37759 }
37760 }
37761 if (q) {
37762 q.strip();
37763 }
37764 a.strip();
37765
37766 // Denormalize
37767 if (mode !== 'div' && shift !== 0) {
37768 a.iushrn(shift);
37769 }
37770
37771 return {
37772 div: q || null,
37773 mod: a
37774 };
37775 };
37776
37777 // NOTE: 1) `mode` can be set to `mod` to request mod only,
37778 // to `div` to request div only, or be absent to
37779 // request both div & mod
37780 // 2) `positive` is true if unsigned mod is requested
37781 BN.prototype.divmod = function divmod (num, mode, positive) {
37782 assert(!num.isZero());
37783
37784 if (this.isZero()) {
37785 return {
37786 div: new BN(0),
37787 mod: new BN(0)
37788 };
37789 }
37790
37791 var div, mod, res;
37792 if (this.negative !== 0 && num.negative === 0) {
37793 res = this.neg().divmod(num, mode);
37794
37795 if (mode !== 'mod') {
37796 div = res.div.neg();
37797 }
37798
37799 if (mode !== 'div') {
37800 mod = res.mod.neg();
37801 if (positive && mod.negative !== 0) {
37802 mod.iadd(num);
37803 }
37804 }
37805
37806 return {
37807 div: div,
37808 mod: mod
37809 };
37810 }
37811
37812 if (this.negative === 0 && num.negative !== 0) {
37813 res = this.divmod(num.neg(), mode);
37814
37815 if (mode !== 'mod') {
37816 div = res.div.neg();
37817 }
37818
37819 return {
37820 div: div,
37821 mod: res.mod
37822 };
37823 }
37824
37825 if ((this.negative & num.negative) !== 0) {
37826 res = this.neg().divmod(num.neg(), mode);
37827
37828 if (mode !== 'div') {
37829 mod = res.mod.neg();
37830 if (positive && mod.negative !== 0) {
37831 mod.isub(num);
37832 }
37833 }
37834
37835 return {
37836 div: res.div,
37837 mod: mod
37838 };
37839 }
37840
37841 // Both numbers are positive at this point
37842
37843 // Strip both numbers to approximate shift value
37844 if (num.length > this.length || this.cmp(num) < 0) {
37845 return {
37846 div: new BN(0),
37847 mod: this
37848 };
37849 }
37850
37851 // Very short reduction
37852 if (num.length === 1) {
37853 if (mode === 'div') {
37854 return {
37855 div: this.divn(num.words[0]),
37856 mod: null
37857 };
37858 }
37859
37860 if (mode === 'mod') {
37861 return {
37862 div: null,
37863 mod: new BN(this.modn(num.words[0]))
37864 };
37865 }
37866
37867 return {
37868 div: this.divn(num.words[0]),
37869 mod: new BN(this.modn(num.words[0]))
37870 };
37871 }
37872
37873 return this._wordDiv(num, mode);
37874 };
37875
37876 // Find `this` / `num`
37877 BN.prototype.div = function div (num) {
37878 return this.divmod(num, 'div', false).div;
37879 };
37880
37881 // Find `this` % `num`
37882 BN.prototype.mod = function mod (num) {
37883 return this.divmod(num, 'mod', false).mod;
37884 };
37885
37886 BN.prototype.umod = function umod (num) {
37887 return this.divmod(num, 'mod', true).mod;
37888 };
37889
37890 // Find Round(`this` / `num`)
37891 BN.prototype.divRound = function divRound (num) {
37892 var dm = this.divmod(num);
37893
37894 // Fast case - exact division
37895 if (dm.mod.isZero()) return dm.div;
37896
37897 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
37898
37899 var half = num.ushrn(1);
37900 var r2 = num.andln(1);
37901 var cmp = mod.cmp(half);
37902
37903 // Round down
37904 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
37905
37906 // Round up
37907 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
37908 };
37909
37910 BN.prototype.modn = function modn (num) {
37911 assert(num <= 0x3ffffff);
37912 var p = (1 << 26) % num;
37913
37914 var acc = 0;
37915 for (var i = this.length - 1; i >= 0; i--) {
37916 acc = (p * acc + (this.words[i] | 0)) % num;
37917 }
37918
37919 return acc;
37920 };
37921
37922 // In-place division by number
37923 BN.prototype.idivn = function idivn (num) {
37924 assert(num <= 0x3ffffff);
37925
37926 var carry = 0;
37927 for (var i = this.length - 1; i >= 0; i--) {
37928 var w = (this.words[i] | 0) + carry * 0x4000000;
37929 this.words[i] = (w / num) | 0;
37930 carry = w % num;
37931 }
37932
37933 return this.strip();
37934 };
37935
37936 BN.prototype.divn = function divn (num) {
37937 return this.clone().idivn(num);
37938 };
37939
37940 BN.prototype.egcd = function egcd (p) {
37941 assert(p.negative === 0);
37942 assert(!p.isZero());
37943
37944 var x = this;
37945 var y = p.clone();
37946
37947 if (x.negative !== 0) {
37948 x = x.umod(p);
37949 } else {
37950 x = x.clone();
37951 }
37952
37953 // A * x + B * y = x
37954 var A = new BN(1);
37955 var B = new BN(0);
37956
37957 // C * x + D * y = y
37958 var C = new BN(0);
37959 var D = new BN(1);
37960
37961 var g = 0;
37962
37963 while (x.isEven() && y.isEven()) {
37964 x.iushrn(1);
37965 y.iushrn(1);
37966 ++g;
37967 }
37968
37969 var yp = y.clone();
37970 var xp = x.clone();
37971
37972 while (!x.isZero()) {
37973 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
37974 if (i > 0) {
37975 x.iushrn(i);
37976 while (i-- > 0) {
37977 if (A.isOdd() || B.isOdd()) {
37978 A.iadd(yp);
37979 B.isub(xp);
37980 }
37981
37982 A.iushrn(1);
37983 B.iushrn(1);
37984 }
37985 }
37986
37987 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
37988 if (j > 0) {
37989 y.iushrn(j);
37990 while (j-- > 0) {
37991 if (C.isOdd() || D.isOdd()) {
37992 C.iadd(yp);
37993 D.isub(xp);
37994 }
37995
37996 C.iushrn(1);
37997 D.iushrn(1);
37998 }
37999 }
38000
38001 if (x.cmp(y) >= 0) {
38002 x.isub(y);
38003 A.isub(C);
38004 B.isub(D);
38005 } else {
38006 y.isub(x);
38007 C.isub(A);
38008 D.isub(B);
38009 }
38010 }
38011
38012 return {
38013 a: C,
38014 b: D,
38015 gcd: y.iushln(g)
38016 };
38017 };
38018
38019 // This is reduced incarnation of the binary EEA
38020 // above, designated to invert members of the
38021 // _prime_ fields F(p) at a maximal speed
38022 BN.prototype._invmp = function _invmp (p) {
38023 assert(p.negative === 0);
38024 assert(!p.isZero());
38025
38026 var a = this;
38027 var b = p.clone();
38028
38029 if (a.negative !== 0) {
38030 a = a.umod(p);
38031 } else {
38032 a = a.clone();
38033 }
38034
38035 var x1 = new BN(1);
38036 var x2 = new BN(0);
38037
38038 var delta = b.clone();
38039
38040 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
38041 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
38042 if (i > 0) {
38043 a.iushrn(i);
38044 while (i-- > 0) {
38045 if (x1.isOdd()) {
38046 x1.iadd(delta);
38047 }
38048
38049 x1.iushrn(1);
38050 }
38051 }
38052
38053 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
38054 if (j > 0) {
38055 b.iushrn(j);
38056 while (j-- > 0) {
38057 if (x2.isOdd()) {
38058 x2.iadd(delta);
38059 }
38060
38061 x2.iushrn(1);
38062 }
38063 }
38064
38065 if (a.cmp(b) >= 0) {
38066 a.isub(b);
38067 x1.isub(x2);
38068 } else {
38069 b.isub(a);
38070 x2.isub(x1);
38071 }
38072 }
38073
38074 var res;
38075 if (a.cmpn(1) === 0) {
38076 res = x1;
38077 } else {
38078 res = x2;
38079 }
38080
38081 if (res.cmpn(0) < 0) {
38082 res.iadd(p);
38083 }
38084
38085 return res;
38086 };
38087
38088 BN.prototype.gcd = function gcd (num) {
38089 if (this.isZero()) return num.abs();
38090 if (num.isZero()) return this.abs();
38091
38092 var a = this.clone();
38093 var b = num.clone();
38094 a.negative = 0;
38095 b.negative = 0;
38096
38097 // Remove common factor of two
38098 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
38099 a.iushrn(1);
38100 b.iushrn(1);
38101 }
38102
38103 do {
38104 while (a.isEven()) {
38105 a.iushrn(1);
38106 }
38107 while (b.isEven()) {
38108 b.iushrn(1);
38109 }
38110
38111 var r = a.cmp(b);
38112 if (r < 0) {
38113 // Swap `a` and `b` to make `a` always bigger than `b`
38114 var t = a;
38115 a = b;
38116 b = t;
38117 } else if (r === 0 || b.cmpn(1) === 0) {
38118 break;
38119 }
38120
38121 a.isub(b);
38122 } while (true);
38123
38124 return b.iushln(shift);
38125 };
38126
38127 // Invert number in the field F(num)
38128 BN.prototype.invm = function invm (num) {
38129 return this.egcd(num).a.umod(num);
38130 };
38131
38132 BN.prototype.isEven = function isEven () {
38133 return (this.words[0] & 1) === 0;
38134 };
38135
38136 BN.prototype.isOdd = function isOdd () {
38137 return (this.words[0] & 1) === 1;
38138 };
38139
38140 // And first word and num
38141 BN.prototype.andln = function andln (num) {
38142 return this.words[0] & num;
38143 };
38144
38145 // Increment at the bit position in-line
38146 BN.prototype.bincn = function bincn (bit) {
38147 assert(typeof bit === 'number');
38148 var r = bit % 26;
38149 var s = (bit - r) / 26;
38150 var q = 1 << r;
38151
38152 // Fast case: bit is much higher than all existing words
38153 if (this.length <= s) {
38154 this._expand(s + 1);
38155 this.words[s] |= q;
38156 return this;
38157 }
38158
38159 // Add bit and propagate, if needed
38160 var carry = q;
38161 for (var i = s; carry !== 0 && i < this.length; i++) {
38162 var w = this.words[i] | 0;
38163 w += carry;
38164 carry = w >>> 26;
38165 w &= 0x3ffffff;
38166 this.words[i] = w;
38167 }
38168 if (carry !== 0) {
38169 this.words[i] = carry;
38170 this.length++;
38171 }
38172 return this;
38173 };
38174
38175 BN.prototype.isZero = function isZero () {
38176 return this.length === 1 && this.words[0] === 0;
38177 };
38178
38179 BN.prototype.cmpn = function cmpn (num) {
38180 var negative = num < 0;
38181
38182 if (this.negative !== 0 && !negative) return -1;
38183 if (this.negative === 0 && negative) return 1;
38184
38185 this.strip();
38186
38187 var res;
38188 if (this.length > 1) {
38189 res = 1;
38190 } else {
38191 if (negative) {
38192 num = -num;
38193 }
38194
38195 assert(num <= 0x3ffffff, 'Number is too big');
38196
38197 var w = this.words[0] | 0;
38198 res = w === num ? 0 : w < num ? -1 : 1;
38199 }
38200 if (this.negative !== 0) return -res | 0;
38201 return res;
38202 };
38203
38204 // Compare two numbers and return:
38205 // 1 - if `this` > `num`
38206 // 0 - if `this` == `num`
38207 // -1 - if `this` < `num`
38208 BN.prototype.cmp = function cmp (num) {
38209 if (this.negative !== 0 && num.negative === 0) return -1;
38210 if (this.negative === 0 && num.negative !== 0) return 1;
38211
38212 var res = this.ucmp(num);
38213 if (this.negative !== 0) return -res | 0;
38214 return res;
38215 };
38216
38217 // Unsigned comparison
38218 BN.prototype.ucmp = function ucmp (num) {
38219 // At this point both numbers have the same sign
38220 if (this.length > num.length) return 1;
38221 if (this.length < num.length) return -1;
38222
38223 var res = 0;
38224 for (var i = this.length - 1; i >= 0; i--) {
38225 var a = this.words[i] | 0;
38226 var b = num.words[i] | 0;
38227
38228 if (a === b) continue;
38229 if (a < b) {
38230 res = -1;
38231 } else if (a > b) {
38232 res = 1;
38233 }
38234 break;
38235 }
38236 return res;
38237 };
38238
38239 BN.prototype.gtn = function gtn (num) {
38240 return this.cmpn(num) === 1;
38241 };
38242
38243 BN.prototype.gt = function gt (num) {
38244 return this.cmp(num) === 1;
38245 };
38246
38247 BN.prototype.gten = function gten (num) {
38248 return this.cmpn(num) >= 0;
38249 };
38250
38251 BN.prototype.gte = function gte (num) {
38252 return this.cmp(num) >= 0;
38253 };
38254
38255 BN.prototype.ltn = function ltn (num) {
38256 return this.cmpn(num) === -1;
38257 };
38258
38259 BN.prototype.lt = function lt (num) {
38260 return this.cmp(num) === -1;
38261 };
38262
38263 BN.prototype.lten = function lten (num) {
38264 return this.cmpn(num) <= 0;
38265 };
38266
38267 BN.prototype.lte = function lte (num) {
38268 return this.cmp(num) <= 0;
38269 };
38270
38271 BN.prototype.eqn = function eqn (num) {
38272 return this.cmpn(num) === 0;
38273 };
38274
38275 BN.prototype.eq = function eq (num) {
38276 return this.cmp(num) === 0;
38277 };
38278
38279 //
38280 // A reduce context, could be using montgomery or something better, depending
38281 // on the `m` itself.
38282 //
38283 BN.red = function red (num) {
38284 return new Red(num);
38285 };
38286
38287 BN.prototype.toRed = function toRed (ctx) {
38288 assert(!this.red, 'Already a number in reduction context');
38289 assert(this.negative === 0, 'red works only with positives');
38290 return ctx.convertTo(this)._forceRed(ctx);
38291 };
38292
38293 BN.prototype.fromRed = function fromRed () {
38294 assert(this.red, 'fromRed works only with numbers in reduction context');
38295 return this.red.convertFrom(this);
38296 };
38297
38298 BN.prototype._forceRed = function _forceRed (ctx) {
38299 this.red = ctx;
38300 return this;
38301 };
38302
38303 BN.prototype.forceRed = function forceRed (ctx) {
38304 assert(!this.red, 'Already a number in reduction context');
38305 return this._forceRed(ctx);
38306 };
38307
38308 BN.prototype.redAdd = function redAdd (num) {
38309 assert(this.red, 'redAdd works only with red numbers');
38310 return this.red.add(this, num);
38311 };
38312
38313 BN.prototype.redIAdd = function redIAdd (num) {
38314 assert(this.red, 'redIAdd works only with red numbers');
38315 return this.red.iadd(this, num);
38316 };
38317
38318 BN.prototype.redSub = function redSub (num) {
38319 assert(this.red, 'redSub works only with red numbers');
38320 return this.red.sub(this, num);
38321 };
38322
38323 BN.prototype.redISub = function redISub (num) {
38324 assert(this.red, 'redISub works only with red numbers');
38325 return this.red.isub(this, num);
38326 };
38327
38328 BN.prototype.redShl = function redShl (num) {
38329 assert(this.red, 'redShl works only with red numbers');
38330 return this.red.shl(this, num);
38331 };
38332
38333 BN.prototype.redMul = function redMul (num) {
38334 assert(this.red, 'redMul works only with red numbers');
38335 this.red._verify2(this, num);
38336 return this.red.mul(this, num);
38337 };
38338
38339 BN.prototype.redIMul = function redIMul (num) {
38340 assert(this.red, 'redMul works only with red numbers');
38341 this.red._verify2(this, num);
38342 return this.red.imul(this, num);
38343 };
38344
38345 BN.prototype.redSqr = function redSqr () {
38346 assert(this.red, 'redSqr works only with red numbers');
38347 this.red._verify1(this);
38348 return this.red.sqr(this);
38349 };
38350
38351 BN.prototype.redISqr = function redISqr () {
38352 assert(this.red, 'redISqr works only with red numbers');
38353 this.red._verify1(this);
38354 return this.red.isqr(this);
38355 };
38356
38357 // Square root over p
38358 BN.prototype.redSqrt = function redSqrt () {
38359 assert(this.red, 'redSqrt works only with red numbers');
38360 this.red._verify1(this);
38361 return this.red.sqrt(this);
38362 };
38363
38364 BN.prototype.redInvm = function redInvm () {
38365 assert(this.red, 'redInvm works only with red numbers');
38366 this.red._verify1(this);
38367 return this.red.invm(this);
38368 };
38369
38370 // Return negative clone of `this` % `red modulo`
38371 BN.prototype.redNeg = function redNeg () {
38372 assert(this.red, 'redNeg works only with red numbers');
38373 this.red._verify1(this);
38374 return this.red.neg(this);
38375 };
38376
38377 BN.prototype.redPow = function redPow (num) {
38378 assert(this.red && !num.red, 'redPow(normalNum)');
38379 this.red._verify1(this);
38380 return this.red.pow(this, num);
38381 };
38382
38383 // Prime numbers with efficient reduction
38384 var primes = {
38385 k256: null,
38386 p224: null,
38387 p192: null,
38388 p25519: null
38389 };
38390
38391 // Pseudo-Mersenne prime
38392 function MPrime (name, p) {
38393 // P = 2 ^ N - K
38394 this.name = name;
38395 this.p = new BN(p, 16);
38396 this.n = this.p.bitLength();
38397 this.k = new BN(1).iushln(this.n).isub(this.p);
38398
38399 this.tmp = this._tmp();
38400 }
38401
38402 MPrime.prototype._tmp = function _tmp () {
38403 var tmp = new BN(null);
38404 tmp.words = new Array(Math.ceil(this.n / 13));
38405 return tmp;
38406 };
38407
38408 MPrime.prototype.ireduce = function ireduce (num) {
38409 // Assumes that `num` is less than `P^2`
38410 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
38411 var r = num;
38412 var rlen;
38413
38414 do {
38415 this.split(r, this.tmp);
38416 r = this.imulK(r);
38417 r = r.iadd(this.tmp);
38418 rlen = r.bitLength();
38419 } while (rlen > this.n);
38420
38421 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
38422 if (cmp === 0) {
38423 r.words[0] = 0;
38424 r.length = 1;
38425 } else if (cmp > 0) {
38426 r.isub(this.p);
38427 } else {
38428 r.strip();
38429 }
38430
38431 return r;
38432 };
38433
38434 MPrime.prototype.split = function split (input, out) {
38435 input.iushrn(this.n, 0, out);
38436 };
38437
38438 MPrime.prototype.imulK = function imulK (num) {
38439 return num.imul(this.k);
38440 };
38441
38442 function K256 () {
38443 MPrime.call(
38444 this,
38445 'k256',
38446 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
38447 }
38448 inherits(K256, MPrime);
38449
38450 K256.prototype.split = function split (input, output) {
38451 // 256 = 9 * 26 + 22
38452 var mask = 0x3fffff;
38453
38454 var outLen = Math.min(input.length, 9);
38455 for (var i = 0; i < outLen; i++) {
38456 output.words[i] = input.words[i];
38457 }
38458 output.length = outLen;
38459
38460 if (input.length <= 9) {
38461 input.words[0] = 0;
38462 input.length = 1;
38463 return;
38464 }
38465
38466 // Shift by 9 limbs
38467 var prev = input.words[9];
38468 output.words[output.length++] = prev & mask;
38469
38470 for (i = 10; i < input.length; i++) {
38471 var next = input.words[i] | 0;
38472 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
38473 prev = next;
38474 }
38475 prev >>>= 22;
38476 input.words[i - 10] = prev;
38477 if (prev === 0 && input.length > 10) {
38478 input.length -= 10;
38479 } else {
38480 input.length -= 9;
38481 }
38482 };
38483
38484 K256.prototype.imulK = function imulK (num) {
38485 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
38486 num.words[num.length] = 0;
38487 num.words[num.length + 1] = 0;
38488 num.length += 2;
38489
38490 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
38491 var lo = 0;
38492 for (var i = 0; i < num.length; i++) {
38493 var w = num.words[i] | 0;
38494 lo += w * 0x3d1;
38495 num.words[i] = lo & 0x3ffffff;
38496 lo = w * 0x40 + ((lo / 0x4000000) | 0);
38497 }
38498
38499 // Fast length reduction
38500 if (num.words[num.length - 1] === 0) {
38501 num.length--;
38502 if (num.words[num.length - 1] === 0) {
38503 num.length--;
38504 }
38505 }
38506 return num;
38507 };
38508
38509 function P224 () {
38510 MPrime.call(
38511 this,
38512 'p224',
38513 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
38514 }
38515 inherits(P224, MPrime);
38516
38517 function P192 () {
38518 MPrime.call(
38519 this,
38520 'p192',
38521 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
38522 }
38523 inherits(P192, MPrime);
38524
38525 function P25519 () {
38526 // 2 ^ 255 - 19
38527 MPrime.call(
38528 this,
38529 '25519',
38530 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
38531 }
38532 inherits(P25519, MPrime);
38533
38534 P25519.prototype.imulK = function imulK (num) {
38535 // K = 0x13
38536 var carry = 0;
38537 for (var i = 0; i < num.length; i++) {
38538 var hi = (num.words[i] | 0) * 0x13 + carry;
38539 var lo = hi & 0x3ffffff;
38540 hi >>>= 26;
38541
38542 num.words[i] = lo;
38543 carry = hi;
38544 }
38545 if (carry !== 0) {
38546 num.words[num.length++] = carry;
38547 }
38548 return num;
38549 };
38550
38551 // Exported mostly for testing purposes, use plain name instead
38552 BN._prime = function prime (name) {
38553 // Cached version of prime
38554 if (primes[name]) return primes[name];
38555
38556 var prime;
38557 if (name === 'k256') {
38558 prime = new K256();
38559 } else if (name === 'p224') {
38560 prime = new P224();
38561 } else if (name === 'p192') {
38562 prime = new P192();
38563 } else if (name === 'p25519') {
38564 prime = new P25519();
38565 } else {
38566 throw new Error('Unknown prime ' + name);
38567 }
38568 primes[name] = prime;
38569
38570 return prime;
38571 };
38572
38573 //
38574 // Base reduction engine
38575 //
38576 function Red (m) {
38577 if (typeof m === 'string') {
38578 var prime = BN._prime(m);
38579 this.m = prime.p;
38580 this.prime = prime;
38581 } else {
38582 assert(m.gtn(1), 'modulus must be greater than 1');
38583 this.m = m;
38584 this.prime = null;
38585 }
38586 }
38587
38588 Red.prototype._verify1 = function _verify1 (a) {
38589 assert(a.negative === 0, 'red works only with positives');
38590 assert(a.red, 'red works only with red numbers');
38591 };
38592
38593 Red.prototype._verify2 = function _verify2 (a, b) {
38594 assert((a.negative | b.negative) === 0, 'red works only with positives');
38595 assert(a.red && a.red === b.red,
38596 'red works only with red numbers');
38597 };
38598
38599 Red.prototype.imod = function imod (a) {
38600 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
38601 return a.umod(this.m)._forceRed(this);
38602 };
38603
38604 Red.prototype.neg = function neg (a) {
38605 if (a.isZero()) {
38606 return a.clone();
38607 }
38608
38609 return this.m.sub(a)._forceRed(this);
38610 };
38611
38612 Red.prototype.add = function add (a, b) {
38613 this._verify2(a, b);
38614
38615 var res = a.add(b);
38616 if (res.cmp(this.m) >= 0) {
38617 res.isub(this.m);
38618 }
38619 return res._forceRed(this);
38620 };
38621
38622 Red.prototype.iadd = function iadd (a, b) {
38623 this._verify2(a, b);
38624
38625 var res = a.iadd(b);
38626 if (res.cmp(this.m) >= 0) {
38627 res.isub(this.m);
38628 }
38629 return res;
38630 };
38631
38632 Red.prototype.sub = function sub (a, b) {
38633 this._verify2(a, b);
38634
38635 var res = a.sub(b);
38636 if (res.cmpn(0) < 0) {
38637 res.iadd(this.m);
38638 }
38639 return res._forceRed(this);
38640 };
38641
38642 Red.prototype.isub = function isub (a, b) {
38643 this._verify2(a, b);
38644
38645 var res = a.isub(b);
38646 if (res.cmpn(0) < 0) {
38647 res.iadd(this.m);
38648 }
38649 return res;
38650 };
38651
38652 Red.prototype.shl = function shl (a, num) {
38653 this._verify1(a);
38654 return this.imod(a.ushln(num));
38655 };
38656
38657 Red.prototype.imul = function imul (a, b) {
38658 this._verify2(a, b);
38659 return this.imod(a.imul(b));
38660 };
38661
38662 Red.prototype.mul = function mul (a, b) {
38663 this._verify2(a, b);
38664 return this.imod(a.mul(b));
38665 };
38666
38667 Red.prototype.isqr = function isqr (a) {
38668 return this.imul(a, a.clone());
38669 };
38670
38671 Red.prototype.sqr = function sqr (a) {
38672 return this.mul(a, a);
38673 };
38674
38675 Red.prototype.sqrt = function sqrt (a) {
38676 if (a.isZero()) return a.clone();
38677
38678 var mod3 = this.m.andln(3);
38679 assert(mod3 % 2 === 1);
38680
38681 // Fast case
38682 if (mod3 === 3) {
38683 var pow = this.m.add(new BN(1)).iushrn(2);
38684 return this.pow(a, pow);
38685 }
38686
38687 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
38688 //
38689 // Find Q and S, that Q * 2 ^ S = (P - 1)
38690 var q = this.m.subn(1);
38691 var s = 0;
38692 while (!q.isZero() && q.andln(1) === 0) {
38693 s++;
38694 q.iushrn(1);
38695 }
38696 assert(!q.isZero());
38697
38698 var one = new BN(1).toRed(this);
38699 var nOne = one.redNeg();
38700
38701 // Find quadratic non-residue
38702 // NOTE: Max is such because of generalized Riemann hypothesis.
38703 var lpow = this.m.subn(1).iushrn(1);
38704 var z = this.m.bitLength();
38705 z = new BN(2 * z * z).toRed(this);
38706
38707 while (this.pow(z, lpow).cmp(nOne) !== 0) {
38708 z.redIAdd(nOne);
38709 }
38710
38711 var c = this.pow(z, q);
38712 var r = this.pow(a, q.addn(1).iushrn(1));
38713 var t = this.pow(a, q);
38714 var m = s;
38715 while (t.cmp(one) !== 0) {
38716 var tmp = t;
38717 for (var i = 0; tmp.cmp(one) !== 0; i++) {
38718 tmp = tmp.redSqr();
38719 }
38720 assert(i < m);
38721 var b = this.pow(c, new BN(1).iushln(m - i - 1));
38722
38723 r = r.redMul(b);
38724 c = b.redSqr();
38725 t = t.redMul(c);
38726 m = i;
38727 }
38728
38729 return r;
38730 };
38731
38732 Red.prototype.invm = function invm (a) {
38733 var inv = a._invmp(this.m);
38734 if (inv.negative !== 0) {
38735 inv.negative = 0;
38736 return this.imod(inv).redNeg();
38737 } else {
38738 return this.imod(inv);
38739 }
38740 };
38741
38742 Red.prototype.pow = function pow (a, num) {
38743 if (num.isZero()) return new BN(1).toRed(this);
38744 if (num.cmpn(1) === 0) return a.clone();
38745
38746 var windowSize = 4;
38747 var wnd = new Array(1 << windowSize);
38748 wnd[0] = new BN(1).toRed(this);
38749 wnd[1] = a;
38750 for (var i = 2; i < wnd.length; i++) {
38751 wnd[i] = this.mul(wnd[i - 1], a);
38752 }
38753
38754 var res = wnd[0];
38755 var current = 0;
38756 var currentLen = 0;
38757 var start = num.bitLength() % 26;
38758 if (start === 0) {
38759 start = 26;
38760 }
38761
38762 for (i = num.length - 1; i >= 0; i--) {
38763 var word = num.words[i];
38764 for (var j = start - 1; j >= 0; j--) {
38765 var bit = (word >> j) & 1;
38766 if (res !== wnd[0]) {
38767 res = this.sqr(res);
38768 }
38769
38770 if (bit === 0 && current === 0) {
38771 currentLen = 0;
38772 continue;
38773 }
38774
38775 current <<= 1;
38776 current |= bit;
38777 currentLen++;
38778 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
38779
38780 res = this.mul(res, wnd[current]);
38781 currentLen = 0;
38782 current = 0;
38783 }
38784 start = 26;
38785 }
38786
38787 return res;
38788 };
38789
38790 Red.prototype.convertTo = function convertTo (num) {
38791 var r = num.umod(this.m);
38792
38793 return r === num ? r.clone() : r;
38794 };
38795
38796 Red.prototype.convertFrom = function convertFrom (num) {
38797 var res = num.clone();
38798 res.red = null;
38799 return res;
38800 };
38801
38802 //
38803 // Montgomery method engine
38804 //
38805
38806 BN.mont = function mont (num) {
38807 return new Mont(num);
38808 };
38809
38810 function Mont (m) {
38811 Red.call(this, m);
38812
38813 this.shift = this.m.bitLength();
38814 if (this.shift % 26 !== 0) {
38815 this.shift += 26 - (this.shift % 26);
38816 }
38817
38818 this.r = new BN(1).iushln(this.shift);
38819 this.r2 = this.imod(this.r.sqr());
38820 this.rinv = this.r._invmp(this.m);
38821
38822 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
38823 this.minv = this.minv.umod(this.r);
38824 this.minv = this.r.sub(this.minv);
38825 }
38826 inherits(Mont, Red);
38827
38828 Mont.prototype.convertTo = function convertTo (num) {
38829 return this.imod(num.ushln(this.shift));
38830 };
38831
38832 Mont.prototype.convertFrom = function convertFrom (num) {
38833 var r = this.imod(num.mul(this.rinv));
38834 r.red = null;
38835 return r;
38836 };
38837
38838 Mont.prototype.imul = function imul (a, b) {
38839 if (a.isZero() || b.isZero()) {
38840 a.words[0] = 0;
38841 a.length = 1;
38842 return a;
38843 }
38844
38845 var t = a.imul(b);
38846 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38847 var u = t.isub(c).iushrn(this.shift);
38848 var res = u;
38849
38850 if (u.cmp(this.m) >= 0) {
38851 res = u.isub(this.m);
38852 } else if (u.cmpn(0) < 0) {
38853 res = u.iadd(this.m);
38854 }
38855
38856 return res._forceRed(this);
38857 };
38858
38859 Mont.prototype.mul = function mul (a, b) {
38860 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
38861
38862 var t = a.mul(b);
38863 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38864 var u = t.isub(c).iushrn(this.shift);
38865 var res = u;
38866 if (u.cmp(this.m) >= 0) {
38867 res = u.isub(this.m);
38868 } else if (u.cmpn(0) < 0) {
38869 res = u.iadd(this.m);
38870 }
38871
38872 return res._forceRed(this);
38873 };
38874
38875 Mont.prototype.invm = function invm (a) {
38876 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
38877 var res = this.imod(a._invmp(this.m).mul(this.r2));
38878 return res._forceRed(this);
38879 };
38880})(module, commonjsGlobal);
38881});
38882
38883var bn$1 = /*#__PURE__*/Object.freeze({
38884 __proto__: null,
38885 'default': bn,
38886 __moduleExports: bn
38887});
38888
38889/**
38890 * @fileoverview
38891 * BigInteger implementation of basic operations
38892 * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
38893 * @module biginteger/bn
38894 * @private
38895 */
38896
38897/**
38898 * @private
38899 */
38900class BigInteger$1 {
38901 /**
38902 * Get a BigInteger (input must be big endian for strings and arrays)
38903 * @param {Number|String|Uint8Array} n - Value to convert
38904 * @throws {Error} on undefined input
38905 */
38906 constructor(n) {
38907 if (n === undefined) {
38908 throw new Error('Invalid BigInteger input');
38909 }
38910
38911 this.value = new bn(n);
38912 }
38913
38914 clone() {
38915 const clone = new BigInteger$1(null);
38916 this.value.copy(clone.value);
38917 return clone;
38918 }
38919
38920 /**
38921 * BigInteger increment in place
38922 */
38923 iinc() {
38924 this.value.iadd(new bn(1));
38925 return this;
38926 }
38927
38928 /**
38929 * BigInteger increment
38930 * @returns {BigInteger} this + 1.
38931 */
38932 inc() {
38933 return this.clone().iinc();
38934 }
38935
38936 /**
38937 * BigInteger decrement in place
38938 */
38939 idec() {
38940 this.value.isub(new bn(1));
38941 return this;
38942 }
38943
38944 /**
38945 * BigInteger decrement
38946 * @returns {BigInteger} this - 1.
38947 */
38948 dec() {
38949 return this.clone().idec();
38950 }
38951
38952
38953 /**
38954 * BigInteger addition in place
38955 * @param {BigInteger} x - Value to add
38956 */
38957 iadd(x) {
38958 this.value.iadd(x.value);
38959 return this;
38960 }
38961
38962 /**
38963 * BigInteger addition
38964 * @param {BigInteger} x - Value to add
38965 * @returns {BigInteger} this + x.
38966 */
38967 add(x) {
38968 return this.clone().iadd(x);
38969 }
38970
38971 /**
38972 * BigInteger subtraction in place
38973 * @param {BigInteger} x - Value to subtract
38974 */
38975 isub(x) {
38976 this.value.isub(x.value);
38977 return this;
38978 }
38979
38980 /**
38981 * BigInteger subtraction
38982 * @param {BigInteger} x - Value to subtract
38983 * @returns {BigInteger} this - x.
38984 */
38985 sub(x) {
38986 return this.clone().isub(x);
38987 }
38988
38989 /**
38990 * BigInteger multiplication in place
38991 * @param {BigInteger} x - Value to multiply
38992 */
38993 imul(x) {
38994 this.value.imul(x.value);
38995 return this;
38996 }
38997
38998 /**
38999 * BigInteger multiplication
39000 * @param {BigInteger} x - Value to multiply
39001 * @returns {BigInteger} this * x.
39002 */
39003 mul(x) {
39004 return this.clone().imul(x);
39005 }
39006
39007 /**
39008 * Compute value modulo m, in place
39009 * @param {BigInteger} m - Modulo
39010 */
39011 imod(m) {
39012 this.value = this.value.umod(m.value);
39013 return this;
39014 }
39015
39016 /**
39017 * Compute value modulo m
39018 * @param {BigInteger} m - Modulo
39019 * @returns {BigInteger} this mod m.
39020 */
39021 mod(m) {
39022 return this.clone().imod(m);
39023 }
39024
39025 /**
39026 * Compute modular exponentiation
39027 * Much faster than this.exp(e).mod(n)
39028 * @param {BigInteger} e - Exponent
39029 * @param {BigInteger} n - Modulo
39030 * @returns {BigInteger} this ** e mod n.
39031 */
39032 modExp(e, n) {
39033 // We use either Montgomery or normal reduction context
39034 // Montgomery requires coprime n and R (montogmery multiplier)
39035 // bn.js picks R as power of 2, so n must be odd
39036 const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value);
39037 const x = this.clone();
39038 x.value = x.value.toRed(nred).redPow(e.value).fromRed();
39039 return x;
39040 }
39041
39042 /**
39043 * Compute the inverse of this value modulo n
39044 * Note: this and and n must be relatively prime
39045 * @param {BigInteger} n - Modulo
39046 * @returns {BigInteger} x such that this*x = 1 mod n
39047 * @throws {Error} if the inverse does not exist
39048 */
39049 modInv(n) {
39050 // invm returns a wrong result if the inverse does not exist
39051 if (!this.gcd(n).isOne()) {
39052 throw new Error('Inverse does not exist');
39053 }
39054 return new BigInteger$1(this.value.invm(n.value));
39055 }
39056
39057 /**
39058 * Compute greatest common divisor between this and n
39059 * @param {BigInteger} n - Operand
39060 * @returns {BigInteger} gcd
39061 */
39062 gcd(n) {
39063 return new BigInteger$1(this.value.gcd(n.value));
39064 }
39065
39066 /**
39067 * Shift this to the left by x, in place
39068 * @param {BigInteger} x - Shift value
39069 */
39070 ileftShift(x) {
39071 this.value.ishln(x.value.toNumber());
39072 return this;
39073 }
39074
39075 /**
39076 * Shift this to the left by x
39077 * @param {BigInteger} x - Shift value
39078 * @returns {BigInteger} this << x.
39079 */
39080 leftShift(x) {
39081 return this.clone().ileftShift(x);
39082 }
39083
39084 /**
39085 * Shift this to the right by x, in place
39086 * @param {BigInteger} x - Shift value
39087 */
39088 irightShift(x) {
39089 this.value.ishrn(x.value.toNumber());
39090 return this;
39091 }
39092
39093 /**
39094 * Shift this to the right by x
39095 * @param {BigInteger} x - Shift value
39096 * @returns {BigInteger} this >> x.
39097 */
39098 rightShift(x) {
39099 return this.clone().irightShift(x);
39100 }
39101
39102 /**
39103 * Whether this value is equal to x
39104 * @param {BigInteger} x
39105 * @returns {Boolean}
39106 */
39107 equal(x) {
39108 return this.value.eq(x.value);
39109 }
39110
39111 /**
39112 * Whether this value is less than x
39113 * @param {BigInteger} x
39114 * @returns {Boolean}
39115 */
39116 lt(x) {
39117 return this.value.lt(x.value);
39118 }
39119
39120 /**
39121 * Whether this value is less than or equal to x
39122 * @param {BigInteger} x
39123 * @returns {Boolean}
39124 */
39125 lte(x) {
39126 return this.value.lte(x.value);
39127 }
39128
39129 /**
39130 * Whether this value is greater than x
39131 * @param {BigInteger} x
39132 * @returns {Boolean}
39133 */
39134 gt(x) {
39135 return this.value.gt(x.value);
39136 }
39137
39138 /**
39139 * Whether this value is greater than or equal to x
39140 * @param {BigInteger} x
39141 * @returns {Boolean}
39142 */
39143 gte(x) {
39144 return this.value.gte(x.value);
39145 }
39146
39147 isZero() {
39148 return this.value.isZero();
39149 }
39150
39151 isOne() {
39152 return this.value.eq(new bn(1));
39153 }
39154
39155 isNegative() {
39156 return this.value.isNeg();
39157 }
39158
39159 isEven() {
39160 return this.value.isEven();
39161 }
39162
39163 abs() {
39164 const res = this.clone();
39165 res.value = res.value.abs();
39166 return res;
39167 }
39168
39169 /**
39170 * Get this value as a string
39171 * @returns {String} this value.
39172 */
39173 toString() {
39174 return this.value.toString();
39175 }
39176
39177 /**
39178 * Get this value as an exact Number (max 53 bits)
39179 * Fails if this value is too large
39180 * @returns {Number}
39181 */
39182 toNumber() {
39183 return this.value.toNumber();
39184 }
39185
39186 /**
39187 * Get value of i-th bit
39188 * @param {Number} i - Bit index
39189 * @returns {Number} Bit value.
39190 */
39191 getBit(i) {
39192 return this.value.testn(i) ? 1 : 0;
39193 }
39194
39195 /**
39196 * Compute bit length
39197 * @returns {Number} Bit length.
39198 */
39199 bitLength() {
39200 return this.value.bitLength();
39201 }
39202
39203 /**
39204 * Compute byte length
39205 * @returns {Number} Byte length.
39206 */
39207 byteLength() {
39208 return this.value.byteLength();
39209 }
39210
39211 /**
39212 * Get Uint8Array representation of this number
39213 * @param {String} endian - Endianess of output array (defaults to 'be')
39214 * @param {Number} length - Of output array
39215 * @returns {Uint8Array}
39216 */
39217 toUint8Array(endian = 'be', length) {
39218 return this.value.toArrayLike(Uint8Array, endian, length);
39219 }
39220}
39221
39222var bn_interface = /*#__PURE__*/Object.freeze({
39223 __proto__: null,
39224 'default': BigInteger$1
39225});
39226
39227var utils_1 = createCommonjsModule(function (module, exports) {
39228
39229var utils = exports;
39230
39231function toArray(msg, enc) {
39232 if (Array.isArray(msg))
39233 return msg.slice();
39234 if (!msg)
39235 return [];
39236 var res = [];
39237 if (typeof msg !== 'string') {
39238 for (var i = 0; i < msg.length; i++)
39239 res[i] = msg[i] | 0;
39240 return res;
39241 }
39242 if (enc === 'hex') {
39243 msg = msg.replace(/[^a-z0-9]+/ig, '');
39244 if (msg.length % 2 !== 0)
39245 msg = '0' + msg;
39246 for (var i = 0; i < msg.length; i += 2)
39247 res.push(parseInt(msg[i] + msg[i + 1], 16));
39248 } else {
39249 for (var i = 0; i < msg.length; i++) {
39250 var c = msg.charCodeAt(i);
39251 var hi = c >> 8;
39252 var lo = c & 0xff;
39253 if (hi)
39254 res.push(hi, lo);
39255 else
39256 res.push(lo);
39257 }
39258 }
39259 return res;
39260}
39261utils.toArray = toArray;
39262
39263function zero2(word) {
39264 if (word.length === 1)
39265 return '0' + word;
39266 else
39267 return word;
39268}
39269utils.zero2 = zero2;
39270
39271function toHex(msg) {
39272 var res = '';
39273 for (var i = 0; i < msg.length; i++)
39274 res += zero2(msg[i].toString(16));
39275 return res;
39276}
39277utils.toHex = toHex;
39278
39279utils.encode = function encode(arr, enc) {
39280 if (enc === 'hex')
39281 return toHex(arr);
39282 else
39283 return arr;
39284};
39285});
39286
39287var utils_1$1 = createCommonjsModule(function (module, exports) {
39288
39289var utils = exports;
39290
39291
39292
39293
39294utils.assert = minimalisticAssert;
39295utils.toArray = utils_1.toArray;
39296utils.zero2 = utils_1.zero2;
39297utils.toHex = utils_1.toHex;
39298utils.encode = utils_1.encode;
39299
39300// Represent num in a w-NAF form
39301function getNAF(num, w) {
39302 var naf = [];
39303 var ws = 1 << (w + 1);
39304 var k = num.clone();
39305 while (k.cmpn(1) >= 0) {
39306 var z;
39307 if (k.isOdd()) {
39308 var mod = k.andln(ws - 1);
39309 if (mod > (ws >> 1) - 1)
39310 z = (ws >> 1) - mod;
39311 else
39312 z = mod;
39313 k.isubn(z);
39314 } else {
39315 z = 0;
39316 }
39317 naf.push(z);
39318
39319 // Optimization, shift by word if possible
39320 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
39321 for (var i = 1; i < shift; i++)
39322 naf.push(0);
39323 k.iushrn(shift);
39324 }
39325
39326 return naf;
39327}
39328utils.getNAF = getNAF;
39329
39330// Represent k1, k2 in a Joint Sparse Form
39331function getJSF(k1, k2) {
39332 var jsf = [
39333 [],
39334 []
39335 ];
39336
39337 k1 = k1.clone();
39338 k2 = k2.clone();
39339 var d1 = 0;
39340 var d2 = 0;
39341 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
39342
39343 // First phase
39344 var m14 = (k1.andln(3) + d1) & 3;
39345 var m24 = (k2.andln(3) + d2) & 3;
39346 if (m14 === 3)
39347 m14 = -1;
39348 if (m24 === 3)
39349 m24 = -1;
39350 var u1;
39351 if ((m14 & 1) === 0) {
39352 u1 = 0;
39353 } else {
39354 var m8 = (k1.andln(7) + d1) & 7;
39355 if ((m8 === 3 || m8 === 5) && m24 === 2)
39356 u1 = -m14;
39357 else
39358 u1 = m14;
39359 }
39360 jsf[0].push(u1);
39361
39362 var u2;
39363 if ((m24 & 1) === 0) {
39364 u2 = 0;
39365 } else {
39366 var m8 = (k2.andln(7) + d2) & 7;
39367 if ((m8 === 3 || m8 === 5) && m14 === 2)
39368 u2 = -m24;
39369 else
39370 u2 = m24;
39371 }
39372 jsf[1].push(u2);
39373
39374 // Second phase
39375 if (2 * d1 === u1 + 1)
39376 d1 = 1 - d1;
39377 if (2 * d2 === u2 + 1)
39378 d2 = 1 - d2;
39379 k1.iushrn(1);
39380 k2.iushrn(1);
39381 }
39382
39383 return jsf;
39384}
39385utils.getJSF = getJSF;
39386
39387function cachedProperty(obj, name, computer) {
39388 var key = '_' + name;
39389 obj.prototype[name] = function cachedProperty() {
39390 return this[key] !== undefined ? this[key] :
39391 this[key] = computer.call(this);
39392 };
39393}
39394utils.cachedProperty = cachedProperty;
39395
39396function parseBytes(bytes) {
39397 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
39398 bytes;
39399}
39400utils.parseBytes = parseBytes;
39401
39402function intFromLE(bytes) {
39403 return new bn(bytes, 'hex', 'le');
39404}
39405utils.intFromLE = intFromLE;
39406});
39407
39408var r$1;
39409
39410var brorand = function rand(len) {
39411 if (!r$1)
39412 r$1 = new Rand(null);
39413
39414 return r$1.generate(len);
39415};
39416
39417function Rand(rand) {
39418 this.rand = rand;
39419}
39420var Rand_1 = Rand;
39421
39422Rand.prototype.generate = function generate(len) {
39423 return this._rand(len);
39424};
39425
39426// Emulate crypto API using randy
39427Rand.prototype._rand = function _rand(n) {
39428 if (this.rand.getBytes)
39429 return this.rand.getBytes(n);
39430
39431 var res = new Uint8Array(n);
39432 for (var i = 0; i < res.length; i++)
39433 res[i] = this.rand.getByte();
39434 return res;
39435};
39436
39437if (typeof self === 'object') {
39438 if (self.crypto && self.crypto.getRandomValues) {
39439 // Modern browsers
39440 Rand.prototype._rand = function _rand(n) {
39441 var arr = new Uint8Array(n);
39442 self.crypto.getRandomValues(arr);
39443 return arr;
39444 };
39445 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39446 // IE
39447 Rand.prototype._rand = function _rand(n) {
39448 var arr = new Uint8Array(n);
39449 self.msCrypto.getRandomValues(arr);
39450 return arr;
39451 };
39452
39453 // Safari's WebWorkers do not have `crypto`
39454 } else if (typeof window === 'object') {
39455 // Old junk
39456 Rand.prototype._rand = function() {
39457 throw new Error('Not implemented yet');
39458 };
39459 }
39460} else {
39461 // Node.js or Web worker with no crypto support
39462 try {
39463 var crypto$2 = crypto__default['default'];
39464 if (typeof crypto$2.randomBytes !== 'function')
39465 throw new Error('Not supported');
39466
39467 Rand.prototype._rand = function _rand(n) {
39468 return crypto$2.randomBytes(n);
39469 };
39470 } catch (e) {
39471 }
39472}
39473brorand.Rand = Rand_1;
39474
39475var getNAF = utils_1$1.getNAF;
39476var getJSF = utils_1$1.getJSF;
39477var assert$2 = utils_1$1.assert;
39478
39479function BaseCurve(type, conf) {
39480 this.type = type;
39481 this.p = new bn(conf.p, 16);
39482
39483 // Use Montgomery, when there is no fast reduction for the prime
39484 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
39485
39486 // Useful for many curves
39487 this.zero = new bn(0).toRed(this.red);
39488 this.one = new bn(1).toRed(this.red);
39489 this.two = new bn(2).toRed(this.red);
39490
39491 // Curve configuration, optional
39492 this.n = conf.n && new bn(conf.n, 16);
39493 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
39494
39495 // Temporary arrays
39496 this._wnafT1 = new Array(4);
39497 this._wnafT2 = new Array(4);
39498 this._wnafT3 = new Array(4);
39499 this._wnafT4 = new Array(4);
39500
39501 // Generalized Greg Maxwell's trick
39502 var adjustCount = this.n && this.p.div(this.n);
39503 if (!adjustCount || adjustCount.cmpn(100) > 0) {
39504 this.redN = null;
39505 } else {
39506 this._maxwellTrick = true;
39507 this.redN = this.n.toRed(this.red);
39508 }
39509}
39510var base = BaseCurve;
39511
39512BaseCurve.prototype.point = function point() {
39513 throw new Error('Not implemented');
39514};
39515
39516BaseCurve.prototype.validate = function validate() {
39517 throw new Error('Not implemented');
39518};
39519
39520BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
39521 assert$2(p.precomputed);
39522 var doubles = p._getDoubles();
39523
39524 var naf = getNAF(k, 1);
39525 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
39526 I /= 3;
39527
39528 // Translate into more windowed form
39529 var repr = [];
39530 for (var j = 0; j < naf.length; j += doubles.step) {
39531 var nafW = 0;
39532 for (var k = j + doubles.step - 1; k >= j; k--)
39533 nafW = (nafW << 1) + naf[k];
39534 repr.push(nafW);
39535 }
39536
39537 var a = this.jpoint(null, null, null);
39538 var b = this.jpoint(null, null, null);
39539 for (var i = I; i > 0; i--) {
39540 for (var j = 0; j < repr.length; j++) {
39541 var nafW = repr[j];
39542 if (nafW === i)
39543 b = b.mixedAdd(doubles.points[j]);
39544 else if (nafW === -i)
39545 b = b.mixedAdd(doubles.points[j].neg());
39546 }
39547 a = a.add(b);
39548 }
39549 return a.toP();
39550};
39551
39552BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
39553 var w = 4;
39554
39555 // Precompute window
39556 var nafPoints = p._getNAFPoints(w);
39557 w = nafPoints.wnd;
39558 var wnd = nafPoints.points;
39559
39560 // Get NAF form
39561 var naf = getNAF(k, w);
39562
39563 // Add `this`*(N+1) for every w-NAF index
39564 var acc = this.jpoint(null, null, null);
39565 for (var i = naf.length - 1; i >= 0; i--) {
39566 // Count zeroes
39567 for (var k = 0; i >= 0 && naf[i] === 0; i--)
39568 k++;
39569 if (i >= 0)
39570 k++;
39571 acc = acc.dblp(k);
39572
39573 if (i < 0)
39574 break;
39575 var z = naf[i];
39576 assert$2(z !== 0);
39577 if (p.type === 'affine') {
39578 // J +- P
39579 if (z > 0)
39580 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
39581 else
39582 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
39583 } else {
39584 // J +- J
39585 if (z > 0)
39586 acc = acc.add(wnd[(z - 1) >> 1]);
39587 else
39588 acc = acc.add(wnd[(-z - 1) >> 1].neg());
39589 }
39590 }
39591 return p.type === 'affine' ? acc.toP() : acc;
39592};
39593
39594BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
39595 points,
39596 coeffs,
39597 len,
39598 jacobianResult) {
39599 var wndWidth = this._wnafT1;
39600 var wnd = this._wnafT2;
39601 var naf = this._wnafT3;
39602
39603 // Fill all arrays
39604 var max = 0;
39605 for (var i = 0; i < len; i++) {
39606 var p = points[i];
39607 var nafPoints = p._getNAFPoints(defW);
39608 wndWidth[i] = nafPoints.wnd;
39609 wnd[i] = nafPoints.points;
39610 }
39611
39612 // Comb small window NAFs
39613 for (var i = len - 1; i >= 1; i -= 2) {
39614 var a = i - 1;
39615 var b = i;
39616 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
39617 naf[a] = getNAF(coeffs[a], wndWidth[a]);
39618 naf[b] = getNAF(coeffs[b], wndWidth[b]);
39619 max = Math.max(naf[a].length, max);
39620 max = Math.max(naf[b].length, max);
39621 continue;
39622 }
39623
39624 var comb = [
39625 points[a], /* 1 */
39626 null, /* 3 */
39627 null, /* 5 */
39628 points[b] /* 7 */
39629 ];
39630
39631 // Try to avoid Projective points, if possible
39632 if (points[a].y.cmp(points[b].y) === 0) {
39633 comb[1] = points[a].add(points[b]);
39634 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39635 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
39636 comb[1] = points[a].toJ().mixedAdd(points[b]);
39637 comb[2] = points[a].add(points[b].neg());
39638 } else {
39639 comb[1] = points[a].toJ().mixedAdd(points[b]);
39640 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39641 }
39642
39643 var index = [
39644 -3, /* -1 -1 */
39645 -1, /* -1 0 */
39646 -5, /* -1 1 */
39647 -7, /* 0 -1 */
39648 0, /* 0 0 */
39649 7, /* 0 1 */
39650 5, /* 1 -1 */
39651 1, /* 1 0 */
39652 3 /* 1 1 */
39653 ];
39654
39655 var jsf = getJSF(coeffs[a], coeffs[b]);
39656 max = Math.max(jsf[0].length, max);
39657 naf[a] = new Array(max);
39658 naf[b] = new Array(max);
39659 for (var j = 0; j < max; j++) {
39660 var ja = jsf[0][j] | 0;
39661 var jb = jsf[1][j] | 0;
39662
39663 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
39664 naf[b][j] = 0;
39665 wnd[a] = comb;
39666 }
39667 }
39668
39669 var acc = this.jpoint(null, null, null);
39670 var tmp = this._wnafT4;
39671 for (var i = max; i >= 0; i--) {
39672 var k = 0;
39673
39674 while (i >= 0) {
39675 var zero = true;
39676 for (var j = 0; j < len; j++) {
39677 tmp[j] = naf[j][i] | 0;
39678 if (tmp[j] !== 0)
39679 zero = false;
39680 }
39681 if (!zero)
39682 break;
39683 k++;
39684 i--;
39685 }
39686 if (i >= 0)
39687 k++;
39688 acc = acc.dblp(k);
39689 if (i < 0)
39690 break;
39691
39692 for (var j = 0; j < len; j++) {
39693 var z = tmp[j];
39694 var p;
39695 if (z === 0)
39696 continue;
39697 else if (z > 0)
39698 p = wnd[j][(z - 1) >> 1];
39699 else if (z < 0)
39700 p = wnd[j][(-z - 1) >> 1].neg();
39701
39702 if (p.type === 'affine')
39703 acc = acc.mixedAdd(p);
39704 else
39705 acc = acc.add(p);
39706 }
39707 }
39708 // Zeroify references
39709 for (var i = 0; i < len; i++)
39710 wnd[i] = null;
39711
39712 if (jacobianResult)
39713 return acc;
39714 else
39715 return acc.toP();
39716};
39717
39718function BasePoint(curve, type) {
39719 this.curve = curve;
39720 this.type = type;
39721 this.precomputed = null;
39722}
39723BaseCurve.BasePoint = BasePoint;
39724
39725BasePoint.prototype.eq = function eq(/*other*/) {
39726 throw new Error('Not implemented');
39727};
39728
39729BasePoint.prototype.validate = function validate() {
39730 return this.curve.validate(this);
39731};
39732
39733BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
39734 bytes = utils_1$1.toArray(bytes, enc);
39735
39736 var len = this.p.byteLength();
39737
39738 // uncompressed, hybrid-odd, hybrid-even
39739 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
39740 bytes.length - 1 === 2 * len) {
39741 if (bytes[0] === 0x06)
39742 assert$2(bytes[bytes.length - 1] % 2 === 0);
39743 else if (bytes[0] === 0x07)
39744 assert$2(bytes[bytes.length - 1] % 2 === 1);
39745
39746 var res = this.point(bytes.slice(1, 1 + len),
39747 bytes.slice(1 + len, 1 + 2 * len));
39748
39749 return res;
39750 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
39751 bytes.length - 1 === len) {
39752 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
39753 }
39754 throw new Error('Unknown point format');
39755};
39756
39757BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
39758 return this.encode(enc, true);
39759};
39760
39761BasePoint.prototype._encode = function _encode(compact) {
39762 var len = this.curve.p.byteLength();
39763 var x = this.getX().toArray('be', len);
39764
39765 if (compact)
39766 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
39767
39768 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
39769};
39770
39771BasePoint.prototype.encode = function encode(enc, compact) {
39772 return utils_1$1.encode(this._encode(compact), enc);
39773};
39774
39775BasePoint.prototype.precompute = function precompute(power) {
39776 if (this.precomputed)
39777 return this;
39778
39779 var precomputed = {
39780 doubles: null,
39781 naf: null,
39782 beta: null
39783 };
39784 precomputed.naf = this._getNAFPoints(8);
39785 precomputed.doubles = this._getDoubles(4, power);
39786 precomputed.beta = this._getBeta();
39787 this.precomputed = precomputed;
39788
39789 return this;
39790};
39791
39792BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
39793 if (!this.precomputed)
39794 return false;
39795
39796 var doubles = this.precomputed.doubles;
39797 if (!doubles)
39798 return false;
39799
39800 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
39801};
39802
39803BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
39804 if (this.precomputed && this.precomputed.doubles)
39805 return this.precomputed.doubles;
39806
39807 var doubles = [ this ];
39808 var acc = this;
39809 for (var i = 0; i < power; i += step) {
39810 for (var j = 0; j < step; j++)
39811 acc = acc.dbl();
39812 doubles.push(acc);
39813 }
39814 return {
39815 step: step,
39816 points: doubles
39817 };
39818};
39819
39820BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
39821 if (this.precomputed && this.precomputed.naf)
39822 return this.precomputed.naf;
39823
39824 var res = [ this ];
39825 var max = (1 << wnd) - 1;
39826 var dbl = max === 1 ? null : this.dbl();
39827 for (var i = 1; i < max; i++)
39828 res[i] = res[i - 1].add(dbl);
39829 return {
39830 wnd: wnd,
39831 points: res
39832 };
39833};
39834
39835BasePoint.prototype._getBeta = function _getBeta() {
39836 return null;
39837};
39838
39839BasePoint.prototype.dblp = function dblp(k) {
39840 var r = this;
39841 for (var i = 0; i < k; i++)
39842 r = r.dbl();
39843 return r;
39844};
39845
39846var assert$3 = utils_1$1.assert;
39847
39848function ShortCurve(conf) {
39849 base.call(this, 'short', conf);
39850
39851 this.a = new bn(conf.a, 16).toRed(this.red);
39852 this.b = new bn(conf.b, 16).toRed(this.red);
39853 this.tinv = this.two.redInvm();
39854
39855 this.zeroA = this.a.fromRed().cmpn(0) === 0;
39856 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
39857
39858 // If the curve is endomorphic, precalculate beta and lambda
39859 this.endo = this._getEndomorphism(conf);
39860 this._endoWnafT1 = new Array(4);
39861 this._endoWnafT2 = new Array(4);
39862}
39863inherits(ShortCurve, base);
39864var short_1 = ShortCurve;
39865
39866ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
39867 // No efficient endomorphism
39868 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
39869 return;
39870
39871 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
39872 var beta;
39873 var lambda;
39874 if (conf.beta) {
39875 beta = new bn(conf.beta, 16).toRed(this.red);
39876 } else {
39877 var betas = this._getEndoRoots(this.p);
39878 // Choose the smallest beta
39879 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
39880 beta = beta.toRed(this.red);
39881 }
39882 if (conf.lambda) {
39883 lambda = new bn(conf.lambda, 16);
39884 } else {
39885 // Choose the lambda that is matching selected beta
39886 var lambdas = this._getEndoRoots(this.n);
39887 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
39888 lambda = lambdas[0];
39889 } else {
39890 lambda = lambdas[1];
39891 assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
39892 }
39893 }
39894
39895 // Get basis vectors, used for balanced length-two representation
39896 var basis;
39897 if (conf.basis) {
39898 basis = conf.basis.map(function(vec) {
39899 return {
39900 a: new bn(vec.a, 16),
39901 b: new bn(vec.b, 16)
39902 };
39903 });
39904 } else {
39905 basis = this._getEndoBasis(lambda);
39906 }
39907
39908 return {
39909 beta: beta,
39910 lambda: lambda,
39911 basis: basis
39912 };
39913};
39914
39915ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
39916 // Find roots of for x^2 + x + 1 in F
39917 // Root = (-1 +- Sqrt(-3)) / 2
39918 //
39919 var red = num === this.p ? this.red : bn.mont(num);
39920 var tinv = new bn(2).toRed(red).redInvm();
39921 var ntinv = tinv.redNeg();
39922
39923 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
39924
39925 var l1 = ntinv.redAdd(s).fromRed();
39926 var l2 = ntinv.redSub(s).fromRed();
39927 return [ l1, l2 ];
39928};
39929
39930ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
39931 // aprxSqrt >= sqrt(this.n)
39932 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
39933
39934 // 3.74
39935 // Run EGCD, until r(L + 1) < aprxSqrt
39936 var u = lambda;
39937 var v = this.n.clone();
39938 var x1 = new bn(1);
39939 var y1 = new bn(0);
39940 var x2 = new bn(0);
39941 var y2 = new bn(1);
39942
39943 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
39944 var a0;
39945 var b0;
39946 // First vector
39947 var a1;
39948 var b1;
39949 // Second vector
39950 var a2;
39951 var b2;
39952
39953 var prevR;
39954 var i = 0;
39955 var r;
39956 var x;
39957 while (u.cmpn(0) !== 0) {
39958 var q = v.div(u);
39959 r = v.sub(q.mul(u));
39960 x = x2.sub(q.mul(x1));
39961 var y = y2.sub(q.mul(y1));
39962
39963 if (!a1 && r.cmp(aprxSqrt) < 0) {
39964 a0 = prevR.neg();
39965 b0 = x1;
39966 a1 = r.neg();
39967 b1 = x;
39968 } else if (a1 && ++i === 2) {
39969 break;
39970 }
39971 prevR = r;
39972
39973 v = u;
39974 u = r;
39975 x2 = x1;
39976 x1 = x;
39977 y2 = y1;
39978 y1 = y;
39979 }
39980 a2 = r.neg();
39981 b2 = x;
39982
39983 var len1 = a1.sqr().add(b1.sqr());
39984 var len2 = a2.sqr().add(b2.sqr());
39985 if (len2.cmp(len1) >= 0) {
39986 a2 = a0;
39987 b2 = b0;
39988 }
39989
39990 // Normalize signs
39991 if (a1.negative) {
39992 a1 = a1.neg();
39993 b1 = b1.neg();
39994 }
39995 if (a2.negative) {
39996 a2 = a2.neg();
39997 b2 = b2.neg();
39998 }
39999
40000 return [
40001 { a: a1, b: b1 },
40002 { a: a2, b: b2 }
40003 ];
40004};
40005
40006ShortCurve.prototype._endoSplit = function _endoSplit(k) {
40007 var basis = this.endo.basis;
40008 var v1 = basis[0];
40009 var v2 = basis[1];
40010
40011 var c1 = v2.b.mul(k).divRound(this.n);
40012 var c2 = v1.b.neg().mul(k).divRound(this.n);
40013
40014 var p1 = c1.mul(v1.a);
40015 var p2 = c2.mul(v2.a);
40016 var q1 = c1.mul(v1.b);
40017 var q2 = c2.mul(v2.b);
40018
40019 // Calculate answer
40020 var k1 = k.sub(p1).sub(p2);
40021 var k2 = q1.add(q2).neg();
40022 return { k1: k1, k2: k2 };
40023};
40024
40025ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
40026 x = new bn(x, 16);
40027 if (!x.red)
40028 x = x.toRed(this.red);
40029
40030 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
40031 var y = y2.redSqrt();
40032 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
40033 throw new Error('invalid point');
40034
40035 // XXX Is there any way to tell if the number is odd without converting it
40036 // to non-red form?
40037 var isOdd = y.fromRed().isOdd();
40038 if (odd && !isOdd || !odd && isOdd)
40039 y = y.redNeg();
40040
40041 return this.point(x, y);
40042};
40043
40044ShortCurve.prototype.validate = function validate(point) {
40045 if (point.inf)
40046 return true;
40047
40048 var x = point.x;
40049 var y = point.y;
40050
40051 var ax = this.a.redMul(x);
40052 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
40053 return y.redSqr().redISub(rhs).cmpn(0) === 0;
40054};
40055
40056ShortCurve.prototype._endoWnafMulAdd =
40057 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
40058 var npoints = this._endoWnafT1;
40059 var ncoeffs = this._endoWnafT2;
40060 for (var i = 0; i < points.length; i++) {
40061 var split = this._endoSplit(coeffs[i]);
40062 var p = points[i];
40063 var beta = p._getBeta();
40064
40065 if (split.k1.negative) {
40066 split.k1.ineg();
40067 p = p.neg(true);
40068 }
40069 if (split.k2.negative) {
40070 split.k2.ineg();
40071 beta = beta.neg(true);
40072 }
40073
40074 npoints[i * 2] = p;
40075 npoints[i * 2 + 1] = beta;
40076 ncoeffs[i * 2] = split.k1;
40077 ncoeffs[i * 2 + 1] = split.k2;
40078 }
40079 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
40080
40081 // Clean-up references to points and coefficients
40082 for (var j = 0; j < i * 2; j++) {
40083 npoints[j] = null;
40084 ncoeffs[j] = null;
40085 }
40086 return res;
40087};
40088
40089function Point(curve, x, y, isRed) {
40090 base.BasePoint.call(this, curve, 'affine');
40091 if (x === null && y === null) {
40092 this.x = null;
40093 this.y = null;
40094 this.inf = true;
40095 } else {
40096 this.x = new bn(x, 16);
40097 this.y = new bn(y, 16);
40098 // Force redgomery representation when loading from JSON
40099 if (isRed) {
40100 this.x.forceRed(this.curve.red);
40101 this.y.forceRed(this.curve.red);
40102 }
40103 if (!this.x.red)
40104 this.x = this.x.toRed(this.curve.red);
40105 if (!this.y.red)
40106 this.y = this.y.toRed(this.curve.red);
40107 this.inf = false;
40108 }
40109}
40110inherits(Point, base.BasePoint);
40111
40112ShortCurve.prototype.point = function point(x, y, isRed) {
40113 return new Point(this, x, y, isRed);
40114};
40115
40116ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
40117 return Point.fromJSON(this, obj, red);
40118};
40119
40120Point.prototype._getBeta = function _getBeta() {
40121 if (!this.curve.endo)
40122 return;
40123
40124 var pre = this.precomputed;
40125 if (pre && pre.beta)
40126 return pre.beta;
40127
40128 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
40129 if (pre) {
40130 var curve = this.curve;
40131 var endoMul = function(p) {
40132 return curve.point(p.x.redMul(curve.endo.beta), p.y);
40133 };
40134 pre.beta = beta;
40135 beta.precomputed = {
40136 beta: null,
40137 naf: pre.naf && {
40138 wnd: pre.naf.wnd,
40139 points: pre.naf.points.map(endoMul)
40140 },
40141 doubles: pre.doubles && {
40142 step: pre.doubles.step,
40143 points: pre.doubles.points.map(endoMul)
40144 }
40145 };
40146 }
40147 return beta;
40148};
40149
40150Point.prototype.toJSON = function toJSON() {
40151 if (!this.precomputed)
40152 return [ this.x, this.y ];
40153
40154 return [ this.x, this.y, this.precomputed && {
40155 doubles: this.precomputed.doubles && {
40156 step: this.precomputed.doubles.step,
40157 points: this.precomputed.doubles.points.slice(1)
40158 },
40159 naf: this.precomputed.naf && {
40160 wnd: this.precomputed.naf.wnd,
40161 points: this.precomputed.naf.points.slice(1)
40162 }
40163 } ];
40164};
40165
40166Point.fromJSON = function fromJSON(curve, obj, red) {
40167 if (typeof obj === 'string')
40168 obj = JSON.parse(obj);
40169 var res = curve.point(obj[0], obj[1], red);
40170 if (!obj[2])
40171 return res;
40172
40173 function obj2point(obj) {
40174 return curve.point(obj[0], obj[1], red);
40175 }
40176
40177 var pre = obj[2];
40178 res.precomputed = {
40179 beta: null,
40180 doubles: pre.doubles && {
40181 step: pre.doubles.step,
40182 points: [ res ].concat(pre.doubles.points.map(obj2point))
40183 },
40184 naf: pre.naf && {
40185 wnd: pre.naf.wnd,
40186 points: [ res ].concat(pre.naf.points.map(obj2point))
40187 }
40188 };
40189 return res;
40190};
40191
40192Point.prototype.inspect = function inspect() {
40193 if (this.isInfinity())
40194 return '<EC Point Infinity>';
40195 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40196 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
40197};
40198
40199Point.prototype.isInfinity = function isInfinity() {
40200 return this.inf;
40201};
40202
40203Point.prototype.add = function add(p) {
40204 // O + P = P
40205 if (this.inf)
40206 return p;
40207
40208 // P + O = P
40209 if (p.inf)
40210 return this;
40211
40212 // P + P = 2P
40213 if (this.eq(p))
40214 return this.dbl();
40215
40216 // P + (-P) = O
40217 if (this.neg().eq(p))
40218 return this.curve.point(null, null);
40219
40220 // P + Q = O
40221 if (this.x.cmp(p.x) === 0)
40222 return this.curve.point(null, null);
40223
40224 var c = this.y.redSub(p.y);
40225 if (c.cmpn(0) !== 0)
40226 c = c.redMul(this.x.redSub(p.x).redInvm());
40227 var nx = c.redSqr().redISub(this.x).redISub(p.x);
40228 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40229 return this.curve.point(nx, ny);
40230};
40231
40232Point.prototype.dbl = function dbl() {
40233 if (this.inf)
40234 return this;
40235
40236 // 2P = O
40237 var ys1 = this.y.redAdd(this.y);
40238 if (ys1.cmpn(0) === 0)
40239 return this.curve.point(null, null);
40240
40241 var a = this.curve.a;
40242
40243 var x2 = this.x.redSqr();
40244 var dyinv = ys1.redInvm();
40245 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
40246
40247 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
40248 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40249 return this.curve.point(nx, ny);
40250};
40251
40252Point.prototype.getX = function getX() {
40253 return this.x.fromRed();
40254};
40255
40256Point.prototype.getY = function getY() {
40257 return this.y.fromRed();
40258};
40259
40260Point.prototype.mul = function mul(k) {
40261 k = new bn(k, 16);
40262 if (this.isInfinity())
40263 return this;
40264 else if (this._hasDoubles(k))
40265 return this.curve._fixedNafMul(this, k);
40266 else if (this.curve.endo)
40267 return this.curve._endoWnafMulAdd([ this ], [ k ]);
40268 else
40269 return this.curve._wnafMul(this, k);
40270};
40271
40272Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
40273 var points = [ this, p2 ];
40274 var coeffs = [ k1, k2 ];
40275 if (this.curve.endo)
40276 return this.curve._endoWnafMulAdd(points, coeffs);
40277 else
40278 return this.curve._wnafMulAdd(1, points, coeffs, 2);
40279};
40280
40281Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
40282 var points = [ this, p2 ];
40283 var coeffs = [ k1, k2 ];
40284 if (this.curve.endo)
40285 return this.curve._endoWnafMulAdd(points, coeffs, true);
40286 else
40287 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
40288};
40289
40290Point.prototype.eq = function eq(p) {
40291 return this === p ||
40292 this.inf === p.inf &&
40293 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
40294};
40295
40296Point.prototype.neg = function neg(_precompute) {
40297 if (this.inf)
40298 return this;
40299
40300 var res = this.curve.point(this.x, this.y.redNeg());
40301 if (_precompute && this.precomputed) {
40302 var pre = this.precomputed;
40303 var negate = function(p) {
40304 return p.neg();
40305 };
40306 res.precomputed = {
40307 naf: pre.naf && {
40308 wnd: pre.naf.wnd,
40309 points: pre.naf.points.map(negate)
40310 },
40311 doubles: pre.doubles && {
40312 step: pre.doubles.step,
40313 points: pre.doubles.points.map(negate)
40314 }
40315 };
40316 }
40317 return res;
40318};
40319
40320Point.prototype.toJ = function toJ() {
40321 if (this.inf)
40322 return this.curve.jpoint(null, null, null);
40323
40324 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
40325 return res;
40326};
40327
40328function JPoint(curve, x, y, z) {
40329 base.BasePoint.call(this, curve, 'jacobian');
40330 if (x === null && y === null && z === null) {
40331 this.x = this.curve.one;
40332 this.y = this.curve.one;
40333 this.z = new bn(0);
40334 } else {
40335 this.x = new bn(x, 16);
40336 this.y = new bn(y, 16);
40337 this.z = new bn(z, 16);
40338 }
40339 if (!this.x.red)
40340 this.x = this.x.toRed(this.curve.red);
40341 if (!this.y.red)
40342 this.y = this.y.toRed(this.curve.red);
40343 if (!this.z.red)
40344 this.z = this.z.toRed(this.curve.red);
40345
40346 this.zOne = this.z === this.curve.one;
40347}
40348inherits(JPoint, base.BasePoint);
40349
40350ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
40351 return new JPoint(this, x, y, z);
40352};
40353
40354JPoint.prototype.toP = function toP() {
40355 if (this.isInfinity())
40356 return this.curve.point(null, null);
40357
40358 var zinv = this.z.redInvm();
40359 var zinv2 = zinv.redSqr();
40360 var ax = this.x.redMul(zinv2);
40361 var ay = this.y.redMul(zinv2).redMul(zinv);
40362
40363 return this.curve.point(ax, ay);
40364};
40365
40366JPoint.prototype.neg = function neg() {
40367 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
40368};
40369
40370JPoint.prototype.add = function add(p) {
40371 // O + P = P
40372 if (this.isInfinity())
40373 return p;
40374
40375 // P + O = P
40376 if (p.isInfinity())
40377 return this;
40378
40379 // 12M + 4S + 7A
40380 var pz2 = p.z.redSqr();
40381 var z2 = this.z.redSqr();
40382 var u1 = this.x.redMul(pz2);
40383 var u2 = p.x.redMul(z2);
40384 var s1 = this.y.redMul(pz2.redMul(p.z));
40385 var s2 = p.y.redMul(z2.redMul(this.z));
40386
40387 var h = u1.redSub(u2);
40388 var r = s1.redSub(s2);
40389 if (h.cmpn(0) === 0) {
40390 if (r.cmpn(0) !== 0)
40391 return this.curve.jpoint(null, null, null);
40392 else
40393 return this.dbl();
40394 }
40395
40396 var h2 = h.redSqr();
40397 var h3 = h2.redMul(h);
40398 var v = u1.redMul(h2);
40399
40400 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40401 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40402 var nz = this.z.redMul(p.z).redMul(h);
40403
40404 return this.curve.jpoint(nx, ny, nz);
40405};
40406
40407JPoint.prototype.mixedAdd = function mixedAdd(p) {
40408 // O + P = P
40409 if (this.isInfinity())
40410 return p.toJ();
40411
40412 // P + O = P
40413 if (p.isInfinity())
40414 return this;
40415
40416 // 8M + 3S + 7A
40417 var z2 = this.z.redSqr();
40418 var u1 = this.x;
40419 var u2 = p.x.redMul(z2);
40420 var s1 = this.y;
40421 var s2 = p.y.redMul(z2).redMul(this.z);
40422
40423 var h = u1.redSub(u2);
40424 var r = s1.redSub(s2);
40425 if (h.cmpn(0) === 0) {
40426 if (r.cmpn(0) !== 0)
40427 return this.curve.jpoint(null, null, null);
40428 else
40429 return this.dbl();
40430 }
40431
40432 var h2 = h.redSqr();
40433 var h3 = h2.redMul(h);
40434 var v = u1.redMul(h2);
40435
40436 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40437 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40438 var nz = this.z.redMul(h);
40439
40440 return this.curve.jpoint(nx, ny, nz);
40441};
40442
40443JPoint.prototype.dblp = function dblp(pow) {
40444 if (pow === 0)
40445 return this;
40446 if (this.isInfinity())
40447 return this;
40448 if (!pow)
40449 return this.dbl();
40450
40451 if (this.curve.zeroA || this.curve.threeA) {
40452 var r = this;
40453 for (var i = 0; i < pow; i++)
40454 r = r.dbl();
40455 return r;
40456 }
40457
40458 // 1M + 2S + 1A + N * (4S + 5M + 8A)
40459 // N = 1 => 6M + 6S + 9A
40460 var a = this.curve.a;
40461 var tinv = this.curve.tinv;
40462
40463 var jx = this.x;
40464 var jy = this.y;
40465 var jz = this.z;
40466 var jz4 = jz.redSqr().redSqr();
40467
40468 // Reuse results
40469 var jyd = jy.redAdd(jy);
40470 for (var i = 0; i < pow; i++) {
40471 var jx2 = jx.redSqr();
40472 var jyd2 = jyd.redSqr();
40473 var jyd4 = jyd2.redSqr();
40474 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40475
40476 var t1 = jx.redMul(jyd2);
40477 var nx = c.redSqr().redISub(t1.redAdd(t1));
40478 var t2 = t1.redISub(nx);
40479 var dny = c.redMul(t2);
40480 dny = dny.redIAdd(dny).redISub(jyd4);
40481 var nz = jyd.redMul(jz);
40482 if (i + 1 < pow)
40483 jz4 = jz4.redMul(jyd4);
40484
40485 jx = nx;
40486 jz = nz;
40487 jyd = dny;
40488 }
40489
40490 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
40491};
40492
40493JPoint.prototype.dbl = function dbl() {
40494 if (this.isInfinity())
40495 return this;
40496
40497 if (this.curve.zeroA)
40498 return this._zeroDbl();
40499 else if (this.curve.threeA)
40500 return this._threeDbl();
40501 else
40502 return this._dbl();
40503};
40504
40505JPoint.prototype._zeroDbl = function _zeroDbl() {
40506 var nx;
40507 var ny;
40508 var nz;
40509 // Z = 1
40510 if (this.zOne) {
40511 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40512 // #doubling-mdbl-2007-bl
40513 // 1M + 5S + 14A
40514
40515 // XX = X1^2
40516 var xx = this.x.redSqr();
40517 // YY = Y1^2
40518 var yy = this.y.redSqr();
40519 // YYYY = YY^2
40520 var yyyy = yy.redSqr();
40521 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40522 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40523 s = s.redIAdd(s);
40524 // M = 3 * XX + a; a = 0
40525 var m = xx.redAdd(xx).redIAdd(xx);
40526 // T = M ^ 2 - 2*S
40527 var t = m.redSqr().redISub(s).redISub(s);
40528
40529 // 8 * YYYY
40530 var yyyy8 = yyyy.redIAdd(yyyy);
40531 yyyy8 = yyyy8.redIAdd(yyyy8);
40532 yyyy8 = yyyy8.redIAdd(yyyy8);
40533
40534 // X3 = T
40535 nx = t;
40536 // Y3 = M * (S - T) - 8 * YYYY
40537 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40538 // Z3 = 2*Y1
40539 nz = this.y.redAdd(this.y);
40540 } else {
40541 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40542 // #doubling-dbl-2009-l
40543 // 2M + 5S + 13A
40544
40545 // A = X1^2
40546 var a = this.x.redSqr();
40547 // B = Y1^2
40548 var b = this.y.redSqr();
40549 // C = B^2
40550 var c = b.redSqr();
40551 // D = 2 * ((X1 + B)^2 - A - C)
40552 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
40553 d = d.redIAdd(d);
40554 // E = 3 * A
40555 var e = a.redAdd(a).redIAdd(a);
40556 // F = E^2
40557 var f = e.redSqr();
40558
40559 // 8 * C
40560 var c8 = c.redIAdd(c);
40561 c8 = c8.redIAdd(c8);
40562 c8 = c8.redIAdd(c8);
40563
40564 // X3 = F - 2 * D
40565 nx = f.redISub(d).redISub(d);
40566 // Y3 = E * (D - X3) - 8 * C
40567 ny = e.redMul(d.redISub(nx)).redISub(c8);
40568 // Z3 = 2 * Y1 * Z1
40569 nz = this.y.redMul(this.z);
40570 nz = nz.redIAdd(nz);
40571 }
40572
40573 return this.curve.jpoint(nx, ny, nz);
40574};
40575
40576JPoint.prototype._threeDbl = function _threeDbl() {
40577 var nx;
40578 var ny;
40579 var nz;
40580 // Z = 1
40581 if (this.zOne) {
40582 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
40583 // #doubling-mdbl-2007-bl
40584 // 1M + 5S + 15A
40585
40586 // XX = X1^2
40587 var xx = this.x.redSqr();
40588 // YY = Y1^2
40589 var yy = this.y.redSqr();
40590 // YYYY = YY^2
40591 var yyyy = yy.redSqr();
40592 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40593 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40594 s = s.redIAdd(s);
40595 // M = 3 * XX + a
40596 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
40597 // T = M^2 - 2 * S
40598 var t = m.redSqr().redISub(s).redISub(s);
40599 // X3 = T
40600 nx = t;
40601 // Y3 = M * (S - T) - 8 * YYYY
40602 var yyyy8 = yyyy.redIAdd(yyyy);
40603 yyyy8 = yyyy8.redIAdd(yyyy8);
40604 yyyy8 = yyyy8.redIAdd(yyyy8);
40605 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40606 // Z3 = 2 * Y1
40607 nz = this.y.redAdd(this.y);
40608 } else {
40609 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
40610 // 3M + 5S
40611
40612 // delta = Z1^2
40613 var delta = this.z.redSqr();
40614 // gamma = Y1^2
40615 var gamma = this.y.redSqr();
40616 // beta = X1 * gamma
40617 var beta = this.x.redMul(gamma);
40618 // alpha = 3 * (X1 - delta) * (X1 + delta)
40619 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
40620 alpha = alpha.redAdd(alpha).redIAdd(alpha);
40621 // X3 = alpha^2 - 8 * beta
40622 var beta4 = beta.redIAdd(beta);
40623 beta4 = beta4.redIAdd(beta4);
40624 var beta8 = beta4.redAdd(beta4);
40625 nx = alpha.redSqr().redISub(beta8);
40626 // Z3 = (Y1 + Z1)^2 - gamma - delta
40627 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
40628 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
40629 var ggamma8 = gamma.redSqr();
40630 ggamma8 = ggamma8.redIAdd(ggamma8);
40631 ggamma8 = ggamma8.redIAdd(ggamma8);
40632 ggamma8 = ggamma8.redIAdd(ggamma8);
40633 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
40634 }
40635
40636 return this.curve.jpoint(nx, ny, nz);
40637};
40638
40639JPoint.prototype._dbl = function _dbl() {
40640 var a = this.curve.a;
40641
40642 // 4M + 6S + 10A
40643 var jx = this.x;
40644 var jy = this.y;
40645 var jz = this.z;
40646 var jz4 = jz.redSqr().redSqr();
40647
40648 var jx2 = jx.redSqr();
40649 var jy2 = jy.redSqr();
40650
40651 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40652
40653 var jxd4 = jx.redAdd(jx);
40654 jxd4 = jxd4.redIAdd(jxd4);
40655 var t1 = jxd4.redMul(jy2);
40656 var nx = c.redSqr().redISub(t1.redAdd(t1));
40657 var t2 = t1.redISub(nx);
40658
40659 var jyd8 = jy2.redSqr();
40660 jyd8 = jyd8.redIAdd(jyd8);
40661 jyd8 = jyd8.redIAdd(jyd8);
40662 jyd8 = jyd8.redIAdd(jyd8);
40663 var ny = c.redMul(t2).redISub(jyd8);
40664 var nz = jy.redAdd(jy).redMul(jz);
40665
40666 return this.curve.jpoint(nx, ny, nz);
40667};
40668
40669JPoint.prototype.trpl = function trpl() {
40670 if (!this.curve.zeroA)
40671 return this.dbl().add(this);
40672
40673 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
40674 // 5M + 10S + ...
40675
40676 // XX = X1^2
40677 var xx = this.x.redSqr();
40678 // YY = Y1^2
40679 var yy = this.y.redSqr();
40680 // ZZ = Z1^2
40681 var zz = this.z.redSqr();
40682 // YYYY = YY^2
40683 var yyyy = yy.redSqr();
40684 // M = 3 * XX + a * ZZ2; a = 0
40685 var m = xx.redAdd(xx).redIAdd(xx);
40686 // MM = M^2
40687 var mm = m.redSqr();
40688 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
40689 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40690 e = e.redIAdd(e);
40691 e = e.redAdd(e).redIAdd(e);
40692 e = e.redISub(mm);
40693 // EE = E^2
40694 var ee = e.redSqr();
40695 // T = 16*YYYY
40696 var t = yyyy.redIAdd(yyyy);
40697 t = t.redIAdd(t);
40698 t = t.redIAdd(t);
40699 t = t.redIAdd(t);
40700 // U = (M + E)^2 - MM - EE - T
40701 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
40702 // X3 = 4 * (X1 * EE - 4 * YY * U)
40703 var yyu4 = yy.redMul(u);
40704 yyu4 = yyu4.redIAdd(yyu4);
40705 yyu4 = yyu4.redIAdd(yyu4);
40706 var nx = this.x.redMul(ee).redISub(yyu4);
40707 nx = nx.redIAdd(nx);
40708 nx = nx.redIAdd(nx);
40709 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
40710 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
40711 ny = ny.redIAdd(ny);
40712 ny = ny.redIAdd(ny);
40713 ny = ny.redIAdd(ny);
40714 // Z3 = (Z1 + E)^2 - ZZ - EE
40715 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
40716
40717 return this.curve.jpoint(nx, ny, nz);
40718};
40719
40720JPoint.prototype.mul = function mul(k, kbase) {
40721 k = new bn(k, kbase);
40722
40723 return this.curve._wnafMul(this, k);
40724};
40725
40726JPoint.prototype.eq = function eq(p) {
40727 if (p.type === 'affine')
40728 return this.eq(p.toJ());
40729
40730 if (this === p)
40731 return true;
40732
40733 // x1 * z2^2 == x2 * z1^2
40734 var z2 = this.z.redSqr();
40735 var pz2 = p.z.redSqr();
40736 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
40737 return false;
40738
40739 // y1 * z2^3 == y2 * z1^3
40740 var z3 = z2.redMul(this.z);
40741 var pz3 = pz2.redMul(p.z);
40742 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
40743};
40744
40745JPoint.prototype.eqXToP = function eqXToP(x) {
40746 var zs = this.z.redSqr();
40747 var rx = x.toRed(this.curve.red).redMul(zs);
40748 if (this.x.cmp(rx) === 0)
40749 return true;
40750
40751 var xc = x.clone();
40752 var t = this.curve.redN.redMul(zs);
40753 for (;;) {
40754 xc.iadd(this.curve.n);
40755 if (xc.cmp(this.curve.p) >= 0)
40756 return false;
40757
40758 rx.redIAdd(t);
40759 if (this.x.cmp(rx) === 0)
40760 return true;
40761 }
40762};
40763
40764JPoint.prototype.inspect = function inspect() {
40765 if (this.isInfinity())
40766 return '<EC JPoint Infinity>';
40767 return '<EC JPoint x: ' + this.x.toString(16, 2) +
40768 ' y: ' + this.y.toString(16, 2) +
40769 ' z: ' + this.z.toString(16, 2) + '>';
40770};
40771
40772JPoint.prototype.isInfinity = function isInfinity() {
40773 // XXX This code assumes that zero is always zero in red
40774 return this.z.cmpn(0) === 0;
40775};
40776
40777function MontCurve(conf) {
40778 base.call(this, 'mont', conf);
40779
40780 this.a = new bn(conf.a, 16).toRed(this.red);
40781 this.b = new bn(conf.b, 16).toRed(this.red);
40782 this.i4 = new bn(4).toRed(this.red).redInvm();
40783 this.two = new bn(2).toRed(this.red);
40784 // Note: this implementation is according to the original paper
40785 // by P. Montgomery, NOT the one by D. J. Bernstein.
40786 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
40787}
40788inherits(MontCurve, base);
40789var mont = MontCurve;
40790
40791MontCurve.prototype.validate = function validate(point) {
40792 var x = point.normalize().x;
40793 var x2 = x.redSqr();
40794 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
40795 var y = rhs.redSqrt();
40796
40797 return y.redSqr().cmp(rhs) === 0;
40798};
40799
40800function Point$1(curve, x, z) {
40801 base.BasePoint.call(this, curve, 'projective');
40802 if (x === null && z === null) {
40803 this.x = this.curve.one;
40804 this.z = this.curve.zero;
40805 } else {
40806 this.x = new bn(x, 16);
40807 this.z = new bn(z, 16);
40808 if (!this.x.red)
40809 this.x = this.x.toRed(this.curve.red);
40810 if (!this.z.red)
40811 this.z = this.z.toRed(this.curve.red);
40812 }
40813}
40814inherits(Point$1, base.BasePoint);
40815
40816MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
40817 var bytes = utils_1$1.toArray(bytes, enc);
40818
40819 // TODO Curve448
40820 // Montgomery curve points must be represented in the compressed format
40821 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40822 if (bytes.length === 33 && bytes[0] === 0x40)
40823 bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
40824 if (bytes.length !== 32)
40825 throw new Error('Unknown point compression format');
40826 return this.point(bytes, 1);
40827};
40828
40829MontCurve.prototype.point = function point(x, z) {
40830 return new Point$1(this, x, z);
40831};
40832
40833MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
40834 return Point$1.fromJSON(this, obj);
40835};
40836
40837Point$1.prototype.precompute = function precompute() {
40838 // No-op
40839};
40840
40841Point$1.prototype._encode = function _encode(compact) {
40842 var len = this.curve.p.byteLength();
40843
40844 // Note: the output should always be little-endian
40845 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40846 if (compact) {
40847 return [ 0x40 ].concat(this.getX().toArray('le', len));
40848 } else {
40849 return this.getX().toArray('be', len);
40850 }
40851};
40852
40853Point$1.fromJSON = function fromJSON(curve, obj) {
40854 return new Point$1(curve, obj[0], obj[1] || curve.one);
40855};
40856
40857Point$1.prototype.inspect = function inspect() {
40858 if (this.isInfinity())
40859 return '<EC Point Infinity>';
40860 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40861 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
40862};
40863
40864Point$1.prototype.isInfinity = function isInfinity() {
40865 // XXX This code assumes that zero is always zero in red
40866 return this.z.cmpn(0) === 0;
40867};
40868
40869Point$1.prototype.dbl = function dbl() {
40870 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
40871 // 2M + 2S + 4A
40872
40873 // A = X1 + Z1
40874 var a = this.x.redAdd(this.z);
40875 // AA = A^2
40876 var aa = a.redSqr();
40877 // B = X1 - Z1
40878 var b = this.x.redSub(this.z);
40879 // BB = B^2
40880 var bb = b.redSqr();
40881 // C = AA - BB
40882 var c = aa.redSub(bb);
40883 // X3 = AA * BB
40884 var nx = aa.redMul(bb);
40885 // Z3 = C * (BB + A24 * C)
40886 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
40887 return this.curve.point(nx, nz);
40888};
40889
40890Point$1.prototype.add = function add() {
40891 throw new Error('Not supported on Montgomery curve');
40892};
40893
40894Point$1.prototype.diffAdd = function diffAdd(p, diff) {
40895 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
40896 // 4M + 2S + 6A
40897
40898 // A = X2 + Z2
40899 var a = this.x.redAdd(this.z);
40900 // B = X2 - Z2
40901 var b = this.x.redSub(this.z);
40902 // C = X3 + Z3
40903 var c = p.x.redAdd(p.z);
40904 // D = X3 - Z3
40905 var d = p.x.redSub(p.z);
40906 // DA = D * A
40907 var da = d.redMul(a);
40908 // CB = C * B
40909 var cb = c.redMul(b);
40910 // X5 = Z1 * (DA + CB)^2
40911 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
40912 // Z5 = X1 * (DA - CB)^2
40913 var nz = diff.x.redMul(da.redISub(cb).redSqr());
40914 return this.curve.point(nx, nz);
40915};
40916
40917Point$1.prototype.mul = function mul(k) {
40918 k = new bn(k, 16);
40919
40920 var t = k.clone();
40921 var a = this; // (N / 2) * Q + Q
40922 var b = this.curve.point(null, null); // (N / 2) * Q
40923 var c = this; // Q
40924
40925 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
40926 bits.push(t.andln(1));
40927
40928 for (var i = bits.length - 1; i >= 0; i--) {
40929 if (bits[i] === 0) {
40930 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
40931 a = a.diffAdd(b, c);
40932 // N * Q = 2 * ((N / 2) * Q + Q))
40933 b = b.dbl();
40934 } else {
40935 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
40936 b = a.diffAdd(b, c);
40937 // N * Q + Q = 2 * ((N / 2) * Q + Q)
40938 a = a.dbl();
40939 }
40940 }
40941 return b;
40942};
40943
40944Point$1.prototype.mulAdd = function mulAdd() {
40945 throw new Error('Not supported on Montgomery curve');
40946};
40947
40948Point$1.prototype.jumlAdd = function jumlAdd() {
40949 throw new Error('Not supported on Montgomery curve');
40950};
40951
40952Point$1.prototype.eq = function eq(other) {
40953 return this.getX().cmp(other.getX()) === 0;
40954};
40955
40956Point$1.prototype.normalize = function normalize() {
40957 this.x = this.x.redMul(this.z.redInvm());
40958 this.z = this.curve.one;
40959 return this;
40960};
40961
40962Point$1.prototype.getX = function getX() {
40963 // Normalize coordinates
40964 this.normalize();
40965
40966 return this.x.fromRed();
40967};
40968
40969var assert$4 = utils_1$1.assert;
40970
40971function EdwardsCurve(conf) {
40972 // NOTE: Important as we are creating point in Base.call()
40973 this.twisted = (conf.a | 0) !== 1;
40974 this.mOneA = this.twisted && (conf.a | 0) === -1;
40975 this.extended = this.mOneA;
40976
40977 base.call(this, 'edwards', conf);
40978
40979 this.a = new bn(conf.a, 16).umod(this.red.m);
40980 this.a = this.a.toRed(this.red);
40981 this.c = new bn(conf.c, 16).toRed(this.red);
40982 this.c2 = this.c.redSqr();
40983 this.d = new bn(conf.d, 16).toRed(this.red);
40984 this.dd = this.d.redAdd(this.d);
40985
40986 assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0);
40987 this.oneC = (conf.c | 0) === 1;
40988}
40989inherits(EdwardsCurve, base);
40990var edwards = EdwardsCurve;
40991
40992EdwardsCurve.prototype._mulA = function _mulA(num) {
40993 if (this.mOneA)
40994 return num.redNeg();
40995 else
40996 return this.a.redMul(num);
40997};
40998
40999EdwardsCurve.prototype._mulC = function _mulC(num) {
41000 if (this.oneC)
41001 return num;
41002 else
41003 return this.c.redMul(num);
41004};
41005
41006// Just for compatibility with Short curve
41007EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
41008 return this.point(x, y, z, t);
41009};
41010
41011EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
41012 x = new bn(x, 16);
41013 if (!x.red)
41014 x = x.toRed(this.red);
41015
41016 var x2 = x.redSqr();
41017 var rhs = this.c2.redSub(this.a.redMul(x2));
41018 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
41019
41020 var y2 = rhs.redMul(lhs.redInvm());
41021 var y = y2.redSqrt();
41022 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
41023 throw new Error('invalid point');
41024
41025 var isOdd = y.fromRed().isOdd();
41026 if (odd && !isOdd || !odd && isOdd)
41027 y = y.redNeg();
41028
41029 return this.point(x, y);
41030};
41031
41032EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
41033 y = new bn(y, 16);
41034 if (!y.red)
41035 y = y.toRed(this.red);
41036
41037 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
41038 var y2 = y.redSqr();
41039 var lhs = y2.redSub(this.c2);
41040 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
41041 var x2 = lhs.redMul(rhs.redInvm());
41042
41043 if (x2.cmp(this.zero) === 0) {
41044 if (odd)
41045 throw new Error('invalid point');
41046 else
41047 return this.point(this.zero, y);
41048 }
41049
41050 var x = x2.redSqrt();
41051 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
41052 throw new Error('invalid point');
41053
41054 if (x.fromRed().isOdd() !== odd)
41055 x = x.redNeg();
41056
41057 return this.point(x, y);
41058};
41059
41060EdwardsCurve.prototype.validate = function validate(point) {
41061 if (point.isInfinity())
41062 return true;
41063
41064 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
41065 point.normalize();
41066
41067 var x2 = point.x.redSqr();
41068 var y2 = point.y.redSqr();
41069 var lhs = x2.redMul(this.a).redAdd(y2);
41070 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
41071
41072 return lhs.cmp(rhs) === 0;
41073};
41074
41075function Point$2(curve, x, y, z, t) {
41076 base.BasePoint.call(this, curve, 'projective');
41077 if (x === null && y === null && z === null) {
41078 this.x = this.curve.zero;
41079 this.y = this.curve.one;
41080 this.z = this.curve.one;
41081 this.t = this.curve.zero;
41082 this.zOne = true;
41083 } else {
41084 this.x = new bn(x, 16);
41085 this.y = new bn(y, 16);
41086 this.z = z ? new bn(z, 16) : this.curve.one;
41087 this.t = t && new bn(t, 16);
41088 if (!this.x.red)
41089 this.x = this.x.toRed(this.curve.red);
41090 if (!this.y.red)
41091 this.y = this.y.toRed(this.curve.red);
41092 if (!this.z.red)
41093 this.z = this.z.toRed(this.curve.red);
41094 if (this.t && !this.t.red)
41095 this.t = this.t.toRed(this.curve.red);
41096 this.zOne = this.z === this.curve.one;
41097
41098 // Use extended coordinates
41099 if (this.curve.extended && !this.t) {
41100 this.t = this.x.redMul(this.y);
41101 if (!this.zOne)
41102 this.t = this.t.redMul(this.z.redInvm());
41103 }
41104 }
41105}
41106inherits(Point$2, base.BasePoint);
41107
41108EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
41109 return Point$2.fromJSON(this, obj);
41110};
41111
41112EdwardsCurve.prototype.point = function point(x, y, z, t) {
41113 return new Point$2(this, x, y, z, t);
41114};
41115
41116Point$2.fromJSON = function fromJSON(curve, obj) {
41117 return new Point$2(curve, obj[0], obj[1], obj[2]);
41118};
41119
41120Point$2.prototype.inspect = function inspect() {
41121 if (this.isInfinity())
41122 return '<EC Point Infinity>';
41123 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
41124 ' y: ' + this.y.fromRed().toString(16, 2) +
41125 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
41126};
41127
41128Point$2.prototype.isInfinity = function isInfinity() {
41129 // XXX This code assumes that zero is always zero in red
41130 return this.x.cmpn(0) === 0 &&
41131 (this.y.cmp(this.z) === 0 ||
41132 (this.zOne && this.y.cmp(this.curve.c) === 0));
41133};
41134
41135Point$2.prototype._extDbl = function _extDbl() {
41136 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41137 // #doubling-dbl-2008-hwcd
41138 // 4M + 4S
41139
41140 // A = X1^2
41141 var a = this.x.redSqr();
41142 // B = Y1^2
41143 var b = this.y.redSqr();
41144 // C = 2 * Z1^2
41145 var c = this.z.redSqr();
41146 c = c.redIAdd(c);
41147 // D = a * A
41148 var d = this.curve._mulA(a);
41149 // E = (X1 + Y1)^2 - A - B
41150 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
41151 // G = D + B
41152 var g = d.redAdd(b);
41153 // F = G - C
41154 var f = g.redSub(c);
41155 // H = D - B
41156 var h = d.redSub(b);
41157 // X3 = E * F
41158 var nx = e.redMul(f);
41159 // Y3 = G * H
41160 var ny = g.redMul(h);
41161 // T3 = E * H
41162 var nt = e.redMul(h);
41163 // Z3 = F * G
41164 var nz = f.redMul(g);
41165 return this.curve.point(nx, ny, nz, nt);
41166};
41167
41168Point$2.prototype._projDbl = function _projDbl() {
41169 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41170 // #doubling-dbl-2008-bbjlp
41171 // #doubling-dbl-2007-bl
41172 // and others
41173 // Generally 3M + 4S or 2M + 4S
41174
41175 // B = (X1 + Y1)^2
41176 var b = this.x.redAdd(this.y).redSqr();
41177 // C = X1^2
41178 var c = this.x.redSqr();
41179 // D = Y1^2
41180 var d = this.y.redSqr();
41181
41182 var nx;
41183 var ny;
41184 var nz;
41185 if (this.curve.twisted) {
41186 // E = a * C
41187 var e = this.curve._mulA(c);
41188 // F = E + D
41189 var f = e.redAdd(d);
41190 if (this.zOne) {
41191 // X3 = (B - C - D) * (F - 2)
41192 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
41193 // Y3 = F * (E - D)
41194 ny = f.redMul(e.redSub(d));
41195 // Z3 = F^2 - 2 * F
41196 nz = f.redSqr().redSub(f).redSub(f);
41197 } else {
41198 // H = Z1^2
41199 var h = this.z.redSqr();
41200 // J = F - 2 * H
41201 var j = f.redSub(h).redISub(h);
41202 // X3 = (B-C-D)*J
41203 nx = b.redSub(c).redISub(d).redMul(j);
41204 // Y3 = F * (E - D)
41205 ny = f.redMul(e.redSub(d));
41206 // Z3 = F * J
41207 nz = f.redMul(j);
41208 }
41209 } else {
41210 // E = C + D
41211 var e = c.redAdd(d);
41212 // H = (c * Z1)^2
41213 var h = this.curve._mulC(this.z).redSqr();
41214 // J = E - 2 * H
41215 var j = e.redSub(h).redSub(h);
41216 // X3 = c * (B - E) * J
41217 nx = this.curve._mulC(b.redISub(e)).redMul(j);
41218 // Y3 = c * E * (C - D)
41219 ny = this.curve._mulC(e).redMul(c.redISub(d));
41220 // Z3 = E * J
41221 nz = e.redMul(j);
41222 }
41223 return this.curve.point(nx, ny, nz);
41224};
41225
41226Point$2.prototype.dbl = function dbl() {
41227 if (this.isInfinity())
41228 return this;
41229
41230 // Double in extended coordinates
41231 if (this.curve.extended)
41232 return this._extDbl();
41233 else
41234 return this._projDbl();
41235};
41236
41237Point$2.prototype._extAdd = function _extAdd(p) {
41238 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41239 // #addition-add-2008-hwcd-3
41240 // 8M
41241
41242 // A = (Y1 - X1) * (Y2 - X2)
41243 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
41244 // B = (Y1 + X1) * (Y2 + X2)
41245 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
41246 // C = T1 * k * T2
41247 var c = this.t.redMul(this.curve.dd).redMul(p.t);
41248 // D = Z1 * 2 * Z2
41249 var d = this.z.redMul(p.z.redAdd(p.z));
41250 // E = B - A
41251 var e = b.redSub(a);
41252 // F = D - C
41253 var f = d.redSub(c);
41254 // G = D + C
41255 var g = d.redAdd(c);
41256 // H = B + A
41257 var h = b.redAdd(a);
41258 // X3 = E * F
41259 var nx = e.redMul(f);
41260 // Y3 = G * H
41261 var ny = g.redMul(h);
41262 // T3 = E * H
41263 var nt = e.redMul(h);
41264 // Z3 = F * G
41265 var nz = f.redMul(g);
41266 return this.curve.point(nx, ny, nz, nt);
41267};
41268
41269Point$2.prototype._projAdd = function _projAdd(p) {
41270 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41271 // #addition-add-2008-bbjlp
41272 // #addition-add-2007-bl
41273 // 10M + 1S
41274
41275 // A = Z1 * Z2
41276 var a = this.z.redMul(p.z);
41277 // B = A^2
41278 var b = a.redSqr();
41279 // C = X1 * X2
41280 var c = this.x.redMul(p.x);
41281 // D = Y1 * Y2
41282 var d = this.y.redMul(p.y);
41283 // E = d * C * D
41284 var e = this.curve.d.redMul(c).redMul(d);
41285 // F = B - E
41286 var f = b.redSub(e);
41287 // G = B + E
41288 var g = b.redAdd(e);
41289 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
41290 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
41291 var nx = a.redMul(f).redMul(tmp);
41292 var ny;
41293 var nz;
41294 if (this.curve.twisted) {
41295 // Y3 = A * G * (D - a * C)
41296 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
41297 // Z3 = F * G
41298 nz = f.redMul(g);
41299 } else {
41300 // Y3 = A * G * (D - C)
41301 ny = a.redMul(g).redMul(d.redSub(c));
41302 // Z3 = c * F * G
41303 nz = this.curve._mulC(f).redMul(g);
41304 }
41305 return this.curve.point(nx, ny, nz);
41306};
41307
41308Point$2.prototype.add = function add(p) {
41309 if (this.isInfinity())
41310 return p;
41311 if (p.isInfinity())
41312 return this;
41313
41314 if (this.curve.extended)
41315 return this._extAdd(p);
41316 else
41317 return this._projAdd(p);
41318};
41319
41320Point$2.prototype.mul = function mul(k) {
41321 if (this._hasDoubles(k))
41322 return this.curve._fixedNafMul(this, k);
41323 else
41324 return this.curve._wnafMul(this, k);
41325};
41326
41327Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) {
41328 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
41329};
41330
41331Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
41332 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
41333};
41334
41335Point$2.prototype.normalize = function normalize() {
41336 if (this.zOne)
41337 return this;
41338
41339 // Normalize coordinates
41340 var zi = this.z.redInvm();
41341 this.x = this.x.redMul(zi);
41342 this.y = this.y.redMul(zi);
41343 if (this.t)
41344 this.t = this.t.redMul(zi);
41345 this.z = this.curve.one;
41346 this.zOne = true;
41347 return this;
41348};
41349
41350Point$2.prototype.neg = function neg() {
41351 return this.curve.point(this.x.redNeg(),
41352 this.y,
41353 this.z,
41354 this.t && this.t.redNeg());
41355};
41356
41357Point$2.prototype.getX = function getX() {
41358 this.normalize();
41359 return this.x.fromRed();
41360};
41361
41362Point$2.prototype.getY = function getY() {
41363 this.normalize();
41364 return this.y.fromRed();
41365};
41366
41367Point$2.prototype.eq = function eq(other) {
41368 return this === other ||
41369 this.getX().cmp(other.getX()) === 0 &&
41370 this.getY().cmp(other.getY()) === 0;
41371};
41372
41373Point$2.prototype.eqXToP = function eqXToP(x) {
41374 var rx = x.toRed(this.curve.red).redMul(this.z);
41375 if (this.x.cmp(rx) === 0)
41376 return true;
41377
41378 var xc = x.clone();
41379 var t = this.curve.redN.redMul(this.z);
41380 for (;;) {
41381 xc.iadd(this.curve.n);
41382 if (xc.cmp(this.curve.p) >= 0)
41383 return false;
41384
41385 rx.redIAdd(t);
41386 if (this.x.cmp(rx) === 0)
41387 return true;
41388 }
41389};
41390
41391// Compatibility with BaseCurve
41392Point$2.prototype.toP = Point$2.prototype.normalize;
41393Point$2.prototype.mixedAdd = Point$2.prototype.add;
41394
41395var curve_1 = createCommonjsModule(function (module, exports) {
41396
41397var curve = exports;
41398
41399curve.base = base;
41400curve.short = short_1;
41401curve.mont = mont;
41402curve.edwards = edwards;
41403});
41404
41405var rotl32$2 = utils.rotl32;
41406var sum32$3 = utils.sum32;
41407var sum32_5$2 = utils.sum32_5;
41408var ft_1$1 = common$1.ft_1;
41409var BlockHash$4 = common.BlockHash;
41410
41411var sha1_K = [
41412 0x5A827999, 0x6ED9EBA1,
41413 0x8F1BBCDC, 0xCA62C1D6
41414];
41415
41416function SHA1() {
41417 if (!(this instanceof SHA1))
41418 return new SHA1();
41419
41420 BlockHash$4.call(this);
41421 this.h = [
41422 0x67452301, 0xefcdab89, 0x98badcfe,
41423 0x10325476, 0xc3d2e1f0 ];
41424 this.W = new Array(80);
41425}
41426
41427utils.inherits(SHA1, BlockHash$4);
41428var _1 = SHA1;
41429
41430SHA1.blockSize = 512;
41431SHA1.outSize = 160;
41432SHA1.hmacStrength = 80;
41433SHA1.padLength = 64;
41434
41435SHA1.prototype._update = function _update(msg, start) {
41436 var W = this.W;
41437
41438 for (var i = 0; i < 16; i++)
41439 W[i] = msg[start + i];
41440
41441 for(; i < W.length; i++)
41442 W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
41443
41444 var a = this.h[0];
41445 var b = this.h[1];
41446 var c = this.h[2];
41447 var d = this.h[3];
41448 var e = this.h[4];
41449
41450 for (i = 0; i < W.length; i++) {
41451 var s = ~~(i / 20);
41452 var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
41453 e = d;
41454 d = c;
41455 c = rotl32$2(b, 30);
41456 b = a;
41457 a = t;
41458 }
41459
41460 this.h[0] = sum32$3(this.h[0], a);
41461 this.h[1] = sum32$3(this.h[1], b);
41462 this.h[2] = sum32$3(this.h[2], c);
41463 this.h[3] = sum32$3(this.h[3], d);
41464 this.h[4] = sum32$3(this.h[4], e);
41465};
41466
41467SHA1.prototype._digest = function digest(enc) {
41468 if (enc === 'hex')
41469 return utils.toHex32(this.h, 'big');
41470 else
41471 return utils.split32(this.h, 'big');
41472};
41473
41474var sha1 = _1;
41475var sha224 = _224;
41476var sha256 = _256;
41477var sha384 = _384;
41478var sha512 = _512;
41479
41480var sha = {
41481 sha1: sha1,
41482 sha224: sha224,
41483 sha256: sha256,
41484 sha384: sha384,
41485 sha512: sha512
41486};
41487
41488function Hmac(hash, key, enc) {
41489 if (!(this instanceof Hmac))
41490 return new Hmac(hash, key, enc);
41491 this.Hash = hash;
41492 this.blockSize = hash.blockSize / 8;
41493 this.outSize = hash.outSize / 8;
41494 this.inner = null;
41495 this.outer = null;
41496
41497 this._init(utils.toArray(key, enc));
41498}
41499var hmac = Hmac;
41500
41501Hmac.prototype._init = function init(key) {
41502 // Shorten key, if needed
41503 if (key.length > this.blockSize)
41504 key = new this.Hash().update(key).digest();
41505 minimalisticAssert(key.length <= this.blockSize);
41506
41507 // Add padding to key
41508 for (var i = key.length; i < this.blockSize; i++)
41509 key.push(0);
41510
41511 for (i = 0; i < key.length; i++)
41512 key[i] ^= 0x36;
41513 this.inner = new this.Hash().update(key);
41514
41515 // 0x36 ^ 0x5c = 0x6a
41516 for (i = 0; i < key.length; i++)
41517 key[i] ^= 0x6a;
41518 this.outer = new this.Hash().update(key);
41519};
41520
41521Hmac.prototype.update = function update(msg, enc) {
41522 this.inner.update(msg, enc);
41523 return this;
41524};
41525
41526Hmac.prototype.digest = function digest(enc) {
41527 this.outer.update(this.inner.digest());
41528 return this.outer.digest(enc);
41529};
41530
41531var hash_1 = createCommonjsModule(function (module, exports) {
41532var hash = exports;
41533
41534hash.utils = utils;
41535hash.common = common;
41536hash.sha = sha;
41537hash.ripemd = ripemd;
41538hash.hmac = hmac;
41539
41540// Proxy hash functions to the main object
41541hash.sha1 = hash.sha.sha1;
41542hash.sha256 = hash.sha.sha256;
41543hash.sha224 = hash.sha.sha224;
41544hash.sha384 = hash.sha.sha384;
41545hash.sha512 = hash.sha.sha512;
41546hash.ripemd160 = hash.ripemd.ripemd160;
41547});
41548
41549var secp256k1 = {
41550 doubles: {
41551 step: 4,
41552 points: [
41553 [
41554 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
41555 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
41556 ],
41557 [
41558 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
41559 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
41560 ],
41561 [
41562 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
41563 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
41564 ],
41565 [
41566 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
41567 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
41568 ],
41569 [
41570 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
41571 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
41572 ],
41573 [
41574 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
41575 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
41576 ],
41577 [
41578 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
41579 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
41580 ],
41581 [
41582 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
41583 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
41584 ],
41585 [
41586 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
41587 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
41588 ],
41589 [
41590 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
41591 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
41592 ],
41593 [
41594 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
41595 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
41596 ],
41597 [
41598 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
41599 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
41600 ],
41601 [
41602 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
41603 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
41604 ],
41605 [
41606 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
41607 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
41608 ],
41609 [
41610 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
41611 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
41612 ],
41613 [
41614 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
41615 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
41616 ],
41617 [
41618 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
41619 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
41620 ],
41621 [
41622 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
41623 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
41624 ],
41625 [
41626 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
41627 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
41628 ],
41629 [
41630 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
41631 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
41632 ],
41633 [
41634 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
41635 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
41636 ],
41637 [
41638 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
41639 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
41640 ],
41641 [
41642 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
41643 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
41644 ],
41645 [
41646 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
41647 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
41648 ],
41649 [
41650 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
41651 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
41652 ],
41653 [
41654 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
41655 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
41656 ],
41657 [
41658 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
41659 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
41660 ],
41661 [
41662 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
41663 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
41664 ],
41665 [
41666 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
41667 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
41668 ],
41669 [
41670 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
41671 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
41672 ],
41673 [
41674 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
41675 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
41676 ],
41677 [
41678 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
41679 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
41680 ],
41681 [
41682 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
41683 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
41684 ],
41685 [
41686 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
41687 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
41688 ],
41689 [
41690 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
41691 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
41692 ],
41693 [
41694 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
41695 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
41696 ],
41697 [
41698 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
41699 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
41700 ],
41701 [
41702 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
41703 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
41704 ],
41705 [
41706 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
41707 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
41708 ],
41709 [
41710 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
41711 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
41712 ],
41713 [
41714 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
41715 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
41716 ],
41717 [
41718 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
41719 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
41720 ],
41721 [
41722 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
41723 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
41724 ],
41725 [
41726 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
41727 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
41728 ],
41729 [
41730 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
41731 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
41732 ],
41733 [
41734 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
41735 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
41736 ],
41737 [
41738 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
41739 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
41740 ],
41741 [
41742 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
41743 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
41744 ],
41745 [
41746 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
41747 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
41748 ],
41749 [
41750 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
41751 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
41752 ],
41753 [
41754 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
41755 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
41756 ],
41757 [
41758 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
41759 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
41760 ],
41761 [
41762 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
41763 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
41764 ],
41765 [
41766 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
41767 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
41768 ],
41769 [
41770 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
41771 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
41772 ],
41773 [
41774 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
41775 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
41776 ],
41777 [
41778 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
41779 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
41780 ],
41781 [
41782 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
41783 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
41784 ],
41785 [
41786 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
41787 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
41788 ],
41789 [
41790 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
41791 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
41792 ],
41793 [
41794 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
41795 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
41796 ],
41797 [
41798 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
41799 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
41800 ],
41801 [
41802 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
41803 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
41804 ],
41805 [
41806 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
41807 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
41808 ],
41809 [
41810 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
41811 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
41812 ]
41813 ]
41814 },
41815 naf: {
41816 wnd: 7,
41817 points: [
41818 [
41819 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
41820 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
41821 ],
41822 [
41823 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
41824 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
41825 ],
41826 [
41827 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
41828 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
41829 ],
41830 [
41831 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
41832 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
41833 ],
41834 [
41835 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
41836 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
41837 ],
41838 [
41839 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
41840 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
41841 ],
41842 [
41843 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
41844 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
41845 ],
41846 [
41847 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
41848 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
41849 ],
41850 [
41851 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
41852 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
41853 ],
41854 [
41855 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
41856 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
41857 ],
41858 [
41859 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
41860 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
41861 ],
41862 [
41863 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
41864 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
41865 ],
41866 [
41867 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
41868 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
41869 ],
41870 [
41871 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
41872 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
41873 ],
41874 [
41875 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
41876 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
41877 ],
41878 [
41879 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
41880 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
41881 ],
41882 [
41883 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
41884 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
41885 ],
41886 [
41887 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
41888 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
41889 ],
41890 [
41891 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
41892 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
41893 ],
41894 [
41895 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
41896 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
41897 ],
41898 [
41899 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
41900 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
41901 ],
41902 [
41903 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
41904 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
41905 ],
41906 [
41907 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
41908 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
41909 ],
41910 [
41911 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
41912 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
41913 ],
41914 [
41915 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
41916 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
41917 ],
41918 [
41919 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
41920 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
41921 ],
41922 [
41923 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
41924 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
41925 ],
41926 [
41927 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
41928 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
41929 ],
41930 [
41931 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
41932 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
41933 ],
41934 [
41935 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
41936 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
41937 ],
41938 [
41939 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
41940 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
41941 ],
41942 [
41943 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
41944 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
41945 ],
41946 [
41947 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
41948 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
41949 ],
41950 [
41951 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
41952 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
41953 ],
41954 [
41955 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
41956 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
41957 ],
41958 [
41959 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
41960 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
41961 ],
41962 [
41963 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
41964 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
41965 ],
41966 [
41967 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
41968 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
41969 ],
41970 [
41971 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
41972 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
41973 ],
41974 [
41975 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
41976 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
41977 ],
41978 [
41979 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
41980 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
41981 ],
41982 [
41983 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
41984 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
41985 ],
41986 [
41987 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
41988 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
41989 ],
41990 [
41991 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
41992 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
41993 ],
41994 [
41995 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
41996 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
41997 ],
41998 [
41999 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
42000 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
42001 ],
42002 [
42003 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
42004 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
42005 ],
42006 [
42007 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
42008 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
42009 ],
42010 [
42011 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
42012 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
42013 ],
42014 [
42015 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
42016 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
42017 ],
42018 [
42019 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
42020 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
42021 ],
42022 [
42023 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
42024 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
42025 ],
42026 [
42027 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
42028 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
42029 ],
42030 [
42031 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
42032 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
42033 ],
42034 [
42035 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
42036 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
42037 ],
42038 [
42039 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
42040 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
42041 ],
42042 [
42043 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
42044 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
42045 ],
42046 [
42047 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
42048 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
42049 ],
42050 [
42051 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
42052 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
42053 ],
42054 [
42055 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
42056 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
42057 ],
42058 [
42059 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
42060 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
42061 ],
42062 [
42063 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
42064 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
42065 ],
42066 [
42067 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
42068 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
42069 ],
42070 [
42071 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
42072 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
42073 ],
42074 [
42075 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
42076 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
42077 ],
42078 [
42079 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
42080 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
42081 ],
42082 [
42083 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
42084 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
42085 ],
42086 [
42087 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
42088 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
42089 ],
42090 [
42091 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
42092 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
42093 ],
42094 [
42095 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
42096 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
42097 ],
42098 [
42099 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
42100 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
42101 ],
42102 [
42103 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
42104 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
42105 ],
42106 [
42107 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
42108 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
42109 ],
42110 [
42111 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
42112 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
42113 ],
42114 [
42115 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
42116 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
42117 ],
42118 [
42119 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
42120 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
42121 ],
42122 [
42123 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
42124 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
42125 ],
42126 [
42127 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
42128 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
42129 ],
42130 [
42131 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
42132 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
42133 ],
42134 [
42135 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
42136 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
42137 ],
42138 [
42139 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
42140 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
42141 ],
42142 [
42143 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
42144 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
42145 ],
42146 [
42147 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
42148 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
42149 ],
42150 [
42151 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
42152 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
42153 ],
42154 [
42155 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
42156 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
42157 ],
42158 [
42159 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
42160 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
42161 ],
42162 [
42163 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
42164 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
42165 ],
42166 [
42167 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
42168 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
42169 ],
42170 [
42171 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
42172 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
42173 ],
42174 [
42175 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
42176 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
42177 ],
42178 [
42179 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
42180 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
42181 ],
42182 [
42183 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
42184 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
42185 ],
42186 [
42187 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
42188 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
42189 ],
42190 [
42191 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
42192 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
42193 ],
42194 [
42195 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
42196 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
42197 ],
42198 [
42199 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
42200 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
42201 ],
42202 [
42203 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
42204 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
42205 ],
42206 [
42207 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
42208 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
42209 ],
42210 [
42211 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
42212 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
42213 ],
42214 [
42215 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
42216 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
42217 ],
42218 [
42219 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
42220 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
42221 ],
42222 [
42223 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
42224 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
42225 ],
42226 [
42227 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
42228 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
42229 ],
42230 [
42231 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
42232 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
42233 ],
42234 [
42235 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
42236 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
42237 ],
42238 [
42239 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
42240 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
42241 ],
42242 [
42243 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
42244 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
42245 ],
42246 [
42247 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
42248 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
42249 ],
42250 [
42251 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
42252 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
42253 ],
42254 [
42255 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
42256 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
42257 ],
42258 [
42259 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
42260 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
42261 ],
42262 [
42263 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
42264 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
42265 ],
42266 [
42267 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
42268 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
42269 ],
42270 [
42271 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
42272 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
42273 ],
42274 [
42275 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
42276 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
42277 ],
42278 [
42279 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
42280 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
42281 ],
42282 [
42283 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
42284 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
42285 ],
42286 [
42287 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
42288 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
42289 ],
42290 [
42291 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
42292 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
42293 ],
42294 [
42295 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
42296 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
42297 ],
42298 [
42299 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
42300 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
42301 ],
42302 [
42303 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
42304 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
42305 ],
42306 [
42307 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
42308 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
42309 ],
42310 [
42311 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
42312 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
42313 ],
42314 [
42315 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
42316 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
42317 ],
42318 [
42319 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
42320 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
42321 ],
42322 [
42323 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
42324 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
42325 ]
42326 ]
42327 }
42328};
42329
42330var curves_1 = createCommonjsModule(function (module, exports) {
42331
42332var curves = exports;
42333
42334
42335
42336
42337
42338var assert = utils_1$1.assert;
42339
42340function PresetCurve(options) {
42341 if (options.type === 'short')
42342 this.curve = new curve_1.short(options);
42343 else if (options.type === 'edwards')
42344 this.curve = new curve_1.edwards(options);
42345 else if (options.type === 'mont')
42346 this.curve = new curve_1.mont(options);
42347 else throw new Error('Unknown curve type.');
42348 this.g = this.curve.g;
42349 this.n = this.curve.n;
42350 this.hash = options.hash;
42351
42352 assert(this.g.validate(), 'Invalid curve');
42353 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
42354}
42355curves.PresetCurve = PresetCurve;
42356
42357function defineCurve(name, options) {
42358 Object.defineProperty(curves, name, {
42359 configurable: true,
42360 enumerable: true,
42361 get: function() {
42362 var curve = new PresetCurve(options);
42363 Object.defineProperty(curves, name, {
42364 configurable: true,
42365 enumerable: true,
42366 value: curve
42367 });
42368 return curve;
42369 }
42370 });
42371}
42372
42373defineCurve('p192', {
42374 type: 'short',
42375 prime: 'p192',
42376 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
42377 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
42378 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
42379 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
42380 hash: hash_1.sha256,
42381 gRed: false,
42382 g: [
42383 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
42384 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
42385 ]
42386});
42387
42388defineCurve('p224', {
42389 type: 'short',
42390 prime: 'p224',
42391 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
42392 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
42393 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
42394 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
42395 hash: hash_1.sha256,
42396 gRed: false,
42397 g: [
42398 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
42399 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
42400 ]
42401});
42402
42403defineCurve('p256', {
42404 type: 'short',
42405 prime: null,
42406 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
42407 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
42408 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
42409 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
42410 hash: hash_1.sha256,
42411 gRed: false,
42412 g: [
42413 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
42414 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
42415 ]
42416});
42417
42418defineCurve('p384', {
42419 type: 'short',
42420 prime: null,
42421 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42422 'fffffffe ffffffff 00000000 00000000 ffffffff',
42423 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42424 'fffffffe ffffffff 00000000 00000000 fffffffc',
42425 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
42426 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
42427 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
42428 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
42429 hash: hash_1.sha384,
42430 gRed: false,
42431 g: [
42432 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
42433 '5502f25d bf55296c 3a545e38 72760ab7',
42434 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
42435 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
42436 ]
42437});
42438
42439defineCurve('p521', {
42440 type: 'short',
42441 prime: null,
42442 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42443 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42444 'ffffffff ffffffff ffffffff ffffffff ffffffff',
42445 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42446 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42447 'ffffffff ffffffff ffffffff ffffffff fffffffc',
42448 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
42449 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
42450 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
42451 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42452 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
42453 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
42454 hash: hash_1.sha512,
42455 gRed: false,
42456 g: [
42457 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
42458 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
42459 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
42460 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
42461 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
42462 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
42463 ]
42464});
42465
42466// https://tools.ietf.org/html/rfc7748#section-4.1
42467defineCurve('curve25519', {
42468 type: 'mont',
42469 prime: 'p25519',
42470 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42471 a: '76d06',
42472 b: '1',
42473 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42474 cofactor: '8',
42475 hash: hash_1.sha256,
42476 gRed: false,
42477 g: [
42478 '9'
42479 ]
42480});
42481
42482defineCurve('ed25519', {
42483 type: 'edwards',
42484 prime: 'p25519',
42485 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42486 a: '-1',
42487 c: '1',
42488 // -121665 * (121666^(-1)) (mod P)
42489 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
42490 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42491 cofactor: '8',
42492 hash: hash_1.sha256,
42493 gRed: false,
42494 g: [
42495 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
42496 // 4/5
42497 '6666666666666666666666666666666666666666666666666666666666666658'
42498 ]
42499});
42500
42501// https://tools.ietf.org/html/rfc5639#section-3.4
42502defineCurve('brainpoolP256r1', {
42503 type: 'short',
42504 prime: null,
42505 p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
42506 a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
42507 b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
42508 n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
42509 hash: hash_1.sha256, // or 384, or 512
42510 gRed: false,
42511 g: [
42512 '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
42513 '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
42514 ]
42515});
42516
42517// https://tools.ietf.org/html/rfc5639#section-3.6
42518defineCurve('brainpoolP384r1', {
42519 type: 'short',
42520 prime: null,
42521 p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
42522 'ACD3A729 901D1A71 87470013 3107EC53',
42523 a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
42524 '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
42525 b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
42526 '7CB43902 95DBC994 3AB78696 FA504C11',
42527 n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
42528 'CF3AB6AF 6B7FC310 3B883202 E9046565',
42529 hash: hash_1.sha384, // or 512
42530 gRed: false,
42531 g: [
42532 '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
42533 'E8E826E03436D646AAEF87B2E247D4AF1E',
42534 '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
42535 '280E4646217791811142820341263C5315'
42536 ]
42537});
42538
42539// https://tools.ietf.org/html/rfc5639#section-3.7
42540defineCurve('brainpoolP512r1', {
42541 type: 'short',
42542 prime: null,
42543 p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
42544 '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
42545 a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
42546 '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
42547 b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
42548 '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
42549 n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
42550 '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
42551 hash: hash_1.sha512,
42552 gRed: false,
42553 g: [
42554 '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
42555 '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
42556 '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
42557 '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
42558 ]
42559});
42560
42561// https://en.bitcoin.it/wiki/Secp256k1
42562var pre;
42563try {
42564 pre = secp256k1;
42565} catch (e) {
42566 pre = undefined;
42567}
42568
42569defineCurve('secp256k1', {
42570 type: 'short',
42571 prime: 'k256',
42572 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
42573 a: '0',
42574 b: '7',
42575 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
42576 h: '1',
42577 hash: hash_1.sha256,
42578
42579 // Precomputed endomorphism
42580 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
42581 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
42582 basis: [
42583 {
42584 a: '3086d221a7d46bcde86c90e49284eb15',
42585 b: '-e4437ed6010e88286f547fa90abfe4c3'
42586 },
42587 {
42588 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
42589 b: '3086d221a7d46bcde86c90e49284eb15'
42590 }
42591 ],
42592
42593 gRed: false,
42594 g: [
42595 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
42596 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
42597 pre
42598 ]
42599});
42600});
42601
42602function HmacDRBG(options) {
42603 if (!(this instanceof HmacDRBG))
42604 return new HmacDRBG(options);
42605 this.hash = options.hash;
42606 this.predResist = !!options.predResist;
42607
42608 this.outLen = this.hash.outSize;
42609 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
42610
42611 this._reseed = null;
42612 this.reseedInterval = null;
42613 this.K = null;
42614 this.V = null;
42615
42616 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
42617 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
42618 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
42619 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42620 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42621 this._init(entropy, nonce, pers);
42622}
42623var hmacDrbg = HmacDRBG;
42624
42625HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
42626 var seed = entropy.concat(nonce).concat(pers);
42627
42628 this.K = new Array(this.outLen / 8);
42629 this.V = new Array(this.outLen / 8);
42630 for (var i = 0; i < this.V.length; i++) {
42631 this.K[i] = 0x00;
42632 this.V[i] = 0x01;
42633 }
42634
42635 this._update(seed);
42636 this._reseed = 1;
42637 this.reseedInterval = 0x1000000000000; // 2^48
42638};
42639
42640HmacDRBG.prototype._hmac = function hmac() {
42641 return new hash_1.hmac(this.hash, this.K);
42642};
42643
42644HmacDRBG.prototype._update = function update(seed) {
42645 var kmac = this._hmac()
42646 .update(this.V)
42647 .update([ 0x00 ]);
42648 if (seed)
42649 kmac = kmac.update(seed);
42650 this.K = kmac.digest();
42651 this.V = this._hmac().update(this.V).digest();
42652 if (!seed)
42653 return;
42654
42655 this.K = this._hmac()
42656 .update(this.V)
42657 .update([ 0x01 ])
42658 .update(seed)
42659 .digest();
42660 this.V = this._hmac().update(this.V).digest();
42661};
42662
42663HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
42664 // Optional entropy enc
42665 if (typeof entropyEnc !== 'string') {
42666 addEnc = add;
42667 add = entropyEnc;
42668 entropyEnc = null;
42669 }
42670
42671 entropy = utils_1.toArray(entropy, entropyEnc);
42672 add = utils_1.toArray(add, addEnc);
42673
42674 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42675 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42676
42677 this._update(entropy.concat(add || []));
42678 this._reseed = 1;
42679};
42680
42681HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
42682 if (this._reseed > this.reseedInterval)
42683 throw new Error('Reseed is required');
42684
42685 // Optional encoding
42686 if (typeof enc !== 'string') {
42687 addEnc = add;
42688 add = enc;
42689 enc = null;
42690 }
42691
42692 // Optional additional data
42693 if (add) {
42694 add = utils_1.toArray(add, addEnc || 'hex');
42695 this._update(add);
42696 }
42697
42698 var temp = [];
42699 while (temp.length < len) {
42700 this.V = this._hmac().update(this.V).digest();
42701 temp = temp.concat(this.V);
42702 }
42703
42704 var res = temp.slice(0, len);
42705 this._update(add);
42706 this._reseed++;
42707 return utils_1.encode(res, enc);
42708};
42709
42710var assert$5 = utils_1$1.assert;
42711
42712function KeyPair(ec, options) {
42713 this.ec = ec;
42714 this.priv = null;
42715 this.pub = null;
42716
42717 // KeyPair(ec, { priv: ..., pub: ... })
42718 if (options.priv)
42719 this._importPrivate(options.priv, options.privEnc);
42720 if (options.pub)
42721 this._importPublic(options.pub, options.pubEnc);
42722}
42723var key = KeyPair;
42724
42725KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
42726 if (pub instanceof KeyPair)
42727 return pub;
42728
42729 return new KeyPair(ec, {
42730 pub: pub,
42731 pubEnc: enc
42732 });
42733};
42734
42735KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
42736 if (priv instanceof KeyPair)
42737 return priv;
42738
42739 return new KeyPair(ec, {
42740 priv: priv,
42741 privEnc: enc
42742 });
42743};
42744
42745// TODO: should not validate for X25519
42746KeyPair.prototype.validate = function validate() {
42747 var pub = this.getPublic();
42748
42749 if (pub.isInfinity())
42750 return { result: false, reason: 'Invalid public key' };
42751 if (!pub.validate())
42752 return { result: false, reason: 'Public key is not a point' };
42753 if (!pub.mul(this.ec.curve.n).isInfinity())
42754 return { result: false, reason: 'Public key * N != O' };
42755
42756 return { result: true, reason: null };
42757};
42758
42759KeyPair.prototype.getPublic = function getPublic(enc, compact) {
42760 if (!this.pub)
42761 this.pub = this.ec.g.mul(this.priv);
42762
42763 if (!enc)
42764 return this.pub;
42765
42766 return this.pub.encode(enc, compact);
42767};
42768
42769KeyPair.prototype.getPrivate = function getPrivate(enc) {
42770 if (enc === 'hex')
42771 return this.priv.toString(16, 2);
42772 else
42773 return this.priv;
42774};
42775
42776KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
42777 this.priv = new bn(key, enc || 16);
42778
42779 // For Curve25519/Curve448 we have a specific procedure.
42780 // TODO Curve448
42781 if (this.ec.curve.type === 'mont') {
42782 var one = this.ec.curve.one;
42783 var mask = one.ushln(255 - 3).sub(one).ushln(3);
42784 this.priv = this.priv.or(one.ushln(255 - 1));
42785 this.priv = this.priv.and(mask);
42786 } else
42787 // Ensure that the priv won't be bigger than n, otherwise we may fail
42788 // in fixed multiplication method
42789 this.priv = this.priv.umod(this.ec.curve.n);
42790};
42791
42792KeyPair.prototype._importPublic = function _importPublic(key, enc) {
42793 if (key.x || key.y) {
42794 // Montgomery points only have an `x` coordinate.
42795 // Weierstrass/Edwards points on the other hand have both `x` and
42796 // `y` coordinates.
42797 if (this.ec.curve.type === 'mont') {
42798 assert$5(key.x, 'Need x coordinate');
42799 } else if (this.ec.curve.type === 'short' ||
42800 this.ec.curve.type === 'edwards') {
42801 assert$5(key.x && key.y, 'Need both x and y coordinate');
42802 }
42803 this.pub = this.ec.curve.point(key.x, key.y);
42804 return;
42805 }
42806 this.pub = this.ec.curve.decodePoint(key, enc);
42807};
42808
42809// ECDH
42810KeyPair.prototype.derive = function derive(pub) {
42811 return pub.mul(this.priv).getX();
42812};
42813
42814// ECDSA
42815KeyPair.prototype.sign = function sign(msg, enc, options) {
42816 return this.ec.sign(msg, this, enc, options);
42817};
42818
42819KeyPair.prototype.verify = function verify(msg, signature) {
42820 return this.ec.verify(msg, signature, this);
42821};
42822
42823KeyPair.prototype.inspect = function inspect() {
42824 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
42825 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
42826};
42827
42828var assert$6 = utils_1$1.assert;
42829
42830function Signature$1(options, enc) {
42831 if (options instanceof Signature$1)
42832 return options;
42833
42834 if (this._importDER(options, enc))
42835 return;
42836
42837 assert$6(options.r && options.s, 'Signature without r or s');
42838 this.r = new bn(options.r, 16);
42839 this.s = new bn(options.s, 16);
42840 if (options.recoveryParam === undefined)
42841 this.recoveryParam = null;
42842 else
42843 this.recoveryParam = options.recoveryParam;
42844}
42845var signature$1 = Signature$1;
42846
42847function Position() {
42848 this.place = 0;
42849}
42850
42851function getLength(buf, p) {
42852 var initial = buf[p.place++];
42853 if (!(initial & 0x80)) {
42854 return initial;
42855 }
42856 var octetLen = initial & 0xf;
42857 var val = 0;
42858 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
42859 val <<= 8;
42860 val |= buf[off];
42861 }
42862 p.place = off;
42863 return val;
42864}
42865
42866function rmPadding(buf) {
42867 var i = 0;
42868 var len = buf.length - 1;
42869 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
42870 i++;
42871 }
42872 if (i === 0) {
42873 return buf;
42874 }
42875 return buf.slice(i);
42876}
42877
42878Signature$1.prototype._importDER = function _importDER(data, enc) {
42879 data = utils_1$1.toArray(data, enc);
42880 var p = new Position();
42881 if (data[p.place++] !== 0x30) {
42882 return false;
42883 }
42884 var len = getLength(data, p);
42885 if ((len + p.place) !== data.length) {
42886 return false;
42887 }
42888 if (data[p.place++] !== 0x02) {
42889 return false;
42890 }
42891 var rlen = getLength(data, p);
42892 var r = data.slice(p.place, rlen + p.place);
42893 p.place += rlen;
42894 if (data[p.place++] !== 0x02) {
42895 return false;
42896 }
42897 var slen = getLength(data, p);
42898 if (data.length !== slen + p.place) {
42899 return false;
42900 }
42901 var s = data.slice(p.place, slen + p.place);
42902 if (r[0] === 0 && (r[1] & 0x80)) {
42903 r = r.slice(1);
42904 }
42905 if (s[0] === 0 && (s[1] & 0x80)) {
42906 s = s.slice(1);
42907 }
42908
42909 this.r = new bn(r);
42910 this.s = new bn(s);
42911 this.recoveryParam = null;
42912
42913 return true;
42914};
42915
42916function constructLength(arr, len) {
42917 if (len < 0x80) {
42918 arr.push(len);
42919 return;
42920 }
42921 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
42922 arr.push(octets | 0x80);
42923 while (--octets) {
42924 arr.push((len >>> (octets << 3)) & 0xff);
42925 }
42926 arr.push(len);
42927}
42928
42929Signature$1.prototype.toDER = function toDER(enc) {
42930 var r = this.r.toArray();
42931 var s = this.s.toArray();
42932
42933 // Pad values
42934 if (r[0] & 0x80)
42935 r = [ 0 ].concat(r);
42936 // Pad values
42937 if (s[0] & 0x80)
42938 s = [ 0 ].concat(s);
42939
42940 r = rmPadding(r);
42941 s = rmPadding(s);
42942
42943 while (!s[0] && !(s[1] & 0x80)) {
42944 s = s.slice(1);
42945 }
42946 var arr = [ 0x02 ];
42947 constructLength(arr, r.length);
42948 arr = arr.concat(r);
42949 arr.push(0x02);
42950 constructLength(arr, s.length);
42951 var backHalf = arr.concat(s);
42952 var res = [ 0x30 ];
42953 constructLength(res, backHalf.length);
42954 res = res.concat(backHalf);
42955 return utils_1$1.encode(res, enc);
42956};
42957
42958var assert$7 = utils_1$1.assert;
42959
42960
42961
42962
42963function EC(options) {
42964 if (!(this instanceof EC))
42965 return new EC(options);
42966
42967 // Shortcut `elliptic.ec(curve-name)`
42968 if (typeof options === 'string') {
42969 assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
42970
42971 options = curves_1[options];
42972 }
42973
42974 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
42975 if (options instanceof curves_1.PresetCurve)
42976 options = { curve: options };
42977
42978 this.curve = options.curve.curve;
42979 this.n = this.curve.n;
42980 this.nh = this.n.ushrn(1);
42981 this.g = this.curve.g;
42982
42983 // Point on curve
42984 this.g = options.curve.g;
42985 this.g.precompute(options.curve.n.bitLength() + 1);
42986
42987 // Hash function for DRBG
42988 this.hash = options.hash || options.curve.hash;
42989}
42990var ec = EC;
42991
42992EC.prototype.keyPair = function keyPair(options) {
42993 return new key(this, options);
42994};
42995
42996EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
42997 return key.fromPrivate(this, priv, enc);
42998};
42999
43000EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
43001 return key.fromPublic(this, pub, enc);
43002};
43003
43004EC.prototype.genKeyPair = function genKeyPair(options) {
43005 if (!options)
43006 options = {};
43007
43008 // Instantiate Hmac_DRBG
43009 var drbg = new hmacDrbg({
43010 hash: this.hash,
43011 pers: options.pers,
43012 persEnc: options.persEnc || 'utf8',
43013 entropy: options.entropy || brorand(this.hash.hmacStrength),
43014 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43015 nonce: this.n.toArray()
43016 });
43017
43018 // Key generation for curve25519 is simpler
43019 if (this.curve.type === 'mont') {
43020 var priv = new bn(drbg.generate(32));
43021 return this.keyFromPrivate(priv);
43022 }
43023
43024 var bytes = this.n.byteLength();
43025 var ns2 = this.n.sub(new bn(2));
43026 do {
43027 var priv = new bn(drbg.generate(bytes));
43028 if (priv.cmp(ns2) > 0)
43029 continue;
43030
43031 priv.iaddn(1);
43032 return this.keyFromPrivate(priv);
43033 } while (true);
43034};
43035
43036EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
43037 bitSize = bitSize || msg.byteLength() * 8;
43038 var delta = bitSize - this.n.bitLength();
43039 if (delta > 0)
43040 msg = msg.ushrn(delta);
43041 if (!truncOnly && msg.cmp(this.n) >= 0)
43042 return msg.sub(this.n);
43043 else
43044 return msg;
43045};
43046
43047EC.prototype.truncateMsg = function truncateMSG(msg) {
43048 // Bit size is only determined correctly for Uint8Arrays and hex strings
43049 var bitSize;
43050 if (msg instanceof Uint8Array) {
43051 bitSize = msg.byteLength * 8;
43052 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43053 } else if (typeof msg === 'string') {
43054 bitSize = msg.length * 4;
43055 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43056 } else {
43057 msg = this._truncateToN(new bn(msg, 16));
43058 }
43059 return msg;
43060};
43061
43062EC.prototype.sign = function sign(msg, key, enc, options) {
43063 if (typeof enc === 'object') {
43064 options = enc;
43065 enc = null;
43066 }
43067 if (!options)
43068 options = {};
43069
43070 key = this.keyFromPrivate(key, enc);
43071 msg = this.truncateMsg(msg);
43072
43073 // Zero-extend key to provide enough entropy
43074 var bytes = this.n.byteLength();
43075 var bkey = key.getPrivate().toArray('be', bytes);
43076
43077 // Zero-extend nonce to have the same byte size as N
43078 var nonce = msg.toArray('be', bytes);
43079
43080 // Instantiate Hmac_DRBG
43081 var drbg = new hmacDrbg({
43082 hash: this.hash,
43083 entropy: bkey,
43084 nonce: nonce,
43085 pers: options.pers,
43086 persEnc: options.persEnc || 'utf8'
43087 });
43088
43089 // Number of bytes to generate
43090 var ns1 = this.n.sub(new bn(1));
43091
43092 for (var iter = 0; true; iter++) {
43093 var k = options.k ?
43094 options.k(iter) :
43095 new bn(drbg.generate(this.n.byteLength()));
43096 k = this._truncateToN(k, true);
43097 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
43098 continue;
43099
43100 var kp = this.g.mul(k);
43101 if (kp.isInfinity())
43102 continue;
43103
43104 var kpX = kp.getX();
43105 var r = kpX.umod(this.n);
43106 if (r.cmpn(0) === 0)
43107 continue;
43108
43109 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
43110 s = s.umod(this.n);
43111 if (s.cmpn(0) === 0)
43112 continue;
43113
43114 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
43115 (kpX.cmp(r) !== 0 ? 2 : 0);
43116
43117 // Use complement of `s`, if it is > `n / 2`
43118 if (options.canonical && s.cmp(this.nh) > 0) {
43119 s = this.n.sub(s);
43120 recoveryParam ^= 1;
43121 }
43122
43123 return new signature$1({ r: r, s: s, recoveryParam: recoveryParam });
43124 }
43125};
43126
43127EC.prototype.verify = function verify(msg, signature, key, enc) {
43128 key = this.keyFromPublic(key, enc);
43129 signature = new signature$1(signature, 'hex');
43130 // Fallback to the old code
43131 var ret = this._verify(this.truncateMsg(msg), signature, key) ||
43132 this._verify(this._truncateToN(new bn(msg, 16)), signature, key);
43133 return ret;
43134};
43135
43136EC.prototype._verify = function _verify(msg, signature, key) {
43137 // Perform primitive values validation
43138 var r = signature.r;
43139 var s = signature.s;
43140 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
43141 return false;
43142 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
43143 return false;
43144
43145 // Validate signature
43146 var sinv = s.invm(this.n);
43147 var u1 = sinv.mul(msg).umod(this.n);
43148 var u2 = sinv.mul(r).umod(this.n);
43149
43150 if (!this.curve._maxwellTrick) {
43151 var p = this.g.mulAdd(u1, key.getPublic(), u2);
43152 if (p.isInfinity())
43153 return false;
43154
43155 return p.getX().umod(this.n).cmp(r) === 0;
43156 }
43157
43158 // NOTE: Greg Maxwell's trick, inspired by:
43159 // https://git.io/vad3K
43160
43161 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
43162 if (p.isInfinity())
43163 return false;
43164
43165 // Compare `p.x` of Jacobian point with `r`,
43166 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
43167 // inverse of `p.z^2`
43168 return p.eqXToP(r);
43169};
43170
43171EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
43172 assert$7((3 & j) === j, 'The recovery param is more than two bits');
43173 signature = new signature$1(signature, enc);
43174
43175 var n = this.n;
43176 var e = new bn(msg);
43177 var r = signature.r;
43178 var s = signature.s;
43179
43180 // A set LSB signifies that the y-coordinate is odd
43181 var isYOdd = j & 1;
43182 var isSecondKey = j >> 1;
43183 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
43184 throw new Error('Unable to find sencond key candinate');
43185
43186 // 1.1. Let x = r + jn.
43187 if (isSecondKey)
43188 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
43189 else
43190 r = this.curve.pointFromX(r, isYOdd);
43191
43192 var rInv = signature.r.invm(n);
43193 var s1 = n.sub(e).mul(rInv).umod(n);
43194 var s2 = s.mul(rInv).umod(n);
43195
43196 // 1.6.1 Compute Q = r^-1 (sR - eG)
43197 // Q = r^-1 (sR + -eG)
43198 return this.g.mulAdd(s1, r, s2);
43199};
43200
43201EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
43202 signature = new signature$1(signature, enc);
43203 if (signature.recoveryParam !== null)
43204 return signature.recoveryParam;
43205
43206 for (var i = 0; i < 4; i++) {
43207 var Qprime;
43208 try {
43209 Qprime = this.recoverPubKey(e, signature, i);
43210 } catch (e) {
43211 continue;
43212 }
43213
43214 if (Qprime.eq(Q))
43215 return i;
43216 }
43217 throw new Error('Unable to find valid recovery factor');
43218};
43219
43220var assert$8 = utils_1$1.assert;
43221var parseBytes = utils_1$1.parseBytes;
43222var cachedProperty = utils_1$1.cachedProperty;
43223
43224/**
43225* @param {EDDSA} eddsa - instance
43226* @param {Object} params - public/private key parameters
43227*
43228* @param {Array<Byte>} [params.secret] - secret seed bytes
43229* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
43230* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
43231*
43232*/
43233function KeyPair$1(eddsa, params) {
43234 this.eddsa = eddsa;
43235 if (params.hasOwnProperty('secret'))
43236 this._secret = parseBytes(params.secret);
43237 if (eddsa.isPoint(params.pub))
43238 this._pub = params.pub;
43239 else {
43240 this._pubBytes = parseBytes(params.pub);
43241 if (this._pubBytes && this._pubBytes.length === 33 &&
43242 this._pubBytes[0] === 0x40)
43243 this._pubBytes = this._pubBytes.slice(1, 33);
43244 if (this._pubBytes && this._pubBytes.length !== 32)
43245 throw new Error('Unknown point compression format');
43246 }
43247}
43248
43249KeyPair$1.fromPublic = function fromPublic(eddsa, pub) {
43250 if (pub instanceof KeyPair$1)
43251 return pub;
43252 return new KeyPair$1(eddsa, { pub: pub });
43253};
43254
43255KeyPair$1.fromSecret = function fromSecret(eddsa, secret) {
43256 if (secret instanceof KeyPair$1)
43257 return secret;
43258 return new KeyPair$1(eddsa, { secret: secret });
43259};
43260
43261KeyPair$1.prototype.secret = function secret() {
43262 return this._secret;
43263};
43264
43265cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() {
43266 return this.eddsa.encodePoint(this.pub());
43267});
43268
43269cachedProperty(KeyPair$1, 'pub', function pub() {
43270 if (this._pubBytes)
43271 return this.eddsa.decodePoint(this._pubBytes);
43272 return this.eddsa.g.mul(this.priv());
43273});
43274
43275cachedProperty(KeyPair$1, 'privBytes', function privBytes() {
43276 var eddsa = this.eddsa;
43277 var hash = this.hash();
43278 var lastIx = eddsa.encodingLength - 1;
43279
43280 // https://tools.ietf.org/html/rfc8032#section-5.1.5
43281 var a = hash.slice(0, eddsa.encodingLength);
43282 a[0] &= 248;
43283 a[lastIx] &= 127;
43284 a[lastIx] |= 64;
43285
43286 return a;
43287});
43288
43289cachedProperty(KeyPair$1, 'priv', function priv() {
43290 return this.eddsa.decodeInt(this.privBytes());
43291});
43292
43293cachedProperty(KeyPair$1, 'hash', function hash() {
43294 return this.eddsa.hash().update(this.secret()).digest();
43295});
43296
43297cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() {
43298 return this.hash().slice(this.eddsa.encodingLength);
43299});
43300
43301KeyPair$1.prototype.sign = function sign(message) {
43302 assert$8(this._secret, 'KeyPair can only verify');
43303 return this.eddsa.sign(message, this);
43304};
43305
43306KeyPair$1.prototype.verify = function verify(message, sig) {
43307 return this.eddsa.verify(message, sig, this);
43308};
43309
43310KeyPair$1.prototype.getSecret = function getSecret(enc) {
43311 assert$8(this._secret, 'KeyPair is public only');
43312 return utils_1$1.encode(this.secret(), enc);
43313};
43314
43315KeyPair$1.prototype.getPublic = function getPublic(enc, compact) {
43316 return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
43317};
43318
43319var key$1 = KeyPair$1;
43320
43321var assert$9 = utils_1$1.assert;
43322var cachedProperty$1 = utils_1$1.cachedProperty;
43323var parseBytes$1 = utils_1$1.parseBytes;
43324
43325/**
43326* @param {EDDSA} eddsa - eddsa instance
43327* @param {Array<Bytes>|Object} sig -
43328* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
43329* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
43330* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
43331* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
43332*/
43333function Signature$2(eddsa, sig) {
43334 this.eddsa = eddsa;
43335
43336 if (typeof sig !== 'object')
43337 sig = parseBytes$1(sig);
43338
43339 if (Array.isArray(sig)) {
43340 sig = {
43341 R: sig.slice(0, eddsa.encodingLength),
43342 S: sig.slice(eddsa.encodingLength)
43343 };
43344 }
43345
43346 assert$9(sig.R && sig.S, 'Signature without R or S');
43347
43348 if (eddsa.isPoint(sig.R))
43349 this._R = sig.R;
43350 if (sig.S instanceof bn)
43351 this._S = sig.S;
43352
43353 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
43354 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
43355}
43356
43357cachedProperty$1(Signature$2, 'S', function S() {
43358 return this.eddsa.decodeInt(this.Sencoded());
43359});
43360
43361cachedProperty$1(Signature$2, 'R', function R() {
43362 return this.eddsa.decodePoint(this.Rencoded());
43363});
43364
43365cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() {
43366 return this.eddsa.encodePoint(this.R());
43367});
43368
43369cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() {
43370 return this.eddsa.encodeInt(this.S());
43371});
43372
43373Signature$2.prototype.toBytes = function toBytes() {
43374 return this.Rencoded().concat(this.Sencoded());
43375};
43376
43377Signature$2.prototype.toHex = function toHex() {
43378 return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase();
43379};
43380
43381var signature$2 = Signature$2;
43382
43383var assert$a = utils_1$1.assert;
43384var parseBytes$2 = utils_1$1.parseBytes;
43385
43386
43387
43388function EDDSA(curve) {
43389 assert$a(curve === 'ed25519', 'only tested with ed25519 so far');
43390
43391 if (!(this instanceof EDDSA))
43392 return new EDDSA(curve);
43393
43394 var curve = curves_1[curve].curve;
43395 this.curve = curve;
43396 this.g = curve.g;
43397 this.g.precompute(curve.n.bitLength() + 1);
43398
43399 this.pointClass = curve.point().constructor;
43400 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
43401 this.hash = hash_1.sha512;
43402}
43403
43404var eddsa$1 = EDDSA;
43405
43406/**
43407* @param {Array|String} message - message bytes
43408* @param {Array|String|KeyPair} secret - secret bytes or a keypair
43409* @returns {Signature} - signature
43410*/
43411EDDSA.prototype.sign = function sign(message, secret) {
43412 message = parseBytes$2(message);
43413 var key = this.keyFromSecret(secret);
43414 var r = this.hashInt(key.messagePrefix(), message);
43415 var R = this.g.mul(r);
43416 var Rencoded = this.encodePoint(R);
43417 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
43418 .mul(key.priv());
43419 var S = r.add(s_).umod(this.curve.n);
43420 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
43421};
43422
43423/**
43424* @param {Array} message - message bytes
43425* @param {Array|String|Signature} sig - sig bytes
43426* @param {Array|String|Point|KeyPair} pub - public key
43427* @returns {Boolean} - true if public key matches sig of message
43428*/
43429EDDSA.prototype.verify = function verify(message, sig, pub) {
43430 message = parseBytes$2(message);
43431 sig = this.makeSignature(sig);
43432 var key = this.keyFromPublic(pub);
43433 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
43434 var SG = this.g.mul(sig.S());
43435 var RplusAh = sig.R().add(key.pub().mul(h));
43436 return RplusAh.eq(SG);
43437};
43438
43439EDDSA.prototype.hashInt = function hashInt() {
43440 var hash = this.hash();
43441 for (var i = 0; i < arguments.length; i++)
43442 hash.update(arguments[i]);
43443 return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n);
43444};
43445
43446EDDSA.prototype.keyPair = function keyPair(options) {
43447 return new key$1(this, options);
43448};
43449
43450EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
43451 return key$1.fromPublic(this, pub);
43452};
43453
43454EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
43455 return key$1.fromSecret(this, secret);
43456};
43457
43458EDDSA.prototype.genKeyPair = function genKeyPair(options) {
43459 if (!options)
43460 options = {};
43461
43462 // Instantiate Hmac_DRBG
43463 var drbg = new hmacDrbg({
43464 hash: this.hash,
43465 pers: options.pers,
43466 persEnc: options.persEnc || 'utf8',
43467 entropy: options.entropy || brorand(this.hash.hmacStrength),
43468 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43469 nonce: this.curve.n.toArray()
43470 });
43471
43472 return this.keyFromSecret(drbg.generate(32));
43473};
43474
43475EDDSA.prototype.makeSignature = function makeSignature(sig) {
43476 if (sig instanceof signature$2)
43477 return sig;
43478 return new signature$2(this, sig);
43479};
43480
43481/**
43482* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
43483*
43484* EDDSA defines methods for encoding and decoding points and integers. These are
43485* helper convenience methods, that pass along to utility functions implied
43486* parameters.
43487*
43488*/
43489EDDSA.prototype.encodePoint = function encodePoint(point) {
43490 var enc = point.getY().toArray('le', this.encodingLength);
43491 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
43492 return enc;
43493};
43494
43495EDDSA.prototype.decodePoint = function decodePoint(bytes) {
43496 bytes = utils_1$1.parseBytes(bytes);
43497
43498 var lastIx = bytes.length - 1;
43499 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
43500 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
43501
43502 var y = utils_1$1.intFromLE(normed);
43503 return this.curve.pointFromY(y, xIsOdd);
43504};
43505
43506EDDSA.prototype.encodeInt = function encodeInt(num) {
43507 return num.toArray('le', this.encodingLength);
43508};
43509
43510EDDSA.prototype.decodeInt = function decodeInt(bytes) {
43511 return utils_1$1.intFromLE(bytes);
43512};
43513
43514EDDSA.prototype.isPoint = function isPoint(val) {
43515 return val instanceof this.pointClass;
43516};
43517
43518var elliptic_1 = createCommonjsModule(function (module, exports) {
43519
43520var elliptic = exports;
43521
43522elliptic.utils = utils_1$1;
43523elliptic.rand = brorand;
43524elliptic.curve = curve_1;
43525elliptic.curves = curves_1;
43526
43527// Protocols
43528elliptic.ec = ec;
43529elliptic.eddsa = eddsa$1;
43530});
43531
43532var elliptic$1 = /*#__PURE__*/Object.freeze({
43533 __proto__: null,
43534 'default': elliptic_1,
43535 __moduleExports: elliptic_1
43536});
43537
43538exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket;
43539exports.CleartextMessage = CleartextMessage;
43540exports.CompressedDataPacket = CompressedDataPacket;
43541exports.LiteralDataPacket = LiteralDataPacket;
43542exports.MarkerPacket = MarkerPacket;
43543exports.Message = Message;
43544exports.OnePassSignaturePacket = OnePassSignaturePacket;
43545exports.PacketList = PacketList;
43546exports.PrivateKey = PrivateKey;
43547exports.PublicKey = PublicKey;
43548exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket;
43549exports.PublicKeyPacket = PublicKeyPacket;
43550exports.PublicSubkeyPacket = PublicSubkeyPacket;
43551exports.SecretKeyPacket = SecretKeyPacket;
43552exports.SecretSubkeyPacket = SecretSubkeyPacket;
43553exports.Signature = Signature;
43554exports.SignaturePacket = SignaturePacket;
43555exports.Subkey = Subkey;
43556exports.SymEncryptedIntegrityProtectedDataPacket = SymEncryptedIntegrityProtectedDataPacket;
43557exports.SymEncryptedSessionKeyPacket = SymEncryptedSessionKeyPacket;
43558exports.SymmetricallyEncryptedDataPacket = SymmetricallyEncryptedDataPacket;
43559exports.TrustPacket = TrustPacket;
43560exports.UnparseablePacket = UnparseablePacket;
43561exports.UserAttributePacket = UserAttributePacket;
43562exports.UserIDPacket = UserIDPacket;
43563exports.armor = armor;
43564exports.config = defaultConfig;
43565exports.createCleartextMessage = createCleartextMessage;
43566exports.createMessage = createMessage;
43567exports.decrypt = decrypt$4;
43568exports.decryptKey = decryptKey;
43569exports.decryptSessionKeys = decryptSessionKeys;
43570exports.encrypt = encrypt$4;
43571exports.encryptKey = encryptKey;
43572exports.encryptSessionKey = encryptSessionKey;
43573exports.enums = enums;
43574exports.generateKey = generateKey;
43575exports.generateSessionKey = generateSessionKey$1;
43576exports.readCleartextMessage = readCleartextMessage;
43577exports.readKey = readKey;
43578exports.readKeys = readKeys;
43579exports.readMessage = readMessage;
43580exports.readPrivateKey = readPrivateKey;
43581exports.readPrivateKeys = readPrivateKeys;
43582exports.readSignature = readSignature;
43583exports.reformatKey = reformatKey;
43584exports.revokeKey = revokeKey;
43585exports.sign = sign$5;
43586exports.unarmor = unarmor;
43587exports.verify = verify$5;