UNPKG

1.38 MBJavaScriptView Raw
1/*! OpenPGP.js v5.0.0-1 - 2021-03-03 - 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$2 = 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$2);
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
26/**
27 * web-streams-polyfill v2.1.1
28 */
29/// <reference lib="es2015.symbol" />
30const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
31 Symbol :
32 description => `Symbol(${description})`;
33
34/// <reference lib="dom" />
35function noop() {
36 // do nothing
37}
38
39/// <reference lib="es2015.core" />
40// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
41const NumberIsNaN = Number.isNaN || function (x) {
42 // eslint-disable-next-line no-self-compare
43 return x !== x;
44};
45
46const rethrowAssertionErrorRejection = noop;
47
48function typeIsObject(x) {
49 return (typeof x === 'object' && x !== null) || typeof x === 'function';
50}
51function createArrayFromList(elements) {
52 // We use arrays to represent lists, so this is basically a no-op.
53 // Do a slice though just in case we happen to depend on the unique-ness.
54 return elements.slice();
55}
56function ArrayBufferCopy(dest, destOffset, src, srcOffset, n) {
57 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
58}
59function IsFiniteNonNegativeNumber(v) {
60 if (IsNonNegativeNumber(v) === false) {
61 return false;
62 }
63 if (v === Infinity) {
64 return false;
65 }
66 return true;
67}
68function IsNonNegativeNumber(v) {
69 if (typeof v !== 'number') {
70 return false;
71 }
72 if (NumberIsNaN(v)) {
73 return false;
74 }
75 if (v < 0) {
76 return false;
77 }
78 return true;
79}
80function Call(F, V, args) {
81 if (typeof F !== 'function') {
82 throw new TypeError('Argument is not a function');
83 }
84 return Function.prototype.apply.call(F, V, args);
85}
86function CreateAlgorithmFromUnderlyingMethod(underlyingObject, methodName, algoArgCount, extraArgs) {
87 const method = underlyingObject[methodName];
88 if (method !== undefined) {
89 if (typeof method !== 'function') {
90 throw new TypeError(`${method} is not a method`);
91 }
92 switch (algoArgCount) {
93 case 0: {
94 return () => {
95 return PromiseCall(method, underlyingObject, extraArgs);
96 };
97 }
98 case 1: {
99 return arg => {
100 const fullArgs = [arg].concat(extraArgs);
101 return PromiseCall(method, underlyingObject, fullArgs);
102 };
103 }
104 }
105 }
106 return () => promiseResolvedWith(undefined);
107}
108function InvokeOrNoop(O, P, args) {
109 const method = O[P];
110 if (method === undefined) {
111 return undefined;
112 }
113 return Call(method, O, args);
114}
115function PromiseCall(F, V, args) {
116 try {
117 return promiseResolvedWith(Call(F, V, args));
118 }
119 catch (value) {
120 return promiseRejectedWith(value);
121 }
122}
123// Not implemented correctly
124function TransferArrayBuffer(O) {
125 return O;
126}
127// Not implemented correctly
128function IsDetachedBuffer(O) {
129 return false;
130}
131function ValidateAndNormalizeHighWaterMark(highWaterMark) {
132 highWaterMark = Number(highWaterMark);
133 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
134 throw new RangeError('highWaterMark property of a queuing strategy must be non-negative and non-NaN');
135 }
136 return highWaterMark;
137}
138function MakeSizeAlgorithmFromSizeFunction(size) {
139 if (size === undefined) {
140 return () => 1;
141 }
142 if (typeof size !== 'function') {
143 throw new TypeError('size property of a queuing strategy must be a function');
144 }
145 return chunk => size(chunk);
146}
147const originalPromise = Promise;
148const originalPromiseThen = Promise.prototype.then;
149const originalPromiseResolve = Promise.resolve.bind(originalPromise);
150const originalPromiseReject = Promise.reject.bind(originalPromise);
151function newPromise(executor) {
152 return new originalPromise(executor);
153}
154function promiseResolvedWith(value) {
155 return originalPromiseResolve(value);
156}
157function promiseRejectedWith(reason) {
158 return originalPromiseReject(reason);
159}
160function PerformPromiseThen(promise, onFulfilled, onRejected) {
161 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
162 // approximation.
163 return originalPromiseThen.call(promise, onFulfilled, onRejected);
164}
165function uponPromise(promise, onFulfilled, onRejected) {
166 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
167}
168function uponFulfillment(promise, onFulfilled) {
169 uponPromise(promise, onFulfilled);
170}
171function uponRejection(promise, onRejected) {
172 uponPromise(promise, undefined, onRejected);
173}
174function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
175 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
176}
177function setPromiseIsHandledToTrue(promise) {
178 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
179}
180
181// Original from Chromium
182// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
183const QUEUE_MAX_ARRAY_SIZE = 16384;
184/**
185 * Simple queue structure.
186 *
187 * Avoids scalability issues with using a packed array directly by using
188 * multiple arrays in a linked list and keeping the array size bounded.
189 */
190class SimpleQueue {
191 constructor() {
192 this._cursor = 0;
193 this._size = 0;
194 // _front and _back are always defined.
195 this._front = {
196 _elements: [],
197 _next: undefined
198 };
199 this._back = this._front;
200 // The cursor is used to avoid calling Array.shift().
201 // It contains the index of the front element of the array inside the
202 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
203 this._cursor = 0;
204 // When there is only one node, size === elements.length - cursor.
205 this._size = 0;
206 }
207 get length() {
208 return this._size;
209 }
210 // For exception safety, this method is structured in order:
211 // 1. Read state
212 // 2. Calculate required state mutations
213 // 3. Perform state mutations
214 push(element) {
215 const oldBack = this._back;
216 let newBack = oldBack;
217 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
218 newBack = {
219 _elements: [],
220 _next: undefined
221 };
222 }
223 // push() is the mutation most likely to throw an exception, so it
224 // goes first.
225 oldBack._elements.push(element);
226 if (newBack !== oldBack) {
227 this._back = newBack;
228 oldBack._next = newBack;
229 }
230 ++this._size;
231 }
232 // Like push(), shift() follows the read -> calculate -> mutate pattern for
233 // exception safety.
234 shift() { // must not be called on an empty queue
235 const oldFront = this._front;
236 let newFront = oldFront;
237 const oldCursor = this._cursor;
238 let newCursor = oldCursor + 1;
239 const elements = oldFront._elements;
240 const element = elements[oldCursor];
241 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
242 newFront = oldFront._next;
243 newCursor = 0;
244 }
245 // No mutations before this point.
246 --this._size;
247 this._cursor = newCursor;
248 if (oldFront !== newFront) {
249 this._front = newFront;
250 }
251 // Permit shifted element to be garbage collected.
252 elements[oldCursor] = undefined;
253 return element;
254 }
255 // The tricky thing about forEach() is that it can be called
256 // re-entrantly. The queue may be mutated inside the callback. It is easy to
257 // see that push() within the callback has no negative effects since the end
258 // of the queue is checked for on every iteration. If shift() is called
259 // repeatedly within the callback then the next iteration may return an
260 // element that has been removed. In this case the callback will be called
261 // with undefined values until we either "catch up" with elements that still
262 // exist or reach the back of the queue.
263 forEach(callback) {
264 let i = this._cursor;
265 let node = this._front;
266 let elements = node._elements;
267 while (i !== elements.length || node._next !== undefined) {
268 if (i === elements.length) {
269 node = node._next;
270 elements = node._elements;
271 i = 0;
272 if (elements.length === 0) {
273 break;
274 }
275 }
276 callback(elements[i]);
277 ++i;
278 }
279 }
280 // Return the element that would be returned if shift() was called now,
281 // without modifying the queue.
282 peek() { // must not be called on an empty queue
283 const front = this._front;
284 const cursor = this._cursor;
285 return front._elements[cursor];
286 }
287}
288
289function ReadableStreamCreateReadResult(value, done, forAuthorCode) {
290 let prototype = null;
291 if (forAuthorCode === true) {
292 prototype = Object.prototype;
293 }
294 const obj = Object.create(prototype);
295 obj.value = value;
296 obj.done = done;
297 return obj;
298}
299function ReadableStreamReaderGenericInitialize(reader, stream) {
300 reader._forAuthorCode = true;
301 reader._ownerReadableStream = stream;
302 stream._reader = reader;
303 if (stream._state === 'readable') {
304 defaultReaderClosedPromiseInitialize(reader);
305 }
306 else if (stream._state === 'closed') {
307 defaultReaderClosedPromiseInitializeAsResolved(reader);
308 }
309 else {
310 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
311 }
312}
313// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
314// check.
315function ReadableStreamReaderGenericCancel(reader, reason) {
316 const stream = reader._ownerReadableStream;
317 return ReadableStreamCancel(stream, reason);
318}
319function ReadableStreamReaderGenericRelease(reader) {
320 if (reader._ownerReadableStream._state === 'readable') {
321 defaultReaderClosedPromiseReject(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
322 }
323 else {
324 defaultReaderClosedPromiseResetToRejected(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
325 }
326 reader._ownerReadableStream._reader = undefined;
327 reader._ownerReadableStream = undefined;
328}
329// Helper functions for the readers.
330function readerLockException(name) {
331 return new TypeError('Cannot ' + name + ' a stream using a released reader');
332}
333// Helper functions for the ReadableStreamDefaultReader.
334function defaultReaderClosedPromiseInitialize(reader) {
335 reader._closedPromise = newPromise((resolve, reject) => {
336 reader._closedPromise_resolve = resolve;
337 reader._closedPromise_reject = reject;
338 });
339}
340function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
341 defaultReaderClosedPromiseInitialize(reader);
342 defaultReaderClosedPromiseReject(reader, reason);
343}
344function defaultReaderClosedPromiseInitializeAsResolved(reader) {
345 defaultReaderClosedPromiseInitialize(reader);
346 defaultReaderClosedPromiseResolve(reader);
347}
348function defaultReaderClosedPromiseReject(reader, reason) {
349 setPromiseIsHandledToTrue(reader._closedPromise);
350 reader._closedPromise_reject(reason);
351 reader._closedPromise_resolve = undefined;
352 reader._closedPromise_reject = undefined;
353}
354function defaultReaderClosedPromiseResetToRejected(reader, reason) {
355 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
356}
357function defaultReaderClosedPromiseResolve(reader) {
358 reader._closedPromise_resolve(undefined);
359 reader._closedPromise_resolve = undefined;
360 reader._closedPromise_reject = undefined;
361}
362
363const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
364const PullSteps = SymbolPolyfill('[[PullSteps]]');
365
366// Abstract operations for the ReadableStream.
367function AcquireReadableStreamDefaultReader(stream, forAuthorCode = false) {
368 const reader = new ReadableStreamDefaultReader(stream);
369 reader._forAuthorCode = forAuthorCode;
370 return reader;
371}
372// ReadableStream API exposed for controllers.
373function ReadableStreamAddReadRequest(stream) {
374 const promise = newPromise((resolve, reject) => {
375 const readRequest = {
376 _resolve: resolve,
377 _reject: reject
378 };
379 stream._reader._readRequests.push(readRequest);
380 });
381 return promise;
382}
383function ReadableStreamFulfillReadRequest(stream, chunk, done) {
384 const reader = stream._reader;
385 const readRequest = reader._readRequests.shift();
386 readRequest._resolve(ReadableStreamCreateReadResult(chunk, done, reader._forAuthorCode));
387}
388function ReadableStreamGetNumReadRequests(stream) {
389 return stream._reader._readRequests.length;
390}
391function ReadableStreamHasDefaultReader(stream) {
392 const reader = stream._reader;
393 if (reader === undefined) {
394 return false;
395 }
396 if (!IsReadableStreamDefaultReader(reader)) {
397 return false;
398 }
399 return true;
400}
401class ReadableStreamDefaultReader {
402 constructor(stream) {
403 if (IsReadableStream(stream) === false) {
404 throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance');
405 }
406 if (IsReadableStreamLocked(stream) === true) {
407 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
408 }
409 ReadableStreamReaderGenericInitialize(this, stream);
410 this._readRequests = new SimpleQueue();
411 }
412 get closed() {
413 if (!IsReadableStreamDefaultReader(this)) {
414 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
415 }
416 return this._closedPromise;
417 }
418 cancel(reason) {
419 if (!IsReadableStreamDefaultReader(this)) {
420 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
421 }
422 if (this._ownerReadableStream === undefined) {
423 return promiseRejectedWith(readerLockException('cancel'));
424 }
425 return ReadableStreamReaderGenericCancel(this, reason);
426 }
427 read() {
428 if (!IsReadableStreamDefaultReader(this)) {
429 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
430 }
431 if (this._ownerReadableStream === undefined) {
432 return promiseRejectedWith(readerLockException('read from'));
433 }
434 return ReadableStreamDefaultReaderRead(this);
435 }
436 releaseLock() {
437 if (!IsReadableStreamDefaultReader(this)) {
438 throw defaultReaderBrandCheckException('releaseLock');
439 }
440 if (this._ownerReadableStream === undefined) {
441 return;
442 }
443 if (this._readRequests.length > 0) {
444 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
445 }
446 ReadableStreamReaderGenericRelease(this);
447 }
448}
449// Abstract operations for the readers.
450function IsReadableStreamDefaultReader(x) {
451 if (!typeIsObject(x)) {
452 return false;
453 }
454 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
455 return false;
456 }
457 return true;
458}
459function ReadableStreamDefaultReaderRead(reader) {
460 const stream = reader._ownerReadableStream;
461 stream._disturbed = true;
462 if (stream._state === 'closed') {
463 return promiseResolvedWith(ReadableStreamCreateReadResult(undefined, true, reader._forAuthorCode));
464 }
465 if (stream._state === 'errored') {
466 return promiseRejectedWith(stream._storedError);
467 }
468 return stream._readableStreamController[PullSteps]();
469}
470// Helper functions for the ReadableStreamDefaultReader.
471function defaultReaderBrandCheckException(name) {
472 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
473}
474
475/// <reference lib="es2018.asynciterable" />
476let AsyncIteratorPrototype;
477if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
478 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
479 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
480 AsyncIteratorPrototype = {
481 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
482 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
483 [SymbolPolyfill.asyncIterator]() {
484 return this;
485 }
486 };
487 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
488}
489
490/// <reference lib="es2018.asynciterable" />
491const ReadableStreamAsyncIteratorPrototype = {
492 next() {
493 if (IsReadableStreamAsyncIterator(this) === false) {
494 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
495 }
496 const reader = this._asyncIteratorReader;
497 if (reader._ownerReadableStream === undefined) {
498 return promiseRejectedWith(readerLockException('iterate'));
499 }
500 return transformPromiseWith(ReadableStreamDefaultReaderRead(reader), result => {
501 const done = result.done;
502 if (done) {
503 ReadableStreamReaderGenericRelease(reader);
504 }
505 const value = result.value;
506 return ReadableStreamCreateReadResult(value, done, true);
507 });
508 },
509 return(value) {
510 if (IsReadableStreamAsyncIterator(this) === false) {
511 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
512 }
513 const reader = this._asyncIteratorReader;
514 if (reader._ownerReadableStream === undefined) {
515 return promiseRejectedWith(readerLockException('finish iterating'));
516 }
517 if (reader._readRequests.length > 0) {
518 return promiseRejectedWith(new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'));
519 }
520 if (this._preventCancel === false) {
521 const result = ReadableStreamReaderGenericCancel(reader, value);
522 ReadableStreamReaderGenericRelease(reader);
523 return transformPromiseWith(result, () => ReadableStreamCreateReadResult(value, true, true));
524 }
525 ReadableStreamReaderGenericRelease(reader);
526 return promiseResolvedWith(ReadableStreamCreateReadResult(value, true, true));
527 }
528};
529if (AsyncIteratorPrototype !== undefined) {
530 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
531}
532Object.defineProperty(ReadableStreamAsyncIteratorPrototype, 'next', { enumerable: false });
533Object.defineProperty(ReadableStreamAsyncIteratorPrototype, 'return', { enumerable: false });
534// Abstract operations for the ReadableStream.
535function AcquireReadableStreamAsyncIterator(stream, preventCancel = false) {
536 const reader = AcquireReadableStreamDefaultReader(stream);
537 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
538 iterator._asyncIteratorReader = reader;
539 iterator._preventCancel = Boolean(preventCancel);
540 return iterator;
541}
542function IsReadableStreamAsyncIterator(x) {
543 if (!typeIsObject(x)) {
544 return false;
545 }
546 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorReader')) {
547 return false;
548 }
549 return true;
550}
551// Helper functions for the ReadableStream.
552function streamAsyncIteratorBrandCheckException(name) {
553 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
554}
555
556function DequeueValue(container) {
557 const pair = container._queue.shift();
558 container._queueTotalSize -= pair.size;
559 if (container._queueTotalSize < 0) {
560 container._queueTotalSize = 0;
561 }
562 return pair.value;
563}
564function EnqueueValueWithSize(container, value, size) {
565 size = Number(size);
566 if (!IsFiniteNonNegativeNumber(size)) {
567 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
568 }
569 container._queue.push({ value, size });
570 container._queueTotalSize += size;
571}
572function PeekQueueValue(container) {
573 const pair = container._queue.peek();
574 return pair.value;
575}
576function ResetQueue(container) {
577 container._queue = new SimpleQueue();
578 container._queueTotalSize = 0;
579}
580
581const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
582const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
583class WritableStream {
584 constructor(underlyingSink = {}, strategy = {}) {
585 InitializeWritableStream(this);
586 const size = strategy.size;
587 let highWaterMark = strategy.highWaterMark;
588 const type = underlyingSink.type;
589 if (type !== undefined) {
590 throw new RangeError('Invalid type is specified');
591 }
592 const sizeAlgorithm = MakeSizeAlgorithmFromSizeFunction(size);
593 if (highWaterMark === undefined) {
594 highWaterMark = 1;
595 }
596 highWaterMark = ValidateAndNormalizeHighWaterMark(highWaterMark);
597 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
598 }
599 get locked() {
600 if (IsWritableStream(this) === false) {
601 throw streamBrandCheckException('locked');
602 }
603 return IsWritableStreamLocked(this);
604 }
605 abort(reason) {
606 if (IsWritableStream(this) === false) {
607 return promiseRejectedWith(streamBrandCheckException('abort'));
608 }
609 if (IsWritableStreamLocked(this) === true) {
610 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
611 }
612 return WritableStreamAbort(this, reason);
613 }
614 close() {
615 if (IsWritableStream(this) === false) {
616 return promiseRejectedWith(streamBrandCheckException('close'));
617 }
618 if (IsWritableStreamLocked(this) === true) {
619 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
620 }
621 if (WritableStreamCloseQueuedOrInFlight(this) === true) {
622 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
623 }
624 return WritableStreamClose(this);
625 }
626 getWriter() {
627 if (IsWritableStream(this) === false) {
628 throw streamBrandCheckException('getWriter');
629 }
630 return AcquireWritableStreamDefaultWriter(this);
631 }
632}
633// Abstract operations for the WritableStream.
634function AcquireWritableStreamDefaultWriter(stream) {
635 return new WritableStreamDefaultWriter(stream);
636}
637// Throws if and only if startAlgorithm throws.
638function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
639 const stream = Object.create(WritableStream.prototype);
640 InitializeWritableStream(stream);
641 const controller = Object.create(WritableStreamDefaultController.prototype);
642 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
643 return stream;
644}
645function InitializeWritableStream(stream) {
646 stream._state = 'writable';
647 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
648 // 'erroring' or 'errored'. May be set to an undefined value.
649 stream._storedError = undefined;
650 stream._writer = undefined;
651 // Initialize to undefined first because the constructor of the controller checks this
652 // variable to validate the caller.
653 stream._writableStreamController = undefined;
654 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
655 // producer without waiting for the queued writes to finish.
656 stream._writeRequests = new SimpleQueue();
657 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
658 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
659 stream._inFlightWriteRequest = undefined;
660 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
661 // has been detached.
662 stream._closeRequest = undefined;
663 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
664 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
665 stream._inFlightCloseRequest = undefined;
666 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
667 stream._pendingAbortRequest = undefined;
668 // The backpressure signal set by the controller.
669 stream._backpressure = false;
670}
671function IsWritableStream(x) {
672 if (!typeIsObject(x)) {
673 return false;
674 }
675 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
676 return false;
677 }
678 return true;
679}
680function IsWritableStreamLocked(stream) {
681 if (stream._writer === undefined) {
682 return false;
683 }
684 return true;
685}
686function WritableStreamAbort(stream, reason) {
687 const state = stream._state;
688 if (state === 'closed' || state === 'errored') {
689 return promiseResolvedWith(undefined);
690 }
691 if (stream._pendingAbortRequest !== undefined) {
692 return stream._pendingAbortRequest._promise;
693 }
694 let wasAlreadyErroring = false;
695 if (state === 'erroring') {
696 wasAlreadyErroring = true;
697 // reason will not be used, so don't keep a reference to it.
698 reason = undefined;
699 }
700 const promise = newPromise((resolve, reject) => {
701 stream._pendingAbortRequest = {
702 _promise: undefined,
703 _resolve: resolve,
704 _reject: reject,
705 _reason: reason,
706 _wasAlreadyErroring: wasAlreadyErroring
707 };
708 });
709 stream._pendingAbortRequest._promise = promise;
710 if (wasAlreadyErroring === false) {
711 WritableStreamStartErroring(stream, reason);
712 }
713 return promise;
714}
715function WritableStreamClose(stream) {
716 const state = stream._state;
717 if (state === 'closed' || state === 'errored') {
718 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
719 }
720 const promise = newPromise((resolve, reject) => {
721 const closeRequest = {
722 _resolve: resolve,
723 _reject: reject
724 };
725 stream._closeRequest = closeRequest;
726 });
727 const writer = stream._writer;
728 if (writer !== undefined && stream._backpressure === true && state === 'writable') {
729 defaultWriterReadyPromiseResolve(writer);
730 }
731 WritableStreamDefaultControllerClose(stream._writableStreamController);
732 return promise;
733}
734// WritableStream API exposed for controllers.
735function WritableStreamAddWriteRequest(stream) {
736 const promise = newPromise((resolve, reject) => {
737 const writeRequest = {
738 _resolve: resolve,
739 _reject: reject
740 };
741 stream._writeRequests.push(writeRequest);
742 });
743 return promise;
744}
745function WritableStreamDealWithRejection(stream, error) {
746 const state = stream._state;
747 if (state === 'writable') {
748 WritableStreamStartErroring(stream, error);
749 return;
750 }
751 WritableStreamFinishErroring(stream);
752}
753function WritableStreamStartErroring(stream, reason) {
754 const controller = stream._writableStreamController;
755 stream._state = 'erroring';
756 stream._storedError = reason;
757 const writer = stream._writer;
758 if (writer !== undefined) {
759 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
760 }
761 if (WritableStreamHasOperationMarkedInFlight(stream) === false && controller._started === true) {
762 WritableStreamFinishErroring(stream);
763 }
764}
765function WritableStreamFinishErroring(stream) {
766 stream._state = 'errored';
767 stream._writableStreamController[ErrorSteps]();
768 const storedError = stream._storedError;
769 stream._writeRequests.forEach(writeRequest => {
770 writeRequest._reject(storedError);
771 });
772 stream._writeRequests = new SimpleQueue();
773 if (stream._pendingAbortRequest === undefined) {
774 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
775 return;
776 }
777 const abortRequest = stream._pendingAbortRequest;
778 stream._pendingAbortRequest = undefined;
779 if (abortRequest._wasAlreadyErroring === true) {
780 abortRequest._reject(storedError);
781 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
782 return;
783 }
784 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
785 uponPromise(promise, () => {
786 abortRequest._resolve();
787 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
788 }, (reason) => {
789 abortRequest._reject(reason);
790 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
791 });
792}
793function WritableStreamFinishInFlightWrite(stream) {
794 stream._inFlightWriteRequest._resolve(undefined);
795 stream._inFlightWriteRequest = undefined;
796}
797function WritableStreamFinishInFlightWriteWithError(stream, error) {
798 stream._inFlightWriteRequest._reject(error);
799 stream._inFlightWriteRequest = undefined;
800 WritableStreamDealWithRejection(stream, error);
801}
802function WritableStreamFinishInFlightClose(stream) {
803 stream._inFlightCloseRequest._resolve(undefined);
804 stream._inFlightCloseRequest = undefined;
805 const state = stream._state;
806 if (state === 'erroring') {
807 // The error was too late to do anything, so it is ignored.
808 stream._storedError = undefined;
809 if (stream._pendingAbortRequest !== undefined) {
810 stream._pendingAbortRequest._resolve();
811 stream._pendingAbortRequest = undefined;
812 }
813 }
814 stream._state = 'closed';
815 const writer = stream._writer;
816 if (writer !== undefined) {
817 defaultWriterClosedPromiseResolve(writer);
818 }
819}
820function WritableStreamFinishInFlightCloseWithError(stream, error) {
821 stream._inFlightCloseRequest._reject(error);
822 stream._inFlightCloseRequest = undefined;
823 // Never execute sink abort() after sink close().
824 if (stream._pendingAbortRequest !== undefined) {
825 stream._pendingAbortRequest._reject(error);
826 stream._pendingAbortRequest = undefined;
827 }
828 WritableStreamDealWithRejection(stream, error);
829}
830// TODO(ricea): Fix alphabetical order.
831function WritableStreamCloseQueuedOrInFlight(stream) {
832 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
833 return false;
834 }
835 return true;
836}
837function WritableStreamHasOperationMarkedInFlight(stream) {
838 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
839 return false;
840 }
841 return true;
842}
843function WritableStreamMarkCloseRequestInFlight(stream) {
844 stream._inFlightCloseRequest = stream._closeRequest;
845 stream._closeRequest = undefined;
846}
847function WritableStreamMarkFirstWriteRequestInFlight(stream) {
848 stream._inFlightWriteRequest = stream._writeRequests.shift();
849}
850function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
851 if (stream._closeRequest !== undefined) {
852 stream._closeRequest._reject(stream._storedError);
853 stream._closeRequest = undefined;
854 }
855 const writer = stream._writer;
856 if (writer !== undefined) {
857 defaultWriterClosedPromiseReject(writer, stream._storedError);
858 }
859}
860function WritableStreamUpdateBackpressure(stream, backpressure) {
861 const writer = stream._writer;
862 if (writer !== undefined && backpressure !== stream._backpressure) {
863 if (backpressure === true) {
864 defaultWriterReadyPromiseReset(writer);
865 }
866 else {
867 defaultWriterReadyPromiseResolve(writer);
868 }
869 }
870 stream._backpressure = backpressure;
871}
872class WritableStreamDefaultWriter {
873 constructor(stream) {
874 if (IsWritableStream(stream) === false) {
875 throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance');
876 }
877 if (IsWritableStreamLocked(stream) === true) {
878 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
879 }
880 this._ownerWritableStream = stream;
881 stream._writer = this;
882 const state = stream._state;
883 if (state === 'writable') {
884 if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._backpressure === true) {
885 defaultWriterReadyPromiseInitialize(this);
886 }
887 else {
888 defaultWriterReadyPromiseInitializeAsResolved(this);
889 }
890 defaultWriterClosedPromiseInitialize(this);
891 }
892 else if (state === 'erroring') {
893 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
894 defaultWriterClosedPromiseInitialize(this);
895 }
896 else if (state === 'closed') {
897 defaultWriterReadyPromiseInitializeAsResolved(this);
898 defaultWriterClosedPromiseInitializeAsResolved(this);
899 }
900 else {
901 const storedError = stream._storedError;
902 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
903 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
904 }
905 }
906 get closed() {
907 if (IsWritableStreamDefaultWriter(this) === false) {
908 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
909 }
910 return this._closedPromise;
911 }
912 get desiredSize() {
913 if (IsWritableStreamDefaultWriter(this) === false) {
914 throw defaultWriterBrandCheckException('desiredSize');
915 }
916 if (this._ownerWritableStream === undefined) {
917 throw defaultWriterLockException('desiredSize');
918 }
919 return WritableStreamDefaultWriterGetDesiredSize(this);
920 }
921 get ready() {
922 if (IsWritableStreamDefaultWriter(this) === false) {
923 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
924 }
925 return this._readyPromise;
926 }
927 abort(reason) {
928 if (IsWritableStreamDefaultWriter(this) === false) {
929 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
930 }
931 if (this._ownerWritableStream === undefined) {
932 return promiseRejectedWith(defaultWriterLockException('abort'));
933 }
934 return WritableStreamDefaultWriterAbort(this, reason);
935 }
936 close() {
937 if (IsWritableStreamDefaultWriter(this) === false) {
938 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
939 }
940 const stream = this._ownerWritableStream;
941 if (stream === undefined) {
942 return promiseRejectedWith(defaultWriterLockException('close'));
943 }
944 if (WritableStreamCloseQueuedOrInFlight(stream) === true) {
945 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
946 }
947 return WritableStreamDefaultWriterClose(this);
948 }
949 releaseLock() {
950 if (IsWritableStreamDefaultWriter(this) === false) {
951 throw defaultWriterBrandCheckException('releaseLock');
952 }
953 const stream = this._ownerWritableStream;
954 if (stream === undefined) {
955 return;
956 }
957 WritableStreamDefaultWriterRelease(this);
958 }
959 write(chunk) {
960 if (IsWritableStreamDefaultWriter(this) === false) {
961 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
962 }
963 if (this._ownerWritableStream === undefined) {
964 return promiseRejectedWith(defaultWriterLockException('write to'));
965 }
966 return WritableStreamDefaultWriterWrite(this, chunk);
967 }
968}
969// Abstract operations for the WritableStreamDefaultWriter.
970function IsWritableStreamDefaultWriter(x) {
971 if (!typeIsObject(x)) {
972 return false;
973 }
974 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
975 return false;
976 }
977 return true;
978}
979// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
980function WritableStreamDefaultWriterAbort(writer, reason) {
981 const stream = writer._ownerWritableStream;
982 return WritableStreamAbort(stream, reason);
983}
984function WritableStreamDefaultWriterClose(writer) {
985 const stream = writer._ownerWritableStream;
986 return WritableStreamClose(stream);
987}
988function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
989 const stream = writer._ownerWritableStream;
990 const state = stream._state;
991 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {
992 return promiseResolvedWith(undefined);
993 }
994 if (state === 'errored') {
995 return promiseRejectedWith(stream._storedError);
996 }
997 return WritableStreamDefaultWriterClose(writer);
998}
999function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
1000 if (writer._closedPromiseState === 'pending') {
1001 defaultWriterClosedPromiseReject(writer, error);
1002 }
1003 else {
1004 defaultWriterClosedPromiseResetToRejected(writer, error);
1005 }
1006}
1007function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
1008 if (writer._readyPromiseState === 'pending') {
1009 defaultWriterReadyPromiseReject(writer, error);
1010 }
1011 else {
1012 defaultWriterReadyPromiseResetToRejected(writer, error);
1013 }
1014}
1015function WritableStreamDefaultWriterGetDesiredSize(writer) {
1016 const stream = writer._ownerWritableStream;
1017 const state = stream._state;
1018 if (state === 'errored' || state === 'erroring') {
1019 return null;
1020 }
1021 if (state === 'closed') {
1022 return 0;
1023 }
1024 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
1025}
1026function WritableStreamDefaultWriterRelease(writer) {
1027 const stream = writer._ownerWritableStream;
1028 const releasedError = new TypeError('Writer was released and can no longer be used to monitor the stream\'s closedness');
1029 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
1030 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
1031 // rejected until afterwards. This means that simply testing state will not work.
1032 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
1033 stream._writer = undefined;
1034 writer._ownerWritableStream = undefined;
1035}
1036function WritableStreamDefaultWriterWrite(writer, chunk) {
1037 const stream = writer._ownerWritableStream;
1038 const controller = stream._writableStreamController;
1039 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
1040 if (stream !== writer._ownerWritableStream) {
1041 return promiseRejectedWith(defaultWriterLockException('write to'));
1042 }
1043 const state = stream._state;
1044 if (state === 'errored') {
1045 return promiseRejectedWith(stream._storedError);
1046 }
1047 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {
1048 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
1049 }
1050 if (state === 'erroring') {
1051 return promiseRejectedWith(stream._storedError);
1052 }
1053 const promise = WritableStreamAddWriteRequest(stream);
1054 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
1055 return promise;
1056}
1057class WritableStreamDefaultController {
1058 /** @internal */
1059 constructor() {
1060 throw new TypeError('WritableStreamDefaultController cannot be constructed explicitly');
1061 }
1062 error(e) {
1063 if (IsWritableStreamDefaultController(this) === false) {
1064 throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
1065 }
1066 const state = this._controlledWritableStream._state;
1067 if (state !== 'writable') {
1068 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
1069 // just treat it as a no-op.
1070 return;
1071 }
1072 WritableStreamDefaultControllerError(this, e);
1073 }
1074 /** @internal */
1075 [AbortSteps](reason) {
1076 const result = this._abortAlgorithm(reason);
1077 WritableStreamDefaultControllerClearAlgorithms(this);
1078 return result;
1079 }
1080 /** @internal */
1081 [ErrorSteps]() {
1082 ResetQueue(this);
1083 }
1084}
1085// Abstract operations implementing interface required by the WritableStream.
1086function IsWritableStreamDefaultController(x) {
1087 if (!typeIsObject(x)) {
1088 return false;
1089 }
1090 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
1091 return false;
1092 }
1093 return true;
1094}
1095function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
1096 controller._controlledWritableStream = stream;
1097 stream._writableStreamController = controller;
1098 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
1099 controller._queue = undefined;
1100 controller._queueTotalSize = undefined;
1101 ResetQueue(controller);
1102 controller._started = false;
1103 controller._strategySizeAlgorithm = sizeAlgorithm;
1104 controller._strategyHWM = highWaterMark;
1105 controller._writeAlgorithm = writeAlgorithm;
1106 controller._closeAlgorithm = closeAlgorithm;
1107 controller._abortAlgorithm = abortAlgorithm;
1108 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
1109 WritableStreamUpdateBackpressure(stream, backpressure);
1110 const startResult = startAlgorithm();
1111 const startPromise = promiseResolvedWith(startResult);
1112 uponPromise(startPromise, () => {
1113 controller._started = true;
1114 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1115 }, r => {
1116 controller._started = true;
1117 WritableStreamDealWithRejection(stream, r);
1118 });
1119}
1120function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
1121 const controller = Object.create(WritableStreamDefaultController.prototype);
1122 function startAlgorithm() {
1123 return InvokeOrNoop(underlyingSink, 'start', [controller]);
1124 }
1125 const writeAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingSink, 'write', 1, [controller]);
1126 const closeAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingSink, 'close', 0, []);
1127 const abortAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingSink, 'abort', 1, []);
1128 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
1129}
1130// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
1131function WritableStreamDefaultControllerClearAlgorithms(controller) {
1132 controller._writeAlgorithm = undefined;
1133 controller._closeAlgorithm = undefined;
1134 controller._abortAlgorithm = undefined;
1135 controller._strategySizeAlgorithm = undefined;
1136}
1137function WritableStreamDefaultControllerClose(controller) {
1138 EnqueueValueWithSize(controller, 'close', 0);
1139 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1140}
1141function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
1142 try {
1143 return controller._strategySizeAlgorithm(chunk);
1144 }
1145 catch (chunkSizeE) {
1146 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
1147 return 1;
1148 }
1149}
1150function WritableStreamDefaultControllerGetDesiredSize(controller) {
1151 return controller._strategyHWM - controller._queueTotalSize;
1152}
1153function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
1154 const writeRecord = { chunk };
1155 try {
1156 EnqueueValueWithSize(controller, writeRecord, chunkSize);
1157 }
1158 catch (enqueueE) {
1159 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
1160 return;
1161 }
1162 const stream = controller._controlledWritableStream;
1163 if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') {
1164 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
1165 WritableStreamUpdateBackpressure(stream, backpressure);
1166 }
1167 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1168}
1169// Abstract operations for the WritableStreamDefaultController.
1170function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
1171 const stream = controller._controlledWritableStream;
1172 if (controller._started === false) {
1173 return;
1174 }
1175 if (stream._inFlightWriteRequest !== undefined) {
1176 return;
1177 }
1178 const state = stream._state;
1179 if (state === 'erroring') {
1180 WritableStreamFinishErroring(stream);
1181 return;
1182 }
1183 if (controller._queue.length === 0) {
1184 return;
1185 }
1186 const writeRecord = PeekQueueValue(controller);
1187 if (writeRecord === 'close') {
1188 WritableStreamDefaultControllerProcessClose(controller);
1189 }
1190 else {
1191 WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);
1192 }
1193}
1194function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
1195 if (controller._controlledWritableStream._state === 'writable') {
1196 WritableStreamDefaultControllerError(controller, error);
1197 }
1198}
1199function WritableStreamDefaultControllerProcessClose(controller) {
1200 const stream = controller._controlledWritableStream;
1201 WritableStreamMarkCloseRequestInFlight(stream);
1202 DequeueValue(controller);
1203 const sinkClosePromise = controller._closeAlgorithm();
1204 WritableStreamDefaultControllerClearAlgorithms(controller);
1205 uponPromise(sinkClosePromise, () => {
1206 WritableStreamFinishInFlightClose(stream);
1207 }, reason => {
1208 WritableStreamFinishInFlightCloseWithError(stream, reason);
1209 });
1210}
1211function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
1212 const stream = controller._controlledWritableStream;
1213 WritableStreamMarkFirstWriteRequestInFlight(stream);
1214 const sinkWritePromise = controller._writeAlgorithm(chunk);
1215 uponPromise(sinkWritePromise, () => {
1216 WritableStreamFinishInFlightWrite(stream);
1217 const state = stream._state;
1218 DequeueValue(controller);
1219 if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') {
1220 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
1221 WritableStreamUpdateBackpressure(stream, backpressure);
1222 }
1223 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1224 }, reason => {
1225 if (stream._state === 'writable') {
1226 WritableStreamDefaultControllerClearAlgorithms(controller);
1227 }
1228 WritableStreamFinishInFlightWriteWithError(stream, reason);
1229 });
1230}
1231function WritableStreamDefaultControllerGetBackpressure(controller) {
1232 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
1233 return desiredSize <= 0;
1234}
1235// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
1236function WritableStreamDefaultControllerError(controller, error) {
1237 const stream = controller._controlledWritableStream;
1238 WritableStreamDefaultControllerClearAlgorithms(controller);
1239 WritableStreamStartErroring(stream, error);
1240}
1241// Helper functions for the WritableStream.
1242function streamBrandCheckException(name) {
1243 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
1244}
1245// Helper functions for the WritableStreamDefaultWriter.
1246function defaultWriterBrandCheckException(name) {
1247 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
1248}
1249function defaultWriterLockException(name) {
1250 return new TypeError('Cannot ' + name + ' a stream using a released writer');
1251}
1252function defaultWriterClosedPromiseInitialize(writer) {
1253 writer._closedPromise = newPromise((resolve, reject) => {
1254 writer._closedPromise_resolve = resolve;
1255 writer._closedPromise_reject = reject;
1256 writer._closedPromiseState = 'pending';
1257 });
1258}
1259function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
1260 defaultWriterClosedPromiseInitialize(writer);
1261 defaultWriterClosedPromiseReject(writer, reason);
1262}
1263function defaultWriterClosedPromiseInitializeAsResolved(writer) {
1264 defaultWriterClosedPromiseInitialize(writer);
1265 defaultWriterClosedPromiseResolve(writer);
1266}
1267function defaultWriterClosedPromiseReject(writer, reason) {
1268 setPromiseIsHandledToTrue(writer._closedPromise);
1269 writer._closedPromise_reject(reason);
1270 writer._closedPromise_resolve = undefined;
1271 writer._closedPromise_reject = undefined;
1272 writer._closedPromiseState = 'rejected';
1273}
1274function defaultWriterClosedPromiseResetToRejected(writer, reason) {
1275 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
1276}
1277function defaultWriterClosedPromiseResolve(writer) {
1278 writer._closedPromise_resolve(undefined);
1279 writer._closedPromise_resolve = undefined;
1280 writer._closedPromise_reject = undefined;
1281 writer._closedPromiseState = 'resolved';
1282}
1283function defaultWriterReadyPromiseInitialize(writer) {
1284 writer._readyPromise = newPromise((resolve, reject) => {
1285 writer._readyPromise_resolve = resolve;
1286 writer._readyPromise_reject = reject;
1287 });
1288 writer._readyPromiseState = 'pending';
1289}
1290function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
1291 defaultWriterReadyPromiseInitialize(writer);
1292 defaultWriterReadyPromiseReject(writer, reason);
1293}
1294function defaultWriterReadyPromiseInitializeAsResolved(writer) {
1295 defaultWriterReadyPromiseInitialize(writer);
1296 defaultWriterReadyPromiseResolve(writer);
1297}
1298function defaultWriterReadyPromiseReject(writer, reason) {
1299 setPromiseIsHandledToTrue(writer._readyPromise);
1300 writer._readyPromise_reject(reason);
1301 writer._readyPromise_resolve = undefined;
1302 writer._readyPromise_reject = undefined;
1303 writer._readyPromiseState = 'rejected';
1304}
1305function defaultWriterReadyPromiseReset(writer) {
1306 defaultWriterReadyPromiseInitialize(writer);
1307}
1308function defaultWriterReadyPromiseResetToRejected(writer, reason) {
1309 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
1310}
1311function defaultWriterReadyPromiseResolve(writer) {
1312 writer._readyPromise_resolve(undefined);
1313 writer._readyPromise_resolve = undefined;
1314 writer._readyPromise_reject = undefined;
1315 writer._readyPromiseState = 'fulfilled';
1316}
1317
1318function isAbortSignal(value) {
1319 if (typeof value !== 'object' || value === null) {
1320 return false;
1321 }
1322 try {
1323 return typeof value.aborted === 'boolean';
1324 }
1325 catch (_a) {
1326 // AbortSignal.prototype.aborted throws if its brand check fails
1327 return false;
1328 }
1329}
1330
1331/// <reference lib="dom" />
1332const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
1333
1334/// <reference types="node" />
1335function isDOMExceptionConstructor(ctor) {
1336 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
1337 return false;
1338 }
1339 try {
1340 new ctor();
1341 return true;
1342 }
1343 catch (_a) {
1344 return false;
1345 }
1346}
1347function createDOMExceptionPolyfill() {
1348 const ctor = function DOMException(message, name) {
1349 this.message = message || '';
1350 this.name = name || 'Error';
1351 if (Error.captureStackTrace) {
1352 Error.captureStackTrace(this, this.constructor);
1353 }
1354 };
1355 ctor.prototype = Object.create(Error.prototype);
1356 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
1357 return ctor;
1358}
1359const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
1360
1361function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
1362 const reader = AcquireReadableStreamDefaultReader(source);
1363 const writer = AcquireWritableStreamDefaultWriter(dest);
1364 source._disturbed = true;
1365 let shuttingDown = false;
1366 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
1367 let currentWrite = promiseResolvedWith(undefined);
1368 return newPromise((resolve, reject) => {
1369 let abortAlgorithm;
1370 if (signal !== undefined) {
1371 abortAlgorithm = () => {
1372 const error = new DOMException$1('Aborted', 'AbortError');
1373 const actions = [];
1374 if (preventAbort === false) {
1375 actions.push(() => {
1376 if (dest._state === 'writable') {
1377 return WritableStreamAbort(dest, error);
1378 }
1379 return promiseResolvedWith(undefined);
1380 });
1381 }
1382 if (preventCancel === false) {
1383 actions.push(() => {
1384 if (source._state === 'readable') {
1385 return ReadableStreamCancel(source, error);
1386 }
1387 return promiseResolvedWith(undefined);
1388 });
1389 }
1390 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
1391 };
1392 if (signal.aborted === true) {
1393 abortAlgorithm();
1394 return;
1395 }
1396 signal.addEventListener('abort', abortAlgorithm);
1397 }
1398 // Using reader and writer, read all chunks from this and write them to dest
1399 // - Backpressure must be enforced
1400 // - Shutdown must stop all activity
1401 function pipeLoop() {
1402 return newPromise((resolveLoop, rejectLoop) => {
1403 function next(done) {
1404 if (done) {
1405 resolveLoop();
1406 }
1407 else {
1408 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
1409 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
1410 PerformPromiseThen(pipeStep(), next, rejectLoop);
1411 }
1412 }
1413 next(false);
1414 });
1415 }
1416 function pipeStep() {
1417 if (shuttingDown === true) {
1418 return promiseResolvedWith(true);
1419 }
1420 return PerformPromiseThen(writer._readyPromise, () => {
1421 return PerformPromiseThen(ReadableStreamDefaultReaderRead(reader), result => {
1422 if (result.done === true) {
1423 return true;
1424 }
1425 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, result.value), undefined, noop);
1426 return false;
1427 });
1428 });
1429 }
1430 // Errors must be propagated forward
1431 isOrBecomesErrored(source, reader._closedPromise, storedError => {
1432 if (preventAbort === false) {
1433 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
1434 }
1435 else {
1436 shutdown(true, storedError);
1437 }
1438 });
1439 // Errors must be propagated backward
1440 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
1441 if (preventCancel === false) {
1442 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
1443 }
1444 else {
1445 shutdown(true, storedError);
1446 }
1447 });
1448 // Closing must be propagated forward
1449 isOrBecomesClosed(source, reader._closedPromise, () => {
1450 if (preventClose === false) {
1451 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
1452 }
1453 else {
1454 shutdown();
1455 }
1456 });
1457 // Closing must be propagated backward
1458 if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') {
1459 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
1460 if (preventCancel === false) {
1461 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
1462 }
1463 else {
1464 shutdown(true, destClosed);
1465 }
1466 }
1467 setPromiseIsHandledToTrue(pipeLoop());
1468 function waitForWritesToFinish() {
1469 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
1470 // for that too.
1471 const oldCurrentWrite = currentWrite;
1472 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
1473 }
1474 function isOrBecomesErrored(stream, promise, action) {
1475 if (stream._state === 'errored') {
1476 action(stream._storedError);
1477 }
1478 else {
1479 uponRejection(promise, action);
1480 }
1481 }
1482 function isOrBecomesClosed(stream, promise, action) {
1483 if (stream._state === 'closed') {
1484 action();
1485 }
1486 else {
1487 uponFulfillment(promise, action);
1488 }
1489 }
1490 function shutdownWithAction(action, originalIsError, originalError) {
1491 if (shuttingDown === true) {
1492 return;
1493 }
1494 shuttingDown = true;
1495 if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
1496 uponFulfillment(waitForWritesToFinish(), doTheRest);
1497 }
1498 else {
1499 doTheRest();
1500 }
1501 function doTheRest() {
1502 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
1503 }
1504 }
1505 function shutdown(isError, error) {
1506 if (shuttingDown === true) {
1507 return;
1508 }
1509 shuttingDown = true;
1510 if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
1511 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
1512 }
1513 else {
1514 finalize(isError, error);
1515 }
1516 }
1517 function finalize(isError, error) {
1518 WritableStreamDefaultWriterRelease(writer);
1519 ReadableStreamReaderGenericRelease(reader);
1520 if (signal !== undefined) {
1521 signal.removeEventListener('abort', abortAlgorithm);
1522 }
1523 if (isError) {
1524 reject(error);
1525 }
1526 else {
1527 resolve(undefined);
1528 }
1529 }
1530 });
1531}
1532
1533class ReadableStreamDefaultController {
1534 /** @internal */
1535 constructor() {
1536 throw new TypeError();
1537 }
1538 get desiredSize() {
1539 if (IsReadableStreamDefaultController(this) === false) {
1540 throw defaultControllerBrandCheckException('desiredSize');
1541 }
1542 return ReadableStreamDefaultControllerGetDesiredSize(this);
1543 }
1544 close() {
1545 if (IsReadableStreamDefaultController(this) === false) {
1546 throw defaultControllerBrandCheckException('close');
1547 }
1548 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(this) === false) {
1549 throw new TypeError('The stream is not in a state that permits close');
1550 }
1551 ReadableStreamDefaultControllerClose(this);
1552 }
1553 enqueue(chunk) {
1554 if (IsReadableStreamDefaultController(this) === false) {
1555 throw defaultControllerBrandCheckException('enqueue');
1556 }
1557 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(this) === false) {
1558 throw new TypeError('The stream is not in a state that permits enqueue');
1559 }
1560 return ReadableStreamDefaultControllerEnqueue(this, chunk);
1561 }
1562 error(e) {
1563 if (IsReadableStreamDefaultController(this) === false) {
1564 throw defaultControllerBrandCheckException('error');
1565 }
1566 ReadableStreamDefaultControllerError(this, e);
1567 }
1568 /** @internal */
1569 [CancelSteps](reason) {
1570 ResetQueue(this);
1571 const result = this._cancelAlgorithm(reason);
1572 ReadableStreamDefaultControllerClearAlgorithms(this);
1573 return result;
1574 }
1575 /** @internal */
1576 [PullSteps]() {
1577 const stream = this._controlledReadableStream;
1578 if (this._queue.length > 0) {
1579 const chunk = DequeueValue(this);
1580 if (this._closeRequested === true && this._queue.length === 0) {
1581 ReadableStreamDefaultControllerClearAlgorithms(this);
1582 ReadableStreamClose(stream);
1583 }
1584 else {
1585 ReadableStreamDefaultControllerCallPullIfNeeded(this);
1586 }
1587 return promiseResolvedWith(ReadableStreamCreateReadResult(chunk, false, stream._reader._forAuthorCode));
1588 }
1589 const pendingPromise = ReadableStreamAddReadRequest(stream);
1590 ReadableStreamDefaultControllerCallPullIfNeeded(this);
1591 return pendingPromise;
1592 }
1593}
1594// Abstract operations for the ReadableStreamDefaultController.
1595function IsReadableStreamDefaultController(x) {
1596 if (!typeIsObject(x)) {
1597 return false;
1598 }
1599 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
1600 return false;
1601 }
1602 return true;
1603}
1604function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
1605 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
1606 if (shouldPull === false) {
1607 return;
1608 }
1609 if (controller._pulling === true) {
1610 controller._pullAgain = true;
1611 return;
1612 }
1613 controller._pulling = true;
1614 const pullPromise = controller._pullAlgorithm();
1615 uponPromise(pullPromise, () => {
1616 controller._pulling = false;
1617 if (controller._pullAgain === true) {
1618 controller._pullAgain = false;
1619 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
1620 }
1621 }, e => {
1622 ReadableStreamDefaultControllerError(controller, e);
1623 });
1624}
1625function ReadableStreamDefaultControllerShouldCallPull(controller) {
1626 const stream = controller._controlledReadableStream;
1627 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) === false) {
1628 return false;
1629 }
1630 if (controller._started === false) {
1631 return false;
1632 }
1633 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
1634 return true;
1635 }
1636 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
1637 if (desiredSize > 0) {
1638 return true;
1639 }
1640 return false;
1641}
1642function ReadableStreamDefaultControllerClearAlgorithms(controller) {
1643 controller._pullAlgorithm = undefined;
1644 controller._cancelAlgorithm = undefined;
1645 controller._strategySizeAlgorithm = undefined;
1646}
1647// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
1648function ReadableStreamDefaultControllerClose(controller) {
1649 const stream = controller._controlledReadableStream;
1650 controller._closeRequested = true;
1651 if (controller._queue.length === 0) {
1652 ReadableStreamDefaultControllerClearAlgorithms(controller);
1653 ReadableStreamClose(stream);
1654 }
1655}
1656function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
1657 const stream = controller._controlledReadableStream;
1658 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
1659 ReadableStreamFulfillReadRequest(stream, chunk, false);
1660 }
1661 else {
1662 let chunkSize;
1663 try {
1664 chunkSize = controller._strategySizeAlgorithm(chunk);
1665 }
1666 catch (chunkSizeE) {
1667 ReadableStreamDefaultControllerError(controller, chunkSizeE);
1668 throw chunkSizeE;
1669 }
1670 try {
1671 EnqueueValueWithSize(controller, chunk, chunkSize);
1672 }
1673 catch (enqueueE) {
1674 ReadableStreamDefaultControllerError(controller, enqueueE);
1675 throw enqueueE;
1676 }
1677 }
1678 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
1679}
1680function ReadableStreamDefaultControllerError(controller, e) {
1681 const stream = controller._controlledReadableStream;
1682 if (stream._state !== 'readable') {
1683 return;
1684 }
1685 ResetQueue(controller);
1686 ReadableStreamDefaultControllerClearAlgorithms(controller);
1687 ReadableStreamError(stream, e);
1688}
1689function ReadableStreamDefaultControllerGetDesiredSize(controller) {
1690 const stream = controller._controlledReadableStream;
1691 const state = stream._state;
1692 if (state === 'errored') {
1693 return null;
1694 }
1695 if (state === 'closed') {
1696 return 0;
1697 }
1698 return controller._strategyHWM - controller._queueTotalSize;
1699}
1700// This is used in the implementation of TransformStream.
1701function ReadableStreamDefaultControllerHasBackpressure(controller) {
1702 if (ReadableStreamDefaultControllerShouldCallPull(controller) === true) {
1703 return false;
1704 }
1705 return true;
1706}
1707function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
1708 const state = controller._controlledReadableStream._state;
1709 if (controller._closeRequested === false && state === 'readable') {
1710 return true;
1711 }
1712 return false;
1713}
1714function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
1715 controller._controlledReadableStream = stream;
1716 controller._queue = undefined;
1717 controller._queueTotalSize = undefined;
1718 ResetQueue(controller);
1719 controller._started = false;
1720 controller._closeRequested = false;
1721 controller._pullAgain = false;
1722 controller._pulling = false;
1723 controller._strategySizeAlgorithm = sizeAlgorithm;
1724 controller._strategyHWM = highWaterMark;
1725 controller._pullAlgorithm = pullAlgorithm;
1726 controller._cancelAlgorithm = cancelAlgorithm;
1727 stream._readableStreamController = controller;
1728 const startResult = startAlgorithm();
1729 uponPromise(promiseResolvedWith(startResult), () => {
1730 controller._started = true;
1731 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
1732 }, r => {
1733 ReadableStreamDefaultControllerError(controller, r);
1734 });
1735}
1736function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
1737 const controller = Object.create(ReadableStreamDefaultController.prototype);
1738 function startAlgorithm() {
1739 return InvokeOrNoop(underlyingSource, 'start', [controller]);
1740 }
1741 const pullAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingSource, 'pull', 0, [controller]);
1742 const cancelAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingSource, 'cancel', 1, []);
1743 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
1744}
1745// Helper functions for the ReadableStreamDefaultController.
1746function defaultControllerBrandCheckException(name) {
1747 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
1748}
1749
1750function ReadableStreamTee(stream, cloneForBranch2) {
1751 const reader = AcquireReadableStreamDefaultReader(stream);
1752 let reading = false;
1753 let canceled1 = false;
1754 let canceled2 = false;
1755 let reason1;
1756 let reason2;
1757 let branch1;
1758 let branch2;
1759 let resolveCancelPromise;
1760 const cancelPromise = newPromise(resolve => {
1761 resolveCancelPromise = resolve;
1762 });
1763 function pullAlgorithm() {
1764 if (reading === true) {
1765 return promiseResolvedWith(undefined);
1766 }
1767 reading = true;
1768 const readPromise = transformPromiseWith(ReadableStreamDefaultReaderRead(reader), result => {
1769 reading = false;
1770 const done = result.done;
1771 if (done === true) {
1772 if (canceled1 === false) {
1773 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
1774 }
1775 if (canceled2 === false) {
1776 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
1777 }
1778 return;
1779 }
1780 const value = result.value;
1781 const value1 = value;
1782 const value2 = value;
1783 // There is no way to access the cloning code right now in the reference implementation.
1784 // If we add one then we'll need an implementation for serializable objects.
1785 // if (canceled2 === false && cloneForBranch2 === true) {
1786 // value2 = StructuredDeserialize(StructuredSerialize(value2));
1787 // }
1788 if (canceled1 === false) {
1789 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
1790 }
1791 if (canceled2 === false) {
1792 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
1793 }
1794 });
1795 setPromiseIsHandledToTrue(readPromise);
1796 return promiseResolvedWith(undefined);
1797 }
1798 function cancel1Algorithm(reason) {
1799 canceled1 = true;
1800 reason1 = reason;
1801 if (canceled2 === true) {
1802 const compositeReason = createArrayFromList([reason1, reason2]);
1803 const cancelResult = ReadableStreamCancel(stream, compositeReason);
1804 resolveCancelPromise(cancelResult);
1805 }
1806 return cancelPromise;
1807 }
1808 function cancel2Algorithm(reason) {
1809 canceled2 = true;
1810 reason2 = reason;
1811 if (canceled1 === true) {
1812 const compositeReason = createArrayFromList([reason1, reason2]);
1813 const cancelResult = ReadableStreamCancel(stream, compositeReason);
1814 resolveCancelPromise(cancelResult);
1815 }
1816 return cancelPromise;
1817 }
1818 function startAlgorithm() { }
1819 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
1820 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
1821 uponRejection(reader._closedPromise, (r) => {
1822 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
1823 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
1824 });
1825 return [branch1, branch2];
1826}
1827
1828/// <reference lib="es2015.core" />
1829// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Polyfill
1830const NumberIsInteger = Number.isInteger || function (value) {
1831 return typeof value === 'number' &&
1832 isFinite(value) &&
1833 Math.floor(value) === value;
1834};
1835
1836class ReadableStreamBYOBRequest {
1837 /** @internal */
1838 constructor() {
1839 throw new TypeError('ReadableStreamBYOBRequest cannot be used directly');
1840 }
1841 get view() {
1842 if (IsReadableStreamBYOBRequest(this) === false) {
1843 throw byobRequestBrandCheckException('view');
1844 }
1845 return this._view;
1846 }
1847 respond(bytesWritten) {
1848 if (IsReadableStreamBYOBRequest(this) === false) {
1849 throw byobRequestBrandCheckException('respond');
1850 }
1851 if (this._associatedReadableByteStreamController === undefined) {
1852 throw new TypeError('This BYOB request has been invalidated');
1853 }
1854 if (IsDetachedBuffer(this._view.buffer) === true) ;
1855 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
1856 }
1857 respondWithNewView(view) {
1858 if (IsReadableStreamBYOBRequest(this) === false) {
1859 throw byobRequestBrandCheckException('respond');
1860 }
1861 if (this._associatedReadableByteStreamController === undefined) {
1862 throw new TypeError('This BYOB request has been invalidated');
1863 }
1864 if (!ArrayBuffer.isView(view)) {
1865 throw new TypeError('You can only respond with array buffer views');
1866 }
1867 if (IsDetachedBuffer(view.buffer) === true) ;
1868 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
1869 }
1870}
1871class ReadableByteStreamController {
1872 /** @internal */
1873 constructor() {
1874 throw new TypeError('ReadableByteStreamController constructor cannot be used directly');
1875 }
1876 get byobRequest() {
1877 if (IsReadableByteStreamController(this) === false) {
1878 throw byteStreamControllerBrandCheckException('byobRequest');
1879 }
1880 if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {
1881 const firstDescriptor = this._pendingPullIntos.peek();
1882 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
1883 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
1884 SetUpReadableStreamBYOBRequest(byobRequest, this, view);
1885 this._byobRequest = byobRequest;
1886 }
1887 return this._byobRequest;
1888 }
1889 get desiredSize() {
1890 if (IsReadableByteStreamController(this) === false) {
1891 throw byteStreamControllerBrandCheckException('desiredSize');
1892 }
1893 return ReadableByteStreamControllerGetDesiredSize(this);
1894 }
1895 close() {
1896 if (IsReadableByteStreamController(this) === false) {
1897 throw byteStreamControllerBrandCheckException('close');
1898 }
1899 if (this._closeRequested === true) {
1900 throw new TypeError('The stream has already been closed; do not close it again!');
1901 }
1902 const state = this._controlledReadableByteStream._state;
1903 if (state !== 'readable') {
1904 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
1905 }
1906 ReadableByteStreamControllerClose(this);
1907 }
1908 enqueue(chunk) {
1909 if (IsReadableByteStreamController(this) === false) {
1910 throw byteStreamControllerBrandCheckException('enqueue');
1911 }
1912 if (this._closeRequested === true) {
1913 throw new TypeError('stream is closed or draining');
1914 }
1915 const state = this._controlledReadableByteStream._state;
1916 if (state !== 'readable') {
1917 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
1918 }
1919 if (!ArrayBuffer.isView(chunk)) {
1920 throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');
1921 }
1922 if (IsDetachedBuffer(chunk.buffer) === true) ;
1923 ReadableByteStreamControllerEnqueue(this, chunk);
1924 }
1925 error(e) {
1926 if (IsReadableByteStreamController(this) === false) {
1927 throw byteStreamControllerBrandCheckException('error');
1928 }
1929 ReadableByteStreamControllerError(this, e);
1930 }
1931 /** @internal */
1932 [CancelSteps](reason) {
1933 if (this._pendingPullIntos.length > 0) {
1934 const firstDescriptor = this._pendingPullIntos.peek();
1935 firstDescriptor.bytesFilled = 0;
1936 }
1937 ResetQueue(this);
1938 const result = this._cancelAlgorithm(reason);
1939 ReadableByteStreamControllerClearAlgorithms(this);
1940 return result;
1941 }
1942 /** @internal */
1943 [PullSteps]() {
1944 const stream = this._controlledReadableByteStream;
1945 if (this._queueTotalSize > 0) {
1946 const entry = this._queue.shift();
1947 this._queueTotalSize -= entry.byteLength;
1948 ReadableByteStreamControllerHandleQueueDrain(this);
1949 let view;
1950 try {
1951 view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1952 }
1953 catch (viewE) {
1954 return promiseRejectedWith(viewE);
1955 }
1956 return promiseResolvedWith(ReadableStreamCreateReadResult(view, false, stream._reader._forAuthorCode));
1957 }
1958 const autoAllocateChunkSize = this._autoAllocateChunkSize;
1959 if (autoAllocateChunkSize !== undefined) {
1960 let buffer;
1961 try {
1962 buffer = new ArrayBuffer(autoAllocateChunkSize);
1963 }
1964 catch (bufferE) {
1965 return promiseRejectedWith(bufferE);
1966 }
1967 const pullIntoDescriptor = {
1968 buffer,
1969 byteOffset: 0,
1970 byteLength: autoAllocateChunkSize,
1971 bytesFilled: 0,
1972 elementSize: 1,
1973 ctor: Uint8Array,
1974 readerType: 'default'
1975 };
1976 this._pendingPullIntos.push(pullIntoDescriptor);
1977 }
1978 const promise = ReadableStreamAddReadRequest(stream);
1979 ReadableByteStreamControllerCallPullIfNeeded(this);
1980 return promise;
1981 }
1982}
1983// Abstract operations for the ReadableByteStreamController.
1984function IsReadableByteStreamController(x) {
1985 if (!typeIsObject(x)) {
1986 return false;
1987 }
1988 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
1989 return false;
1990 }
1991 return true;
1992}
1993function IsReadableStreamBYOBRequest(x) {
1994 if (!typeIsObject(x)) {
1995 return false;
1996 }
1997 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
1998 return false;
1999 }
2000 return true;
2001}
2002function ReadableByteStreamControllerCallPullIfNeeded(controller) {
2003 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
2004 if (shouldPull === false) {
2005 return;
2006 }
2007 if (controller._pulling === true) {
2008 controller._pullAgain = true;
2009 return;
2010 }
2011 controller._pulling = true;
2012 // TODO: Test controller argument
2013 const pullPromise = controller._pullAlgorithm();
2014 uponPromise(pullPromise, () => {
2015 controller._pulling = false;
2016 if (controller._pullAgain === true) {
2017 controller._pullAgain = false;
2018 ReadableByteStreamControllerCallPullIfNeeded(controller);
2019 }
2020 }, e => {
2021 ReadableByteStreamControllerError(controller, e);
2022 });
2023}
2024function ReadableByteStreamControllerClearPendingPullIntos(controller) {
2025 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
2026 controller._pendingPullIntos = new SimpleQueue();
2027}
2028function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
2029 let done = false;
2030 if (stream._state === 'closed') {
2031 done = true;
2032 }
2033 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
2034 if (pullIntoDescriptor.readerType === 'default') {
2035 ReadableStreamFulfillReadRequest(stream, filledView, done);
2036 }
2037 else {
2038 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
2039 }
2040}
2041function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
2042 const bytesFilled = pullIntoDescriptor.bytesFilled;
2043 const elementSize = pullIntoDescriptor.elementSize;
2044 return new pullIntoDescriptor.ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
2045}
2046function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
2047 controller._queue.push({ buffer, byteOffset, byteLength });
2048 controller._queueTotalSize += byteLength;
2049}
2050function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
2051 const elementSize = pullIntoDescriptor.elementSize;
2052 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
2053 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
2054 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
2055 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
2056 let totalBytesToCopyRemaining = maxBytesToCopy;
2057 let ready = false;
2058 if (maxAlignedBytes > currentAlignedBytes) {
2059 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
2060 ready = true;
2061 }
2062 const queue = controller._queue;
2063 while (totalBytesToCopyRemaining > 0) {
2064 const headOfQueue = queue.peek();
2065 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
2066 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
2067 ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
2068 if (headOfQueue.byteLength === bytesToCopy) {
2069 queue.shift();
2070 }
2071 else {
2072 headOfQueue.byteOffset += bytesToCopy;
2073 headOfQueue.byteLength -= bytesToCopy;
2074 }
2075 controller._queueTotalSize -= bytesToCopy;
2076 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
2077 totalBytesToCopyRemaining -= bytesToCopy;
2078 }
2079 return ready;
2080}
2081function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
2082 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
2083 pullIntoDescriptor.bytesFilled += size;
2084}
2085function ReadableByteStreamControllerHandleQueueDrain(controller) {
2086 if (controller._queueTotalSize === 0 && controller._closeRequested === true) {
2087 ReadableByteStreamControllerClearAlgorithms(controller);
2088 ReadableStreamClose(controller._controlledReadableByteStream);
2089 }
2090 else {
2091 ReadableByteStreamControllerCallPullIfNeeded(controller);
2092 }
2093}
2094function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
2095 if (controller._byobRequest === undefined) {
2096 return;
2097 }
2098 controller._byobRequest._associatedReadableByteStreamController = undefined;
2099 controller._byobRequest._view = undefined;
2100 controller._byobRequest = undefined;
2101}
2102function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
2103 while (controller._pendingPullIntos.length > 0) {
2104 if (controller._queueTotalSize === 0) {
2105 return;
2106 }
2107 const pullIntoDescriptor = controller._pendingPullIntos.peek();
2108 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {
2109 ReadableByteStreamControllerShiftPendingPullInto(controller);
2110 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
2111 }
2112 }
2113}
2114function ReadableByteStreamControllerPullInto(controller, view) {
2115 const stream = controller._controlledReadableByteStream;
2116 let elementSize = 1;
2117 if (view.constructor !== DataView) {
2118 elementSize = view.constructor.BYTES_PER_ELEMENT;
2119 }
2120 const ctor = view.constructor;
2121 const buffer = TransferArrayBuffer(view.buffer);
2122 const pullIntoDescriptor = {
2123 buffer,
2124 byteOffset: view.byteOffset,
2125 byteLength: view.byteLength,
2126 bytesFilled: 0,
2127 elementSize,
2128 ctor,
2129 readerType: 'byob'
2130 };
2131 if (controller._pendingPullIntos.length > 0) {
2132 controller._pendingPullIntos.push(pullIntoDescriptor);
2133 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
2134 // - No change happens on desiredSize
2135 // - The source has already been notified of that there's at least 1 pending read(view)
2136 return ReadableStreamAddReadIntoRequest(stream);
2137 }
2138 if (stream._state === 'closed') {
2139 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
2140 return promiseResolvedWith(ReadableStreamCreateReadResult(emptyView, true, stream._reader._forAuthorCode));
2141 }
2142 if (controller._queueTotalSize > 0) {
2143 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {
2144 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
2145 ReadableByteStreamControllerHandleQueueDrain(controller);
2146 return promiseResolvedWith(ReadableStreamCreateReadResult(filledView, false, stream._reader._forAuthorCode));
2147 }
2148 if (controller._closeRequested === true) {
2149 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
2150 ReadableByteStreamControllerError(controller, e);
2151 return promiseRejectedWith(e);
2152 }
2153 }
2154 controller._pendingPullIntos.push(pullIntoDescriptor);
2155 const promise = ReadableStreamAddReadIntoRequest(stream);
2156 ReadableByteStreamControllerCallPullIfNeeded(controller);
2157 return promise;
2158}
2159function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
2160 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
2161 const stream = controller._controlledReadableByteStream;
2162 if (ReadableStreamHasBYOBReader(stream) === true) {
2163 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
2164 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
2165 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
2166 }
2167 }
2168}
2169function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
2170 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
2171 throw new RangeError('bytesWritten out of range');
2172 }
2173 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
2174 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
2175 // TODO: Figure out whether we should detach the buffer or not here.
2176 return;
2177 }
2178 ReadableByteStreamControllerShiftPendingPullInto(controller);
2179 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
2180 if (remainderSize > 0) {
2181 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
2182 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
2183 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
2184 }
2185 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
2186 pullIntoDescriptor.bytesFilled -= remainderSize;
2187 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
2188 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
2189}
2190function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
2191 const firstDescriptor = controller._pendingPullIntos.peek();
2192 const stream = controller._controlledReadableByteStream;
2193 if (stream._state === 'closed') {
2194 if (bytesWritten !== 0) {
2195 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
2196 }
2197 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
2198 }
2199 else {
2200 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
2201 }
2202 ReadableByteStreamControllerCallPullIfNeeded(controller);
2203}
2204function ReadableByteStreamControllerShiftPendingPullInto(controller) {
2205 const descriptor = controller._pendingPullIntos.shift();
2206 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
2207 return descriptor;
2208}
2209function ReadableByteStreamControllerShouldCallPull(controller) {
2210 const stream = controller._controlledReadableByteStream;
2211 if (stream._state !== 'readable') {
2212 return false;
2213 }
2214 if (controller._closeRequested === true) {
2215 return false;
2216 }
2217 if (controller._started === false) {
2218 return false;
2219 }
2220 if (ReadableStreamHasDefaultReader(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {
2221 return true;
2222 }
2223 if (ReadableStreamHasBYOBReader(stream) === true && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
2224 return true;
2225 }
2226 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
2227 if (desiredSize > 0) {
2228 return true;
2229 }
2230 return false;
2231}
2232function ReadableByteStreamControllerClearAlgorithms(controller) {
2233 controller._pullAlgorithm = undefined;
2234 controller._cancelAlgorithm = undefined;
2235}
2236// A client of ReadableByteStreamController may use these functions directly to bypass state check.
2237function ReadableByteStreamControllerClose(controller) {
2238 const stream = controller._controlledReadableByteStream;
2239 if (controller._queueTotalSize > 0) {
2240 controller._closeRequested = true;
2241 return;
2242 }
2243 if (controller._pendingPullIntos.length > 0) {
2244 const firstPendingPullInto = controller._pendingPullIntos.peek();
2245 if (firstPendingPullInto.bytesFilled > 0) {
2246 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
2247 ReadableByteStreamControllerError(controller, e);
2248 throw e;
2249 }
2250 }
2251 ReadableByteStreamControllerClearAlgorithms(controller);
2252 ReadableStreamClose(stream);
2253}
2254function ReadableByteStreamControllerEnqueue(controller, chunk) {
2255 const stream = controller._controlledReadableByteStream;
2256 const buffer = chunk.buffer;
2257 const byteOffset = chunk.byteOffset;
2258 const byteLength = chunk.byteLength;
2259 const transferredBuffer = TransferArrayBuffer(buffer);
2260 if (ReadableStreamHasDefaultReader(stream) === true) {
2261 if (ReadableStreamGetNumReadRequests(stream) === 0) {
2262 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
2263 }
2264 else {
2265 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
2266 ReadableStreamFulfillReadRequest(stream, transferredView, false);
2267 }
2268 }
2269 else if (ReadableStreamHasBYOBReader(stream) === true) {
2270 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
2271 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
2272 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
2273 }
2274 else {
2275 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
2276 }
2277 ReadableByteStreamControllerCallPullIfNeeded(controller);
2278}
2279function ReadableByteStreamControllerError(controller, e) {
2280 const stream = controller._controlledReadableByteStream;
2281 if (stream._state !== 'readable') {
2282 return;
2283 }
2284 ReadableByteStreamControllerClearPendingPullIntos(controller);
2285 ResetQueue(controller);
2286 ReadableByteStreamControllerClearAlgorithms(controller);
2287 ReadableStreamError(stream, e);
2288}
2289function ReadableByteStreamControllerGetDesiredSize(controller) {
2290 const stream = controller._controlledReadableByteStream;
2291 const state = stream._state;
2292 if (state === 'errored') {
2293 return null;
2294 }
2295 if (state === 'closed') {
2296 return 0;
2297 }
2298 return controller._strategyHWM - controller._queueTotalSize;
2299}
2300function ReadableByteStreamControllerRespond(controller, bytesWritten) {
2301 bytesWritten = Number(bytesWritten);
2302 if (IsFiniteNonNegativeNumber(bytesWritten) === false) {
2303 throw new RangeError('bytesWritten must be a finite');
2304 }
2305 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
2306}
2307function ReadableByteStreamControllerRespondWithNewView(controller, view) {
2308 const firstDescriptor = controller._pendingPullIntos.peek();
2309 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
2310 throw new RangeError('The region specified by view does not match byobRequest');
2311 }
2312 if (firstDescriptor.byteLength !== view.byteLength) {
2313 throw new RangeError('The buffer of view has different capacity than byobRequest');
2314 }
2315 firstDescriptor.buffer = view.buffer;
2316 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
2317}
2318function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
2319 controller._controlledReadableByteStream = stream;
2320 controller._pullAgain = false;
2321 controller._pulling = false;
2322 controller._byobRequest = undefined;
2323 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
2324 controller._queue = controller._queueTotalSize = undefined;
2325 ResetQueue(controller);
2326 controller._closeRequested = false;
2327 controller._started = false;
2328 controller._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark);
2329 controller._pullAlgorithm = pullAlgorithm;
2330 controller._cancelAlgorithm = cancelAlgorithm;
2331 controller._autoAllocateChunkSize = autoAllocateChunkSize;
2332 controller._pendingPullIntos = new SimpleQueue();
2333 stream._readableStreamController = controller;
2334 const startResult = startAlgorithm();
2335 uponPromise(promiseResolvedWith(startResult), () => {
2336 controller._started = true;
2337 ReadableByteStreamControllerCallPullIfNeeded(controller);
2338 }, r => {
2339 ReadableByteStreamControllerError(controller, r);
2340 });
2341}
2342function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
2343 const controller = Object.create(ReadableByteStreamController.prototype);
2344 function startAlgorithm() {
2345 return InvokeOrNoop(underlyingByteSource, 'start', [controller]);
2346 }
2347 const pullAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingByteSource, 'pull', 0, [controller]);
2348 const cancelAlgorithm = CreateAlgorithmFromUnderlyingMethod(underlyingByteSource, 'cancel', 1, []);
2349 let autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
2350 if (autoAllocateChunkSize !== undefined) {
2351 autoAllocateChunkSize = Number(autoAllocateChunkSize);
2352 if (NumberIsInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) {
2353 throw new RangeError('autoAllocateChunkSize must be a positive integer');
2354 }
2355 }
2356 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
2357}
2358function SetUpReadableStreamBYOBRequest(request, controller, view) {
2359 request._associatedReadableByteStreamController = controller;
2360 request._view = view;
2361}
2362// Helper functions for the ReadableStreamBYOBRequest.
2363function byobRequestBrandCheckException(name) {
2364 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
2365}
2366// Helper functions for the ReadableByteStreamController.
2367function byteStreamControllerBrandCheckException(name) {
2368 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
2369}
2370
2371// Abstract operations for the ReadableStream.
2372function AcquireReadableStreamBYOBReader(stream, forAuthorCode = false) {
2373 const reader = new ReadableStreamBYOBReader(stream);
2374 reader._forAuthorCode = forAuthorCode;
2375 return reader;
2376}
2377// ReadableStream API exposed for controllers.
2378function ReadableStreamAddReadIntoRequest(stream) {
2379 const promise = newPromise((resolve, reject) => {
2380 const readIntoRequest = {
2381 _resolve: resolve,
2382 _reject: reject
2383 };
2384 stream._reader._readIntoRequests.push(readIntoRequest);
2385 });
2386 return promise;
2387}
2388function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
2389 const reader = stream._reader;
2390 const readIntoRequest = reader._readIntoRequests.shift();
2391 readIntoRequest._resolve(ReadableStreamCreateReadResult(chunk, done, reader._forAuthorCode));
2392}
2393function ReadableStreamGetNumReadIntoRequests(stream) {
2394 return stream._reader._readIntoRequests.length;
2395}
2396function ReadableStreamHasBYOBReader(stream) {
2397 const reader = stream._reader;
2398 if (reader === undefined) {
2399 return false;
2400 }
2401 if (!IsReadableStreamBYOBReader(reader)) {
2402 return false;
2403 }
2404 return true;
2405}
2406class ReadableStreamBYOBReader {
2407 constructor(stream) {
2408 if (!IsReadableStream(stream)) {
2409 throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' +
2410 'byte source');
2411 }
2412 if (IsReadableByteStreamController(stream._readableStreamController) === false) {
2413 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
2414 'source');
2415 }
2416 if (IsReadableStreamLocked(stream)) {
2417 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
2418 }
2419 ReadableStreamReaderGenericInitialize(this, stream);
2420 this._readIntoRequests = new SimpleQueue();
2421 }
2422 get closed() {
2423 if (!IsReadableStreamBYOBReader(this)) {
2424 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
2425 }
2426 return this._closedPromise;
2427 }
2428 cancel(reason) {
2429 if (!IsReadableStreamBYOBReader(this)) {
2430 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
2431 }
2432 if (this._ownerReadableStream === undefined) {
2433 return promiseRejectedWith(readerLockException('cancel'));
2434 }
2435 return ReadableStreamReaderGenericCancel(this, reason);
2436 }
2437 read(view) {
2438 if (!IsReadableStreamBYOBReader(this)) {
2439 return promiseRejectedWith(byobReaderBrandCheckException('read'));
2440 }
2441 if (this._ownerReadableStream === undefined) {
2442 return promiseRejectedWith(readerLockException('read from'));
2443 }
2444 if (!ArrayBuffer.isView(view)) {
2445 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
2446 }
2447 if (IsDetachedBuffer(view.buffer) === true) ;
2448 if (view.byteLength === 0) {
2449 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
2450 }
2451 return ReadableStreamBYOBReaderRead(this, view);
2452 }
2453 releaseLock() {
2454 if (!IsReadableStreamBYOBReader(this)) {
2455 throw byobReaderBrandCheckException('releaseLock');
2456 }
2457 if (this._ownerReadableStream === undefined) {
2458 return;
2459 }
2460 if (this._readIntoRequests.length > 0) {
2461 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
2462 }
2463 ReadableStreamReaderGenericRelease(this);
2464 }
2465}
2466// Abstract operations for the readers.
2467function IsReadableStreamBYOBReader(x) {
2468 if (!typeIsObject(x)) {
2469 return false;
2470 }
2471 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
2472 return false;
2473 }
2474 return true;
2475}
2476function ReadableStreamBYOBReaderRead(reader, view) {
2477 const stream = reader._ownerReadableStream;
2478 stream._disturbed = true;
2479 if (stream._state === 'errored') {
2480 return promiseRejectedWith(stream._storedError);
2481 }
2482 // Controllers must implement this.
2483 return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);
2484}
2485// Helper functions for the ReadableStreamBYOBReader.
2486function byobReaderBrandCheckException(name) {
2487 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
2488}
2489
2490class ReadableStream {
2491 constructor(underlyingSource = {}, strategy = {}) {
2492 InitializeReadableStream(this);
2493 const size = strategy.size;
2494 let highWaterMark = strategy.highWaterMark;
2495 const type = underlyingSource.type;
2496 const typeString = String(type);
2497 if (typeString === 'bytes') {
2498 if (size !== undefined) {
2499 throw new RangeError('The strategy for a byte stream cannot have a size function');
2500 }
2501 if (highWaterMark === undefined) {
2502 highWaterMark = 0;
2503 }
2504 highWaterMark = ValidateAndNormalizeHighWaterMark(highWaterMark);
2505 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
2506 }
2507 else if (type === undefined) {
2508 const sizeAlgorithm = MakeSizeAlgorithmFromSizeFunction(size);
2509 if (highWaterMark === undefined) {
2510 highWaterMark = 1;
2511 }
2512 highWaterMark = ValidateAndNormalizeHighWaterMark(highWaterMark);
2513 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
2514 }
2515 else {
2516 throw new RangeError('Invalid type is specified');
2517 }
2518 }
2519 get locked() {
2520 if (IsReadableStream(this) === false) {
2521 throw streamBrandCheckException$1('locked');
2522 }
2523 return IsReadableStreamLocked(this);
2524 }
2525 cancel(reason) {
2526 if (IsReadableStream(this) === false) {
2527 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
2528 }
2529 if (IsReadableStreamLocked(this) === true) {
2530 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
2531 }
2532 return ReadableStreamCancel(this, reason);
2533 }
2534 getReader({ mode } = {}) {
2535 if (IsReadableStream(this) === false) {
2536 throw streamBrandCheckException$1('getReader');
2537 }
2538 if (mode === undefined) {
2539 return AcquireReadableStreamDefaultReader(this, true);
2540 }
2541 mode = String(mode);
2542 if (mode === 'byob') {
2543 return AcquireReadableStreamBYOBReader(this, true);
2544 }
2545 throw new RangeError('Invalid mode is specified');
2546 }
2547 pipeThrough({ writable, readable }, { preventClose, preventAbort, preventCancel, signal } = {}) {
2548 if (IsReadableStream(this) === false) {
2549 throw streamBrandCheckException$1('pipeThrough');
2550 }
2551 if (IsWritableStream(writable) === false) {
2552 throw new TypeError('writable argument to pipeThrough must be a WritableStream');
2553 }
2554 if (IsReadableStream(readable) === false) {
2555 throw new TypeError('readable argument to pipeThrough must be a ReadableStream');
2556 }
2557 preventClose = Boolean(preventClose);
2558 preventAbort = Boolean(preventAbort);
2559 preventCancel = Boolean(preventCancel);
2560 if (signal !== undefined && !isAbortSignal(signal)) {
2561 throw new TypeError('ReadableStream.prototype.pipeThrough\'s signal option must be an AbortSignal');
2562 }
2563 if (IsReadableStreamLocked(this) === true) {
2564 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
2565 }
2566 if (IsWritableStreamLocked(writable) === true) {
2567 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
2568 }
2569 const promise = ReadableStreamPipeTo(this, writable, preventClose, preventAbort, preventCancel, signal);
2570 setPromiseIsHandledToTrue(promise);
2571 return readable;
2572 }
2573 pipeTo(dest, { preventClose, preventAbort, preventCancel, signal } = {}) {
2574 if (IsReadableStream(this) === false) {
2575 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
2576 }
2577 if (IsWritableStream(dest) === false) {
2578 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo\'s first argument must be a WritableStream'));
2579 }
2580 preventClose = Boolean(preventClose);
2581 preventAbort = Boolean(preventAbort);
2582 preventCancel = Boolean(preventCancel);
2583 if (signal !== undefined && !isAbortSignal(signal)) {
2584 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo\'s signal option must be an AbortSignal'));
2585 }
2586 if (IsReadableStreamLocked(this) === true) {
2587 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
2588 }
2589 if (IsWritableStreamLocked(dest) === true) {
2590 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
2591 }
2592 return ReadableStreamPipeTo(this, dest, preventClose, preventAbort, preventCancel, signal);
2593 }
2594 tee() {
2595 if (IsReadableStream(this) === false) {
2596 throw streamBrandCheckException$1('tee');
2597 }
2598 const branches = ReadableStreamTee(this);
2599 return createArrayFromList(branches);
2600 }
2601 getIterator({ preventCancel = false } = {}) {
2602 if (IsReadableStream(this) === false) {
2603 throw streamBrandCheckException$1('getIterator');
2604 }
2605 return AcquireReadableStreamAsyncIterator(this, preventCancel);
2606 }
2607}
2608if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
2609 Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
2610 value: ReadableStream.prototype.getIterator,
2611 enumerable: false,
2612 writable: true,
2613 configurable: true
2614 });
2615}
2616// Abstract operations for the ReadableStream.
2617// Throws if and only if startAlgorithm throws.
2618function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
2619 const stream = Object.create(ReadableStream.prototype);
2620 InitializeReadableStream(stream);
2621 const controller = Object.create(ReadableStreamDefaultController.prototype);
2622 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
2623 return stream;
2624}
2625function InitializeReadableStream(stream) {
2626 stream._state = 'readable';
2627 stream._reader = undefined;
2628 stream._storedError = undefined;
2629 stream._disturbed = false;
2630}
2631function IsReadableStream(x) {
2632 if (!typeIsObject(x)) {
2633 return false;
2634 }
2635 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
2636 return false;
2637 }
2638 return true;
2639}
2640function IsReadableStreamLocked(stream) {
2641 if (stream._reader === undefined) {
2642 return false;
2643 }
2644 return true;
2645}
2646// ReadableStream API exposed for controllers.
2647function ReadableStreamCancel(stream, reason) {
2648 stream._disturbed = true;
2649 if (stream._state === 'closed') {
2650 return promiseResolvedWith(undefined);
2651 }
2652 if (stream._state === 'errored') {
2653 return promiseRejectedWith(stream._storedError);
2654 }
2655 ReadableStreamClose(stream);
2656 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
2657 return transformPromiseWith(sourceCancelPromise, noop);
2658}
2659function ReadableStreamClose(stream) {
2660 stream._state = 'closed';
2661 const reader = stream._reader;
2662 if (reader === undefined) {
2663 return;
2664 }
2665 if (IsReadableStreamDefaultReader(reader)) {
2666 reader._readRequests.forEach(readRequest => {
2667 readRequest._resolve(ReadableStreamCreateReadResult(undefined, true, reader._forAuthorCode));
2668 });
2669 reader._readRequests = new SimpleQueue();
2670 }
2671 defaultReaderClosedPromiseResolve(reader);
2672}
2673function ReadableStreamError(stream, e) {
2674 stream._state = 'errored';
2675 stream._storedError = e;
2676 const reader = stream._reader;
2677 if (reader === undefined) {
2678 return;
2679 }
2680 if (IsReadableStreamDefaultReader(reader)) {
2681 reader._readRequests.forEach(readRequest => {
2682 readRequest._reject(e);
2683 });
2684 reader._readRequests = new SimpleQueue();
2685 }
2686 else {
2687 reader._readIntoRequests.forEach(readIntoRequest => {
2688 readIntoRequest._reject(e);
2689 });
2690 reader._readIntoRequests = new SimpleQueue();
2691 }
2692 defaultReaderClosedPromiseReject(reader, e);
2693}
2694// Helper functions for the ReadableStream.
2695function streamBrandCheckException$1(name) {
2696 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
2697}
2698
2699// Class TransformStream
2700class TransformStream {
2701 constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
2702 const writableSizeFunction = writableStrategy.size;
2703 let writableHighWaterMark = writableStrategy.highWaterMark;
2704 const readableSizeFunction = readableStrategy.size;
2705 let readableHighWaterMark = readableStrategy.highWaterMark;
2706 const writableType = transformer.writableType;
2707 if (writableType !== undefined) {
2708 throw new RangeError('Invalid writable type specified');
2709 }
2710 const writableSizeAlgorithm = MakeSizeAlgorithmFromSizeFunction(writableSizeFunction);
2711 if (writableHighWaterMark === undefined) {
2712 writableHighWaterMark = 1;
2713 }
2714 writableHighWaterMark = ValidateAndNormalizeHighWaterMark(writableHighWaterMark);
2715 const readableType = transformer.readableType;
2716 if (readableType !== undefined) {
2717 throw new RangeError('Invalid readable type specified');
2718 }
2719 const readableSizeAlgorithm = MakeSizeAlgorithmFromSizeFunction(readableSizeFunction);
2720 if (readableHighWaterMark === undefined) {
2721 readableHighWaterMark = 0;
2722 }
2723 readableHighWaterMark = ValidateAndNormalizeHighWaterMark(readableHighWaterMark);
2724 let startPromise_resolve;
2725 const startPromise = newPromise(resolve => {
2726 startPromise_resolve = resolve;
2727 });
2728 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
2729 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
2730 const startResult = InvokeOrNoop(transformer, 'start', [this._transformStreamController]);
2731 startPromise_resolve(startResult);
2732 }
2733 get readable() {
2734 if (IsTransformStream(this) === false) {
2735 throw streamBrandCheckException$2('readable');
2736 }
2737 return this._readable;
2738 }
2739 get writable() {
2740 if (IsTransformStream(this) === false) {
2741 throw streamBrandCheckException$2('writable');
2742 }
2743 return this._writable;
2744 }
2745}
2746function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
2747 function startAlgorithm() {
2748 return startPromise;
2749 }
2750 function writeAlgorithm(chunk) {
2751 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
2752 }
2753 function abortAlgorithm(reason) {
2754 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
2755 }
2756 function closeAlgorithm() {
2757 return TransformStreamDefaultSinkCloseAlgorithm(stream);
2758 }
2759 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
2760 function pullAlgorithm() {
2761 return TransformStreamDefaultSourcePullAlgorithm(stream);
2762 }
2763 function cancelAlgorithm(reason) {
2764 TransformStreamErrorWritableAndUnblockWrite(stream, reason);
2765 return promiseResolvedWith(undefined);
2766 }
2767 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
2768 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
2769 stream._backpressure = undefined;
2770 stream._backpressureChangePromise = undefined;
2771 stream._backpressureChangePromise_resolve = undefined;
2772 TransformStreamSetBackpressure(stream, true);
2773 // Used by IsWritableStream() which is called by SetUpTransformStreamDefaultController().
2774 stream._transformStreamController = undefined;
2775}
2776function IsTransformStream(x) {
2777 if (!typeIsObject(x)) {
2778 return false;
2779 }
2780 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
2781 return false;
2782 }
2783 return true;
2784}
2785// This is a no-op if both sides are already errored.
2786function TransformStreamError(stream, e) {
2787 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
2788 TransformStreamErrorWritableAndUnblockWrite(stream, e);
2789}
2790function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
2791 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
2792 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
2793 if (stream._backpressure === true) {
2794 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
2795 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
2796 // _backpressure is set.
2797 TransformStreamSetBackpressure(stream, false);
2798 }
2799}
2800function TransformStreamSetBackpressure(stream, backpressure) {
2801 // Passes also when called during construction.
2802 if (stream._backpressureChangePromise !== undefined) {
2803 stream._backpressureChangePromise_resolve();
2804 }
2805 stream._backpressureChangePromise = newPromise(resolve => {
2806 stream._backpressureChangePromise_resolve = resolve;
2807 });
2808 stream._backpressure = backpressure;
2809}
2810class TransformStreamDefaultController {
2811 /** @internal */
2812 constructor() {
2813 throw new TypeError('TransformStreamDefaultController instances cannot be created directly');
2814 }
2815 get desiredSize() {
2816 if (IsTransformStreamDefaultController(this) === false) {
2817 throw defaultControllerBrandCheckException$1('desiredSize');
2818 }
2819 const readableController = this._controlledTransformStream._readable._readableStreamController;
2820 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
2821 }
2822 enqueue(chunk) {
2823 if (IsTransformStreamDefaultController(this) === false) {
2824 throw defaultControllerBrandCheckException$1('enqueue');
2825 }
2826 TransformStreamDefaultControllerEnqueue(this, chunk);
2827 }
2828 error(reason) {
2829 if (IsTransformStreamDefaultController(this) === false) {
2830 throw defaultControllerBrandCheckException$1('error');
2831 }
2832 TransformStreamDefaultControllerError(this, reason);
2833 }
2834 terminate() {
2835 if (IsTransformStreamDefaultController(this) === false) {
2836 throw defaultControllerBrandCheckException$1('terminate');
2837 }
2838 TransformStreamDefaultControllerTerminate(this);
2839 }
2840}
2841// Transform Stream Default Controller Abstract Operations
2842function IsTransformStreamDefaultController(x) {
2843 if (!typeIsObject(x)) {
2844 return false;
2845 }
2846 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
2847 return false;
2848 }
2849 return true;
2850}
2851function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
2852 controller._controlledTransformStream = stream;
2853 stream._transformStreamController = controller;
2854 controller._transformAlgorithm = transformAlgorithm;
2855 controller._flushAlgorithm = flushAlgorithm;
2856}
2857function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
2858 const controller = Object.create(TransformStreamDefaultController.prototype);
2859 let transformAlgorithm = (chunk) => {
2860 try {
2861 TransformStreamDefaultControllerEnqueue(controller, chunk);
2862 return promiseResolvedWith(undefined);
2863 }
2864 catch (transformResultE) {
2865 return promiseRejectedWith(transformResultE);
2866 }
2867 };
2868 const transformMethod = transformer.transform;
2869 if (transformMethod !== undefined) {
2870 if (typeof transformMethod !== 'function') {
2871 throw new TypeError('transform is not a method');
2872 }
2873 transformAlgorithm = chunk => PromiseCall(transformMethod, transformer, [chunk, controller]);
2874 }
2875 const flushAlgorithm = CreateAlgorithmFromUnderlyingMethod(transformer, 'flush', 0, [controller]);
2876 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
2877}
2878function TransformStreamDefaultControllerClearAlgorithms(controller) {
2879 controller._transformAlgorithm = undefined;
2880 controller._flushAlgorithm = undefined;
2881}
2882function TransformStreamDefaultControllerEnqueue(controller, chunk) {
2883 const stream = controller._controlledTransformStream;
2884 const readableController = stream._readable._readableStreamController;
2885 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) === false) {
2886 throw new TypeError('Readable side is not in a state that permits enqueue');
2887 }
2888 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
2889 // accept TransformStreamDefaultControllerEnqueue() calls.
2890 try {
2891 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
2892 }
2893 catch (e) {
2894 // This happens when readableStrategy.size() throws.
2895 TransformStreamErrorWritableAndUnblockWrite(stream, e);
2896 throw stream._readable._storedError;
2897 }
2898 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
2899 if (backpressure !== stream._backpressure) {
2900 TransformStreamSetBackpressure(stream, true);
2901 }
2902}
2903function TransformStreamDefaultControllerError(controller, e) {
2904 TransformStreamError(controller._controlledTransformStream, e);
2905}
2906function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
2907 const transformPromise = controller._transformAlgorithm(chunk);
2908 return transformPromiseWith(transformPromise, undefined, r => {
2909 TransformStreamError(controller._controlledTransformStream, r);
2910 throw r;
2911 });
2912}
2913function TransformStreamDefaultControllerTerminate(controller) {
2914 const stream = controller._controlledTransformStream;
2915 const readableController = stream._readable._readableStreamController;
2916 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) === true) {
2917 ReadableStreamDefaultControllerClose(readableController);
2918 }
2919 const error = new TypeError('TransformStream terminated');
2920 TransformStreamErrorWritableAndUnblockWrite(stream, error);
2921}
2922// TransformStreamDefaultSink Algorithms
2923function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
2924 const controller = stream._transformStreamController;
2925 if (stream._backpressure === true) {
2926 const backpressureChangePromise = stream._backpressureChangePromise;
2927 return transformPromiseWith(backpressureChangePromise, () => {
2928 const writable = stream._writable;
2929 const state = writable._state;
2930 if (state === 'erroring') {
2931 throw writable._storedError;
2932 }
2933 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
2934 });
2935 }
2936 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
2937}
2938function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
2939 // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
2940 // errored.
2941 TransformStreamError(stream, reason);
2942 return promiseResolvedWith(undefined);
2943}
2944function TransformStreamDefaultSinkCloseAlgorithm(stream) {
2945 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
2946 const readable = stream._readable;
2947 const controller = stream._transformStreamController;
2948 const flushPromise = controller._flushAlgorithm();
2949 TransformStreamDefaultControllerClearAlgorithms(controller);
2950 // Return a promise that is fulfilled with undefined on success.
2951 return transformPromiseWith(flushPromise, () => {
2952 if (readable._state === 'errored') {
2953 throw readable._storedError;
2954 }
2955 const readableController = readable._readableStreamController;
2956 if (ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) === true) {
2957 ReadableStreamDefaultControllerClose(readableController);
2958 }
2959 }, r => {
2960 TransformStreamError(stream, r);
2961 throw readable._storedError;
2962 });
2963}
2964// TransformStreamDefaultSource Algorithms
2965function TransformStreamDefaultSourcePullAlgorithm(stream) {
2966 // Invariant. Enforced by the promises returned by start() and pull().
2967 TransformStreamSetBackpressure(stream, false);
2968 // Prevent the next pull() call until there is backpressure.
2969 return stream._backpressureChangePromise;
2970}
2971// Helper functions for the TransformStreamDefaultController.
2972function defaultControllerBrandCheckException$1(name) {
2973 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
2974}
2975// Helper functions for the TransformStream.
2976function streamBrandCheckException$2(name) {
2977 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
2978}
2979
2980/*! *****************************************************************************
2981Copyright (c) Microsoft Corporation. All rights reserved.
2982Licensed under the Apache License, Version 2.0 (the "License"); you may not use
2983this file except in compliance with the License. You may obtain a copy of the
2984License at http://www.apache.org/licenses/LICENSE-2.0
2985
2986THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
2987KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
2988WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
2989MERCHANTABLITY OR NON-INFRINGEMENT.
2990
2991See the Apache Version 2.0 License for specific language governing permissions
2992and limitations under the License.
2993***************************************************************************** */
2994/* global Reflect, Promise */
2995
2996var extendStatics = function(d, b) {
2997 extendStatics = Object.setPrototypeOf ||
2998 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2999 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
3000 return extendStatics(d, b);
3001};
3002
3003function __extends(d, b) {
3004 extendStatics(d, b);
3005 function __() { this.constructor = d; }
3006 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
3007}
3008
3009function assert(test) {
3010 if (!test) {
3011 throw new TypeError('Assertion failed');
3012 }
3013}
3014
3015function noop$1() {
3016 return;
3017}
3018function typeIsObject$1(x) {
3019 return (typeof x === 'object' && x !== null) || typeof x === 'function';
3020}
3021
3022function isStreamConstructor(ctor) {
3023 if (typeof ctor !== 'function') {
3024 return false;
3025 }
3026 var startCalled = false;
3027 try {
3028 new ctor({
3029 start: function () {
3030 startCalled = true;
3031 }
3032 });
3033 }
3034 catch (e) {
3035 // ignore
3036 }
3037 return startCalled;
3038}
3039function isReadableStream(readable) {
3040 if (!typeIsObject$1(readable)) {
3041 return false;
3042 }
3043 if (typeof readable.getReader !== 'function') {
3044 return false;
3045 }
3046 return true;
3047}
3048function isReadableStreamConstructor(ctor) {
3049 if (!isStreamConstructor(ctor)) {
3050 return false;
3051 }
3052 if (!isReadableStream(new ctor())) {
3053 return false;
3054 }
3055 return true;
3056}
3057function supportsByobReader(readable) {
3058 try {
3059 var reader = readable.getReader({ mode: 'byob' });
3060 reader.releaseLock();
3061 return true;
3062 }
3063 catch (_a) {
3064 return false;
3065 }
3066}
3067function supportsByteSource(ctor) {
3068 try {
3069 new ctor({ type: 'bytes' });
3070 return true;
3071 }
3072 catch (_a) {
3073 return false;
3074 }
3075}
3076
3077function createReadableStreamWrapper(ctor) {
3078 assert(isReadableStreamConstructor(ctor));
3079 var byteSourceSupported = supportsByteSource(ctor);
3080 return function (readable, _a) {
3081 var type = (_a === void 0 ? {} : _a).type;
3082 type = parseReadableType(type);
3083 if (type === 'bytes' && !byteSourceSupported) {
3084 type = undefined;
3085 }
3086 if (readable.constructor === ctor) {
3087 if (type !== 'bytes' || supportsByobReader(readable)) {
3088 return readable;
3089 }
3090 }
3091 var source = createWrappingReadableSource(readable, { type: type });
3092 return new ctor(source);
3093 };
3094}
3095function createWrappingReadableSource(readable, _a) {
3096 var type = (_a === void 0 ? {} : _a).type;
3097 assert(isReadableStream(readable));
3098 assert(readable.locked === false);
3099 type = parseReadableType(type);
3100 var source;
3101 if (type === 'bytes') {
3102 source = new WrappingReadableByteStreamSource(readable);
3103 }
3104 else {
3105 source = new WrappingReadableStreamDefaultSource(readable);
3106 }
3107 return source;
3108}
3109function parseReadableType(type) {
3110 var typeString = String(type);
3111 if (typeString === 'bytes') {
3112 return typeString;
3113 }
3114 else if (type === undefined) {
3115 return type;
3116 }
3117 else {
3118 throw new RangeError('Invalid type is specified');
3119 }
3120}
3121var AbstractWrappingReadableStreamSource = /** @class */ (function () {
3122 function AbstractWrappingReadableStreamSource(underlyingStream) {
3123 this._underlyingReader = undefined;
3124 this._readerMode = undefined;
3125 this._readableStreamController = undefined;
3126 this._pendingRead = undefined;
3127 this._underlyingStream = underlyingStream;
3128 // always keep a reader attached to detect close/error
3129 this._attachDefaultReader();
3130 }
3131 AbstractWrappingReadableStreamSource.prototype.start = function (controller) {
3132 this._readableStreamController = controller;
3133 };
3134 AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {
3135 assert(this._underlyingReader !== undefined);
3136 return this._underlyingReader.cancel(reason);
3137 };
3138 AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {
3139 if (this._readerMode === "default" /* DEFAULT */) {
3140 return;
3141 }
3142 this._detachReader();
3143 var reader = this._underlyingStream.getReader();
3144 this._readerMode = "default" /* DEFAULT */;
3145 this._attachReader(reader);
3146 };
3147 AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {
3148 var _this = this;
3149 assert(this._underlyingReader === undefined);
3150 this._underlyingReader = reader;
3151 var closed = this._underlyingReader.closed;
3152 if (!closed) {
3153 return;
3154 }
3155 closed
3156 .then(function () { return _this._finishPendingRead(); })
3157 .then(function () {
3158 if (reader === _this._underlyingReader) {
3159 _this._readableStreamController.close();
3160 }
3161 }, function (reason) {
3162 if (reader === _this._underlyingReader) {
3163 _this._readableStreamController.error(reason);
3164 }
3165 })
3166 .catch(noop$1);
3167 };
3168 AbstractWrappingReadableStreamSource.prototype._detachReader = function () {
3169 if (this._underlyingReader === undefined) {
3170 return;
3171 }
3172 this._underlyingReader.releaseLock();
3173 this._underlyingReader = undefined;
3174 this._readerMode = undefined;
3175 };
3176 AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {
3177 var _this = this;
3178 this._attachDefaultReader();
3179 // TODO Backpressure?
3180 var read = this._underlyingReader.read()
3181 .then(function (result) {
3182 var controller = _this._readableStreamController;
3183 if (result.done) {
3184 _this._tryClose();
3185 }
3186 else {
3187 controller.enqueue(result.value);
3188 }
3189 });
3190 this._setPendingRead(read);
3191 return read;
3192 };
3193 AbstractWrappingReadableStreamSource.prototype._tryClose = function () {
3194 try {
3195 this._readableStreamController.close();
3196 }
3197 catch (_a) {
3198 // already errored or closed
3199 }
3200 };
3201 AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {
3202 var _this = this;
3203 var pendingRead;
3204 var finishRead = function () {
3205 if (_this._pendingRead === pendingRead) {
3206 _this._pendingRead = undefined;
3207 }
3208 };
3209 this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);
3210 };
3211 AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {
3212 var _this = this;
3213 if (!this._pendingRead) {
3214 return undefined;
3215 }
3216 var afterRead = function () { return _this._finishPendingRead(); };
3217 return this._pendingRead.then(afterRead, afterRead);
3218 };
3219 return AbstractWrappingReadableStreamSource;
3220}());
3221var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {
3222 __extends(WrappingReadableStreamDefaultSource, _super);
3223 function WrappingReadableStreamDefaultSource() {
3224 return _super !== null && _super.apply(this, arguments) || this;
3225 }
3226 WrappingReadableStreamDefaultSource.prototype.pull = function () {
3227 return this._pullWithDefaultReader();
3228 };
3229 return WrappingReadableStreamDefaultSource;
3230}(AbstractWrappingReadableStreamSource));
3231function toUint8Array(view) {
3232 return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
3233}
3234function copyArrayBufferView(from, to) {
3235 var fromArray = toUint8Array(from);
3236 var toArray = toUint8Array(to);
3237 toArray.set(fromArray, 0);
3238}
3239var WrappingReadableByteStreamSource = /** @class */ (function (_super) {
3240 __extends(WrappingReadableByteStreamSource, _super);
3241 function WrappingReadableByteStreamSource(underlyingStream) {
3242 var _this = this;
3243 var supportsByob = supportsByobReader(underlyingStream);
3244 _this = _super.call(this, underlyingStream) || this;
3245 _this._supportsByob = supportsByob;
3246 return _this;
3247 }
3248 Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", {
3249 get: function () {
3250 return 'bytes';
3251 },
3252 enumerable: true,
3253 configurable: true
3254 });
3255 WrappingReadableByteStreamSource.prototype._attachByobReader = function () {
3256 if (this._readerMode === "byob" /* BYOB */) {
3257 return;
3258 }
3259 assert(this._supportsByob);
3260 this._detachReader();
3261 var reader = this._underlyingStream.getReader({ mode: 'byob' });
3262 this._readerMode = "byob" /* BYOB */;
3263 this._attachReader(reader);
3264 };
3265 WrappingReadableByteStreamSource.prototype.pull = function () {
3266 if (this._supportsByob) {
3267 var byobRequest = this._readableStreamController.byobRequest;
3268 if (byobRequest !== undefined) {
3269 return this._pullWithByobRequest(byobRequest);
3270 }
3271 }
3272 return this._pullWithDefaultReader();
3273 };
3274 WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {
3275 var _this = this;
3276 this._attachByobReader();
3277 // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly
3278 // create a separate buffer to read into, then copy that to byobRequest.view
3279 var buffer = new Uint8Array(byobRequest.view.byteLength);
3280 // TODO Backpressure?
3281 var read = this._underlyingReader.read(buffer)
3282 .then(function (result) {
3283 _this._readableStreamController;
3284 if (result.done) {
3285 _this._tryClose();
3286 byobRequest.respond(0);
3287 }
3288 else {
3289 copyArrayBufferView(result.value, byobRequest.view);
3290 byobRequest.respond(result.value.byteLength);
3291 }
3292 });
3293 this._setPendingRead(read);
3294 return read;
3295 };
3296 return WrappingReadableByteStreamSource;
3297}(AbstractWrappingReadableStreamSource));
3298
3299const isNode = typeof globalThis.process === 'object' &&
3300 typeof globalThis.process.versions === 'object';
3301
3302const NodeReadableStream = isNode && stream__default['default'].Readable;
3303
3304/**
3305 * Check whether data is a Stream, and if so of which type
3306 * @param {Any} input data to check
3307 * @returns {'web'|'ponyfill'|'node'|false}
3308 */
3309function isStream(input) {
3310 if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
3311 return 'web';
3312 }
3313 if (stream.ReadableStream.prototype.isPrototypeOf(input)) {
3314 return 'ponyfill';
3315 }
3316 if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
3317 return 'node';
3318 }
3319 return false;
3320}
3321
3322/**
3323 * Check whether data is a Uint8Array
3324 * @param {Any} input data to check
3325 * @returns {Boolean}
3326 */
3327function isUint8Array(input) {
3328 return Uint8Array.prototype.isPrototypeOf(input);
3329}
3330
3331/**
3332 * Concat Uint8Arrays
3333 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
3334 * @returns {Uint8array} Concatenated array
3335 */
3336function concatUint8Array(arrays) {
3337 if (arrays.length === 1) return arrays[0];
3338
3339 let totalLength = 0;
3340 for (let i = 0; i < arrays.length; i++) {
3341 if (!isUint8Array(arrays[i])) {
3342 throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
3343 }
3344
3345 totalLength += arrays[i].length;
3346 }
3347
3348 const result = new Uint8Array(totalLength);
3349 let pos = 0;
3350 arrays.forEach(function (element) {
3351 result.set(element, pos);
3352 pos += element.length;
3353 });
3354
3355 return result;
3356}
3357
3358const NodeBuffer = isNode && buffer__default['default'].Buffer;
3359const NodeReadableStream$1 = isNode && stream__default['default'].Readable;
3360
3361/**
3362 * Web / node stream conversion functions
3363 * From https://github.com/gwicke/node-web-streams
3364 */
3365
3366let nodeToWeb;
3367let webToNode;
3368
3369if (NodeReadableStream$1) {
3370
3371 /**
3372 * Convert a Node Readable Stream to a Web ReadableStream
3373 * @param {Readable} nodeStream
3374 * @returns {ReadableStream}
3375 */
3376 nodeToWeb = function(nodeStream) {
3377 return new stream.ReadableStream({
3378 start(controller) {
3379 nodeStream.pause();
3380 nodeStream.on('data', chunk => {
3381 if (NodeBuffer.isBuffer(chunk)) {
3382 chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
3383 }
3384 controller.enqueue(chunk);
3385 nodeStream.pause();
3386 });
3387 nodeStream.on('end', () => controller.close());
3388 nodeStream.on('error', e => controller.error(e));
3389 },
3390 pull() {
3391 nodeStream.resume();
3392 },
3393 cancel(reason) {
3394 nodeStream.pause();
3395 if (nodeStream.cancel) {
3396 return nodeStream.cancel(reason);
3397 }
3398 }
3399 });
3400 };
3401
3402
3403 class NodeReadable extends NodeReadableStream$1 {
3404 constructor(webStream, options) {
3405 super(options);
3406 this._webStream = webStream;
3407 this._reader = stream.getReader(webStream);
3408 this._reading = false;
3409 this._doneReadingPromise = Promise.resolve();
3410 this._cancelling = false;
3411 }
3412
3413 _read(size) {
3414 if (this._reading || this._cancelling) {
3415 return;
3416 }
3417 this._reading = true;
3418 const doRead = async () => {
3419 try {
3420 while (true) {
3421 const { done, value } = await this._reader.read();
3422 if (done) {
3423 this.push(null);
3424 break;
3425 }
3426 if (!this.push(value) || this._cancelling) {
3427 this._reading = false;
3428 break;
3429 }
3430 }
3431 } catch(e) {
3432 this.emit('error', e);
3433 }
3434 };
3435 this._doneReadingPromise = doRead();
3436 }
3437
3438 async cancel(reason) {
3439 this._cancelling = true;
3440 await this._doneReadingPromise;
3441 this._reader.releaseLock();
3442 return this._webStream.cancel(reason);
3443 }
3444 }
3445
3446 /**
3447 * Convert a Web ReadableStream to a Node Readable Stream
3448 * @param {ReadableStream} webStream
3449 * @returns {Readable}
3450 */
3451 webToNode = function(webStream) {
3452 return new NodeReadable(webStream);
3453 };
3454
3455}
3456
3457const doneReadingSet = new WeakSet();
3458const externalBuffer = Symbol('externalBuffer');
3459
3460/**
3461 * A wrapper class over the native ReadableStreamDefaultReader.
3462 * This additionally implements pushing back data on the stream, which
3463 * lets us implement peeking and a host of convenience functions.
3464 * It also lets you read data other than streams, such as a Uint8Array.
3465 * @class
3466 */
3467function Reader(input) {
3468 this.stream = input;
3469 if (input[externalBuffer]) {
3470 this[externalBuffer] = input[externalBuffer].slice();
3471 }
3472 let streamType = stream.isStream(input);
3473 if (streamType === 'node') {
3474 input = stream.nodeToWeb(input);
3475 }
3476 if (streamType) {
3477 const reader = input.getReader();
3478 this._read = reader.read.bind(reader);
3479 this._releaseLock = () => {
3480 reader.closed.catch(function() {});
3481 reader.releaseLock();
3482 };
3483 return;
3484 }
3485 let doneReading = false;
3486 this._read = async () => {
3487 if (doneReading || doneReadingSet.has(input)) {
3488 return { value: undefined, done: true };
3489 }
3490 doneReading = true;
3491 return { value: input, done: false };
3492 };
3493 this._releaseLock = () => {
3494 if (doneReading) {
3495 try {
3496 doneReadingSet.add(input);
3497 } catch(e) {}
3498 }
3499 };
3500}
3501
3502/**
3503 * Read a chunk of data.
3504 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
3505 * @async
3506 */
3507Reader.prototype.read = async function() {
3508 if (this[externalBuffer] && this[externalBuffer].length) {
3509 const value = this[externalBuffer].shift();
3510 return { done: false, value };
3511 }
3512 return this._read();
3513};
3514
3515/**
3516 * Allow others to read the stream.
3517 */
3518Reader.prototype.releaseLock = function() {
3519 if (this[externalBuffer]) {
3520 this.stream[externalBuffer] = this[externalBuffer];
3521 }
3522 this._releaseLock();
3523};
3524
3525/**
3526 * Read up to and including the first \n character.
3527 * @returns {Promise<String|Undefined>}
3528 * @async
3529 */
3530Reader.prototype.readLine = async function() {
3531 let buffer = [];
3532 let returnVal;
3533 while (!returnVal) {
3534 let { done, value } = await this.read();
3535 value += '';
3536 if (done) {
3537 if (buffer.length) return stream.concat(buffer);
3538 return;
3539 }
3540 const lineEndIndex = value.indexOf('\n') + 1;
3541 if (lineEndIndex) {
3542 returnVal = stream.concat(buffer.concat(value.substr(0, lineEndIndex)));
3543 buffer = [];
3544 }
3545 if (lineEndIndex !== value.length) {
3546 buffer.push(value.substr(lineEndIndex));
3547 }
3548 }
3549 this.unshift(...buffer);
3550 return returnVal;
3551};
3552
3553/**
3554 * Read a single byte/character.
3555 * @returns {Promise<Number|String|Undefined>}
3556 * @async
3557 */
3558Reader.prototype.readByte = async function() {
3559 const { done, value } = await this.read();
3560 if (done) return;
3561 const byte = value[0];
3562 this.unshift(stream.slice(value, 1));
3563 return byte;
3564};
3565
3566/**
3567 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
3568 * @returns {Promise<Uint8Array|String|Undefined>}
3569 * @async
3570 */
3571Reader.prototype.readBytes = async function(length) {
3572 const buffer = [];
3573 let bufferLength = 0;
3574 while (true) {
3575 const { done, value } = await this.read();
3576 if (done) {
3577 if (buffer.length) return stream.concat(buffer);
3578 return;
3579 }
3580 buffer.push(value);
3581 bufferLength += value.length;
3582 if (bufferLength >= length) {
3583 const bufferConcat = stream.concat(buffer);
3584 this.unshift(stream.slice(bufferConcat, length));
3585 return stream.slice(bufferConcat, 0, length);
3586 }
3587 }
3588};
3589
3590/**
3591 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
3592 * @returns {Promise<Uint8Array|String|Undefined>}
3593 * @async
3594 */
3595Reader.prototype.peekBytes = async function(length) {
3596 const bytes = await this.readBytes(length);
3597 this.unshift(bytes);
3598 return bytes;
3599};
3600
3601/**
3602 * Push data to the front of the stream.
3603 * Data must have been read in the last call to read*.
3604 * @param {...(Uint8Array|String|Undefined)} values
3605 */
3606Reader.prototype.unshift = function(...values) {
3607 if (!this[externalBuffer]) {
3608 this[externalBuffer] = [];
3609 }
3610 if (
3611 values.length === 1 && isUint8Array(values[0]) &&
3612 this[externalBuffer].length && values[0].length &&
3613 this[externalBuffer][0].byteOffset >= values[0].length
3614 ) {
3615 this[externalBuffer][0] = new Uint8Array(
3616 this[externalBuffer][0].buffer,
3617 this[externalBuffer][0].byteOffset - values[0].length,
3618 this[externalBuffer][0].byteLength + values[0].length
3619 );
3620 return;
3621 }
3622 this[externalBuffer].unshift(...values.filter(value => value && value.length));
3623};
3624
3625/**
3626 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
3627 * @param {Function} join
3628 * @returns {Promise<Uint8array|String|Any>} the return value of join()
3629 * @async
3630 */
3631Reader.prototype.readToEnd = async function(join=stream.concat) {
3632 const result = [];
3633 while (true) {
3634 const { done, value } = await this.read();
3635 if (done) break;
3636 result.push(value);
3637 }
3638 return join(result);
3639};
3640
3641const { ReadableStream: ReadableStream$1, WritableStream: WritableStream$1, TransformStream: TransformStream$1 } = globalThis.TransformStream ? globalThis : {
3642 ReadableStream: ReadableStream,
3643 WritableStream: WritableStream,
3644 TransformStream: TransformStream
3645};
3646
3647const toPonyfillReadable = globalThis.ReadableStream &&
3648 ReadableStream$1 !== globalThis.ReadableStream &&
3649 createReadableStreamWrapper(ReadableStream$1);
3650
3651const NodeBuffer$1 = isNode && buffer__default['default'].Buffer;
3652
3653/**
3654 * Convert data to Stream
3655 * @param {ReadableStream|Uint8array|String} input data to convert
3656 * @returns {ReadableStream} Converted data
3657 */
3658function toStream(input) {
3659 let streamType = isStream(input);
3660 if (streamType === 'node') {
3661 return nodeToWeb(input);
3662 }
3663 if (streamType === 'web' && toPonyfillReadable) {
3664 return toPonyfillReadable(input);
3665 }
3666 if (streamType) {
3667 return input;
3668 }
3669 return new ReadableStream$1({
3670 start(controller) {
3671 controller.enqueue(input);
3672 controller.close();
3673 }
3674 });
3675}
3676
3677/**
3678 * Concat a list of Uint8Arrays, Strings or Streams
3679 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
3680 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
3681 * @returns {Uint8array|String|ReadableStream} Concatenated array
3682 */
3683function concat(list) {
3684 if (list.some(isStream)) {
3685 return concatStream(list);
3686 }
3687 if (typeof list[0] === 'string') {
3688 return list.join('');
3689 }
3690 if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) {
3691 return NodeBuffer$1.concat(list);
3692 }
3693 return concatUint8Array(list);
3694}
3695
3696/**
3697 * Concat a list of Streams
3698 * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
3699 * @returns {ReadableStream} Concatenated list
3700 */
3701function concatStream(list) {
3702 list = list.map(toStream);
3703 const transform = transformWithCancel(async function(reason) {
3704 await Promise.all(transforms.map(stream => cancel(stream, reason)));
3705 });
3706 let prev = Promise.resolve();
3707 const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
3708 prev = prev.then(() => pipe(readable, transform.writable, {
3709 preventClose: i !== list.length - 1
3710 }));
3711 return prev;
3712 }));
3713 return transform.readable;
3714}
3715
3716/**
3717 * Get a Reader
3718 * @param {ReadableStream|Uint8array|String} input
3719 * @returns {Reader}
3720 */
3721function getReader(input) {
3722 return new Reader(input);
3723}
3724
3725/**
3726 * Get a Writer
3727 * @param {WritableStream} input
3728 * @returns {WritableStreamDefaultWriter}
3729 */
3730function getWriter(input) {
3731 const writer = input.getWriter();
3732 const releaseLock = writer.releaseLock;
3733 writer.releaseLock = () => {
3734 writer.closed.catch(function() {});
3735 releaseLock.call(writer);
3736 };
3737 return writer;
3738}
3739
3740/**
3741 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
3742 * @param {ReadableStream|Uint8array|String} input
3743 * @param {WritableStream} target
3744 * @param {Object} (optional) options
3745 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
3746 * @async
3747 */
3748async function pipe(input, target, options) {
3749 input = toStream(input);
3750 try {
3751 if (input[externalBuffer]) {
3752 const writer = getWriter(target);
3753 for (let i = 0; i < input[externalBuffer].length; i++) {
3754 await writer.ready;
3755 await writer.write(input[externalBuffer][i]);
3756 }
3757 writer.releaseLock();
3758 }
3759 return await input.pipeTo(target, options);
3760 } catch(e) {}
3761}
3762
3763/**
3764 * Pipe a readable stream through a transform stream.
3765 * @param {ReadableStream|Uint8array|String} input
3766 * @param {Object} (optional) options
3767 * @returns {ReadableStream} transformed stream
3768 */
3769function transformRaw(input, options) {
3770 const transformStream = new TransformStream$1(options);
3771 pipe(input, transformStream.writable);
3772 return transformStream.readable;
3773}
3774
3775/**
3776 * Create a cancelable TransformStream.
3777 * @param {Function} cancel
3778 * @returns {TransformStream}
3779 */
3780function transformWithCancel(cancel) {
3781 let pulled = false;
3782 let backpressureChangePromiseResolve;
3783 let outputController;
3784 return {
3785 readable: new ReadableStream$1({
3786 start(controller) {
3787 outputController = controller;
3788 },
3789 pull() {
3790 if (backpressureChangePromiseResolve) {
3791 backpressureChangePromiseResolve();
3792 } else {
3793 pulled = true;
3794 }
3795 },
3796 cancel
3797 }, {highWaterMark: 0}),
3798 writable: new WritableStream$1({
3799 write: async function(chunk) {
3800 outputController.enqueue(chunk);
3801 if (!pulled) {
3802 await new Promise(resolve => {
3803 backpressureChangePromiseResolve = resolve;
3804 });
3805 backpressureChangePromiseResolve = null;
3806 } else {
3807 pulled = false;
3808 }
3809 },
3810 close: outputController.close.bind(outputController),
3811 abort: outputController.error.bind(outputController)
3812 })
3813 };
3814}
3815
3816/**
3817 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
3818 * @param {ReadableStream|Uint8array|String} input
3819 * @param {Function} process
3820 * @param {Function} finish
3821 * @returns {ReadableStream|Uint8array|String}
3822 */
3823function transform(input, process = () => undefined, finish = () => undefined) {
3824 if (isStream(input)) {
3825 return transformRaw(input, {
3826 async transform(value, controller) {
3827 try {
3828 const result = await process(value);
3829 if (result !== undefined) controller.enqueue(result);
3830 } catch(e) {
3831 controller.error(e);
3832 }
3833 },
3834 async flush(controller) {
3835 try {
3836 const result = await finish();
3837 if (result !== undefined) controller.enqueue(result);
3838 } catch(e) {
3839 controller.error(e);
3840 }
3841 }
3842 });
3843 }
3844 const result1 = process(input);
3845 const result2 = finish();
3846 if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
3847 return result1 !== undefined ? result1 : result2;
3848}
3849
3850/**
3851 * Transform a stream using a helper function which is passed a readable and a writable stream.
3852 * This function also maintains the possibility to cancel the input stream,
3853 * and does so on cancelation of the output stream, despite cancelation
3854 * normally being impossible when the input stream is being read from.
3855 * @param {ReadableStream|Uint8array|String} input
3856 * @param {Function} fn
3857 * @returns {ReadableStream}
3858 */
3859function transformPair(input, fn) {
3860 let incomingTransformController;
3861 const incoming = new TransformStream$1({
3862 start(controller) {
3863 incomingTransformController = controller;
3864 }
3865 });
3866
3867 const pipeDonePromise = pipe(input, incoming.writable);
3868
3869 const outgoing = transformWithCancel(async function() {
3870 incomingTransformController.error(new Error('Readable side was canceled.'));
3871 await pipeDonePromise;
3872 await new Promise(setTimeout);
3873 });
3874 fn(incoming.readable, outgoing.writable);
3875 return outgoing.readable;
3876}
3877
3878/**
3879 * Parse a stream using a helper function which is passed a Reader.
3880 * The reader additionally has a remainder() method which returns a
3881 * stream pointing to the remainder of input, and is linked to input
3882 * for cancelation.
3883 * @param {ReadableStream|Uint8array|String} input
3884 * @param {Function} fn
3885 * @returns {Any} the return value of fn()
3886 */
3887function parse(input, fn) {
3888 let returnValue;
3889 const transformed = transformPair(input, (readable, writable) => {
3890 const reader = getReader(readable);
3891 reader.remainder = () => {
3892 reader.releaseLock();
3893 pipe(readable, writable);
3894 return transformed;
3895 };
3896 returnValue = fn(reader);
3897 });
3898 return returnValue;
3899}
3900
3901/**
3902 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
3903 * Reading either of the two returned streams will pull from the input stream.
3904 * The input stream will only be canceled if both of the returned streams are canceled.
3905 * @param {ReadableStream|Uint8array|String} input
3906 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
3907 */
3908function tee(input) {
3909 if (isStream(input)) {
3910 const teed = toStream(input).tee();
3911 teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
3912 return teed;
3913 }
3914 return [slice(input), slice(input)];
3915}
3916
3917/**
3918 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
3919 * Reading from the clone will pull from the input stream.
3920 * The input stream will only be canceled if both the clone and the input stream are canceled.
3921 * @param {ReadableStream|Uint8array|String} input
3922 * @returns {ReadableStream|Uint8array|String} cloned input
3923 */
3924function clone(input) {
3925 if (isStream(input)) {
3926 const teed = tee(input);
3927 overwrite(input, teed[0]);
3928 return teed[1];
3929 }
3930 return slice(input);
3931}
3932
3933/**
3934 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
3935 * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
3936 * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
3937 * If the input stream is canceled, the clone will be errored.
3938 * @param {ReadableStream|Uint8array|String} input
3939 * @returns {ReadableStream|Uint8array|String} cloned input
3940 */
3941function passiveClone(input) {
3942 if (isStream(input)) {
3943 return new ReadableStream$1({
3944 start(controller) {
3945 const transformed = transformPair(input, async (readable, writable) => {
3946 const reader = getReader(readable);
3947 const writer = getWriter(writable);
3948 try {
3949 while (true) {
3950 await writer.ready;
3951 const { done, value } = await reader.read();
3952 if (done) {
3953 try { controller.close(); } catch(e) {}
3954 await writer.close();
3955 return;
3956 }
3957 try { controller.enqueue(value); } catch(e) {}
3958 await writer.write(value);
3959 }
3960 } catch(e) {
3961 controller.error(e);
3962 await writer.abort(e);
3963 }
3964 });
3965 overwrite(input, transformed);
3966 }
3967 });
3968 }
3969 return slice(input);
3970}
3971
3972/**
3973 * Modify a stream object to point to a different stream object.
3974 * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
3975 * @param {ReadableStream} input
3976 * @param {ReadableStream} clone
3977 */
3978function overwrite(input, clone) {
3979 // Overwrite input.getReader, input.locked, etc to point to clone
3980 Object.entries(Object.getOwnPropertyDescriptors(ReadableStream$1.prototype)).forEach(([name, descriptor]) => {
3981 if (name === 'constructor') {
3982 return;
3983 }
3984 if (descriptor.value) {
3985 descriptor.value = descriptor.value.bind(clone);
3986 } else {
3987 descriptor.get = descriptor.get.bind(clone);
3988 }
3989 Object.defineProperty(input, name, descriptor);
3990 });
3991}
3992
3993/**
3994 * Return a stream pointing to a part of the input stream.
3995 * @param {ReadableStream|Uint8array|String} input
3996 * @returns {ReadableStream|Uint8array|String} clone
3997 */
3998function slice(input, begin=0, end=Infinity) {
3999 if (isStream(input)) {
4000 if (begin >= 0 && end >= 0) {
4001 let bytesRead = 0;
4002 return transformRaw(input, {
4003 transform(value, controller) {
4004 if (bytesRead < end) {
4005 if (bytesRead + value.length >= begin) {
4006 controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
4007 }
4008 bytesRead += value.length;
4009 } else {
4010 controller.terminate();
4011 }
4012 }
4013 });
4014 }
4015 if (begin < 0 && (end < 0 || end === Infinity)) {
4016 let lastBytes = [];
4017 return transform(input, value => {
4018 if (value.length >= -begin) lastBytes = [value];
4019 else lastBytes.push(value);
4020 }, () => slice(concat(lastBytes), begin, end));
4021 }
4022 if (begin === 0 && end < 0) {
4023 let lastBytes;
4024 return transform(input, value => {
4025 const returnValue = lastBytes ? concat([lastBytes, value]) : value;
4026 if (returnValue.length >= -end) {
4027 lastBytes = slice(returnValue, end);
4028 return slice(returnValue, begin, end);
4029 } else {
4030 lastBytes = returnValue;
4031 }
4032 });
4033 }
4034 console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
4035 return fromAsync(async () => slice(await readToEnd(input), begin, end));
4036 }
4037 if (input[externalBuffer]) {
4038 input = concat(input[externalBuffer].concat([input]));
4039 }
4040 if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) {
4041 if (end === Infinity) end = input.length;
4042 return input.subarray(begin, end);
4043 }
4044 return input.slice(begin, end);
4045}
4046
4047/**
4048 * Read a stream to the end and return its contents, concatenated by the concat function (defaults to concat).
4049 * @param {ReadableStream|Uint8array|String} input
4050 * @param {Function} concat
4051 * @returns {Promise<Uint8array|String|Any>} the return value of concat()
4052 * @async
4053 */
4054async function readToEnd(input, concat) {
4055 if (isStream(input)) {
4056 return getReader(input).readToEnd(concat);
4057 }
4058 return input;
4059}
4060
4061/**
4062 * Cancel a stream.
4063 * @param {ReadableStream|Uint8array|String} input
4064 * @param {Any} reason
4065 * @returns {Promise<Any>} indicates when the stream has been canceled
4066 * @async
4067 */
4068async function cancel(input, reason) {
4069 if (isStream(input) && input.cancel) {
4070 return input.cancel(reason);
4071 }
4072}
4073
4074/**
4075 * Convert an async function to a Stream. When the function returns, its return value is enqueued to the stream.
4076 * @param {Function} fn
4077 * @returns {ReadableStream}
4078 */
4079function fromAsync(fn) {
4080 return new ReadableStream$1({
4081 pull: async controller => {
4082 try {
4083 controller.enqueue(await fn());
4084 controller.close();
4085 } catch(e) {
4086 controller.error(e);
4087 }
4088 }
4089 });
4090}
4091
4092
4093var stream = { ReadableStream: ReadableStream$1, WritableStream: WritableStream$1, TransformStream: TransformStream$1, isStream, isUint8Array, toStream, concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb, webToNode };
4094
4095/* eslint-disable new-cap */
4096
4097/**
4098 * @fileoverview
4099 * BigInteger implementation of basic operations
4100 * that wraps the native BigInt library.
4101 * Operations are not constant time,
4102 * but we try and limit timing leakage where we can
4103 * @module biginteger/native
4104 * @private
4105 */
4106
4107/**
4108 * @private
4109 */
4110class BigInteger {
4111 /**
4112 * Get a BigInteger (input must be big endian for strings and arrays)
4113 * @param {Number|String|Uint8Array} n - Value to convert
4114 * @throws {Error} on null or undefined input
4115 */
4116 constructor(n) {
4117 if (n === undefined) {
4118 throw new Error('Invalid BigInteger input');
4119 }
4120
4121 if (n instanceof Uint8Array) {
4122 const bytes = n;
4123 const hex = new Array(bytes.length);
4124 for (let i = 0; i < bytes.length; i++) {
4125 const hexByte = bytes[i].toString(16);
4126 hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
4127 }
4128 this.value = BigInt('0x0' + hex.join(''));
4129 } else {
4130 this.value = BigInt(n);
4131 }
4132 }
4133
4134 clone() {
4135 return new BigInteger(this.value);
4136 }
4137
4138 /**
4139 * BigInteger increment in place
4140 */
4141 iinc() {
4142 this.value++;
4143 return this;
4144 }
4145
4146 /**
4147 * BigInteger increment
4148 * @returns {BigInteger} this + 1.
4149 */
4150 inc() {
4151 return this.clone().iinc();
4152 }
4153
4154 /**
4155 * BigInteger decrement in place
4156 */
4157 idec() {
4158 this.value--;
4159 return this;
4160 }
4161
4162 /**
4163 * BigInteger decrement
4164 * @returns {BigInteger} this - 1.
4165 */
4166 dec() {
4167 return this.clone().idec();
4168 }
4169
4170 /**
4171 * BigInteger addition in place
4172 * @param {BigInteger} x - Value to add
4173 */
4174 iadd(x) {
4175 this.value += x.value;
4176 return this;
4177 }
4178
4179 /**
4180 * BigInteger addition
4181 * @param {BigInteger} x - Value to add
4182 * @returns {BigInteger} this + x.
4183 */
4184 add(x) {
4185 return this.clone().iadd(x);
4186 }
4187
4188 /**
4189 * BigInteger subtraction in place
4190 * @param {BigInteger} x - Value to subtract
4191 */
4192 isub(x) {
4193 this.value -= x.value;
4194 return this;
4195 }
4196
4197 /**
4198 * BigInteger subtraction
4199 * @param {BigInteger} x - Value to subtract
4200 * @returns {BigInteger} this - x.
4201 */
4202 sub(x) {
4203 return this.clone().isub(x);
4204 }
4205
4206 /**
4207 * BigInteger multiplication in place
4208 * @param {BigInteger} x - Value to multiply
4209 */
4210 imul(x) {
4211 this.value *= x.value;
4212 return this;
4213 }
4214
4215 /**
4216 * BigInteger multiplication
4217 * @param {BigInteger} x - Value to multiply
4218 * @returns {BigInteger} this * x.
4219 */
4220 mul(x) {
4221 return this.clone().imul(x);
4222 }
4223
4224 /**
4225 * Compute value modulo m, in place
4226 * @param {BigInteger} m - Modulo
4227 */
4228 imod(m) {
4229 this.value %= m.value;
4230 if (this.isNegative()) {
4231 this.iadd(m);
4232 }
4233 return this;
4234 }
4235
4236 /**
4237 * Compute value modulo m
4238 * @param {BigInteger} m - Modulo
4239 * @returns {BigInteger} this mod m.
4240 */
4241 mod(m) {
4242 return this.clone().imod(m);
4243 }
4244
4245 /**
4246 * Compute modular exponentiation using square and multiply
4247 * @param {BigInteger} e - Exponent
4248 * @param {BigInteger} n - Modulo
4249 * @returns {BigInteger} this ** e mod n.
4250 */
4251 modExp(e, n) {
4252 if (n.isZero()) throw Error("Modulo cannot be zero");
4253 if (n.isOne()) return new BigInteger(0);
4254 if (e.isNegative()) throw Error("Unsopported negative exponent");
4255
4256 let exp = e.value;
4257 let x = this.value;
4258
4259 x %= n.value;
4260 let r = BigInt(1);
4261 while (exp > BigInt(0)) {
4262 const lsb = exp & BigInt(1);
4263 exp >>= BigInt(1); // e / 2
4264 // Always compute multiplication step, to reduce timing leakage
4265 const rx = (r * x) % n.value;
4266 // Update r only if lsb is 1 (odd exponent)
4267 r = lsb ? rx : r;
4268 x = (x * x) % n.value; // Square
4269 }
4270 return new BigInteger(r);
4271 }
4272
4273
4274 /**
4275 * Compute the inverse of this value modulo n
4276 * Note: this and and n must be relatively prime
4277 * @param {BigInteger} n - Modulo
4278 * @returns {BigInteger} x such that this*x = 1 mod n
4279 * @throws {Error} if the inverse does not exist
4280 */
4281 modInv(n) {
4282 const { gcd, x } = this._egcd(n);
4283 if (!gcd.isOne()) {
4284 throw new Error('Inverse does not exist');
4285 }
4286 return x.add(n).mod(n);
4287 }
4288
4289 /**
4290 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
4291 * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
4292 * @param {BigInteger} b - Second operand
4293 * @returns {{ gcd, x, y: BigInteger }}
4294 */
4295 _egcd(b) {
4296 let x = BigInt(0);
4297 let y = BigInt(1);
4298 let xPrev = BigInt(1);
4299 let yPrev = BigInt(0);
4300
4301 let a = this.value;
4302 b = b.value;
4303
4304 while (b !== BigInt(0)) {
4305 const q = a / b;
4306 let tmp = x;
4307 x = xPrev - q * x;
4308 xPrev = tmp;
4309
4310 tmp = y;
4311 y = yPrev - q * y;
4312 yPrev = tmp;
4313
4314 tmp = b;
4315 b = a % b;
4316 a = tmp;
4317 }
4318
4319 return {
4320 x: new BigInteger(xPrev),
4321 y: new BigInteger(yPrev),
4322 gcd: new BigInteger(a)
4323 };
4324 }
4325
4326 /**
4327 * Compute greatest common divisor between this and n
4328 * @param {BigInteger} b - Operand
4329 * @returns {BigInteger} gcd
4330 */
4331 gcd(b) {
4332 let a = this.value;
4333 b = b.value;
4334 while (b !== BigInt(0)) {
4335 const tmp = b;
4336 b = a % b;
4337 a = tmp;
4338 }
4339 return new BigInteger(a);
4340 }
4341
4342 /**
4343 * Shift this to the left by x, in place
4344 * @param {BigInteger} x - Shift value
4345 */
4346 ileftShift(x) {
4347 this.value <<= x.value;
4348 return this;
4349 }
4350
4351 /**
4352 * Shift this to the left by x
4353 * @param {BigInteger} x - Shift value
4354 * @returns {BigInteger} this << x.
4355 */
4356 leftShift(x) {
4357 return this.clone().ileftShift(x);
4358 }
4359
4360 /**
4361 * Shift this to the right by x, in place
4362 * @param {BigInteger} x - Shift value
4363 */
4364 irightShift(x) {
4365 this.value >>= x.value;
4366 return this;
4367 }
4368
4369 /**
4370 * Shift this to the right by x
4371 * @param {BigInteger} x - Shift value
4372 * @returns {BigInteger} this >> x.
4373 */
4374 rightShift(x) {
4375 return this.clone().irightShift(x);
4376 }
4377
4378 /**
4379 * Whether this value is equal to x
4380 * @param {BigInteger} x
4381 * @returns {Boolean}
4382 */
4383 equal(x) {
4384 return this.value === x.value;
4385 }
4386
4387 /**
4388 * Whether this value is less than x
4389 * @param {BigInteger} x
4390 * @returns {Boolean}
4391 */
4392 lt(x) {
4393 return this.value < x.value;
4394 }
4395
4396 /**
4397 * Whether this value is less than or equal to x
4398 * @param {BigInteger} x
4399 * @returns {Boolean}
4400 */
4401 lte(x) {
4402 return this.value <= x.value;
4403 }
4404
4405 /**
4406 * Whether this value is greater than x
4407 * @param {BigInteger} x
4408 * @returns {Boolean}
4409 */
4410 gt(x) {
4411 return this.value > x.value;
4412 }
4413
4414 /**
4415 * Whether this value is greater than or equal to x
4416 * @param {BigInteger} x
4417 * @returns {Boolean}
4418 */
4419 gte(x) {
4420 return this.value >= x.value;
4421 }
4422
4423 isZero() {
4424 return this.value === BigInt(0);
4425 }
4426
4427 isOne() {
4428 return this.value === BigInt(1);
4429 }
4430
4431 isNegative() {
4432 return this.value < BigInt(0);
4433 }
4434
4435 isEven() {
4436 return !(this.value & BigInt(1));
4437 }
4438
4439 abs() {
4440 const res = this.clone();
4441 if (this.isNegative()) {
4442 res.value = -res.value;
4443 }
4444 return res;
4445 }
4446
4447 /**
4448 * Get this value as a string
4449 * @returns {String} this value.
4450 */
4451 toString() {
4452 return this.value.toString();
4453 }
4454
4455 /**
4456 * Get this value as an exact Number (max 53 bits)
4457 * Fails if this value is too large
4458 * @returns {Number}
4459 */
4460 toNumber() {
4461 const number = Number(this.value);
4462 if (number > Number.MAX_SAFE_INTEGER) {
4463 // We throw and error to conform with the bn.js implementation
4464 throw new Error('Number can only safely store up to 53 bits');
4465 }
4466 return number;
4467 }
4468
4469 /**
4470 * Get value of i-th bit
4471 * @param {Number} i - Bit index
4472 * @returns {Number} Bit value.
4473 */
4474 getBit(i) {
4475 const bit = (this.value >> BigInt(i)) & BigInt(1);
4476 return (bit === BigInt(0)) ? 0 : 1;
4477 }
4478
4479 /**
4480 * Compute bit length
4481 * @returns {Number} Bit length.
4482 */
4483 bitLength() {
4484 const zero = new BigInteger(0);
4485 const one = new BigInteger(1);
4486 const negOne = new BigInteger(-1);
4487
4488 // -1n >> -1n is -1n
4489 // 1n >> 1n is 0n
4490 const target = this.isNegative() ? negOne : zero;
4491 let bitlen = 1;
4492 const tmp = this.clone();
4493 while (!tmp.irightShift(one).equal(target)) {
4494 bitlen++;
4495 }
4496 return bitlen;
4497 }
4498
4499 /**
4500 * Compute byte length
4501 * @returns {Number} Byte length.
4502 */
4503 byteLength() {
4504 const zero = new BigInteger(0);
4505 const negOne = new BigInteger(-1);
4506
4507 const target = this.isNegative() ? negOne : zero;
4508 const eight = new BigInteger(8);
4509 let len = 1;
4510 const tmp = this.clone();
4511 while (!tmp.irightShift(eight).equal(target)) {
4512 len++;
4513 }
4514 return len;
4515 }
4516
4517 /**
4518 * Get Uint8Array representation of this number
4519 * @param {String} endian - Endianess of output array (defaults to 'be')
4520 * @param {Number} length - Of output array
4521 * @returns {Uint8Array}
4522 */
4523 toUint8Array(endian = 'be', length) {
4524 // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
4525 // this is faster than shift+mod iterations
4526 let hex = this.value.toString(16);
4527 if (hex.length % 2 === 1) {
4528 hex = '0' + hex;
4529 }
4530
4531 const rawLength = hex.length / 2;
4532 const bytes = new Uint8Array(length || rawLength);
4533 // parse hex
4534 const offset = length ? (length - rawLength) : 0;
4535 let i = 0;
4536 while (i < rawLength) {
4537 bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
4538 i++;
4539 }
4540
4541 if (endian !== 'be') {
4542 bytes.reverse();
4543 }
4544
4545 return bytes;
4546 }
4547}
4548
4549async function getBigInteger() {
4550 if (util.detectBigInt()) {
4551 return BigInteger;
4552 } else {
4553 const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; });
4554 return BigInteger;
4555 }
4556}
4557
4558const debugMode = globalThis.process && globalThis.process.env.NODE_ENV === 'development';
4559
4560const util = {
4561 isString: function(data) {
4562 return typeof data === 'string' || String.prototype.isPrototypeOf(data);
4563 },
4564
4565 isArray: function(data) {
4566 return Array.prototype.isPrototypeOf(data);
4567 },
4568
4569 isBigInteger: function(data) {
4570 return data !== null && typeof data === 'object' && data.value &&
4571 // eslint-disable-next-line valid-typeof
4572 (typeof data.value === 'bigint' || this.isBN(data.value));
4573 },
4574
4575 isBN: function(data) {
4576 return data !== null && typeof data === 'object' &&
4577 (data.constructor.name === 'BN' ||
4578 (data.constructor.wordSize === 26 && Array.isArray(data.words))); // taken from BN.isBN()
4579 },
4580
4581 isUint8Array: stream.isUint8Array,
4582
4583 isStream: stream.isStream,
4584
4585 /**
4586 * Convert MessagePorts back to ReadableStreams
4587 * @param {Object} obj
4588 * @returns {Object}
4589 */
4590 restoreStreams: function(obj, streaming) {
4591 if (Object.prototype.toString.call(obj) === '[object MessagePort]') {
4592 return new (streaming === 'web' ? globalThis.ReadableStream : stream.ReadableStream)({
4593 pull(controller) {
4594 return new Promise(resolve => {
4595 obj.onmessage = evt => {
4596 const { done, value, error } = evt.data;
4597 if (error) {
4598 controller.error(new Error(error));
4599 } else if (!done) {
4600 controller.enqueue(value);
4601 } else {
4602 controller.close();
4603 }
4604 resolve();
4605 };
4606 obj.postMessage({ action: 'read' });
4607 });
4608 },
4609 cancel() {
4610 return new Promise(resolve => {
4611 obj.onmessage = resolve;
4612 obj.postMessage({ action: 'cancel' });
4613 });
4614 }
4615 }, { highWaterMark: 0 });
4616 }
4617 if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
4618 Object.entries(obj).forEach(([key, value]) => { // recursively search all children
4619 obj[key] = util.restoreStreams(value, streaming);
4620 });
4621 }
4622 return obj;
4623 },
4624
4625 readNumber: function (bytes) {
4626 let n = 0;
4627 for (let i = 0; i < bytes.length; i++) {
4628 n += (256 ** i) * bytes[bytes.length - 1 - i];
4629 }
4630 return n;
4631 },
4632
4633 writeNumber: function (n, bytes) {
4634 const b = new Uint8Array(bytes);
4635 for (let i = 0; i < bytes; i++) {
4636 b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
4637 }
4638
4639 return b;
4640 },
4641
4642 readDate: function (bytes) {
4643 const n = util.readNumber(bytes);
4644 const d = new Date(n * 1000);
4645 return d;
4646 },
4647
4648 writeDate: function (time) {
4649 const numeric = Math.floor(time.getTime() / 1000);
4650
4651 return util.writeNumber(numeric, 4);
4652 },
4653
4654 normalizeDate: function (time = Date.now()) {
4655 return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
4656 },
4657
4658 /**
4659 * Create hex string from a binary
4660 * @param {String} str - String to convert
4661 * @returns {String} String containing the hexadecimal values.
4662 */
4663 strToHex: function (str) {
4664 if (str === null) {
4665 return "";
4666 }
4667 const r = [];
4668 const e = str.length;
4669 let c = 0;
4670 let h;
4671 while (c < e) {
4672 h = str.charCodeAt(c++).toString(16);
4673 while (h.length < 2) {
4674 h = "0" + h;
4675 }
4676 r.push("" + h);
4677 }
4678 return r.join('');
4679 },
4680
4681 /**
4682 * Create binary string from a hex encoded string
4683 * @param {String} str - Hex string to convert
4684 * @returns {String}
4685 */
4686 hexToStr: function (hex) {
4687 let str = '';
4688 for (let i = 0; i < hex.length; i += 2) {
4689 str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
4690 }
4691 return str;
4692 },
4693
4694 /**
4695 * Read one MPI from bytes in input
4696 * @param {Uint8Array} bytes - Input data to parse
4697 * @returns {Uint8Array} Parsed MPI.
4698 */
4699 readMPI: function (bytes) {
4700 const bits = (bytes[0] << 8) | bytes[1];
4701 const bytelen = (bits + 7) >>> 3;
4702 return bytes.subarray(2, 2 + bytelen);
4703 },
4704
4705 /**
4706 * Left-pad Uint8Array to length by adding 0x0 bytes
4707 * @param {Uint8Array} bytes - Data to pad
4708 * @param {Number} length - Padded length
4709 * @returns {Uint8Array} Padded bytes.
4710 */
4711 leftPad(bytes, length) {
4712 const padded = new Uint8Array(length);
4713 const offset = length - bytes.length;
4714 padded.set(bytes, offset);
4715 return padded;
4716 },
4717
4718 /**
4719 * Convert a Uint8Array to an MPI-formatted Uint8Array.
4720 * @param {Uint8Array} bin - An array of 8-bit integers to convert
4721 * @returns {Uint8Array} MPI-formatted Uint8Array.
4722 */
4723 uint8ArrayToMpi: function (bin) {
4724 let i; // index of leading non-zero byte
4725 for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;
4726 if (i === bin.length) {
4727 throw new Error('Zero MPI');
4728 }
4729 const stripped = bin.subarray(i);
4730 const size = (stripped.length - 1) * 8 + util.nbits(stripped[0]);
4731 const prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]);
4732 return util.concatUint8Array([prefix, stripped]);
4733 },
4734
4735 /**
4736 * Convert a hex string to an array of 8-bit integers
4737 * @param {String} hex - A hex string to convert
4738 * @returns {Uint8Array} An array of 8-bit integers.
4739 */
4740 hexToUint8Array: function (hex) {
4741 const result = new Uint8Array(hex.length >> 1);
4742 for (let k = 0; k < hex.length >> 1; k++) {
4743 result[k] = parseInt(hex.substr(k << 1, 2), 16);
4744 }
4745 return result;
4746 },
4747
4748 /**
4749 * Convert an array of 8-bit integers to a hex string
4750 * @param {Uint8Array} bytes - Array of 8-bit integers to convert
4751 * @returns {String} Hexadecimal representation of the array.
4752 */
4753 uint8ArrayToHex: function (bytes) {
4754 const r = [];
4755 const e = bytes.length;
4756 let c = 0;
4757 let h;
4758 while (c < e) {
4759 h = bytes[c++].toString(16);
4760 while (h.length < 2) {
4761 h = "0" + h;
4762 }
4763 r.push("" + h);
4764 }
4765 return r.join('');
4766 },
4767
4768 /**
4769 * Convert a string to an array of 8-bit integers
4770 * @param {String} str - String to convert
4771 * @returns {Uint8Array} An array of 8-bit integers.
4772 */
4773 strToUint8Array: function (str) {
4774 return stream.transform(str, str => {
4775 if (!util.isString(str)) {
4776 throw new Error('strToUint8Array: Data must be in the form of a string');
4777 }
4778
4779 const result = new Uint8Array(str.length);
4780 for (let i = 0; i < str.length; i++) {
4781 result[i] = str.charCodeAt(i);
4782 }
4783 return result;
4784 });
4785 },
4786
4787 /**
4788 * Convert an array of 8-bit integers to a string
4789 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
4790 * @returns {String} String representation of the array.
4791 */
4792 uint8ArrayToStr: function (bytes) {
4793 bytes = new Uint8Array(bytes);
4794 const result = [];
4795 const bs = 1 << 14;
4796 const j = bytes.length;
4797
4798 for (let i = 0; i < j; i += bs) {
4799 result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
4800 }
4801 return result.join('');
4802 },
4803
4804 /**
4805 * Convert a native javascript string to a Uint8Array of utf8 bytes
4806 * @param {String|ReadableStream} str - The string to convert
4807 * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
4808 */
4809 encodeUtf8: function (str) {
4810 const encoder = new TextEncoder('utf-8');
4811 // eslint-disable-next-line no-inner-declarations
4812 function process(value, lastChunk = false) {
4813 return encoder.encode(value, { stream: !lastChunk });
4814 }
4815 return stream.transform(str, process, () => process('', true));
4816 },
4817
4818 /**
4819 * Convert a Uint8Array of utf8 bytes to a native javascript string
4820 * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
4821 * @returns {String|ReadableStream} A native javascript string.
4822 */
4823 decodeUtf8: function (utf8) {
4824 const decoder = new TextDecoder('utf-8');
4825 // eslint-disable-next-line no-inner-declarations
4826 function process(value, lastChunk = false) {
4827 return decoder.decode(value, { stream: !lastChunk });
4828 }
4829 return stream.transform(utf8, process, () => process(new Uint8Array(), true));
4830 },
4831
4832 /**
4833 * Concat a list of Uint8Arrays, Strings or Streams
4834 * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
4835 * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
4836 * @returns {Uint8Array|String|ReadableStream} Concatenated array.
4837 */
4838 concat: stream.concat,
4839
4840 /**
4841 * Concat Uint8Arrays
4842 * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
4843 * @returns {Uint8Array} Concatenated array.
4844 */
4845 concatUint8Array: stream.concatUint8Array,
4846
4847 /**
4848 * Check Uint8Array equality
4849 * @param {Uint8Array} array1 - First array
4850 * @param {Uint8Array} array2 - Second array
4851 * @returns {Boolean} Equality.
4852 */
4853 equalsUint8Array: function (array1, array2) {
4854 if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
4855 throw new Error('Data must be in the form of a Uint8Array');
4856 }
4857
4858 if (array1.length !== array2.length) {
4859 return false;
4860 }
4861
4862 for (let i = 0; i < array1.length; i++) {
4863 if (array1[i] !== array2[i]) {
4864 return false;
4865 }
4866 }
4867 return true;
4868 },
4869
4870 /**
4871 * Calculates a 16bit sum of a Uint8Array by adding each character
4872 * codes modulus 65535
4873 * @param {Uint8Array} Uint8Array - To create a sum of
4874 * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
4875 */
4876 writeChecksum: function (text) {
4877 let s = 0;
4878 for (let i = 0; i < text.length; i++) {
4879 s = (s + text[i]) & 0xFFFF;
4880 }
4881 return util.writeNumber(s, 2);
4882 },
4883
4884 /**
4885 * Helper function to print a debug message. Debug
4886 * messages are only printed if
4887 * @param {String} str - String of the debug message
4888 */
4889 printDebug: function (str) {
4890 if (debugMode) {
4891 console.log(str);
4892 }
4893 },
4894
4895 /**
4896 * Helper function to print a debug message. Debug
4897 * messages are only printed if
4898 * Different than print_debug because will call Uint8ArrayToHex iff necessary.
4899 * @param {String} str - String of the debug message
4900 */
4901 printDebugHexArrayDump: function (str, arrToHex) {
4902 if (debugMode) {
4903 str += ': ' + util.uint8ArrayToHex(arrToHex);
4904 console.log(str);
4905 }
4906 },
4907
4908 /**
4909 * Helper function to print a debug message. Debug
4910 * messages are only printed if
4911 * Different than print_debug because will call strToHex iff necessary.
4912 * @param {String} str - String of the debug message
4913 */
4914 printDebugHexStrDump: function (str, strToHex) {
4915 if (debugMode) {
4916 str += util.strToHex(strToHex);
4917 console.log(str);
4918 }
4919 },
4920
4921 /**
4922 * Helper function to print a debug error. Debug
4923 * messages are only printed if
4924 * @param {String} str - String of the debug message
4925 */
4926 printDebugError: function (error) {
4927 if (debugMode) {
4928 console.error(error);
4929 }
4930 },
4931
4932 /**
4933 * Read a stream to the end and print it to the console when it's closed.
4934 * @param {String} str - String of the debug message
4935 * @param {ReadableStream|Uint8array|String} input - Stream to print
4936 * @param {Function} concat - Function to concatenate chunks of the stream (defaults to util.concat).
4937 */
4938 printEntireStream: function (str, input, concat) {
4939 stream.readToEnd(stream.clone(input), concat).then(result => {
4940 console.log(str + ': ', result);
4941 });
4942 },
4943
4944 // returns bit length of the integer x
4945 nbits: function (x) {
4946 let r = 1;
4947 let t = x >>> 16;
4948 if (t !== 0) {
4949 x = t;
4950 r += 16;
4951 }
4952 t = x >> 8;
4953 if (t !== 0) {
4954 x = t;
4955 r += 8;
4956 }
4957 t = x >> 4;
4958 if (t !== 0) {
4959 x = t;
4960 r += 4;
4961 }
4962 t = x >> 2;
4963 if (t !== 0) {
4964 x = t;
4965 r += 2;
4966 }
4967 t = x >> 1;
4968 if (t !== 0) {
4969 x = t;
4970 r += 1;
4971 }
4972 return r;
4973 },
4974
4975 /**
4976 * If S[1] == 0, then double(S) == (S[2..128] || 0);
4977 * otherwise, double(S) == (S[2..128] || 0) xor
4978 * (zeros(120) || 10000111).
4979 *
4980 * Both OCB and EAX (through CMAC) require this function to be constant-time.
4981 *
4982 * @param {Uint8Array} data
4983 */
4984 double: function(data) {
4985 const double_var = new Uint8Array(data.length);
4986 const last = data.length - 1;
4987 for (let i = 0; i < last; i++) {
4988 double_var[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
4989 }
4990 double_var[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
4991 return double_var;
4992 },
4993
4994 /**
4995 * Shift a Uint8Array to the right by n bits
4996 * @param {Uint8Array} array - The array to shift
4997 * @param {Integer} bits - Amount of bits to shift (MUST be smaller
4998 * than 8)
4999 * @returns {String} Resulting array.
5000 */
5001 shiftRight: function (array, bits) {
5002 if (bits) {
5003 for (let i = array.length - 1; i >= 0; i--) {
5004 array[i] >>= bits;
5005 if (i > 0) {
5006 array[i] |= (array[i - 1] << (8 - bits));
5007 }
5008 }
5009 }
5010 return array;
5011 },
5012
5013 /**
5014 * Get native Web Cryptography api, only the current version of the spec.
5015 * @returns {Object} The SubtleCrypto api or 'undefined'.
5016 */
5017 getWebCrypto: function() {
5018 return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
5019 },
5020
5021 /**
5022 * Detect Node.js runtime.
5023 */
5024 detectNode: function() {
5025 return typeof globalThis.process === 'object' &&
5026 typeof globalThis.process.versions === 'object';
5027 },
5028
5029 /**
5030 * Detect native BigInt support
5031 */
5032 detectBigInt: () => typeof BigInt !== 'undefined',
5033
5034 /**
5035 * Get BigInteger class
5036 * It wraps the native BigInt type if it's available
5037 * Otherwise it relies on bn.js
5038 * @returns {BigInteger}
5039 * @async
5040 */
5041 getBigInteger,
5042
5043 /**
5044 * Get native Node.js crypto api.
5045 * @returns {Object} The crypto module or 'undefined'.
5046 */
5047 getNodeCrypto: function() {
5048 return crypto__default['default'];
5049 },
5050
5051 getNodeZlib: function() {
5052 return zlib__default['default'];
5053 },
5054
5055 /**
5056 * Get native Node.js Buffer constructor. This should be used since
5057 * Buffer is not available under browserify.
5058 * @returns {Function} The Buffer constructor or 'undefined'.
5059 */
5060 getNodeBuffer: function() {
5061 return (buffer__default['default'] || {}).Buffer;
5062 },
5063
5064 getNodeStream: function() {
5065 return (stream__default['default'] || {}).Readable;
5066 },
5067
5068 getHardwareConcurrency: function() {
5069 if (util.detectNode()) {
5070 const os = os__default['default'];
5071 return os.cpus().length;
5072 }
5073
5074 return navigator.hardwareConcurrency || 1;
5075 },
5076
5077 isEmailAddress: function(data) {
5078 if (!util.isString(data)) {
5079 return false;
5080 }
5081 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]+)))$/;
5082 return re.test(data);
5083 },
5084
5085 /**
5086 * Normalize line endings to <CR><LF>
5087 * Support any encoding where CR=0x0D, LF=0x0A
5088 */
5089 canonicalizeEOL: function(data) {
5090 const CR = 13;
5091 const LF = 10;
5092 let carryOverCR = false;
5093
5094 return stream.transform(data, bytes => {
5095 if (carryOverCR) {
5096 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
5097 }
5098
5099 if (bytes[bytes.length - 1] === CR) {
5100 carryOverCR = true;
5101 bytes = bytes.subarray(0, -1);
5102 } else {
5103 carryOverCR = false;
5104 }
5105
5106 let index;
5107 const indices = [];
5108 for (let i = 0; ; i = index) {
5109 index = bytes.indexOf(LF, i) + 1;
5110 if (index) {
5111 if (bytes[index - 2] !== CR) indices.push(index);
5112 } else {
5113 break;
5114 }
5115 }
5116 if (!indices.length) {
5117 return bytes;
5118 }
5119
5120 const normalized = new Uint8Array(bytes.length + indices.length);
5121 let j = 0;
5122 for (let i = 0; i < indices.length; i++) {
5123 const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
5124 normalized.set(sub, j);
5125 j += sub.length;
5126 normalized[j - 1] = CR;
5127 normalized[j] = LF;
5128 j++;
5129 }
5130 normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
5131 return normalized;
5132 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
5133 },
5134
5135 /**
5136 * Convert line endings from canonicalized <CR><LF> to native <LF>
5137 * Support any encoding where CR=0x0D, LF=0x0A
5138 */
5139 nativeEOL: function(data) {
5140 const CR = 13;
5141 const LF = 10;
5142 let carryOverCR = false;
5143
5144 return stream.transform(data, bytes => {
5145 if (carryOverCR && bytes[0] !== LF) {
5146 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
5147 } else {
5148 bytes = new Uint8Array(bytes); // Don't mutate passed bytes
5149 }
5150
5151 if (bytes[bytes.length - 1] === CR) {
5152 carryOverCR = true;
5153 bytes = bytes.subarray(0, -1);
5154 } else {
5155 carryOverCR = false;
5156 }
5157
5158 let index;
5159 let j = 0;
5160 for (let i = 0; i !== bytes.length; i = index) {
5161 index = bytes.indexOf(CR, i) + 1;
5162 if (!index) index = bytes.length;
5163 const last = index - (bytes[index] === LF ? 1 : 0);
5164 if (i) bytes.copyWithin(j, i, last);
5165 j += last - i;
5166 }
5167 return bytes.subarray(0, j);
5168 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
5169 },
5170
5171 /**
5172 * Remove trailing spaces and tabs from each line
5173 */
5174 removeTrailingSpaces: function(text) {
5175 return text.split('\n').map(line => {
5176 let i = line.length - 1;
5177 for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--);
5178 return line.substr(0, i + 1);
5179 }).join('\n');
5180 },
5181
5182 wrapError: function(message, error) {
5183 if (!error) {
5184 return new Error(message);
5185 }
5186
5187 // update error message
5188 try {
5189 error.message = message + ': ' + error.message;
5190 } catch (e) {}
5191
5192 return error;
5193 }
5194};
5195
5196/* OpenPGP radix-64/base64 string encoding/decoding
5197 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
5198 * version 1.0, check www.haneWIN.de for the latest version
5199 *
5200 * This software is provided as-is, without express or implied warranty.
5201 * Permission to use, copy, modify, distribute or sell this software, with or
5202 * without fee, for any purpose and by any individual or organization, is hereby
5203 * granted, provided that the above copyright notice and this paragraph appear
5204 * in all copies. Distribution as a part of an application or binary must
5205 * include the above copyright notice in the documentation and/or other materials
5206 * provided with the application or distribution.
5207 */
5208
5209const Buffer = util.getNodeBuffer();
5210
5211let encodeChunk;
5212let decodeChunk;
5213if (Buffer) {
5214 encodeChunk = buf => Buffer.from(buf).toString('base64');
5215 decodeChunk = str => {
5216 const b = Buffer.from(str, 'base64');
5217 return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
5218 };
5219} else {
5220 encodeChunk = buf => btoa(util.uint8ArrayToStr(buf));
5221 decodeChunk = str => util.strToUint8Array(atob(str));
5222}
5223
5224/**
5225 * Convert binary array to radix-64
5226 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
5227 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
5228 * @static
5229 */
5230function encode(data) {
5231 let buf = new Uint8Array();
5232 return stream.transform(data, value => {
5233 buf = util.concatUint8Array([buf, value]);
5234 const r = [];
5235 const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
5236 const lines = Math.floor(buf.length / bytesPerLine);
5237 const bytes = lines * bytesPerLine;
5238 const encoded = encodeChunk(buf.subarray(0, bytes));
5239 for (let i = 0; i < lines; i++) {
5240 r.push(encoded.substr(i * 60, 60));
5241 r.push('\n');
5242 }
5243 buf = buf.subarray(bytes);
5244 return r.join('');
5245 }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
5246}
5247
5248/**
5249 * Convert radix-64 to binary array
5250 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
5251 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
5252 * @static
5253 */
5254function decode(data) {
5255 let buf = '';
5256 return stream.transform(data, value => {
5257 buf += value;
5258
5259 // Count how many whitespace characters there are in buf
5260 let spaces = 0;
5261 const spacechars = [' ', '\t', '\r', '\n'];
5262 for (let i = 0; i < spacechars.length; i++) {
5263 const spacechar = spacechars[i];
5264 for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
5265 spaces++;
5266 }
5267 }
5268
5269 // Backtrack until we have 4n non-whitespace characters
5270 // that we can safely base64-decode
5271 let length = buf.length;
5272 for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
5273 if (spacechars.includes(buf[length])) spaces--;
5274 }
5275
5276 const decoded = decodeChunk(buf.substr(0, length));
5277 buf = buf.substr(length);
5278 return decoded;
5279 }, () => decodeChunk(buf));
5280}
5281
5282/**
5283 * Convert a Base-64 encoded string an array of 8-bit integer
5284 *
5285 * Note: accepts both Radix-64 and URL-safe strings
5286 * @param {String} base64 - Base-64 encoded string to convert
5287 * @returns {Uint8Array} An array of 8-bit integers.
5288 */
5289function b64ToUint8Array(base64) {
5290 return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
5291}
5292
5293/**
5294 * Convert an array of 8-bit integer to a Base-64 encoded string
5295 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
5296 * @param {bool} url - If true, output is URL-safe
5297 * @returns {String} Base-64 encoded string.
5298 */
5299function uint8ArrayToB64(bytes, url) {
5300 let encoded = encode(bytes).replace(/[\r\n]/g, '');
5301 if (url) {
5302 encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
5303 }
5304 return encoded;
5305}
5306
5307/**
5308 * @module enums
5309 */
5310
5311const byValue = Symbol('byValue');
5312
5313var enums = {
5314
5315 /** Maps curve names under various standards to one
5316 * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
5317 * @enum {String}
5318 * @readonly
5319 */
5320 curve: {
5321 /** NIST P-256 Curve */
5322 "p256": "p256",
5323 "P-256": "p256",
5324 "secp256r1": "p256",
5325 "prime256v1": "p256",
5326 "1.2.840.10045.3.1.7": "p256",
5327 "2a8648ce3d030107": "p256",
5328 "2A8648CE3D030107": "p256",
5329
5330 /** NIST P-384 Curve */
5331 "p384": "p384",
5332 "P-384": "p384",
5333 "secp384r1": "p384",
5334 "1.3.132.0.34": "p384",
5335 "2b81040022": "p384",
5336 "2B81040022": "p384",
5337
5338 /** NIST P-521 Curve */
5339 "p521": "p521",
5340 "P-521": "p521",
5341 "secp521r1": "p521",
5342 "1.3.132.0.35": "p521",
5343 "2b81040023": "p521",
5344 "2B81040023": "p521",
5345
5346 /** SECG SECP256k1 Curve */
5347 "secp256k1": "secp256k1",
5348 "1.3.132.0.10": "secp256k1",
5349 "2b8104000a": "secp256k1",
5350 "2B8104000A": "secp256k1",
5351
5352 /** Ed25519 */
5353 "ED25519": "ed25519",
5354 "ed25519": "ed25519",
5355 "Ed25519": "ed25519",
5356 "1.3.6.1.4.1.11591.15.1": "ed25519",
5357 "2b06010401da470f01": "ed25519",
5358 "2B06010401DA470F01": "ed25519",
5359
5360 /** Curve25519 */
5361 "X25519": "curve25519",
5362 "cv25519": "curve25519",
5363 "curve25519": "curve25519",
5364 "Curve25519": "curve25519",
5365 "1.3.6.1.4.1.3029.1.5.1": "curve25519",
5366 "2b060104019755010501": "curve25519",
5367 "2B060104019755010501": "curve25519",
5368
5369 /** BrainpoolP256r1 Curve */
5370 "brainpoolP256r1": "brainpoolP256r1",
5371 "1.3.36.3.3.2.8.1.1.7": "brainpoolP256r1",
5372 "2b2403030208010107": "brainpoolP256r1",
5373 "2B2403030208010107": "brainpoolP256r1",
5374
5375 /** BrainpoolP384r1 Curve */
5376 "brainpoolP384r1": "brainpoolP384r1",
5377 "1.3.36.3.3.2.8.1.1.11": "brainpoolP384r1",
5378 "2b240303020801010b": "brainpoolP384r1",
5379 "2B240303020801010B": "brainpoolP384r1",
5380
5381 /** BrainpoolP512r1 Curve */
5382 "brainpoolP512r1": "brainpoolP512r1",
5383 "1.3.36.3.3.2.8.1.1.13": "brainpoolP512r1",
5384 "2b240303020801010d": "brainpoolP512r1",
5385 "2B240303020801010D": "brainpoolP512r1"
5386 },
5387
5388 /** A string to key specifier type
5389 * @enum {Integer}
5390 * @readonly
5391 */
5392 s2k: {
5393 simple: 0,
5394 salted: 1,
5395 iterated: 3,
5396 gnu: 101
5397 },
5398
5399 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
5400 * @enum {Integer}
5401 * @readonly
5402 */
5403 publicKey: {
5404 /** RSA (Encrypt or Sign) [HAC] */
5405 rsaEncryptSign: 1,
5406 /** RSA (Encrypt only) [HAC] */
5407 rsaEncrypt: 2,
5408 /** RSA (Sign only) [HAC] */
5409 rsaSign: 3,
5410 /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
5411 elgamal: 16,
5412 /** DSA (Sign only) [FIPS186] [HAC] */
5413 dsa: 17,
5414 /** ECDH (Encrypt only) [RFC6637] */
5415 ecdh: 18,
5416 /** ECDSA (Sign only) [RFC6637] */
5417 ecdsa: 19,
5418 /** EdDSA (Sign only)
5419 * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
5420 eddsa: 22,
5421 /** Reserved for AEDH */
5422 aedh: 23,
5423 /** Reserved for AEDSA */
5424 aedsa: 24
5425 },
5426
5427 /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
5428 * @enum {Integer}
5429 * @readonly
5430 */
5431 symmetric: {
5432 plaintext: 0,
5433 /** Not implemented! */
5434 idea: 1,
5435 tripledes: 2,
5436 cast5: 3,
5437 blowfish: 4,
5438 aes128: 7,
5439 aes192: 8,
5440 aes256: 9,
5441 twofish: 10
5442 },
5443
5444 /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
5445 * @enum {Integer}
5446 * @readonly
5447 */
5448 compression: {
5449 uncompressed: 0,
5450 /** RFC1951 */
5451 zip: 1,
5452 /** RFC1950 */
5453 zlib: 2,
5454 bzip2: 3
5455 },
5456
5457 /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
5458 * @enum {Integer}
5459 * @readonly
5460 */
5461 hash: {
5462 md5: 1,
5463 sha1: 2,
5464 ripemd: 3,
5465 sha256: 8,
5466 sha384: 9,
5467 sha512: 10,
5468 sha224: 11
5469 },
5470
5471 /** A list of hash names as accepted by webCrypto functions.
5472 * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
5473 * @enum {String}
5474 */
5475 webHash: {
5476 'SHA-1': 2,
5477 'SHA-256': 8,
5478 'SHA-384': 9,
5479 'SHA-512': 10
5480 },
5481
5482 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
5483 * @enum {Integer}
5484 * @readonly
5485 */
5486 aead: {
5487 eax: 1,
5488 ocb: 2,
5489 experimentalGcm: 100 // Private algorithm
5490 },
5491
5492 /** A list of packet types and numeric tags associated with them.
5493 * @enum {Integer}
5494 * @readonly
5495 */
5496 packet: {
5497 publicKeyEncryptedSessionKey: 1,
5498 signature: 2,
5499 symEncryptedSessionKey: 3,
5500 onePassSignature: 4,
5501 secretKey: 5,
5502 publicKey: 6,
5503 secretSubkey: 7,
5504 compressedData: 8,
5505 symmetricallyEncryptedData: 9,
5506 marker: 10,
5507 literalData: 11,
5508 trust: 12,
5509 userID: 13,
5510 publicSubkey: 14,
5511 userAttribute: 17,
5512 symEncryptedIntegrityProtectedData: 18,
5513 modificationDetectionCode: 19,
5514 AEADEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
5515 },
5516
5517 /** Data types in the literal packet
5518 * @enum {Integer}
5519 * @readonly
5520 */
5521 literal: {
5522 /** Binary data 'b' */
5523 binary: 'b'.charCodeAt(),
5524 /** Text data 't' */
5525 text: 't'.charCodeAt(),
5526 /** Utf8 data 'u' */
5527 utf8: 'u'.charCodeAt(),
5528 /** MIME message body part 'm' */
5529 mime: 'm'.charCodeAt()
5530 },
5531
5532
5533 /** One pass signature packet type
5534 * @enum {Integer}
5535 * @readonly
5536 */
5537 signature: {
5538 /** 0x00: Signature of a binary document. */
5539 binary: 0,
5540 /** 0x01: Signature of a canonical text document.
5541 *
5542 * Canonicalyzing the document by converting line endings. */
5543 text: 1,
5544 /** 0x02: Standalone signature.
5545 *
5546 * This signature is a signature of only its own subpacket contents.
5547 * It is calculated identically to a signature over a zero-lengh
5548 * binary document. Note that it doesn't make sense to have a V3
5549 * standalone signature. */
5550 standalone: 2,
5551 /** 0x10: Generic certification of a User ID and Public-Key packet.
5552 *
5553 * The issuer of this certification does not make any particular
5554 * assertion as to how well the certifier has checked that the owner
5555 * of the key is in fact the person described by the User ID. */
5556 certGeneric: 16,
5557 /** 0x11: Persona certification of a User ID and Public-Key packet.
5558 *
5559 * The issuer of this certification has not done any verification of
5560 * the claim that the owner of this key is the User ID specified. */
5561 certPersona: 17,
5562 /** 0x12: Casual certification of a User ID and Public-Key packet.
5563 *
5564 * The issuer of this certification has done some casual
5565 * verification of the claim of identity. */
5566 certCasual: 18,
5567 /** 0x13: Positive certification of a User ID and Public-Key packet.
5568 *
5569 * The issuer of this certification has done substantial
5570 * verification of the claim of identity.
5571 *
5572 * Most OpenPGP implementations make their "key signatures" as 0x10
5573 * certifications. Some implementations can issue 0x11-0x13
5574 * certifications, but few differentiate between the types. */
5575 certPositive: 19,
5576 /** 0x30: Certification revocation signature
5577 *
5578 * This signature revokes an earlier User ID certification signature
5579 * (signature class 0x10 through 0x13) or direct-key signature
5580 * (0x1F). It should be issued by the same key that issued the
5581 * revoked signature or an authorized revocation key. The signature
5582 * is computed over the same data as the certificate that it
5583 * revokes, and should have a later creation date than that
5584 * certificate. */
5585 certRevocation: 48,
5586 /** 0x18: Subkey Binding Signature
5587 *
5588 * This signature is a statement by the top-level signing key that
5589 * indicates that it owns the subkey. This signature is calculated
5590 * directly on the primary key and subkey, and not on any User ID or
5591 * other packets. A signature that binds a signing subkey MUST have
5592 * an Embedded Signature subpacket in this binding signature that
5593 * contains a 0x19 signature made by the signing subkey on the
5594 * primary key and subkey. */
5595 subkeyBinding: 24,
5596 /** 0x19: Primary Key Binding Signature
5597 *
5598 * This signature is a statement by a signing subkey, indicating
5599 * that it is owned by the primary key and subkey. This signature
5600 * is calculated the same way as a 0x18 signature: directly on the
5601 * primary key and subkey, and not on any User ID or other packets.
5602 *
5603 * When a signature is made over a key, the hash data starts with the
5604 * octet 0x99, followed by a two-octet length of the key, and then body
5605 * of the key packet. (Note that this is an old-style packet header for
5606 * a key packet with two-octet length.) A subkey binding signature
5607 * (type 0x18) or primary key binding signature (type 0x19) then hashes
5608 * the subkey using the same format as the main key (also using 0x99 as
5609 * the first octet). */
5610 keyBinding: 25,
5611 /** 0x1F: Signature directly on a key
5612 *
5613 * This signature is calculated directly on a key. It binds the
5614 * information in the Signature subpackets to the key, and is
5615 * appropriate to be used for subpackets that provide information
5616 * about the key, such as the Revocation Key subpacket. It is also
5617 * appropriate for statements that non-self certifiers want to make
5618 * about the key itself, rather than the binding between a key and a
5619 * name. */
5620 key: 31,
5621 /** 0x20: Key revocation signature
5622 *
5623 * The signature is calculated directly on the key being revoked. A
5624 * revoked key is not to be used. Only revocation signatures by the
5625 * key being revoked, or by an authorized revocation key, should be
5626 * considered valid revocation signatures.a */
5627 keyRevocation: 32,
5628 /** 0x28: Subkey revocation signature
5629 *
5630 * The signature is calculated directly on the subkey being revoked.
5631 * A revoked subkey is not to be used. Only revocation signatures
5632 * by the top-level signature key that is bound to this subkey, or
5633 * by an authorized revocation key, should be considered valid
5634 * revocation signatures.
5635 *
5636 * Key revocation signatures (types 0x20 and 0x28)
5637 * hash only the key being revoked. */
5638 subkeyRevocation: 40,
5639 /** 0x40: Timestamp signature.
5640 * This signature is only meaningful for the timestamp contained in
5641 * it. */
5642 timestamp: 64,
5643 /** 0x50: Third-Party Confirmation signature.
5644 *
5645 * This signature is a signature over some other OpenPGP Signature
5646 * packet(s). It is analogous to a notary seal on the signed data.
5647 * A third-party signature SHOULD include Signature Target
5648 * subpacket(s) to give easy identification. Note that we really do
5649 * mean SHOULD. There are plausible uses for this (such as a blind
5650 * party that only sees the signature, not the key or source
5651 * document) that cannot include a target subpacket. */
5652 thirdParty: 80
5653 },
5654
5655 /** Signature subpacket type
5656 * @enum {Integer}
5657 * @readonly
5658 */
5659 signatureSubpacket: {
5660 signatureCreationTime: 2,
5661 signatureExpirationTime: 3,
5662 exportableCertification: 4,
5663 trustSignature: 5,
5664 regularExpression: 6,
5665 revocable: 7,
5666 keyExpirationTime: 9,
5667 placeholderBackwardsCompatibility: 10,
5668 preferredSymmetricAlgorithms: 11,
5669 revocationKey: 12,
5670 issuer: 16,
5671 notationData: 20,
5672 preferredHashAlgorithms: 21,
5673 preferredCompressionAlgorithms: 22,
5674 keyServerPreferences: 23,
5675 preferredKeyServer: 24,
5676 primaryUserId: 25,
5677 policyUri: 26,
5678 keyFlags: 27,
5679 signersUserId: 28,
5680 reasonForRevocation: 29,
5681 features: 30,
5682 signatureTarget: 31,
5683 embeddedSignature: 32,
5684 issuerFingerprint: 33,
5685 preferredAeadAlgorithms: 34
5686 },
5687
5688 /** Key flags
5689 * @enum {Integer}
5690 * @readonly
5691 */
5692 keyFlags: {
5693 /** 0x01 - This key may be used to certify other keys. */
5694 certifyKeys: 1,
5695 /** 0x02 - This key may be used to sign data. */
5696 signData: 2,
5697 /** 0x04 - This key may be used to encrypt communications. */
5698 encryptCommunication: 4,
5699 /** 0x08 - This key may be used to encrypt storage. */
5700 encryptStorage: 8,
5701 /** 0x10 - The private component of this key may have been split
5702 * by a secret-sharing mechanism. */
5703 splitPrivateKey: 16,
5704 /** 0x20 - This key may be used for authentication. */
5705 authentication: 32,
5706 /** 0x80 - The private component of this key may be in the
5707 * possession of more than one person. */
5708 sharedPrivateKey: 128
5709 },
5710
5711 /** Armor type
5712 * @enum {Integer}
5713 * @readonly
5714 */
5715 armor: {
5716 multipartSection: 0,
5717 multipartLast: 1,
5718 signed: 2,
5719 message: 3,
5720 publicKey: 4,
5721 privateKey: 5,
5722 signature: 6
5723 },
5724
5725 /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
5726 * @enum {Integer}
5727 * @readonly
5728 */
5729 reasonForRevocation: {
5730 /** No reason specified (key revocations or cert revocations) */
5731 noReason: 0,
5732 /** Key is superseded (key revocations) */
5733 keySuperseded: 1,
5734 /** Key material has been compromised (key revocations) */
5735 keyCompromised: 2,
5736 /** Key is retired and no longer used (key revocations) */
5737 keyRetired: 3,
5738 /** User ID information is no longer valid (cert revocations) */
5739 userIdInvalid: 32
5740 },
5741
5742 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
5743 * @enum {Integer}
5744 * @readonly
5745 */
5746 features: {
5747 /** 0x01 - Modification Detection (packets 18 and 19) */
5748 modificationDetection: 1,
5749 /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
5750 * Symmetric-Key Encrypted Session Key Packets (packet 3) */
5751 aead: 2,
5752 /** 0x04 - Version 5 Public-Key Packet format and corresponding new
5753 * fingerprint format */
5754 v5Keys: 4
5755 },
5756
5757 /** Asserts validity and converts from string/integer to integer. */
5758 write: function(type, e) {
5759 if (typeof e === 'number') {
5760 e = this.read(type, e);
5761 }
5762
5763 if (type[e] !== undefined) {
5764 return type[e];
5765 }
5766
5767 throw new Error('Invalid enum value.');
5768 },
5769
5770 /** Converts from an integer to string. */
5771 read: function(type, e) {
5772 if (!type[byValue]) {
5773 type[byValue] = [];
5774 Object.entries(type).forEach(([key, value]) => {
5775 type[byValue][value] = key;
5776 });
5777 }
5778
5779 if (type[byValue][e] !== undefined) {
5780 return type[byValue][e];
5781 }
5782
5783 throw new Error('Invalid enum value.');
5784 }
5785
5786};
5787
5788// GPG4Browsers - An OpenPGP implementation in javascript
5789
5790var defaultConfig = {
5791 /**
5792 * @memberof module:config
5793 * @property {Integer} preferHashAlgorithm Default hash algorithm {@link module:enums.hash}
5794 */
5795 preferHashAlgorithm: enums.hash.sha256,
5796 /**
5797 * @memberof module:config
5798 * @property {Integer} encryptionCipher Default encryption cipher {@link module:enums.symmetric}
5799 */
5800 encryptionCipher: enums.symmetric.aes256,
5801 /**
5802 * @memberof module:config
5803 * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
5804 */
5805 compression: enums.compression.uncompressed,
5806 /**
5807 * @memberof module:config
5808 * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
5809 */
5810 deflateLevel: 6,
5811
5812 /**
5813 * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
5814 * Note: not all OpenPGP implementations are compatible with this option.
5815 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
5816 * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
5817 * @memberof module:config
5818 * @property {Boolean} aeadProtect
5819 */
5820 aeadProtect: false,
5821 /**
5822 * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
5823 * Only has an effect when aeadProtect is set to true.
5824 * @memberof module:config
5825 * @property {Integer} aeadMode Default AEAD mode {@link module:enums.aead}
5826 */
5827 aeadMode: enums.aead.eax,
5828 /**
5829 * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
5830 * Only has an effect when aeadProtect is set to true.
5831 * Must be an integer value from 0 to 56.
5832 * @memberof module:config
5833 * @property {Integer} aeadChunkSizeByte
5834 */
5835 aeadChunkSizeByte: 12,
5836 /**
5837 * Use V5 keys.
5838 * Note: not all OpenPGP implementations are compatible with this option.
5839 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
5840 * @memberof module:config
5841 * @property {Boolean} v5Keys
5842 */
5843 v5Keys: false,
5844 /**
5845 * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
5846 * Iteration Count Byte for S2K (String to Key)
5847 * @memberof module:config
5848 * @property {Integer} s2kIterationCountByte
5849 */
5850 s2kIterationCountByte: 224,
5851 /**
5852 * Allow decryption of messages without integrity protection.
5853 * This is an **insecure** setting:
5854 * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
5855 * - it enables downgrade attacks against integrity-protected messages.
5856 * @memberof module:config
5857 * @property {Boolean} allowUnauthenticatedMessages
5858 */
5859 allowUnauthenticatedMessages: false,
5860 /**
5861 * Allow streaming unauthenticated data before its integrity has been checked.
5862 * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.
5863 * @memberof module:config
5864 * @property {Boolean} allowUnauthenticatedStream
5865 */
5866 allowUnauthenticatedStream: false,
5867 /**
5868 * @memberof module:config
5869 * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
5870 */
5871 checksumRequired: false,
5872 /**
5873 * @memberof module:config
5874 * @property {Number} minRsaBits Minimum RSA key size allowed for key generation
5875 */
5876 minRsaBits: 2048,
5877 /**
5878 * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
5879 * **Slower and slightly less secure**
5880 * @memberof module:config
5881 * @property {Boolean} passwordCollisionCheck
5882 */
5883 passwordCollisionCheck: false,
5884 /**
5885 * @memberof module:config
5886 * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
5887 */
5888 revocationsExpire: false,
5889 /**
5890 * Allow decryption using RSA keys without `encrypt` flag.
5891 * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
5892 * where key flags were ignored when selecting a key for encryption.
5893 * @memberof module:config
5894 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
5895 */
5896 allowInsecureDecryptionWithSigningKeys: false,
5897
5898 /**
5899 * @memberof module:config
5900 * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
5901 */
5902 minBytesForWebCrypto: 1000,
5903 /**
5904 * @memberof module:config
5905 * @property {Boolean} tolerant Ignore unsupported/unrecognizable packets instead of throwing an error
5906 */
5907 tolerant: true,
5908
5909 /**
5910 * @memberof module:config
5911 * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
5912 */
5913 showVersion: false,
5914 /**
5915 * @memberof module:config
5916 * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
5917 */
5918 showComment: false,
5919 /**
5920 * @memberof module:config
5921 * @property {String} versionString A version string to be included in armored messages
5922 */
5923 versionString: "OpenPGP.js 5.0.0-1",
5924 /**
5925 * @memberof module:config
5926 * @property {String} commentString A comment string to be included in armored messages
5927 */
5928 commentString: "https://openpgpjs.org",
5929
5930 /**
5931 * Max userid string length (used for parsing)
5932 * @memberof module:config
5933 * @property {Integer} maxUseridLength
5934 */
5935 maxUseridLength: 1024 * 5,
5936 /**
5937 * Contains notatations that are considered "known". Known notations do not trigger
5938 * validation error when the notation is marked as critical.
5939 * @memberof module:config
5940 * @property {Array} knownNotations
5941 */
5942 knownNotations: ["preferred-email-encoding@pgp.com", "pka-address@gnupg.org"],
5943 /**
5944 * @memberof module:config
5945 * @property {Boolean} useIndutnyElliptic Whether to use the indutny/elliptic library. When false, certain curves will not be supported.
5946 */
5947 useIndutnyElliptic: true,
5948 /**
5949 * @memberof module:config
5950 * @property {Set<Integer>} reject_hash_algorithms Reject insecure hash algorithms {@link module:enums.hash}
5951 */
5952 rejectHashAlgorithms: new globalThis.Set([enums.hash.md5, enums.hash.ripemd]),
5953 /**
5954 * @memberof module:config
5955 * @property {Set<Integer>} reject_message_hash_algorithms Reject insecure message hash algorithms {@link module:enums.hash}
5956 */
5957 rejectMessageHashAlgorithms: new globalThis.Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1])
5958};
5959
5960// GPG4Browsers - An OpenPGP implementation in javascript
5961
5962/**
5963 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
5964 * @param {String} text - ascii armored text
5965 * @returns {Integer} 0 = MESSAGE PART n of m.
5966 * 1 = MESSAGE PART n
5967 * 2 = SIGNED MESSAGE
5968 * 3 = PGP MESSAGE
5969 * 4 = PUBLIC KEY BLOCK
5970 * 5 = PRIVATE KEY BLOCK
5971 * 6 = SIGNATURE
5972 * @private
5973 */
5974function getType(text) {
5975 const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
5976
5977 const header = text.match(reHeader);
5978
5979 if (!header) {
5980 throw new Error('Unknown ASCII armor type');
5981 }
5982
5983 // BEGIN PGP MESSAGE, PART X/Y
5984 // Used for multi-part messages, where the armor is split amongst Y
5985 // parts, and this is the Xth part out of Y.
5986 if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
5987 return enums.armor.multipartSection;
5988 } else
5989 // BEGIN PGP MESSAGE, PART X
5990 // Used for multi-part messages, where this is the Xth part of an
5991 // unspecified number of parts. Requires the MESSAGE-ID Armor
5992 // Header to be used.
5993 if (/MESSAGE, PART \d+/.test(header[1])) {
5994 return enums.armor.multipartLast;
5995 } else
5996 // BEGIN PGP SIGNED MESSAGE
5997 if (/SIGNED MESSAGE/.test(header[1])) {
5998 return enums.armor.signed;
5999 } else
6000 // BEGIN PGP MESSAGE
6001 // Used for signed, encrypted, or compressed files.
6002 if (/MESSAGE/.test(header[1])) {
6003 return enums.armor.message;
6004 } else
6005 // BEGIN PGP PUBLIC KEY BLOCK
6006 // Used for armoring public keys.
6007 if (/PUBLIC KEY BLOCK/.test(header[1])) {
6008 return enums.armor.publicKey;
6009 } else
6010 // BEGIN PGP PRIVATE KEY BLOCK
6011 // Used for armoring private keys.
6012 if (/PRIVATE KEY BLOCK/.test(header[1])) {
6013 return enums.armor.privateKey;
6014 } else
6015 // BEGIN PGP SIGNATURE
6016 // Used for detached signatures, OpenPGP/MIME signatures, and
6017 // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
6018 // for detached signatures.
6019 if (/SIGNATURE/.test(header[1])) {
6020 return enums.armor.signature;
6021 }
6022}
6023
6024/**
6025 * Add additional information to the armor version of an OpenPGP binary
6026 * packet block.
6027 * @author Alex
6028 * @version 2011-12-16
6029 * @param {String} [customComment] - Additional comment to add to the armored string
6030 * @returns {String} The header information.
6031 * @private
6032 */
6033function addheader(customComment, config) {
6034 let result = "";
6035 if (config.showVersion) {
6036 result += "Version: " + config.versionString + '\n';
6037 }
6038 if (config.showComment) {
6039 result += "Comment: " + config.commentString + '\n';
6040 }
6041 if (customComment) {
6042 result += "Comment: " + customComment + '\n';
6043 }
6044 result += '\n';
6045 return result;
6046}
6047
6048
6049/**
6050 * Calculates a checksum over the given data and returns it base64 encoded
6051 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
6052 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
6053 * @private
6054 */
6055function getCheckSum(data) {
6056 const crc = createcrc24(data);
6057 return encode(crc);
6058}
6059
6060// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
6061
6062const crc_table = [
6063 new Array(0xFF),
6064 new Array(0xFF),
6065 new Array(0xFF),
6066 new Array(0xFF)
6067];
6068
6069for (let i = 0; i <= 0xFF; i++) {
6070 let crc = i << 16;
6071 for (let j = 0; j < 8; j++) {
6072 crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
6073 }
6074 crc_table[0][i] =
6075 ((crc & 0xFF0000) >> 16) |
6076 (crc & 0x00FF00) |
6077 ((crc & 0x0000FF) << 16);
6078}
6079for (let i = 0; i <= 0xFF; i++) {
6080 crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
6081}
6082for (let i = 0; i <= 0xFF; i++) {
6083 crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
6084}
6085for (let i = 0; i <= 0xFF; i++) {
6086 crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
6087}
6088
6089// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
6090const isLittleEndian = (function() {
6091 const buffer = new ArrayBuffer(2);
6092 new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
6093 // Int16Array uses the platform's endianness.
6094 return new Int16Array(buffer)[0] === 0xFF;
6095}());
6096
6097/**
6098 * Internal function to calculate a CRC-24 checksum over a given string (data)
6099 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
6100 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
6101 * @private
6102 */
6103function createcrc24(input) {
6104 let crc = 0xCE04B7;
6105 return stream.transform(input, value => {
6106 const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;
6107 const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
6108 for (let i = 0; i < len32; i++) {
6109 crc ^= arr32[i];
6110 crc =
6111 crc_table[0][(crc >> 24) & 0xFF] ^
6112 crc_table[1][(crc >> 16) & 0xFF] ^
6113 crc_table[2][(crc >> 8) & 0xFF] ^
6114 crc_table[3][(crc >> 0) & 0xFF];
6115 }
6116 for (let i = len32 * 4; i < value.length; i++) {
6117 crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
6118 }
6119 }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
6120}
6121
6122/**
6123 * Verify armored headers. RFC4880, section 6.3: "OpenPGP should consider improperly formatted
6124 * Armor Headers to be corruption of the ASCII Armor."
6125 * @private
6126 * @param {Array<String>} headers - Armor headers
6127 */
6128function verifyHeaders(headers) {
6129 for (let i = 0; i < headers.length; i++) {
6130 if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
6131 throw new Error('Improperly formatted armor header: ' + headers[i]);
6132 }
6133 if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
6134 util.printDebugError(new Error('Unknown header: ' + headers[i]));
6135 }
6136 }
6137}
6138
6139/**
6140 * Splits a message into two parts, the body and the checksum. This is an internal function
6141 * @param {String} text - OpenPGP armored message part
6142 * @returns {Object} An object with attribute "body" containing the body.
6143 * and an attribute "checksum" containing the checksum.
6144 * @private
6145 */
6146function splitChecksum(text) {
6147 let body = text;
6148 let checksum = "";
6149
6150 const lastEquals = text.lastIndexOf("=");
6151
6152 if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
6153 body = text.slice(0, lastEquals);
6154 checksum = text.slice(lastEquals + 1).substr(0, 4);
6155 }
6156
6157 return { body: body, checksum: checksum };
6158}
6159
6160/**
6161 * Dearmor an OpenPGP armored message; verify the checksum and return
6162 * the encoded bytes
6163 * @param {String} input - OpenPGP armored message
6164 * @returns {Object} An object with attribute "text" containing the message text,
6165 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
6166 * @async
6167 * @static
6168 */
6169function unarmor(input, config = defaultConfig) {
6170 return new Promise(async (resolve, reject) => {
6171 try {
6172 const reSplit = /^-----[^-]+-----$/m;
6173 const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
6174
6175 let type;
6176 const headers = [];
6177 let lastHeaders = headers;
6178 let headersDone;
6179 let text = [];
6180 let textDone;
6181 let checksum;
6182 let data = decode(stream.transformPair(input, async (readable, writable) => {
6183 const reader = stream.getReader(readable);
6184 try {
6185 while (true) {
6186 let line = await reader.readLine();
6187 if (line === undefined) {
6188 throw new Error('Misformed armored text');
6189 }
6190 // remove trailing whitespace at end of lines
6191 line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
6192 if (!type) {
6193 if (reSplit.test(line)) {
6194 type = getType(line);
6195 }
6196 } else if (!headersDone) {
6197 if (reSplit.test(line)) {
6198 reject(new Error('Mandatory blank line missing between armor headers and armor data'));
6199 }
6200 if (!reEmptyLine.test(line)) {
6201 lastHeaders.push(line);
6202 } else {
6203 verifyHeaders(lastHeaders);
6204 headersDone = true;
6205 if (textDone || type !== 2) {
6206 resolve({ text, data, headers, type });
6207 break;
6208 }
6209 }
6210 } else if (!textDone && type === 2) {
6211 if (!reSplit.test(line)) {
6212 // Reverse dash-escaping for msg
6213 text.push(line.replace(/^- /, ''));
6214 } else {
6215 text = text.join('\r\n');
6216 textDone = true;
6217 verifyHeaders(lastHeaders);
6218 lastHeaders = [];
6219 headersDone = false;
6220 }
6221 }
6222 }
6223 } catch (e) {
6224 reject(e);
6225 return;
6226 }
6227 const writer = stream.getWriter(writable);
6228 try {
6229 while (true) {
6230 await writer.ready;
6231 const { done, value } = await reader.read();
6232 if (done) {
6233 throw new Error('Misformed armored text');
6234 }
6235 const line = value + '';
6236 if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
6237 await writer.write(line);
6238 } else {
6239 let remainder = await reader.readToEnd();
6240 if (!remainder.length) remainder = '';
6241 remainder = line + remainder;
6242 remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
6243 const parts = remainder.split(reSplit);
6244 if (parts.length === 1) {
6245 throw new Error('Misformed armored text');
6246 }
6247 const split = splitChecksum(parts[0].slice(0, -1));
6248 checksum = split.checksum;
6249 await writer.write(split.body);
6250 break;
6251 }
6252 }
6253 await writer.ready;
6254 await writer.close();
6255 } catch (e) {
6256 await writer.abort(e);
6257 }
6258 }));
6259 data = stream.transformPair(data, async (readable, writable) => {
6260 const checksumVerified = stream.readToEnd(getCheckSum(stream.passiveClone(readable)));
6261 checksumVerified.catch(() => {});
6262 await stream.pipe(readable, writable, {
6263 preventClose: true
6264 });
6265 const writer = stream.getWriter(writable);
6266 try {
6267 const checksumVerifiedString = (await checksumVerified).replace('\n', '');
6268 if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {
6269 throw new Error("Ascii armor integrity check on message failed: '" + checksum + "' should be '" +
6270 checksumVerifiedString + "'");
6271 }
6272 await writer.ready;
6273 await writer.close();
6274 } catch (e) {
6275 await writer.abort(e);
6276 }
6277 });
6278 } catch (e) {
6279 reject(e);
6280 }
6281 });
6282}
6283
6284
6285/**
6286 * Armor an OpenPGP binary packet block
6287 * @param {module:enums.armor} messageType - Type of the message
6288 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
6289 * @param {Integer} [partIndex]
6290 * @param {Integer} [partTotal]
6291 * @param {String} [customComment] - Additional comment to add to the armored string
6292 * @returns {String | ReadableStream<String>} Armored text.
6293 * @static
6294 */
6295function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {
6296 let text;
6297 let hash;
6298 if (messageType === enums.armor.signed) {
6299 text = body.text;
6300 hash = body.hash;
6301 body = body.data;
6302 }
6303 const bodyClone = stream.passiveClone(body);
6304 const result = [];
6305 switch (messageType) {
6306 case enums.armor.multipartSection:
6307 result.push("-----BEGIN PGP MESSAGE, PART " + partIndex + "/" + partTotal + "-----\n");
6308 result.push(addheader(customComment, config));
6309 result.push(encode(body));
6310 result.push("=", getCheckSum(bodyClone));
6311 result.push("-----END PGP MESSAGE, PART " + partIndex + "/" + partTotal + "-----\n");
6312 break;
6313 case enums.armor.multipartLast:
6314 result.push("-----BEGIN PGP MESSAGE, PART " + partIndex + "-----\n");
6315 result.push(addheader(customComment, config));
6316 result.push(encode(body));
6317 result.push("=", getCheckSum(bodyClone));
6318 result.push("-----END PGP MESSAGE, PART " + partIndex + "-----\n");
6319 break;
6320 case enums.armor.signed:
6321 result.push("\n-----BEGIN PGP SIGNED MESSAGE-----\n");
6322 result.push("Hash: " + hash + "\n\n");
6323 result.push(text.replace(/^-/mg, "- -"));
6324 result.push("\n-----BEGIN PGP SIGNATURE-----\n");
6325 result.push(addheader(customComment, config));
6326 result.push(encode(body));
6327 result.push("=", getCheckSum(bodyClone));
6328 result.push("-----END PGP SIGNATURE-----\n");
6329 break;
6330 case enums.armor.message:
6331 result.push("-----BEGIN PGP MESSAGE-----\n");
6332 result.push(addheader(customComment, config));
6333 result.push(encode(body));
6334 result.push("=", getCheckSum(bodyClone));
6335 result.push("-----END PGP MESSAGE-----\n");
6336 break;
6337 case enums.armor.publicKey:
6338 result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\n");
6339 result.push(addheader(customComment, config));
6340 result.push(encode(body));
6341 result.push("=", getCheckSum(bodyClone));
6342 result.push("-----END PGP PUBLIC KEY BLOCK-----\n");
6343 break;
6344 case enums.armor.privateKey:
6345 result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\n");
6346 result.push(addheader(customComment, config));
6347 result.push(encode(body));
6348 result.push("=", getCheckSum(bodyClone));
6349 result.push("-----END PGP PRIVATE KEY BLOCK-----\n");
6350 break;
6351 case enums.armor.signature:
6352 result.push("-----BEGIN PGP SIGNATURE-----\n");
6353 result.push(addheader(customComment, config));
6354 result.push(encode(body));
6355 result.push("=", getCheckSum(bodyClone));
6356 result.push("-----END PGP SIGNATURE-----\n");
6357 break;
6358 }
6359
6360 return util.concat(result);
6361}
6362
6363// GPG4Browsers - An OpenPGP implementation in javascript
6364
6365/**
6366 * Implementation of type key id
6367 *
6368 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
6369 * A Key ID is an eight-octet scalar that identifies a key.
6370 * Implementations SHOULD NOT assume that Key IDs are unique. The
6371 * section "Enhanced Key Formats" below describes how Key IDs are
6372 * formed.
6373 */
6374class Keyid {
6375 constructor() {
6376 this.bytes = '';
6377 }
6378
6379 /**
6380 * Parsing method for a key id
6381 * @param {Uint8Array} bytes - Input to read the key id from
6382 */
6383 read(bytes) {
6384 this.bytes = util.uint8ArrayToStr(bytes.subarray(0, 8));
6385 }
6386
6387 /**
6388 * Serializes the Key ID
6389 * @returns {Uint8Array} Key ID as a Uint8Array.
6390 */
6391 write() {
6392 return util.strToUint8Array(this.bytes);
6393 }
6394
6395 /**
6396 * Returns the Key ID represented as a hexadecimal string
6397 * @returns {String} Key ID as a hexadecimal string.
6398 */
6399 toHex() {
6400 return util.strToHex(this.bytes);
6401 }
6402
6403 /**
6404 * Checks equality of Key ID's
6405 * @param {Keyid} keyid
6406 * @param {Boolean} matchWildcard - Indicates whether to check if either keyid is a wildcard
6407 */
6408 equals(keyid, matchWildcard = false) {
6409 return (matchWildcard && (keyid.isWildcard() || this.isWildcard())) || this.bytes === keyid.bytes;
6410 }
6411
6412 /**
6413 * Checks to see if the Key ID is unset
6414 * @returns {Boolean} True if the Key ID is null.
6415 */
6416 isNull() {
6417 return this.bytes === '';
6418 }
6419
6420 /**
6421 * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
6422 * @returns {Boolean} True if this is a wildcard Key ID.
6423 */
6424 isWildcard() {
6425 return /^0+$/.test(this.toHex());
6426 }
6427
6428 static mapToHex(keyId) {
6429 return keyId.toHex();
6430 }
6431
6432 static fromId(hex) {
6433 const keyid = new Keyid();
6434 keyid.read(util.hexToUint8Array(hex));
6435 return keyid;
6436 }
6437
6438 static wildcard() {
6439 const keyid = new Keyid();
6440 keyid.read(new Uint8Array(8));
6441 return keyid;
6442 }
6443}
6444
6445/**
6446 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
6447 * @author Artem S Vybornov <vybornov@gmail.com>
6448 * @license MIT
6449 */
6450var AES_asm = function () {
6451
6452 /**
6453 * Galois Field stuff init flag
6454 */
6455 var ginit_done = false;
6456
6457 /**
6458 * Galois Field exponentiation and logarithm tables for 3 (the generator)
6459 */
6460 var gexp3, glog3;
6461
6462 /**
6463 * Init Galois Field tables
6464 */
6465 function ginit() {
6466 gexp3 = [],
6467 glog3 = [];
6468
6469 var a = 1, c, d;
6470 for (c = 0; c < 255; c++) {
6471 gexp3[c] = a;
6472
6473 // Multiply by three
6474 d = a & 0x80, a <<= 1, a &= 255;
6475 if (d === 0x80) a ^= 0x1b;
6476 a ^= gexp3[c];
6477
6478 // Set the log table value
6479 glog3[gexp3[c]] = c;
6480 }
6481 gexp3[255] = gexp3[0];
6482 glog3[0] = 0;
6483
6484 ginit_done = true;
6485 }
6486
6487 /**
6488 * Galois Field multiplication
6489 * @param {number} a
6490 * @param {number} b
6491 * @return {number}
6492 */
6493 function gmul(a, b) {
6494 var c = gexp3[(glog3[a] + glog3[b]) % 255];
6495 if (a === 0 || b === 0) c = 0;
6496 return c;
6497 }
6498
6499 /**
6500 * Galois Field reciprocal
6501 * @param {number} a
6502 * @return {number}
6503 */
6504 function ginv(a) {
6505 var i = gexp3[255 - glog3[a]];
6506 if (a === 0) i = 0;
6507 return i;
6508 }
6509
6510 /**
6511 * AES stuff init flag
6512 */
6513 var aes_init_done = false;
6514
6515 /**
6516 * Encryption, Decryption, S-Box and KeyTransform tables
6517 *
6518 * @type {number[]}
6519 */
6520 var aes_sbox;
6521
6522 /**
6523 * @type {number[]}
6524 */
6525 var aes_sinv;
6526
6527 /**
6528 * @type {number[][]}
6529 */
6530 var aes_enc;
6531
6532 /**
6533 * @type {number[][]}
6534 */
6535 var aes_dec;
6536
6537 /**
6538 * Init AES tables
6539 */
6540 function aes_init() {
6541 if (!ginit_done) ginit();
6542
6543 // Calculates AES S-Box value
6544 function _s(a) {
6545 var c, s, x;
6546 s = x = ginv(a);
6547 for (c = 0; c < 4; c++) {
6548 s = ((s << 1) | (s >>> 7)) & 255;
6549 x ^= s;
6550 }
6551 x ^= 99;
6552 return x;
6553 }
6554
6555 // Tables
6556 aes_sbox = [],
6557 aes_sinv = [],
6558 aes_enc = [[], [], [], []],
6559 aes_dec = [[], [], [], []];
6560
6561 for (var i = 0; i < 256; i++) {
6562 var s = _s(i);
6563
6564 // S-Box and its inverse
6565 aes_sbox[i] = s;
6566 aes_sinv[s] = i;
6567
6568 // Ecryption and Decryption tables
6569 aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);
6570 aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);
6571 // Rotate tables
6572 for (var t = 1; t < 4; t++) {
6573 aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);
6574 aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);
6575 }
6576 }
6577
6578 aes_init_done = true;
6579 }
6580
6581 /**
6582 * Asm.js module constructor.
6583 *
6584 * <p>
6585 * Heap buffer layout by offset:
6586 * <pre>
6587 * 0x0000 encryption key schedule
6588 * 0x0400 decryption key schedule
6589 * 0x0800 sbox
6590 * 0x0c00 inv sbox
6591 * 0x1000 encryption tables
6592 * 0x2000 decryption tables
6593 * 0x3000 reserved (future GCM multiplication lookup table)
6594 * 0x4000 data
6595 * </pre>
6596 * Don't touch anything before <code>0x400</code>.
6597 * </p>
6598 *
6599 * @alias AES_asm
6600 * @class
6601 * @param foreign - <i>ignored</i>
6602 * @param buffer - heap buffer to link with
6603 */
6604 var wrapper = function (foreign, buffer) {
6605 // Init AES stuff for the first time
6606 if (!aes_init_done) aes_init();
6607
6608 // Fill up AES tables
6609 var heap = new Uint32Array(buffer);
6610 heap.set(aes_sbox, 0x0800 >> 2);
6611 heap.set(aes_sinv, 0x0c00 >> 2);
6612 for (var i = 0; i < 4; i++) {
6613 heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);
6614 heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);
6615 }
6616
6617 /**
6618 * Calculate AES key schedules.
6619 * @instance
6620 * @memberof AES_asm
6621 * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
6622 * @param {number} k0 - key vector components
6623 * @param {number} k1 - key vector components
6624 * @param {number} k2 - key vector components
6625 * @param {number} k3 - key vector components
6626 * @param {number} k4 - key vector components
6627 * @param {number} k5 - key vector components
6628 * @param {number} k6 - key vector components
6629 * @param {number} k7 - key vector components
6630 */
6631 function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
6632 var ekeys = heap.subarray(0x000, 60),
6633 dkeys = heap.subarray(0x100, 0x100 + 60);
6634
6635 // Encryption key schedule
6636 ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
6637 for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
6638 var k = ekeys[i - 1];
6639 if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {
6640 k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
6641 }
6642 if (i % ks === 0) {
6643 k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
6644 rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);
6645 }
6646 ekeys[i] = ekeys[i - ks] ^ k;
6647 }
6648
6649 // Decryption key schedule
6650 for (var j = 0; j < i; j += 4) {
6651 for (var jj = 0; jj < 4; jj++) {
6652 var k = ekeys[i - (4 + j) + (4 - jj) % 4];
6653 if (j < 4 || j >= i - 4) {
6654 dkeys[j + jj] = k;
6655 } else {
6656 dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]
6657 ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]
6658 ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]
6659 ^ aes_dec[3][aes_sbox[k & 255]];
6660 }
6661 }
6662 }
6663
6664 // Set rounds number
6665 asm.set_rounds(ks + 5);
6666 }
6667
6668 // create library object with necessary properties
6669 var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};
6670
6671 var asm = function (stdlib, foreign, buffer) {
6672 "use asm";
6673
6674 var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
6675 I0 = 0, I1 = 0, I2 = 0, I3 = 0,
6676 N0 = 0, N1 = 0, N2 = 0, N3 = 0,
6677 M0 = 0, M1 = 0, M2 = 0, M3 = 0,
6678 H0 = 0, H1 = 0, H2 = 0, H3 = 0,
6679 R = 0;
6680
6681 var HEAP = new stdlib.Uint32Array(buffer),
6682 DATA = new stdlib.Uint8Array(buffer);
6683
6684 /**
6685 * AES core
6686 * @param {number} k - precomputed key schedule offset
6687 * @param {number} s - precomputed sbox table offset
6688 * @param {number} t - precomputed round table offset
6689 * @param {number} r - number of inner rounds to perform
6690 * @param {number} x0 - 128-bit input block vector
6691 * @param {number} x1 - 128-bit input block vector
6692 * @param {number} x2 - 128-bit input block vector
6693 * @param {number} x3 - 128-bit input block vector
6694 */
6695 function _core(k, s, t, r, x0, x1, x2, x3) {
6696 k = k | 0;
6697 s = s | 0;
6698 t = t | 0;
6699 r = r | 0;
6700 x0 = x0 | 0;
6701 x1 = x1 | 0;
6702 x2 = x2 | 0;
6703 x3 = x3 | 0;
6704
6705 var t1 = 0, t2 = 0, t3 = 0,
6706 y0 = 0, y1 = 0, y2 = 0, y3 = 0,
6707 i = 0;
6708
6709 t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
6710
6711 // round 0
6712 x0 = x0 ^ HEAP[(k | 0) >> 2],
6713 x1 = x1 ^ HEAP[(k | 4) >> 2],
6714 x2 = x2 ^ HEAP[(k | 8) >> 2],
6715 x3 = x3 ^ HEAP[(k | 12) >> 2];
6716
6717 // round 1..r
6718 for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {
6719 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],
6720 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],
6721 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],
6722 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];
6723 x0 = y0, x1 = y1, x2 = y2, x3 = y3;
6724 }
6725
6726 // final round
6727 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],
6728 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],
6729 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],
6730 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];
6731 }
6732
6733 /**
6734 * ECB mode encryption
6735 * @param {number} x0 - 128-bit input block vector
6736 * @param {number} x1 - 128-bit input block vector
6737 * @param {number} x2 - 128-bit input block vector
6738 * @param {number} x3 - 128-bit input block vector
6739 */
6740 function _ecb_enc(x0, x1, x2, x3) {
6741 x0 = x0 | 0;
6742 x1 = x1 | 0;
6743 x2 = x2 | 0;
6744 x3 = x3 | 0;
6745
6746 _core(
6747 0x0000, 0x0800, 0x1000,
6748 R,
6749 x0,
6750 x1,
6751 x2,
6752 x3
6753 );
6754 }
6755
6756 /**
6757 * ECB mode decryption
6758 * @param {number} x0 - 128-bit input block vector
6759 * @param {number} x1 - 128-bit input block vector
6760 * @param {number} x2 - 128-bit input block vector
6761 * @param {number} x3 - 128-bit input block vector
6762 */
6763 function _ecb_dec(x0, x1, x2, x3) {
6764 x0 = x0 | 0;
6765 x1 = x1 | 0;
6766 x2 = x2 | 0;
6767 x3 = x3 | 0;
6768
6769 var t = 0;
6770
6771 _core(
6772 0x0400, 0x0c00, 0x2000,
6773 R,
6774 x0,
6775 x3,
6776 x2,
6777 x1
6778 );
6779
6780 t = S1, S1 = S3, S3 = t;
6781 }
6782
6783
6784 /**
6785 * CBC mode encryption
6786 * @param {number} x0 - 128-bit input block vector
6787 * @param {number} x1 - 128-bit input block vector
6788 * @param {number} x2 - 128-bit input block vector
6789 * @param {number} x3 - 128-bit input block vector
6790 */
6791 function _cbc_enc(x0, x1, x2, x3) {
6792 x0 = x0 | 0;
6793 x1 = x1 | 0;
6794 x2 = x2 | 0;
6795 x3 = x3 | 0;
6796
6797 _core(
6798 0x0000, 0x0800, 0x1000,
6799 R,
6800 I0 ^ x0,
6801 I1 ^ x1,
6802 I2 ^ x2,
6803 I3 ^ x3
6804 );
6805
6806 I0 = S0,
6807 I1 = S1,
6808 I2 = S2,
6809 I3 = S3;
6810 }
6811
6812 /**
6813 * CBC mode decryption
6814 * @param {number} x0 - 128-bit input block vector
6815 * @param {number} x1 - 128-bit input block vector
6816 * @param {number} x2 - 128-bit input block vector
6817 * @param {number} x3 - 128-bit input block vector
6818 */
6819 function _cbc_dec(x0, x1, x2, x3) {
6820 x0 = x0 | 0;
6821 x1 = x1 | 0;
6822 x2 = x2 | 0;
6823 x3 = x3 | 0;
6824
6825 var t = 0;
6826
6827 _core(
6828 0x0400, 0x0c00, 0x2000,
6829 R,
6830 x0,
6831 x3,
6832 x2,
6833 x1
6834 );
6835
6836 t = S1, S1 = S3, S3 = t;
6837
6838 S0 = S0 ^ I0,
6839 S1 = S1 ^ I1,
6840 S2 = S2 ^ I2,
6841 S3 = S3 ^ I3;
6842
6843 I0 = x0,
6844 I1 = x1,
6845 I2 = x2,
6846 I3 = x3;
6847 }
6848
6849 /**
6850 * CFB mode encryption
6851 * @param {number} x0 - 128-bit input block vector
6852 * @param {number} x1 - 128-bit input block vector
6853 * @param {number} x2 - 128-bit input block vector
6854 * @param {number} x3 - 128-bit input block vector
6855 */
6856 function _cfb_enc(x0, x1, x2, x3) {
6857 x0 = x0 | 0;
6858 x1 = x1 | 0;
6859 x2 = x2 | 0;
6860 x3 = x3 | 0;
6861
6862 _core(
6863 0x0000, 0x0800, 0x1000,
6864 R,
6865 I0,
6866 I1,
6867 I2,
6868 I3
6869 );
6870
6871 I0 = S0 = S0 ^ x0,
6872 I1 = S1 = S1 ^ x1,
6873 I2 = S2 = S2 ^ x2,
6874 I3 = S3 = S3 ^ x3;
6875 }
6876
6877
6878 /**
6879 * CFB mode decryption
6880 * @param {number} x0 - 128-bit input block vector
6881 * @param {number} x1 - 128-bit input block vector
6882 * @param {number} x2 - 128-bit input block vector
6883 * @param {number} x3 - 128-bit input block vector
6884 */
6885 function _cfb_dec(x0, x1, x2, x3) {
6886 x0 = x0 | 0;
6887 x1 = x1 | 0;
6888 x2 = x2 | 0;
6889 x3 = x3 | 0;
6890
6891 _core(
6892 0x0000, 0x0800, 0x1000,
6893 R,
6894 I0,
6895 I1,
6896 I2,
6897 I3
6898 );
6899
6900 S0 = S0 ^ x0,
6901 S1 = S1 ^ x1,
6902 S2 = S2 ^ x2,
6903 S3 = S3 ^ x3;
6904
6905 I0 = x0,
6906 I1 = x1,
6907 I2 = x2,
6908 I3 = x3;
6909 }
6910
6911 /**
6912 * OFB mode encryption / decryption
6913 * @param {number} x0 - 128-bit input block vector
6914 * @param {number} x1 - 128-bit input block vector
6915 * @param {number} x2 - 128-bit input block vector
6916 * @param {number} x3 - 128-bit input block vector
6917 */
6918 function _ofb(x0, x1, x2, x3) {
6919 x0 = x0 | 0;
6920 x1 = x1 | 0;
6921 x2 = x2 | 0;
6922 x3 = x3 | 0;
6923
6924 _core(
6925 0x0000, 0x0800, 0x1000,
6926 R,
6927 I0,
6928 I1,
6929 I2,
6930 I3
6931 );
6932
6933 I0 = S0,
6934 I1 = S1,
6935 I2 = S2,
6936 I3 = S3;
6937
6938 S0 = S0 ^ x0,
6939 S1 = S1 ^ x1,
6940 S2 = S2 ^ x2,
6941 S3 = S3 ^ x3;
6942 }
6943
6944 /**
6945 * CTR mode encryption / decryption
6946 * @param {number} x0 - 128-bit input block vector
6947 * @param {number} x1 - 128-bit input block vector
6948 * @param {number} x2 - 128-bit input block vector
6949 * @param {number} x3 - 128-bit input block vector
6950 */
6951 function _ctr(x0, x1, x2, x3) {
6952 x0 = x0 | 0;
6953 x1 = x1 | 0;
6954 x2 = x2 | 0;
6955 x3 = x3 | 0;
6956
6957 _core(
6958 0x0000, 0x0800, 0x1000,
6959 R,
6960 N0,
6961 N1,
6962 N2,
6963 N3
6964 );
6965
6966 N3 = (~M3 & N3) | M3 & (N3 + 1);
6967 N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));
6968 N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));
6969 N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));
6970
6971 S0 = S0 ^ x0;
6972 S1 = S1 ^ x1;
6973 S2 = S2 ^ x2;
6974 S3 = S3 ^ x3;
6975 }
6976
6977 /**
6978 * GCM mode MAC calculation
6979 * @param {number} x0 - 128-bit input block vector
6980 * @param {number} x1 - 128-bit input block vector
6981 * @param {number} x2 - 128-bit input block vector
6982 * @param {number} x3 - 128-bit input block vector
6983 */
6984 function _gcm_mac(x0, x1, x2, x3) {
6985 x0 = x0 | 0;
6986 x1 = x1 | 0;
6987 x2 = x2 | 0;
6988 x3 = x3 | 0;
6989
6990 var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
6991 z0 = 0, z1 = 0, z2 = 0, z3 = 0,
6992 i = 0, c = 0;
6993
6994 x0 = x0 ^ I0,
6995 x1 = x1 ^ I1,
6996 x2 = x2 ^ I2,
6997 x3 = x3 ^ I3;
6998
6999 y0 = H0 | 0,
7000 y1 = H1 | 0,
7001 y2 = H2 | 0,
7002 y3 = H3 | 0;
7003
7004 for (; (i | 0) < 128; i = (i + 1) | 0) {
7005 if (y0 >>> 31) {
7006 z0 = z0 ^ x0,
7007 z1 = z1 ^ x1,
7008 z2 = z2 ^ x2,
7009 z3 = z3 ^ x3;
7010 }
7011
7012 y0 = (y0 << 1) | (y1 >>> 31),
7013 y1 = (y1 << 1) | (y2 >>> 31),
7014 y2 = (y2 << 1) | (y3 >>> 31),
7015 y3 = (y3 << 1);
7016
7017 c = x3 & 1;
7018
7019 x3 = (x3 >>> 1) | (x2 << 31),
7020 x2 = (x2 >>> 1) | (x1 << 31),
7021 x1 = (x1 >>> 1) | (x0 << 31),
7022 x0 = (x0 >>> 1);
7023
7024 if (c) x0 = x0 ^ 0xe1000000;
7025 }
7026
7027 I0 = z0,
7028 I1 = z1,
7029 I2 = z2,
7030 I3 = z3;
7031 }
7032
7033 /**
7034 * Set the internal rounds number.
7035 * @instance
7036 * @memberof AES_asm
7037 * @param {number} r - number if inner AES rounds
7038 */
7039 function set_rounds(r) {
7040 r = r | 0;
7041 R = r;
7042 }
7043
7044 /**
7045 * Populate the internal state of the module.
7046 * @instance
7047 * @memberof AES_asm
7048 * @param {number} s0 - state vector
7049 * @param {number} s1 - state vector
7050 * @param {number} s2 - state vector
7051 * @param {number} s3 - state vector
7052 */
7053 function set_state(s0, s1, s2, s3) {
7054 s0 = s0 | 0;
7055 s1 = s1 | 0;
7056 s2 = s2 | 0;
7057 s3 = s3 | 0;
7058
7059 S0 = s0,
7060 S1 = s1,
7061 S2 = s2,
7062 S3 = s3;
7063 }
7064
7065 /**
7066 * Populate the internal iv of the module.
7067 * @instance
7068 * @memberof AES_asm
7069 * @param {number} i0 - iv vector
7070 * @param {number} i1 - iv vector
7071 * @param {number} i2 - iv vector
7072 * @param {number} i3 - iv vector
7073 */
7074 function set_iv(i0, i1, i2, i3) {
7075 i0 = i0 | 0;
7076 i1 = i1 | 0;
7077 i2 = i2 | 0;
7078 i3 = i3 | 0;
7079
7080 I0 = i0,
7081 I1 = i1,
7082 I2 = i2,
7083 I3 = i3;
7084 }
7085
7086 /**
7087 * Set nonce for CTR-family modes.
7088 * @instance
7089 * @memberof AES_asm
7090 * @param {number} n0 - nonce vector
7091 * @param {number} n1 - nonce vector
7092 * @param {number} n2 - nonce vector
7093 * @param {number} n3 - nonce vector
7094 */
7095 function set_nonce(n0, n1, n2, n3) {
7096 n0 = n0 | 0;
7097 n1 = n1 | 0;
7098 n2 = n2 | 0;
7099 n3 = n3 | 0;
7100
7101 N0 = n0,
7102 N1 = n1,
7103 N2 = n2,
7104 N3 = n3;
7105 }
7106
7107 /**
7108 * Set counter mask for CTR-family modes.
7109 * @instance
7110 * @memberof AES_asm
7111 * @param {number} m0 - counter mask vector
7112 * @param {number} m1 - counter mask vector
7113 * @param {number} m2 - counter mask vector
7114 * @param {number} m3 - counter mask vector
7115 */
7116 function set_mask(m0, m1, m2, m3) {
7117 m0 = m0 | 0;
7118 m1 = m1 | 0;
7119 m2 = m2 | 0;
7120 m3 = m3 | 0;
7121
7122 M0 = m0,
7123 M1 = m1,
7124 M2 = m2,
7125 M3 = m3;
7126 }
7127
7128 /**
7129 * Set counter for CTR-family modes.
7130 * @instance
7131 * @memberof AES_asm
7132 * @param {number} c0 - counter vector
7133 * @param {number} c1 - counter vector
7134 * @param {number} c2 - counter vector
7135 * @param {number} c3 - counter vector
7136 */
7137 function set_counter(c0, c1, c2, c3) {
7138 c0 = c0 | 0;
7139 c1 = c1 | 0;
7140 c2 = c2 | 0;
7141 c3 = c3 | 0;
7142
7143 N3 = (~M3 & N3) | M3 & c3,
7144 N2 = (~M2 & N2) | M2 & c2,
7145 N1 = (~M1 & N1) | M1 & c1,
7146 N0 = (~M0 & N0) | M0 & c0;
7147 }
7148
7149 /**
7150 * Store the internal state vector into the heap.
7151 * @instance
7152 * @memberof AES_asm
7153 * @param {number} pos - offset where to put the data
7154 * @return {number} The number of bytes have been written into the heap, always 16.
7155 */
7156 function get_state(pos) {
7157 pos = pos | 0;
7158
7159 if (pos & 15) return -1;
7160
7161 DATA[pos | 0] = S0 >>> 24,
7162 DATA[pos | 1] = S0 >>> 16 & 255,
7163 DATA[pos | 2] = S0 >>> 8 & 255,
7164 DATA[pos | 3] = S0 & 255,
7165 DATA[pos | 4] = S1 >>> 24,
7166 DATA[pos | 5] = S1 >>> 16 & 255,
7167 DATA[pos | 6] = S1 >>> 8 & 255,
7168 DATA[pos | 7] = S1 & 255,
7169 DATA[pos | 8] = S2 >>> 24,
7170 DATA[pos | 9] = S2 >>> 16 & 255,
7171 DATA[pos | 10] = S2 >>> 8 & 255,
7172 DATA[pos | 11] = S2 & 255,
7173 DATA[pos | 12] = S3 >>> 24,
7174 DATA[pos | 13] = S3 >>> 16 & 255,
7175 DATA[pos | 14] = S3 >>> 8 & 255,
7176 DATA[pos | 15] = S3 & 255;
7177
7178 return 16;
7179 }
7180
7181 /**
7182 * Store the internal iv vector into the heap.
7183 * @instance
7184 * @memberof AES_asm
7185 * @param {number} pos - offset where to put the data
7186 * @return {number} The number of bytes have been written into the heap, always 16.
7187 */
7188 function get_iv(pos) {
7189 pos = pos | 0;
7190
7191 if (pos & 15) return -1;
7192
7193 DATA[pos | 0] = I0 >>> 24,
7194 DATA[pos | 1] = I0 >>> 16 & 255,
7195 DATA[pos | 2] = I0 >>> 8 & 255,
7196 DATA[pos | 3] = I0 & 255,
7197 DATA[pos | 4] = I1 >>> 24,
7198 DATA[pos | 5] = I1 >>> 16 & 255,
7199 DATA[pos | 6] = I1 >>> 8 & 255,
7200 DATA[pos | 7] = I1 & 255,
7201 DATA[pos | 8] = I2 >>> 24,
7202 DATA[pos | 9] = I2 >>> 16 & 255,
7203 DATA[pos | 10] = I2 >>> 8 & 255,
7204 DATA[pos | 11] = I2 & 255,
7205 DATA[pos | 12] = I3 >>> 24,
7206 DATA[pos | 13] = I3 >>> 16 & 255,
7207 DATA[pos | 14] = I3 >>> 8 & 255,
7208 DATA[pos | 15] = I3 & 255;
7209
7210 return 16;
7211 }
7212
7213 /**
7214 * GCM initialization.
7215 * @instance
7216 * @memberof AES_asm
7217 */
7218 function gcm_init() {
7219 _ecb_enc(0, 0, 0, 0);
7220 H0 = S0,
7221 H1 = S1,
7222 H2 = S2,
7223 H3 = S3;
7224 }
7225
7226 /**
7227 * Perform ciphering operation on the supplied data.
7228 * @instance
7229 * @memberof AES_asm
7230 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
7231 * @param {number} pos - offset of the data being processed
7232 * @param {number} len - length of the data being processed
7233 * @return {number} Actual amount of data have been processed.
7234 */
7235 function cipher(mode, pos, len) {
7236 mode = mode | 0;
7237 pos = pos | 0;
7238 len = len | 0;
7239
7240 var ret = 0;
7241
7242 if (pos & 15) return -1;
7243
7244 while ((len | 0) >= 16) {
7245 _cipher_modes[mode & 7](
7246 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
7247 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
7248 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
7249 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
7250 );
7251
7252 DATA[pos | 0] = S0 >>> 24,
7253 DATA[pos | 1] = S0 >>> 16 & 255,
7254 DATA[pos | 2] = S0 >>> 8 & 255,
7255 DATA[pos | 3] = S0 & 255,
7256 DATA[pos | 4] = S1 >>> 24,
7257 DATA[pos | 5] = S1 >>> 16 & 255,
7258 DATA[pos | 6] = S1 >>> 8 & 255,
7259 DATA[pos | 7] = S1 & 255,
7260 DATA[pos | 8] = S2 >>> 24,
7261 DATA[pos | 9] = S2 >>> 16 & 255,
7262 DATA[pos | 10] = S2 >>> 8 & 255,
7263 DATA[pos | 11] = S2 & 255,
7264 DATA[pos | 12] = S3 >>> 24,
7265 DATA[pos | 13] = S3 >>> 16 & 255,
7266 DATA[pos | 14] = S3 >>> 8 & 255,
7267 DATA[pos | 15] = S3 & 255;
7268
7269 ret = (ret + 16) | 0,
7270 pos = (pos + 16) | 0,
7271 len = (len - 16) | 0;
7272 }
7273
7274 return ret | 0;
7275 }
7276
7277 /**
7278 * Calculates MAC of the supplied data.
7279 * @instance
7280 * @memberof AES_asm
7281 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
7282 * @param {number} pos - offset of the data being processed
7283 * @param {number} len - length of the data being processed
7284 * @return {number} Actual amount of data have been processed.
7285 */
7286 function mac(mode, pos, len) {
7287 mode = mode | 0;
7288 pos = pos | 0;
7289 len = len | 0;
7290
7291 var ret = 0;
7292
7293 if (pos & 15) return -1;
7294
7295 while ((len | 0) >= 16) {
7296 _mac_modes[mode & 1](
7297 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
7298 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
7299 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
7300 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
7301 );
7302
7303 ret = (ret + 16) | 0,
7304 pos = (pos + 16) | 0,
7305 len = (len - 16) | 0;
7306 }
7307
7308 return ret | 0;
7309 }
7310
7311 /**
7312 * AES cipher modes table (virual methods)
7313 */
7314 var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
7315
7316 /**
7317 * AES MAC modes table (virual methods)
7318 */
7319 var _mac_modes = [_cbc_enc, _gcm_mac];
7320
7321 /**
7322 * Asm.js module exports
7323 */
7324 return {
7325 set_rounds: set_rounds,
7326 set_state: set_state,
7327 set_iv: set_iv,
7328 set_nonce: set_nonce,
7329 set_mask: set_mask,
7330 set_counter: set_counter,
7331 get_state: get_state,
7332 get_iv: get_iv,
7333 gcm_init: gcm_init,
7334 cipher: cipher,
7335 mac: mac,
7336 };
7337 }(stdlib, foreign, buffer);
7338
7339 asm.set_key = set_key;
7340
7341 return asm;
7342 };
7343
7344 /**
7345 * AES enciphering mode constants
7346 * @enum {number}
7347 * @const
7348 */
7349 wrapper.ENC = {
7350 ECB: 0,
7351 CBC: 2,
7352 CFB: 4,
7353 OFB: 6,
7354 CTR: 7,
7355 },
7356
7357 /**
7358 * AES deciphering mode constants
7359 * @enum {number}
7360 * @const
7361 */
7362 wrapper.DEC = {
7363 ECB: 1,
7364 CBC: 3,
7365 CFB: 5,
7366 OFB: 6,
7367 CTR: 7,
7368 },
7369
7370 /**
7371 * AES MAC mode constants
7372 * @enum {number}
7373 * @const
7374 */
7375 wrapper.MAC = {
7376 CBC: 0,
7377 GCM: 1,
7378 };
7379
7380 /**
7381 * Heap data offset
7382 * @type {number}
7383 * @const
7384 */
7385 wrapper.HEAP_DATA = 0x4000;
7386
7387 return wrapper;
7388}();
7389
7390function is_bytes(a) {
7391 return a instanceof Uint8Array;
7392}
7393function _heap_init(heap, heapSize) {
7394 const size = heap ? heap.byteLength : heapSize || 65536;
7395 if (size & 0xfff || size <= 0)
7396 throw new Error('heap size must be a positive integer and a multiple of 4096');
7397 heap = heap || new Uint8Array(new ArrayBuffer(size));
7398 return heap;
7399}
7400function _heap_write(heap, hpos, data, dpos, dlen) {
7401 const hlen = heap.length - hpos;
7402 const wlen = hlen < dlen ? hlen : dlen;
7403 heap.set(data.subarray(dpos, dpos + wlen), hpos);
7404 return wlen;
7405}
7406function joinBytes(...arg) {
7407 const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);
7408 const ret = new Uint8Array(totalLenght);
7409 let cursor = 0;
7410 for (let i = 0; i < arg.length; i++) {
7411 ret.set(arg[i], cursor);
7412 cursor += arg[i].length;
7413 }
7414 return ret;
7415}
7416
7417class IllegalStateError extends Error {
7418 constructor(...args) {
7419 super(...args);
7420 }
7421}
7422class IllegalArgumentError extends Error {
7423 constructor(...args) {
7424 super(...args);
7425 }
7426}
7427class SecurityError extends Error {
7428 constructor(...args) {
7429 super(...args);
7430 }
7431}
7432
7433const heap_pool = [];
7434const asm_pool = [];
7435class AES {
7436 constructor(key, iv, padding = true, mode, heap, asm) {
7437 this.pos = 0;
7438 this.len = 0;
7439 this.mode = mode;
7440 // The AES object state
7441 this.pos = 0;
7442 this.len = 0;
7443 this.key = key;
7444 this.iv = iv;
7445 this.padding = padding;
7446 // The AES "worker"
7447 this.acquire_asm(heap, asm);
7448 }
7449 acquire_asm(heap, asm) {
7450 if (this.heap === undefined || this.asm === undefined) {
7451 this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);
7452 this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);
7453 this.reset(this.key, this.iv);
7454 }
7455 return { heap: this.heap, asm: this.asm };
7456 }
7457 release_asm() {
7458 if (this.heap !== undefined && this.asm !== undefined) {
7459 heap_pool.push(this.heap);
7460 asm_pool.push(this.asm);
7461 }
7462 this.heap = undefined;
7463 this.asm = undefined;
7464 }
7465 reset(key, iv) {
7466 const { asm } = this.acquire_asm();
7467 // Key
7468 const keylen = key.length;
7469 if (keylen !== 16 && keylen !== 24 && keylen !== 32)
7470 throw new IllegalArgumentError('illegal key size');
7471 const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
7472 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);
7473 // IV
7474 if (iv !== undefined) {
7475 if (iv.length !== 16)
7476 throw new IllegalArgumentError('illegal iv size');
7477 let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
7478 asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
7479 }
7480 else {
7481 asm.set_iv(0, 0, 0, 0);
7482 }
7483 }
7484 AES_Encrypt_process(data) {
7485 if (!is_bytes(data))
7486 throw new TypeError("data isn't of expected type");
7487 let { heap, asm } = this.acquire_asm();
7488 let amode = AES_asm.ENC[this.mode];
7489 let hpos = AES_asm.HEAP_DATA;
7490 let pos = this.pos;
7491 let len = this.len;
7492 let dpos = 0;
7493 let dlen = data.length || 0;
7494 let rpos = 0;
7495 let rlen = (len + dlen) & -16;
7496 let wlen = 0;
7497 let result = new Uint8Array(rlen);
7498 while (dlen > 0) {
7499 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
7500 len += wlen;
7501 dpos += wlen;
7502 dlen -= wlen;
7503 wlen = asm.cipher(amode, hpos + pos, len);
7504 if (wlen)
7505 result.set(heap.subarray(pos, pos + wlen), rpos);
7506 rpos += wlen;
7507 if (wlen < len) {
7508 pos += wlen;
7509 len -= wlen;
7510 }
7511 else {
7512 pos = 0;
7513 len = 0;
7514 }
7515 }
7516 this.pos = pos;
7517 this.len = len;
7518 return result;
7519 }
7520 AES_Encrypt_finish() {
7521 let { heap, asm } = this.acquire_asm();
7522 let amode = AES_asm.ENC[this.mode];
7523 let hpos = AES_asm.HEAP_DATA;
7524 let pos = this.pos;
7525 let len = this.len;
7526 let plen = 16 - (len % 16);
7527 let rlen = len;
7528 if (this.hasOwnProperty('padding')) {
7529 if (this.padding) {
7530 for (let p = 0; p < plen; ++p) {
7531 heap[pos + len + p] = plen;
7532 }
7533 len += plen;
7534 rlen = len;
7535 }
7536 else if (len % 16) {
7537 throw new IllegalArgumentError('data length must be a multiple of the block size');
7538 }
7539 }
7540 else {
7541 len += plen;
7542 }
7543 const result = new Uint8Array(rlen);
7544 if (len)
7545 asm.cipher(amode, hpos + pos, len);
7546 if (rlen)
7547 result.set(heap.subarray(pos, pos + rlen));
7548 this.pos = 0;
7549 this.len = 0;
7550 this.release_asm();
7551 return result;
7552 }
7553 AES_Decrypt_process(data) {
7554 if (!is_bytes(data))
7555 throw new TypeError("data isn't of expected type");
7556 let { heap, asm } = this.acquire_asm();
7557 let amode = AES_asm.DEC[this.mode];
7558 let hpos = AES_asm.HEAP_DATA;
7559 let pos = this.pos;
7560 let len = this.len;
7561 let dpos = 0;
7562 let dlen = data.length || 0;
7563 let rpos = 0;
7564 let rlen = (len + dlen) & -16;
7565 let plen = 0;
7566 let wlen = 0;
7567 if (this.padding) {
7568 plen = len + dlen - rlen || 16;
7569 rlen -= plen;
7570 }
7571 const result = new Uint8Array(rlen);
7572 while (dlen > 0) {
7573 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
7574 len += wlen;
7575 dpos += wlen;
7576 dlen -= wlen;
7577 wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
7578 if (wlen)
7579 result.set(heap.subarray(pos, pos + wlen), rpos);
7580 rpos += wlen;
7581 if (wlen < len) {
7582 pos += wlen;
7583 len -= wlen;
7584 }
7585 else {
7586 pos = 0;
7587 len = 0;
7588 }
7589 }
7590 this.pos = pos;
7591 this.len = len;
7592 return result;
7593 }
7594 AES_Decrypt_finish() {
7595 let { heap, asm } = this.acquire_asm();
7596 let amode = AES_asm.DEC[this.mode];
7597 let hpos = AES_asm.HEAP_DATA;
7598 let pos = this.pos;
7599 let len = this.len;
7600 let rlen = len;
7601 if (len > 0) {
7602 if (len % 16) {
7603 if (this.hasOwnProperty('padding')) {
7604 throw new IllegalArgumentError('data length must be a multiple of the block size');
7605 }
7606 else {
7607 len += 16 - (len % 16);
7608 }
7609 }
7610 asm.cipher(amode, hpos + pos, len);
7611 if (this.hasOwnProperty('padding') && this.padding) {
7612 let pad = heap[pos + rlen - 1];
7613 if (pad < 1 || pad > 16 || pad > rlen)
7614 throw new SecurityError('bad padding');
7615 let pcheck = 0;
7616 for (let i = pad; i > 1; i--)
7617 pcheck |= pad ^ heap[pos + rlen - i];
7618 if (pcheck)
7619 throw new SecurityError('bad padding');
7620 rlen -= pad;
7621 }
7622 }
7623 const result = new Uint8Array(rlen);
7624 if (rlen > 0) {
7625 result.set(heap.subarray(pos, pos + rlen));
7626 }
7627 this.pos = 0;
7628 this.len = 0;
7629 this.release_asm();
7630 return result;
7631 }
7632}
7633
7634class AES_ECB {
7635 static encrypt(data, key, padding = false) {
7636 return new AES_ECB(key, padding).encrypt(data);
7637 }
7638 static decrypt(data, key, padding = false) {
7639 return new AES_ECB(key, padding).decrypt(data);
7640 }
7641 constructor(key, padding = false, aes) {
7642 this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');
7643 }
7644 encrypt(data) {
7645 const r1 = this.aes.AES_Encrypt_process(data);
7646 const r2 = this.aes.AES_Encrypt_finish();
7647 return joinBytes(r1, r2);
7648 }
7649 decrypt(data) {
7650 const r1 = this.aes.AES_Decrypt_process(data);
7651 const r2 = this.aes.AES_Decrypt_finish();
7652 return joinBytes(r1, r2);
7653 }
7654}
7655
7656// TODO use webCrypto or nodeCrypto when possible.
7657function aes(length) {
7658 const C = function(key) {
7659 const aes_ecb = new AES_ECB(key);
7660
7661 this.encrypt = function(block) {
7662 return aes_ecb.encrypt(block);
7663 };
7664
7665 this.decrypt = function(block) {
7666 return aes_ecb.decrypt(block);
7667 };
7668 };
7669
7670 C.blockSize = C.prototype.blockSize = 16;
7671 C.keySize = C.prototype.keySize = length / 8;
7672
7673 return C;
7674}
7675
7676//Paul Tero, July 2001
7677//http://www.tero.co.uk/des/
7678//
7679//Optimised for performance with large blocks by Michael Hayworth, November 2001
7680//http://www.netdealing.com
7681//
7682// Modified by Recurity Labs GmbH
7683
7684//THIS SOFTWARE IS PROVIDED "AS IS" AND
7685//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
7686//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
7687//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
7688//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
7689//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
7690//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
7691//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
7692//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
7693//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
7694//SUCH DAMAGE.
7695
7696//des
7697//this takes the key, the message, and whether to encrypt or decrypt
7698
7699function des(keys, message, encrypt, mode, iv, padding) {
7700 //declaring this locally speeds things up a bit
7701 const spfunction1 = [
7702 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
7703 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
7704 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
7705 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
7706 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
7707 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
7708 ];
7709 const spfunction2 = [
7710 -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,
7711 -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,
7712 -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,
7713 -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,
7714 -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,
7715 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,
7716 -0x7fef7fe0, 0x108000
7717 ];
7718 const spfunction3 = [
7719 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
7720 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
7721 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
7722 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
7723 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
7724 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
7725 ];
7726 const spfunction4 = [
7727 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
7728 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
7729 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
7730 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
7731 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
7732 ];
7733 const spfunction5 = [
7734 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
7735 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
7736 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
7737 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
7738 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
7739 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
7740 0x40080000, 0x2080100, 0x40000100
7741 ];
7742 const spfunction6 = [
7743 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
7744 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
7745 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
7746 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
7747 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
7748 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
7749 ];
7750 const spfunction7 = [
7751 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
7752 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
7753 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
7754 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
7755 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
7756 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
7757 ];
7758 const spfunction8 = [
7759 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
7760 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
7761 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
7762 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
7763 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
7764 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
7765 ];
7766
7767 //create the 16 or 48 subkeys we will need
7768 let m = 0;
7769 let i;
7770 let j;
7771 let temp;
7772 let right1;
7773 let right2;
7774 let left;
7775 let right;
7776 let looping;
7777 let cbcleft;
7778 let cbcleft2;
7779 let cbcright;
7780 let cbcright2;
7781 let endloop;
7782 let loopinc;
7783 let len = message.length;
7784
7785 //set up the loops for single and triple des
7786 const iterations = keys.length === 32 ? 3 : 9; //single or triple des
7787 if (iterations === 3) {
7788 looping = encrypt ? [0, 32, 2] : [30, -2, -2];
7789 } else {
7790 looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
7791 }
7792
7793 //pad the message depending on the padding parameter
7794 //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
7795 if (encrypt) {
7796 message = des_addPadding(message, padding);
7797 len = message.length;
7798 }
7799
7800 //store the result here
7801 let result = new Uint8Array(len);
7802 let k = 0;
7803
7804 if (mode === 1) { //CBC mode
7805 cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
7806 cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
7807 m = 0;
7808 }
7809
7810 //loop through each 64 bit chunk of the message
7811 while (m < len) {
7812 left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
7813 right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
7814
7815 //for Cipher Block Chaining mode, xor the message with the previous result
7816 if (mode === 1) {
7817 if (encrypt) {
7818 left ^= cbcleft;
7819 right ^= cbcright;
7820 } else {
7821 cbcleft2 = cbcleft;
7822 cbcright2 = cbcright;
7823 cbcleft = left;
7824 cbcright = right;
7825 }
7826 }
7827
7828 //first each 64 but chunk of the message must be permuted according to IP
7829 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
7830 right ^= temp;
7831 left ^= (temp << 4);
7832 temp = ((left >>> 16) ^ right) & 0x0000ffff;
7833 right ^= temp;
7834 left ^= (temp << 16);
7835 temp = ((right >>> 2) ^ left) & 0x33333333;
7836 left ^= temp;
7837 right ^= (temp << 2);
7838 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
7839 left ^= temp;
7840 right ^= (temp << 8);
7841 temp = ((left >>> 1) ^ right) & 0x55555555;
7842 right ^= temp;
7843 left ^= (temp << 1);
7844
7845 left = ((left << 1) | (left >>> 31));
7846 right = ((right << 1) | (right >>> 31));
7847
7848 //do this either 1 or 3 times for each chunk of the message
7849 for (j = 0; j < iterations; j += 3) {
7850 endloop = looping[j + 1];
7851 loopinc = looping[j + 2];
7852 //now go through and perform the encryption or decryption
7853 for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
7854 right1 = right ^ keys[i];
7855 right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
7856 //the result is attained by passing these bytes through the S selection functions
7857 temp = left;
7858 left = right;
7859 right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
7860 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
7861 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
7862 }
7863 temp = left;
7864 left = right;
7865 right = temp; //unreverse left and right
7866 } //for either 1 or 3 iterations
7867
7868 //move then each one bit to the right
7869 left = ((left >>> 1) | (left << 31));
7870 right = ((right >>> 1) | (right << 31));
7871
7872 //now perform IP-1, which is IP in the opposite direction
7873 temp = ((left >>> 1) ^ right) & 0x55555555;
7874 right ^= temp;
7875 left ^= (temp << 1);
7876 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
7877 left ^= temp;
7878 right ^= (temp << 8);
7879 temp = ((right >>> 2) ^ left) & 0x33333333;
7880 left ^= temp;
7881 right ^= (temp << 2);
7882 temp = ((left >>> 16) ^ right) & 0x0000ffff;
7883 right ^= temp;
7884 left ^= (temp << 16);
7885 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
7886 right ^= temp;
7887 left ^= (temp << 4);
7888
7889 //for Cipher Block Chaining mode, xor the message with the previous result
7890 if (mode === 1) {
7891 if (encrypt) {
7892 cbcleft = left;
7893 cbcright = right;
7894 } else {
7895 left ^= cbcleft2;
7896 right ^= cbcright2;
7897 }
7898 }
7899
7900 result[k++] = (left >>> 24);
7901 result[k++] = ((left >>> 16) & 0xff);
7902 result[k++] = ((left >>> 8) & 0xff);
7903 result[k++] = (left & 0xff);
7904 result[k++] = (right >>> 24);
7905 result[k++] = ((right >>> 16) & 0xff);
7906 result[k++] = ((right >>> 8) & 0xff);
7907 result[k++] = (right & 0xff);
7908 } //for every 8 characters, or 64 bits in the message
7909
7910 //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
7911 if (!encrypt) {
7912 result = des_removePadding(result, padding);
7913 }
7914
7915 return result;
7916} //end of des
7917
7918
7919//des_createKeys
7920//this takes as input a 64 bit key (even though only 56 bits are used)
7921//as an array of 2 integers, and returns 16 48 bit keys
7922
7923function des_createKeys(key) {
7924 //declaring this locally speeds things up a bit
7925 const pc2bytes0 = [
7926 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
7927 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
7928 ];
7929 const pc2bytes1 = [
7930 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
7931 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
7932 ];
7933 const pc2bytes2 = [
7934 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
7935 0x1000000, 0x1000008, 0x1000800, 0x1000808
7936 ];
7937 const pc2bytes3 = [
7938 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
7939 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
7940 ];
7941 const pc2bytes4 = [
7942 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
7943 0x41000, 0x1010, 0x41010
7944 ];
7945 const pc2bytes5 = [
7946 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
7947 0x2000000, 0x2000400, 0x2000020, 0x2000420
7948 ];
7949 const pc2bytes6 = [
7950 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
7951 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
7952 ];
7953 const pc2bytes7 = [
7954 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
7955 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
7956 ];
7957 const pc2bytes8 = [
7958 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
7959 0x2000002, 0x2040002, 0x2000002, 0x2040002
7960 ];
7961 const pc2bytes9 = [
7962 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
7963 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
7964 ];
7965 const pc2bytes10 = [
7966 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
7967 0x102000, 0x102020, 0x102000, 0x102020
7968 ];
7969 const pc2bytes11 = [
7970 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
7971 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
7972 ];
7973 const pc2bytes12 = [
7974 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
7975 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
7976 ];
7977 const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
7978
7979 //how many iterations (1 for des, 3 for triple des)
7980 const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
7981 //stores the return keys
7982 const keys = new Array(32 * iterations);
7983 //now define the left shifts which need to be done
7984 const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
7985 //other variables
7986 let lefttemp;
7987 let righttemp;
7988 let m = 0;
7989 let n = 0;
7990 let temp;
7991
7992 for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
7993 let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
7994 let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
7995
7996 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
7997 right ^= temp;
7998 left ^= (temp << 4);
7999 temp = ((right >>> -16) ^ left) & 0x0000ffff;
8000 left ^= temp;
8001 right ^= (temp << -16);
8002 temp = ((left >>> 2) ^ right) & 0x33333333;
8003 right ^= temp;
8004 left ^= (temp << 2);
8005 temp = ((right >>> -16) ^ left) & 0x0000ffff;
8006 left ^= temp;
8007 right ^= (temp << -16);
8008 temp = ((left >>> 1) ^ right) & 0x55555555;
8009 right ^= temp;
8010 left ^= (temp << 1);
8011 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
8012 left ^= temp;
8013 right ^= (temp << 8);
8014 temp = ((left >>> 1) ^ right) & 0x55555555;
8015 right ^= temp;
8016 left ^= (temp << 1);
8017
8018 //the right side needs to be shifted and to get the last four bits of the left side
8019 temp = (left << 8) | ((right >>> 20) & 0x000000f0);
8020 //left needs to be put upside down
8021 left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
8022 right = temp;
8023
8024 //now go through and perform these shifts on the left and right keys
8025 for (let i = 0; i < shifts.length; i++) {
8026 //shift the keys either one or two bits to the left
8027 if (shifts[i]) {
8028 left = (left << 2) | (left >>> 26);
8029 right = (right << 2) | (right >>> 26);
8030 } else {
8031 left = (left << 1) | (left >>> 27);
8032 right = (right << 1) | (right >>> 27);
8033 }
8034 left &= -0xf;
8035 right &= -0xf;
8036
8037 //now apply PC-2, in such a way that E is easier when encrypting or decrypting
8038 //this conversion will look like PC-2 except only the last 6 bits of each byte are used
8039 //rather than 48 consecutive bits and the order of lines will be according to
8040 //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
8041 lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(
8042 left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
8043 0xf];
8044 righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
8045 pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
8046 pc2bytes13[(right >>> 4) & 0xf];
8047 temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
8048 keys[n++] = lefttemp ^ temp;
8049 keys[n++] = righttemp ^ (temp << 16);
8050 }
8051 } //for each iterations
8052 //return the keys we've created
8053 return keys;
8054} //end of des_createKeys
8055
8056
8057function des_addPadding(message, padding) {
8058 const padLength = 8 - (message.length % 8);
8059
8060 let pad;
8061 if (padding === 2 && (padLength < 8)) { //pad the message with spaces
8062 pad = " ".charCodeAt(0);
8063 } else if (padding === 1) { //PKCS7 padding
8064 pad = padLength;
8065 } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
8066 pad = 0;
8067 } else if (padLength === 8) {
8068 return message;
8069 } else {
8070 throw new Error('des: invalid padding');
8071 }
8072
8073 const paddedMessage = new Uint8Array(message.length + padLength);
8074 for (let i = 0; i < message.length; i++) {
8075 paddedMessage[i] = message[i];
8076 }
8077 for (let j = 0; j < padLength; j++) {
8078 paddedMessage[message.length + j] = pad;
8079 }
8080
8081 return paddedMessage;
8082}
8083
8084function des_removePadding(message, padding) {
8085 let padLength = null;
8086 let pad;
8087 if (padding === 2) { // space padded
8088 pad = " ".charCodeAt(0);
8089 } else if (padding === 1) { // PKCS7
8090 padLength = message[message.length - 1];
8091 } else if (!padding) { // null padding
8092 pad = 0;
8093 } else {
8094 throw new Error('des: invalid padding');
8095 }
8096
8097 if (!padLength) {
8098 padLength = 1;
8099 while (message[message.length - padLength] === pad) {
8100 padLength++;
8101 }
8102 padLength--;
8103 }
8104
8105 return message.subarray(0, message.length - padLength);
8106}
8107
8108// added by Recurity Labs
8109
8110function TripleDES(key) {
8111 this.key = [];
8112
8113 for (let i = 0; i < 3; i++) {
8114 this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
8115 }
8116
8117 this.encrypt = function(block) {
8118 return des(
8119 des_createKeys(this.key[2]),
8120 des(
8121 des_createKeys(this.key[1]),
8122 des(
8123 des_createKeys(this.key[0]),
8124 block, true, 0, null, null
8125 ),
8126 false, 0, null, null
8127 ), true, 0, null, null
8128 );
8129 };
8130}
8131
8132TripleDES.keySize = TripleDES.prototype.keySize = 24;
8133TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
8134
8135// This is "original" DES
8136
8137function DES(key) {
8138 this.key = key;
8139
8140 this.encrypt = function(block, padding) {
8141 const keys = des_createKeys(this.key);
8142 return des(keys, block, true, 0, null, padding);
8143 };
8144
8145 this.decrypt = function(block, padding) {
8146 const keys = des_createKeys(this.key);
8147 return des(keys, block, false, 0, null, padding);
8148 };
8149}
8150
8151// Use of this source code is governed by a BSD-style
8152// license that can be found in the LICENSE file.
8153
8154// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
8155
8156// Modified by Recurity Labs GmbH
8157
8158// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
8159// check www.haneWIN.de for the latest version
8160
8161// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
8162// CAST-128 is a common OpenPGP cipher.
8163
8164
8165// CAST5 constructor
8166
8167function OpenpgpSymencCast5() {
8168 this.BlockSize = 8;
8169 this.KeySize = 16;
8170
8171 this.setKey = function(key) {
8172 this.masking = new Array(16);
8173 this.rotate = new Array(16);
8174
8175 this.reset();
8176
8177 if (key.length === this.KeySize) {
8178 this.keySchedule(key);
8179 } else {
8180 throw new Error('CAST-128: keys must be 16 bytes');
8181 }
8182 return true;
8183 };
8184
8185 this.reset = function() {
8186 for (let i = 0; i < 16; i++) {
8187 this.masking[i] = 0;
8188 this.rotate[i] = 0;
8189 }
8190 };
8191
8192 this.getBlockSize = function() {
8193 return this.BlockSize;
8194 };
8195
8196 this.encrypt = function(src) {
8197 const dst = new Array(src.length);
8198
8199 for (let i = 0; i < src.length; i += 8) {
8200 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
8201 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
8202 let t;
8203
8204 t = r;
8205 r = l ^ f1(r, this.masking[0], this.rotate[0]);
8206 l = t;
8207 t = r;
8208 r = l ^ f2(r, this.masking[1], this.rotate[1]);
8209 l = t;
8210 t = r;
8211 r = l ^ f3(r, this.masking[2], this.rotate[2]);
8212 l = t;
8213 t = r;
8214 r = l ^ f1(r, this.masking[3], this.rotate[3]);
8215 l = t;
8216
8217 t = r;
8218 r = l ^ f2(r, this.masking[4], this.rotate[4]);
8219 l = t;
8220 t = r;
8221 r = l ^ f3(r, this.masking[5], this.rotate[5]);
8222 l = t;
8223 t = r;
8224 r = l ^ f1(r, this.masking[6], this.rotate[6]);
8225 l = t;
8226 t = r;
8227 r = l ^ f2(r, this.masking[7], this.rotate[7]);
8228 l = t;
8229
8230 t = r;
8231 r = l ^ f3(r, this.masking[8], this.rotate[8]);
8232 l = t;
8233 t = r;
8234 r = l ^ f1(r, this.masking[9], this.rotate[9]);
8235 l = t;
8236 t = r;
8237 r = l ^ f2(r, this.masking[10], this.rotate[10]);
8238 l = t;
8239 t = r;
8240 r = l ^ f3(r, this.masking[11], this.rotate[11]);
8241 l = t;
8242
8243 t = r;
8244 r = l ^ f1(r, this.masking[12], this.rotate[12]);
8245 l = t;
8246 t = r;
8247 r = l ^ f2(r, this.masking[13], this.rotate[13]);
8248 l = t;
8249 t = r;
8250 r = l ^ f3(r, this.masking[14], this.rotate[14]);
8251 l = t;
8252 t = r;
8253 r = l ^ f1(r, this.masking[15], this.rotate[15]);
8254 l = t;
8255
8256 dst[i] = (r >>> 24) & 255;
8257 dst[i + 1] = (r >>> 16) & 255;
8258 dst[i + 2] = (r >>> 8) & 255;
8259 dst[i + 3] = r & 255;
8260 dst[i + 4] = (l >>> 24) & 255;
8261 dst[i + 5] = (l >>> 16) & 255;
8262 dst[i + 6] = (l >>> 8) & 255;
8263 dst[i + 7] = l & 255;
8264 }
8265
8266 return dst;
8267 };
8268
8269 this.decrypt = function(src) {
8270 const dst = new Array(src.length);
8271
8272 for (let i = 0; i < src.length; i += 8) {
8273 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
8274 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
8275 let t;
8276
8277 t = r;
8278 r = l ^ f1(r, this.masking[15], this.rotate[15]);
8279 l = t;
8280 t = r;
8281 r = l ^ f3(r, this.masking[14], this.rotate[14]);
8282 l = t;
8283 t = r;
8284 r = l ^ f2(r, this.masking[13], this.rotate[13]);
8285 l = t;
8286 t = r;
8287 r = l ^ f1(r, this.masking[12], this.rotate[12]);
8288 l = t;
8289
8290 t = r;
8291 r = l ^ f3(r, this.masking[11], this.rotate[11]);
8292 l = t;
8293 t = r;
8294 r = l ^ f2(r, this.masking[10], this.rotate[10]);
8295 l = t;
8296 t = r;
8297 r = l ^ f1(r, this.masking[9], this.rotate[9]);
8298 l = t;
8299 t = r;
8300 r = l ^ f3(r, this.masking[8], this.rotate[8]);
8301 l = t;
8302
8303 t = r;
8304 r = l ^ f2(r, this.masking[7], this.rotate[7]);
8305 l = t;
8306 t = r;
8307 r = l ^ f1(r, this.masking[6], this.rotate[6]);
8308 l = t;
8309 t = r;
8310 r = l ^ f3(r, this.masking[5], this.rotate[5]);
8311 l = t;
8312 t = r;
8313 r = l ^ f2(r, this.masking[4], this.rotate[4]);
8314 l = t;
8315
8316 t = r;
8317 r = l ^ f1(r, this.masking[3], this.rotate[3]);
8318 l = t;
8319 t = r;
8320 r = l ^ f3(r, this.masking[2], this.rotate[2]);
8321 l = t;
8322 t = r;
8323 r = l ^ f2(r, this.masking[1], this.rotate[1]);
8324 l = t;
8325 t = r;
8326 r = l ^ f1(r, this.masking[0], this.rotate[0]);
8327 l = t;
8328
8329 dst[i] = (r >>> 24) & 255;
8330 dst[i + 1] = (r >>> 16) & 255;
8331 dst[i + 2] = (r >>> 8) & 255;
8332 dst[i + 3] = r & 255;
8333 dst[i + 4] = (l >>> 24) & 255;
8334 dst[i + 5] = (l >> 16) & 255;
8335 dst[i + 6] = (l >> 8) & 255;
8336 dst[i + 7] = l & 255;
8337 }
8338
8339 return dst;
8340 };
8341 const scheduleA = new Array(4);
8342
8343 scheduleA[0] = new Array(4);
8344 scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
8345 scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
8346 scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
8347 scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
8348
8349 scheduleA[1] = new Array(4);
8350 scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
8351 scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
8352 scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
8353 scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
8354
8355 scheduleA[2] = new Array(4);
8356 scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
8357 scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
8358 scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
8359 scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
8360
8361
8362 scheduleA[3] = new Array(4);
8363 scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
8364 scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
8365 scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
8366 scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
8367
8368 const scheduleB = new Array(4);
8369
8370 scheduleB[0] = new Array(4);
8371 scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
8372 scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
8373 scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
8374 scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
8375
8376 scheduleB[1] = new Array(4);
8377 scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
8378 scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
8379 scheduleB[1][2] = [7, 6, 8, 9, 3];
8380 scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
8381
8382
8383 scheduleB[2] = new Array(4);
8384 scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
8385 scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
8386 scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
8387 scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
8388
8389
8390 scheduleB[3] = new Array(4);
8391 scheduleB[3][0] = [8, 9, 7, 6, 3];
8392 scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
8393 scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
8394 scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
8395
8396 // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
8397 this.keySchedule = function(inn) {
8398 const t = new Array(8);
8399 const k = new Array(32);
8400
8401 let j;
8402
8403 for (let i = 0; i < 4; i++) {
8404 j = i * 4;
8405 t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
8406 }
8407
8408 const x = [6, 7, 4, 5];
8409 let ki = 0;
8410 let w;
8411
8412 for (let half = 0; half < 2; half++) {
8413 for (let round = 0; round < 4; round++) {
8414 for (j = 0; j < 4; j++) {
8415 const a = scheduleA[round][j];
8416 w = t[a[1]];
8417
8418 w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
8419 w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
8420 w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
8421 w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
8422 w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
8423 t[a[0]] = w;
8424 }
8425
8426 for (j = 0; j < 4; j++) {
8427 const b = scheduleB[round][j];
8428 w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
8429
8430 w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
8431 w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
8432 w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
8433 w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
8434 k[ki] = w;
8435 ki++;
8436 }
8437 }
8438 }
8439
8440 for (let i = 0; i < 16; i++) {
8441 this.masking[i] = k[i];
8442 this.rotate[i] = k[16 + i] & 0x1f;
8443 }
8444 };
8445
8446 // These are the three 'f' functions. See RFC 2144, section 2.2.
8447
8448 function f1(d, m, r) {
8449 const t = m + d;
8450 const I = (t << r) | (t >>> (32 - r));
8451 return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
8452 }
8453
8454 function f2(d, m, r) {
8455 const t = m ^ d;
8456 const I = (t << r) | (t >>> (32 - r));
8457 return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
8458 }
8459
8460 function f3(d, m, r) {
8461 const t = m - d;
8462 const I = (t << r) | (t >>> (32 - r));
8463 return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
8464 }
8465
8466 const sBox = new Array(8);
8467 sBox[0] = [
8468 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
8469 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
8470 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
8471 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
8472 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
8473 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
8474 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
8475 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
8476 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
8477 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
8478 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
8479 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
8480 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
8481 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
8482 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
8483 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
8484 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
8485 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
8486 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
8487 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
8488 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
8489 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
8490 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
8491 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
8492 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
8493 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
8494 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
8495 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
8496 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
8497 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
8498 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
8499 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
8500 ];
8501
8502 sBox[1] = [
8503 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
8504 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
8505 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
8506 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
8507 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
8508 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
8509 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
8510 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
8511 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
8512 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
8513 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
8514 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
8515 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
8516 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
8517 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
8518 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
8519 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
8520 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
8521 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
8522 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
8523 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
8524 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
8525 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
8526 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
8527 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
8528 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
8529 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
8530 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
8531 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
8532 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
8533 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
8534 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
8535 ];
8536
8537 sBox[2] = [
8538 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
8539 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
8540 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
8541 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
8542 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
8543 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
8544 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
8545 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
8546 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
8547 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
8548 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
8549 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
8550 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
8551 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
8552 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
8553 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
8554 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
8555 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
8556 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
8557 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
8558 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
8559 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
8560 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
8561 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
8562 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
8563 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
8564 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
8565 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
8566 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
8567 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
8568 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
8569 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
8570 ];
8571
8572 sBox[3] = [
8573 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
8574 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
8575 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
8576 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
8577 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
8578 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
8579 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
8580 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
8581 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
8582 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
8583 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
8584 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
8585 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
8586 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
8587 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
8588 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
8589 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
8590 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
8591 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
8592 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
8593 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
8594 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
8595 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
8596 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
8597 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
8598 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
8599 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
8600 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
8601 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
8602 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
8603 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
8604 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
8605 ];
8606
8607 sBox[4] = [
8608 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
8609 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
8610 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
8611 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
8612 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
8613 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
8614 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
8615 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
8616 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
8617 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
8618 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
8619 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
8620 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
8621 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
8622 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
8623 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
8624 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
8625 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
8626 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
8627 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
8628 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
8629 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
8630 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
8631 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
8632 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
8633 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
8634 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
8635 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
8636 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
8637 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
8638 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
8639 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
8640 ];
8641
8642 sBox[5] = [
8643 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
8644 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
8645 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
8646 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
8647 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
8648 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
8649 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
8650 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
8651 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
8652 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
8653 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
8654 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
8655 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
8656 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
8657 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
8658 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
8659 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
8660 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
8661 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
8662 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
8663 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
8664 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
8665 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
8666 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
8667 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
8668 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
8669 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
8670 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
8671 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
8672 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
8673 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
8674 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
8675 ];
8676
8677 sBox[6] = [
8678 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
8679 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
8680 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
8681 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
8682 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
8683 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
8684 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
8685 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
8686 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
8687 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
8688 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
8689 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
8690 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
8691 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
8692 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
8693 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
8694 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
8695 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
8696 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
8697 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
8698 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
8699 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
8700 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
8701 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
8702 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
8703 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
8704 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
8705 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
8706 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
8707 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
8708 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
8709 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
8710 ];
8711
8712 sBox[7] = [
8713 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
8714 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
8715 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
8716 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
8717 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
8718 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
8719 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
8720 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
8721 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
8722 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
8723 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
8724 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
8725 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
8726 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
8727 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
8728 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
8729 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
8730 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
8731 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
8732 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
8733 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
8734 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
8735 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
8736 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
8737 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
8738 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
8739 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
8740 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
8741 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
8742 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
8743 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
8744 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
8745 ];
8746}
8747
8748function Cast5(key) {
8749 this.cast5 = new OpenpgpSymencCast5();
8750 this.cast5.setKey(key);
8751
8752 this.encrypt = function(block) {
8753 return this.cast5.encrypt(block);
8754 };
8755}
8756
8757Cast5.blockSize = Cast5.prototype.blockSize = 8;
8758Cast5.keySize = Cast5.prototype.keySize = 16;
8759
8760/* eslint-disable no-mixed-operators, no-fallthrough */
8761
8762
8763/* Modified by Recurity Labs GmbH
8764 *
8765 * Cipher.js
8766 * A block-cipher algorithm implementation on JavaScript
8767 * See Cipher.readme.txt for further information.
8768 *
8769 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
8770 * This script file is distributed under the LGPL
8771 *
8772 * ACKNOWLEDGMENT
8773 *
8774 * The main subroutines are written by Michiel van Everdingen.
8775 *
8776 * Michiel van Everdingen
8777 * http://home.versatel.nl/MAvanEverdingen/index.html
8778 *
8779 * All rights for these routines are reserved to Michiel van Everdingen.
8780 *
8781 */
8782
8783////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
8784//Math
8785////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
8786
8787const MAXINT = 0xFFFFFFFF;
8788
8789function rotw(w, n) {
8790 return (w << n | w >>> (32 - n)) & MAXINT;
8791}
8792
8793function getW(a, i) {
8794 return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
8795}
8796
8797function setW(a, i, w) {
8798 a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
8799}
8800
8801function getB(x, n) {
8802 return (x >>> (n * 8)) & 0xFF;
8803}
8804
8805// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
8806// Twofish
8807// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
8808
8809function createTwofish() {
8810 //
8811 let keyBytes = null;
8812 let dataBytes = null;
8813 let dataOffset = -1;
8814 // var dataLength = -1;
8815 // var idx2 = -1;
8816 //
8817
8818 let tfsKey = [];
8819 let tfsM = [
8820 [],
8821 [],
8822 [],
8823 []
8824 ];
8825
8826 function tfsInit(key) {
8827 keyBytes = key;
8828 let i;
8829 let a;
8830 let b;
8831 let c;
8832 let d;
8833 const meKey = [];
8834 const moKey = [];
8835 const inKey = [];
8836 let kLen;
8837 const sKey = [];
8838 let f01;
8839 let f5b;
8840 let fef;
8841
8842 const q0 = [
8843 [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
8844 [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
8845 ];
8846 const q1 = [
8847 [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
8848 [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
8849 ];
8850 const q2 = [
8851 [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
8852 [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
8853 ];
8854 const q3 = [
8855 [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
8856 [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
8857 ];
8858 const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
8859 const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
8860 const q = [
8861 [],
8862 []
8863 ];
8864 const m = [
8865 [],
8866 [],
8867 [],
8868 []
8869 ];
8870
8871 function ffm5b(x) {
8872 return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
8873 }
8874
8875 function ffmEf(x) {
8876 return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
8877 }
8878
8879 function mdsRem(p, q) {
8880 let i;
8881 let t;
8882 let u;
8883 for (i = 0; i < 8; i++) {
8884 t = q >>> 24;
8885 q = ((q << 8) & MAXINT) | p >>> 24;
8886 p = (p << 8) & MAXINT;
8887 u = t << 1;
8888 if (t & 128) {
8889 u ^= 333;
8890 }
8891 q ^= t ^ (u << 16);
8892 u ^= t >>> 1;
8893 if (t & 1) {
8894 u ^= 166;
8895 }
8896 q ^= u << 24 | u << 8;
8897 }
8898 return q;
8899 }
8900
8901 function qp(n, x) {
8902 const a = x >> 4;
8903 const b = x & 15;
8904 const c = q0[n][a ^ b];
8905 const d = q1[n][ror4[b] ^ ashx[a]];
8906 return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
8907 }
8908
8909 function hFun(x, key) {
8910 let a = getB(x, 0);
8911 let b = getB(x, 1);
8912 let c = getB(x, 2);
8913 let d = getB(x, 3);
8914 switch (kLen) {
8915 case 4:
8916 a = q[1][a] ^ getB(key[3], 0);
8917 b = q[0][b] ^ getB(key[3], 1);
8918 c = q[0][c] ^ getB(key[3], 2);
8919 d = q[1][d] ^ getB(key[3], 3);
8920 case 3:
8921 a = q[1][a] ^ getB(key[2], 0);
8922 b = q[1][b] ^ getB(key[2], 1);
8923 c = q[0][c] ^ getB(key[2], 2);
8924 d = q[0][d] ^ getB(key[2], 3);
8925 case 2:
8926 a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
8927 b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
8928 c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
8929 d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
8930 }
8931 return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
8932 }
8933
8934 keyBytes = keyBytes.slice(0, 32);
8935 i = keyBytes.length;
8936 while (i !== 16 && i !== 24 && i !== 32) {
8937 keyBytes[i++] = 0;
8938 }
8939
8940 for (i = 0; i < keyBytes.length; i += 4) {
8941 inKey[i >> 2] = getW(keyBytes, i);
8942 }
8943 for (i = 0; i < 256; i++) {
8944 q[0][i] = qp(0, i);
8945 q[1][i] = qp(1, i);
8946 }
8947 for (i = 0; i < 256; i++) {
8948 f01 = q[1][i];
8949 f5b = ffm5b(f01);
8950 fef = ffmEf(f01);
8951 m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
8952 m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
8953 f01 = q[0][i];
8954 f5b = ffm5b(f01);
8955 fef = ffmEf(f01);
8956 m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
8957 m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
8958 }
8959
8960 kLen = inKey.length / 2;
8961 for (i = 0; i < kLen; i++) {
8962 a = inKey[i + i];
8963 meKey[i] = a;
8964 b = inKey[i + i + 1];
8965 moKey[i] = b;
8966 sKey[kLen - i - 1] = mdsRem(a, b);
8967 }
8968 for (i = 0; i < 40; i += 2) {
8969 a = 0x1010101 * i;
8970 b = a + 0x1010101;
8971 a = hFun(a, meKey);
8972 b = rotw(hFun(b, moKey), 8);
8973 tfsKey[i] = (a + b) & MAXINT;
8974 tfsKey[i + 1] = rotw(a + 2 * b, 9);
8975 }
8976 for (i = 0; i < 256; i++) {
8977 a = b = c = d = i;
8978 switch (kLen) {
8979 case 4:
8980 a = q[1][a] ^ getB(sKey[3], 0);
8981 b = q[0][b] ^ getB(sKey[3], 1);
8982 c = q[0][c] ^ getB(sKey[3], 2);
8983 d = q[1][d] ^ getB(sKey[3], 3);
8984 case 3:
8985 a = q[1][a] ^ getB(sKey[2], 0);
8986 b = q[1][b] ^ getB(sKey[2], 1);
8987 c = q[0][c] ^ getB(sKey[2], 2);
8988 d = q[0][d] ^ getB(sKey[2], 3);
8989 case 2:
8990 tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
8991 tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
8992 tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
8993 tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
8994 }
8995 }
8996 }
8997
8998 function tfsG0(x) {
8999 return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
9000 }
9001
9002 function tfsG1(x) {
9003 return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
9004 }
9005
9006 function tfsFrnd(r, blk) {
9007 let a = tfsG0(blk[0]);
9008 let b = tfsG1(blk[1]);
9009 blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
9010 blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
9011 a = tfsG0(blk[2]);
9012 b = tfsG1(blk[3]);
9013 blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
9014 blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
9015 }
9016
9017 function tfsIrnd(i, blk) {
9018 let a = tfsG0(blk[0]);
9019 let b = tfsG1(blk[1]);
9020 blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
9021 blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
9022 a = tfsG0(blk[2]);
9023 b = tfsG1(blk[3]);
9024 blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
9025 blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
9026 }
9027
9028 function tfsClose() {
9029 tfsKey = [];
9030 tfsM = [
9031 [],
9032 [],
9033 [],
9034 []
9035 ];
9036 }
9037
9038 function tfsEncrypt(data, offset) {
9039 dataBytes = data;
9040 dataOffset = offset;
9041 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
9042 getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
9043 getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
9044 getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
9045 for (let j = 0; j < 8; j++) {
9046 tfsFrnd(j, blk);
9047 }
9048 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
9049 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
9050 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
9051 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
9052 dataOffset += 16;
9053 return dataBytes;
9054 }
9055
9056 function tfsDecrypt(data, offset) {
9057 dataBytes = data;
9058 dataOffset = offset;
9059 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
9060 getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
9061 getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
9062 getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
9063 for (let j = 7; j >= 0; j--) {
9064 tfsIrnd(j, blk);
9065 }
9066 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
9067 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
9068 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
9069 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
9070 dataOffset += 16;
9071 }
9072
9073 // added by Recurity Labs
9074
9075 function tfsFinal() {
9076 return dataBytes;
9077 }
9078
9079 return {
9080 name: "twofish",
9081 blocksize: 128 / 8,
9082 open: tfsInit,
9083 close: tfsClose,
9084 encrypt: tfsEncrypt,
9085 decrypt: tfsDecrypt,
9086 // added by Recurity Labs
9087 finalize: tfsFinal
9088 };
9089}
9090
9091// added by Recurity Labs
9092
9093function TF(key) {
9094 this.tf = createTwofish();
9095 this.tf.open(Array.from(key), 0);
9096
9097 this.encrypt = function(block) {
9098 return this.tf.encrypt(Array.from(block), 0);
9099 };
9100}
9101
9102TF.keySize = TF.prototype.keySize = 32;
9103TF.blockSize = TF.prototype.blockSize = 16;
9104
9105/* Modified by Recurity Labs GmbH
9106 *
9107 * Originally written by nklein software (nklein.com)
9108 */
9109
9110/*
9111 * Javascript implementation based on Bruce Schneier's reference implementation.
9112 *
9113 *
9114 * The constructor doesn't do much of anything. It's just here
9115 * so we can start defining properties and methods and such.
9116 */
9117function Blowfish() {}
9118
9119/*
9120 * Declare the block size so that protocols know what size
9121 * Initialization Vector (IV) they will need.
9122 */
9123Blowfish.prototype.BLOCKSIZE = 8;
9124
9125/*
9126 * These are the default SBOXES.
9127 */
9128Blowfish.prototype.SBOXES = [
9129 [
9130 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
9131 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
9132 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
9133 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
9134 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
9135 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
9136 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
9137 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
9138 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
9139 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
9140 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
9141 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
9142 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
9143 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
9144 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
9145 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
9146 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
9147 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
9148 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
9149 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
9150 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
9151 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
9152 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
9153 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
9154 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
9155 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
9156 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
9157 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
9158 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
9159 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
9160 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
9161 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
9162 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
9163 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
9164 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
9165 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
9166 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
9167 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
9168 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
9169 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
9170 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
9171 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
9172 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
9173 ],
9174 [
9175 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
9176 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
9177 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
9178 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
9179 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
9180 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
9181 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
9182 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
9183 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
9184 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
9185 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
9186 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
9187 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
9188 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
9189 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
9190 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
9191 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
9192 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
9193 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
9194 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
9195 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
9196 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
9197 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
9198 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
9199 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
9200 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
9201 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
9202 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
9203 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
9204 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
9205 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
9206 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
9207 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
9208 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
9209 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
9210 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
9211 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
9212 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
9213 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
9214 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
9215 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
9216 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
9217 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
9218 ],
9219 [
9220 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
9221 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
9222 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
9223 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
9224 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
9225 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
9226 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
9227 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
9228 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
9229 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
9230 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
9231 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
9232 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
9233 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
9234 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
9235 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
9236 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
9237 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
9238 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
9239 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
9240 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
9241 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
9242 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
9243 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
9244 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
9245 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
9246 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
9247 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
9248 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
9249 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
9250 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
9251 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
9252 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
9253 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
9254 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
9255 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
9256 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
9257 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
9258 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
9259 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
9260 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
9261 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
9262 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
9263 ],
9264 [
9265 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
9266 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
9267 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
9268 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
9269 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
9270 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
9271 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
9272 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
9273 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
9274 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
9275 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
9276 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
9277 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
9278 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
9279 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
9280 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
9281 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
9282 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
9283 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
9284 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
9285 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
9286 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
9287 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
9288 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
9289 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
9290 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
9291 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
9292 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
9293 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
9294 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
9295 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
9296 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
9297 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
9298 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
9299 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
9300 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
9301 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
9302 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
9303 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
9304 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
9305 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
9306 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
9307 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
9308 ]
9309];
9310
9311//*
9312//* This is the default PARRAY
9313//*
9314Blowfish.prototype.PARRAY = [
9315 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
9316 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
9317 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
9318];
9319
9320//*
9321//* This is the number of rounds the cipher will go
9322//*
9323Blowfish.prototype.NN = 16;
9324
9325//*
9326//* This function is needed to get rid of problems
9327//* with the high-bit getting set. If we don't do
9328//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
9329//* equal to ( bb & 0x00FFFFFFFF ) even when they
9330//* agree bit-for-bit for the first 32 bits.
9331//*
9332Blowfish.prototype._clean = function(xx) {
9333 if (xx < 0) {
9334 const yy = xx & 0x7FFFFFFF;
9335 xx = yy + 0x80000000;
9336 }
9337 return xx;
9338};
9339
9340//*
9341//* This is the mixing function that uses the sboxes
9342//*
9343Blowfish.prototype._F = function(xx) {
9344 let yy;
9345
9346 const dd = xx & 0x00FF;
9347 xx >>>= 8;
9348 const cc = xx & 0x00FF;
9349 xx >>>= 8;
9350 const bb = xx & 0x00FF;
9351 xx >>>= 8;
9352 const aa = xx & 0x00FF;
9353
9354 yy = this.sboxes[0][aa] + this.sboxes[1][bb];
9355 yy ^= this.sboxes[2][cc];
9356 yy += this.sboxes[3][dd];
9357
9358 return yy;
9359};
9360
9361//*
9362//* This method takes an array with two values, left and right
9363//* and does NN rounds of Blowfish on them.
9364//*
9365Blowfish.prototype._encrypt_block = function(vals) {
9366 let dataL = vals[0];
9367 let dataR = vals[1];
9368
9369 let ii;
9370
9371 for (ii = 0; ii < this.NN; ++ii) {
9372 dataL ^= this.parray[ii];
9373 dataR = this._F(dataL) ^ dataR;
9374
9375 const tmp = dataL;
9376 dataL = dataR;
9377 dataR = tmp;
9378 }
9379
9380 dataL ^= this.parray[this.NN + 0];
9381 dataR ^= this.parray[this.NN + 1];
9382
9383 vals[0] = this._clean(dataR);
9384 vals[1] = this._clean(dataL);
9385};
9386
9387//*
9388//* This method takes a vector of numbers and turns them
9389//* into long words so that they can be processed by the
9390//* real algorithm.
9391//*
9392//* Maybe I should make the real algorithm above take a vector
9393//* instead. That will involve more looping, but it won't require
9394//* the F() method to deconstruct the vector.
9395//*
9396Blowfish.prototype.encrypt_block = function(vector) {
9397 let ii;
9398 const vals = [0, 0];
9399 const off = this.BLOCKSIZE / 2;
9400 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
9401 vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
9402 vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
9403 }
9404
9405 this._encrypt_block(vals);
9406
9407 const ret = [];
9408 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
9409 ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
9410 ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
9411 // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
9412 // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
9413 }
9414
9415 return ret;
9416};
9417
9418//*
9419//* This method takes an array with two values, left and right
9420//* and undoes NN rounds of Blowfish on them.
9421//*
9422Blowfish.prototype._decrypt_block = function(vals) {
9423 let dataL = vals[0];
9424 let dataR = vals[1];
9425
9426 let ii;
9427
9428 for (ii = this.NN + 1; ii > 1; --ii) {
9429 dataL ^= this.parray[ii];
9430 dataR = this._F(dataL) ^ dataR;
9431
9432 const tmp = dataL;
9433 dataL = dataR;
9434 dataR = tmp;
9435 }
9436
9437 dataL ^= this.parray[1];
9438 dataR ^= this.parray[0];
9439
9440 vals[0] = this._clean(dataR);
9441 vals[1] = this._clean(dataL);
9442};
9443
9444//*
9445//* This method takes a key array and initializes the
9446//* sboxes and parray for this encryption.
9447//*
9448Blowfish.prototype.init = function(key) {
9449 let ii;
9450 let jj = 0;
9451
9452 this.parray = [];
9453 for (ii = 0; ii < this.NN + 2; ++ii) {
9454 let data = 0x00000000;
9455 for (let kk = 0; kk < 4; ++kk) {
9456 data = (data << 8) | (key[jj] & 0x00FF);
9457 if (++jj >= key.length) {
9458 jj = 0;
9459 }
9460 }
9461 this.parray[ii] = this.PARRAY[ii] ^ data;
9462 }
9463
9464 this.sboxes = [];
9465 for (ii = 0; ii < 4; ++ii) {
9466 this.sboxes[ii] = [];
9467 for (jj = 0; jj < 256; ++jj) {
9468 this.sboxes[ii][jj] = this.SBOXES[ii][jj];
9469 }
9470 }
9471
9472 const vals = [0x00000000, 0x00000000];
9473
9474 for (ii = 0; ii < this.NN + 2; ii += 2) {
9475 this._encrypt_block(vals);
9476 this.parray[ii + 0] = vals[0];
9477 this.parray[ii + 1] = vals[1];
9478 }
9479
9480 for (ii = 0; ii < 4; ++ii) {
9481 for (jj = 0; jj < 256; jj += 2) {
9482 this._encrypt_block(vals);
9483 this.sboxes[ii][jj + 0] = vals[0];
9484 this.sboxes[ii][jj + 1] = vals[1];
9485 }
9486 }
9487};
9488
9489// added by Recurity Labs
9490function BF(key) {
9491 this.bf = new Blowfish();
9492 this.bf.init(key);
9493
9494 this.encrypt = function(block) {
9495 return this.bf.encrypt_block(block);
9496 };
9497}
9498
9499BF.keySize = BF.prototype.keySize = 16;
9500BF.blockSize = BF.prototype.blockSize = 8;
9501
9502/**
9503 * @fileoverview Symmetric cryptography functions
9504 * @module crypto/cipher
9505 * @private
9506 */
9507
9508/**
9509 * AES-128 encryption and decryption (ID 7)
9510 * @function
9511 * @param {String} key - 128-bit key
9512 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9513 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
9514 * @returns {Object}
9515 */
9516const aes128 = aes(128);
9517/**
9518 * AES-128 Block Cipher (ID 8)
9519 * @function
9520 * @param {String} key - 192-bit key
9521 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9522 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
9523 * @returns {Object}
9524 */
9525const aes192 = aes(192);
9526/**
9527 * AES-128 Block Cipher (ID 9)
9528 * @function
9529 * @param {String} key - 256-bit key
9530 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9531 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
9532 * @returns {Object}
9533 */
9534const aes256 = aes(256);
9535// Not in OpenPGP specifications
9536const des$1 = DES;
9537/**
9538 * Triple DES Block Cipher (ID 2)
9539 * @function
9540 * @param {String} key - 192-bit key
9541 * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
9542 * @returns {Object}
9543 */
9544const tripledes = TripleDES;
9545/**
9546 * CAST-128 Block Cipher (ID 3)
9547 * @function
9548 * @param {String} key - 128-bit key
9549 * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
9550 * @returns {Object}
9551 */
9552const cast5 = Cast5;
9553/**
9554 * Twofish Block Cipher (ID 10)
9555 * @function
9556 * @param {String} key - 256-bit key
9557 * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
9558 * @returns {Object}
9559 */
9560const twofish = TF;
9561/**
9562 * Blowfish Block Cipher (ID 4)
9563 * @function
9564 * @param {String} key - 128-bit key
9565 * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
9566 * @returns {Object}
9567 */
9568const blowfish = BF;
9569/**
9570 * Not implemented
9571 * @function
9572 * @throws {Error}
9573 */
9574const idea = function() {
9575 throw new Error('IDEA symmetric-key algorithm not implemented');
9576};
9577
9578var cipher = /*#__PURE__*/Object.freeze({
9579 __proto__: null,
9580 aes128: aes128,
9581 aes192: aes192,
9582 aes256: aes256,
9583 des: des$1,
9584 tripledes: tripledes,
9585 cast5: cast5,
9586 twofish: twofish,
9587 blowfish: blowfish,
9588 idea: idea
9589});
9590
9591var sha1_asm = function ( stdlib, foreign, buffer ) {
9592 "use asm";
9593
9594 // SHA256 state
9595 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
9596 TOTAL0 = 0, TOTAL1 = 0;
9597
9598 // HMAC state
9599 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
9600 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
9601
9602 // I/O buffer
9603 var HEAP = new stdlib.Uint8Array(buffer);
9604
9605 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
9606 w0 = w0|0;
9607 w1 = w1|0;
9608 w2 = w2|0;
9609 w3 = w3|0;
9610 w4 = w4|0;
9611 w5 = w5|0;
9612 w6 = w6|0;
9613 w7 = w7|0;
9614 w8 = w8|0;
9615 w9 = w9|0;
9616 w10 = w10|0;
9617 w11 = w11|0;
9618 w12 = w12|0;
9619 w13 = w13|0;
9620 w14 = w14|0;
9621 w15 = w15|0;
9622
9623 var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
9624 w16 = 0, w17 = 0, w18 = 0, w19 = 0,
9625 w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
9626 w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
9627 w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
9628 w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
9629 w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
9630 w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
9631
9632 a = H0;
9633 b = H1;
9634 c = H2;
9635 d = H3;
9636 e = H4;
9637
9638 // 0
9639 t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9640 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9641
9642 // 1
9643 t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9644 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9645
9646 // 2
9647 t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9648 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9649
9650 // 3
9651 t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9652 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9653
9654 // 4
9655 t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9656 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9657
9658 // 5
9659 t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9660 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9661
9662 // 6
9663 t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9664 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9665
9666 // 7
9667 t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9668 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9669
9670 // 8
9671 t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9672 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9673
9674 // 9
9675 t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9676 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9677
9678 // 10
9679 t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9680 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9681
9682 // 11
9683 t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9684 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9685
9686 // 12
9687 t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9688 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9689
9690 // 13
9691 t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9692 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9693
9694 // 14
9695 t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9696 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9697
9698 // 15
9699 t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9700 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9701
9702 // 16
9703 n = w13 ^ w8 ^ w2 ^ w0;
9704 w16 = (n << 1) | (n >>> 31);
9705 t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9706 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9707
9708 // 17
9709 n = w14 ^ w9 ^ w3 ^ w1;
9710 w17 = (n << 1) | (n >>> 31);
9711 t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9712 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9713
9714 // 18
9715 n = w15 ^ w10 ^ w4 ^ w2;
9716 w18 = (n << 1) | (n >>> 31);
9717 t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9718 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9719
9720 // 19
9721 n = w16 ^ w11 ^ w5 ^ w3;
9722 w19 = (n << 1) | (n >>> 31);
9723 t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
9724 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9725
9726 // 20
9727 n = w17 ^ w12 ^ w6 ^ w4;
9728 w20 = (n << 1) | (n >>> 31);
9729 t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9730 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9731
9732 // 21
9733 n = w18 ^ w13 ^ w7 ^ w5;
9734 w21 = (n << 1) | (n >>> 31);
9735 t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9736 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9737
9738 // 22
9739 n = w19 ^ w14 ^ w8 ^ w6;
9740 w22 = (n << 1) | (n >>> 31);
9741 t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9742 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9743
9744 // 23
9745 n = w20 ^ w15 ^ w9 ^ w7;
9746 w23 = (n << 1) | (n >>> 31);
9747 t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9748 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9749
9750 // 24
9751 n = w21 ^ w16 ^ w10 ^ w8;
9752 w24 = (n << 1) | (n >>> 31);
9753 t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9754 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9755
9756 // 25
9757 n = w22 ^ w17 ^ w11 ^ w9;
9758 w25 = (n << 1) | (n >>> 31);
9759 t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9760 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9761
9762 // 26
9763 n = w23 ^ w18 ^ w12 ^ w10;
9764 w26 = (n << 1) | (n >>> 31);
9765 t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9766 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9767
9768 // 27
9769 n = w24 ^ w19 ^ w13 ^ w11;
9770 w27 = (n << 1) | (n >>> 31);
9771 t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9772 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9773
9774 // 28
9775 n = w25 ^ w20 ^ w14 ^ w12;
9776 w28 = (n << 1) | (n >>> 31);
9777 t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9778 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9779
9780 // 29
9781 n = w26 ^ w21 ^ w15 ^ w13;
9782 w29 = (n << 1) | (n >>> 31);
9783 t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9784 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9785
9786 // 30
9787 n = w27 ^ w22 ^ w16 ^ w14;
9788 w30 = (n << 1) | (n >>> 31);
9789 t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9790 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9791
9792 // 31
9793 n = w28 ^ w23 ^ w17 ^ w15;
9794 w31 = (n << 1) | (n >>> 31);
9795 t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9796 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9797
9798 // 32
9799 n = w29 ^ w24 ^ w18 ^ w16;
9800 w32 = (n << 1) | (n >>> 31);
9801 t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9802 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9803
9804 // 33
9805 n = w30 ^ w25 ^ w19 ^ w17;
9806 w33 = (n << 1) | (n >>> 31);
9807 t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9808 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9809
9810 // 34
9811 n = w31 ^ w26 ^ w20 ^ w18;
9812 w34 = (n << 1) | (n >>> 31);
9813 t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9814 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9815
9816 // 35
9817 n = w32 ^ w27 ^ w21 ^ w19;
9818 w35 = (n << 1) | (n >>> 31);
9819 t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9820 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9821
9822 // 36
9823 n = w33 ^ w28 ^ w22 ^ w20;
9824 w36 = (n << 1) | (n >>> 31);
9825 t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9826 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9827
9828 // 37
9829 n = w34 ^ w29 ^ w23 ^ w21;
9830 w37 = (n << 1) | (n >>> 31);
9831 t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9832 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9833
9834 // 38
9835 n = w35 ^ w30 ^ w24 ^ w22;
9836 w38 = (n << 1) | (n >>> 31);
9837 t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9838 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9839
9840 // 39
9841 n = w36 ^ w31 ^ w25 ^ w23;
9842 w39 = (n << 1) | (n >>> 31);
9843 t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
9844 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9845
9846 // 40
9847 n = w37 ^ w32 ^ w26 ^ w24;
9848 w40 = (n << 1) | (n >>> 31);
9849 t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9850 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9851
9852 // 41
9853 n = w38 ^ w33 ^ w27 ^ w25;
9854 w41 = (n << 1) | (n >>> 31);
9855 t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9856 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9857
9858 // 42
9859 n = w39 ^ w34 ^ w28 ^ w26;
9860 w42 = (n << 1) | (n >>> 31);
9861 t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9862 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9863
9864 // 43
9865 n = w40 ^ w35 ^ w29 ^ w27;
9866 w43 = (n << 1) | (n >>> 31);
9867 t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9868 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9869
9870 // 44
9871 n = w41 ^ w36 ^ w30 ^ w28;
9872 w44 = (n << 1) | (n >>> 31);
9873 t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9874 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9875
9876 // 45
9877 n = w42 ^ w37 ^ w31 ^ w29;
9878 w45 = (n << 1) | (n >>> 31);
9879 t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9880 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9881
9882 // 46
9883 n = w43 ^ w38 ^ w32 ^ w30;
9884 w46 = (n << 1) | (n >>> 31);
9885 t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9886 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9887
9888 // 47
9889 n = w44 ^ w39 ^ w33 ^ w31;
9890 w47 = (n << 1) | (n >>> 31);
9891 t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9892 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9893
9894 // 48
9895 n = w45 ^ w40 ^ w34 ^ w32;
9896 w48 = (n << 1) | (n >>> 31);
9897 t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9898 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9899
9900 // 49
9901 n = w46 ^ w41 ^ w35 ^ w33;
9902 w49 = (n << 1) | (n >>> 31);
9903 t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9904 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9905
9906 // 50
9907 n = w47 ^ w42 ^ w36 ^ w34;
9908 w50 = (n << 1) | (n >>> 31);
9909 t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9910 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9911
9912 // 51
9913 n = w48 ^ w43 ^ w37 ^ w35;
9914 w51 = (n << 1) | (n >>> 31);
9915 t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9916 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9917
9918 // 52
9919 n = w49 ^ w44 ^ w38 ^ w36;
9920 w52 = (n << 1) | (n >>> 31);
9921 t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9922 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9923
9924 // 53
9925 n = w50 ^ w45 ^ w39 ^ w37;
9926 w53 = (n << 1) | (n >>> 31);
9927 t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9928 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9929
9930 // 54
9931 n = w51 ^ w46 ^ w40 ^ w38;
9932 w54 = (n << 1) | (n >>> 31);
9933 t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9934 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9935
9936 // 55
9937 n = w52 ^ w47 ^ w41 ^ w39;
9938 w55 = (n << 1) | (n >>> 31);
9939 t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9940 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9941
9942 // 56
9943 n = w53 ^ w48 ^ w42 ^ w40;
9944 w56 = (n << 1) | (n >>> 31);
9945 t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9946 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9947
9948 // 57
9949 n = w54 ^ w49 ^ w43 ^ w41;
9950 w57 = (n << 1) | (n >>> 31);
9951 t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9952 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9953
9954 // 58
9955 n = w55 ^ w50 ^ w44 ^ w42;
9956 w58 = (n << 1) | (n >>> 31);
9957 t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9958 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9959
9960 // 59
9961 n = w56 ^ w51 ^ w45 ^ w43;
9962 w59 = (n << 1) | (n >>> 31);
9963 t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
9964 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9965
9966 // 60
9967 n = w57 ^ w52 ^ w46 ^ w44;
9968 w60 = (n << 1) | (n >>> 31);
9969 t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
9970 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9971
9972 // 61
9973 n = w58 ^ w53 ^ w47 ^ w45;
9974 w61 = (n << 1) | (n >>> 31);
9975 t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
9976 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9977
9978 // 62
9979 n = w59 ^ w54 ^ w48 ^ w46;
9980 w62 = (n << 1) | (n >>> 31);
9981 t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
9982 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9983
9984 // 63
9985 n = w60 ^ w55 ^ w49 ^ w47;
9986 w63 = (n << 1) | (n >>> 31);
9987 t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
9988 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9989
9990 // 64
9991 n = w61 ^ w56 ^ w50 ^ w48;
9992 w64 = (n << 1) | (n >>> 31);
9993 t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
9994 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
9995
9996 // 65
9997 n = w62 ^ w57 ^ w51 ^ w49;
9998 w65 = (n << 1) | (n >>> 31);
9999 t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10000 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10001
10002 // 66
10003 n = w63 ^ w58 ^ w52 ^ w50;
10004 w66 = (n << 1) | (n >>> 31);
10005 t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10006 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10007
10008 // 67
10009 n = w64 ^ w59 ^ w53 ^ w51;
10010 w67 = (n << 1) | (n >>> 31);
10011 t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10012 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10013
10014 // 68
10015 n = w65 ^ w60 ^ w54 ^ w52;
10016 w68 = (n << 1) | (n >>> 31);
10017 t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10018 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10019
10020 // 69
10021 n = w66 ^ w61 ^ w55 ^ w53;
10022 w69 = (n << 1) | (n >>> 31);
10023 t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10024 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10025
10026 // 70
10027 n = w67 ^ w62 ^ w56 ^ w54;
10028 w70 = (n << 1) | (n >>> 31);
10029 t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10030 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10031
10032 // 71
10033 n = w68 ^ w63 ^ w57 ^ w55;
10034 w71 = (n << 1) | (n >>> 31);
10035 t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10036 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10037
10038 // 72
10039 n = w69 ^ w64 ^ w58 ^ w56;
10040 w72 = (n << 1) | (n >>> 31);
10041 t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10042 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10043
10044 // 73
10045 n = w70 ^ w65 ^ w59 ^ w57;
10046 w73 = (n << 1) | (n >>> 31);
10047 t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10048 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10049
10050 // 74
10051 n = w71 ^ w66 ^ w60 ^ w58;
10052 w74 = (n << 1) | (n >>> 31);
10053 t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10054 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10055
10056 // 75
10057 n = w72 ^ w67 ^ w61 ^ w59;
10058 w75 = (n << 1) | (n >>> 31);
10059 t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10060 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10061
10062 // 76
10063 n = w73 ^ w68 ^ w62 ^ w60;
10064 w76 = (n << 1) | (n >>> 31);
10065 t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10066 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10067
10068 // 77
10069 n = w74 ^ w69 ^ w63 ^ w61;
10070 w77 = (n << 1) | (n >>> 31);
10071 t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10072 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10073
10074 // 78
10075 n = w75 ^ w70 ^ w64 ^ w62;
10076 w78 = (n << 1) | (n >>> 31);
10077 t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10078 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10079
10080 // 79
10081 n = w76 ^ w71 ^ w65 ^ w63;
10082 w79 = (n << 1) | (n >>> 31);
10083 t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
10084 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
10085
10086 H0 = ( H0 + a )|0;
10087 H1 = ( H1 + b )|0;
10088 H2 = ( H2 + c )|0;
10089 H3 = ( H3 + d )|0;
10090 H4 = ( H4 + e )|0;
10091
10092 }
10093
10094 function _core_heap ( offset ) {
10095 offset = offset|0;
10096
10097 _core(
10098 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
10099 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
10100 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
10101 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
10102 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
10103 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
10104 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
10105 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
10106 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
10107 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
10108 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
10109 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
10110 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
10111 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
10112 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
10113 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
10114 );
10115 }
10116
10117 // offset — multiple of 32
10118 function _state_to_heap ( output ) {
10119 output = output|0;
10120
10121 HEAP[output|0] = H0>>>24;
10122 HEAP[output|1] = H0>>>16&255;
10123 HEAP[output|2] = H0>>>8&255;
10124 HEAP[output|3] = H0&255;
10125 HEAP[output|4] = H1>>>24;
10126 HEAP[output|5] = H1>>>16&255;
10127 HEAP[output|6] = H1>>>8&255;
10128 HEAP[output|7] = H1&255;
10129 HEAP[output|8] = H2>>>24;
10130 HEAP[output|9] = H2>>>16&255;
10131 HEAP[output|10] = H2>>>8&255;
10132 HEAP[output|11] = H2&255;
10133 HEAP[output|12] = H3>>>24;
10134 HEAP[output|13] = H3>>>16&255;
10135 HEAP[output|14] = H3>>>8&255;
10136 HEAP[output|15] = H3&255;
10137 HEAP[output|16] = H4>>>24;
10138 HEAP[output|17] = H4>>>16&255;
10139 HEAP[output|18] = H4>>>8&255;
10140 HEAP[output|19] = H4&255;
10141 }
10142
10143 function reset () {
10144 H0 = 0x67452301;
10145 H1 = 0xefcdab89;
10146 H2 = 0x98badcfe;
10147 H3 = 0x10325476;
10148 H4 = 0xc3d2e1f0;
10149 TOTAL0 = TOTAL1 = 0;
10150 }
10151
10152 function init ( h0, h1, h2, h3, h4, total0, total1 ) {
10153 h0 = h0|0;
10154 h1 = h1|0;
10155 h2 = h2|0;
10156 h3 = h3|0;
10157 h4 = h4|0;
10158 total0 = total0|0;
10159 total1 = total1|0;
10160
10161 H0 = h0;
10162 H1 = h1;
10163 H2 = h2;
10164 H3 = h3;
10165 H4 = h4;
10166 TOTAL0 = total0;
10167 TOTAL1 = total1;
10168 }
10169
10170 // offset — multiple of 64
10171 function process ( offset, length ) {
10172 offset = offset|0;
10173 length = length|0;
10174
10175 var hashed = 0;
10176
10177 if ( offset & 63 )
10178 return -1;
10179
10180 while ( (length|0) >= 64 ) {
10181 _core_heap(offset);
10182
10183 offset = ( offset + 64 )|0;
10184 length = ( length - 64 )|0;
10185
10186 hashed = ( hashed + 64 )|0;
10187 }
10188
10189 TOTAL0 = ( TOTAL0 + hashed )|0;
10190 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
10191
10192 return hashed|0;
10193 }
10194
10195 // offset — multiple of 64
10196 // output — multiple of 32
10197 function finish ( offset, length, output ) {
10198 offset = offset|0;
10199 length = length|0;
10200 output = output|0;
10201
10202 var hashed = 0,
10203 i = 0;
10204
10205 if ( offset & 63 )
10206 return -1;
10207
10208 if ( ~output )
10209 if ( output & 31 )
10210 return -1;
10211
10212 if ( (length|0) >= 64 ) {
10213 hashed = process( offset, length )|0;
10214 if ( (hashed|0) == -1 )
10215 return -1;
10216
10217 offset = ( offset + hashed )|0;
10218 length = ( length - hashed )|0;
10219 }
10220
10221 hashed = ( hashed + length )|0;
10222 TOTAL0 = ( TOTAL0 + length )|0;
10223 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
10224
10225 HEAP[offset|length] = 0x80;
10226
10227 if ( (length|0) >= 56 ) {
10228 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
10229 HEAP[offset|i] = 0x00;
10230 _core_heap(offset);
10231
10232 length = 0;
10233
10234 HEAP[offset|0] = 0;
10235 }
10236
10237 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
10238 HEAP[offset|i] = 0;
10239
10240 HEAP[offset|56] = TOTAL1>>>21&255;
10241 HEAP[offset|57] = TOTAL1>>>13&255;
10242 HEAP[offset|58] = TOTAL1>>>5&255;
10243 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
10244 HEAP[offset|60] = TOTAL0>>>21&255;
10245 HEAP[offset|61] = TOTAL0>>>13&255;
10246 HEAP[offset|62] = TOTAL0>>>5&255;
10247 HEAP[offset|63] = TOTAL0<<3&255;
10248 _core_heap(offset);
10249
10250 if ( ~output )
10251 _state_to_heap(output);
10252
10253 return hashed|0;
10254 }
10255
10256 function hmac_reset () {
10257 H0 = I0;
10258 H1 = I1;
10259 H2 = I2;
10260 H3 = I3;
10261 H4 = I4;
10262 TOTAL0 = 64;
10263 TOTAL1 = 0;
10264 }
10265
10266 function _hmac_opad () {
10267 H0 = O0;
10268 H1 = O1;
10269 H2 = O2;
10270 H3 = O3;
10271 H4 = O4;
10272 TOTAL0 = 64;
10273 TOTAL1 = 0;
10274 }
10275
10276 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
10277 p0 = p0|0;
10278 p1 = p1|0;
10279 p2 = p2|0;
10280 p3 = p3|0;
10281 p4 = p4|0;
10282 p5 = p5|0;
10283 p6 = p6|0;
10284 p7 = p7|0;
10285 p8 = p8|0;
10286 p9 = p9|0;
10287 p10 = p10|0;
10288 p11 = p11|0;
10289 p12 = p12|0;
10290 p13 = p13|0;
10291 p14 = p14|0;
10292 p15 = p15|0;
10293
10294 // opad
10295 reset();
10296 _core(
10297 p0 ^ 0x5c5c5c5c,
10298 p1 ^ 0x5c5c5c5c,
10299 p2 ^ 0x5c5c5c5c,
10300 p3 ^ 0x5c5c5c5c,
10301 p4 ^ 0x5c5c5c5c,
10302 p5 ^ 0x5c5c5c5c,
10303 p6 ^ 0x5c5c5c5c,
10304 p7 ^ 0x5c5c5c5c,
10305 p8 ^ 0x5c5c5c5c,
10306 p9 ^ 0x5c5c5c5c,
10307 p10 ^ 0x5c5c5c5c,
10308 p11 ^ 0x5c5c5c5c,
10309 p12 ^ 0x5c5c5c5c,
10310 p13 ^ 0x5c5c5c5c,
10311 p14 ^ 0x5c5c5c5c,
10312 p15 ^ 0x5c5c5c5c
10313 );
10314 O0 = H0;
10315 O1 = H1;
10316 O2 = H2;
10317 O3 = H3;
10318 O4 = H4;
10319
10320 // ipad
10321 reset();
10322 _core(
10323 p0 ^ 0x36363636,
10324 p1 ^ 0x36363636,
10325 p2 ^ 0x36363636,
10326 p3 ^ 0x36363636,
10327 p4 ^ 0x36363636,
10328 p5 ^ 0x36363636,
10329 p6 ^ 0x36363636,
10330 p7 ^ 0x36363636,
10331 p8 ^ 0x36363636,
10332 p9 ^ 0x36363636,
10333 p10 ^ 0x36363636,
10334 p11 ^ 0x36363636,
10335 p12 ^ 0x36363636,
10336 p13 ^ 0x36363636,
10337 p14 ^ 0x36363636,
10338 p15 ^ 0x36363636
10339 );
10340 I0 = H0;
10341 I1 = H1;
10342 I2 = H2;
10343 I3 = H3;
10344 I4 = H4;
10345
10346 TOTAL0 = 64;
10347 TOTAL1 = 0;
10348 }
10349
10350 // offset — multiple of 64
10351 // output — multiple of 32
10352 function hmac_finish ( offset, length, output ) {
10353 offset = offset|0;
10354 length = length|0;
10355 output = output|0;
10356
10357 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
10358
10359 if ( offset & 63 )
10360 return -1;
10361
10362 if ( ~output )
10363 if ( output & 31 )
10364 return -1;
10365
10366 hashed = finish( offset, length, -1 )|0;
10367 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
10368
10369 _hmac_opad();
10370 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
10371
10372 if ( ~output )
10373 _state_to_heap(output);
10374
10375 return hashed|0;
10376 }
10377
10378 // salt is assumed to be already processed
10379 // offset — multiple of 64
10380 // output — multiple of 32
10381 function pbkdf2_generate_block ( offset, length, block, count, output ) {
10382 offset = offset|0;
10383 length = length|0;
10384 block = block|0;
10385 count = count|0;
10386 output = output|0;
10387
10388 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
10389 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
10390
10391 if ( offset & 63 )
10392 return -1;
10393
10394 if ( ~output )
10395 if ( output & 31 )
10396 return -1;
10397
10398 // pad block number into heap
10399 // FIXME probable OOB write
10400 HEAP[(offset+length)|0] = block>>>24;
10401 HEAP[(offset+length+1)|0] = block>>>16&255;
10402 HEAP[(offset+length+2)|0] = block>>>8&255;
10403 HEAP[(offset+length+3)|0] = block&255;
10404
10405 // finish first iteration
10406 hmac_finish( offset, (length+4)|0, -1 )|0;
10407 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
10408 count = (count-1)|0;
10409
10410 // perform the rest iterations
10411 while ( (count|0) > 0 ) {
10412 hmac_reset();
10413 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
10414 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
10415
10416 _hmac_opad();
10417 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
10418 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
10419
10420 h0 = h0 ^ H0;
10421 h1 = h1 ^ H1;
10422 h2 = h2 ^ H2;
10423 h3 = h3 ^ H3;
10424 h4 = h4 ^ H4;
10425
10426 count = (count-1)|0;
10427 }
10428
10429 H0 = h0;
10430 H1 = h1;
10431 H2 = h2;
10432 H3 = h3;
10433 H4 = h4;
10434
10435 if ( ~output )
10436 _state_to_heap(output);
10437
10438 return 0;
10439 }
10440
10441 return {
10442 // SHA1
10443 reset: reset,
10444 init: init,
10445 process: process,
10446 finish: finish,
10447
10448 // HMAC-SHA1
10449 hmac_reset: hmac_reset,
10450 hmac_init: hmac_init,
10451 hmac_finish: hmac_finish,
10452
10453 // PBKDF2-HMAC-SHA1
10454 pbkdf2_generate_block: pbkdf2_generate_block
10455 }
10456};
10457
10458class Hash {
10459 constructor() {
10460 this.pos = 0;
10461 this.len = 0;
10462 }
10463 reset() {
10464 const { asm } = this.acquire_asm();
10465 this.result = null;
10466 this.pos = 0;
10467 this.len = 0;
10468 asm.reset();
10469 return this;
10470 }
10471 process(data) {
10472 if (this.result !== null)
10473 throw new IllegalStateError('state must be reset before processing new data');
10474 const { asm, heap } = this.acquire_asm();
10475 let hpos = this.pos;
10476 let hlen = this.len;
10477 let dpos = 0;
10478 let dlen = data.length;
10479 let wlen = 0;
10480 while (dlen > 0) {
10481 wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
10482 hlen += wlen;
10483 dpos += wlen;
10484 dlen -= wlen;
10485 wlen = asm.process(hpos, hlen);
10486 hpos += wlen;
10487 hlen -= wlen;
10488 if (!hlen)
10489 hpos = 0;
10490 }
10491 this.pos = hpos;
10492 this.len = hlen;
10493 return this;
10494 }
10495 finish() {
10496 if (this.result !== null)
10497 throw new IllegalStateError('state must be reset before processing new data');
10498 const { asm, heap } = this.acquire_asm();
10499 asm.finish(this.pos, this.len, 0);
10500 this.result = new Uint8Array(this.HASH_SIZE);
10501 this.result.set(heap.subarray(0, this.HASH_SIZE));
10502 this.pos = 0;
10503 this.len = 0;
10504 this.release_asm();
10505 return this;
10506 }
10507}
10508
10509const _sha1_block_size = 64;
10510const _sha1_hash_size = 20;
10511const heap_pool$1 = [];
10512const asm_pool$1 = [];
10513class Sha1 extends Hash {
10514 constructor() {
10515 super();
10516 this.NAME = 'sha1';
10517 this.BLOCK_SIZE = _sha1_block_size;
10518 this.HASH_SIZE = _sha1_hash_size;
10519 this.acquire_asm();
10520 }
10521 acquire_asm() {
10522 if (this.heap === undefined || this.asm === undefined) {
10523 this.heap = heap_pool$1.pop() || _heap_init();
10524 this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
10525 this.reset();
10526 }
10527 return { heap: this.heap, asm: this.asm };
10528 }
10529 release_asm() {
10530 if (this.heap !== undefined && this.asm !== undefined) {
10531 heap_pool$1.push(this.heap);
10532 asm_pool$1.push(this.asm);
10533 }
10534 this.heap = undefined;
10535 this.asm = undefined;
10536 }
10537 static bytes(data) {
10538 return new Sha1().process(data).finish().result;
10539 }
10540}
10541Sha1.NAME = 'sha1';
10542Sha1.heap_pool = [];
10543Sha1.asm_pool = [];
10544Sha1.asm_function = sha1_asm;
10545
10546var sha256_asm = function ( stdlib, foreign, buffer ) {
10547 "use asm";
10548
10549 // SHA256 state
10550 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
10551 TOTAL0 = 0, TOTAL1 = 0;
10552
10553 // HMAC state
10554 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
10555 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
10556
10557 // I/O buffer
10558 var HEAP = new stdlib.Uint8Array(buffer);
10559
10560 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
10561 w0 = w0|0;
10562 w1 = w1|0;
10563 w2 = w2|0;
10564 w3 = w3|0;
10565 w4 = w4|0;
10566 w5 = w5|0;
10567 w6 = w6|0;
10568 w7 = w7|0;
10569 w8 = w8|0;
10570 w9 = w9|0;
10571 w10 = w10|0;
10572 w11 = w11|0;
10573 w12 = w12|0;
10574 w13 = w13|0;
10575 w14 = w14|0;
10576 w15 = w15|0;
10577
10578 var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
10579
10580 a = H0;
10581 b = H1;
10582 c = H2;
10583 d = H3;
10584 e = H4;
10585 f = H5;
10586 g = H6;
10587 h = H7;
10588
10589 // 0
10590 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
10591 d = ( d + h )|0;
10592 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10593
10594 // 1
10595 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
10596 c = ( c + g )|0;
10597 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10598
10599 // 2
10600 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
10601 b = ( b + f )|0;
10602 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10603
10604 // 3
10605 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
10606 a = ( a + e )|0;
10607 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10608
10609 // 4
10610 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
10611 h = ( h + d )|0;
10612 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10613
10614 // 5
10615 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
10616 g = ( g + c )|0;
10617 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10618
10619 // 6
10620 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
10621 f = ( f + b )|0;
10622 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10623
10624 // 7
10625 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
10626 e = ( e + a )|0;
10627 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10628
10629 // 8
10630 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
10631 d = ( d + h )|0;
10632 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10633
10634 // 9
10635 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
10636 c = ( c + g )|0;
10637 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10638
10639 // 10
10640 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
10641 b = ( b + f )|0;
10642 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10643
10644 // 11
10645 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
10646 a = ( a + e )|0;
10647 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10648
10649 // 12
10650 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
10651 h = ( h + d )|0;
10652 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10653
10654 // 13
10655 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
10656 g = ( g + c )|0;
10657 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10658
10659 // 14
10660 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
10661 f = ( f + b )|0;
10662 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10663
10664 // 15
10665 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
10666 e = ( e + a )|0;
10667 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10668
10669 // 16
10670 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
10671 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
10672 d = ( d + h )|0;
10673 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10674
10675 // 17
10676 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
10677 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
10678 c = ( c + g )|0;
10679 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10680
10681 // 18
10682 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
10683 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
10684 b = ( b + f )|0;
10685 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10686
10687 // 19
10688 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
10689 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
10690 a = ( a + e )|0;
10691 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10692
10693 // 20
10694 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
10695 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
10696 h = ( h + d )|0;
10697 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10698
10699 // 21
10700 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
10701 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
10702 g = ( g + c )|0;
10703 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10704
10705 // 22
10706 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
10707 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
10708 f = ( f + b )|0;
10709 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10710
10711 // 23
10712 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
10713 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
10714 e = ( e + a )|0;
10715 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10716
10717 // 24
10718 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
10719 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
10720 d = ( d + h )|0;
10721 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10722
10723 // 25
10724 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
10725 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
10726 c = ( c + g )|0;
10727 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10728
10729 // 26
10730 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
10731 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
10732 b = ( b + f )|0;
10733 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10734
10735 // 27
10736 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
10737 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
10738 a = ( a + e )|0;
10739 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10740
10741 // 28
10742 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
10743 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
10744 h = ( h + d )|0;
10745 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10746
10747 // 29
10748 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
10749 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
10750 g = ( g + c )|0;
10751 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10752
10753 // 30
10754 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
10755 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
10756 f = ( f + b )|0;
10757 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10758
10759 // 31
10760 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
10761 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
10762 e = ( e + a )|0;
10763 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10764
10765 // 32
10766 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
10767 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
10768 d = ( d + h )|0;
10769 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10770
10771 // 33
10772 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
10773 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
10774 c = ( c + g )|0;
10775 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10776
10777 // 34
10778 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
10779 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
10780 b = ( b + f )|0;
10781 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10782
10783 // 35
10784 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
10785 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
10786 a = ( a + e )|0;
10787 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10788
10789 // 36
10790 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
10791 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
10792 h = ( h + d )|0;
10793 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10794
10795 // 37
10796 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
10797 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
10798 g = ( g + c )|0;
10799 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10800
10801 // 38
10802 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
10803 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
10804 f = ( f + b )|0;
10805 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10806
10807 // 39
10808 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
10809 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
10810 e = ( e + a )|0;
10811 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10812
10813 // 40
10814 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
10815 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
10816 d = ( d + h )|0;
10817 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10818
10819 // 41
10820 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
10821 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
10822 c = ( c + g )|0;
10823 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10824
10825 // 42
10826 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
10827 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
10828 b = ( b + f )|0;
10829 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10830
10831 // 43
10832 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
10833 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
10834 a = ( a + e )|0;
10835 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10836
10837 // 44
10838 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
10839 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
10840 h = ( h + d )|0;
10841 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10842
10843 // 45
10844 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
10845 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
10846 g = ( g + c )|0;
10847 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10848
10849 // 46
10850 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
10851 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
10852 f = ( f + b )|0;
10853 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10854
10855 // 47
10856 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
10857 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
10858 e = ( e + a )|0;
10859 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10860
10861 // 48
10862 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
10863 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
10864 d = ( d + h )|0;
10865 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10866
10867 // 49
10868 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
10869 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
10870 c = ( c + g )|0;
10871 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10872
10873 // 50
10874 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
10875 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
10876 b = ( b + f )|0;
10877 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10878
10879 // 51
10880 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
10881 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
10882 a = ( a + e )|0;
10883 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10884
10885 // 52
10886 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
10887 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
10888 h = ( h + d )|0;
10889 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10890
10891 // 53
10892 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
10893 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
10894 g = ( g + c )|0;
10895 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10896
10897 // 54
10898 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
10899 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
10900 f = ( f + b )|0;
10901 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10902
10903 // 55
10904 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
10905 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
10906 e = ( e + a )|0;
10907 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10908
10909 // 56
10910 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
10911 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
10912 d = ( d + h )|0;
10913 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
10914
10915 // 57
10916 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
10917 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
10918 c = ( c + g )|0;
10919 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
10920
10921 // 58
10922 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
10923 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
10924 b = ( b + f )|0;
10925 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
10926
10927 // 59
10928 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
10929 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
10930 a = ( a + e )|0;
10931 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
10932
10933 // 60
10934 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
10935 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
10936 h = ( h + d )|0;
10937 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
10938
10939 // 61
10940 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
10941 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
10942 g = ( g + c )|0;
10943 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
10944
10945 // 62
10946 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
10947 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
10948 f = ( f + b )|0;
10949 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
10950
10951 // 63
10952 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
10953 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
10954 e = ( e + a )|0;
10955 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
10956
10957 H0 = ( H0 + a )|0;
10958 H1 = ( H1 + b )|0;
10959 H2 = ( H2 + c )|0;
10960 H3 = ( H3 + d )|0;
10961 H4 = ( H4 + e )|0;
10962 H5 = ( H5 + f )|0;
10963 H6 = ( H6 + g )|0;
10964 H7 = ( H7 + h )|0;
10965 }
10966
10967 function _core_heap ( offset ) {
10968 offset = offset|0;
10969
10970 _core(
10971 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
10972 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
10973 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
10974 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
10975 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
10976 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
10977 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
10978 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
10979 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
10980 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
10981 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
10982 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
10983 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
10984 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
10985 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
10986 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
10987 );
10988 }
10989
10990 // offset — multiple of 32
10991 function _state_to_heap ( output ) {
10992 output = output|0;
10993
10994 HEAP[output|0] = H0>>>24;
10995 HEAP[output|1] = H0>>>16&255;
10996 HEAP[output|2] = H0>>>8&255;
10997 HEAP[output|3] = H0&255;
10998 HEAP[output|4] = H1>>>24;
10999 HEAP[output|5] = H1>>>16&255;
11000 HEAP[output|6] = H1>>>8&255;
11001 HEAP[output|7] = H1&255;
11002 HEAP[output|8] = H2>>>24;
11003 HEAP[output|9] = H2>>>16&255;
11004 HEAP[output|10] = H2>>>8&255;
11005 HEAP[output|11] = H2&255;
11006 HEAP[output|12] = H3>>>24;
11007 HEAP[output|13] = H3>>>16&255;
11008 HEAP[output|14] = H3>>>8&255;
11009 HEAP[output|15] = H3&255;
11010 HEAP[output|16] = H4>>>24;
11011 HEAP[output|17] = H4>>>16&255;
11012 HEAP[output|18] = H4>>>8&255;
11013 HEAP[output|19] = H4&255;
11014 HEAP[output|20] = H5>>>24;
11015 HEAP[output|21] = H5>>>16&255;
11016 HEAP[output|22] = H5>>>8&255;
11017 HEAP[output|23] = H5&255;
11018 HEAP[output|24] = H6>>>24;
11019 HEAP[output|25] = H6>>>16&255;
11020 HEAP[output|26] = H6>>>8&255;
11021 HEAP[output|27] = H6&255;
11022 HEAP[output|28] = H7>>>24;
11023 HEAP[output|29] = H7>>>16&255;
11024 HEAP[output|30] = H7>>>8&255;
11025 HEAP[output|31] = H7&255;
11026 }
11027
11028 function reset () {
11029 H0 = 0x6a09e667;
11030 H1 = 0xbb67ae85;
11031 H2 = 0x3c6ef372;
11032 H3 = 0xa54ff53a;
11033 H4 = 0x510e527f;
11034 H5 = 0x9b05688c;
11035 H6 = 0x1f83d9ab;
11036 H7 = 0x5be0cd19;
11037 TOTAL0 = TOTAL1 = 0;
11038 }
11039
11040 function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
11041 h0 = h0|0;
11042 h1 = h1|0;
11043 h2 = h2|0;
11044 h3 = h3|0;
11045 h4 = h4|0;
11046 h5 = h5|0;
11047 h6 = h6|0;
11048 h7 = h7|0;
11049 total0 = total0|0;
11050 total1 = total1|0;
11051
11052 H0 = h0;
11053 H1 = h1;
11054 H2 = h2;
11055 H3 = h3;
11056 H4 = h4;
11057 H5 = h5;
11058 H6 = h6;
11059 H7 = h7;
11060 TOTAL0 = total0;
11061 TOTAL1 = total1;
11062 }
11063
11064 // offset — multiple of 64
11065 function process ( offset, length ) {
11066 offset = offset|0;
11067 length = length|0;
11068
11069 var hashed = 0;
11070
11071 if ( offset & 63 )
11072 return -1;
11073
11074 while ( (length|0) >= 64 ) {
11075 _core_heap(offset);
11076
11077 offset = ( offset + 64 )|0;
11078 length = ( length - 64 )|0;
11079
11080 hashed = ( hashed + 64 )|0;
11081 }
11082
11083 TOTAL0 = ( TOTAL0 + hashed )|0;
11084 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
11085
11086 return hashed|0;
11087 }
11088
11089 // offset — multiple of 64
11090 // output — multiple of 32
11091 function finish ( offset, length, output ) {
11092 offset = offset|0;
11093 length = length|0;
11094 output = output|0;
11095
11096 var hashed = 0,
11097 i = 0;
11098
11099 if ( offset & 63 )
11100 return -1;
11101
11102 if ( ~output )
11103 if ( output & 31 )
11104 return -1;
11105
11106 if ( (length|0) >= 64 ) {
11107 hashed = process( offset, length )|0;
11108 if ( (hashed|0) == -1 )
11109 return -1;
11110
11111 offset = ( offset + hashed )|0;
11112 length = ( length - hashed )|0;
11113 }
11114
11115 hashed = ( hashed + length )|0;
11116 TOTAL0 = ( TOTAL0 + length )|0;
11117 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
11118
11119 HEAP[offset|length] = 0x80;
11120
11121 if ( (length|0) >= 56 ) {
11122 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
11123 HEAP[offset|i] = 0x00;
11124
11125 _core_heap(offset);
11126
11127 length = 0;
11128
11129 HEAP[offset|0] = 0;
11130 }
11131
11132 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
11133 HEAP[offset|i] = 0;
11134
11135 HEAP[offset|56] = TOTAL1>>>21&255;
11136 HEAP[offset|57] = TOTAL1>>>13&255;
11137 HEAP[offset|58] = TOTAL1>>>5&255;
11138 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
11139 HEAP[offset|60] = TOTAL0>>>21&255;
11140 HEAP[offset|61] = TOTAL0>>>13&255;
11141 HEAP[offset|62] = TOTAL0>>>5&255;
11142 HEAP[offset|63] = TOTAL0<<3&255;
11143 _core_heap(offset);
11144
11145 if ( ~output )
11146 _state_to_heap(output);
11147
11148 return hashed|0;
11149 }
11150
11151 function hmac_reset () {
11152 H0 = I0;
11153 H1 = I1;
11154 H2 = I2;
11155 H3 = I3;
11156 H4 = I4;
11157 H5 = I5;
11158 H6 = I6;
11159 H7 = I7;
11160 TOTAL0 = 64;
11161 TOTAL1 = 0;
11162 }
11163
11164 function _hmac_opad () {
11165 H0 = O0;
11166 H1 = O1;
11167 H2 = O2;
11168 H3 = O3;
11169 H4 = O4;
11170 H5 = O5;
11171 H6 = O6;
11172 H7 = O7;
11173 TOTAL0 = 64;
11174 TOTAL1 = 0;
11175 }
11176
11177 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
11178 p0 = p0|0;
11179 p1 = p1|0;
11180 p2 = p2|0;
11181 p3 = p3|0;
11182 p4 = p4|0;
11183 p5 = p5|0;
11184 p6 = p6|0;
11185 p7 = p7|0;
11186 p8 = p8|0;
11187 p9 = p9|0;
11188 p10 = p10|0;
11189 p11 = p11|0;
11190 p12 = p12|0;
11191 p13 = p13|0;
11192 p14 = p14|0;
11193 p15 = p15|0;
11194
11195 // opad
11196 reset();
11197 _core(
11198 p0 ^ 0x5c5c5c5c,
11199 p1 ^ 0x5c5c5c5c,
11200 p2 ^ 0x5c5c5c5c,
11201 p3 ^ 0x5c5c5c5c,
11202 p4 ^ 0x5c5c5c5c,
11203 p5 ^ 0x5c5c5c5c,
11204 p6 ^ 0x5c5c5c5c,
11205 p7 ^ 0x5c5c5c5c,
11206 p8 ^ 0x5c5c5c5c,
11207 p9 ^ 0x5c5c5c5c,
11208 p10 ^ 0x5c5c5c5c,
11209 p11 ^ 0x5c5c5c5c,
11210 p12 ^ 0x5c5c5c5c,
11211 p13 ^ 0x5c5c5c5c,
11212 p14 ^ 0x5c5c5c5c,
11213 p15 ^ 0x5c5c5c5c
11214 );
11215 O0 = H0;
11216 O1 = H1;
11217 O2 = H2;
11218 O3 = H3;
11219 O4 = H4;
11220 O5 = H5;
11221 O6 = H6;
11222 O7 = H7;
11223
11224 // ipad
11225 reset();
11226 _core(
11227 p0 ^ 0x36363636,
11228 p1 ^ 0x36363636,
11229 p2 ^ 0x36363636,
11230 p3 ^ 0x36363636,
11231 p4 ^ 0x36363636,
11232 p5 ^ 0x36363636,
11233 p6 ^ 0x36363636,
11234 p7 ^ 0x36363636,
11235 p8 ^ 0x36363636,
11236 p9 ^ 0x36363636,
11237 p10 ^ 0x36363636,
11238 p11 ^ 0x36363636,
11239 p12 ^ 0x36363636,
11240 p13 ^ 0x36363636,
11241 p14 ^ 0x36363636,
11242 p15 ^ 0x36363636
11243 );
11244 I0 = H0;
11245 I1 = H1;
11246 I2 = H2;
11247 I3 = H3;
11248 I4 = H4;
11249 I5 = H5;
11250 I6 = H6;
11251 I7 = H7;
11252
11253 TOTAL0 = 64;
11254 TOTAL1 = 0;
11255 }
11256
11257 // offset — multiple of 64
11258 // output — multiple of 32
11259 function hmac_finish ( offset, length, output ) {
11260 offset = offset|0;
11261 length = length|0;
11262 output = output|0;
11263
11264 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
11265 hashed = 0;
11266
11267 if ( offset & 63 )
11268 return -1;
11269
11270 if ( ~output )
11271 if ( output & 31 )
11272 return -1;
11273
11274 hashed = finish( offset, length, -1 )|0;
11275 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
11276
11277 _hmac_opad();
11278 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
11279
11280 if ( ~output )
11281 _state_to_heap(output);
11282
11283 return hashed|0;
11284 }
11285
11286 // salt is assumed to be already processed
11287 // offset — multiple of 64
11288 // output — multiple of 32
11289 function pbkdf2_generate_block ( offset, length, block, count, output ) {
11290 offset = offset|0;
11291 length = length|0;
11292 block = block|0;
11293 count = count|0;
11294 output = output|0;
11295
11296 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
11297 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
11298
11299 if ( offset & 63 )
11300 return -1;
11301
11302 if ( ~output )
11303 if ( output & 31 )
11304 return -1;
11305
11306 // pad block number into heap
11307 // FIXME probable OOB write
11308 HEAP[(offset+length)|0] = block>>>24;
11309 HEAP[(offset+length+1)|0] = block>>>16&255;
11310 HEAP[(offset+length+2)|0] = block>>>8&255;
11311 HEAP[(offset+length+3)|0] = block&255;
11312
11313 // finish first iteration
11314 hmac_finish( offset, (length+4)|0, -1 )|0;
11315 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
11316 count = (count-1)|0;
11317
11318 // perform the rest iterations
11319 while ( (count|0) > 0 ) {
11320 hmac_reset();
11321 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
11322 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
11323
11324 _hmac_opad();
11325 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
11326 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
11327
11328 h0 = h0 ^ H0;
11329 h1 = h1 ^ H1;
11330 h2 = h2 ^ H2;
11331 h3 = h3 ^ H3;
11332 h4 = h4 ^ H4;
11333 h5 = h5 ^ H5;
11334 h6 = h6 ^ H6;
11335 h7 = h7 ^ H7;
11336
11337 count = (count-1)|0;
11338 }
11339
11340 H0 = h0;
11341 H1 = h1;
11342 H2 = h2;
11343 H3 = h3;
11344 H4 = h4;
11345 H5 = h5;
11346 H6 = h6;
11347 H7 = h7;
11348
11349 if ( ~output )
11350 _state_to_heap(output);
11351
11352 return 0;
11353 }
11354
11355 return {
11356 // SHA256
11357 reset: reset,
11358 init: init,
11359 process: process,
11360 finish: finish,
11361
11362 // HMAC-SHA256
11363 hmac_reset: hmac_reset,
11364 hmac_init: hmac_init,
11365 hmac_finish: hmac_finish,
11366
11367 // PBKDF2-HMAC-SHA256
11368 pbkdf2_generate_block: pbkdf2_generate_block
11369 }
11370};
11371
11372const _sha256_block_size = 64;
11373const _sha256_hash_size = 32;
11374const heap_pool$2 = [];
11375const asm_pool$2 = [];
11376class Sha256 extends Hash {
11377 constructor() {
11378 super();
11379 this.NAME = 'sha256';
11380 this.BLOCK_SIZE = _sha256_block_size;
11381 this.HASH_SIZE = _sha256_hash_size;
11382 this.acquire_asm();
11383 }
11384 acquire_asm() {
11385 if (this.heap === undefined || this.asm === undefined) {
11386 this.heap = heap_pool$2.pop() || _heap_init();
11387 this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
11388 this.reset();
11389 }
11390 return { heap: this.heap, asm: this.asm };
11391 }
11392 release_asm() {
11393 if (this.heap !== undefined && this.asm !== undefined) {
11394 heap_pool$2.push(this.heap);
11395 asm_pool$2.push(this.asm);
11396 }
11397 this.heap = undefined;
11398 this.asm = undefined;
11399 }
11400 static bytes(data) {
11401 return new Sha256().process(data).finish().result;
11402 }
11403}
11404Sha256.NAME = 'sha256';
11405
11406var minimalisticAssert = assert$1;
11407
11408function assert$1(val, msg) {
11409 if (!val)
11410 throw new Error(msg || 'Assertion failed');
11411}
11412
11413assert$1.equal = function assertEqual(l, r, msg) {
11414 if (l != r)
11415 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
11416};
11417
11418var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
11419
11420function createCommonjsModule(fn, module) {
11421 return module = { exports: {} }, fn(module, module.exports), module.exports;
11422}
11423
11424function commonjsRequire () {
11425 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
11426}
11427
11428var inherits_browser = createCommonjsModule(function (module) {
11429if (typeof Object.create === 'function') {
11430 // implementation from standard node.js 'util' module
11431 module.exports = function inherits(ctor, superCtor) {
11432 ctor.super_ = superCtor;
11433 ctor.prototype = Object.create(superCtor.prototype, {
11434 constructor: {
11435 value: ctor,
11436 enumerable: false,
11437 writable: true,
11438 configurable: true
11439 }
11440 });
11441 };
11442} else {
11443 // old school shim for old browsers
11444 module.exports = function inherits(ctor, superCtor) {
11445 ctor.super_ = superCtor;
11446 var TempCtor = function () {};
11447 TempCtor.prototype = superCtor.prototype;
11448 ctor.prototype = new TempCtor();
11449 ctor.prototype.constructor = ctor;
11450 };
11451}
11452});
11453
11454var inherits = createCommonjsModule(function (module) {
11455try {
11456 var util = util__default['default'];
11457 if (typeof util.inherits !== 'function') throw '';
11458 module.exports = util.inherits;
11459} catch (e) {
11460 module.exports = inherits_browser;
11461}
11462});
11463
11464var inherits_1 = inherits;
11465
11466function toArray(msg, enc) {
11467 if (Array.isArray(msg))
11468 return msg.slice();
11469 if (!msg)
11470 return [];
11471 var res = [];
11472 if (typeof msg === 'string') {
11473 if (!enc) {
11474 for (var i = 0; i < msg.length; i++) {
11475 var c = msg.charCodeAt(i);
11476 var hi = c >> 8;
11477 var lo = c & 0xff;
11478 if (hi)
11479 res.push(hi, lo);
11480 else
11481 res.push(lo);
11482 }
11483 } else if (enc === 'hex') {
11484 msg = msg.replace(/[^a-z0-9]+/ig, '');
11485 if (msg.length % 2 !== 0)
11486 msg = '0' + msg;
11487 for (i = 0; i < msg.length; i += 2)
11488 res.push(parseInt(msg[i] + msg[i + 1], 16));
11489 }
11490 } else {
11491 for (i = 0; i < msg.length; i++)
11492 res[i] = msg[i] | 0;
11493 }
11494 return res;
11495}
11496var toArray_1 = toArray;
11497
11498function toHex(msg) {
11499 var res = '';
11500 for (var i = 0; i < msg.length; i++)
11501 res += zero2(msg[i].toString(16));
11502 return res;
11503}
11504var toHex_1 = toHex;
11505
11506function htonl(w) {
11507 var res = (w >>> 24) |
11508 ((w >>> 8) & 0xff00) |
11509 ((w << 8) & 0xff0000) |
11510 ((w & 0xff) << 24);
11511 return res >>> 0;
11512}
11513var htonl_1 = htonl;
11514
11515function toHex32(msg, endian) {
11516 var res = '';
11517 for (var i = 0; i < msg.length; i++) {
11518 var w = msg[i];
11519 if (endian === 'little')
11520 w = htonl(w);
11521 res += zero8(w.toString(16));
11522 }
11523 return res;
11524}
11525var toHex32_1 = toHex32;
11526
11527function zero2(word) {
11528 if (word.length === 1)
11529 return '0' + word;
11530 else
11531 return word;
11532}
11533var zero2_1 = zero2;
11534
11535function zero8(word) {
11536 if (word.length === 7)
11537 return '0' + word;
11538 else if (word.length === 6)
11539 return '00' + word;
11540 else if (word.length === 5)
11541 return '000' + word;
11542 else if (word.length === 4)
11543 return '0000' + word;
11544 else if (word.length === 3)
11545 return '00000' + word;
11546 else if (word.length === 2)
11547 return '000000' + word;
11548 else if (word.length === 1)
11549 return '0000000' + word;
11550 else
11551 return word;
11552}
11553var zero8_1 = zero8;
11554
11555function join32(msg, start, end, endian) {
11556 var len = end - start;
11557 minimalisticAssert(len % 4 === 0);
11558 var res = new Array(len / 4);
11559 for (var i = 0, k = start; i < res.length; i++, k += 4) {
11560 var w;
11561 if (endian === 'big')
11562 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
11563 else
11564 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
11565 res[i] = w >>> 0;
11566 }
11567 return res;
11568}
11569var join32_1 = join32;
11570
11571function split32(msg, endian) {
11572 var res = new Array(msg.length * 4);
11573 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
11574 var m = msg[i];
11575 if (endian === 'big') {
11576 res[k] = m >>> 24;
11577 res[k + 1] = (m >>> 16) & 0xff;
11578 res[k + 2] = (m >>> 8) & 0xff;
11579 res[k + 3] = m & 0xff;
11580 } else {
11581 res[k + 3] = m >>> 24;
11582 res[k + 2] = (m >>> 16) & 0xff;
11583 res[k + 1] = (m >>> 8) & 0xff;
11584 res[k] = m & 0xff;
11585 }
11586 }
11587 return res;
11588}
11589var split32_1 = split32;
11590
11591function rotr32(w, b) {
11592 return (w >>> b) | (w << (32 - b));
11593}
11594var rotr32_1 = rotr32;
11595
11596function rotl32(w, b) {
11597 return (w << b) | (w >>> (32 - b));
11598}
11599var rotl32_1 = rotl32;
11600
11601function sum32(a, b) {
11602 return (a + b) >>> 0;
11603}
11604var sum32_1 = sum32;
11605
11606function sum32_3(a, b, c) {
11607 return (a + b + c) >>> 0;
11608}
11609var sum32_3_1 = sum32_3;
11610
11611function sum32_4(a, b, c, d) {
11612 return (a + b + c + d) >>> 0;
11613}
11614var sum32_4_1 = sum32_4;
11615
11616function sum32_5(a, b, c, d, e) {
11617 return (a + b + c + d + e) >>> 0;
11618}
11619var sum32_5_1 = sum32_5;
11620
11621function sum64(buf, pos, ah, al) {
11622 var bh = buf[pos];
11623 var bl = buf[pos + 1];
11624
11625 var lo = (al + bl) >>> 0;
11626 var hi = (lo < al ? 1 : 0) + ah + bh;
11627 buf[pos] = hi >>> 0;
11628 buf[pos + 1] = lo;
11629}
11630var sum64_1 = sum64;
11631
11632function sum64_hi(ah, al, bh, bl) {
11633 var lo = (al + bl) >>> 0;
11634 var hi = (lo < al ? 1 : 0) + ah + bh;
11635 return hi >>> 0;
11636}
11637var sum64_hi_1 = sum64_hi;
11638
11639function sum64_lo(ah, al, bh, bl) {
11640 var lo = al + bl;
11641 return lo >>> 0;
11642}
11643var sum64_lo_1 = sum64_lo;
11644
11645function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
11646 var carry = 0;
11647 var lo = al;
11648 lo = (lo + bl) >>> 0;
11649 carry += lo < al ? 1 : 0;
11650 lo = (lo + cl) >>> 0;
11651 carry += lo < cl ? 1 : 0;
11652 lo = (lo + dl) >>> 0;
11653 carry += lo < dl ? 1 : 0;
11654
11655 var hi = ah + bh + ch + dh + carry;
11656 return hi >>> 0;
11657}
11658var sum64_4_hi_1 = sum64_4_hi;
11659
11660function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
11661 var lo = al + bl + cl + dl;
11662 return lo >>> 0;
11663}
11664var sum64_4_lo_1 = sum64_4_lo;
11665
11666function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
11667 var carry = 0;
11668 var lo = al;
11669 lo = (lo + bl) >>> 0;
11670 carry += lo < al ? 1 : 0;
11671 lo = (lo + cl) >>> 0;
11672 carry += lo < cl ? 1 : 0;
11673 lo = (lo + dl) >>> 0;
11674 carry += lo < dl ? 1 : 0;
11675 lo = (lo + el) >>> 0;
11676 carry += lo < el ? 1 : 0;
11677
11678 var hi = ah + bh + ch + dh + eh + carry;
11679 return hi >>> 0;
11680}
11681var sum64_5_hi_1 = sum64_5_hi;
11682
11683function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
11684 var lo = al + bl + cl + dl + el;
11685
11686 return lo >>> 0;
11687}
11688var sum64_5_lo_1 = sum64_5_lo;
11689
11690function rotr64_hi(ah, al, num) {
11691 var r = (al << (32 - num)) | (ah >>> num);
11692 return r >>> 0;
11693}
11694var rotr64_hi_1 = rotr64_hi;
11695
11696function rotr64_lo(ah, al, num) {
11697 var r = (ah << (32 - num)) | (al >>> num);
11698 return r >>> 0;
11699}
11700var rotr64_lo_1 = rotr64_lo;
11701
11702function shr64_hi(ah, al, num) {
11703 return ah >>> num;
11704}
11705var shr64_hi_1 = shr64_hi;
11706
11707function shr64_lo(ah, al, num) {
11708 var r = (ah << (32 - num)) | (al >>> num);
11709 return r >>> 0;
11710}
11711var shr64_lo_1 = shr64_lo;
11712
11713var utils = {
11714 inherits: inherits_1,
11715 toArray: toArray_1,
11716 toHex: toHex_1,
11717 htonl: htonl_1,
11718 toHex32: toHex32_1,
11719 zero2: zero2_1,
11720 zero8: zero8_1,
11721 join32: join32_1,
11722 split32: split32_1,
11723 rotr32: rotr32_1,
11724 rotl32: rotl32_1,
11725 sum32: sum32_1,
11726 sum32_3: sum32_3_1,
11727 sum32_4: sum32_4_1,
11728 sum32_5: sum32_5_1,
11729 sum64: sum64_1,
11730 sum64_hi: sum64_hi_1,
11731 sum64_lo: sum64_lo_1,
11732 sum64_4_hi: sum64_4_hi_1,
11733 sum64_4_lo: sum64_4_lo_1,
11734 sum64_5_hi: sum64_5_hi_1,
11735 sum64_5_lo: sum64_5_lo_1,
11736 rotr64_hi: rotr64_hi_1,
11737 rotr64_lo: rotr64_lo_1,
11738 shr64_hi: shr64_hi_1,
11739 shr64_lo: shr64_lo_1
11740};
11741
11742function BlockHash() {
11743 this.pending = null;
11744 this.pendingTotal = 0;
11745 this.blockSize = this.constructor.blockSize;
11746 this.outSize = this.constructor.outSize;
11747 this.hmacStrength = this.constructor.hmacStrength;
11748 this.padLength = this.constructor.padLength / 8;
11749 this.endian = 'big';
11750
11751 this._delta8 = this.blockSize / 8;
11752 this._delta32 = this.blockSize / 32;
11753}
11754var BlockHash_1 = BlockHash;
11755
11756BlockHash.prototype.update = function update(msg, enc) {
11757 // Convert message to array, pad it, and join into 32bit blocks
11758 msg = utils.toArray(msg, enc);
11759 if (!this.pending)
11760 this.pending = msg;
11761 else
11762 this.pending = this.pending.concat(msg);
11763 this.pendingTotal += msg.length;
11764
11765 // Enough data, try updating
11766 if (this.pending.length >= this._delta8) {
11767 msg = this.pending;
11768
11769 // Process pending data in blocks
11770 var r = msg.length % this._delta8;
11771 this.pending = msg.slice(msg.length - r, msg.length);
11772 if (this.pending.length === 0)
11773 this.pending = null;
11774
11775 msg = utils.join32(msg, 0, msg.length - r, this.endian);
11776 for (var i = 0; i < msg.length; i += this._delta32)
11777 this._update(msg, i, i + this._delta32);
11778 }
11779
11780 return this;
11781};
11782
11783BlockHash.prototype.digest = function digest(enc) {
11784 this.update(this._pad());
11785 minimalisticAssert(this.pending === null);
11786
11787 return this._digest(enc);
11788};
11789
11790BlockHash.prototype._pad = function pad() {
11791 var len = this.pendingTotal;
11792 var bytes = this._delta8;
11793 var k = bytes - ((len + this.padLength) % bytes);
11794 var res = new Array(k + this.padLength);
11795 res[0] = 0x80;
11796 for (var i = 1; i < k; i++)
11797 res[i] = 0;
11798
11799 // Append length
11800 len <<= 3;
11801 if (this.endian === 'big') {
11802 for (var t = 8; t < this.padLength; t++)
11803 res[i++] = 0;
11804
11805 res[i++] = 0;
11806 res[i++] = 0;
11807 res[i++] = 0;
11808 res[i++] = 0;
11809 res[i++] = (len >>> 24) & 0xff;
11810 res[i++] = (len >>> 16) & 0xff;
11811 res[i++] = (len >>> 8) & 0xff;
11812 res[i++] = len & 0xff;
11813 } else {
11814 res[i++] = len & 0xff;
11815 res[i++] = (len >>> 8) & 0xff;
11816 res[i++] = (len >>> 16) & 0xff;
11817 res[i++] = (len >>> 24) & 0xff;
11818 res[i++] = 0;
11819 res[i++] = 0;
11820 res[i++] = 0;
11821 res[i++] = 0;
11822
11823 for (t = 8; t < this.padLength; t++)
11824 res[i++] = 0;
11825 }
11826
11827 return res;
11828};
11829
11830var common = {
11831 BlockHash: BlockHash_1
11832};
11833
11834var rotr32$1 = utils.rotr32;
11835
11836function ft_1(s, x, y, z) {
11837 if (s === 0)
11838 return ch32(x, y, z);
11839 if (s === 1 || s === 3)
11840 return p32(x, y, z);
11841 if (s === 2)
11842 return maj32(x, y, z);
11843}
11844var ft_1_1 = ft_1;
11845
11846function ch32(x, y, z) {
11847 return (x & y) ^ ((~x) & z);
11848}
11849var ch32_1 = ch32;
11850
11851function maj32(x, y, z) {
11852 return (x & y) ^ (x & z) ^ (y & z);
11853}
11854var maj32_1 = maj32;
11855
11856function p32(x, y, z) {
11857 return x ^ y ^ z;
11858}
11859var p32_1 = p32;
11860
11861function s0_256(x) {
11862 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
11863}
11864var s0_256_1 = s0_256;
11865
11866function s1_256(x) {
11867 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
11868}
11869var s1_256_1 = s1_256;
11870
11871function g0_256(x) {
11872 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
11873}
11874var g0_256_1 = g0_256;
11875
11876function g1_256(x) {
11877 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
11878}
11879var g1_256_1 = g1_256;
11880
11881var common$1 = {
11882 ft_1: ft_1_1,
11883 ch32: ch32_1,
11884 maj32: maj32_1,
11885 p32: p32_1,
11886 s0_256: s0_256_1,
11887 s1_256: s1_256_1,
11888 g0_256: g0_256_1,
11889 g1_256: g1_256_1
11890};
11891
11892var sum32$1 = utils.sum32;
11893var sum32_4$1 = utils.sum32_4;
11894var sum32_5$1 = utils.sum32_5;
11895var ch32$1 = common$1.ch32;
11896var maj32$1 = common$1.maj32;
11897var s0_256$1 = common$1.s0_256;
11898var s1_256$1 = common$1.s1_256;
11899var g0_256$1 = common$1.g0_256;
11900var g1_256$1 = common$1.g1_256;
11901
11902var BlockHash$1 = common.BlockHash;
11903
11904var sha256_K = [
11905 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
11906 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
11907 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
11908 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
11909 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
11910 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
11911 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
11912 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
11913 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
11914 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
11915 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
11916 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
11917 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
11918 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
11919 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
11920 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
11921];
11922
11923function SHA256() {
11924 if (!(this instanceof SHA256))
11925 return new SHA256();
11926
11927 BlockHash$1.call(this);
11928 this.h = [
11929 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
11930 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
11931 ];
11932 this.k = sha256_K;
11933 this.W = new Array(64);
11934}
11935utils.inherits(SHA256, BlockHash$1);
11936var _256 = SHA256;
11937
11938SHA256.blockSize = 512;
11939SHA256.outSize = 256;
11940SHA256.hmacStrength = 192;
11941SHA256.padLength = 64;
11942
11943SHA256.prototype._update = function _update(msg, start) {
11944 var W = this.W;
11945
11946 for (var i = 0; i < 16; i++)
11947 W[i] = msg[start + i];
11948 for (; i < W.length; i++)
11949 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
11950
11951 var a = this.h[0];
11952 var b = this.h[1];
11953 var c = this.h[2];
11954 var d = this.h[3];
11955 var e = this.h[4];
11956 var f = this.h[5];
11957 var g = this.h[6];
11958 var h = this.h[7];
11959
11960 minimalisticAssert(this.k.length === W.length);
11961 for (i = 0; i < W.length; i++) {
11962 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
11963 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
11964 h = g;
11965 g = f;
11966 f = e;
11967 e = sum32$1(d, T1);
11968 d = c;
11969 c = b;
11970 b = a;
11971 a = sum32$1(T1, T2);
11972 }
11973
11974 this.h[0] = sum32$1(this.h[0], a);
11975 this.h[1] = sum32$1(this.h[1], b);
11976 this.h[2] = sum32$1(this.h[2], c);
11977 this.h[3] = sum32$1(this.h[3], d);
11978 this.h[4] = sum32$1(this.h[4], e);
11979 this.h[5] = sum32$1(this.h[5], f);
11980 this.h[6] = sum32$1(this.h[6], g);
11981 this.h[7] = sum32$1(this.h[7], h);
11982};
11983
11984SHA256.prototype._digest = function digest(enc) {
11985 if (enc === 'hex')
11986 return utils.toHex32(this.h, 'big');
11987 else
11988 return utils.split32(this.h, 'big');
11989};
11990
11991function SHA224() {
11992 if (!(this instanceof SHA224))
11993 return new SHA224();
11994
11995 _256.call(this);
11996 this.h = [
11997 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
11998 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
11999}
12000utils.inherits(SHA224, _256);
12001var _224 = SHA224;
12002
12003SHA224.blockSize = 512;
12004SHA224.outSize = 224;
12005SHA224.hmacStrength = 192;
12006SHA224.padLength = 64;
12007
12008SHA224.prototype._digest = function digest(enc) {
12009 // Just truncate output
12010 if (enc === 'hex')
12011 return utils.toHex32(this.h.slice(0, 7), 'big');
12012 else
12013 return utils.split32(this.h.slice(0, 7), 'big');
12014};
12015
12016var rotr64_hi$1 = utils.rotr64_hi;
12017var rotr64_lo$1 = utils.rotr64_lo;
12018var shr64_hi$1 = utils.shr64_hi;
12019var shr64_lo$1 = utils.shr64_lo;
12020var sum64$1 = utils.sum64;
12021var sum64_hi$1 = utils.sum64_hi;
12022var sum64_lo$1 = utils.sum64_lo;
12023var sum64_4_hi$1 = utils.sum64_4_hi;
12024var sum64_4_lo$1 = utils.sum64_4_lo;
12025var sum64_5_hi$1 = utils.sum64_5_hi;
12026var sum64_5_lo$1 = utils.sum64_5_lo;
12027
12028var BlockHash$2 = common.BlockHash;
12029
12030var sha512_K = [
12031 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
12032 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
12033 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
12034 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
12035 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
12036 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
12037 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
12038 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
12039 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
12040 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
12041 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
12042 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
12043 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
12044 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
12045 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
12046 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
12047 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
12048 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
12049 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
12050 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
12051 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
12052 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
12053 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
12054 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
12055 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
12056 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
12057 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
12058 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
12059 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
12060 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
12061 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
12062 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
12063 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
12064 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
12065 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
12066 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
12067 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
12068 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
12069 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
12070 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
12071];
12072
12073function SHA512() {
12074 if (!(this instanceof SHA512))
12075 return new SHA512();
12076
12077 BlockHash$2.call(this);
12078 this.h = [
12079 0x6a09e667, 0xf3bcc908,
12080 0xbb67ae85, 0x84caa73b,
12081 0x3c6ef372, 0xfe94f82b,
12082 0xa54ff53a, 0x5f1d36f1,
12083 0x510e527f, 0xade682d1,
12084 0x9b05688c, 0x2b3e6c1f,
12085 0x1f83d9ab, 0xfb41bd6b,
12086 0x5be0cd19, 0x137e2179 ];
12087 this.k = sha512_K;
12088 this.W = new Array(160);
12089}
12090utils.inherits(SHA512, BlockHash$2);
12091var _512 = SHA512;
12092
12093SHA512.blockSize = 1024;
12094SHA512.outSize = 512;
12095SHA512.hmacStrength = 192;
12096SHA512.padLength = 128;
12097
12098SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
12099 var W = this.W;
12100
12101 // 32 x 32bit words
12102 for (var i = 0; i < 32; i++)
12103 W[i] = msg[start + i];
12104 for (; i < W.length; i += 2) {
12105 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
12106 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
12107 var c1_hi = W[i - 14]; // i - 7
12108 var c1_lo = W[i - 13];
12109 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
12110 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
12111 var c3_hi = W[i - 32]; // i - 16
12112 var c3_lo = W[i - 31];
12113
12114 W[i] = sum64_4_hi$1(
12115 c0_hi, c0_lo,
12116 c1_hi, c1_lo,
12117 c2_hi, c2_lo,
12118 c3_hi, c3_lo);
12119 W[i + 1] = sum64_4_lo$1(
12120 c0_hi, c0_lo,
12121 c1_hi, c1_lo,
12122 c2_hi, c2_lo,
12123 c3_hi, c3_lo);
12124 }
12125};
12126
12127SHA512.prototype._update = function _update(msg, start) {
12128 this._prepareBlock(msg, start);
12129
12130 var W = this.W;
12131
12132 var ah = this.h[0];
12133 var al = this.h[1];
12134 var bh = this.h[2];
12135 var bl = this.h[3];
12136 var ch = this.h[4];
12137 var cl = this.h[5];
12138 var dh = this.h[6];
12139 var dl = this.h[7];
12140 var eh = this.h[8];
12141 var el = this.h[9];
12142 var fh = this.h[10];
12143 var fl = this.h[11];
12144 var gh = this.h[12];
12145 var gl = this.h[13];
12146 var hh = this.h[14];
12147 var hl = this.h[15];
12148
12149 minimalisticAssert(this.k.length === W.length);
12150 for (var i = 0; i < W.length; i += 2) {
12151 var c0_hi = hh;
12152 var c0_lo = hl;
12153 var c1_hi = s1_512_hi(eh, el);
12154 var c1_lo = s1_512_lo(eh, el);
12155 var c2_hi = ch64_hi(eh, el, fh, fl, gh);
12156 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
12157 var c3_hi = this.k[i];
12158 var c3_lo = this.k[i + 1];
12159 var c4_hi = W[i];
12160 var c4_lo = W[i + 1];
12161
12162 var T1_hi = sum64_5_hi$1(
12163 c0_hi, c0_lo,
12164 c1_hi, c1_lo,
12165 c2_hi, c2_lo,
12166 c3_hi, c3_lo,
12167 c4_hi, c4_lo);
12168 var T1_lo = sum64_5_lo$1(
12169 c0_hi, c0_lo,
12170 c1_hi, c1_lo,
12171 c2_hi, c2_lo,
12172 c3_hi, c3_lo,
12173 c4_hi, c4_lo);
12174
12175 c0_hi = s0_512_hi(ah, al);
12176 c0_lo = s0_512_lo(ah, al);
12177 c1_hi = maj64_hi(ah, al, bh, bl, ch);
12178 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
12179
12180 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
12181 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
12182
12183 hh = gh;
12184 hl = gl;
12185
12186 gh = fh;
12187 gl = fl;
12188
12189 fh = eh;
12190 fl = el;
12191
12192 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
12193 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
12194
12195 dh = ch;
12196 dl = cl;
12197
12198 ch = bh;
12199 cl = bl;
12200
12201 bh = ah;
12202 bl = al;
12203
12204 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
12205 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
12206 }
12207
12208 sum64$1(this.h, 0, ah, al);
12209 sum64$1(this.h, 2, bh, bl);
12210 sum64$1(this.h, 4, ch, cl);
12211 sum64$1(this.h, 6, dh, dl);
12212 sum64$1(this.h, 8, eh, el);
12213 sum64$1(this.h, 10, fh, fl);
12214 sum64$1(this.h, 12, gh, gl);
12215 sum64$1(this.h, 14, hh, hl);
12216};
12217
12218SHA512.prototype._digest = function digest(enc) {
12219 if (enc === 'hex')
12220 return utils.toHex32(this.h, 'big');
12221 else
12222 return utils.split32(this.h, 'big');
12223};
12224
12225function ch64_hi(xh, xl, yh, yl, zh) {
12226 var r = (xh & yh) ^ ((~xh) & zh);
12227 if (r < 0)
12228 r += 0x100000000;
12229 return r;
12230}
12231
12232function ch64_lo(xh, xl, yh, yl, zh, zl) {
12233 var r = (xl & yl) ^ ((~xl) & zl);
12234 if (r < 0)
12235 r += 0x100000000;
12236 return r;
12237}
12238
12239function maj64_hi(xh, xl, yh, yl, zh) {
12240 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
12241 if (r < 0)
12242 r += 0x100000000;
12243 return r;
12244}
12245
12246function maj64_lo(xh, xl, yh, yl, zh, zl) {
12247 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
12248 if (r < 0)
12249 r += 0x100000000;
12250 return r;
12251}
12252
12253function s0_512_hi(xh, xl) {
12254 var c0_hi = rotr64_hi$1(xh, xl, 28);
12255 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
12256 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
12257
12258 var r = c0_hi ^ c1_hi ^ c2_hi;
12259 if (r < 0)
12260 r += 0x100000000;
12261 return r;
12262}
12263
12264function s0_512_lo(xh, xl) {
12265 var c0_lo = rotr64_lo$1(xh, xl, 28);
12266 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
12267 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
12268
12269 var r = c0_lo ^ c1_lo ^ c2_lo;
12270 if (r < 0)
12271 r += 0x100000000;
12272 return r;
12273}
12274
12275function s1_512_hi(xh, xl) {
12276 var c0_hi = rotr64_hi$1(xh, xl, 14);
12277 var c1_hi = rotr64_hi$1(xh, xl, 18);
12278 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
12279
12280 var r = c0_hi ^ c1_hi ^ c2_hi;
12281 if (r < 0)
12282 r += 0x100000000;
12283 return r;
12284}
12285
12286function s1_512_lo(xh, xl) {
12287 var c0_lo = rotr64_lo$1(xh, xl, 14);
12288 var c1_lo = rotr64_lo$1(xh, xl, 18);
12289 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
12290
12291 var r = c0_lo ^ c1_lo ^ c2_lo;
12292 if (r < 0)
12293 r += 0x100000000;
12294 return r;
12295}
12296
12297function g0_512_hi(xh, xl) {
12298 var c0_hi = rotr64_hi$1(xh, xl, 1);
12299 var c1_hi = rotr64_hi$1(xh, xl, 8);
12300 var c2_hi = shr64_hi$1(xh, xl, 7);
12301
12302 var r = c0_hi ^ c1_hi ^ c2_hi;
12303 if (r < 0)
12304 r += 0x100000000;
12305 return r;
12306}
12307
12308function g0_512_lo(xh, xl) {
12309 var c0_lo = rotr64_lo$1(xh, xl, 1);
12310 var c1_lo = rotr64_lo$1(xh, xl, 8);
12311 var c2_lo = shr64_lo$1(xh, xl, 7);
12312
12313 var r = c0_lo ^ c1_lo ^ c2_lo;
12314 if (r < 0)
12315 r += 0x100000000;
12316 return r;
12317}
12318
12319function g1_512_hi(xh, xl) {
12320 var c0_hi = rotr64_hi$1(xh, xl, 19);
12321 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
12322 var c2_hi = shr64_hi$1(xh, xl, 6);
12323
12324 var r = c0_hi ^ c1_hi ^ c2_hi;
12325 if (r < 0)
12326 r += 0x100000000;
12327 return r;
12328}
12329
12330function g1_512_lo(xh, xl) {
12331 var c0_lo = rotr64_lo$1(xh, xl, 19);
12332 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
12333 var c2_lo = shr64_lo$1(xh, xl, 6);
12334
12335 var r = c0_lo ^ c1_lo ^ c2_lo;
12336 if (r < 0)
12337 r += 0x100000000;
12338 return r;
12339}
12340
12341function SHA384() {
12342 if (!(this instanceof SHA384))
12343 return new SHA384();
12344
12345 _512.call(this);
12346 this.h = [
12347 0xcbbb9d5d, 0xc1059ed8,
12348 0x629a292a, 0x367cd507,
12349 0x9159015a, 0x3070dd17,
12350 0x152fecd8, 0xf70e5939,
12351 0x67332667, 0xffc00b31,
12352 0x8eb44a87, 0x68581511,
12353 0xdb0c2e0d, 0x64f98fa7,
12354 0x47b5481d, 0xbefa4fa4 ];
12355}
12356utils.inherits(SHA384, _512);
12357var _384 = SHA384;
12358
12359SHA384.blockSize = 1024;
12360SHA384.outSize = 384;
12361SHA384.hmacStrength = 192;
12362SHA384.padLength = 128;
12363
12364SHA384.prototype._digest = function digest(enc) {
12365 if (enc === 'hex')
12366 return utils.toHex32(this.h.slice(0, 12), 'big');
12367 else
12368 return utils.split32(this.h.slice(0, 12), 'big');
12369};
12370
12371var rotl32$1 = utils.rotl32;
12372var sum32$2 = utils.sum32;
12373var sum32_3$1 = utils.sum32_3;
12374var sum32_4$2 = utils.sum32_4;
12375var BlockHash$3 = common.BlockHash;
12376
12377function RIPEMD160() {
12378 if (!(this instanceof RIPEMD160))
12379 return new RIPEMD160();
12380
12381 BlockHash$3.call(this);
12382
12383 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
12384 this.endian = 'little';
12385}
12386utils.inherits(RIPEMD160, BlockHash$3);
12387var ripemd160 = RIPEMD160;
12388
12389RIPEMD160.blockSize = 512;
12390RIPEMD160.outSize = 160;
12391RIPEMD160.hmacStrength = 192;
12392RIPEMD160.padLength = 64;
12393
12394RIPEMD160.prototype._update = function update(msg, start) {
12395 var A = this.h[0];
12396 var B = this.h[1];
12397 var C = this.h[2];
12398 var D = this.h[3];
12399 var E = this.h[4];
12400 var Ah = A;
12401 var Bh = B;
12402 var Ch = C;
12403 var Dh = D;
12404 var Eh = E;
12405 for (var j = 0; j < 80; j++) {
12406 var T = sum32$2(
12407 rotl32$1(
12408 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
12409 s[j]),
12410 E);
12411 A = E;
12412 E = D;
12413 D = rotl32$1(C, 10);
12414 C = B;
12415 B = T;
12416 T = sum32$2(
12417 rotl32$1(
12418 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
12419 sh[j]),
12420 Eh);
12421 Ah = Eh;
12422 Eh = Dh;
12423 Dh = rotl32$1(Ch, 10);
12424 Ch = Bh;
12425 Bh = T;
12426 }
12427 T = sum32_3$1(this.h[1], C, Dh);
12428 this.h[1] = sum32_3$1(this.h[2], D, Eh);
12429 this.h[2] = sum32_3$1(this.h[3], E, Ah);
12430 this.h[3] = sum32_3$1(this.h[4], A, Bh);
12431 this.h[4] = sum32_3$1(this.h[0], B, Ch);
12432 this.h[0] = T;
12433};
12434
12435RIPEMD160.prototype._digest = function digest(enc) {
12436 if (enc === 'hex')
12437 return utils.toHex32(this.h, 'little');
12438 else
12439 return utils.split32(this.h, 'little');
12440};
12441
12442function f(j, x, y, z) {
12443 if (j <= 15)
12444 return x ^ y ^ z;
12445 else if (j <= 31)
12446 return (x & y) | ((~x) & z);
12447 else if (j <= 47)
12448 return (x | (~y)) ^ z;
12449 else if (j <= 63)
12450 return (x & z) | (y & (~z));
12451 else
12452 return x ^ (y | (~z));
12453}
12454
12455function K(j) {
12456 if (j <= 15)
12457 return 0x00000000;
12458 else if (j <= 31)
12459 return 0x5a827999;
12460 else if (j <= 47)
12461 return 0x6ed9eba1;
12462 else if (j <= 63)
12463 return 0x8f1bbcdc;
12464 else
12465 return 0xa953fd4e;
12466}
12467
12468function Kh(j) {
12469 if (j <= 15)
12470 return 0x50a28be6;
12471 else if (j <= 31)
12472 return 0x5c4dd124;
12473 else if (j <= 47)
12474 return 0x6d703ef3;
12475 else if (j <= 63)
12476 return 0x7a6d76e9;
12477 else
12478 return 0x00000000;
12479}
12480
12481var r = [
12482 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
12483 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
12484 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
12485 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
12486 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
12487];
12488
12489var rh = [
12490 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
12491 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
12492 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
12493 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12494 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
12495];
12496
12497var s = [
12498 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
12499 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
12500 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
12501 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
12502 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
12503];
12504
12505var sh = [
12506 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
12507 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
12508 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
12509 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
12510 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
12511];
12512
12513var ripemd = {
12514 ripemd160: ripemd160
12515};
12516
12517/**
12518 * A fast MD5 JavaScript implementation
12519 * Copyright (c) 2012 Joseph Myers
12520 * http://www.myersdaily.org/joseph/javascript/md5-text.html
12521 *
12522 * Permission to use, copy, modify, and distribute this software
12523 * and its documentation for any purposes and without
12524 * fee is hereby granted provided that this copyright notice
12525 * appears in all copies.
12526 *
12527 * Of course, this soft is provided "as is" without express or implied
12528 * warranty of any kind.
12529 */
12530
12531// MD5 Digest
12532async function md5(entree) {
12533 const digest = md51(util.uint8ArrayToStr(entree));
12534 return util.hexToUint8Array(hex(digest));
12535}
12536
12537function md5cycle(x, k) {
12538 let a = x[0];
12539 let b = x[1];
12540 let c = x[2];
12541 let d = x[3];
12542
12543 a = ff(a, b, c, d, k[0], 7, -680876936);
12544 d = ff(d, a, b, c, k[1], 12, -389564586);
12545 c = ff(c, d, a, b, k[2], 17, 606105819);
12546 b = ff(b, c, d, a, k[3], 22, -1044525330);
12547 a = ff(a, b, c, d, k[4], 7, -176418897);
12548 d = ff(d, a, b, c, k[5], 12, 1200080426);
12549 c = ff(c, d, a, b, k[6], 17, -1473231341);
12550 b = ff(b, c, d, a, k[7], 22, -45705983);
12551 a = ff(a, b, c, d, k[8], 7, 1770035416);
12552 d = ff(d, a, b, c, k[9], 12, -1958414417);
12553 c = ff(c, d, a, b, k[10], 17, -42063);
12554 b = ff(b, c, d, a, k[11], 22, -1990404162);
12555 a = ff(a, b, c, d, k[12], 7, 1804603682);
12556 d = ff(d, a, b, c, k[13], 12, -40341101);
12557 c = ff(c, d, a, b, k[14], 17, -1502002290);
12558 b = ff(b, c, d, a, k[15], 22, 1236535329);
12559
12560 a = gg(a, b, c, d, k[1], 5, -165796510);
12561 d = gg(d, a, b, c, k[6], 9, -1069501632);
12562 c = gg(c, d, a, b, k[11], 14, 643717713);
12563 b = gg(b, c, d, a, k[0], 20, -373897302);
12564 a = gg(a, b, c, d, k[5], 5, -701558691);
12565 d = gg(d, a, b, c, k[10], 9, 38016083);
12566 c = gg(c, d, a, b, k[15], 14, -660478335);
12567 b = gg(b, c, d, a, k[4], 20, -405537848);
12568 a = gg(a, b, c, d, k[9], 5, 568446438);
12569 d = gg(d, a, b, c, k[14], 9, -1019803690);
12570 c = gg(c, d, a, b, k[3], 14, -187363961);
12571 b = gg(b, c, d, a, k[8], 20, 1163531501);
12572 a = gg(a, b, c, d, k[13], 5, -1444681467);
12573 d = gg(d, a, b, c, k[2], 9, -51403784);
12574 c = gg(c, d, a, b, k[7], 14, 1735328473);
12575 b = gg(b, c, d, a, k[12], 20, -1926607734);
12576
12577 a = hh(a, b, c, d, k[5], 4, -378558);
12578 d = hh(d, a, b, c, k[8], 11, -2022574463);
12579 c = hh(c, d, a, b, k[11], 16, 1839030562);
12580 b = hh(b, c, d, a, k[14], 23, -35309556);
12581 a = hh(a, b, c, d, k[1], 4, -1530992060);
12582 d = hh(d, a, b, c, k[4], 11, 1272893353);
12583 c = hh(c, d, a, b, k[7], 16, -155497632);
12584 b = hh(b, c, d, a, k[10], 23, -1094730640);
12585 a = hh(a, b, c, d, k[13], 4, 681279174);
12586 d = hh(d, a, b, c, k[0], 11, -358537222);
12587 c = hh(c, d, a, b, k[3], 16, -722521979);
12588 b = hh(b, c, d, a, k[6], 23, 76029189);
12589 a = hh(a, b, c, d, k[9], 4, -640364487);
12590 d = hh(d, a, b, c, k[12], 11, -421815835);
12591 c = hh(c, d, a, b, k[15], 16, 530742520);
12592 b = hh(b, c, d, a, k[2], 23, -995338651);
12593
12594 a = ii(a, b, c, d, k[0], 6, -198630844);
12595 d = ii(d, a, b, c, k[7], 10, 1126891415);
12596 c = ii(c, d, a, b, k[14], 15, -1416354905);
12597 b = ii(b, c, d, a, k[5], 21, -57434055);
12598 a = ii(a, b, c, d, k[12], 6, 1700485571);
12599 d = ii(d, a, b, c, k[3], 10, -1894986606);
12600 c = ii(c, d, a, b, k[10], 15, -1051523);
12601 b = ii(b, c, d, a, k[1], 21, -2054922799);
12602 a = ii(a, b, c, d, k[8], 6, 1873313359);
12603 d = ii(d, a, b, c, k[15], 10, -30611744);
12604 c = ii(c, d, a, b, k[6], 15, -1560198380);
12605 b = ii(b, c, d, a, k[13], 21, 1309151649);
12606 a = ii(a, b, c, d, k[4], 6, -145523070);
12607 d = ii(d, a, b, c, k[11], 10, -1120210379);
12608 c = ii(c, d, a, b, k[2], 15, 718787259);
12609 b = ii(b, c, d, a, k[9], 21, -343485551);
12610
12611 x[0] = add32(a, x[0]);
12612 x[1] = add32(b, x[1]);
12613 x[2] = add32(c, x[2]);
12614 x[3] = add32(d, x[3]);
12615}
12616
12617function cmn(q, a, b, x, s, t) {
12618 a = add32(add32(a, q), add32(x, t));
12619 return add32((a << s) | (a >>> (32 - s)), b);
12620}
12621
12622function ff(a, b, c, d, x, s, t) {
12623 return cmn((b & c) | ((~b) & d), a, b, x, s, t);
12624}
12625
12626function gg(a, b, c, d, x, s, t) {
12627 return cmn((b & d) | (c & (~d)), a, b, x, s, t);
12628}
12629
12630function hh(a, b, c, d, x, s, t) {
12631 return cmn(b ^ c ^ d, a, b, x, s, t);
12632}
12633
12634function ii(a, b, c, d, x, s, t) {
12635 return cmn(c ^ (b | (~d)), a, b, x, s, t);
12636}
12637
12638function md51(s) {
12639 const n = s.length;
12640 const state = [1732584193, -271733879, -1732584194, 271733878];
12641 let i;
12642 for (i = 64; i <= s.length; i += 64) {
12643 md5cycle(state, md5blk(s.substring(i - 64, i)));
12644 }
12645 s = s.substring(i - 64);
12646 const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
12647 for (i = 0; i < s.length; i++) {
12648 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
12649 }
12650 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
12651 if (i > 55) {
12652 md5cycle(state, tail);
12653 for (i = 0; i < 16; i++) {
12654 tail[i] = 0;
12655 }
12656 }
12657 tail[14] = n * 8;
12658 md5cycle(state, tail);
12659 return state;
12660}
12661
12662/* there needs to be support for Unicode here,
12663 * unless we pretend that we can redefine the MD-5
12664 * algorithm for multi-byte characters (perhaps
12665 * by adding every four 16-bit characters and
12666 * shortening the sum to 32 bits). Otherwise
12667 * I suggest performing MD-5 as if every character
12668 * was two bytes--e.g., 0040 0025 = @%--but then
12669 * how will an ordinary MD-5 sum be matched?
12670 * There is no way to standardize text to something
12671 * like UTF-8 before transformation; speed cost is
12672 * utterly prohibitive. The JavaScript standard
12673 * itself needs to look at this: it should start
12674 * providing access to strings as preformed UTF-8
12675 * 8-bit unsigned value arrays.
12676 */
12677function md5blk(s) { /* I figured global was faster. */
12678 const md5blks = [];
12679 let i; /* Andy King said do it this way. */
12680 for (i = 0; i < 64; i += 4) {
12681 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<
12682 24);
12683 }
12684 return md5blks;
12685}
12686
12687const hex_chr = '0123456789abcdef'.split('');
12688
12689function rhex(n) {
12690 let s = '';
12691 let j = 0;
12692 for (; j < 4; j++) {
12693 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
12694 }
12695 return s;
12696}
12697
12698function hex(x) {
12699 for (let i = 0; i < x.length; i++) {
12700 x[i] = rhex(x[i]);
12701 }
12702 return x.join('');
12703}
12704
12705/* this function is much faster,
12706so if possible we use it. Some IEs
12707are the only ones I know of that
12708need the idiotic second function,
12709generated by an if clause. */
12710
12711function add32(a, b) {
12712 return (a + b) & 0xFFFFFFFF;
12713}
12714
12715/**
12716 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
12717 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
12718 * @see {@link https://github.com/indutny/hash.js|hash.js}
12719 * @module crypto/hash
12720 * @private
12721 */
12722
12723const webCrypto = util.getWebCrypto();
12724const nodeCrypto = util.getNodeCrypto();
12725const Buffer$1 = util.getNodeBuffer();
12726
12727function node_hash(type) {
12728 return async function (data) {
12729 const shasum = nodeCrypto.createHash(type);
12730 return stream.transform(data, value => {
12731 shasum.update(Buffer$1.from(value));
12732 }, () => new Uint8Array(shasum.digest()));
12733 };
12734}
12735
12736function hashjs_hash(hash, webCryptoHash) {
12737 return async function(data, config = defaultConfig) {
12738 if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
12739 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
12740 }
12741 const hashInstance = hash();
12742 return stream.transform(data, value => {
12743 hashInstance.update(value);
12744 }, () => new Uint8Array(hashInstance.digest()));
12745 };
12746}
12747
12748function asmcrypto_hash(hash, webCryptoHash) {
12749 return async function(data, config = defaultConfig) {
12750 if (util.isStream(data)) {
12751 const hashInstance = new hash();
12752 return stream.transform(data, value => {
12753 hashInstance.process(value);
12754 }, () => hashInstance.finish().result);
12755 } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
12756 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
12757 } else {
12758 return hash.bytes(data);
12759 }
12760 };
12761}
12762
12763let hash_fns;
12764if (nodeCrypto) { // Use Node native crypto for all hash functions
12765 hash_fns = {
12766 md5: node_hash('md5'),
12767 sha1: node_hash('sha1'),
12768 sha224: node_hash('sha224'),
12769 sha256: node_hash('sha256'),
12770 sha384: node_hash('sha384'),
12771 sha512: node_hash('sha512'),
12772 ripemd: node_hash('ripemd160')
12773 };
12774} else { // Use JS fallbacks
12775 hash_fns = {
12776 md5: md5,
12777 sha1: asmcrypto_hash(Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'),
12778 sha224: hashjs_hash(_224),
12779 sha256: asmcrypto_hash(Sha256, 'SHA-256'),
12780 sha384: hashjs_hash(_384, 'SHA-384'),
12781 sha512: hashjs_hash(_512, 'SHA-512'), // asmcrypto sha512 is huge.
12782 ripemd: hashjs_hash(ripemd160)
12783 };
12784}
12785
12786var hash = {
12787
12788 /** @see module:md5 */
12789 md5: hash_fns.md5,
12790 /** @see asmCrypto */
12791 sha1: hash_fns.sha1,
12792 /** @see hash.js */
12793 sha224: hash_fns.sha224,
12794 /** @see asmCrypto */
12795 sha256: hash_fns.sha256,
12796 /** @see hash.js */
12797 sha384: hash_fns.sha384,
12798 /** @see asmCrypto */
12799 sha512: hash_fns.sha512,
12800 /** @see hash.js */
12801 ripemd: hash_fns.ripemd,
12802
12803 /**
12804 * Create a hash on the specified data using the specified algorithm
12805 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
12806 * @param {Uint8Array} data - Data to be hashed
12807 * @returns {Uint8Array} Hash value.
12808 * @async
12809 */
12810 digest: function(algo, data) {
12811 switch (algo) {
12812 case 1:
12813 // - MD5 [HAC]
12814 return this.md5(data);
12815 case 2:
12816 // - SHA-1 [FIPS180]
12817 return this.sha1(data);
12818 case 3:
12819 // - RIPE-MD/160 [HAC]
12820 return this.ripemd(data);
12821 case 8:
12822 // - SHA256 [FIPS180]
12823 return this.sha256(data);
12824 case 9:
12825 // - SHA384 [FIPS180]
12826 return this.sha384(data);
12827 case 10:
12828 // - SHA512 [FIPS180]
12829 return this.sha512(data);
12830 case 11:
12831 // - SHA224 [FIPS180]
12832 return this.sha224(data);
12833 default:
12834 throw new Error('Invalid hash function.');
12835 }
12836 },
12837
12838 /**
12839 * Returns the hash size in bytes of the specified hash algorithm type
12840 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
12841 * @returns {Integer} Size in bytes of the resulting hash.
12842 */
12843 getHashByteLength: function(algo) {
12844 switch (algo) {
12845 case 1: // - MD5 [HAC]
12846 return 16;
12847 case 2: // - SHA-1 [FIPS180]
12848 case 3: // - RIPE-MD/160 [HAC]
12849 return 20;
12850 case 8: // - SHA256 [FIPS180]
12851 return 32;
12852 case 9: // - SHA384 [FIPS180]
12853 return 48;
12854 case 10: // - SHA512 [FIPS180]
12855 return 64;
12856 case 11: // - SHA224 [FIPS180]
12857 return 28;
12858 default:
12859 throw new Error('Invalid hash algorithm.');
12860 }
12861 }
12862};
12863
12864class AES_CFB {
12865 static encrypt(data, key, iv) {
12866 return new AES_CFB(key, iv).encrypt(data);
12867 }
12868 static decrypt(data, key, iv) {
12869 return new AES_CFB(key, iv).decrypt(data);
12870 }
12871 constructor(key, iv, aes) {
12872 this.aes = aes ? aes : new AES(key, iv, true, 'CFB');
12873 delete this.aes.padding;
12874 }
12875 encrypt(data) {
12876 const r1 = this.aes.AES_Encrypt_process(data);
12877 const r2 = this.aes.AES_Encrypt_finish();
12878 return joinBytes(r1, r2);
12879 }
12880 decrypt(data) {
12881 const r1 = this.aes.AES_Decrypt_process(data);
12882 const r2 = this.aes.AES_Decrypt_finish();
12883 return joinBytes(r1, r2);
12884 }
12885}
12886
12887// Modified by ProtonTech AG
12888
12889const webCrypto$1 = util.getWebCrypto();
12890const nodeCrypto$1 = util.getNodeCrypto();
12891const Buffer$2 = util.getNodeBuffer();
12892
12893const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : [];
12894const nodeAlgos = {
12895 idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
12896 tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
12897 cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
12898 blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
12899 aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
12900 aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
12901 aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
12902 /* twofish is not implemented in OpenSSL */
12903};
12904
12905async function encrypt(algo, key, plaintext, iv, config) {
12906 if (util.getNodeCrypto() && nodeAlgos[algo]) { // Node crypto library.
12907 return nodeEncrypt(algo, key, plaintext, iv);
12908 }
12909 if (algo.substr(0, 3) === 'aes') {
12910 return aesEncrypt(algo, key, plaintext, iv, config);
12911 }
12912
12913 const cipherfn = new cipher[algo](key);
12914 const block_size = cipherfn.blockSize;
12915
12916 const blockc = iv.slice();
12917 let pt = new Uint8Array();
12918 const process = chunk => {
12919 if (chunk) {
12920 pt = util.concatUint8Array([pt, chunk]);
12921 }
12922 const ciphertext = new Uint8Array(pt.length);
12923 let i;
12924 let j = 0;
12925 while (chunk ? pt.length >= block_size : pt.length) {
12926 const encblock = cipherfn.encrypt(blockc);
12927 for (i = 0; i < block_size; i++) {
12928 blockc[i] = pt[i] ^ encblock[i];
12929 ciphertext[j++] = blockc[i];
12930 }
12931 pt = pt.subarray(block_size);
12932 }
12933 return ciphertext.subarray(0, j);
12934 };
12935 return stream.transform(plaintext, process, process);
12936}
12937
12938async function decrypt(algo, key, ciphertext, iv) {
12939 if (util.getNodeCrypto() && nodeAlgos[algo]) { // Node crypto library.
12940 return nodeDecrypt(algo, key, ciphertext, iv);
12941 }
12942 if (algo.substr(0, 3) === 'aes') {
12943 return aesDecrypt(algo, key, ciphertext, iv);
12944 }
12945
12946 const cipherfn = new cipher[algo](key);
12947 const block_size = cipherfn.blockSize;
12948
12949 let blockp = iv;
12950 let ct = new Uint8Array();
12951 const process = chunk => {
12952 if (chunk) {
12953 ct = util.concatUint8Array([ct, chunk]);
12954 }
12955 const plaintext = new Uint8Array(ct.length);
12956 let i;
12957 let j = 0;
12958 while (chunk ? ct.length >= block_size : ct.length) {
12959 const decblock = cipherfn.encrypt(blockp);
12960 blockp = ct;
12961 for (i = 0; i < block_size; i++) {
12962 plaintext[j++] = blockp[i] ^ decblock[i];
12963 }
12964 ct = ct.subarray(block_size);
12965 }
12966 return plaintext.subarray(0, j);
12967 };
12968 return stream.transform(ciphertext, process, process);
12969}
12970
12971function aesEncrypt(algo, key, pt, iv, config) {
12972 if (
12973 util.getWebCrypto() &&
12974 key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
12975 !util.isStream(pt) &&
12976 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
12977 ) { // Web Crypto
12978 return webEncrypt(algo, key, pt, iv);
12979 }
12980 // asm.js fallback
12981 const cfb = new AES_CFB(key, iv);
12982 return stream.transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
12983}
12984
12985function aesDecrypt(algo, key, ct, iv) {
12986 if (util.isStream(ct)) {
12987 const cfb = new AES_CFB(key, iv);
12988 return stream.transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
12989 }
12990 return AES_CFB.decrypt(ct, key, iv);
12991}
12992
12993function xorMut(a, b) {
12994 for (let i = 0; i < a.length; i++) {
12995 a[i] = a[i] ^ b[i];
12996 }
12997}
12998
12999async function webEncrypt(algo, key, pt, iv) {
13000 const ALGO = 'AES-CBC';
13001 const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
13002 const { blockSize } = cipher[algo];
13003 const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);
13004 const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);
13005 xorMut(ct, pt);
13006 return ct;
13007}
13008
13009function nodeEncrypt(algo, key, pt, iv) {
13010 key = Buffer$2.from(key);
13011 iv = Buffer$2.from(iv);
13012 const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algo], key, iv);
13013 return stream.transform(pt, value => new Uint8Array(cipherObj.update(Buffer$2.from(value))));
13014}
13015
13016function nodeDecrypt(algo, key, ct, iv) {
13017 key = Buffer$2.from(key);
13018 iv = Buffer$2.from(iv);
13019 const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algo], key, iv);
13020 return stream.transform(ct, value => new Uint8Array(decipherObj.update(Buffer$2.from(value))));
13021}
13022
13023var cfb = /*#__PURE__*/Object.freeze({
13024 __proto__: null,
13025 encrypt: encrypt,
13026 decrypt: decrypt
13027});
13028
13029const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
13030class AES_GCM {
13031 constructor(key, nonce, adata, tagSize = 16, aes) {
13032 this.tagSize = tagSize;
13033 this.gamma0 = 0;
13034 this.counter = 1;
13035 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
13036 let { asm, heap } = this.aes.acquire_asm();
13037 // Init GCM
13038 asm.gcm_init();
13039 // Tag size
13040 if (this.tagSize < 4 || this.tagSize > 16)
13041 throw new IllegalArgumentError('illegal tagSize value');
13042 // Nonce
13043 const noncelen = nonce.length || 0;
13044 const noncebuf = new Uint8Array(16);
13045 if (noncelen !== 12) {
13046 this._gcm_mac_process(nonce);
13047 heap[0] = 0;
13048 heap[1] = 0;
13049 heap[2] = 0;
13050 heap[3] = 0;
13051 heap[4] = 0;
13052 heap[5] = 0;
13053 heap[6] = 0;
13054 heap[7] = 0;
13055 heap[8] = 0;
13056 heap[9] = 0;
13057 heap[10] = 0;
13058 heap[11] = noncelen >>> 29;
13059 heap[12] = (noncelen >>> 21) & 255;
13060 heap[13] = (noncelen >>> 13) & 255;
13061 heap[14] = (noncelen >>> 5) & 255;
13062 heap[15] = (noncelen << 3) & 255;
13063 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
13064 asm.get_iv(AES_asm.HEAP_DATA);
13065 asm.set_iv(0, 0, 0, 0);
13066 noncebuf.set(heap.subarray(0, 16));
13067 }
13068 else {
13069 noncebuf.set(nonce);
13070 noncebuf[15] = 1;
13071 }
13072 const nonceview = new DataView(noncebuf.buffer);
13073 this.gamma0 = nonceview.getUint32(12);
13074 asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
13075 asm.set_mask(0, 0, 0, 0xffffffff);
13076 // Associated data
13077 if (adata !== undefined) {
13078 if (adata.length > _AES_GCM_data_maxLength)
13079 throw new IllegalArgumentError('illegal adata length');
13080 if (adata.length) {
13081 this.adata = adata;
13082 this._gcm_mac_process(adata);
13083 }
13084 else {
13085 this.adata = undefined;
13086 }
13087 }
13088 else {
13089 this.adata = undefined;
13090 }
13091 // Counter
13092 if (this.counter < 1 || this.counter > 0xffffffff)
13093 throw new RangeError('counter must be a positive 32-bit integer');
13094 asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);
13095 }
13096 static encrypt(cleartext, key, nonce, adata, tagsize) {
13097 return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
13098 }
13099 static decrypt(ciphertext, key, nonce, adata, tagsize) {
13100 return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
13101 }
13102 encrypt(data) {
13103 return this.AES_GCM_encrypt(data);
13104 }
13105 decrypt(data) {
13106 return this.AES_GCM_decrypt(data);
13107 }
13108 AES_GCM_Encrypt_process(data) {
13109 let dpos = 0;
13110 let dlen = data.length || 0;
13111 let { asm, heap } = this.aes.acquire_asm();
13112 let counter = this.counter;
13113 let pos = this.aes.pos;
13114 let len = this.aes.len;
13115 let rpos = 0;
13116 let rlen = (len + dlen) & -16;
13117 let wlen = 0;
13118 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
13119 throw new RangeError('counter overflow');
13120 const result = new Uint8Array(rlen);
13121 while (dlen > 0) {
13122 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
13123 len += wlen;
13124 dpos += wlen;
13125 dlen -= wlen;
13126 wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);
13127 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
13128 if (wlen)
13129 result.set(heap.subarray(pos, pos + wlen), rpos);
13130 counter += wlen >>> 4;
13131 rpos += wlen;
13132 if (wlen < len) {
13133 pos += wlen;
13134 len -= wlen;
13135 }
13136 else {
13137 pos = 0;
13138 len = 0;
13139 }
13140 }
13141 this.counter = counter;
13142 this.aes.pos = pos;
13143 this.aes.len = len;
13144 return result;
13145 }
13146 AES_GCM_Encrypt_finish() {
13147 let { asm, heap } = this.aes.acquire_asm();
13148 let counter = this.counter;
13149 let tagSize = this.tagSize;
13150 let adata = this.adata;
13151 let pos = this.aes.pos;
13152 let len = this.aes.len;
13153 const result = new Uint8Array(len + tagSize);
13154 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);
13155 if (len)
13156 result.set(heap.subarray(pos, pos + len));
13157 let i = len;
13158 for (; i & 15; i++)
13159 heap[pos + i] = 0;
13160 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
13161 const alen = adata !== undefined ? adata.length : 0;
13162 const clen = ((counter - 1) << 4) + len;
13163 heap[0] = 0;
13164 heap[1] = 0;
13165 heap[2] = 0;
13166 heap[3] = alen >>> 29;
13167 heap[4] = alen >>> 21;
13168 heap[5] = (alen >>> 13) & 255;
13169 heap[6] = (alen >>> 5) & 255;
13170 heap[7] = (alen << 3) & 255;
13171 heap[8] = heap[9] = heap[10] = 0;
13172 heap[11] = clen >>> 29;
13173 heap[12] = (clen >>> 21) & 255;
13174 heap[13] = (clen >>> 13) & 255;
13175 heap[14] = (clen >>> 5) & 255;
13176 heap[15] = (clen << 3) & 255;
13177 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
13178 asm.get_iv(AES_asm.HEAP_DATA);
13179 asm.set_counter(0, 0, 0, this.gamma0);
13180 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
13181 result.set(heap.subarray(0, tagSize), len);
13182 this.counter = 1;
13183 this.aes.pos = 0;
13184 this.aes.len = 0;
13185 return result;
13186 }
13187 AES_GCM_Decrypt_process(data) {
13188 let dpos = 0;
13189 let dlen = data.length || 0;
13190 let { asm, heap } = this.aes.acquire_asm();
13191 let counter = this.counter;
13192 let tagSize = this.tagSize;
13193 let pos = this.aes.pos;
13194 let len = this.aes.len;
13195 let rpos = 0;
13196 let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;
13197 let tlen = len + dlen - rlen;
13198 let wlen = 0;
13199 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
13200 throw new RangeError('counter overflow');
13201 const result = new Uint8Array(rlen);
13202 while (dlen > tlen) {
13203 wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);
13204 len += wlen;
13205 dpos += wlen;
13206 dlen -= wlen;
13207 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
13208 wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);
13209 if (wlen)
13210 result.set(heap.subarray(pos, pos + wlen), rpos);
13211 counter += wlen >>> 4;
13212 rpos += wlen;
13213 pos = 0;
13214 len = 0;
13215 }
13216 if (dlen > 0) {
13217 len += _heap_write(heap, 0, data, dpos, dlen);
13218 }
13219 this.counter = counter;
13220 this.aes.pos = pos;
13221 this.aes.len = len;
13222 return result;
13223 }
13224 AES_GCM_Decrypt_finish() {
13225 let { asm, heap } = this.aes.acquire_asm();
13226 let tagSize = this.tagSize;
13227 let adata = this.adata;
13228 let counter = this.counter;
13229 let pos = this.aes.pos;
13230 let len = this.aes.len;
13231 let rlen = len - tagSize;
13232 if (len < tagSize)
13233 throw new IllegalStateError('authentication tag not found');
13234 const result = new Uint8Array(rlen);
13235 const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
13236 let i = rlen;
13237 for (; i & 15; i++)
13238 heap[pos + i] = 0;
13239 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
13240 asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);
13241 if (rlen)
13242 result.set(heap.subarray(pos, pos + rlen));
13243 const alen = adata !== undefined ? adata.length : 0;
13244 const clen = ((counter - 1) << 4) + len - tagSize;
13245 heap[0] = 0;
13246 heap[1] = 0;
13247 heap[2] = 0;
13248 heap[3] = alen >>> 29;
13249 heap[4] = alen >>> 21;
13250 heap[5] = (alen >>> 13) & 255;
13251 heap[6] = (alen >>> 5) & 255;
13252 heap[7] = (alen << 3) & 255;
13253 heap[8] = heap[9] = heap[10] = 0;
13254 heap[11] = clen >>> 29;
13255 heap[12] = (clen >>> 21) & 255;
13256 heap[13] = (clen >>> 13) & 255;
13257 heap[14] = (clen >>> 5) & 255;
13258 heap[15] = (clen << 3) & 255;
13259 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
13260 asm.get_iv(AES_asm.HEAP_DATA);
13261 asm.set_counter(0, 0, 0, this.gamma0);
13262 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
13263 let acheck = 0;
13264 for (let i = 0; i < tagSize; ++i)
13265 acheck |= atag[i] ^ heap[i];
13266 if (acheck)
13267 throw new SecurityError('data integrity check failed');
13268 this.counter = 1;
13269 this.aes.pos = 0;
13270 this.aes.len = 0;
13271 return result;
13272 }
13273 AES_GCM_decrypt(data) {
13274 const result1 = this.AES_GCM_Decrypt_process(data);
13275 const result2 = this.AES_GCM_Decrypt_finish();
13276 const result = new Uint8Array(result1.length + result2.length);
13277 if (result1.length)
13278 result.set(result1);
13279 if (result2.length)
13280 result.set(result2, result1.length);
13281 return result;
13282 }
13283 AES_GCM_encrypt(data) {
13284 const result1 = this.AES_GCM_Encrypt_process(data);
13285 const result2 = this.AES_GCM_Encrypt_finish();
13286 const result = new Uint8Array(result1.length + result2.length);
13287 if (result1.length)
13288 result.set(result1);
13289 if (result2.length)
13290 result.set(result2, result1.length);
13291 return result;
13292 }
13293 _gcm_mac_process(data) {
13294 let { asm, heap } = this.aes.acquire_asm();
13295 let dpos = 0;
13296 let dlen = data.length || 0;
13297 let wlen = 0;
13298 while (dlen > 0) {
13299 wlen = _heap_write(heap, 0, data, dpos, dlen);
13300 dpos += wlen;
13301 dlen -= wlen;
13302 while (wlen & 15)
13303 heap[wlen++] = 0;
13304 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);
13305 }
13306 }
13307}
13308
13309// OpenPGP.js - An OpenPGP implementation in javascript
13310
13311const webCrypto$2 = util.getWebCrypto(); // no GCM support in IE11, Safari 9
13312const nodeCrypto$2 = util.getNodeCrypto();
13313const Buffer$3 = util.getNodeBuffer();
13314
13315const blockLength = 16;
13316const ivLength = 12; // size of the IV in bytes
13317const tagLength = 16; // size of the tag in bytes
13318const ALGO = 'AES-GCM';
13319
13320/**
13321 * Class to en/decrypt using GCM mode.
13322 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
13323 * @param {Uint8Array} key - The encryption key
13324 */
13325async function GCM(cipher, key) {
13326 if (cipher.substr(0, 3) !== 'aes') {
13327 throw new Error('GCM mode supports only AES cipher');
13328 }
13329
13330 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
13331 const _key = await webCrypto$2.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
13332
13333 return {
13334 encrypt: async function(pt, iv, adata = new Uint8Array()) {
13335 if (
13336 !pt.length ||
13337 // iOS does not support GCM-en/decrypting empty messages
13338 // Also, synchronous en/decryption might be faster in this case.
13339 (!adata.length && navigator.userAgent.indexOf('Edge') !== -1)
13340 // Edge does not support GCM-en/decrypting without ADATA
13341 ) {
13342 return AES_GCM.encrypt(pt, key, iv, adata);
13343 }
13344 const ct = await webCrypto$2.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);
13345 return new Uint8Array(ct);
13346 },
13347
13348 decrypt: async function(ct, iv, adata = new Uint8Array()) {
13349 if (
13350 ct.length === tagLength ||
13351 // iOS does not support GCM-en/decrypting empty messages
13352 // Also, synchronous en/decryption might be faster in this case.
13353 (!adata.length && navigator.userAgent.indexOf('Edge') !== -1)
13354 // Edge does not support GCM-en/decrypting without ADATA
13355 ) {
13356 return AES_GCM.decrypt(ct, key, iv, adata);
13357 }
13358 const pt = await webCrypto$2.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);
13359 return new Uint8Array(pt);
13360 }
13361 };
13362 }
13363
13364 if (util.getNodeCrypto()) { // Node crypto library
13365 key = Buffer$3.from(key);
13366
13367 return {
13368 encrypt: async function(pt, iv, adata = new Uint8Array()) {
13369 pt = Buffer$3.from(pt);
13370 iv = Buffer$3.from(iv);
13371 adata = Buffer$3.from(adata);
13372 const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
13373 en.setAAD(adata);
13374 const ct = Buffer$3.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
13375 return new Uint8Array(ct);
13376 },
13377
13378 decrypt: async function(ct, iv, adata = new Uint8Array()) {
13379 ct = Buffer$3.from(ct);
13380 iv = Buffer$3.from(iv);
13381 adata = Buffer$3.from(adata);
13382 const de = new nodeCrypto$2.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
13383 de.setAAD(adata);
13384 de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext
13385 const pt = Buffer$3.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);
13386 return new Uint8Array(pt);
13387 }
13388 };
13389 }
13390
13391 return {
13392 encrypt: async function(pt, iv, adata) {
13393 return AES_GCM.encrypt(pt, key, iv, adata);
13394 },
13395
13396 decrypt: async function(ct, iv, adata) {
13397 return AES_GCM.decrypt(ct, key, iv, adata);
13398 }
13399 };
13400}
13401
13402
13403/**
13404 * Get GCM nonce. Note: this operation is not defined by the standard.
13405 * A future version of the standard may define GCM mode differently,
13406 * hopefully under a different ID (we use Private/Experimental algorithm
13407 * ID 100) so that we can maintain backwards compatibility.
13408 * @param {Uint8Array} iv - The initialization vector (12 bytes)
13409 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
13410 */
13411GCM.getNonce = function(iv, chunkIndex) {
13412 const nonce = iv.slice();
13413 for (let i = 0; i < chunkIndex.length; i++) {
13414 nonce[4 + i] ^= chunkIndex[i];
13415 }
13416 return nonce;
13417};
13418
13419GCM.blockLength = blockLength;
13420GCM.ivLength = ivLength;
13421GCM.tagLength = tagLength;
13422
13423class AES_CTR {
13424 static encrypt(data, key, nonce) {
13425 return new AES_CTR(key, nonce).encrypt(data);
13426 }
13427 static decrypt(data, key, nonce) {
13428 return new AES_CTR(key, nonce).encrypt(data);
13429 }
13430 constructor(key, nonce, aes) {
13431 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
13432 delete this.aes.padding;
13433 this.AES_CTR_set_options(nonce);
13434 }
13435 encrypt(data) {
13436 const r1 = this.aes.AES_Encrypt_process(data);
13437 const r2 = this.aes.AES_Encrypt_finish();
13438 return joinBytes(r1, r2);
13439 }
13440 decrypt(data) {
13441 const r1 = this.aes.AES_Encrypt_process(data);
13442 const r2 = this.aes.AES_Encrypt_finish();
13443 return joinBytes(r1, r2);
13444 }
13445 AES_CTR_set_options(nonce, counter, size) {
13446 let { asm } = this.aes.acquire_asm();
13447 if (size !== undefined) {
13448 if (size < 8 || size > 48)
13449 throw new IllegalArgumentError('illegal counter size');
13450 let mask = Math.pow(2, size) - 1;
13451 asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);
13452 }
13453 else {
13454 size = 48;
13455 asm.set_mask(0, 0, 0xffff, 0xffffffff);
13456 }
13457 if (nonce !== undefined) {
13458 let len = nonce.length;
13459 if (!len || len > 16)
13460 throw new IllegalArgumentError('illegal nonce size');
13461 let view = new DataView(new ArrayBuffer(16));
13462 new Uint8Array(view.buffer).set(nonce);
13463 asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
13464 }
13465 else {
13466 throw new Error('nonce is required');
13467 }
13468 if (counter !== undefined) {
13469 if (counter < 0 || counter >= Math.pow(2, size))
13470 throw new IllegalArgumentError('illegal counter value');
13471 asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);
13472 }
13473 }
13474}
13475
13476class AES_CBC {
13477 static encrypt(data, key, padding = true, iv) {
13478 return new AES_CBC(key, iv, padding).encrypt(data);
13479 }
13480 static decrypt(data, key, padding = true, iv) {
13481 return new AES_CBC(key, iv, padding).decrypt(data);
13482 }
13483 constructor(key, iv, padding = true, aes) {
13484 this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');
13485 }
13486 encrypt(data) {
13487 const r1 = this.aes.AES_Encrypt_process(data);
13488 const r2 = this.aes.AES_Encrypt_finish();
13489 return joinBytes(r1, r2);
13490 }
13491 decrypt(data) {
13492 const r1 = this.aes.AES_Decrypt_process(data);
13493 const r2 = this.aes.AES_Decrypt_finish();
13494 return joinBytes(r1, r2);
13495 }
13496}
13497
13498/**
13499 * @fileoverview This module implements AES-CMAC on top of
13500 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
13501 * @module crypto/cmac
13502 * @private
13503 */
13504
13505const webCrypto$3 = util.getWebCrypto();
13506const nodeCrypto$3 = util.getNodeCrypto();
13507const Buffer$4 = util.getNodeBuffer();
13508
13509
13510/**
13511 * This implementation of CMAC is based on the description of OMAC in
13512 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
13513 * document:
13514 *
13515 * We have made a small modification to the OMAC algorithm as it was
13516 * originally presented, changing one of its two constants.
13517 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
13518 * multiplicative inverse of 2) in the original definition of OMAC [14].
13519 * The OMAC authors indicate that they will promulgate this modification
13520 * [15], which slightly simplifies implementations.
13521 */
13522
13523const blockLength$1 = 16;
13524
13525
13526/**
13527 * xor `padding` into the end of `data`. This function implements "the
13528 * operation xor→ [which] xors the shorter string into the end of longer
13529 * one". Since data is always as least as long as padding, we can
13530 * simplify the implementation.
13531 * @param {Uint8Array} data
13532 * @param {Uint8Array} padding
13533 */
13534function rightXorMut(data, padding) {
13535 const offset = data.length - blockLength$1;
13536 for (let i = 0; i < blockLength$1; i++) {
13537 data[i + offset] ^= padding[i];
13538 }
13539 return data;
13540}
13541
13542function pad(data, padding, padding2) {
13543 // if |M| in {n, 2n, 3n, ...}
13544 if (data.length && data.length % blockLength$1 === 0) {
13545 // then return M xor→ B,
13546 return rightXorMut(data, padding);
13547 }
13548 // else return (M || 10^(n−1−(|M| mod n))) xor→ P
13549 const padded = new Uint8Array(data.length + (blockLength$1 - data.length % blockLength$1));
13550 padded.set(data);
13551 padded[data.length] = 0b10000000;
13552 return rightXorMut(padded, padding2);
13553}
13554
13555const zeroBlock = new Uint8Array(blockLength$1);
13556
13557async function CMAC(key) {
13558 const cbc = await CBC(key);
13559
13560 // L ← E_K(0^n); B ← 2L; P ← 4L
13561 const padding = util.double(await cbc(zeroBlock));
13562 const padding2 = util.double(padding);
13563
13564 return async function(data) {
13565 // return CBC_K(pad(M; B, P))
13566 return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$1);
13567 };
13568}
13569
13570async function CBC(key) {
13571 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
13572 key = await webCrypto$3.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
13573 return async function(pt) {
13574 const ct = await webCrypto$3.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength$1 * 8 }, key, pt);
13575 return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$1);
13576 };
13577 }
13578 if (util.getNodeCrypto()) { // Node crypto library
13579 key = Buffer$4.from(key);
13580 return async function(pt) {
13581 pt = Buffer$4.from(pt);
13582 const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
13583 const ct = en.update(pt);
13584 return new Uint8Array(ct);
13585 };
13586 }
13587 // asm.js fallback
13588 return async function(pt) {
13589 return AES_CBC.encrypt(pt, key, false, zeroBlock);
13590 };
13591}
13592
13593// OpenPGP.js - An OpenPGP implementation in javascript
13594
13595const webCrypto$4 = util.getWebCrypto();
13596const nodeCrypto$4 = util.getNodeCrypto();
13597const Buffer$5 = util.getNodeBuffer();
13598
13599
13600const blockLength$2 = 16;
13601const ivLength$1 = blockLength$2;
13602const tagLength$1 = blockLength$2;
13603
13604const zero = new Uint8Array(blockLength$2);
13605const one = new Uint8Array(blockLength$2); one[blockLength$2 - 1] = 1;
13606const two = new Uint8Array(blockLength$2); two[blockLength$2 - 1] = 2;
13607
13608async function OMAC(key) {
13609 const cmac = await CMAC(key);
13610 return function(t, message) {
13611 return cmac(util.concatUint8Array([t, message]));
13612 };
13613}
13614
13615async function CTR(key) {
13616 if (
13617 util.getWebCrypto() &&
13618 key.length !== 24 && // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
13619 navigator.userAgent.indexOf('Edge') === -1
13620 ) {
13621 key = await webCrypto$4.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
13622 return async function(pt, iv) {
13623 const ct = await webCrypto$4.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, key, pt);
13624 return new Uint8Array(ct);
13625 };
13626 }
13627 if (util.getNodeCrypto()) { // Node crypto library
13628 key = Buffer$5.from(key);
13629 return async function(pt, iv) {
13630 pt = Buffer$5.from(pt);
13631 iv = Buffer$5.from(iv);
13632 const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
13633 const ct = Buffer$5.concat([en.update(pt), en.final()]);
13634 return new Uint8Array(ct);
13635 };
13636 }
13637 // asm.js fallback
13638 return async function(pt, iv) {
13639 return AES_CTR.encrypt(pt, key, iv);
13640 };
13641}
13642
13643
13644/**
13645 * Class to en/decrypt using EAX mode.
13646 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
13647 * @param {Uint8Array} key - The encryption key
13648 */
13649async function EAX(cipher, key) {
13650 if (cipher.substr(0, 3) !== 'aes') {
13651 throw new Error('EAX mode supports only AES cipher');
13652 }
13653
13654 const [
13655 omac,
13656 ctr
13657 ] = await Promise.all([
13658 OMAC(key),
13659 CTR(key)
13660 ]);
13661
13662 return {
13663 /**
13664 * Encrypt plaintext input.
13665 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
13666 * @param {Uint8Array} nonce - The nonce (16 bytes)
13667 * @param {Uint8Array} adata - Associated data to sign
13668 * @returns {Uint8Array} The ciphertext output.
13669 * @async
13670 */
13671 encrypt: async function(plaintext, nonce, adata) {
13672 const [
13673 omacNonce,
13674 omacAdata
13675 ] = await Promise.all([
13676 omac(zero, nonce),
13677 omac(one, adata)
13678 ]);
13679 const ciphered = await ctr(plaintext, omacNonce);
13680 const omacCiphered = await omac(two, ciphered);
13681 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
13682 for (let i = 0; i < tagLength$1; i++) {
13683 tag[i] ^= omacAdata[i] ^ omacNonce[i];
13684 }
13685 return util.concatUint8Array([ciphered, tag]);
13686 },
13687
13688 /**
13689 * Decrypt ciphertext input.
13690 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
13691 * @param {Uint8Array} nonce - The nonce (16 bytes)
13692 * @param {Uint8Array} adata - Associated data to verify
13693 * @returns {Uint8Array} The plaintext output.
13694 * @async
13695 */
13696 decrypt: async function(ciphertext, nonce, adata) {
13697 if (ciphertext.length < tagLength$1) throw new Error('Invalid EAX ciphertext');
13698 const ciphered = ciphertext.subarray(0, -tagLength$1);
13699 const ctTag = ciphertext.subarray(-tagLength$1);
13700 const [
13701 omacNonce,
13702 omacAdata,
13703 omacCiphered
13704 ] = await Promise.all([
13705 omac(zero, nonce),
13706 omac(one, adata),
13707 omac(two, ciphered)
13708 ]);
13709 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
13710 for (let i = 0; i < tagLength$1; i++) {
13711 tag[i] ^= omacAdata[i] ^ omacNonce[i];
13712 }
13713 if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
13714 const plaintext = await ctr(ciphered, omacNonce);
13715 return plaintext;
13716 }
13717 };
13718}
13719
13720
13721/**
13722 * 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}.
13723 * @param {Uint8Array} iv - The initialization vector (16 bytes)
13724 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
13725 */
13726EAX.getNonce = function(iv, chunkIndex) {
13727 const nonce = iv.slice();
13728 for (let i = 0; i < chunkIndex.length; i++) {
13729 nonce[8 + i] ^= chunkIndex[i];
13730 }
13731 return nonce;
13732};
13733
13734EAX.blockLength = blockLength$2;
13735EAX.ivLength = ivLength$1;
13736EAX.tagLength = tagLength$1;
13737
13738// OpenPGP.js - An OpenPGP implementation in javascript
13739
13740
13741const blockLength$3 = 16;
13742const ivLength$2 = 15;
13743
13744// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
13745// While OCB [RFC7253] allows the authentication tag length to be of any
13746// number up to 128 bits long, this document requires a fixed
13747// authentication tag length of 128 bits (16 octets) for simplicity.
13748const tagLength$2 = 16;
13749
13750
13751function ntz(n) {
13752 let ntz = 0;
13753 for (let i = 1; (n & i) === 0; i <<= 1) {
13754 ntz++;
13755 }
13756 return ntz;
13757}
13758
13759function xorMut$1(S, T) {
13760 for (let i = 0; i < S.length; i++) {
13761 S[i] ^= T[i];
13762 }
13763 return S;
13764}
13765
13766function xor(S, T) {
13767 return xorMut$1(S.slice(), T);
13768}
13769
13770const zeroBlock$1 = new Uint8Array(blockLength$3);
13771const one$1 = new Uint8Array([1]);
13772
13773/**
13774 * Class to en/decrypt using OCB mode.
13775 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
13776 * @param {Uint8Array} key - The encryption key
13777 */
13778async function OCB(cipher$1, key) {
13779
13780 let maxNtz = 0;
13781 let encipher;
13782 let decipher;
13783 let mask;
13784
13785 constructKeyVariables(cipher$1, key);
13786
13787 function constructKeyVariables(cipher$1, key) {
13788 const aes = new cipher[cipher$1](key);
13789 encipher = aes.encrypt.bind(aes);
13790 decipher = aes.decrypt.bind(aes);
13791
13792 const mask_x = encipher(zeroBlock$1);
13793 const mask_$ = util.double(mask_x);
13794 mask = [];
13795 mask[0] = util.double(mask_$);
13796
13797
13798 mask.x = mask_x;
13799 mask.$ = mask_$;
13800 }
13801
13802 function extendKeyVariables(text, adata) {
13803 const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$3 | 0) - 1;
13804 for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
13805 mask[i] = util.double(mask[i - 1]);
13806 }
13807 maxNtz = newMaxNtz;
13808 }
13809
13810 function hash(adata) {
13811 if (!adata.length) {
13812 // Fast path
13813 return zeroBlock$1;
13814 }
13815
13816 //
13817 // Consider A as a sequence of 128-bit blocks
13818 //
13819 const m = adata.length / blockLength$3 | 0;
13820
13821 const offset = new Uint8Array(blockLength$3);
13822 const sum = new Uint8Array(blockLength$3);
13823 for (let i = 0; i < m; i++) {
13824 xorMut$1(offset, mask[ntz(i + 1)]);
13825 xorMut$1(sum, encipher(xor(offset, adata)));
13826 adata = adata.subarray(blockLength$3);
13827 }
13828
13829 //
13830 // Process any final partial block; compute final hash value
13831 //
13832 if (adata.length) {
13833 xorMut$1(offset, mask.x);
13834
13835 const cipherInput = new Uint8Array(blockLength$3);
13836 cipherInput.set(adata, 0);
13837 cipherInput[adata.length] = 0b10000000;
13838 xorMut$1(cipherInput, offset);
13839
13840 xorMut$1(sum, encipher(cipherInput));
13841 }
13842
13843 return sum;
13844 }
13845
13846 /**
13847 * Encrypt/decrypt data.
13848 * @param {encipher|decipher} fn - Encryption/decryption block cipher function
13849 * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
13850 * @param {Uint8Array} nonce - The nonce (15 bytes)
13851 * @param {Uint8Array} adata - Associated data to sign
13852 * @returns {Uint8Array} The ciphertext or plaintext output, with tag appended in both cases.
13853 */
13854 function crypt(fn, text, nonce, adata) {
13855 //
13856 // Consider P as a sequence of 128-bit blocks
13857 //
13858 const m = text.length / blockLength$3 | 0;
13859
13860 //
13861 // Key-dependent variables
13862 //
13863 extendKeyVariables(text, adata);
13864
13865 //
13866 // Nonce-dependent and per-encryption variables
13867 //
13868 // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
13869 // Note: We assume here that tagLength mod 16 == 0.
13870 const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$2 - nonce.length), one$1, nonce]);
13871 // bottom = str2num(Nonce[123..128])
13872 const bottom = paddedNonce[blockLength$3 - 1] & 0b111111;
13873 // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
13874 paddedNonce[blockLength$3 - 1] &= 0b11000000;
13875 const kTop = encipher(paddedNonce);
13876 // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
13877 const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
13878 // Offset_0 = Stretch[1+bottom..128+bottom]
13879 const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
13880 // Checksum_0 = zeros(128)
13881 const checksum = new Uint8Array(blockLength$3);
13882
13883 const ct = new Uint8Array(text.length + tagLength$2);
13884
13885 //
13886 // Process any whole blocks
13887 //
13888 let i;
13889 let pos = 0;
13890 for (i = 0; i < m; i++) {
13891 // Offset_i = Offset_{i-1} xor L_{ntz(i)}
13892 xorMut$1(offset, mask[ntz(i + 1)]);
13893 // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
13894 // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
13895 ct.set(xorMut$1(fn(xor(offset, text)), offset), pos);
13896 // Checksum_i = Checksum_{i-1} xor P_i
13897 xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos));
13898
13899 text = text.subarray(blockLength$3);
13900 pos += blockLength$3;
13901 }
13902
13903 //
13904 // Process any final partial block and compute raw tag
13905 //
13906 if (text.length) {
13907 // Offset_* = Offset_m xor L_*
13908 xorMut$1(offset, mask.x);
13909 // Pad = ENCIPHER(K, Offset_*)
13910 const padding = encipher(offset);
13911 // C_* = P_* xor Pad[1..bitlen(P_*)]
13912 ct.set(xor(text, padding), pos);
13913
13914 // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
13915 const xorInput = new Uint8Array(blockLength$3);
13916 xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$2), 0);
13917 xorInput[text.length] = 0b10000000;
13918 xorMut$1(checksum, xorInput);
13919 pos += text.length;
13920 }
13921 // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
13922 const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata));
13923
13924 //
13925 // Assemble ciphertext
13926 //
13927 // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
13928 ct.set(tag, pos);
13929 return ct;
13930 }
13931
13932
13933 return {
13934 /**
13935 * Encrypt plaintext input.
13936 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
13937 * @param {Uint8Array} nonce - The nonce (15 bytes)
13938 * @param {Uint8Array} adata - Associated data to sign
13939 * @returns {Uint8Array} The ciphertext output.
13940 * @async
13941 */
13942 encrypt: async function(plaintext, nonce, adata) {
13943 return crypt(encipher, plaintext, nonce, adata);
13944 },
13945
13946 /**
13947 * Decrypt ciphertext input.
13948 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
13949 * @param {Uint8Array} nonce - The nonce (15 bytes)
13950 * @param {Uint8Array} adata - Associated data to sign
13951 * @returns {Uint8Array} The ciphertext output.
13952 * @async
13953 */
13954 decrypt: async function(ciphertext, nonce, adata) {
13955 if (ciphertext.length < tagLength$2) throw new Error('Invalid OCB ciphertext');
13956
13957 const tag = ciphertext.subarray(-tagLength$2);
13958 ciphertext = ciphertext.subarray(0, -tagLength$2);
13959
13960 const crypted = crypt(decipher, ciphertext, nonce, adata);
13961 // if (Tag[1..TAGLEN] == T)
13962 if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$2))) {
13963 return crypted.subarray(0, -tagLength$2);
13964 }
13965 throw new Error('Authentication tag mismatch');
13966 }
13967 };
13968}
13969
13970
13971/**
13972 * 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}.
13973 * @param {Uint8Array} iv - The initialization vector (15 bytes)
13974 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
13975 */
13976OCB.getNonce = function(iv, chunkIndex) {
13977 const nonce = iv.slice();
13978 for (let i = 0; i < chunkIndex.length; i++) {
13979 nonce[7 + i] ^= chunkIndex[i];
13980 }
13981 return nonce;
13982};
13983
13984OCB.blockLength = blockLength$3;
13985OCB.ivLength = ivLength$2;
13986OCB.tagLength = tagLength$2;
13987
13988var naclFastLight = createCommonjsModule(function (module) {
13989/*jshint bitwise: false*/
13990
13991(function(nacl) {
13992
13993// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
13994// Public domain.
13995//
13996// Implementation derived from TweetNaCl version 20140427.
13997// See for details: http://tweetnacl.cr.yp.to/
13998
13999var gf = function(init) {
14000 var i, r = new Float64Array(16);
14001 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
14002 return r;
14003};
14004
14005// Pluggable, initialized in high-level API below.
14006var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
14007
14008var _9 = new Uint8Array(32); _9[0] = 9;
14009
14010var gf0 = gf(),
14011 gf1 = gf([1]),
14012 _121665 = gf([0xdb41, 1]),
14013 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
14014 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
14015 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
14016 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
14017 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
14018
14019function vn(x, xi, y, yi, n) {
14020 var i,d = 0;
14021 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
14022 return (1 & ((d - 1) >>> 8)) - 1;
14023}
14024
14025function crypto_verify_32(x, xi, y, yi) {
14026 return vn(x,xi,y,yi,32);
14027}
14028
14029function set25519(r, a) {
14030 var i;
14031 for (i = 0; i < 16; i++) r[i] = a[i]|0;
14032}
14033
14034function car25519(o) {
14035 var i, v, c = 1;
14036 for (i = 0; i < 16; i++) {
14037 v = o[i] + c + 65535;
14038 c = Math.floor(v / 65536);
14039 o[i] = v - c * 65536;
14040 }
14041 o[0] += c-1 + 37 * (c-1);
14042}
14043
14044function sel25519(p, q, b) {
14045 var t, c = ~(b-1);
14046 for (var i = 0; i < 16; i++) {
14047 t = c & (p[i] ^ q[i]);
14048 p[i] ^= t;
14049 q[i] ^= t;
14050 }
14051}
14052
14053function pack25519(o, n) {
14054 var i, j, b;
14055 var m = gf(), t = gf();
14056 for (i = 0; i < 16; i++) t[i] = n[i];
14057 car25519(t);
14058 car25519(t);
14059 car25519(t);
14060 for (j = 0; j < 2; j++) {
14061 m[0] = t[0] - 0xffed;
14062 for (i = 1; i < 15; i++) {
14063 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
14064 m[i-1] &= 0xffff;
14065 }
14066 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
14067 b = (m[15]>>16) & 1;
14068 m[14] &= 0xffff;
14069 sel25519(t, m, 1-b);
14070 }
14071 for (i = 0; i < 16; i++) {
14072 o[2*i] = t[i] & 0xff;
14073 o[2*i+1] = t[i]>>8;
14074 }
14075}
14076
14077function neq25519(a, b) {
14078 var c = new Uint8Array(32), d = new Uint8Array(32);
14079 pack25519(c, a);
14080 pack25519(d, b);
14081 return crypto_verify_32(c, 0, d, 0);
14082}
14083
14084function par25519(a) {
14085 var d = new Uint8Array(32);
14086 pack25519(d, a);
14087 return d[0] & 1;
14088}
14089
14090function unpack25519(o, n) {
14091 var i;
14092 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
14093 o[15] &= 0x7fff;
14094}
14095
14096function A(o, a, b) {
14097 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
14098}
14099
14100function Z(o, a, b) {
14101 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
14102}
14103
14104function M(o, a, b) {
14105 var v, c,
14106 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
14107 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
14108 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
14109 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
14110 b0 = b[0],
14111 b1 = b[1],
14112 b2 = b[2],
14113 b3 = b[3],
14114 b4 = b[4],
14115 b5 = b[5],
14116 b6 = b[6],
14117 b7 = b[7],
14118 b8 = b[8],
14119 b9 = b[9],
14120 b10 = b[10],
14121 b11 = b[11],
14122 b12 = b[12],
14123 b13 = b[13],
14124 b14 = b[14],
14125 b15 = b[15];
14126
14127 v = a[0];
14128 t0 += v * b0;
14129 t1 += v * b1;
14130 t2 += v * b2;
14131 t3 += v * b3;
14132 t4 += v * b4;
14133 t5 += v * b5;
14134 t6 += v * b6;
14135 t7 += v * b7;
14136 t8 += v * b8;
14137 t9 += v * b9;
14138 t10 += v * b10;
14139 t11 += v * b11;
14140 t12 += v * b12;
14141 t13 += v * b13;
14142 t14 += v * b14;
14143 t15 += v * b15;
14144 v = a[1];
14145 t1 += v * b0;
14146 t2 += v * b1;
14147 t3 += v * b2;
14148 t4 += v * b3;
14149 t5 += v * b4;
14150 t6 += v * b5;
14151 t7 += v * b6;
14152 t8 += v * b7;
14153 t9 += v * b8;
14154 t10 += v * b9;
14155 t11 += v * b10;
14156 t12 += v * b11;
14157 t13 += v * b12;
14158 t14 += v * b13;
14159 t15 += v * b14;
14160 t16 += v * b15;
14161 v = a[2];
14162 t2 += v * b0;
14163 t3 += v * b1;
14164 t4 += v * b2;
14165 t5 += v * b3;
14166 t6 += v * b4;
14167 t7 += v * b5;
14168 t8 += v * b6;
14169 t9 += v * b7;
14170 t10 += v * b8;
14171 t11 += v * b9;
14172 t12 += v * b10;
14173 t13 += v * b11;
14174 t14 += v * b12;
14175 t15 += v * b13;
14176 t16 += v * b14;
14177 t17 += v * b15;
14178 v = a[3];
14179 t3 += v * b0;
14180 t4 += v * b1;
14181 t5 += v * b2;
14182 t6 += v * b3;
14183 t7 += v * b4;
14184 t8 += v * b5;
14185 t9 += v * b6;
14186 t10 += v * b7;
14187 t11 += v * b8;
14188 t12 += v * b9;
14189 t13 += v * b10;
14190 t14 += v * b11;
14191 t15 += v * b12;
14192 t16 += v * b13;
14193 t17 += v * b14;
14194 t18 += v * b15;
14195 v = a[4];
14196 t4 += v * b0;
14197 t5 += v * b1;
14198 t6 += v * b2;
14199 t7 += v * b3;
14200 t8 += v * b4;
14201 t9 += v * b5;
14202 t10 += v * b6;
14203 t11 += v * b7;
14204 t12 += v * b8;
14205 t13 += v * b9;
14206 t14 += v * b10;
14207 t15 += v * b11;
14208 t16 += v * b12;
14209 t17 += v * b13;
14210 t18 += v * b14;
14211 t19 += v * b15;
14212 v = a[5];
14213 t5 += v * b0;
14214 t6 += v * b1;
14215 t7 += v * b2;
14216 t8 += v * b3;
14217 t9 += v * b4;
14218 t10 += v * b5;
14219 t11 += v * b6;
14220 t12 += v * b7;
14221 t13 += v * b8;
14222 t14 += v * b9;
14223 t15 += v * b10;
14224 t16 += v * b11;
14225 t17 += v * b12;
14226 t18 += v * b13;
14227 t19 += v * b14;
14228 t20 += v * b15;
14229 v = a[6];
14230 t6 += v * b0;
14231 t7 += v * b1;
14232 t8 += v * b2;
14233 t9 += v * b3;
14234 t10 += v * b4;
14235 t11 += v * b5;
14236 t12 += v * b6;
14237 t13 += v * b7;
14238 t14 += v * b8;
14239 t15 += v * b9;
14240 t16 += v * b10;
14241 t17 += v * b11;
14242 t18 += v * b12;
14243 t19 += v * b13;
14244 t20 += v * b14;
14245 t21 += v * b15;
14246 v = a[7];
14247 t7 += v * b0;
14248 t8 += v * b1;
14249 t9 += v * b2;
14250 t10 += v * b3;
14251 t11 += v * b4;
14252 t12 += v * b5;
14253 t13 += v * b6;
14254 t14 += v * b7;
14255 t15 += v * b8;
14256 t16 += v * b9;
14257 t17 += v * b10;
14258 t18 += v * b11;
14259 t19 += v * b12;
14260 t20 += v * b13;
14261 t21 += v * b14;
14262 t22 += v * b15;
14263 v = a[8];
14264 t8 += v * b0;
14265 t9 += v * b1;
14266 t10 += v * b2;
14267 t11 += v * b3;
14268 t12 += v * b4;
14269 t13 += v * b5;
14270 t14 += v * b6;
14271 t15 += v * b7;
14272 t16 += v * b8;
14273 t17 += v * b9;
14274 t18 += v * b10;
14275 t19 += v * b11;
14276 t20 += v * b12;
14277 t21 += v * b13;
14278 t22 += v * b14;
14279 t23 += v * b15;
14280 v = a[9];
14281 t9 += v * b0;
14282 t10 += v * b1;
14283 t11 += v * b2;
14284 t12 += v * b3;
14285 t13 += v * b4;
14286 t14 += v * b5;
14287 t15 += v * b6;
14288 t16 += v * b7;
14289 t17 += v * b8;
14290 t18 += v * b9;
14291 t19 += v * b10;
14292 t20 += v * b11;
14293 t21 += v * b12;
14294 t22 += v * b13;
14295 t23 += v * b14;
14296 t24 += v * b15;
14297 v = a[10];
14298 t10 += v * b0;
14299 t11 += v * b1;
14300 t12 += v * b2;
14301 t13 += v * b3;
14302 t14 += v * b4;
14303 t15 += v * b5;
14304 t16 += v * b6;
14305 t17 += v * b7;
14306 t18 += v * b8;
14307 t19 += v * b9;
14308 t20 += v * b10;
14309 t21 += v * b11;
14310 t22 += v * b12;
14311 t23 += v * b13;
14312 t24 += v * b14;
14313 t25 += v * b15;
14314 v = a[11];
14315 t11 += v * b0;
14316 t12 += v * b1;
14317 t13 += v * b2;
14318 t14 += v * b3;
14319 t15 += v * b4;
14320 t16 += v * b5;
14321 t17 += v * b6;
14322 t18 += v * b7;
14323 t19 += v * b8;
14324 t20 += v * b9;
14325 t21 += v * b10;
14326 t22 += v * b11;
14327 t23 += v * b12;
14328 t24 += v * b13;
14329 t25 += v * b14;
14330 t26 += v * b15;
14331 v = a[12];
14332 t12 += v * b0;
14333 t13 += v * b1;
14334 t14 += v * b2;
14335 t15 += v * b3;
14336 t16 += v * b4;
14337 t17 += v * b5;
14338 t18 += v * b6;
14339 t19 += v * b7;
14340 t20 += v * b8;
14341 t21 += v * b9;
14342 t22 += v * b10;
14343 t23 += v * b11;
14344 t24 += v * b12;
14345 t25 += v * b13;
14346 t26 += v * b14;
14347 t27 += v * b15;
14348 v = a[13];
14349 t13 += v * b0;
14350 t14 += v * b1;
14351 t15 += v * b2;
14352 t16 += v * b3;
14353 t17 += v * b4;
14354 t18 += v * b5;
14355 t19 += v * b6;
14356 t20 += v * b7;
14357 t21 += v * b8;
14358 t22 += v * b9;
14359 t23 += v * b10;
14360 t24 += v * b11;
14361 t25 += v * b12;
14362 t26 += v * b13;
14363 t27 += v * b14;
14364 t28 += v * b15;
14365 v = a[14];
14366 t14 += v * b0;
14367 t15 += v * b1;
14368 t16 += v * b2;
14369 t17 += v * b3;
14370 t18 += v * b4;
14371 t19 += v * b5;
14372 t20 += v * b6;
14373 t21 += v * b7;
14374 t22 += v * b8;
14375 t23 += v * b9;
14376 t24 += v * b10;
14377 t25 += v * b11;
14378 t26 += v * b12;
14379 t27 += v * b13;
14380 t28 += v * b14;
14381 t29 += v * b15;
14382 v = a[15];
14383 t15 += v * b0;
14384 t16 += v * b1;
14385 t17 += v * b2;
14386 t18 += v * b3;
14387 t19 += v * b4;
14388 t20 += v * b5;
14389 t21 += v * b6;
14390 t22 += v * b7;
14391 t23 += v * b8;
14392 t24 += v * b9;
14393 t25 += v * b10;
14394 t26 += v * b11;
14395 t27 += v * b12;
14396 t28 += v * b13;
14397 t29 += v * b14;
14398 t30 += v * b15;
14399
14400 t0 += 38 * t16;
14401 t1 += 38 * t17;
14402 t2 += 38 * t18;
14403 t3 += 38 * t19;
14404 t4 += 38 * t20;
14405 t5 += 38 * t21;
14406 t6 += 38 * t22;
14407 t7 += 38 * t23;
14408 t8 += 38 * t24;
14409 t9 += 38 * t25;
14410 t10 += 38 * t26;
14411 t11 += 38 * t27;
14412 t12 += 38 * t28;
14413 t13 += 38 * t29;
14414 t14 += 38 * t30;
14415 // t15 left as is
14416
14417 // first car
14418 c = 1;
14419 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
14420 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
14421 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
14422 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
14423 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
14424 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
14425 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
14426 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
14427 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
14428 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
14429 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
14430 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
14431 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
14432 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
14433 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
14434 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
14435 t0 += c-1 + 37 * (c-1);
14436
14437 // second car
14438 c = 1;
14439 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
14440 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
14441 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
14442 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
14443 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
14444 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
14445 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
14446 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
14447 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
14448 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
14449 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
14450 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
14451 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
14452 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
14453 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
14454 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
14455 t0 += c-1 + 37 * (c-1);
14456
14457 o[ 0] = t0;
14458 o[ 1] = t1;
14459 o[ 2] = t2;
14460 o[ 3] = t3;
14461 o[ 4] = t4;
14462 o[ 5] = t5;
14463 o[ 6] = t6;
14464 o[ 7] = t7;
14465 o[ 8] = t8;
14466 o[ 9] = t9;
14467 o[10] = t10;
14468 o[11] = t11;
14469 o[12] = t12;
14470 o[13] = t13;
14471 o[14] = t14;
14472 o[15] = t15;
14473}
14474
14475function S(o, a) {
14476 M(o, a, a);
14477}
14478
14479function inv25519(o, i) {
14480 var c = gf();
14481 var a;
14482 for (a = 0; a < 16; a++) c[a] = i[a];
14483 for (a = 253; a >= 0; a--) {
14484 S(c, c);
14485 if(a !== 2 && a !== 4) M(c, c, i);
14486 }
14487 for (a = 0; a < 16; a++) o[a] = c[a];
14488}
14489
14490function pow2523(o, i) {
14491 var c = gf();
14492 var a;
14493 for (a = 0; a < 16; a++) c[a] = i[a];
14494 for (a = 250; a >= 0; a--) {
14495 S(c, c);
14496 if(a !== 1) M(c, c, i);
14497 }
14498 for (a = 0; a < 16; a++) o[a] = c[a];
14499}
14500
14501function crypto_scalarmult(q, n, p) {
14502 var z = new Uint8Array(32);
14503 var x = new Float64Array(80), r, i;
14504 var a = gf(), b = gf(), c = gf(),
14505 d = gf(), e = gf(), f = gf();
14506 for (i = 0; i < 31; i++) z[i] = n[i];
14507 z[31]=(n[31]&127)|64;
14508 z[0]&=248;
14509 unpack25519(x,p);
14510 for (i = 0; i < 16; i++) {
14511 b[i]=x[i];
14512 d[i]=a[i]=c[i]=0;
14513 }
14514 a[0]=d[0]=1;
14515 for (i=254; i>=0; --i) {
14516 r=(z[i>>>3]>>>(i&7))&1;
14517 sel25519(a,b,r);
14518 sel25519(c,d,r);
14519 A(e,a,c);
14520 Z(a,a,c);
14521 A(c,b,d);
14522 Z(b,b,d);
14523 S(d,e);
14524 S(f,a);
14525 M(a,c,a);
14526 M(c,b,e);
14527 A(e,a,c);
14528 Z(a,a,c);
14529 S(b,a);
14530 Z(c,d,f);
14531 M(a,c,_121665);
14532 A(a,a,d);
14533 M(c,c,a);
14534 M(a,d,f);
14535 M(d,b,x);
14536 S(b,e);
14537 sel25519(a,b,r);
14538 sel25519(c,d,r);
14539 }
14540 for (i = 0; i < 16; i++) {
14541 x[i+16]=a[i];
14542 x[i+32]=c[i];
14543 x[i+48]=b[i];
14544 x[i+64]=d[i];
14545 }
14546 var x32 = x.subarray(32);
14547 var x16 = x.subarray(16);
14548 inv25519(x32,x32);
14549 M(x16,x16,x32);
14550 pack25519(q,x16);
14551 return 0;
14552}
14553
14554function crypto_scalarmult_base(q, n) {
14555 return crypto_scalarmult(q, n, _9);
14556}
14557
14558function crypto_box_keypair(y, x) {
14559 randombytes(x, 32);
14560 return crypto_scalarmult_base(y, x);
14561}
14562
14563function add(p, q) {
14564 var a = gf(), b = gf(), c = gf(),
14565 d = gf(), e = gf(), f = gf(),
14566 g = gf(), h = gf(), t = gf();
14567
14568 Z(a, p[1], p[0]);
14569 Z(t, q[1], q[0]);
14570 M(a, a, t);
14571 A(b, p[0], p[1]);
14572 A(t, q[0], q[1]);
14573 M(b, b, t);
14574 M(c, p[3], q[3]);
14575 M(c, c, D2);
14576 M(d, p[2], q[2]);
14577 A(d, d, d);
14578 Z(e, b, a);
14579 Z(f, d, c);
14580 A(g, d, c);
14581 A(h, b, a);
14582
14583 M(p[0], e, f);
14584 M(p[1], h, g);
14585 M(p[2], g, f);
14586 M(p[3], e, h);
14587}
14588
14589function cswap(p, q, b) {
14590 var i;
14591 for (i = 0; i < 4; i++) {
14592 sel25519(p[i], q[i], b);
14593 }
14594}
14595
14596function pack(r, p) {
14597 var tx = gf(), ty = gf(), zi = gf();
14598 inv25519(zi, p[2]);
14599 M(tx, p[0], zi);
14600 M(ty, p[1], zi);
14601 pack25519(r, ty);
14602 r[31] ^= par25519(tx) << 7;
14603}
14604
14605function scalarmult(p, q, s) {
14606 var b, i;
14607 set25519(p[0], gf0);
14608 set25519(p[1], gf1);
14609 set25519(p[2], gf1);
14610 set25519(p[3], gf0);
14611 for (i = 255; i >= 0; --i) {
14612 b = (s[(i/8)|0] >> (i&7)) & 1;
14613 cswap(p, q, b);
14614 add(q, p);
14615 add(p, p);
14616 cswap(p, q, b);
14617 }
14618}
14619
14620function scalarbase(p, s) {
14621 var q = [gf(), gf(), gf(), gf()];
14622 set25519(q[0], X);
14623 set25519(q[1], Y);
14624 set25519(q[2], gf1);
14625 M(q[3], X, Y);
14626 scalarmult(p, q, s);
14627}
14628
14629function crypto_sign_keypair(pk, sk, seeded) {
14630 var d;
14631 var p = [gf(), gf(), gf(), gf()];
14632 var i;
14633
14634 if (!seeded) randombytes(sk, 32);
14635 d = nacl.hash(sk.subarray(0, 32));
14636 d[0] &= 248;
14637 d[31] &= 127;
14638 d[31] |= 64;
14639
14640 scalarbase(p, d);
14641 pack(pk, p);
14642
14643 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
14644 return 0;
14645}
14646
14647var 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]);
14648
14649function modL(r, x) {
14650 var carry, i, j, k;
14651 for (i = 63; i >= 32; --i) {
14652 carry = 0;
14653 for (j = i - 32, k = i - 12; j < k; ++j) {
14654 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
14655 carry = Math.floor((x[j] + 128) / 256);
14656 x[j] -= carry * 256;
14657 }
14658 x[j] += carry;
14659 x[i] = 0;
14660 }
14661 carry = 0;
14662 for (j = 0; j < 32; j++) {
14663 x[j] += carry - (x[31] >> 4) * L[j];
14664 carry = x[j] >> 8;
14665 x[j] &= 255;
14666 }
14667 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
14668 for (i = 0; i < 32; i++) {
14669 x[i+1] += x[i] >> 8;
14670 r[i] = x[i] & 255;
14671 }
14672}
14673
14674function reduce(r) {
14675 var x = new Float64Array(64), i;
14676 for (i = 0; i < 64; i++) x[i] = r[i];
14677 for (i = 0; i < 64; i++) r[i] = 0;
14678 modL(r, x);
14679}
14680
14681// Note: difference from C - smlen returned, not passed as argument.
14682function crypto_sign(sm, m, n, sk) {
14683 var d, h, r;
14684 var i, j, x = new Float64Array(64);
14685 var p = [gf(), gf(), gf(), gf()];
14686
14687 d = nacl.hash(sk.subarray(0, 32));
14688 d[0] &= 248;
14689 d[31] &= 127;
14690 d[31] |= 64;
14691
14692 var smlen = n + 64;
14693 for (i = 0; i < n; i++) sm[64 + i] = m[i];
14694 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
14695
14696 r = nacl.hash(sm.subarray(32, smlen));
14697 reduce(r);
14698 scalarbase(p, r);
14699 pack(sm, p);
14700
14701 for (i = 32; i < 64; i++) sm[i] = sk[i];
14702 h = nacl.hash(sm.subarray(0, smlen));
14703 reduce(h);
14704
14705 for (i = 0; i < 64; i++) x[i] = 0;
14706 for (i = 0; i < 32; i++) x[i] = r[i];
14707 for (i = 0; i < 32; i++) {
14708 for (j = 0; j < 32; j++) {
14709 x[i+j] += h[i] * d[j];
14710 }
14711 }
14712
14713 modL(sm.subarray(32), x);
14714 return smlen;
14715}
14716
14717function unpackneg(r, p) {
14718 var t = gf(), chk = gf(), num = gf(),
14719 den = gf(), den2 = gf(), den4 = gf(),
14720 den6 = gf();
14721
14722 set25519(r[2], gf1);
14723 unpack25519(r[1], p);
14724 S(num, r[1]);
14725 M(den, num, D);
14726 Z(num, num, r[2]);
14727 A(den, r[2], den);
14728
14729 S(den2, den);
14730 S(den4, den2);
14731 M(den6, den4, den2);
14732 M(t, den6, num);
14733 M(t, t, den);
14734
14735 pow2523(t, t);
14736 M(t, t, num);
14737 M(t, t, den);
14738 M(t, t, den);
14739 M(r[0], t, den);
14740
14741 S(chk, r[0]);
14742 M(chk, chk, den);
14743 if (neq25519(chk, num)) M(r[0], r[0], I);
14744
14745 S(chk, r[0]);
14746 M(chk, chk, den);
14747 if (neq25519(chk, num)) return -1;
14748
14749 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
14750
14751 M(r[3], r[0], r[1]);
14752 return 0;
14753}
14754
14755function crypto_sign_open(m, sm, n, pk) {
14756 var i;
14757 var t = new Uint8Array(32), h;
14758 var p = [gf(), gf(), gf(), gf()],
14759 q = [gf(), gf(), gf(), gf()];
14760
14761 if (n < 64) return -1;
14762
14763 if (unpackneg(q, pk)) return -1;
14764
14765 for (i = 0; i < n; i++) m[i] = sm[i];
14766 for (i = 0; i < 32; i++) m[i+32] = pk[i];
14767 h = nacl.hash(m.subarray(0, n));
14768 reduce(h);
14769 scalarmult(p, q, h);
14770
14771 scalarbase(q, sm.subarray(32));
14772 add(p, q);
14773 pack(t, p);
14774
14775 n -= 64;
14776 if (crypto_verify_32(sm, 0, t, 0)) {
14777 for (i = 0; i < n; i++) m[i] = 0;
14778 return -1;
14779 }
14780
14781 for (i = 0; i < n; i++) m[i] = sm[i + 64];
14782 return n;
14783}
14784
14785var crypto_scalarmult_BYTES = 32,
14786 crypto_scalarmult_SCALARBYTES = 32,
14787 crypto_box_PUBLICKEYBYTES = 32,
14788 crypto_box_SECRETKEYBYTES = 32,
14789 crypto_sign_BYTES = 64,
14790 crypto_sign_PUBLICKEYBYTES = 32,
14791 crypto_sign_SECRETKEYBYTES = 64,
14792 crypto_sign_SEEDBYTES = 32;
14793
14794function checkArrayTypes() {
14795 for (var i = 0; i < arguments.length; i++) {
14796 if (!(arguments[i] instanceof Uint8Array))
14797 throw new TypeError('unexpected type, use Uint8Array');
14798 }
14799}
14800
14801function cleanup(arr) {
14802 for (var i = 0; i < arr.length; i++) arr[i] = 0;
14803}
14804
14805nacl.scalarMult = function(n, p) {
14806 checkArrayTypes(n, p);
14807 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
14808 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
14809 var q = new Uint8Array(crypto_scalarmult_BYTES);
14810 crypto_scalarmult(q, n, p);
14811 return q;
14812};
14813
14814nacl.box = {};
14815
14816nacl.box.keyPair = function() {
14817 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
14818 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
14819 crypto_box_keypair(pk, sk);
14820 return {publicKey: pk, secretKey: sk};
14821};
14822
14823nacl.box.keyPair.fromSecretKey = function(secretKey) {
14824 checkArrayTypes(secretKey);
14825 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
14826 throw new Error('bad secret key size');
14827 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
14828 crypto_scalarmult_base(pk, secretKey);
14829 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
14830};
14831
14832nacl.sign = function(msg, secretKey) {
14833 checkArrayTypes(msg, secretKey);
14834 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
14835 throw new Error('bad secret key size');
14836 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
14837 crypto_sign(signedMsg, msg, msg.length, secretKey);
14838 return signedMsg;
14839};
14840
14841nacl.sign.detached = function(msg, secretKey) {
14842 var signedMsg = nacl.sign(msg, secretKey);
14843 var sig = new Uint8Array(crypto_sign_BYTES);
14844 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
14845 return sig;
14846};
14847
14848nacl.sign.detached.verify = function(msg, sig, publicKey) {
14849 checkArrayTypes(msg, sig, publicKey);
14850 if (sig.length !== crypto_sign_BYTES)
14851 throw new Error('bad signature size');
14852 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
14853 throw new Error('bad public key size');
14854 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
14855 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
14856 var i;
14857 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
14858 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
14859 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
14860};
14861
14862nacl.sign.keyPair = function() {
14863 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
14864 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
14865 crypto_sign_keypair(pk, sk);
14866 return {publicKey: pk, secretKey: sk};
14867};
14868
14869nacl.sign.keyPair.fromSecretKey = function(secretKey) {
14870 checkArrayTypes(secretKey);
14871 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
14872 throw new Error('bad secret key size');
14873 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
14874 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
14875 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
14876};
14877
14878nacl.sign.keyPair.fromSeed = function(seed) {
14879 checkArrayTypes(seed);
14880 if (seed.length !== crypto_sign_SEEDBYTES)
14881 throw new Error('bad seed size');
14882 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
14883 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
14884 for (var i = 0; i < 32; i++) sk[i] = seed[i];
14885 crypto_sign_keypair(pk, sk, true);
14886 return {publicKey: pk, secretKey: sk};
14887};
14888
14889nacl.setPRNG = function(fn) {
14890 randombytes = fn;
14891};
14892
14893(function() {
14894 // Initialize PRNG if environment provides CSPRNG.
14895 // If not, methods calling randombytes will throw.
14896 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
14897 if (crypto && crypto.getRandomValues) {
14898 // Browsers.
14899 var QUOTA = 65536;
14900 nacl.setPRNG(function(x, n) {
14901 var i, v = new Uint8Array(n);
14902 for (i = 0; i < n; i += QUOTA) {
14903 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
14904 }
14905 for (i = 0; i < n; i++) x[i] = v[i];
14906 cleanup(v);
14907 });
14908 } else if (typeof commonjsRequire !== 'undefined') {
14909 // Node.js.
14910 crypto = crypto__default['default'];
14911 if (crypto && crypto.randomBytes) {
14912 nacl.setPRNG(function(x, n) {
14913 var i, v = crypto.randomBytes(n);
14914 for (i = 0; i < n; i++) x[i] = v[i];
14915 cleanup(v);
14916 });
14917 }
14918 }
14919})();
14920
14921})(module.exports ? module.exports : (self.nacl = self.nacl || {}));
14922});
14923
14924// GPG4Browsers - An OpenPGP implementation in javascript
14925
14926const nodeCrypto$5 = util.getNodeCrypto();
14927
14928/**
14929 * Buffer for secure random numbers
14930 */
14931class RandomBuffer {
14932 constructor() {
14933 this.buffer = null;
14934 this.size = null;
14935 this.callback = null;
14936 }
14937
14938 /**
14939 * Initialize buffer
14940 * @param {Integer} size - size of buffer
14941 */
14942 init(size, callback) {
14943 this.buffer = new Uint8Array(size);
14944 this.size = 0;
14945 this.callback = callback;
14946 }
14947
14948 /**
14949 * Concat array of secure random numbers to buffer
14950 * @param {Uint8Array} buf
14951 */
14952 set(buf) {
14953 if (!this.buffer) {
14954 throw new Error('RandomBuffer is not initialized');
14955 }
14956 if (!(buf instanceof Uint8Array)) {
14957 throw new Error('Invalid type: buf not an Uint8Array');
14958 }
14959 const freeSpace = this.buffer.length - this.size;
14960 if (buf.length > freeSpace) {
14961 buf = buf.subarray(0, freeSpace);
14962 }
14963 // set buf with offset old size of buffer
14964 this.buffer.set(buf, this.size);
14965 this.size += buf.length;
14966 }
14967
14968 /**
14969 * Take numbers out of buffer and copy to array
14970 * @param {Uint8Array} buf - The destination array
14971 */
14972 async get(buf) {
14973 if (!this.buffer) {
14974 throw new Error('RandomBuffer is not initialized');
14975 }
14976 if (!(buf instanceof Uint8Array)) {
14977 throw new Error('Invalid type: buf not an Uint8Array');
14978 }
14979 if (this.size < buf.length) {
14980 if (!this.callback) {
14981 throw new Error('Random number buffer depleted');
14982 }
14983 // Wait for random bytes from main context, then try again
14984 await this.callback();
14985 return this.get(buf);
14986 }
14987 for (let i = 0; i < buf.length; i++) {
14988 buf[i] = this.buffer[--this.size];
14989 // clear buffer value
14990 this.buffer[this.size] = 0;
14991 }
14992 }
14993}
14994
14995/**
14996 * Retrieve secure random byte array of the specified length
14997 * @param {Integer} length - Length in bytes to generate
14998 * @returns {Uint8Array} Random byte array.
14999 * @async
15000 */
15001async function getRandomBytes(length) {
15002 const buf = new Uint8Array(length);
15003 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
15004 crypto.getRandomValues(buf);
15005 } else if (typeof globalThis !== 'undefined' && typeof globalThis.msCrypto === 'object' && typeof globalThis.msCrypto.getRandomValues === 'function') {
15006 globalThis.msCrypto.getRandomValues(buf);
15007 } else if (nodeCrypto$5) {
15008 const bytes = nodeCrypto$5.randomBytes(buf.length);
15009 buf.set(bytes);
15010 } else if (randomBuffer.buffer) {
15011 await randomBuffer.get(buf);
15012 } else {
15013 throw new Error('No secure random number generator available.');
15014 }
15015 return buf;
15016}
15017
15018/**
15019 * Create a secure random BigInteger that is greater than or equal to min and less than max.
15020 * @param {module:BigInteger} min - Lower bound, included
15021 * @param {module:BigInteger} max - Upper bound, excluded
15022 * @returns {module:BigInteger} Random BigInteger.
15023 * @async
15024 */
15025async function getRandomBigInteger(min, max) {
15026 const BigInteger = await util.getBigInteger();
15027
15028 if (max.lt(min)) {
15029 throw new Error('Illegal parameter value: max <= min');
15030 }
15031
15032 const modulus = max.sub(min);
15033 const bytes = modulus.byteLength();
15034
15035 // Using a while loop is necessary to avoid bias introduced by the mod operation.
15036 // However, we request 64 extra random bits so that the bias is negligible.
15037 // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
15038 const r = new BigInteger(await getRandomBytes(bytes + 8));
15039 return r.mod(modulus).add(min);
15040}
15041
15042const randomBuffer = new RandomBuffer();
15043
15044var random = /*#__PURE__*/Object.freeze({
15045 __proto__: null,
15046 getRandomBytes: getRandomBytes,
15047 getRandomBigInteger: getRandomBigInteger,
15048 randomBuffer: randomBuffer
15049});
15050
15051// OpenPGP.js - An OpenPGP implementation in javascript
15052
15053/**
15054 * Probabilistic random number generator
15055 * @param {Integer} bits - Bit length of the prime
15056 * @param {BigInteger} e - Optional RSA exponent to check against the prime
15057 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
15058 * @returns BigInteger
15059 * @async
15060 */
15061async function randomProbablePrime(bits, e, k) {
15062 const BigInteger = await util.getBigInteger();
15063 const one = new BigInteger(1);
15064 const min = one.leftShift(new BigInteger(bits - 1));
15065 const thirty = new BigInteger(30);
15066 /*
15067 * We can avoid any multiples of 3 and 5 by looking at n mod 30
15068 * 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
15069 * the next possible prime is mod 30:
15070 * 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
15071 */
15072 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];
15073
15074 const n = await getRandomBigInteger(min, min.leftShift(one));
15075 let i = n.mod(thirty).toNumber();
15076
15077 do {
15078 n.iadd(new BigInteger(adds[i]));
15079 i = (i + adds[i]) % adds.length;
15080 // If reached the maximum, go back to the minimum.
15081 if (n.bitLength() > bits) {
15082 n.imod(min.leftShift(one)).iadd(min);
15083 i = n.mod(thirty).toNumber();
15084 }
15085 } while (!await isProbablePrime(n, e, k));
15086 return n;
15087}
15088
15089/**
15090 * Probabilistic primality testing
15091 * @param {BigInteger} n - Number to test
15092 * @param {BigInteger} e - Optional RSA exponent to check against the prime
15093 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
15094 * @returns {boolean}
15095 * @async
15096 */
15097async function isProbablePrime(n, e, k) {
15098 if (e && !n.dec().gcd(e).isOne()) {
15099 return false;
15100 }
15101 if (!await divisionTest(n)) {
15102 return false;
15103 }
15104 if (!await fermat(n)) {
15105 return false;
15106 }
15107 if (!await millerRabin(n, k)) {
15108 return false;
15109 }
15110 // TODO implement the Lucas test
15111 // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
15112 return true;
15113}
15114
15115/**
15116 * Tests whether n is probably prime or not using Fermat's test with b = 2.
15117 * Fails if b^(n-1) mod n != 1.
15118 * @param {BigInteger} n - Number to test
15119 * @param {BigInteger} b - Optional Fermat test base
15120 * @returns {boolean}
15121 */
15122async function fermat(n, b) {
15123 const BigInteger = await util.getBigInteger();
15124 b = b || new BigInteger(2);
15125 return b.modExp(n.dec(), n).isOne();
15126}
15127
15128async function divisionTest(n) {
15129 const BigInteger = await util.getBigInteger();
15130 return smallPrimes.every(m => {
15131 return n.mod(new BigInteger(m)) !== 0;
15132 });
15133}
15134
15135// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
15136const smallPrimes = [
15137 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
15138 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
15139 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
15140 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
15141 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
15142 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
15143 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
15144 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
15145 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
15146 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
15147 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
15148 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
15149 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
15150 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
15151 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
15152 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
15153 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
15154 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
15155 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
15156 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
15157 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
15158 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
15159 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
15160 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
15161 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
15162 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
15163 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
15164 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
15165 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
15166 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
15167 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
15168 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
15169 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
15170 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
15171 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
15172 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
15173 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
15174 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
15175 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
15176 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
15177 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
15178 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
15179 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
15180 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
15181 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
15182 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
15183 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
15184 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
15185 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
15186 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
15187 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
15188 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
15189 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
15190 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
15191 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
15192 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
15193 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
15194 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
15195 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
15196 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
15197 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
15198 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
15199 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
15200 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
15201 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
15202 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
15203 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
15204 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
15205 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
15206 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
15207 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
15208 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
15209 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
15210 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
15211 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
15212 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
15213 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
15214 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
15215 4957, 4967, 4969, 4973, 4987, 4993, 4999
15216];
15217
15218
15219// Miller-Rabin - Miller Rabin algorithm for primality test
15220// Copyright Fedor Indutny, 2014.
15221//
15222// This software is licensed under the MIT License.
15223//
15224// Permission is hereby granted, free of charge, to any person obtaining a
15225// copy of this software and associated documentation files (the
15226// "Software"), to deal in the Software without restriction, including
15227// without limitation the rights to use, copy, modify, merge, publish,
15228// distribute, sublicense, and/or sell copies of the Software, and to permit
15229// persons to whom the Software is furnished to do so, subject to the
15230// following conditions:
15231//
15232// The above copyright notice and this permission notice shall be included
15233// in all copies or substantial portions of the Software.
15234//
15235// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15236// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15237// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15238// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15239// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15240// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15241// USE OR OTHER DEALINGS IN THE SOFTWARE.
15242
15243// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
15244
15245// Sample syntax for Fixed-Base Miller-Rabin:
15246// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
15247
15248/**
15249 * Tests whether n is probably prime or not using the Miller-Rabin test.
15250 * See HAC Remark 4.28.
15251 * @param {BigInteger} n - Number to test
15252 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
15253 * @param {Function} rand - Optional function to generate potential witnesses
15254 * @returns {boolean}
15255 * @async
15256 */
15257async function millerRabin(n, k, rand) {
15258 const BigInteger = await util.getBigInteger();
15259 const len = n.bitLength();
15260
15261 if (!k) {
15262 k = Math.max(1, (len / 48) | 0);
15263 }
15264
15265 const n1 = n.dec(); // n - 1
15266
15267 // Find d and s, (n - 1) = (2 ^ s) * d;
15268 let s = 0;
15269 while (!n1.getBit(s)) { s++; }
15270 const d = n.rightShift(new BigInteger(s));
15271
15272 for (; k > 0; k--) {
15273 const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);
15274
15275 let x = a.modExp(d, n);
15276 if (x.isOne() || x.equal(n1)) {
15277 continue;
15278 }
15279
15280 let i;
15281 for (i = 1; i < s; i++) {
15282 x = x.mul(x).mod(n);
15283
15284 if (x.isOne()) {
15285 return false;
15286 }
15287 if (x.equal(n1)) {
15288 break;
15289 }
15290 }
15291
15292 if (i === s) {
15293 return false;
15294 }
15295 }
15296
15297 return true;
15298}
15299
15300// GPG4Browsers - An OpenPGP implementation in javascript
15301
15302/**
15303 * ASN1 object identifiers for hashes
15304 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
15305 */
15306const hash_headers = [];
15307hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
15308 0x10];
15309hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
15310hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
15311hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
15312 0x04, 0x20];
15313hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
15314 0x04, 0x30];
15315hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
15316 0x00, 0x04, 0x40];
15317hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
15318 0x00, 0x04, 0x1C];
15319
15320/**
15321 * Create padding with secure random data
15322 * @private
15323 * @param {Integer} length - Length of the padding in bytes
15324 * @returns {Uint8Array} Random padding.
15325 * @async
15326 */
15327async function getPkcs1Padding(length) {
15328 const result = new Uint8Array(length);
15329 let count = 0;
15330 while (count < length) {
15331 const randomBytes = await getRandomBytes(length - count);
15332 for (let i = 0; i < randomBytes.length; i++) {
15333 if (randomBytes[i] !== 0) {
15334 result[count++] = randomBytes[i];
15335 }
15336 }
15337 }
15338 return result;
15339}
15340
15341/**
15342 * Create a EME-PKCS1-v1_5 padded message
15343 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
15344 * @param {Uint8Array} message - Message to be encoded
15345 * @param {Integer} keyLength - The length in octets of the key modulus
15346 * @returns {Uint8Array} EME-PKCS1 padded message.
15347 * @async
15348 */
15349async function emeEncode(message, keyLength) {
15350 const mLength = message.length;
15351 // length checking
15352 if (mLength > keyLength - 11) {
15353 throw new Error('Message too long');
15354 }
15355 // Generate an octet string PS of length k - mLen - 3 consisting of
15356 // pseudo-randomly generated nonzero octets
15357 const PS = await getPkcs1Padding(keyLength - mLength - 3);
15358 // Concatenate PS, the message M, and other padding to form an
15359 // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
15360 const encoded = new Uint8Array(keyLength);
15361 // 0x00 byte
15362 encoded[1] = 2;
15363 encoded.set(PS, 2);
15364 // 0x00 bytes
15365 encoded.set(message, keyLength - mLength);
15366 return encoded;
15367}
15368
15369/**
15370 * Decode a EME-PKCS1-v1_5 padded message
15371 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
15372 * @param {Uint8Array} encoded - Encoded message bytes
15373 * @returns {Uint8Array} Message.
15374 */
15375function emeDecode(encoded) {
15376 let i = 2;
15377 while (encoded[i] !== 0 && i < encoded.length) {
15378 i++;
15379 }
15380 const psLen = i - 2;
15381 const separator = encoded[i++];
15382 if (encoded[0] === 0 && encoded[1] === 2 && psLen >= 8 && separator === 0) {
15383 return encoded.subarray(i);
15384 }
15385 throw new Error('Decryption error');
15386}
15387
15388/**
15389 * Create a EMSA-PKCS1-v1_5 padded message
15390 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
15391 * @param {Integer} algo - Hash algorithm type used
15392 * @param {Uint8Array} hashed - Message to be encoded
15393 * @param {Integer} emLen - Intended length in octets of the encoded message
15394 * @returns {Uint8Array} Encoded message.
15395 */
15396async function emsaEncode(algo, hashed, emLen) {
15397 let i;
15398 if (hashed.length !== hash.getHashByteLength(algo)) {
15399 throw new Error('Invalid hash length');
15400 }
15401 // produce an ASN.1 DER value for the hash function used.
15402 // Let T be the full hash prefix
15403 const hashPrefix = new Uint8Array(hash_headers[algo].length);
15404 for (i = 0; i < hash_headers[algo].length; i++) {
15405 hashPrefix[i] = hash_headers[algo][i];
15406 }
15407 // and let tLen be the length in octets prefix and hashed data
15408 const tLen = hashPrefix.length + hashed.length;
15409 if (emLen < tLen + 11) {
15410 throw new Error('Intended encoded message length too short');
15411 }
15412 // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
15413 // The length of PS will be at least 8 octets
15414 const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
15415
15416 // Concatenate PS, the hash prefix, hashed data, and other padding to form the
15417 // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
15418 const EM = new Uint8Array(emLen);
15419 EM[1] = 0x01;
15420 EM.set(PS, 2);
15421 EM.set(hashPrefix, emLen - tLen);
15422 EM.set(hashed, emLen - hashed.length);
15423 return EM;
15424}
15425
15426var pkcs1 = /*#__PURE__*/Object.freeze({
15427 __proto__: null,
15428 emeEncode: emeEncode,
15429 emeDecode: emeDecode,
15430 emsaEncode: emsaEncode
15431});
15432
15433const webCrypto$5 = util.getWebCrypto();
15434const nodeCrypto$6 = util.getNodeCrypto();
15435const asn1 = nodeCrypto$6 ? asn1__default['default'] : undefined;
15436
15437// Helper for IE11 KeyOperation objects
15438function promisifyIE11Op(keyObj, err) {
15439 if (typeof keyObj.then !== 'function') { // IE11 KeyOperation
15440 return new Promise(function(resolve, reject) {
15441 keyObj.onerror = function () {
15442 reject(new Error(err));
15443 };
15444 keyObj.oncomplete = function (e) {
15445 resolve(e.target.result);
15446 };
15447 });
15448 }
15449 return keyObj;
15450}
15451
15452/* eslint-disable no-invalid-this */
15453const RSAPrivateKey = util.detectNode() ? asn1.define('RSAPrivateKey', function () {
15454 this.seq().obj( // used for native NodeJS crypto
15455 this.key('version').int(), // 0
15456 this.key('modulus').int(), // n
15457 this.key('publicExponent').int(), // e
15458 this.key('privateExponent').int(), // d
15459 this.key('prime1').int(), // p
15460 this.key('prime2').int(), // q
15461 this.key('exponent1').int(), // dp
15462 this.key('exponent2').int(), // dq
15463 this.key('coefficient').int() // u
15464 );
15465}) : undefined;
15466
15467const RSAPublicKey = util.detectNode() ? asn1.define('RSAPubliceKey', function () {
15468 this.seq().obj( // used for native NodeJS crypto
15469 this.key('modulus').int(), // n
15470 this.key('publicExponent').int(), // e
15471 );
15472}) : undefined;
15473/* eslint-enable no-invalid-this */
15474
15475/** Create signature
15476 * @param {module:enums.hash} hash_algo - Hash algorithm
15477 * @param {Uint8Array} data - Message
15478 * @param {Uint8Array} n - RSA public modulus
15479 * @param {Uint8Array} e - RSA public exponent
15480 * @param {Uint8Array} d - RSA private exponent
15481 * @param {Uint8Array} p - RSA private prime p
15482 * @param {Uint8Array} q - RSA private prime q
15483 * @param {Uint8Array} u - RSA private coefficient
15484 * @param {Uint8Array} hashed - Hashed message
15485 * @returns {Uint8Array} RSA Signature.
15486 * @async
15487 */
15488async function sign(hash_algo, data, n, e, d, p, q, u, hashed) {
15489 if (data && !util.isStream(data)) {
15490 if (util.getWebCrypto()) {
15491 try {
15492 return await webSign(enums.read(enums.webHash, hash_algo), data, n, e, d, p, q, u);
15493 } catch (err) {
15494 util.printDebugError(err);
15495 }
15496 } else if (util.getNodeCrypto()) {
15497 return nodeSign(hash_algo, data, n, e, d, p, q, u);
15498 }
15499 }
15500 return bnSign(hash_algo, n, d, hashed);
15501}
15502
15503/**
15504 * Verify signature
15505 * @param {module:enums.hash} hash_algo - Hash algorithm
15506 * @param {Uint8Array} data - Message
15507 * @param {Uint8Array} s - Signature
15508 * @param {Uint8Array} n - RSA public modulus
15509 * @param {Uint8Array} e - RSA public exponent
15510 * @param {Uint8Array} hashed - Hashed message
15511 * @returns {Boolean}
15512 * @async
15513 */
15514async function verify(hash_algo, data, s, n, e, hashed) {
15515 if (data && !util.isStream(data)) {
15516 if (util.getWebCrypto()) {
15517 try {
15518 return await webVerify(enums.read(enums.webHash, hash_algo), data, s, n, e);
15519 } catch (err) {
15520 util.printDebugError(err);
15521 }
15522 } else if (util.getNodeCrypto()) {
15523 return nodeVerify(hash_algo, data, s, n, e);
15524 }
15525 }
15526 return bnVerify(hash_algo, s, n, e, hashed);
15527}
15528
15529/**
15530 * Encrypt message
15531 * @param {Uint8Array} data - Message
15532 * @param {Uint8Array} n - RSA public modulus
15533 * @param {Uint8Array} e - RSA public exponent
15534 * @returns {Uint8Array} RSA Ciphertext.
15535 * @async
15536 */
15537async function encrypt$1(data, n, e) {
15538 if (util.getNodeCrypto()) {
15539 return nodeEncrypt$1(data, n, e);
15540 }
15541 return bnEncrypt(data, n, e);
15542}
15543
15544/**
15545 * Decrypt RSA message
15546 * @param {Uint8Array} m - Message
15547 * @param {Uint8Array} n - RSA public modulus
15548 * @param {Uint8Array} e - RSA public exponent
15549 * @param {Uint8Array} d - RSA private exponent
15550 * @param {Uint8Array} p - RSA private prime p
15551 * @param {Uint8Array} q - RSA private prime q
15552 * @param {Uint8Array} u - RSA private coefficient
15553 * @returns {String} RSA Plaintext.
15554 * @async
15555 */
15556async function decrypt$1(data, n, e, d, p, q, u) {
15557 if (util.getNodeCrypto()) {
15558 return nodeDecrypt$1(data, n, e, d, p, q, u);
15559 }
15560 return bnDecrypt(data, n, e, d, p, q, u);
15561}
15562
15563/**
15564 * Generate a new random private key B bits long with public exponent E.
15565 *
15566 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
15567 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
15568 * @see module:crypto/public_key/prime
15569 * @param {Integer} bits - RSA bit length
15570 * @param {Integer} e - RSA public exponent
15571 * @returns {{n, e, d,
15572 * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,
15573 * RSA private prime p, RSA private prime q, u = p ** -1 mod q
15574 * @async
15575 */
15576async function generate(bits, e) {
15577 const BigInteger = await util.getBigInteger();
15578
15579 e = new BigInteger(e);
15580
15581 // Native RSA keygen using Web Crypto
15582 if (util.getWebCrypto()) {
15583 let keyPair;
15584 let keyGenOpt;
15585 if ((globalThis.crypto && globalThis.crypto.subtle) || globalThis.msCrypto) {
15586 // current standard spec
15587 keyGenOpt = {
15588 name: 'RSASSA-PKCS1-v1_5',
15589 modulusLength: bits, // the specified keysize in bits
15590 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
15591 hash: {
15592 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
15593 }
15594 };
15595 keyPair = webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']);
15596 keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.');
15597 } else if (globalThis.crypto && globalThis.crypto.webkitSubtle) {
15598 // outdated spec implemented by old Webkit
15599 keyGenOpt = {
15600 name: 'RSA-OAEP',
15601 modulusLength: bits, // the specified keysize in bits
15602 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
15603 hash: {
15604 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
15605 }
15606 };
15607 keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']);
15608 } else {
15609 throw new Error('Unknown WebCrypto implementation');
15610 }
15611
15612 // export the generated keys as JsonWebKey (JWK)
15613 // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
15614 let jwk = webCrypto$5.exportKey('jwk', keyPair.privateKey);
15615 jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.');
15616
15617 // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk)
15618 if (jwk instanceof ArrayBuffer) {
15619 jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk)));
15620 }
15621 // map JWK parameters to corresponding OpenPGP names
15622 return {
15623 n: b64ToUint8Array(jwk.n),
15624 e: e.toUint8Array(),
15625 d: b64ToUint8Array(jwk.d),
15626 // switch p and q
15627 p: b64ToUint8Array(jwk.q),
15628 q: b64ToUint8Array(jwk.p),
15629 // Since p and q are switched in places, u is the inverse of jwk.q
15630 u: b64ToUint8Array(jwk.qi)
15631 };
15632 } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) {
15633 const opts = {
15634 modulusLength: bits,
15635 publicExponent: e.toNumber(),
15636 publicKeyEncoding: { type: 'pkcs1', format: 'der' },
15637 privateKeyEncoding: { type: 'pkcs1', format: 'der' }
15638 };
15639 const prv = await new Promise((resolve, reject) => nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => {
15640 if (err) {
15641 reject(err);
15642 } else {
15643 resolve(RSAPrivateKey.decode(der, 'der'));
15644 }
15645 }));
15646 /**
15647 * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.
15648 * @link https://tools.ietf.org/html/rfc3447#section-3.2
15649 * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
15650 */
15651 return {
15652 n: prv.modulus.toArrayLike(Uint8Array),
15653 e: prv.publicExponent.toArrayLike(Uint8Array),
15654 d: prv.privateExponent.toArrayLike(Uint8Array),
15655 // switch p and q
15656 p: prv.prime2.toArrayLike(Uint8Array),
15657 q: prv.prime1.toArrayLike(Uint8Array),
15658 // Since p and q are switched in places, we can keep u as defined by DER
15659 u: prv.coefficient.toArrayLike(Uint8Array)
15660 };
15661 }
15662
15663 // RSA keygen fallback using 40 iterations of the Miller-Rabin test
15664 // See https://stackoverflow.com/a/6330138 for justification
15665 // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
15666 let q = await randomProbablePrime(bits - (bits >> 1), e, 40);
15667 let p = await randomProbablePrime(bits >> 1, e, 40);
15668
15669 if (q.lt(p)) {
15670 [p, q] = [q, p];
15671 }
15672 const phi = p.dec().imul(q.dec());
15673 return {
15674 n: p.mul(q).toUint8Array(),
15675 e: e.toUint8Array(),
15676 d: e.modInv(phi).toUint8Array(),
15677 p: p.toUint8Array(),
15678 q: q.toUint8Array(),
15679 // dp: d.mod(p.subn(1)),
15680 // dq: d.mod(q.subn(1)),
15681 u: p.modInv(q).toUint8Array()
15682 };
15683}
15684
15685/**
15686 * Validate RSA parameters
15687 * @param {Uint8Array} n - RSA public modulus
15688 * @param {Uint8Array} e - RSA public exponent
15689 * @param {Uint8Array} d - RSA private exponent
15690 * @param {Uint8Array} p - RSA private prime p
15691 * @param {Uint8Array} q - RSA private prime q
15692 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
15693 * @returns {Boolean} Whether params are valid.
15694 * @async
15695 */
15696async function validateParams(n, e, d, p, q, u) {
15697 const BigInteger = await util.getBigInteger();
15698 n = new BigInteger(n);
15699 p = new BigInteger(p);
15700 q = new BigInteger(q);
15701
15702 // expect pq = n
15703 if (!p.mul(q).equal(n)) {
15704 return false;
15705 }
15706
15707 const two = new BigInteger(2);
15708 // expect p*u = 1 mod q
15709 u = new BigInteger(u);
15710 if (!p.mul(u).mod(q).isOne()) {
15711 return false;
15712 }
15713
15714 e = new BigInteger(e);
15715 d = new BigInteger(d);
15716 /**
15717 * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
15718 * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
15719 * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
15720 *
15721 * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
15722 */
15723 const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));
15724 const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q
15725 const rde = r.mul(d).mul(e);
15726
15727 const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);
15728 if (!areInverses) {
15729 return false;
15730 }
15731
15732 return true;
15733}
15734
15735async function bnSign(hash_algo, n, d, hashed) {
15736 const BigInteger = await util.getBigInteger();
15737 n = new BigInteger(n);
15738 const m = new BigInteger(await emsaEncode(hash_algo, hashed, n.byteLength()));
15739 d = new BigInteger(d);
15740 if (m.gte(n)) {
15741 throw new Error('Message size cannot exceed modulus size');
15742 }
15743 return m.modExp(d, n).toUint8Array('be', n.byteLength());
15744}
15745
15746async function webSign(hash_name, data, n, e, d, p, q, u) {
15747 /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
15748 * We swap them in privateToJwk, so it usually works out, but nevertheless,
15749 * not all OpenPGP keys are compatible with this requirement.
15750 * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
15751 * does if the underlying Web Crypto does so (e.g. old MS Edge 50% of the time).
15752 */
15753 const jwk = await privateToJwk(n, e, d, p, q, u);
15754 const algo = {
15755 name: "RSASSA-PKCS1-v1_5",
15756 hash: { name: hash_name }
15757 };
15758 const key = await webCrypto$5.importKey("jwk", jwk, algo, false, ["sign"]);
15759 // add hash field for ms edge support
15760 return new Uint8Array(await webCrypto$5.sign({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, data));
15761}
15762
15763async function nodeSign(hash_algo, data, n, e, d, p, q, u) {
15764 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
15765 const pBNum = new BN(p);
15766 const qBNum = new BN(q);
15767 const dBNum = new BN(d);
15768 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
15769 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
15770 const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hash_algo));
15771 sign.write(data);
15772 sign.end();
15773 const keyObject = {
15774 version: 0,
15775 modulus: new BN(n),
15776 publicExponent: new BN(e),
15777 privateExponent: new BN(d),
15778 // switch p and q
15779 prime1: new BN(q),
15780 prime2: new BN(p),
15781 // switch dp and dq
15782 exponent1: dq,
15783 exponent2: dp,
15784 coefficient: new BN(u)
15785 };
15786 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
15787 const der = RSAPrivateKey.encode(keyObject, 'der');
15788 return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
15789 }
15790 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
15791 label: 'RSA PRIVATE KEY'
15792 });
15793 return new Uint8Array(sign.sign(pem));
15794}
15795
15796async function bnVerify(hash_algo, s, n, e, hashed) {
15797 const BigInteger = await util.getBigInteger();
15798 n = new BigInteger(n);
15799 s = new BigInteger(s);
15800 e = new BigInteger(e);
15801 if (s.gte(n)) {
15802 throw new Error('Signature size cannot exceed modulus size');
15803 }
15804 const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());
15805 const EM2 = await emsaEncode(hash_algo, hashed, n.byteLength());
15806 return util.equalsUint8Array(EM1, EM2);
15807}
15808
15809async function webVerify(hash_name, data, s, n, e) {
15810 const jwk = publicToJwk(n, e);
15811 const key = await webCrypto$5.importKey("jwk", jwk, {
15812 name: "RSASSA-PKCS1-v1_5",
15813 hash: { name: hash_name }
15814 }, false, ["verify"]);
15815 // add hash field for ms edge support
15816 return webCrypto$5.verify({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, s, data);
15817}
15818
15819async function nodeVerify(hash_algo, data, s, n, e) {
15820 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
15821
15822 const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hash_algo));
15823 verify.write(data);
15824 verify.end();
15825 const keyObject = {
15826 modulus: new BN(n),
15827 publicExponent: new BN(e)
15828 };
15829 let key;
15830 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
15831 const der = RSAPublicKey.encode(keyObject, 'der');
15832 key = { key: der, format: 'der', type: 'pkcs1' };
15833 } else {
15834 key = RSAPublicKey.encode(keyObject, 'pem', {
15835 label: 'RSA PUBLIC KEY'
15836 });
15837 }
15838 try {
15839 return await verify.verify(key, s);
15840 } catch (err) {
15841 return false;
15842 }
15843}
15844
15845async function nodeEncrypt$1(data, n, e) {
15846 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
15847
15848 const keyObject = {
15849 modulus: new BN(n),
15850 publicExponent: new BN(e)
15851 };
15852 let key;
15853 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
15854 const der = RSAPublicKey.encode(keyObject, 'der');
15855 key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
15856 } else {
15857 const pem = RSAPublicKey.encode(keyObject, 'pem', {
15858 label: 'RSA PUBLIC KEY'
15859 });
15860 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
15861 }
15862 return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data));
15863}
15864
15865async function bnEncrypt(data, n, e) {
15866 const BigInteger = await util.getBigInteger();
15867 n = new BigInteger(n);
15868 data = new BigInteger(await emeEncode(data, n.byteLength()));
15869 e = new BigInteger(e);
15870 if (data.gte(n)) {
15871 throw new Error('Message size cannot exceed modulus size');
15872 }
15873 return data.modExp(e, n).toUint8Array('be', n.byteLength());
15874}
15875
15876async function nodeDecrypt$1(data, n, e, d, p, q, u) {
15877 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
15878
15879 const pBNum = new BN(p);
15880 const qBNum = new BN(q);
15881 const dBNum = new BN(d);
15882 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
15883 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
15884 const keyObject = {
15885 version: 0,
15886 modulus: new BN(n),
15887 publicExponent: new BN(e),
15888 privateExponent: new BN(d),
15889 // switch p and q
15890 prime1: new BN(q),
15891 prime2: new BN(p),
15892 // switch dp and dq
15893 exponent1: dq,
15894 exponent2: dp,
15895 coefficient: new BN(u)
15896 };
15897 let key;
15898 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
15899 const der = RSAPrivateKey.encode(keyObject, 'der');
15900 key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
15901 } else {
15902 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
15903 label: 'RSA PRIVATE KEY'
15904 });
15905 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
15906 }
15907 try {
15908 return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data));
15909 } catch (err) {
15910 throw new Error('Decryption error');
15911 }
15912}
15913
15914async function bnDecrypt(data, n, e, d, p, q, u) {
15915 const BigInteger = await util.getBigInteger();
15916 data = new BigInteger(data);
15917 n = new BigInteger(n);
15918 e = new BigInteger(e);
15919 d = new BigInteger(d);
15920 p = new BigInteger(p);
15921 q = new BigInteger(q);
15922 u = new BigInteger(u);
15923 if (data.gte(n)) {
15924 throw new Error('Data too large.');
15925 }
15926 const dq = d.mod(q.dec()); // d mod (q-1)
15927 const dp = d.mod(p.dec()); // d mod (p-1)
15928
15929 const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);
15930 const blinder = unblinder.modInv(n).modExp(e, n);
15931 data = data.mul(blinder).mod(n);
15932
15933
15934 const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p
15935 const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q
15936 const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)
15937
15938 let result = h.mul(p).add(mp); // result < n due to relations above
15939
15940 result = result.mul(unblinder).mod(n);
15941
15942
15943 return emeDecode(result.toUint8Array('be', n.byteLength()));
15944}
15945
15946/** Convert Openpgp private key params to jwk key according to
15947 * @link https://tools.ietf.org/html/rfc7517
15948 * @param {String} hash_algo
15949 * @param {Uint8Array} n
15950 * @param {Uint8Array} e
15951 * @param {Uint8Array} d
15952 * @param {Uint8Array} p
15953 * @param {Uint8Array} q
15954 * @param {Uint8Array} u
15955 */
15956async function privateToJwk(n, e, d, p, q, u) {
15957 const BigInteger = await util.getBigInteger();
15958 const pNum = new BigInteger(p);
15959 const qNum = new BigInteger(q);
15960 const dNum = new BigInteger(d);
15961
15962 let dq = dNum.mod(qNum.dec()); // d mod (q-1)
15963 let dp = dNum.mod(pNum.dec()); // d mod (p-1)
15964 dp = dp.toUint8Array();
15965 dq = dq.toUint8Array();
15966 return {
15967 kty: 'RSA',
15968 n: uint8ArrayToB64(n, true),
15969 e: uint8ArrayToB64(e, true),
15970 d: uint8ArrayToB64(d, true),
15971 // switch p and q
15972 p: uint8ArrayToB64(q, true),
15973 q: uint8ArrayToB64(p, true),
15974 // switch dp and dq
15975 dp: uint8ArrayToB64(dq, true),
15976 dq: uint8ArrayToB64(dp, true),
15977 qi: uint8ArrayToB64(u, true),
15978 ext: true
15979 };
15980}
15981
15982/** Convert Openpgp key public params to jwk key according to
15983 * @link https://tools.ietf.org/html/rfc7517
15984 * @param {String} hash_algo
15985 * @param {Uint8Array} n
15986 * @param {Uint8Array} e
15987 */
15988function publicToJwk(n, e) {
15989 return {
15990 kty: 'RSA',
15991 n: uint8ArrayToB64(n, true),
15992 e: uint8ArrayToB64(e, true),
15993 ext: true
15994 };
15995}
15996
15997var rsa = /*#__PURE__*/Object.freeze({
15998 __proto__: null,
15999 sign: sign,
16000 verify: verify,
16001 encrypt: encrypt$1,
16002 decrypt: decrypt$1,
16003 generate: generate,
16004 validateParams: validateParams
16005});
16006
16007// GPG4Browsers - An OpenPGP implementation in javascript
16008
16009/**
16010 * ElGamal Encryption function
16011 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
16012 * @param {Uint8Array} data - To be padded and encrypted
16013 * @param {Uint8Array} p
16014 * @param {Uint8Array} g
16015 * @param {Uint8Array} y
16016 * @returns {{ c1: Uint8Array, c2: Uint8Array }}
16017 * @async
16018 */
16019async function encrypt$2(data, p, g, y) {
16020 const BigInteger = await util.getBigInteger();
16021 p = new BigInteger(p);
16022 g = new BigInteger(g);
16023 y = new BigInteger(y);
16024
16025 const padded = await emeEncode(data, p.byteLength());
16026 const m = new BigInteger(padded);
16027
16028 // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
16029 // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
16030 const k = await getRandomBigInteger(new BigInteger(1), p.dec());
16031 return {
16032 c1: g.modExp(k, p).toUint8Array(),
16033 c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()
16034 };
16035}
16036
16037/**
16038 * ElGamal Encryption function
16039 * @param {Uint8Array} c1
16040 * @param {Uint8Array} c2
16041 * @param {Uint8Array} p
16042 * @param {Uint8Array} x
16043 * @returns {Uint8Array} Unpadded message.
16044 * @async
16045 */
16046async function decrypt$2(c1, c2, p, x) {
16047 const BigInteger = await util.getBigInteger();
16048 c1 = new BigInteger(c1);
16049 c2 = new BigInteger(c2);
16050 p = new BigInteger(p);
16051 x = new BigInteger(x);
16052
16053 const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);
16054 return emeDecode(padded.toUint8Array('be', p.byteLength()));
16055}
16056
16057/**
16058 * Validate ElGamal parameters
16059 * @param {Uint8Array} p - ElGamal prime
16060 * @param {Uint8Array} g - ElGamal group generator
16061 * @param {Uint8Array} y - ElGamal public key
16062 * @param {Uint8Array} x - ElGamal private exponent
16063 * @returns {Boolean} Whether params are valid.
16064 * @async
16065 */
16066async function validateParams$1(p, g, y, x) {
16067 const BigInteger = await util.getBigInteger();
16068 p = new BigInteger(p);
16069 g = new BigInteger(g);
16070 y = new BigInteger(y);
16071
16072 const one = new BigInteger(1);
16073 // Check that 1 < g < p
16074 if (g.lte(one) || g.gte(p)) {
16075 return false;
16076 }
16077
16078 // Expect p-1 to be large
16079 const pSize = new BigInteger(p.bitLength());
16080 const n1023 = new BigInteger(1023);
16081 if (pSize.lt(n1023)) {
16082 return false;
16083 }
16084
16085 /**
16086 * g should have order p-1
16087 * Check that g ** (p-1) = 1 mod p
16088 */
16089 if (!g.modExp(p.dec(), p).isOne()) {
16090 return false;
16091 }
16092
16093 /**
16094 * Since p-1 is not prime, g might have a smaller order that divides p-1
16095 * We want to make sure that the order is large enough to hinder a small subgroup attack
16096 *
16097 * We just check g**i != 1 for all i up to a threshold
16098 */
16099 let res = g;
16100 const i = new BigInteger(1);
16101 const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold
16102 while (i.lt(threshold)) {
16103 res = res.mul(g).imod(p);
16104 if (res.isOne()) {
16105 return false;
16106 }
16107 i.iinc();
16108 }
16109
16110 /**
16111 * Re-derive public key y' = g ** x mod p
16112 * Expect y == y'
16113 *
16114 * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
16115 */
16116 x = new BigInteger(x);
16117 const two = new BigInteger(2);
16118 const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1
16119 const rqx = p.dec().imul(r).iadd(x);
16120 if (!y.equal(g.modExp(rqx, p))) {
16121 return false;
16122 }
16123
16124 return true;
16125}
16126
16127var elgamal = /*#__PURE__*/Object.freeze({
16128 __proto__: null,
16129 encrypt: encrypt$2,
16130 decrypt: decrypt$2,
16131 validateParams: validateParams$1
16132});
16133
16134// OpenPGP.js - An OpenPGP implementation in javascript
16135
16136class OID {
16137 constructor(oid) {
16138 if (oid instanceof OID) {
16139 this.oid = oid.oid;
16140 } else if (util.isArray(oid) ||
16141 util.isUint8Array(oid)) {
16142 oid = new Uint8Array(oid);
16143 if (oid[0] === 0x06) { // DER encoded oid byte array
16144 if (oid[1] !== oid.length - 2) {
16145 throw new Error('Length mismatch in DER encoded oid');
16146 }
16147 oid = oid.subarray(2);
16148 }
16149 this.oid = oid;
16150 } else {
16151 this.oid = '';
16152 }
16153 }
16154
16155 /**
16156 * Method to read an OID object
16157 * @param {Uint8Array} input - Where to read the OID from
16158 * @returns {Number} Number of read bytes.
16159 */
16160 read(input) {
16161 if (input.length >= 1) {
16162 const length = input[0];
16163 if (input.length >= 1 + length) {
16164 this.oid = input.subarray(1, 1 + length);
16165 return 1 + this.oid.length;
16166 }
16167 }
16168 throw new Error('Invalid oid');
16169 }
16170
16171 /**
16172 * Serialize an OID object
16173 * @returns {Uint8Array} Array with the serialized value the OID.
16174 */
16175 write() {
16176 return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
16177 }
16178
16179 /**
16180 * Serialize an OID object as a hex string
16181 * @returns {string} String with the hex value of the OID.
16182 */
16183 toHex() {
16184 return util.uint8ArrayToHex(this.oid);
16185 }
16186
16187 /**
16188 * If a known curve object identifier, return the canonical name of the curve
16189 * @returns {string} String with the canonical name of the curve.
16190 */
16191 getName() {
16192 const hex = this.toHex();
16193 if (enums.curve[hex]) {
16194 return enums.write(enums.curve, hex);
16195 } else {
16196 throw new Error('Unknown curve object identifier.');
16197 }
16198 }
16199}
16200
16201// OpenPGP.js - An OpenPGP implementation in javascript
16202
16203function keyFromPrivate(indutnyCurve, priv) {
16204 const keyPair = indutnyCurve.keyPair({ priv: priv });
16205 return keyPair;
16206}
16207
16208function keyFromPublic(indutnyCurve, pub) {
16209 const keyPair = indutnyCurve.keyPair({ pub: pub });
16210 if (keyPair.validate().result !== true) {
16211 throw new Error('Invalid elliptic public key');
16212 }
16213 return keyPair;
16214}
16215
16216async function getIndutnyCurve(name) {
16217 if (!defaultConfig.useIndutnyElliptic) {
16218 throw new Error('This curve is only supported in the full build of OpenPGP.js');
16219 }
16220 const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; });
16221 return new elliptic.ec(name);
16222}
16223
16224// OpenPGP.js - An OpenPGP implementation in javascript
16225
16226const webCrypto$6 = util.getWebCrypto();
16227const nodeCrypto$7 = util.getNodeCrypto();
16228
16229const webCurves = {
16230 'p256': 'P-256',
16231 'p384': 'P-384',
16232 'p521': 'P-521'
16233};
16234const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : [];
16235const nodeCurves = nodeCrypto$7 ? {
16236 secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
16237 p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
16238 p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
16239 p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
16240 ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
16241 curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
16242 brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
16243 brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
16244 brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
16245} : {};
16246
16247const curves = {
16248 p256: {
16249 oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
16250 keyType: enums.publicKey.ecdsa,
16251 hash: enums.hash.sha256,
16252 cipher: enums.symmetric.aes128,
16253 node: nodeCurves.p256,
16254 web: webCurves.p256,
16255 payloadSize: 32,
16256 sharedSize: 256
16257 },
16258 p384: {
16259 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
16260 keyType: enums.publicKey.ecdsa,
16261 hash: enums.hash.sha384,
16262 cipher: enums.symmetric.aes192,
16263 node: nodeCurves.p384,
16264 web: webCurves.p384,
16265 payloadSize: 48,
16266 sharedSize: 384
16267 },
16268 p521: {
16269 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
16270 keyType: enums.publicKey.ecdsa,
16271 hash: enums.hash.sha512,
16272 cipher: enums.symmetric.aes256,
16273 node: nodeCurves.p521,
16274 web: webCurves.p521,
16275 payloadSize: 66,
16276 sharedSize: 528
16277 },
16278 secp256k1: {
16279 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
16280 keyType: enums.publicKey.ecdsa,
16281 hash: enums.hash.sha256,
16282 cipher: enums.symmetric.aes128,
16283 node: nodeCurves.secp256k1,
16284 payloadSize: 32
16285 },
16286 ed25519: {
16287 oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
16288 keyType: enums.publicKey.eddsa,
16289 hash: enums.hash.sha512,
16290 node: false, // nodeCurves.ed25519 TODO
16291 payloadSize: 32
16292 },
16293 curve25519: {
16294 oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
16295 keyType: enums.publicKey.ecdh,
16296 hash: enums.hash.sha256,
16297 cipher: enums.symmetric.aes128,
16298 node: false, // nodeCurves.curve25519 TODO
16299 payloadSize: 32
16300 },
16301 brainpoolP256r1: {
16302 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
16303 keyType: enums.publicKey.ecdsa,
16304 hash: enums.hash.sha256,
16305 cipher: enums.symmetric.aes128,
16306 node: nodeCurves.brainpoolP256r1,
16307 payloadSize: 32
16308 },
16309 brainpoolP384r1: {
16310 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
16311 keyType: enums.publicKey.ecdsa,
16312 hash: enums.hash.sha384,
16313 cipher: enums.symmetric.aes192,
16314 node: nodeCurves.brainpoolP384r1,
16315 payloadSize: 48
16316 },
16317 brainpoolP512r1: {
16318 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
16319 keyType: enums.publicKey.ecdsa,
16320 hash: enums.hash.sha512,
16321 cipher: enums.symmetric.aes256,
16322 node: nodeCurves.brainpoolP512r1,
16323 payloadSize: 64
16324 }
16325};
16326
16327class Curve {
16328 constructor(oid_or_name, params) {
16329 try {
16330 if (util.isArray(oid_or_name) ||
16331 util.isUint8Array(oid_or_name)) {
16332 // by oid byte array
16333 oid_or_name = new OID(oid_or_name);
16334 }
16335 if (oid_or_name instanceof OID) {
16336 // by curve OID
16337 oid_or_name = oid_or_name.getName();
16338 }
16339 // by curve name or oid string
16340 this.name = enums.write(enums.curve, oid_or_name);
16341 } catch (err) {
16342 throw new Error('Not valid curve');
16343 }
16344 params = params || curves[this.name];
16345
16346 this.keyType = params.keyType;
16347
16348 this.oid = params.oid;
16349 this.hash = params.hash;
16350 this.cipher = params.cipher;
16351 this.node = params.node && curves[this.name];
16352 this.web = params.web && curves[this.name];
16353 this.payloadSize = params.payloadSize;
16354 if (this.web && util.getWebCrypto()) {
16355 this.type = 'web';
16356 } else if (this.node && util.getNodeCrypto()) {
16357 this.type = 'node';
16358 } else if (this.name === 'curve25519') {
16359 this.type = 'curve25519';
16360 } else if (this.name === 'ed25519') {
16361 this.type = 'ed25519';
16362 }
16363 }
16364
16365 async genKeyPair() {
16366 let keyPair;
16367 switch (this.type) {
16368 case 'web':
16369 try {
16370 return await webGenKeyPair(this.name);
16371 } catch (err) {
16372 util.printDebugError("Browser did not support generating ec key " + err.message);
16373 break;
16374 }
16375 case 'node':
16376 return nodeGenKeyPair(this.name);
16377 case 'curve25519': {
16378 const privateKey = await getRandomBytes(32);
16379 privateKey[0] = (privateKey[0] & 127) | 64;
16380 privateKey[31] &= 248;
16381 const secretKey = privateKey.slice().reverse();
16382 keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey);
16383 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
16384 return { publicKey, privateKey };
16385 }
16386 case 'ed25519': {
16387 const privateKey = await getRandomBytes(32);
16388 const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey);
16389 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
16390 return { publicKey, privateKey };
16391 }
16392 }
16393 const indutnyCurve = await getIndutnyCurve(this.name);
16394 keyPair = await indutnyCurve.genKeyPair({
16395 entropy: util.uint8ArrayToStr(await getRandomBytes(32))
16396 });
16397 return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
16398 }
16399}
16400
16401async function generate$1(curve) {
16402 const BigInteger = await util.getBigInteger();
16403
16404 curve = new Curve(curve);
16405 const keyPair = await curve.genKeyPair();
16406 const Q = new BigInteger(keyPair.publicKey).toUint8Array();
16407 const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);
16408 return {
16409 oid: curve.oid,
16410 Q,
16411 secret,
16412 hash: curve.hash,
16413 cipher: curve.cipher
16414 };
16415}
16416
16417function getPreferredHashAlgo(oid) {
16418 return curves[enums.write(enums.curve, oid.toHex())].hash;
16419}
16420
16421/**
16422 * Validate ECDH and EcDSA parameters
16423 * Not suitable for EdDSA (different secret key format)
16424 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
16425 * @param {module:type/oid} oid - EC object identifier
16426 * @param {Uint8Array} Q - EC public point
16427 * @param {Uint8Array} d - EC secret scalar
16428 * @returns {Boolean} Whether params are valid.
16429 * @async
16430 */
16431async function validateStandardParams(algo, oid, Q, d) {
16432 const supportedCurves = {
16433 p256: true,
16434 p384: true,
16435 p521: true,
16436 secp256k1: true,
16437 curve25519: algo === enums.publicKey.ecdh,
16438 brainpoolP256r1: true,
16439 brainpoolP384r1: true,
16440 brainpoolP512r1: true
16441 };
16442
16443 // Check whether the given curve is supported
16444 const curveName = oid.getName();
16445 if (!supportedCurves[curveName]) {
16446 return false;
16447 }
16448
16449 if (curveName === 'curve25519') {
16450 d = d.slice().reverse();
16451 // Re-derive public point Q'
16452 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d);
16453
16454 Q = new Uint8Array(Q);
16455 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
16456 if (!util.equalsUint8Array(dG, Q)) {
16457 return false;
16458 }
16459
16460 return true;
16461 }
16462
16463 const curve = await getIndutnyCurve(curveName);
16464 try {
16465 // Parse Q and check that it is on the curve but not at infinity
16466 Q = keyFromPublic(curve, Q).getPublic();
16467 } catch (validationErrors) {
16468 return false;
16469 }
16470
16471 /**
16472 * Re-derive public point Q' = dG from private key
16473 * Expect Q == Q'
16474 */
16475 const dG = keyFromPrivate(curve, d).getPublic();
16476 if (!dG.eq(Q)) {
16477 return false;
16478 }
16479
16480 return true;
16481}
16482
16483//////////////////////////
16484// //
16485// Helper functions //
16486// //
16487//////////////////////////
16488
16489
16490async function webGenKeyPair(name) {
16491 // Note: keys generated with ECDSA and ECDH are structurally equivalent
16492 const webCryptoKey = await webCrypto$6.generateKey({ name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"]);
16493
16494 const privateKey = await webCrypto$6.exportKey("jwk", webCryptoKey.privateKey);
16495 const publicKey = await webCrypto$6.exportKey("jwk", webCryptoKey.publicKey);
16496
16497 return {
16498 publicKey: jwkToRawPublic(publicKey),
16499 privateKey: b64ToUint8Array(privateKey.d)
16500 };
16501}
16502
16503async function nodeGenKeyPair(name) {
16504 // Note: ECDSA and ECDH key generation is structurally equivalent
16505 const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]);
16506 await ecdh.generateKeys();
16507 return {
16508 publicKey: new Uint8Array(ecdh.getPublicKey()),
16509 privateKey: new Uint8Array(ecdh.getPrivateKey())
16510 };
16511}
16512
16513//////////////////////////
16514// //
16515// Helper functions //
16516// //
16517//////////////////////////
16518
16519/**
16520 * @param {JsonWebKey} jwk - key for conversion
16521 *
16522 * @returns {Uint8Array} Raw public key.
16523 */
16524function jwkToRawPublic(jwk) {
16525 const bufX = b64ToUint8Array(jwk.x);
16526 const bufY = b64ToUint8Array(jwk.y);
16527 const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
16528 publicKey[0] = 0x04;
16529 publicKey.set(bufX, 1);
16530 publicKey.set(bufY, bufX.length + 1);
16531 return publicKey;
16532}
16533
16534/**
16535 * @param {Integer} payloadSize - ec payload size
16536 * @param {String} name - curve name
16537 * @param {Uint8Array} publicKey - public key
16538 *
16539 * @returns {JsonWebKey} Public key in jwk format.
16540 */
16541function rawPublicToJwk(payloadSize, name, publicKey) {
16542 const len = payloadSize;
16543 const bufX = publicKey.slice(1, len + 1);
16544 const bufY = publicKey.slice(len + 1, len * 2 + 1);
16545 // https://www.rfc-editor.org/rfc/rfc7518.txt
16546 const jwk = {
16547 kty: "EC",
16548 crv: name,
16549 x: uint8ArrayToB64(bufX, true),
16550 y: uint8ArrayToB64(bufY, true),
16551 ext: true
16552 };
16553 return jwk;
16554}
16555
16556/**
16557 * @param {Integer} payloadSize - ec payload size
16558 * @param {String} name - curve name
16559 * @param {Uint8Array} publicKey - public key
16560 * @param {Uint8Array} privateKey - private key
16561 *
16562 * @returns {JsonWebKey} Private key in jwk format.
16563 */
16564function privateToJwk$1(payloadSize, name, publicKey, privateKey) {
16565 const jwk = rawPublicToJwk(payloadSize, name, publicKey);
16566 jwk.d = uint8ArrayToB64(privateKey, true);
16567 return jwk;
16568}
16569
16570const webCrypto$7 = util.getWebCrypto();
16571const nodeCrypto$8 = util.getNodeCrypto();
16572
16573/**
16574 * Sign a message using the provided key
16575 * @param {module:type/oid} oid - Elliptic curve object identifier
16576 * @param {module:enums.hash} hash_algo - Hash algorithm used to sign
16577 * @param {Uint8Array} message - Message to sign
16578 * @param {Uint8Array} publicKey - Public key
16579 * @param {Uint8Array} privateKey - Private key used to sign the message
16580 * @param {Uint8Array} hashed - The hashed message
16581 * @returns {{r: Uint8Array,
16582 * s: Uint8Array}} Signature of the message
16583 * @async
16584 */
16585async function sign$1(oid, hash_algo, message, publicKey, privateKey, hashed) {
16586 const curve = new Curve(oid);
16587 if (message && !util.isStream(message)) {
16588 const keyPair = { publicKey, privateKey };
16589 switch (curve.type) {
16590 case 'web': {
16591 // If browser doesn't support a curve, we'll catch it
16592 try {
16593 // Need to await to make sure browser succeeds
16594 return await webSign$1(curve, hash_algo, message, keyPair);
16595 } catch (err) {
16596 // We do not fallback if the error is related to key integrity
16597 // Unfortunaley Safari does not support p521 and throws a DataError when using it
16598 // So we need to always fallback for that curve
16599 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
16600 throw err;
16601 }
16602 util.printDebugError("Browser did not support signing: " + err.message);
16603 }
16604 break;
16605 }
16606 case 'node': {
16607 const signature = await nodeSign$1(curve, hash_algo, message, keyPair);
16608 return {
16609 r: signature.r.toArrayLike(Uint8Array),
16610 s: signature.s.toArrayLike(Uint8Array)
16611 };
16612 }
16613 }
16614 }
16615 return ellipticSign(curve, hashed, privateKey);
16616}
16617
16618/**
16619 * Verifies if a signature is valid for a message
16620 * @param {module:type/oid} oid - Elliptic curve object identifier
16621 * @param {module:enums.hash} hash_algo - Hash algorithm used in the signature
16622 * @param {{r: Uint8Array,
16623 s: Uint8Array}} signature Signature to verify
16624 * @param {Uint8Array} message - Message to verify
16625 * @param {Uint8Array} publicKey - Public key used to verify the message
16626 * @param {Uint8Array} hashed - The hashed message
16627 * @returns {Boolean}
16628 * @async
16629 */
16630async function verify$1(oid, hash_algo, signature, message, publicKey, hashed) {
16631 const curve = new Curve(oid);
16632 if (message && !util.isStream(message)) {
16633 switch (curve.type) {
16634 case 'web':
16635 try {
16636 // Need to await to make sure browser succeeds
16637 return await webVerify$1(curve, hash_algo, signature, message, publicKey);
16638 } catch (err) {
16639 // We do not fallback if the error is related to key integrity
16640 // Unfortunately Safari does not support p521 and throws a DataError when using it
16641 // So we need to always fallback for that curve
16642 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
16643 throw err;
16644 }
16645 util.printDebugError("Browser did not support verifying: " + err.message);
16646 }
16647 break;
16648 case 'node':
16649 return nodeVerify$1(curve, hash_algo, signature, message, publicKey);
16650 }
16651 }
16652 const digest = (typeof hash_algo === 'undefined') ? message : hashed;
16653 return ellipticVerify(curve, signature, digest, publicKey);
16654}
16655
16656/**
16657 * Validate EcDSA parameters
16658 * @param {module:type/oid} oid - Elliptic curve object identifier
16659 * @param {Uint8Array} Q - EcDSA public point
16660 * @param {Uint8Array} d - EcDSA secret scalar
16661 * @returns {Boolean} Whether params are valid.
16662 * @async
16663 */
16664async function validateParams$2(oid, Q, d) {
16665 const curve = new Curve(oid);
16666 // Reject curves x25519 and ed25519
16667 if (curve.keyType !== enums.publicKey.ecdsa) {
16668 return false;
16669 }
16670
16671 // To speed up the validation, we try to use node- or webcrypto when available
16672 // and sign + verify a random message
16673 switch (curve.type) {
16674 case 'web':
16675 case 'node': {
16676 const message = await getRandomBytes(8);
16677 const hashAlgo = enums.hash.sha256;
16678 const hashed = await hash.digest(hashAlgo, message);
16679 try {
16680 const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed);
16681 return await verify$1(oid, hashAlgo, signature, message, Q, hashed);
16682 } catch (err) {
16683 return false;
16684 }
16685 }
16686 default:
16687 return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
16688 }
16689}
16690
16691
16692//////////////////////////
16693// //
16694// Helper functions //
16695// //
16696//////////////////////////
16697
16698async function ellipticSign(curve, hashed, privateKey) {
16699 const indutnyCurve = await getIndutnyCurve(curve.name);
16700 const key = keyFromPrivate(indutnyCurve, privateKey);
16701 const signature = key.sign(hashed);
16702 return {
16703 r: signature.r.toArrayLike(Uint8Array),
16704 s: signature.s.toArrayLike(Uint8Array)
16705 };
16706}
16707
16708async function ellipticVerify(curve, signature, digest, publicKey) {
16709 const indutnyCurve = await getIndutnyCurve(curve.name);
16710 const key = keyFromPublic(indutnyCurve, publicKey);
16711 return key.verify(digest, signature);
16712}
16713
16714async function webSign$1(curve, hash_algo, message, keyPair) {
16715 const len = curve.payloadSize;
16716 const jwk = privateToJwk$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
16717 const key = await webCrypto$7.importKey(
16718 "jwk",
16719 jwk,
16720 {
16721 "name": "ECDSA",
16722 "namedCurve": webCurves[curve.name],
16723 "hash": { name: enums.read(enums.webHash, curve.hash) }
16724 },
16725 false,
16726 ["sign"]
16727 );
16728
16729 const signature = new Uint8Array(await webCrypto$7.sign(
16730 {
16731 "name": 'ECDSA',
16732 "namedCurve": webCurves[curve.name],
16733 "hash": { name: enums.read(enums.webHash, hash_algo) }
16734 },
16735 key,
16736 message
16737 ));
16738
16739 return {
16740 r: signature.slice(0, len),
16741 s: signature.slice(len, len << 1)
16742 };
16743}
16744
16745async function webVerify$1(curve, hash_algo, { r, s }, message, publicKey) {
16746 const jwk = rawPublicToJwk(curve.payloadSize, webCurves[curve.name], publicKey);
16747 const key = await webCrypto$7.importKey(
16748 "jwk",
16749 jwk,
16750 {
16751 "name": "ECDSA",
16752 "namedCurve": webCurves[curve.name],
16753 "hash": { name: enums.read(enums.webHash, curve.hash) }
16754 },
16755 false,
16756 ["verify"]
16757 );
16758
16759 const signature = util.concatUint8Array([r, s]).buffer;
16760
16761 return webCrypto$7.verify(
16762 {
16763 "name": 'ECDSA',
16764 "namedCurve": webCurves[curve.name],
16765 "hash": { name: enums.read(enums.webHash, hash_algo) }
16766 },
16767 key,
16768 signature,
16769 message
16770 );
16771}
16772
16773async function nodeSign$1(curve, hash_algo, message, keyPair) {
16774 const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hash_algo));
16775 sign.write(message);
16776 sign.end();
16777 const key = ECPrivateKey.encode({
16778 version: 1,
16779 parameters: curve.oid,
16780 privateKey: Array.from(keyPair.privateKey),
16781 publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
16782 }, 'pem', {
16783 label: 'EC PRIVATE KEY'
16784 });
16785
16786 return ECDSASignature.decode(sign.sign(key), 'der');
16787}
16788
16789async function nodeVerify$1(curve, hash_algo, { r, s }, message, publicKey) {
16790 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
16791
16792 const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hash_algo));
16793 verify.write(message);
16794 verify.end();
16795 const key = SubjectPublicKeyInfo.encode({
16796 algorithm: {
16797 algorithm: [1, 2, 840, 10045, 2, 1],
16798 parameters: curve.oid
16799 },
16800 subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
16801 }, 'pem', {
16802 label: 'PUBLIC KEY'
16803 });
16804 const signature = ECDSASignature.encode({
16805 r: new BN(r), s: new BN(s)
16806 }, 'der');
16807
16808 try {
16809 return verify.verify(key, signature);
16810 } catch (err) {
16811 return false;
16812 }
16813}
16814
16815// Originally written by Owen Smith https://github.com/omsmith
16816// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
16817
16818/* eslint-disable no-invalid-this */
16819
16820const asn1$1 = nodeCrypto$8 ? asn1__default['default'] : undefined;
16821
16822const ECDSASignature = nodeCrypto$8 ?
16823 asn1$1.define('ECDSASignature', function() {
16824 this.seq().obj(
16825 this.key('r').int(),
16826 this.key('s').int()
16827 );
16828 }) : undefined;
16829
16830const ECPrivateKey = nodeCrypto$8 ?
16831 asn1$1.define('ECPrivateKey', function() {
16832 this.seq().obj(
16833 this.key('version').int(),
16834 this.key('privateKey').octstr(),
16835 this.key('parameters').explicit(0).optional().any(),
16836 this.key('publicKey').explicit(1).optional().bitstr()
16837 );
16838 }) : undefined;
16839
16840const AlgorithmIdentifier = nodeCrypto$8 ?
16841 asn1$1.define('AlgorithmIdentifier', function() {
16842 this.seq().obj(
16843 this.key('algorithm').objid(),
16844 this.key('parameters').optional().any()
16845 );
16846 }) : undefined;
16847
16848const SubjectPublicKeyInfo = nodeCrypto$8 ?
16849 asn1$1.define('SubjectPublicKeyInfo', function() {
16850 this.seq().obj(
16851 this.key('algorithm').use(AlgorithmIdentifier),
16852 this.key('subjectPublicKey').bitstr()
16853 );
16854 }) : undefined;
16855
16856var ecdsa = /*#__PURE__*/Object.freeze({
16857 __proto__: null,
16858 sign: sign$1,
16859 verify: verify$1,
16860 validateParams: validateParams$2
16861});
16862
16863// OpenPGP.js - An OpenPGP implementation in javascript
16864
16865naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
16866
16867/**
16868 * Sign a message using the provided key
16869 * @param {module:type/oid} oid - Elliptic curve object identifier
16870 * @param {module:enums.hash} hash_algo - Hash algorithm used to sign
16871 * @param {Uint8Array} message - Message to sign
16872 * @param {Uint8Array} publicKey - Public key
16873 * @param {Uint8Array} privateKey - Private key used to sign the message
16874 * @param {Uint8Array} hashed - The hashed message
16875 * @returns {{r: Uint8Array,
16876 * s: Uint8Array}} Signature of the message
16877 * @async
16878 */
16879async function sign$2(oid, hash_algo, message, publicKey, privateKey, hashed) {
16880 const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);
16881 const signature = naclFastLight.sign.detached(hashed, secretKey);
16882 // EdDSA signature params are returned in little-endian format
16883 return {
16884 r: signature.subarray(0, 32),
16885 s: signature.subarray(32)
16886 };
16887}
16888
16889/**
16890 * Verifies if a signature is valid for a message
16891 * @param {module:type/oid} oid - Elliptic curve object identifier
16892 * @param {module:enums.hash} hash_algo - Hash algorithm used in the signature
16893 * @param {{r: Uint8Array,
16894 s: Uint8Array}} signature Signature to verify the message
16895 * @param {Uint8Array} m - Message to verify
16896 * @param {Uint8Array} publicKey - Public key used to verify the message
16897 * @param {Uint8Array} hashed - The hashed message
16898 * @returns {Boolean}
16899 * @async
16900 */
16901async function verify$2(oid, hash_algo, { r, s }, m, publicKey, hashed) {
16902 const signature = util.concatUint8Array([r, s]);
16903 return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1));
16904}
16905/**
16906 * Validate EdDSA parameters
16907 * @param {module:type/oid} oid - Elliptic curve object identifier
16908 * @param {Uint8Array} Q - EdDSA public point
16909 * @param {Uint8Array} k - EdDSA secret seed
16910 * @returns {Boolean} Whether params are valid.
16911 * @async
16912 */
16913async function validateParams$3(oid, Q, k) {
16914 // Check whether the given curve is supported
16915 if (oid.getName() !== 'ed25519') {
16916 return false;
16917 }
16918
16919 /**
16920 * Derive public point Q' = dG from private key
16921 * and expect Q == Q'
16922 */
16923 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k);
16924 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
16925 return util.equalsUint8Array(Q, dG);
16926}
16927
16928var eddsa = /*#__PURE__*/Object.freeze({
16929 __proto__: null,
16930 sign: sign$2,
16931 verify: verify$2,
16932 validateParams: validateParams$3
16933});
16934
16935// OpenPGP.js - An OpenPGP implementation in javascript
16936
16937/**
16938 * AES key wrap
16939 * @function
16940 * @param {Uint8Array} key
16941 * @param {Uint8Array} data
16942 * @returns {Uint8Array}
16943 */
16944function wrap(key, data) {
16945 const aes = new cipher["aes" + (key.length * 8)](key);
16946 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
16947 const P = unpack(data);
16948 let A = IV;
16949 const R = P;
16950 const n = P.length / 2;
16951 const t = new Uint32Array([0, 0]);
16952 let B = new Uint32Array(4);
16953 for (let j = 0; j <= 5; ++j) {
16954 for (let i = 0; i < n; ++i) {
16955 t[1] = n * j + (1 + i);
16956 // B = A
16957 B[0] = A[0];
16958 B[1] = A[1];
16959 // B = A || R[i]
16960 B[2] = R[2 * i];
16961 B[3] = R[2 * i + 1];
16962 // B = AES(K, B)
16963 B = unpack(aes.encrypt(pack(B)));
16964 // A = MSB(64, B) ^ t
16965 A = B.subarray(0, 2);
16966 A[0] ^= t[0];
16967 A[1] ^= t[1];
16968 // R[i] = LSB(64, B)
16969 R[2 * i] = B[2];
16970 R[2 * i + 1] = B[3];
16971 }
16972 }
16973 return pack(A, R);
16974}
16975
16976/**
16977 * AES key unwrap
16978 * @function
16979 * @param {String} key
16980 * @param {String} data
16981 * @returns {Uint8Array}
16982 * @throws {Error}
16983 */
16984function unwrap(key, data) {
16985 const aes = new cipher["aes" + (key.length * 8)](key);
16986 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
16987 const C = unpack(data);
16988 let A = C.subarray(0, 2);
16989 const R = C.subarray(2);
16990 const n = C.length / 2 - 1;
16991 const t = new Uint32Array([0, 0]);
16992 let B = new Uint32Array(4);
16993 for (let j = 5; j >= 0; --j) {
16994 for (let i = n - 1; i >= 0; --i) {
16995 t[1] = n * j + (i + 1);
16996 // B = A ^ t
16997 B[0] = A[0] ^ t[0];
16998 B[1] = A[1] ^ t[1];
16999 // B = (A ^ t) || R[i]
17000 B[2] = R[2 * i];
17001 B[3] = R[2 * i + 1];
17002 // B = AES-1(B)
17003 B = unpack(aes.decrypt(pack(B)));
17004 // A = MSB(64, B)
17005 A = B.subarray(0, 2);
17006 // R[i] = LSB(64, B)
17007 R[2 * i] = B[2];
17008 R[2 * i + 1] = B[3];
17009 }
17010 }
17011 if (A[0] === IV[0] && A[1] === IV[1]) {
17012 return pack(R);
17013 }
17014 throw new Error("Key Data Integrity failed");
17015}
17016
17017function createArrayBuffer(data) {
17018 if (util.isString(data)) {
17019 const { length } = data;
17020 const buffer = new ArrayBuffer(length);
17021 const view = new Uint8Array(buffer);
17022 for (let j = 0; j < length; ++j) {
17023 view[j] = data.charCodeAt(j);
17024 }
17025 return buffer;
17026 }
17027 return new Uint8Array(data).buffer;
17028}
17029
17030function unpack(data) {
17031 const { length } = data;
17032 const buffer = createArrayBuffer(data);
17033 const view = new DataView(buffer);
17034 const arr = new Uint32Array(length / 4);
17035 for (let i = 0; i < length / 4; ++i) {
17036 arr[i] = view.getUint32(4 * i);
17037 }
17038 return arr;
17039}
17040
17041function pack() {
17042 let length = 0;
17043 for (let k = 0; k < arguments.length; ++k) {
17044 length += 4 * arguments[k].length;
17045 }
17046 const buffer = new ArrayBuffer(length);
17047 const view = new DataView(buffer);
17048 let offset = 0;
17049 for (let i = 0; i < arguments.length; ++i) {
17050 for (let j = 0; j < arguments[i].length; ++j) {
17051 view.setUint32(offset + 4 * j, arguments[i][j]);
17052 }
17053 offset += 4 * arguments[i].length;
17054 }
17055 return new Uint8Array(buffer);
17056}
17057
17058var aes_kw = /*#__PURE__*/Object.freeze({
17059 __proto__: null,
17060 wrap: wrap,
17061 unwrap: unwrap
17062});
17063
17064// OpenPGP.js - An OpenPGP implementation in javascript
17065
17066/**
17067 * @fileoverview Functions to add and remove PKCS5 padding
17068 * @see PublicKeyEncryptedSessionKeyPacket
17069 * @module crypto/pkcs5
17070 * @private
17071 */
17072
17073/**
17074 * Add pkcs5 padding to a message
17075 * @param {Uint8Array} message - message to pad
17076 * @returns {Uint8Array} Padded message.
17077 */
17078function encode$1(message) {
17079 const c = 8 - (message.length % 8);
17080 const padded = new Uint8Array(message.length + c).fill(c);
17081 padded.set(message);
17082 return padded;
17083}
17084
17085/**
17086 * Remove pkcs5 padding from a message
17087 * @param {Uint8Array} message - message to remove padding from
17088 * @returns {Uint8Array} Message without padding.
17089 */
17090function decode$1(message) {
17091 const len = message.length;
17092 if (len > 0) {
17093 const c = message[len - 1];
17094 if (c >= 1) {
17095 const provided = message.subarray(len - c);
17096 const computed = new Uint8Array(c).fill(c);
17097 if (util.equalsUint8Array(provided, computed)) {
17098 return message.subarray(0, len - c);
17099 }
17100 }
17101 }
17102 throw new Error('Invalid padding');
17103}
17104
17105var pkcs5 = /*#__PURE__*/Object.freeze({
17106 __proto__: null,
17107 encode: encode$1,
17108 decode: decode$1
17109});
17110
17111// OpenPGP.js - An OpenPGP implementation in javascript
17112
17113const webCrypto$8 = util.getWebCrypto();
17114const nodeCrypto$9 = util.getNodeCrypto();
17115
17116/**
17117 * Validate ECDH parameters
17118 * @param {module:type/oid} oid - Elliptic curve object identifier
17119 * @param {Uint8Array} Q - ECDH public point
17120 * @param {Uint8Array} d - ECDH secret scalar
17121 * @returns {Boolean} Whether params are valid.
17122 * @async
17123 */
17124async function validateParams$4(oid, Q, d) {
17125 return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
17126}
17127
17128// Build Param for ECDH algorithm (RFC 6637)
17129function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
17130 return util.concatUint8Array([
17131 oid.write(),
17132 new Uint8Array([public_algo]),
17133 kdfParams.write(),
17134 util.strToUint8Array("Anonymous Sender "),
17135 fingerprint.subarray(0, 20)
17136 ]);
17137}
17138
17139// Key Derivation Function (RFC 6637)
17140async function kdf(hash_algo, X, length, param, stripLeading = false, stripTrailing = false) {
17141 // Note: X is little endian for Curve25519, big-endian for all others.
17142 // This is not ideal, but the RFC's are unclear
17143 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
17144 let i;
17145 if (stripLeading) {
17146 // Work around old go crypto bug
17147 for (i = 0; i < X.length && X[i] === 0; i++);
17148 X = X.subarray(i);
17149 }
17150 if (stripTrailing) {
17151 // Work around old OpenPGP.js bug
17152 for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
17153 X = X.subarray(0, i + 1);
17154 }
17155 const digest = await hash.digest(hash_algo, util.concatUint8Array([
17156 new Uint8Array([0, 0, 0, 1]),
17157 X,
17158 param
17159 ]));
17160 return digest.subarray(0, length);
17161}
17162
17163/**
17164 * Generate ECDHE ephemeral key and secret from public key
17165 *
17166 * @param {Curve} curve - Elliptic curve object
17167 * @param {Uint8Array} Q - Recipient public key
17168 * @returns {{publicKey: Uint8Array, sharedKey: Uint8Array}}
17169 * @async
17170 */
17171async function genPublicEphemeralKey(curve, Q) {
17172 switch (curve.type) {
17173 case 'curve25519': {
17174 const d = await getRandomBytes(32);
17175 const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);
17176 let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey);
17177 publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
17178 return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
17179 }
17180 case 'web':
17181 if (curve.web && util.getWebCrypto()) {
17182 try {
17183 return await webPublicEphemeralKey(curve, Q);
17184 } catch (err) {
17185 util.printDebugError(err);
17186 }
17187 }
17188 break;
17189 case 'node':
17190 return nodePublicEphemeralKey(curve, Q);
17191 }
17192 return ellipticPublicEphemeralKey(curve, Q);
17193}
17194
17195/**
17196 * Encrypt and wrap a session key
17197 *
17198 * @param {module:type/oid} oid - Elliptic curve object identifier
17199 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
17200 * @param {Uint8Array} data - Unpadded session key data
17201 * @param {Uint8Array} Q - Recipient public key
17202 * @param {Uint8Array} fingerprint - Recipient fingerprint
17203 * @returns {{publicKey: Uint8Array, wrappedKey: Uint8Array}}
17204 * @async
17205 */
17206async function encrypt$3(oid, kdfParams, data, Q, fingerprint) {
17207 const m = encode$1(data);
17208
17209 const curve = new Curve(oid);
17210 const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
17211 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
17212 const cipher_algo = enums.read(enums.symmetric, kdfParams.cipher);
17213 const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipher_algo].keySize, param);
17214 const wrappedKey = wrap(Z, m);
17215 return { publicKey, wrappedKey };
17216}
17217
17218/**
17219 * Generate ECDHE secret from private key and public part of ephemeral key
17220 *
17221 * @param {Curve} curve - Elliptic curve object
17222 * @param {Uint8Array} V - Public part of ephemeral key
17223 * @param {Uint8Array} Q - Recipient public key
17224 * @param {Uint8Array} d - Recipient private key
17225 * @returns {{secretKey: Uint8Array, sharedKey: Uint8Array}}
17226 * @async
17227 */
17228async function genPrivateEphemeralKey(curve, V, Q, d) {
17229 if (d.length !== curve.payloadSize) {
17230 const privateKey = new Uint8Array(curve.payloadSize);
17231 privateKey.set(d, curve.payloadSize - d.length);
17232 d = privateKey;
17233 }
17234 switch (curve.type) {
17235 case 'curve25519': {
17236 const secretKey = d.slice().reverse();
17237 const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1));
17238 return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
17239 }
17240 case 'web':
17241 if (curve.web && util.getWebCrypto()) {
17242 try {
17243 return await webPrivateEphemeralKey(curve, V, Q, d);
17244 } catch (err) {
17245 util.printDebugError(err);
17246 }
17247 }
17248 break;
17249 case 'node':
17250 return nodePrivateEphemeralKey(curve, V, d);
17251 }
17252 return ellipticPrivateEphemeralKey(curve, V, d);
17253}
17254
17255/**
17256 * Decrypt and unwrap the value derived from session key
17257 *
17258 * @param {module:type/oid} oid - Elliptic curve object identifier
17259 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
17260 * @param {Uint8Array} V - Public part of ephemeral key
17261 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
17262 * @param {Uint8Array} Q - Recipient public key
17263 * @param {Uint8Array} d - Recipient private key
17264 * @param {Uint8Array} fingerprint - Recipient fingerprint
17265 * @returns {Uint8Array} Value derived from session key.
17266 * @async
17267 */
17268async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) {
17269 const curve = new Curve(oid);
17270 const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
17271 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
17272 const cipher_algo = enums.read(enums.symmetric, kdfParams.cipher);
17273 let err;
17274 for (let i = 0; i < 3; i++) {
17275 try {
17276 // Work around old go crypto bug and old OpenPGP.js bug, respectively.
17277 const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipher_algo].keySize, param, i === 1, i === 2);
17278 return decode$1(unwrap(Z, C));
17279 } catch (e) {
17280 err = e;
17281 }
17282 }
17283 throw err;
17284}
17285
17286/**
17287 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
17288 *
17289 * @param {Curve} curve - Elliptic curve object
17290 * @param {Uint8Array} V - Public part of ephemeral key
17291 * @param {Uint8Array} Q - Recipient public key
17292 * @param {Uint8Array} d - Recipient private key
17293 * @returns {{secretKey: Uint8Array, sharedKey: Uint8Array}}
17294 * @async
17295 */
17296async function webPrivateEphemeralKey(curve, V, Q, d) {
17297 const recipient = privateToJwk$1(curve.payloadSize, curve.web.web, Q, d);
17298 let privateKey = webCrypto$8.importKey(
17299 "jwk",
17300 recipient,
17301 {
17302 name: "ECDH",
17303 namedCurve: curve.web.web
17304 },
17305 true,
17306 ["deriveKey", "deriveBits"]
17307 );
17308 const jwk = rawPublicToJwk(curve.payloadSize, curve.web.web, V);
17309 let sender = webCrypto$8.importKey(
17310 "jwk",
17311 jwk,
17312 {
17313 name: "ECDH",
17314 namedCurve: curve.web.web
17315 },
17316 true,
17317 []
17318 );
17319 [privateKey, sender] = await Promise.all([privateKey, sender]);
17320 let S = webCrypto$8.deriveBits(
17321 {
17322 name: "ECDH",
17323 namedCurve: curve.web.web,
17324 public: sender
17325 },
17326 privateKey,
17327 curve.web.sharedSize
17328 );
17329 let secret = webCrypto$8.exportKey(
17330 "jwk",
17331 privateKey
17332 );
17333 [S, secret] = await Promise.all([S, secret]);
17334 const sharedKey = new Uint8Array(S);
17335 const secretKey = b64ToUint8Array(secret.d);
17336 return { secretKey, sharedKey };
17337}
17338
17339/**
17340 * Generate ECDHE ephemeral key and secret from public key using webCrypto
17341 *
17342 * @param {Curve} curve - Elliptic curve object
17343 * @param {Uint8Array} Q - Recipient public key
17344 * @returns {{publicKey: Uint8Array, sharedKey: Uint8Array}}
17345 * @async
17346 */
17347async function webPublicEphemeralKey(curve, Q) {
17348 const jwk = rawPublicToJwk(curve.payloadSize, curve.web.web, Q);
17349 let keyPair = webCrypto$8.generateKey(
17350 {
17351 name: "ECDH",
17352 namedCurve: curve.web.web
17353 },
17354 true,
17355 ["deriveKey", "deriveBits"]
17356 );
17357 let recipient = webCrypto$8.importKey(
17358 "jwk",
17359 jwk,
17360 {
17361 name: "ECDH",
17362 namedCurve: curve.web.web
17363 },
17364 false,
17365 []
17366 );
17367 [keyPair, recipient] = await Promise.all([keyPair, recipient]);
17368 let s = webCrypto$8.deriveBits(
17369 {
17370 name: "ECDH",
17371 namedCurve: curve.web.web,
17372 public: recipient
17373 },
17374 keyPair.privateKey,
17375 curve.web.sharedSize
17376 );
17377 let p = webCrypto$8.exportKey(
17378 "jwk",
17379 keyPair.publicKey
17380 );
17381 [s, p] = await Promise.all([s, p]);
17382 const sharedKey = new Uint8Array(s);
17383 const publicKey = new Uint8Array(jwkToRawPublic(p));
17384 return { publicKey, sharedKey };
17385}
17386
17387/**
17388 * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
17389 *
17390 * @param {Curve} curve - Elliptic curve object
17391 * @param {Uint8Array} V - Public part of ephemeral key
17392 * @param {Uint8Array} d - Recipient private key
17393 * @returns {{secretKey: Uint8Array, sharedKey: Uint8Array}}
17394 * @async
17395 */
17396async function ellipticPrivateEphemeralKey(curve, V, d) {
17397 const indutnyCurve = await getIndutnyCurve(curve.name);
17398 V = keyFromPublic(indutnyCurve, V);
17399 d = keyFromPrivate(indutnyCurve, d);
17400 const secretKey = new Uint8Array(d.getPrivate());
17401 const S = d.derive(V.getPublic());
17402 const len = indutnyCurve.curve.p.byteLength();
17403 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
17404 return { secretKey, sharedKey };
17405}
17406
17407/**
17408 * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
17409 *
17410 * @param {Curve} curve - Elliptic curve object
17411 * @param {Uint8Array} Q - Recipient public key
17412 * @returns {{publicKey: Uint8Array, sharedKey: Uint8Array}}
17413 * @async
17414 */
17415async function ellipticPublicEphemeralKey(curve, Q) {
17416 const indutnyCurve = await getIndutnyCurve(curve.name);
17417 const v = await curve.genKeyPair();
17418 Q = keyFromPublic(indutnyCurve, Q);
17419 const V = keyFromPrivate(indutnyCurve, v.privateKey);
17420 const publicKey = v.publicKey;
17421 const S = V.derive(Q.getPublic());
17422 const len = indutnyCurve.curve.p.byteLength();
17423 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
17424 return { publicKey, sharedKey };
17425}
17426
17427/**
17428 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
17429 *
17430 * @param {Curve} curve - Elliptic curve object
17431 * @param {Uint8Array} V - Public part of ephemeral key
17432 * @param {Uint8Array} d - Recipient private key
17433 * @returns {{secretKey: Uint8Array, sharedKey: Uint8Array}}
17434 * @async
17435 */
17436async function nodePrivateEphemeralKey(curve, V, d) {
17437 const recipient = nodeCrypto$9.createECDH(curve.node.node);
17438 recipient.setPrivateKey(d);
17439 const sharedKey = new Uint8Array(recipient.computeSecret(V));
17440 const secretKey = new Uint8Array(recipient.getPrivateKey());
17441 return { secretKey, sharedKey };
17442}
17443
17444/**
17445 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
17446 *
17447 * @param {Curve} curve - Elliptic curve object
17448 * @param {Uint8Array} Q - Recipient public key
17449 * @returns {{publicKey: Uint8Array, sharedKey: Uint8Array}}
17450 * @async
17451 */
17452async function nodePublicEphemeralKey(curve, Q) {
17453 const sender = nodeCrypto$9.createECDH(curve.node.node);
17454 sender.generateKeys();
17455 const sharedKey = new Uint8Array(sender.computeSecret(Q));
17456 const publicKey = new Uint8Array(sender.getPublicKey());
17457 return { publicKey, sharedKey };
17458}
17459
17460var ecdh = /*#__PURE__*/Object.freeze({
17461 __proto__: null,
17462 validateParams: validateParams$4,
17463 encrypt: encrypt$3,
17464 decrypt: decrypt$3
17465});
17466
17467// OpenPGP.js - An OpenPGP implementation in javascript
17468
17469var elliptic = /*#__PURE__*/Object.freeze({
17470 __proto__: null,
17471 Curve: Curve,
17472 ecdh: ecdh,
17473 ecdsa: ecdsa,
17474 eddsa: eddsa,
17475 generate: generate$1,
17476 getPreferredHashAlgo: getPreferredHashAlgo
17477});
17478
17479// GPG4Browsers - An OpenPGP implementation in javascript
17480
17481/*
17482 TODO regarding the hash function, read:
17483 https://tools.ietf.org/html/rfc4880#section-13.6
17484 https://tools.ietf.org/html/rfc4880#section-14
17485*/
17486
17487/**
17488 * DSA Sign function
17489 * @param {Integer} hash_algo
17490 * @param {Uint8Array} hashed
17491 * @param {Uint8Array} g
17492 * @param {Uint8Array} p
17493 * @param {Uint8Array} q
17494 * @param {Uint8Array} x
17495 * @returns {{ r: Uint8Array, s: Uint8Array }}
17496 * @async
17497 */
17498async function sign$3(hash_algo, hashed, g, p, q, x) {
17499 const BigInteger = await util.getBigInteger();
17500 const one = new BigInteger(1);
17501 p = new BigInteger(p);
17502 q = new BigInteger(q);
17503 g = new BigInteger(g);
17504 x = new BigInteger(x);
17505
17506 let k;
17507 let r;
17508 let s;
17509 let t;
17510 g = g.mod(p);
17511 x = x.mod(q);
17512 // If the output size of the chosen hash is larger than the number of
17513 // bits of q, the hash result is truncated to fit by taking the number
17514 // of leftmost bits equal to the number of bits of q. This (possibly
17515 // truncated) hash function result is treated as a number and used
17516 // directly in the DSA signature algorithm.
17517 const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);
17518 // FIPS-186-4, section 4.6:
17519 // The values of r and s shall be checked to determine if r = 0 or s = 0.
17520 // If either r = 0 or s = 0, a new value of k shall be generated, and the
17521 // signature shall be recalculated. It is extremely unlikely that r = 0
17522 // or s = 0 if signatures are generated properly.
17523 while (true) {
17524 // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
17525 k = await getRandomBigInteger(one, q); // returns in [1, q-1]
17526 r = g.modExp(k, p).imod(q); // (g**k mod p) mod q
17527 if (r.isZero()) {
17528 continue;
17529 }
17530 const xr = x.mul(r).imod(q);
17531 t = h.add(xr).imod(q); // H(m) + x*r mod q
17532 s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q
17533 if (s.isZero()) {
17534 continue;
17535 }
17536 break;
17537 }
17538 return {
17539 r: r.toUint8Array('be', q.byteLength()),
17540 s: s.toUint8Array('be', q.byteLength())
17541 };
17542}
17543
17544/**
17545 * DSA Verify function
17546 * @param {Integer} hash_algo
17547 * @param {Uint8Array} r
17548 * @param {Uint8Array} s
17549 * @param {Uint8Array} hashed
17550 * @param {Uint8Array} g
17551 * @param {Uint8Array} p
17552 * @param {Uint8Array} q
17553 * @param {Uint8Array} y
17554 * @returns {boolean}
17555 * @async
17556 */
17557async function verify$3(hash_algo, r, s, hashed, g, p, q, y) {
17558 const BigInteger = await util.getBigInteger();
17559 const zero = new BigInteger(0);
17560 r = new BigInteger(r);
17561 s = new BigInteger(s);
17562
17563 p = new BigInteger(p);
17564 q = new BigInteger(q);
17565 g = new BigInteger(g);
17566 y = new BigInteger(y);
17567
17568 if (r.lte(zero) || r.gte(q) ||
17569 s.lte(zero) || s.gte(q)) {
17570 util.printDebug("invalid DSA Signature");
17571 return false;
17572 }
17573 const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);
17574 const w = s.modInv(q); // s**-1 mod q
17575 if (w.isZero()) {
17576 util.printDebug("invalid DSA Signature");
17577 return false;
17578 }
17579
17580 g = g.mod(p);
17581 y = y.mod(p);
17582 const u1 = h.mul(w).imod(q); // H(m) * w mod q
17583 const u2 = r.mul(w).imod(q); // r * w mod q
17584 const t1 = g.modExp(u1, p); // g**u1 mod p
17585 const t2 = y.modExp(u2, p); // y**u2 mod p
17586 const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q
17587 return v.equal(r);
17588}
17589
17590/**
17591 * Validate DSA parameters
17592 * @param {Uint8Array} p - DSA prime
17593 * @param {Uint8Array} q - DSA group order
17594 * @param {Uint8Array} g - DSA sub-group generator
17595 * @param {Uint8Array} y - DSA public key
17596 * @param {Uint8Array} x - DSA private key
17597 * @returns {Boolean} Whether params are valid.
17598 * @async
17599 */
17600async function validateParams$5(p, q, g, y, x) {
17601 const BigInteger = await util.getBigInteger();
17602 p = new BigInteger(p);
17603 q = new BigInteger(q);
17604 g = new BigInteger(g);
17605 y = new BigInteger(y);
17606 const one = new BigInteger(1);
17607 // Check that 1 < g < p
17608 if (g.lte(one) || g.gte(p)) {
17609 return false;
17610 }
17611
17612 /**
17613 * Check that subgroup order q divides p-1
17614 */
17615 if (!p.dec().mod(q).isZero()) {
17616 return false;
17617 }
17618
17619 /**
17620 * g has order q
17621 * Check that g ** q = 1 mod p
17622 */
17623 if (!g.modExp(q, p).isOne()) {
17624 return false;
17625 }
17626
17627 /**
17628 * Check q is large and probably prime (we mainly want to avoid small factors)
17629 */
17630 const qSize = new BigInteger(q.bitLength());
17631 const n150 = new BigInteger(150);
17632 if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {
17633 return false;
17634 }
17635
17636 /**
17637 * Re-derive public key y' = g ** x mod p
17638 * Expect y == y'
17639 *
17640 * Blinded exponentiation computes g**{rq + x} to compare to y
17641 */
17642 x = new BigInteger(x);
17643 const two = new BigInteger(2);
17644 const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q
17645 const rqx = q.mul(r).add(x);
17646 if (!y.equal(g.modExp(rqx, p))) {
17647 return false;
17648 }
17649
17650 return true;
17651}
17652
17653var dsa = /*#__PURE__*/Object.freeze({
17654 __proto__: null,
17655 sign: sign$3,
17656 verify: verify$3,
17657 validateParams: validateParams$5
17658});
17659
17660/**
17661 * @fileoverview Asymmetric cryptography functions
17662 * @module crypto/public_key
17663 * @private
17664 */
17665
17666var publicKey = {
17667 /** @see module:crypto/public_key/rsa */
17668 rsa: rsa,
17669 /** @see module:crypto/public_key/elgamal */
17670 elgamal: elgamal,
17671 /** @see module:crypto/public_key/elliptic */
17672 elliptic: elliptic,
17673 /** @see module:crypto/public_key/dsa */
17674 dsa: dsa,
17675 /** @see tweetnacl */
17676 nacl: naclFastLight
17677};
17678
17679/**
17680 * @fileoverview Provides functions for asymmetric signing and signature verification
17681 * @module crypto/signature
17682 * @private
17683 */
17684
17685/**
17686 * Parse signature in binary form to get the parameters.
17687 * The returned values are only padded for EdDSA, since in the other cases their expected length
17688 * depends on the key params, hence we delegate the padding to the signature verification function.
17689 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
17690 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
17691 * @param {module:enums.publicKey} algo - Public key algorithm
17692 * @param {Uint8Array} signature - Data for which the signature was created
17693 * @returns {Object} True if signature is valid.
17694 * @async
17695 */
17696function parseSignatureParams(algo, signature) {
17697 let read = 0;
17698 switch (algo) {
17699 // Algorithm-Specific Fields for RSA signatures:
17700 // - MPI of RSA signature value m**d mod n.
17701 case enums.publicKey.rsaEncryptSign:
17702 case enums.publicKey.rsaEncrypt:
17703 case enums.publicKey.rsaSign: {
17704 const s = util.readMPI(signature.subarray(read));
17705 // The signature needs to be the same length as the public key modulo n.
17706 // We pad s on signature verification, where we have access to n.
17707 return { s };
17708 }
17709 // Algorithm-Specific Fields for DSA or ECDSA signatures:
17710 // - MPI of DSA or ECDSA value r.
17711 // - MPI of DSA or ECDSA value s.
17712 case enums.publicKey.dsa:
17713 case enums.publicKey.ecdsa:
17714 {
17715 const r = util.readMPI(signature.subarray(read)); read += r.length + 2;
17716 const s = util.readMPI(signature.subarray(read));
17717 return { r, s };
17718 }
17719 // Algorithm-Specific Fields for EdDSA signatures:
17720 // - MPI of an EC point r.
17721 // - EdDSA value s, in MPI, in the little endian representation
17722 case enums.publicKey.eddsa: {
17723 // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
17724 // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
17725 let r = util.readMPI(signature.subarray(read)); read += r.length + 2;
17726 r = util.leftPad(r, 32);
17727 let s = util.readMPI(signature.subarray(read));
17728 s = util.leftPad(s, 32);
17729 return { r, s };
17730 }
17731 default:
17732 throw new Error('Invalid signature algorithm.');
17733 }
17734}
17735
17736/**
17737 * Verifies the signature provided for data using specified algorithms and public key parameters.
17738 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
17739 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
17740 * for public key and hash algorithms.
17741 * @param {module:enums.publicKey} algo - Public key algorithm
17742 * @param {module:enums.hash} hashAlgo - Hash algorithm
17743 * @param {Object} signature - Named algorithm-specific signature parameters
17744 * @param {Object} publicParams - Algorithm-specific public key parameters
17745 * @param {Uint8Array} data - Data for which the signature was created
17746 * @param {Uint8Array} hashed - The hashed data
17747 * @returns {Boolean} True if signature is valid.
17748 * @async
17749 */
17750async function verify$4(algo, hashAlgo, signature, publicParams, data, hashed) {
17751 switch (algo) {
17752 case enums.publicKey.rsaEncryptSign:
17753 case enums.publicKey.rsaEncrypt:
17754 case enums.publicKey.rsaSign: {
17755 const { n, e } = publicParams;
17756 const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
17757 return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);
17758 }
17759 case enums.publicKey.dsa: {
17760 const { g, p, q, y } = publicParams;
17761 const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
17762 return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);
17763 }
17764 case enums.publicKey.ecdsa: {
17765 const { oid, Q } = publicParams;
17766 const curveSize = new publicKey.elliptic.Curve(oid).payloadSize;
17767 // padding needed for webcrypto
17768 const r = util.leftPad(signature.r, curveSize);
17769 const s = util.leftPad(signature.s, curveSize);
17770 return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);
17771 }
17772 case enums.publicKey.eddsa: {
17773 const { oid, Q } = publicParams;
17774 // signature already padded on parsing
17775 return publicKey.elliptic.eddsa.verify(oid, hashAlgo, signature, data, Q, hashed);
17776 }
17777 default:
17778 throw new Error('Invalid signature algorithm.');
17779 }
17780}
17781
17782/**
17783 * Creates a signature on data using specified algorithms and private key parameters.
17784 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
17785 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
17786 * for public key and hash algorithms.
17787 * @param {module:enums.publicKey} algo - Public key algorithm
17788 * @param {module:enums.hash} hashAlgo - Hash algorithm
17789 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
17790 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
17791 * @param {Uint8Array} data - Data to be signed
17792 * @param {Uint8Array} hashed - The hashed data
17793 * @returns {Object} Signature Object containing named signature parameters.
17794 * @async
17795 */
17796async function sign$4(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
17797 if (!publicKeyParams || !privateKeyParams) {
17798 throw new Error('Missing key parameters');
17799 }
17800 switch (algo) {
17801 case enums.publicKey.rsaEncryptSign:
17802 case enums.publicKey.rsaEncrypt:
17803 case enums.publicKey.rsaSign: {
17804 const { n, e } = publicKeyParams;
17805 const { d, p, q, u } = privateKeyParams;
17806 const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);
17807 return { s };
17808 }
17809 case enums.publicKey.dsa: {
17810 const { g, p, q } = publicKeyParams;
17811 const { x } = privateKeyParams;
17812 return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);
17813 }
17814 case enums.publicKey.elgamal: {
17815 throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
17816 }
17817 case enums.publicKey.ecdsa: {
17818 const { oid, Q } = publicKeyParams;
17819 const { d } = privateKeyParams;
17820 return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);
17821 }
17822 case enums.publicKey.eddsa: {
17823 const { oid, Q } = publicKeyParams;
17824 const { seed } = privateKeyParams;
17825 return publicKey.elliptic.eddsa.sign(oid, hashAlgo, data, Q, seed, hashed);
17826 }
17827 default:
17828 throw new Error('Invalid signature algorithm.');
17829 }
17830}
17831
17832var signature = /*#__PURE__*/Object.freeze({
17833 __proto__: null,
17834 parseSignatureParams: parseSignatureParams,
17835 verify: verify$4,
17836 sign: sign$4
17837});
17838
17839// OpenPGP.js - An OpenPGP implementation in javascript
17840
17841class ECDHSymmetricKey {
17842 constructor(data) {
17843 if (typeof data === 'undefined') {
17844 data = new Uint8Array([]);
17845 } else if (util.isString(data)) {
17846 data = util.strToUint8Array(data);
17847 } else {
17848 data = new Uint8Array(data);
17849 }
17850 this.data = data;
17851 }
17852
17853 /**
17854 * Read an ECDHSymmetricKey from an Uint8Array
17855 * @param {Uint8Array} input - Where to read the encoded symmetric key from
17856 * @returns {Number} Number of read bytes.
17857 */
17858 read(input) {
17859 if (input.length >= 1) {
17860 const length = input[0];
17861 if (input.length >= 1 + length) {
17862 this.data = input.subarray(1, 1 + length);
17863 return 1 + this.data.length;
17864 }
17865 }
17866 throw new Error('Invalid symmetric key');
17867 }
17868
17869 /**
17870 * Write an ECDHSymmetricKey as an Uint8Array
17871 * @returns {Uint8Array} An array containing the value
17872 */
17873 write() {
17874 return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
17875 }
17876}
17877
17878// OpenPGP.js - An OpenPGP implementation in javascript
17879// Copyright (C) 2015-2016 Decentral
17880//
17881// This library is free software; you can redistribute it and/or
17882// modify it under the terms of the GNU Lesser General Public
17883// License as published by the Free Software Foundation; either
17884// version 3.0 of the License, or (at your option) any later version.
17885//
17886// This library is distributed in the hope that it will be useful,
17887// but WITHOUT ANY WARRANTY; without even the implied warranty of
17888// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17889// Lesser General Public License for more details.
17890//
17891// You should have received a copy of the GNU Lesser General Public
17892// License along with this library; if not, write to the Free Software
17893// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17894
17895/**
17896 * Implementation of type KDF parameters
17897 *
17898 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
17899 * A key derivation function (KDF) is necessary to implement the EC
17900 * encryption. The Concatenation Key Derivation Function (Approved
17901 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
17902 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
17903 * @module type/kdf_params
17904 * @private
17905 */
17906
17907class KDFParams {
17908 /**
17909 * @param {enums.hash} hash - Hash algorithm
17910 * @param {enums.symmetric} cipher - Symmetric algorithm
17911 */
17912 constructor(data) {
17913 if (data) {
17914 const { hash, cipher } = data;
17915 this.hash = hash;
17916 this.cipher = cipher;
17917 } else {
17918 this.hash = null;
17919 this.cipher = null;
17920 }
17921 }
17922
17923 /**
17924 * Read KDFParams from an Uint8Array
17925 * @param {Uint8Array} input - Where to read the KDFParams from
17926 * @returns {Number} Number of read bytes.
17927 */
17928 read(input) {
17929 if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
17930 throw new Error('Cannot read KDFParams');
17931 }
17932 this.hash = input[2];
17933 this.cipher = input[3];
17934 return 4;
17935 }
17936
17937 /**
17938 * Write KDFParams to an Uint8Array
17939 * @returns {Uint8Array} Array with the KDFParams value
17940 */
17941 write() {
17942 return new Uint8Array([3, 1, this.hash, this.cipher]);
17943 }
17944}
17945
17946// GPG4Browsers - An OpenPGP implementation in javascript
17947
17948/**
17949 * Encrypts data using specified algorithm and public key parameters.
17950 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
17951 * @param {module:enums.publicKey} algo - Public key algorithm
17952 * @param {Object} publicParams - Algorithm-specific public key parameters
17953 * @param {Uint8Array} data - Data to be encrypted
17954 * @param {Uint8Array} fingerprint - Recipient fingerprint
17955 * @returns {Object} Encrypted session key parameters.
17956 * @async
17957 */
17958async function publicKeyEncrypt(algo, publicParams, data, fingerprint) {
17959 switch (algo) {
17960 case enums.publicKey.rsaEncrypt:
17961 case enums.publicKey.rsaEncryptSign: {
17962 const { n, e } = publicParams;
17963 const c = await publicKey.rsa.encrypt(data, n, e);
17964 return { c };
17965 }
17966 case enums.publicKey.elgamal: {
17967 const { p, g, y } = publicParams;
17968 return publicKey.elgamal.encrypt(data, p, g, y);
17969 }
17970 case enums.publicKey.ecdh: {
17971 const { oid, Q, kdfParams } = publicParams;
17972 const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(
17973 oid, kdfParams, data, Q, fingerprint);
17974 return { V, C: new ECDHSymmetricKey(C) };
17975 }
17976 default:
17977 return [];
17978 }
17979}
17980
17981/**
17982 * Decrypts data using specified algorithm and private key parameters.
17983 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
17984 * @param {module:enums.publicKey} algo - Public key algorithm
17985 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
17986 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
17987 * @param {Object} sessionKeyParams - Encrypted session key parameters
17988 * @param {Uint8Array} fingerprint - Recipient fingerprint
17989 * @returns {Uint8Array} Decrypted data.
17990 * @async
17991 */
17992async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint) {
17993 switch (algo) {
17994 case enums.publicKey.rsaEncryptSign:
17995 case enums.publicKey.rsaEncrypt: {
17996 const { c } = sessionKeyParams;
17997 const { n, e } = publicKeyParams;
17998 const { d, p, q, u } = privateKeyParams;
17999 return publicKey.rsa.decrypt(c, n, e, d, p, q, u);
18000 }
18001 case enums.publicKey.elgamal: {
18002 const { c1, c2 } = sessionKeyParams;
18003 const p = publicKeyParams.p;
18004 const x = privateKeyParams.x;
18005 return publicKey.elgamal.decrypt(c1, c2, p, x);
18006 }
18007 case enums.publicKey.ecdh: {
18008 const { oid, Q, kdfParams } = publicKeyParams;
18009 const { d } = privateKeyParams;
18010 const { V, C } = sessionKeyParams;
18011 return publicKey.elliptic.ecdh.decrypt(
18012 oid, kdfParams, V, C.data, Q, d, fingerprint);
18013 }
18014 default:
18015 throw new Error('Invalid public key encryption algorithm.');
18016 }
18017}
18018
18019/**
18020 * Parse public key material in binary form to get the key parameters
18021 * @param {module:enums.publicKey} algo - The key algorithm
18022 * @param {Uint8Array} bytes - The key material to parse
18023 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
18024 */
18025function parsePublicKeyParams(algo, bytes) {
18026 let read = 0;
18027 switch (algo) {
18028 case enums.publicKey.rsaEncrypt:
18029 case enums.publicKey.rsaEncryptSign:
18030 case enums.publicKey.rsaSign: {
18031 const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;
18032 const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;
18033 return { read, publicParams: { n, e } };
18034 }
18035 case enums.publicKey.dsa: {
18036 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
18037 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
18038 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
18039 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
18040 return { read, publicParams: { p, q, g, y } };
18041 }
18042 case enums.publicKey.elgamal: {
18043 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
18044 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
18045 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
18046 return { read, publicParams: { p, g, y } };
18047 }
18048 case enums.publicKey.ecdsa: {
18049 const oid = new OID(); read += oid.read(bytes);
18050 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
18051 return { read: read, publicParams: { oid, Q } };
18052 }
18053 case enums.publicKey.eddsa: {
18054 const oid = new OID(); read += oid.read(bytes);
18055 let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
18056 Q = util.leftPad(Q, 33);
18057 return { read: read, publicParams: { oid, Q } };
18058 }
18059 case enums.publicKey.ecdh: {
18060 const oid = new OID(); read += oid.read(bytes);
18061 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
18062 const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));
18063 return { read: read, publicParams: { oid, Q, kdfParams } };
18064 }
18065 default:
18066 throw new Error('Invalid public key encryption algorithm.');
18067 }
18068}
18069
18070/**
18071 * Parse private key material in binary form to get the key parameters
18072 * @param {module:enums.publicKey} algo - The key algorithm
18073 * @param {Uint8Array} bytes - The key material to parse
18074 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
18075 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
18076 */
18077function parsePrivateKeyParams(algo, bytes, publicParams) {
18078 let read = 0;
18079 switch (algo) {
18080 case enums.publicKey.rsaEncrypt:
18081 case enums.publicKey.rsaEncryptSign:
18082 case enums.publicKey.rsaSign: {
18083 const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
18084 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
18085 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
18086 const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;
18087 return { read, privateParams: { d, p, q, u } };
18088 }
18089 case enums.publicKey.dsa:
18090 case enums.publicKey.elgamal: {
18091 const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;
18092 return { read, privateParams: { x } };
18093 }
18094 case enums.publicKey.ecdsa:
18095 case enums.publicKey.ecdh: {
18096 const curve = new Curve(publicParams.oid);
18097 let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
18098 d = util.leftPad(d, curve.payloadSize);
18099 return { read, privateParams: { d } };
18100 }
18101 case enums.publicKey.eddsa: {
18102 let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;
18103 seed = util.leftPad(seed, 32);
18104 return { read, privateParams: { seed } };
18105 }
18106 default:
18107 throw new Error('Invalid public key encryption algorithm.');
18108 }
18109}
18110
18111/** Returns the types comprising the encrypted session key of an algorithm
18112 * @param {module:enums.publicKey} algo - The key algorithm
18113 * @param {Uint8Array} bytes - The key material to parse
18114 * @returns {Object} The session key parameters referenced by name.
18115 */
18116function parseEncSessionKeyParams(algo, bytes) {
18117 let read = 0;
18118 switch (algo) {
18119 // Algorithm-Specific Fields for RSA encrypted session keys:
18120 // - MPI of RSA encrypted value m**e mod n.
18121 case enums.publicKey.rsaEncrypt:
18122 case enums.publicKey.rsaEncryptSign: {
18123 const c = util.readMPI(bytes.subarray(read));
18124 return { c };
18125 }
18126
18127 // Algorithm-Specific Fields for Elgamal encrypted session keys:
18128 // - MPI of Elgamal value g**k mod p
18129 // - MPI of Elgamal value m * y**k mod p
18130 case enums.publicKey.elgamal: {
18131 const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;
18132 const c2 = util.readMPI(bytes.subarray(read));
18133 return { c1, c2 };
18134 }
18135 // Algorithm-Specific Fields for ECDH encrypted session keys:
18136 // - MPI containing the ephemeral key used to establish the shared secret
18137 // - ECDH Symmetric Key
18138 case enums.publicKey.ecdh: {
18139 const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;
18140 const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read));
18141 return { V, C };
18142 }
18143 default:
18144 throw new Error('Invalid public key encryption algorithm.');
18145 }
18146}
18147
18148/**
18149 * Convert params to MPI and serializes them in the proper order
18150 * @param {module:enums.publicKey} algo - The public key algorithm
18151 * @param {Object} params - The key parameters indexed by name
18152 * @returns {Uint8Array} The array containing the MPIs.
18153 */
18154function serializeParams(algo, params) {
18155 const orderedParams = Object.keys(params).map(name => {
18156 const param = params[name];
18157 return util.isUint8Array(param) ? util.uint8ArrayToMpi(param) : param.write();
18158 });
18159 return util.concatUint8Array(orderedParams);
18160}
18161
18162/**
18163 * Generate algorithm-specific key parameters
18164 * @param {module:enums.publicKey} algo - The public key algorithm
18165 * @param {Integer} bits - Bit length for RSA keys
18166 * @param {module:type/oid} oid - Object identifier for ECC keys
18167 * @returns {{ publicParams: {Object}, privateParams: {Object} }} The parameters referenced by name.
18168 * @async
18169 */
18170function generateParams(algo, bits, oid) {
18171 switch (algo) {
18172 case enums.publicKey.rsaEncrypt:
18173 case enums.publicKey.rsaEncryptSign:
18174 case enums.publicKey.rsaSign: {
18175 return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({
18176 privateParams: { d, p, q, u },
18177 publicParams: { n, e }
18178 }));
18179 }
18180 case enums.publicKey.ecdsa:
18181 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
18182 privateParams: { d: secret },
18183 publicParams: { oid: new OID(oid), Q }
18184 }));
18185 case enums.publicKey.eddsa:
18186 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
18187 privateParams: { seed: secret },
18188 publicParams: { oid: new OID(oid), Q }
18189 }));
18190 case enums.publicKey.ecdh:
18191 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({
18192 privateParams: { d: secret },
18193 publicParams: {
18194 oid: new OID(oid),
18195 Q,
18196 kdfParams: new KDFParams({ hash, cipher })
18197 }
18198 }));
18199 case enums.publicKey.dsa:
18200 case enums.publicKey.elgamal:
18201 throw new Error('Unsupported algorithm for key generation.');
18202 default:
18203 throw new Error('Invalid public key algorithm.');
18204 }
18205}
18206
18207/**
18208 * Validate algorithm-specific key parameters
18209 * @param {module:enums.publicKey} algo - The public key algorithm
18210 * @param {Object} publicParams - Algorithm-specific public key parameters
18211 * @param {Object} privateParams - Algorithm-specific private key parameters
18212 * @returns {Boolean} Whether the parameters are valid.
18213 * @async
18214 */
18215async function validateParams$6(algo, publicParams, privateParams) {
18216 if (!publicParams || !privateParams) {
18217 throw new Error('Missing key parameters');
18218 }
18219 switch (algo) {
18220 case enums.publicKey.rsaEncrypt:
18221 case enums.publicKey.rsaEncryptSign:
18222 case enums.publicKey.rsaSign: {
18223 const { n, e } = publicParams;
18224 const { d, p, q, u } = privateParams;
18225 return publicKey.rsa.validateParams(n, e, d, p, q, u);
18226 }
18227 case enums.publicKey.dsa: {
18228 const { p, q, g, y } = publicParams;
18229 const { x } = privateParams;
18230 return publicKey.dsa.validateParams(p, q, g, y, x);
18231 }
18232 case enums.publicKey.elgamal: {
18233 const { p, g, y } = publicParams;
18234 const { x } = privateParams;
18235 return publicKey.elgamal.validateParams(p, g, y, x);
18236 }
18237 case enums.publicKey.ecdsa:
18238 case enums.publicKey.ecdh: {
18239 const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];
18240 const { oid, Q } = publicParams;
18241 const { d } = privateParams;
18242 return algoModule.validateParams(oid, Q, d);
18243 }
18244 case enums.publicKey.eddsa: {
18245 const { oid, Q } = publicParams;
18246 const { seed } = privateParams;
18247 return publicKey.elliptic.eddsa.validateParams(oid, Q, seed);
18248 }
18249 default:
18250 throw new Error('Invalid public key algorithm.');
18251 }
18252}
18253
18254/**
18255 * Generates a random byte prefix for the specified algorithm
18256 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
18257 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
18258 * @returns {Uint8Array} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
18259 * @async
18260 */
18261async function getPrefixRandom(algo) {
18262 const prefixrandom = await getRandomBytes(cipher[algo].blockSize);
18263 const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
18264 return util.concat([prefixrandom, repeat]);
18265}
18266
18267/**
18268 * Generating a session key for the specified symmetric algorithm
18269 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
18270 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
18271 * @returns {Uint8Array} Random bytes as a string to be used as a key.
18272 * @async
18273 */
18274function generateSessionKey(algo) {
18275 return getRandomBytes(cipher[algo].keySize);
18276}
18277
18278var crypto$1 = /*#__PURE__*/Object.freeze({
18279 __proto__: null,
18280 publicKeyEncrypt: publicKeyEncrypt,
18281 publicKeyDecrypt: publicKeyDecrypt,
18282 parsePublicKeyParams: parsePublicKeyParams,
18283 parsePrivateKeyParams: parsePrivateKeyParams,
18284 parseEncSessionKeyParams: parseEncSessionKeyParams,
18285 serializeParams: serializeParams,
18286 generateParams: generateParams,
18287 validateParams: validateParams$6,
18288 getPrefixRandom: getPrefixRandom,
18289 generateSessionKey: generateSessionKey
18290});
18291
18292/**
18293 * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
18294 * @see module:crypto/crypto
18295 * @see module:crypto/signature
18296 * @see module:crypto/public_key
18297 * @see module:crypto/cipher
18298 * @see module:crypto/random
18299 * @see module:crypto/hash
18300 * @module crypto
18301 * @private
18302 */
18303
18304// TODO move cfb and gcm to cipher
18305const mod = {
18306 /** @see module:crypto/cipher */
18307 cipher: cipher,
18308 /** @see module:crypto/hash */
18309 hash: hash,
18310 /** @see module:crypto/cfb */
18311 cfb: cfb,
18312 /** @see module:crypto/gcm */
18313 gcm: GCM,
18314 experimentalGcm: GCM,
18315 /** @see module:crypto/eax */
18316 eax: EAX,
18317 /** @see module:crypto/ocb */
18318 ocb: OCB,
18319 /** @see module:crypto/public_key */
18320 publicKey: publicKey,
18321 /** @see module:crypto/signature */
18322 signature: signature,
18323 /** @see module:crypto/random */
18324 random: random,
18325 /** @see module:crypto/pkcs1 */
18326 pkcs1: pkcs1,
18327 /** @see module:crypto/pkcs5 */
18328 pkcs5: pkcs5,
18329 /** @see module:crypto/aes_kw */
18330 aes_kw: aes_kw
18331};
18332
18333Object.assign(mod, crypto$1);
18334
18335var TYPED_OK = typeof Uint8Array !== "undefined" &&
18336 typeof Uint16Array !== "undefined" &&
18337 typeof Int32Array !== "undefined";
18338
18339
18340// reduce buffer size, avoiding mem copy
18341function shrinkBuf(buf, size) {
18342 if (buf.length === size) {
18343 return buf;
18344 }
18345 if (buf.subarray) {
18346 return buf.subarray(0, size);
18347 }
18348 buf.length = size;
18349 return buf;
18350}
18351
18352
18353const fnTyped = {
18354 arraySet: function (dest, src, src_offs, len, dest_offs) {
18355 if (src.subarray && dest.subarray) {
18356 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
18357 return;
18358 }
18359 // Fallback to ordinary array
18360 for (let i = 0; i < len; i++) {
18361 dest[dest_offs + i] = src[src_offs + i];
18362 }
18363 },
18364 // Join array of chunks to single array.
18365 flattenChunks: function (chunks) {
18366 let i, l, len, pos, chunk;
18367
18368 // calculate data length
18369 len = 0;
18370 for (i = 0, l = chunks.length; i < l; i++) {
18371 len += chunks[i].length;
18372 }
18373
18374 // join chunks
18375 const result = new Uint8Array(len);
18376 pos = 0;
18377 for (i = 0, l = chunks.length; i < l; i++) {
18378 chunk = chunks[i];
18379 result.set(chunk, pos);
18380 pos += chunk.length;
18381 }
18382
18383 return result;
18384 }
18385};
18386
18387const fnUntyped = {
18388 arraySet: function (dest, src, src_offs, len, dest_offs) {
18389 for (let i = 0; i < len; i++) {
18390 dest[dest_offs + i] = src[src_offs + i];
18391 }
18392 },
18393 // Join array of chunks to single array.
18394 flattenChunks: function (chunks) {
18395 return [].concat.apply([], chunks);
18396 }
18397};
18398
18399
18400// Enable/Disable typed arrays use, for testing
18401//
18402
18403let Buf8 = TYPED_OK ? Uint8Array : Array;
18404let Buf16 = TYPED_OK ? Uint16Array : Array;
18405let Buf32 = TYPED_OK ? Int32Array : Array;
18406let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;
18407let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;
18408
18409// (C) 1995-2013 Jean-loup Gailly and Mark Adler
18410// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18411//
18412// This software is provided 'as-is', without any express or implied
18413// warranty. In no event will the authors be held liable for any damages
18414// arising from the use of this software.
18415//
18416// Permission is granted to anyone to use this software for any purpose,
18417// including commercial applications, and to alter it and redistribute it
18418// freely, subject to the following restrictions:
18419//
18420// 1. The origin of this software must not be misrepresented; you must not
18421// claim that you wrote the original software. If you use this software
18422// in a product, an acknowledgment in the product documentation would be
18423// appreciated but is not required.
18424// 2. Altered source versions must be plainly marked as such, and must not be
18425// misrepresented as being the original software.
18426// 3. This notice may not be removed or altered from any source distribution.
18427
18428/* Allowed flush values; see deflate() and inflate() below for details */
18429const Z_NO_FLUSH = 0;
18430const Z_PARTIAL_FLUSH = 1;
18431const Z_SYNC_FLUSH = 2;
18432const Z_FULL_FLUSH = 3;
18433const Z_FINISH = 4;
18434const Z_BLOCK = 5;
18435const Z_TREES = 6;
18436
18437/* Return codes for the compression/decompression functions. Negative values
18438 * are errors, positive values are used for special but normal events.
18439 */
18440const Z_OK = 0;
18441const Z_STREAM_END = 1;
18442const Z_NEED_DICT = 2;
18443const Z_STREAM_ERROR = -2;
18444const Z_DATA_ERROR = -3;
18445//export const Z_MEM_ERROR = -4;
18446const Z_BUF_ERROR = -5;
18447const Z_DEFAULT_COMPRESSION = -1;
18448
18449
18450const Z_FILTERED = 1;
18451const Z_HUFFMAN_ONLY = 2;
18452const Z_RLE = 3;
18453const Z_FIXED = 4;
18454const Z_DEFAULT_STRATEGY = 0;
18455
18456/* Possible values of the data_type field (though see inflate()) */
18457const Z_BINARY = 0;
18458const Z_TEXT = 1;
18459//export const Z_ASCII = 1; // = Z_TEXT (deprecated)
18460const Z_UNKNOWN = 2;
18461
18462/* The deflate compression method */
18463const Z_DEFLATED = 8;
18464//export const Z_NULL = null // Use -1 or null inline, depending on var type
18465
18466/*============================================================================*/
18467
18468
18469function zero$1(buf) {
18470 let len = buf.length; while (--len >= 0) {
18471 buf[len] = 0;
18472 }
18473}
18474
18475// From zutil.h
18476
18477const STORED_BLOCK = 0;
18478const STATIC_TREES = 1;
18479const DYN_TREES = 2;
18480/* The three kinds of block type */
18481
18482const MIN_MATCH = 3;
18483const MAX_MATCH = 258;
18484/* The minimum and maximum match lengths */
18485
18486// From deflate.h
18487/* ===========================================================================
18488 * Internal compression state.
18489 */
18490
18491const LENGTH_CODES = 29;
18492/* number of length codes, not counting the special END_BLOCK code */
18493
18494const LITERALS = 256;
18495/* number of literal bytes 0..255 */
18496
18497const L_CODES = LITERALS + 1 + LENGTH_CODES;
18498/* number of Literal or Length codes, including the END_BLOCK code */
18499
18500const D_CODES = 30;
18501/* number of distance codes */
18502
18503const BL_CODES = 19;
18504/* number of codes used to transfer the bit lengths */
18505
18506const HEAP_SIZE = 2 * L_CODES + 1;
18507/* maximum heap size */
18508
18509const MAX_BITS = 15;
18510/* All codes must not exceed MAX_BITS bits */
18511
18512const Buf_size = 16;
18513/* size of bit buffer in bi_buf */
18514
18515
18516/* ===========================================================================
18517 * Constants
18518 */
18519
18520const MAX_BL_BITS = 7;
18521/* Bit length codes must not exceed MAX_BL_BITS bits */
18522
18523const END_BLOCK = 256;
18524/* end of block literal code */
18525
18526const REP_3_6 = 16;
18527/* repeat previous bit length 3-6 times (2 bits of repeat count) */
18528
18529const REPZ_3_10 = 17;
18530/* repeat a zero length 3-10 times (3 bits of repeat count) */
18531
18532const REPZ_11_138 = 18;
18533/* repeat a zero length 11-138 times (7 bits of repeat count) */
18534
18535/* eslint-disable comma-spacing,array-bracket-spacing */
18536const extra_lbits = /* extra bits for each length code */
18537 [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];
18538
18539const extra_dbits = /* extra bits for each distance code */
18540 [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];
18541
18542const extra_blbits = /* extra bits for each bit length code */
18543 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
18544
18545const bl_order =
18546 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
18547/* eslint-enable comma-spacing,array-bracket-spacing */
18548
18549/* The lengths of the bit length codes are sent in order of decreasing
18550 * probability, to avoid transmitting the lengths for unused bit length codes.
18551 */
18552
18553/* ===========================================================================
18554 * Local data. These are initialized only once.
18555 */
18556
18557// We pre-fill arrays with 0 to avoid uninitialized gaps
18558
18559const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
18560
18561// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
18562const static_ltree = new Array((L_CODES + 2) * 2);
18563zero$1(static_ltree);
18564/* The static literal tree. Since the bit lengths are imposed, there is no
18565 * need for the L_CODES extra codes used during heap construction. However
18566 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
18567 * below).
18568 */
18569
18570const static_dtree = new Array(D_CODES * 2);
18571zero$1(static_dtree);
18572/* The static distance tree. (Actually a trivial tree since all codes use
18573 * 5 bits.)
18574 */
18575
18576const _dist_code = new Array(DIST_CODE_LEN);
18577zero$1(_dist_code);
18578/* Distance codes. The first 256 values correspond to the distances
18579 * 3 .. 258, the last 256 values correspond to the top 8 bits of
18580 * the 15 bit distances.
18581 */
18582
18583const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
18584zero$1(_length_code);
18585/* length code for each normalized match length (0 == MIN_MATCH) */
18586
18587const base_length = new Array(LENGTH_CODES);
18588zero$1(base_length);
18589/* First normalized length for each code (0 = MIN_MATCH) */
18590
18591const base_dist = new Array(D_CODES);
18592zero$1(base_dist);
18593/* First normalized distance for each code (0 = distance of 1) */
18594
18595
18596function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
18597
18598 this.static_tree = static_tree; /* static tree or NULL */
18599 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
18600 this.extra_base = extra_base; /* base index for extra_bits */
18601 this.elems = elems; /* max number of elements in the tree */
18602 this.max_length = max_length; /* max bit length for the codes */
18603
18604 // show if `static_tree` has data or dummy - needed for monomorphic objects
18605 this.has_stree = static_tree && static_tree.length;
18606}
18607
18608
18609let static_l_desc;
18610let static_d_desc;
18611let static_bl_desc;
18612
18613
18614function TreeDesc(dyn_tree, stat_desc) {
18615 this.dyn_tree = dyn_tree; /* the dynamic tree */
18616 this.max_code = 0; /* largest code with non zero frequency */
18617 this.stat_desc = stat_desc; /* the corresponding static tree */
18618}
18619
18620
18621
18622function d_code(dist) {
18623 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
18624}
18625
18626
18627/* ===========================================================================
18628 * Output a short LSB first on the stream.
18629 * IN assertion: there is enough room in pendingBuf.
18630 */
18631function put_short(s, w) {
18632// put_byte(s, (uch)((w) & 0xff));
18633// put_byte(s, (uch)((ush)(w) >> 8));
18634 s.pending_buf[s.pending++] = w & 0xff;
18635 s.pending_buf[s.pending++] = w >>> 8 & 0xff;
18636}
18637
18638
18639/* ===========================================================================
18640 * Send a value on a given number of bits.
18641 * IN assertion: length <= 16 and value fits in length bits.
18642 */
18643function send_bits(s, value, length) {
18644 if (s.bi_valid > Buf_size - length) {
18645 s.bi_buf |= value << s.bi_valid & 0xffff;
18646 put_short(s, s.bi_buf);
18647 s.bi_buf = value >> Buf_size - s.bi_valid;
18648 s.bi_valid += length - Buf_size;
18649 } else {
18650 s.bi_buf |= value << s.bi_valid & 0xffff;
18651 s.bi_valid += length;
18652 }
18653}
18654
18655
18656function send_code(s, c, tree) {
18657 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
18658}
18659
18660
18661/* ===========================================================================
18662 * Reverse the first len bits of a code, using straightforward code (a faster
18663 * method would use a table)
18664 * IN assertion: 1 <= len <= 15
18665 */
18666function bi_reverse(code, len) {
18667 let res = 0;
18668 do {
18669 res |= code & 1;
18670 code >>>= 1;
18671 res <<= 1;
18672 } while (--len > 0);
18673 return res >>> 1;
18674}
18675
18676
18677/* ===========================================================================
18678 * Flush the bit buffer, keeping at most 7 bits in it.
18679 */
18680function bi_flush(s) {
18681 if (s.bi_valid === 16) {
18682 put_short(s, s.bi_buf);
18683 s.bi_buf = 0;
18684 s.bi_valid = 0;
18685
18686 } else if (s.bi_valid >= 8) {
18687 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
18688 s.bi_buf >>= 8;
18689 s.bi_valid -= 8;
18690 }
18691}
18692
18693
18694/* ===========================================================================
18695 * Compute the optimal bit lengths for a tree and update the total bit length
18696 * for the current block.
18697 * IN assertion: the fields freq and dad are set, heap[heap_max] and
18698 * above are the tree nodes sorted by increasing frequency.
18699 * OUT assertions: the field len is set to the optimal bit length, the
18700 * array bl_count contains the frequencies for each bit length.
18701 * The length opt_len is updated; static_len is also updated if stree is
18702 * not null.
18703 */
18704function gen_bitlen(s, desc)
18705// deflate_state *s;
18706// tree_desc *desc; /* the tree descriptor */
18707{
18708 const tree = desc.dyn_tree;
18709 const max_code = desc.max_code;
18710 const stree = desc.stat_desc.static_tree;
18711 const has_stree = desc.stat_desc.has_stree;
18712 const extra = desc.stat_desc.extra_bits;
18713 const base = desc.stat_desc.extra_base;
18714 const max_length = desc.stat_desc.max_length;
18715 let h; /* heap index */
18716 let n, m; /* iterate over the tree elements */
18717 let bits; /* bit length */
18718 let xbits; /* extra bits */
18719 let f; /* frequency */
18720 let overflow = 0; /* number of elements with bit length too large */
18721
18722 for (bits = 0; bits <= MAX_BITS; bits++) {
18723 s.bl_count[bits] = 0;
18724 }
18725
18726 /* In a first pass, compute the optimal bit lengths (which may
18727 * overflow in the case of the bit length tree).
18728 */
18729 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
18730
18731 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
18732 n = s.heap[h];
18733 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
18734 if (bits > max_length) {
18735 bits = max_length;
18736 overflow++;
18737 }
18738 tree[n * 2 + 1]/*.Len*/ = bits;
18739 /* We overwrite tree[n].Dad which is no longer needed */
18740
18741 if (n > max_code) {
18742 continue;
18743 } /* not a leaf node */
18744
18745 s.bl_count[bits]++;
18746 xbits = 0;
18747 if (n >= base) {
18748 xbits = extra[n - base];
18749 }
18750 f = tree[n * 2]/*.Freq*/;
18751 s.opt_len += f * (bits + xbits);
18752 if (has_stree) {
18753 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
18754 }
18755 }
18756 if (overflow === 0) {
18757 return;
18758 }
18759
18760 // Trace((stderr,"\nbit length overflow\n"));
18761 /* This happens for example on obj2 and pic of the Calgary corpus */
18762
18763 /* Find the first bit length which could increase: */
18764 do {
18765 bits = max_length - 1;
18766 while (s.bl_count[bits] === 0) {
18767 bits--;
18768 }
18769 s.bl_count[bits]--; /* move one leaf down the tree */
18770 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
18771 s.bl_count[max_length]--;
18772 /* The brother of the overflow item also moves one step up,
18773 * but this does not affect bl_count[max_length]
18774 */
18775 overflow -= 2;
18776 } while (overflow > 0);
18777
18778 /* Now recompute all bit lengths, scanning in increasing frequency.
18779 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
18780 * lengths instead of fixing only the wrong ones. This idea is taken
18781 * from 'ar' written by Haruhiko Okumura.)
18782 */
18783 for (bits = max_length; bits !== 0; bits--) {
18784 n = s.bl_count[bits];
18785 while (n !== 0) {
18786 m = s.heap[--h];
18787 if (m > max_code) {
18788 continue;
18789 }
18790 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
18791 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
18792 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
18793 tree[m * 2 + 1]/*.Len*/ = bits;
18794 }
18795 n--;
18796 }
18797 }
18798}
18799
18800
18801/* ===========================================================================
18802 * Generate the codes for a given tree and bit counts (which need not be
18803 * optimal).
18804 * IN assertion: the array bl_count contains the bit length statistics for
18805 * the given tree and the field len is set for all tree elements.
18806 * OUT assertion: the field code is set for all tree elements of non
18807 * zero code length.
18808 */
18809function gen_codes(tree, max_code, bl_count)
18810// ct_data *tree; /* the tree to decorate */
18811// int max_code; /* largest code with non zero frequency */
18812// ushf *bl_count; /* number of codes at each bit length */
18813{
18814 const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
18815 let code = 0; /* running code value */
18816 let bits; /* bit index */
18817 let n; /* code index */
18818
18819 /* The distribution counts are first used to generate the code values
18820 * without bit reversal.
18821 */
18822 for (bits = 1; bits <= MAX_BITS; bits++) {
18823 next_code[bits] = code = code + bl_count[bits - 1] << 1;
18824 }
18825 /* Check that the bit counts in bl_count are consistent. The last code
18826 * must be all ones.
18827 */
18828 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
18829 // "inconsistent bit counts");
18830 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
18831
18832 for (n = 0; n <= max_code; n++) {
18833 const len = tree[n * 2 + 1]/*.Len*/;
18834 if (len === 0) {
18835 continue;
18836 }
18837 /* Now reverse the bits */
18838 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
18839
18840 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
18841 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
18842 }
18843}
18844
18845
18846/* ===========================================================================
18847 * Initialize the various 'constant' tables.
18848 */
18849function tr_static_init() {
18850 let n; /* iterates over tree elements */
18851 let bits; /* bit counter */
18852 let length; /* length value */
18853 let code; /* code value */
18854 let dist; /* distance index */
18855 const bl_count = new Array(MAX_BITS + 1);
18856 /* number of codes at each bit length for an optimal tree */
18857
18858 // do check in _tr_init()
18859 //if (static_init_done) return;
18860
18861 /* For some embedded targets, global variables are not initialized: */
18862 /*#ifdef NO_INIT_GLOBAL_POINTERS
18863 static_l_desc.static_tree = static_ltree;
18864 static_l_desc.extra_bits = extra_lbits;
18865 static_d_desc.static_tree = static_dtree;
18866 static_d_desc.extra_bits = extra_dbits;
18867 static_bl_desc.extra_bits = extra_blbits;
18868#endif*/
18869
18870 /* Initialize the mapping length (0..255) -> length code (0..28) */
18871 length = 0;
18872 for (code = 0; code < LENGTH_CODES - 1; code++) {
18873 base_length[code] = length;
18874 for (n = 0; n < 1 << extra_lbits[code]; n++) {
18875 _length_code[length++] = code;
18876 }
18877 }
18878 //Assert (length == 256, "tr_static_init: length != 256");
18879 /* Note that the length 255 (match length 258) can be represented
18880 * in two different ways: code 284 + 5 bits or code 285, so we
18881 * overwrite length_code[255] to use the best encoding:
18882 */
18883 _length_code[length - 1] = code;
18884
18885 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
18886 dist = 0;
18887 for (code = 0; code < 16; code++) {
18888 base_dist[code] = dist;
18889 for (n = 0; n < 1 << extra_dbits[code]; n++) {
18890 _dist_code[dist++] = code;
18891 }
18892 }
18893 //Assert (dist == 256, "tr_static_init: dist != 256");
18894 dist >>= 7; /* from now on, all distances are divided by 128 */
18895 for (; code < D_CODES; code++) {
18896 base_dist[code] = dist << 7;
18897 for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
18898 _dist_code[256 + dist++] = code;
18899 }
18900 }
18901 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
18902
18903 /* Construct the codes of the static literal tree */
18904 for (bits = 0; bits <= MAX_BITS; bits++) {
18905 bl_count[bits] = 0;
18906 }
18907
18908 n = 0;
18909 while (n <= 143) {
18910 static_ltree[n * 2 + 1]/*.Len*/ = 8;
18911 n++;
18912 bl_count[8]++;
18913 }
18914 while (n <= 255) {
18915 static_ltree[n * 2 + 1]/*.Len*/ = 9;
18916 n++;
18917 bl_count[9]++;
18918 }
18919 while (n <= 279) {
18920 static_ltree[n * 2 + 1]/*.Len*/ = 7;
18921 n++;
18922 bl_count[7]++;
18923 }
18924 while (n <= 287) {
18925 static_ltree[n * 2 + 1]/*.Len*/ = 8;
18926 n++;
18927 bl_count[8]++;
18928 }
18929 /* Codes 286 and 287 do not exist, but we must include them in the
18930 * tree construction to get a canonical Huffman tree (longest code
18931 * all ones)
18932 */
18933 gen_codes(static_ltree, L_CODES + 1, bl_count);
18934
18935 /* The static distance tree is trivial: */
18936 for (n = 0; n < D_CODES; n++) {
18937 static_dtree[n * 2 + 1]/*.Len*/ = 5;
18938 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
18939 }
18940
18941 // Now data ready and we can init static trees
18942 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
18943 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
18944 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
18945
18946 //static_init_done = true;
18947}
18948
18949
18950/* ===========================================================================
18951 * Initialize a new block.
18952 */
18953function init_block(s) {
18954 let n; /* iterates over tree elements */
18955
18956 /* Initialize the trees. */
18957 for (n = 0; n < L_CODES; n++) {
18958 s.dyn_ltree[n * 2]/*.Freq*/ = 0;
18959 }
18960 for (n = 0; n < D_CODES; n++) {
18961 s.dyn_dtree[n * 2]/*.Freq*/ = 0;
18962 }
18963 for (n = 0; n < BL_CODES; n++) {
18964 s.bl_tree[n * 2]/*.Freq*/ = 0;
18965 }
18966
18967 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
18968 s.opt_len = s.static_len = 0;
18969 s.last_lit = s.matches = 0;
18970}
18971
18972
18973/* ===========================================================================
18974 * Flush the bit buffer and align the output on a byte boundary
18975 */
18976function bi_windup(s) {
18977 if (s.bi_valid > 8) {
18978 put_short(s, s.bi_buf);
18979 } else if (s.bi_valid > 0) {
18980 //put_byte(s, (Byte)s->bi_buf);
18981 s.pending_buf[s.pending++] = s.bi_buf;
18982 }
18983 s.bi_buf = 0;
18984 s.bi_valid = 0;
18985}
18986
18987/* ===========================================================================
18988 * Copy a stored block, storing first the length and its
18989 * one's complement if requested.
18990 */
18991function copy_block(s, buf, len, header)
18992//DeflateState *s;
18993//charf *buf; /* the input data */
18994//unsigned len; /* its length */
18995//int header; /* true if block header must be written */
18996{
18997 bi_windup(s); /* align on byte boundary */
18998
18999 if (header) {
19000 put_short(s, len);
19001 put_short(s, ~len);
19002 }
19003 // while (len--) {
19004 // put_byte(s, *buf++);
19005 // }
19006 arraySet(s.pending_buf, s.window, buf, len, s.pending);
19007 s.pending += len;
19008}
19009
19010/* ===========================================================================
19011 * Compares to subtrees, using the tree depth as tie breaker when
19012 * the subtrees have equal frequency. This minimizes the worst case length.
19013 */
19014function smaller(tree, n, m, depth) {
19015 const _n2 = n * 2;
19016 const _m2 = m * 2;
19017 return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
19018 tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];
19019}
19020
19021/* ===========================================================================
19022 * Restore the heap property by moving down the tree starting at node k,
19023 * exchanging a node with the smallest of its two sons if necessary, stopping
19024 * when the heap property is re-established (each father smaller than its
19025 * two sons).
19026 */
19027function pqdownheap(s, tree, k)
19028// deflate_state *s;
19029// ct_data *tree; /* the tree to restore */
19030// int k; /* node to move down */
19031{
19032 const v = s.heap[k];
19033 let j = k << 1; /* left son of k */
19034 while (j <= s.heap_len) {
19035 /* Set j to the smallest of the two sons: */
19036 if (j < s.heap_len &&
19037 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
19038 j++;
19039 }
19040 /* Exit if v is smaller than both sons */
19041 if (smaller(tree, v, s.heap[j], s.depth)) {
19042 break;
19043 }
19044
19045 /* Exchange v with the smallest son */
19046 s.heap[k] = s.heap[j];
19047 k = j;
19048
19049 /* And continue down the tree, setting j to the left son of k */
19050 j <<= 1;
19051 }
19052 s.heap[k] = v;
19053}
19054
19055
19056// inlined manually
19057// var SMALLEST = 1;
19058
19059/* ===========================================================================
19060 * Send the block data compressed using the given Huffman trees
19061 */
19062function compress_block(s, ltree, dtree)
19063// deflate_state *s;
19064// const ct_data *ltree; /* literal tree */
19065// const ct_data *dtree; /* distance tree */
19066{
19067 let dist; /* distance of matched string */
19068 let lc; /* match length or unmatched char (if dist == 0) */
19069 let lx = 0; /* running index in l_buf */
19070 let code; /* the code to send */
19071 let extra; /* number of extra bits to send */
19072
19073 if (s.last_lit !== 0) {
19074 do {
19075 dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
19076 lc = s.pending_buf[s.l_buf + lx];
19077 lx++;
19078
19079 if (dist === 0) {
19080 send_code(s, lc, ltree); /* send a literal byte */
19081 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
19082 } else {
19083 /* Here, lc is the match length - MIN_MATCH */
19084 code = _length_code[lc];
19085 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
19086 extra = extra_lbits[code];
19087 if (extra !== 0) {
19088 lc -= base_length[code];
19089 send_bits(s, lc, extra); /* send the extra length bits */
19090 }
19091 dist--; /* dist is now the match distance - 1 */
19092 code = d_code(dist);
19093 //Assert (code < D_CODES, "bad d_code");
19094
19095 send_code(s, code, dtree); /* send the distance code */
19096 extra = extra_dbits[code];
19097 if (extra !== 0) {
19098 dist -= base_dist[code];
19099 send_bits(s, dist, extra); /* send the extra distance bits */
19100 }
19101 } /* literal or match pair ? */
19102
19103 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
19104 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
19105 // "pendingBuf overflow");
19106
19107 } while (lx < s.last_lit);
19108 }
19109
19110 send_code(s, END_BLOCK, ltree);
19111}
19112
19113
19114/* ===========================================================================
19115 * Construct one Huffman tree and assigns the code bit strings and lengths.
19116 * Update the total bit length for the current block.
19117 * IN assertion: the field freq is set for all tree elements.
19118 * OUT assertions: the fields len and code are set to the optimal bit length
19119 * and corresponding code. The length opt_len is updated; static_len is
19120 * also updated if stree is not null. The field max_code is set.
19121 */
19122function build_tree(s, desc)
19123// deflate_state *s;
19124// tree_desc *desc; /* the tree descriptor */
19125{
19126 const tree = desc.dyn_tree;
19127 const stree = desc.stat_desc.static_tree;
19128 const has_stree = desc.stat_desc.has_stree;
19129 const elems = desc.stat_desc.elems;
19130 let n, m; /* iterate over heap elements */
19131 let max_code = -1; /* largest code with non zero frequency */
19132 let node; /* new node being created */
19133
19134 /* Construct the initial heap, with least frequent element in
19135 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
19136 * heap[0] is not used.
19137 */
19138 s.heap_len = 0;
19139 s.heap_max = HEAP_SIZE;
19140
19141 for (n = 0; n < elems; n++) {
19142 if (tree[n * 2]/*.Freq*/ !== 0) {
19143 s.heap[++s.heap_len] = max_code = n;
19144 s.depth[n] = 0;
19145
19146 } else {
19147 tree[n * 2 + 1]/*.Len*/ = 0;
19148 }
19149 }
19150
19151 /* The pkzip format requires that at least one distance code exists,
19152 * and that at least one bit should be sent even if there is only one
19153 * possible code. So to avoid special checks later on we force at least
19154 * two codes of non zero frequency.
19155 */
19156 while (s.heap_len < 2) {
19157 node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
19158 tree[node * 2]/*.Freq*/ = 1;
19159 s.depth[node] = 0;
19160 s.opt_len--;
19161
19162 if (has_stree) {
19163 s.static_len -= stree[node * 2 + 1]/*.Len*/;
19164 }
19165 /* node is 0 or 1 so it does not have extra bits */
19166 }
19167 desc.max_code = max_code;
19168
19169 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
19170 * establish sub-heaps of increasing lengths:
19171 */
19172 for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {
19173 pqdownheap(s, tree, n);
19174 }
19175
19176 /* Construct the Huffman tree by repeatedly combining the least two
19177 * frequent nodes.
19178 */
19179 node = elems; /* next internal node of the tree */
19180 do {
19181 //pqremove(s, tree, n); /* n = node of least frequency */
19182 /*** pqremove ***/
19183 n = s.heap[1/*SMALLEST*/];
19184 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
19185 pqdownheap(s, tree, 1/*SMALLEST*/);
19186 /***/
19187
19188 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
19189
19190 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
19191 s.heap[--s.heap_max] = m;
19192
19193 /* Create a new node father of n and m */
19194 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
19195 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
19196 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
19197
19198 /* and insert the new node in the heap */
19199 s.heap[1/*SMALLEST*/] = node++;
19200 pqdownheap(s, tree, 1/*SMALLEST*/);
19201
19202 } while (s.heap_len >= 2);
19203
19204 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
19205
19206 /* At this point, the fields freq and dad are set. We can now
19207 * generate the bit lengths.
19208 */
19209 gen_bitlen(s, desc);
19210
19211 /* The field len is now set, we can generate the bit codes */
19212 gen_codes(tree, max_code, s.bl_count);
19213}
19214
19215
19216/* ===========================================================================
19217 * Scan a literal or distance tree to determine the frequencies of the codes
19218 * in the bit length tree.
19219 */
19220function scan_tree(s, tree, max_code)
19221// deflate_state *s;
19222// ct_data *tree; /* the tree to be scanned */
19223// int max_code; /* and its largest code of non zero frequency */
19224{
19225 let n; /* iterates over all tree elements */
19226 let prevlen = -1; /* last emitted length */
19227 let curlen; /* length of current code */
19228
19229 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
19230
19231 let count = 0; /* repeat count of the current code */
19232 let max_count = 7; /* max repeat count */
19233 let min_count = 4; /* min repeat count */
19234
19235 if (nextlen === 0) {
19236 max_count = 138;
19237 min_count = 3;
19238 }
19239 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
19240
19241 for (n = 0; n <= max_code; n++) {
19242 curlen = nextlen;
19243 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
19244
19245 if (++count < max_count && curlen === nextlen) {
19246 continue;
19247
19248 } else if (count < min_count) {
19249 s.bl_tree[curlen * 2]/*.Freq*/ += count;
19250
19251 } else if (curlen !== 0) {
19252
19253 if (curlen !== prevlen) {
19254 s.bl_tree[curlen * 2]/*.Freq*/++;
19255 }
19256 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
19257
19258 } else if (count <= 10) {
19259 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
19260
19261 } else {
19262 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
19263 }
19264
19265 count = 0;
19266 prevlen = curlen;
19267
19268 if (nextlen === 0) {
19269 max_count = 138;
19270 min_count = 3;
19271
19272 } else if (curlen === nextlen) {
19273 max_count = 6;
19274 min_count = 3;
19275
19276 } else {
19277 max_count = 7;
19278 min_count = 4;
19279 }
19280 }
19281}
19282
19283
19284/* ===========================================================================
19285 * Send a literal or distance tree in compressed form, using the codes in
19286 * bl_tree.
19287 */
19288function send_tree(s, tree, max_code)
19289// deflate_state *s;
19290// ct_data *tree; /* the tree to be scanned */
19291// int max_code; /* and its largest code of non zero frequency */
19292{
19293 let n; /* iterates over all tree elements */
19294 let prevlen = -1; /* last emitted length */
19295 let curlen; /* length of current code */
19296
19297 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
19298
19299 let count = 0; /* repeat count of the current code */
19300 let max_count = 7; /* max repeat count */
19301 let min_count = 4; /* min repeat count */
19302
19303 /* tree[max_code+1].Len = -1; */ /* guard already set */
19304 if (nextlen === 0) {
19305 max_count = 138;
19306 min_count = 3;
19307 }
19308
19309 for (n = 0; n <= max_code; n++) {
19310 curlen = nextlen;
19311 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
19312
19313 if (++count < max_count && curlen === nextlen) {
19314 continue;
19315
19316 } else if (count < min_count) {
19317 do {
19318 send_code(s, curlen, s.bl_tree);
19319 } while (--count !== 0);
19320
19321 } else if (curlen !== 0) {
19322 if (curlen !== prevlen) {
19323 send_code(s, curlen, s.bl_tree);
19324 count--;
19325 }
19326 //Assert(count >= 3 && count <= 6, " 3_6?");
19327 send_code(s, REP_3_6, s.bl_tree);
19328 send_bits(s, count - 3, 2);
19329
19330 } else if (count <= 10) {
19331 send_code(s, REPZ_3_10, s.bl_tree);
19332 send_bits(s, count - 3, 3);
19333
19334 } else {
19335 send_code(s, REPZ_11_138, s.bl_tree);
19336 send_bits(s, count - 11, 7);
19337 }
19338
19339 count = 0;
19340 prevlen = curlen;
19341 if (nextlen === 0) {
19342 max_count = 138;
19343 min_count = 3;
19344
19345 } else if (curlen === nextlen) {
19346 max_count = 6;
19347 min_count = 3;
19348
19349 } else {
19350 max_count = 7;
19351 min_count = 4;
19352 }
19353 }
19354}
19355
19356
19357/* ===========================================================================
19358 * Construct the Huffman tree for the bit lengths and return the index in
19359 * bl_order of the last bit length code to send.
19360 */
19361function build_bl_tree(s) {
19362 let max_blindex; /* index of last bit length code of non zero freq */
19363
19364 /* Determine the bit length frequencies for literal and distance trees */
19365 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
19366 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
19367
19368 /* Build the bit length tree: */
19369 build_tree(s, s.bl_desc);
19370 /* opt_len now includes the length of the tree representations, except
19371 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
19372 */
19373
19374 /* Determine the number of bit length codes to send. The pkzip format
19375 * requires that at least 4 bit length codes be sent. (appnote.txt says
19376 * 3 but the actual value used is 4.)
19377 */
19378 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
19379 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
19380 break;
19381 }
19382 }
19383 /* Update opt_len to include the bit length tree and counts */
19384 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
19385 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
19386 // s->opt_len, s->static_len));
19387
19388 return max_blindex;
19389}
19390
19391
19392/* ===========================================================================
19393 * Send the header for a block using dynamic Huffman trees: the counts, the
19394 * lengths of the bit length codes, the literal tree and the distance tree.
19395 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
19396 */
19397function send_all_trees(s, lcodes, dcodes, blcodes)
19398// deflate_state *s;
19399// int lcodes, dcodes, blcodes; /* number of codes for each tree */
19400{
19401 let rank; /* index in bl_order */
19402
19403 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
19404 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
19405 // "too many codes");
19406 //Tracev((stderr, "\nbl counts: "));
19407 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
19408 send_bits(s, dcodes - 1, 5);
19409 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
19410 for (rank = 0; rank < blcodes; rank++) {
19411 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
19412 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
19413 }
19414 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
19415
19416 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
19417 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
19418
19419 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
19420 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
19421}
19422
19423
19424/* ===========================================================================
19425 * Check if the data type is TEXT or BINARY, using the following algorithm:
19426 * - TEXT if the two conditions below are satisfied:
19427 * a) There are no non-portable control characters belonging to the
19428 * "black list" (0..6, 14..25, 28..31).
19429 * b) There is at least one printable character belonging to the
19430 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
19431 * - BINARY otherwise.
19432 * - The following partially-portable control characters form a
19433 * "gray list" that is ignored in this detection algorithm:
19434 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
19435 * IN assertion: the fields Freq of dyn_ltree are set.
19436 */
19437function detect_data_type(s) {
19438 /* black_mask is the bit mask of black-listed bytes
19439 * set bits 0..6, 14..25, and 28..31
19440 * 0xf3ffc07f = binary 11110011111111111100000001111111
19441 */
19442 let black_mask = 0xf3ffc07f;
19443 let n;
19444
19445 /* Check for non-textual ("black-listed") bytes. */
19446 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
19447 if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
19448 return Z_BINARY;
19449 }
19450 }
19451
19452 /* Check for textual ("white-listed") bytes. */
19453 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
19454 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
19455 return Z_TEXT;
19456 }
19457 for (n = 32; n < LITERALS; n++) {
19458 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
19459 return Z_TEXT;
19460 }
19461 }
19462
19463 /* There are no "black-listed" or "white-listed" bytes:
19464 * this stream either is empty or has tolerated ("gray-listed") bytes only.
19465 */
19466 return Z_BINARY;
19467}
19468
19469
19470let static_init_done = false;
19471
19472/* ===========================================================================
19473 * Initialize the tree data structures for a new zlib stream.
19474 */
19475function _tr_init(s) {
19476
19477 if (!static_init_done) {
19478 tr_static_init();
19479 static_init_done = true;
19480 }
19481
19482 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
19483 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
19484 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
19485
19486 s.bi_buf = 0;
19487 s.bi_valid = 0;
19488
19489 /* Initialize the first block of the first file: */
19490 init_block(s);
19491}
19492
19493
19494/* ===========================================================================
19495 * Send a stored block
19496 */
19497function _tr_stored_block(s, buf, stored_len, last)
19498//DeflateState *s;
19499//charf *buf; /* input block */
19500//ulg stored_len; /* length of input block */
19501//int last; /* one if this is the last block for a file */
19502{
19503 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
19504 copy_block(s, buf, stored_len, true); /* with header */
19505}
19506
19507
19508/* ===========================================================================
19509 * Send one empty static block to give enough lookahead for inflate.
19510 * This takes 10 bits, of which 7 may remain in the bit buffer.
19511 */
19512function _tr_align(s) {
19513 send_bits(s, STATIC_TREES << 1, 3);
19514 send_code(s, END_BLOCK, static_ltree);
19515 bi_flush(s);
19516}
19517
19518
19519/* ===========================================================================
19520 * Determine the best encoding for the current block: dynamic trees, static
19521 * trees or store, and output the encoded block to the zip file.
19522 */
19523function _tr_flush_block(s, buf, stored_len, last)
19524//DeflateState *s;
19525//charf *buf; /* input block, or NULL if too old */
19526//ulg stored_len; /* length of input block */
19527//int last; /* one if this is the last block for a file */
19528{
19529 let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
19530 let max_blindex = 0; /* index of last bit length code of non zero freq */
19531
19532 /* Build the Huffman trees unless a stored block is forced */
19533 if (s.level > 0) {
19534
19535 /* Check if the file is binary or text */
19536 if (s.strm.data_type === Z_UNKNOWN) {
19537 s.strm.data_type = detect_data_type(s);
19538 }
19539
19540 /* Construct the literal and distance trees */
19541 build_tree(s, s.l_desc);
19542 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
19543 // s->static_len));
19544
19545 build_tree(s, s.d_desc);
19546 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
19547 // s->static_len));
19548 /* At this point, opt_len and static_len are the total bit lengths of
19549 * the compressed block data, excluding the tree representations.
19550 */
19551
19552 /* Build the bit length tree for the above two trees, and get the index
19553 * in bl_order of the last bit length code to send.
19554 */
19555 max_blindex = build_bl_tree(s);
19556
19557 /* Determine the best encoding. Compute the block lengths in bytes. */
19558 opt_lenb = s.opt_len + 3 + 7 >>> 3;
19559 static_lenb = s.static_len + 3 + 7 >>> 3;
19560
19561 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
19562 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
19563 // s->last_lit));
19564
19565 if (static_lenb <= opt_lenb) {
19566 opt_lenb = static_lenb;
19567 }
19568
19569 } else {
19570 // Assert(buf != (char*)0, "lost buf");
19571 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
19572 }
19573
19574 if (stored_len + 4 <= opt_lenb && buf !== -1) {
19575 /* 4: two words for the lengths */
19576
19577 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
19578 * Otherwise we can't have processed more than WSIZE input bytes since
19579 * the last block flush, because compression would have been
19580 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
19581 * transform a block into a stored block.
19582 */
19583 _tr_stored_block(s, buf, stored_len, last);
19584
19585 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
19586
19587 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
19588 compress_block(s, static_ltree, static_dtree);
19589
19590 } else {
19591 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
19592 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
19593 compress_block(s, s.dyn_ltree, s.dyn_dtree);
19594 }
19595 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
19596 /* The above check is made mod 2^32, for files larger than 512 MB
19597 * and uLong implemented on 32 bits.
19598 */
19599 init_block(s);
19600
19601 if (last) {
19602 bi_windup(s);
19603 }
19604 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
19605 // s->compressed_len-7*last));
19606}
19607
19608/* ===========================================================================
19609 * Save the match info and tally the frequency counts. Return true if
19610 * the current block must be flushed.
19611 */
19612function _tr_tally(s, dist, lc)
19613// deflate_state *s;
19614// unsigned dist; /* distance of matched string */
19615// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
19616{
19617 //var out_length, in_length, dcode;
19618
19619 s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
19620 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
19621
19622 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
19623 s.last_lit++;
19624
19625 if (dist === 0) {
19626 /* lc is the unmatched char */
19627 s.dyn_ltree[lc * 2]/*.Freq*/++;
19628 } else {
19629 s.matches++;
19630 /* Here, lc is the match length - MIN_MATCH */
19631 dist--; /* dist = match distance - 1 */
19632 //Assert((ush)dist < (ush)MAX_DIST(s) &&
19633 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
19634 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
19635
19636 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
19637 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
19638 }
19639
19640 // (!) This block is disabled in zlib defaults,
19641 // don't enable it for binary compatibility
19642
19643 //#ifdef TRUNCATE_BLOCK
19644 // /* Try to guess if it is profitable to stop the current block here */
19645 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
19646 // /* Compute an upper bound for the compressed length */
19647 // out_length = s.last_lit*8;
19648 // in_length = s.strstart - s.block_start;
19649 //
19650 // for (dcode = 0; dcode < D_CODES; dcode++) {
19651 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
19652 // }
19653 // out_length >>>= 3;
19654 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
19655 // // s->last_lit, in_length, out_length,
19656 // // 100L - out_length*100L/in_length));
19657 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
19658 // return true;
19659 // }
19660 // }
19661 //#endif
19662
19663 return s.last_lit === s.lit_bufsize - 1;
19664 /* We avoid equality with lit_bufsize because of wraparound at 64K
19665 * on 16 bit machines and because stored blocks are restricted to
19666 * 64K-1 bytes.
19667 */
19668}
19669
19670// Note: adler32 takes 12% for level 0 and 2% for level 6.
19671// It isn't worth it to make additional optimizations as in original.
19672// Small size is preferable.
19673
19674// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19675// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19676//
19677// This software is provided 'as-is', without any express or implied
19678// warranty. In no event will the authors be held liable for any damages
19679// arising from the use of this software.
19680//
19681// Permission is granted to anyone to use this software for any purpose,
19682// including commercial applications, and to alter it and redistribute it
19683// freely, subject to the following restrictions:
19684//
19685// 1. The origin of this software must not be misrepresented; you must not
19686// claim that you wrote the original software. If you use this software
19687// in a product, an acknowledgment in the product documentation would be
19688// appreciated but is not required.
19689// 2. Altered source versions must be plainly marked as such, and must not be
19690// misrepresented as being the original software.
19691// 3. This notice may not be removed or altered from any source distribution.
19692
19693function adler32(adler, buf, len, pos) {
19694 let s1 = adler & 0xffff |0,
19695 s2 = adler >>> 16 & 0xffff |0,
19696 n = 0;
19697
19698 while (len !== 0) {
19699 // Set limit ~ twice less than 5552, to keep
19700 // s2 in 31-bits, because we force signed ints.
19701 // in other case %= will fail.
19702 n = len > 2000 ? 2000 : len;
19703 len -= n;
19704
19705 do {
19706 s1 = s1 + buf[pos++] |0;
19707 s2 = s2 + s1 |0;
19708 } while (--n);
19709
19710 s1 %= 65521;
19711 s2 %= 65521;
19712 }
19713
19714 return s1 | s2 << 16 |0;
19715}
19716
19717// Note: we can't get significant speed boost here.
19718// So write code to minimize size - no pregenerated tables
19719// and array tools dependencies.
19720
19721// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19722// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19723//
19724// This software is provided 'as-is', without any express or implied
19725// warranty. In no event will the authors be held liable for any damages
19726// arising from the use of this software.
19727//
19728// Permission is granted to anyone to use this software for any purpose,
19729// including commercial applications, and to alter it and redistribute it
19730// freely, subject to the following restrictions:
19731//
19732// 1. The origin of this software must not be misrepresented; you must not
19733// claim that you wrote the original software. If you use this software
19734// in a product, an acknowledgment in the product documentation would be
19735// appreciated but is not required.
19736// 2. Altered source versions must be plainly marked as such, and must not be
19737// misrepresented as being the original software.
19738// 3. This notice may not be removed or altered from any source distribution.
19739
19740// Use ordinary array, since untyped makes no boost here
19741function makeTable() {
19742 let c;
19743 const table = [];
19744
19745 for (let n = 0; n < 256; n++) {
19746 c = n;
19747 for (let k = 0; k < 8; k++) {
19748 c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
19749 }
19750 table[n] = c;
19751 }
19752
19753 return table;
19754}
19755
19756// Create table on load. Just 255 signed longs. Not a problem.
19757const crcTable = makeTable();
19758
19759
19760function crc32(crc, buf, len, pos) {
19761 const t = crcTable,
19762 end = pos + len;
19763
19764 crc ^= -1;
19765
19766 for (let i = pos; i < end; i++) {
19767 crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
19768 }
19769
19770 return crc ^ -1; // >>> 0;
19771}
19772
19773// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19774// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19775//
19776// This software is provided 'as-is', without any express or implied
19777// warranty. In no event will the authors be held liable for any damages
19778// arising from the use of this software.
19779//
19780// Permission is granted to anyone to use this software for any purpose,
19781// including commercial applications, and to alter it and redistribute it
19782// freely, subject to the following restrictions:
19783//
19784// 1. The origin of this software must not be misrepresented; you must not
19785// claim that you wrote the original software. If you use this software
19786// in a product, an acknowledgment in the product documentation would be
19787// appreciated but is not required.
19788// 2. Altered source versions must be plainly marked as such, and must not be
19789// misrepresented as being the original software.
19790// 3. This notice may not be removed or altered from any source distribution.
19791
19792var msg = {
19793 2: "need dictionary", /* Z_NEED_DICT 2 */
19794 1: "stream end", /* Z_STREAM_END 1 */
19795 0: "", /* Z_OK 0 */
19796 "-1": "file error", /* Z_ERRNO (-1) */
19797 "-2": "stream error", /* Z_STREAM_ERROR (-2) */
19798 "-3": "data error", /* Z_DATA_ERROR (-3) */
19799 "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */
19800 "-5": "buffer error", /* Z_BUF_ERROR (-5) */
19801 "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */
19802};
19803
19804/*============================================================================*/
19805
19806
19807const MAX_MEM_LEVEL = 9;
19808
19809
19810const LENGTH_CODES$1 = 29;
19811/* number of length codes, not counting the special END_BLOCK code */
19812const LITERALS$1 = 256;
19813/* number of literal bytes 0..255 */
19814const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
19815/* number of Literal or Length codes, including the END_BLOCK code */
19816const D_CODES$1 = 30;
19817/* number of distance codes */
19818const BL_CODES$1 = 19;
19819/* number of codes used to transfer the bit lengths */
19820const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
19821/* maximum heap size */
19822const MAX_BITS$1 = 15;
19823/* All codes must not exceed MAX_BITS bits */
19824
19825const MIN_MATCH$1 = 3;
19826const MAX_MATCH$1 = 258;
19827const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
19828
19829const PRESET_DICT = 0x20;
19830
19831const INIT_STATE = 42;
19832const EXTRA_STATE = 69;
19833const NAME_STATE = 73;
19834const COMMENT_STATE = 91;
19835const HCRC_STATE = 103;
19836const BUSY_STATE = 113;
19837const FINISH_STATE = 666;
19838
19839const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
19840const BS_BLOCK_DONE = 2; /* block flush performed */
19841const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
19842const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
19843
19844const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
19845
19846function err(strm, errorCode) {
19847 strm.msg = msg[errorCode];
19848 return errorCode;
19849}
19850
19851function rank(f) {
19852 return ((f) << 1) - ((f) > 4 ? 9 : 0);
19853}
19854
19855function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
19856
19857
19858/* =========================================================================
19859 * Flush as much pending output as possible. All deflate() output goes
19860 * through this function so some applications may wish to modify it
19861 * to avoid allocating a large strm->output buffer and copying into it.
19862 * (See also read_buf()).
19863 */
19864function flush_pending(strm) {
19865 const s = strm.state;
19866
19867 //_tr_flush_bits(s);
19868 let len = s.pending;
19869 if (len > strm.avail_out) {
19870 len = strm.avail_out;
19871 }
19872 if (len === 0) { return; }
19873
19874 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
19875 strm.next_out += len;
19876 s.pending_out += len;
19877 strm.total_out += len;
19878 strm.avail_out -= len;
19879 s.pending -= len;
19880 if (s.pending === 0) {
19881 s.pending_out = 0;
19882 }
19883}
19884
19885
19886function flush_block_only(s, last) {
19887 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
19888 s.block_start = s.strstart;
19889 flush_pending(s.strm);
19890}
19891
19892
19893function put_byte(s, b) {
19894 s.pending_buf[s.pending++] = b;
19895}
19896
19897
19898/* =========================================================================
19899 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
19900 * IN assertion: the stream state is correct and there is enough room in
19901 * pending_buf.
19902 */
19903function putShortMSB(s, b) {
19904 // put_byte(s, (Byte)(b >> 8));
19905 // put_byte(s, (Byte)(b & 0xff));
19906 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
19907 s.pending_buf[s.pending++] = b & 0xff;
19908}
19909
19910
19911/* ===========================================================================
19912 * Read a new buffer from the current input stream, update the adler32
19913 * and total number of bytes read. All deflate() input goes through
19914 * this function so some applications may wish to modify it to avoid
19915 * allocating a large strm->input buffer and copying from it.
19916 * (See also flush_pending()).
19917 */
19918function read_buf(strm, buf, start, size) {
19919 let len = strm.avail_in;
19920
19921 if (len > size) { len = size; }
19922 if (len === 0) { return 0; }
19923
19924 strm.avail_in -= len;
19925
19926 // zmemcpy(buf, strm->next_in, len);
19927 arraySet(buf, strm.input, strm.next_in, len, start);
19928 if (strm.state.wrap === 1) {
19929 strm.adler = adler32(strm.adler, buf, len, start);
19930 }
19931
19932 else if (strm.state.wrap === 2) {
19933 strm.adler = crc32(strm.adler, buf, len, start);
19934 }
19935
19936 strm.next_in += len;
19937 strm.total_in += len;
19938
19939 return len;
19940}
19941
19942
19943/* ===========================================================================
19944 * Set match_start to the longest match starting at the given string and
19945 * return its length. Matches shorter or equal to prev_length are discarded,
19946 * in which case the result is equal to prev_length and match_start is
19947 * garbage.
19948 * IN assertions: cur_match is the head of the hash chain for the current
19949 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
19950 * OUT assertion: the match length is not greater than s->lookahead.
19951 */
19952function longest_match(s, cur_match) {
19953 let chain_length = s.max_chain_length; /* max hash chain length */
19954 let scan = s.strstart; /* current string */
19955 let match; /* matched string */
19956 let len; /* length of current match */
19957 let best_len = s.prev_length; /* best match length so far */
19958 let nice_match = s.nice_match; /* stop if match long enough */
19959 const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
19960 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
19961
19962 const _win = s.window; // shortcut
19963
19964 const wmask = s.w_mask;
19965 const prev = s.prev;
19966
19967 /* Stop when cur_match becomes <= limit. To simplify the code,
19968 * we prevent matches with the string of window index 0.
19969 */
19970
19971 const strend = s.strstart + MAX_MATCH$1;
19972 let scan_end1 = _win[scan + best_len - 1];
19973 let scan_end = _win[scan + best_len];
19974
19975 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
19976 * It is easy to get rid of this optimization if necessary.
19977 */
19978 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
19979
19980 /* Do not waste too much time if we already have a good match: */
19981 if (s.prev_length >= s.good_match) {
19982 chain_length >>= 2;
19983 }
19984 /* Do not look for matches beyond the end of the input. This is necessary
19985 * to make deflate deterministic.
19986 */
19987 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
19988
19989 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
19990
19991 do {
19992 // Assert(cur_match < s->strstart, "no future");
19993 match = cur_match;
19994
19995 /* Skip to next match if the match length cannot increase
19996 * or if the match length is less than 2. Note that the checks below
19997 * for insufficient lookahead only occur occasionally for performance
19998 * reasons. Therefore uninitialized memory will be accessed, and
19999 * conditional jumps will be made that depend on those values.
20000 * However the length of the match is limited to the lookahead, so
20001 * the output of deflate is not affected by the uninitialized values.
20002 */
20003
20004 if (_win[match + best_len] !== scan_end ||
20005 _win[match + best_len - 1] !== scan_end1 ||
20006 _win[match] !== _win[scan] ||
20007 _win[++match] !== _win[scan + 1]) {
20008 continue;
20009 }
20010
20011 /* The check at best_len-1 can be removed because it will be made
20012 * again later. (This heuristic is not always a win.)
20013 * It is not necessary to compare scan[2] and match[2] since they
20014 * are always equal when the other bytes match, given that
20015 * the hash keys are equal and that HASH_BITS >= 8.
20016 */
20017 scan += 2;
20018 match++;
20019 // Assert(*scan == *match, "match[2]?");
20020
20021 /* We check for insufficient lookahead only every 8th comparison;
20022 * the 256th check will be made at strstart+258.
20023 */
20024 do {
20025 /*jshint noempty:false*/
20026 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
20027 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
20028 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
20029 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
20030 scan < strend);
20031
20032 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
20033
20034 len = MAX_MATCH$1 - (strend - scan);
20035 scan = strend - MAX_MATCH$1;
20036
20037 if (len > best_len) {
20038 s.match_start = cur_match;
20039 best_len = len;
20040 if (len >= nice_match) {
20041 break;
20042 }
20043 scan_end1 = _win[scan + best_len - 1];
20044 scan_end = _win[scan + best_len];
20045 }
20046 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
20047
20048 if (best_len <= s.lookahead) {
20049 return best_len;
20050 }
20051 return s.lookahead;
20052}
20053
20054
20055/* ===========================================================================
20056 * Fill the window when the lookahead becomes insufficient.
20057 * Updates strstart and lookahead.
20058 *
20059 * IN assertion: lookahead < MIN_LOOKAHEAD
20060 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
20061 * At least one byte has been read, or avail_in == 0; reads are
20062 * performed for at least two bytes (required for the zip translate_eol
20063 * option -- not supported here).
20064 */
20065function fill_window(s) {
20066 const _w_size = s.w_size;
20067 let p, n, m, more, str;
20068
20069 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
20070
20071 do {
20072 more = s.window_size - s.lookahead - s.strstart;
20073
20074 // JS ints have 32 bit, block below not needed
20075 /* Deal with !@#$% 64K limit: */
20076 //if (sizeof(int) <= 2) {
20077 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
20078 // more = wsize;
20079 //
20080 // } else if (more == (unsigned)(-1)) {
20081 // /* Very unlikely, but possible on 16 bit machine if
20082 // * strstart == 0 && lookahead == 1 (input done a byte at time)
20083 // */
20084 // more--;
20085 // }
20086 //}
20087
20088
20089 /* If the window is almost full and there is insufficient lookahead,
20090 * move the upper half to the lower one to make room in the upper half.
20091 */
20092 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
20093
20094 arraySet(s.window, s.window, _w_size, _w_size, 0);
20095 s.match_start -= _w_size;
20096 s.strstart -= _w_size;
20097 /* we now have strstart >= MAX_DIST */
20098 s.block_start -= _w_size;
20099
20100 /* Slide the hash table (could be avoided with 32 bit values
20101 at the expense of memory usage). We slide even when level == 0
20102 to keep the hash table consistent if we switch back to level > 0
20103 later. (Using level 0 permanently is not an optimal usage of
20104 zlib, so we don't care about this pathological case.)
20105 */
20106
20107 n = s.hash_size;
20108 p = n;
20109 do {
20110 m = s.head[--p];
20111 s.head[p] = (m >= _w_size ? m - _w_size : 0);
20112 } while (--n);
20113
20114 n = _w_size;
20115 p = n;
20116 do {
20117 m = s.prev[--p];
20118 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
20119 /* If n is not on any hash chain, prev[n] is garbage but
20120 * its value will never be used.
20121 */
20122 } while (--n);
20123
20124 more += _w_size;
20125 }
20126 if (s.strm.avail_in === 0) {
20127 break;
20128 }
20129
20130 /* If there was no sliding:
20131 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
20132 * more == window_size - lookahead - strstart
20133 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
20134 * => more >= window_size - 2*WSIZE + 2
20135 * In the BIG_MEM or MMAP case (not yet supported),
20136 * window_size == input_size + MIN_LOOKAHEAD &&
20137 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
20138 * Otherwise, window_size == 2*WSIZE so more >= 2.
20139 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
20140 */
20141 //Assert(more >= 2, "more < 2");
20142 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
20143 s.lookahead += n;
20144
20145 /* Initialize the hash value now that we have some input: */
20146 if (s.lookahead + s.insert >= MIN_MATCH$1) {
20147 str = s.strstart - s.insert;
20148 s.ins_h = s.window[str];
20149
20150 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
20151 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
20152 //#if MIN_MATCH != 3
20153 // Call update_hash() MIN_MATCH-3 more times
20154 //#endif
20155 while (s.insert) {
20156 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
20157 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
20158
20159 s.prev[str & s.w_mask] = s.head[s.ins_h];
20160 s.head[s.ins_h] = str;
20161 str++;
20162 s.insert--;
20163 if (s.lookahead + s.insert < MIN_MATCH$1) {
20164 break;
20165 }
20166 }
20167 }
20168 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
20169 * but this is not important since only literal bytes will be emitted.
20170 */
20171
20172 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
20173
20174 /* If the WIN_INIT bytes after the end of the current data have never been
20175 * written, then zero those bytes in order to avoid memory check reports of
20176 * the use of uninitialized (or uninitialised as Julian writes) bytes by
20177 * the longest match routines. Update the high water mark for the next
20178 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
20179 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
20180 */
20181 // if (s.high_water < s.window_size) {
20182 // var curr = s.strstart + s.lookahead;
20183 // var init = 0;
20184 //
20185 // if (s.high_water < curr) {
20186 // /* Previous high water mark below current data -- zero WIN_INIT
20187 // * bytes or up to end of window, whichever is less.
20188 // */
20189 // init = s.window_size - curr;
20190 // if (init > WIN_INIT)
20191 // init = WIN_INIT;
20192 // zmemzero(s->window + curr, (unsigned)init);
20193 // s->high_water = curr + init;
20194 // }
20195 // else if (s->high_water < (ulg)curr + WIN_INIT) {
20196 // /* High water mark at or above current data, but below current data
20197 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
20198 // * to end of window, whichever is less.
20199 // */
20200 // init = (ulg)curr + WIN_INIT - s->high_water;
20201 // if (init > s->window_size - s->high_water)
20202 // init = s->window_size - s->high_water;
20203 // zmemzero(s->window + s->high_water, (unsigned)init);
20204 // s->high_water += init;
20205 // }
20206 // }
20207 //
20208 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
20209 // "not enough room for search");
20210}
20211
20212/* ===========================================================================
20213 * Copy without compression as much as possible from the input stream, return
20214 * the current block state.
20215 * This function does not insert new strings in the dictionary since
20216 * uncompressible data is probably not useful. This function is used
20217 * only for the level=0 compression option.
20218 * NOTE: this function should be optimized to avoid extra copying from
20219 * window to pending_buf.
20220 */
20221function deflate_stored(s, flush) {
20222 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
20223 * to pending_buf_size, and each stored block has a 5 byte header:
20224 */
20225 let max_block_size = 0xffff;
20226
20227 if (max_block_size > s.pending_buf_size - 5) {
20228 max_block_size = s.pending_buf_size - 5;
20229 }
20230
20231 /* Copy as much as possible from input to output: */
20232 for (; ;) {
20233 /* Fill the window as much as possible: */
20234 if (s.lookahead <= 1) {
20235
20236 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
20237 // s->block_start >= (long)s->w_size, "slide too late");
20238 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
20239 // s.block_start >= s.w_size)) {
20240 // throw new Error("slide too late");
20241 // }
20242
20243 fill_window(s);
20244 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
20245 return BS_NEED_MORE;
20246 }
20247
20248 if (s.lookahead === 0) {
20249 break;
20250 }
20251 /* flush the current block */
20252 }
20253 //Assert(s->block_start >= 0L, "block gone");
20254 // if (s.block_start < 0) throw new Error("block gone");
20255
20256 s.strstart += s.lookahead;
20257 s.lookahead = 0;
20258
20259 /* Emit a stored block if pending_buf will be full: */
20260 const max_start = s.block_start + max_block_size;
20261
20262 if (s.strstart === 0 || s.strstart >= max_start) {
20263 /* strstart == 0 is possible when wraparound on 16-bit machine */
20264 s.lookahead = s.strstart - max_start;
20265 s.strstart = max_start;
20266 /*** FLUSH_BLOCK(s, 0); ***/
20267 flush_block_only(s, false);
20268 if (s.strm.avail_out === 0) {
20269 return BS_NEED_MORE;
20270 }
20271 /***/
20272
20273
20274 }
20275 /* Flush if we may have to slide, otherwise block_start may become
20276 * negative and the data will be gone:
20277 */
20278 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
20279 /*** FLUSH_BLOCK(s, 0); ***/
20280 flush_block_only(s, false);
20281 if (s.strm.avail_out === 0) {
20282 return BS_NEED_MORE;
20283 }
20284 /***/
20285 }
20286 }
20287
20288 s.insert = 0;
20289
20290 if (flush === Z_FINISH) {
20291 /*** FLUSH_BLOCK(s, 1); ***/
20292 flush_block_only(s, true);
20293 if (s.strm.avail_out === 0) {
20294 return BS_FINISH_STARTED;
20295 }
20296 /***/
20297 return BS_FINISH_DONE;
20298 }
20299
20300 if (s.strstart > s.block_start) {
20301 /*** FLUSH_BLOCK(s, 0); ***/
20302 flush_block_only(s, false);
20303 if (s.strm.avail_out === 0) {
20304 return BS_NEED_MORE;
20305 }
20306 /***/
20307 }
20308
20309 return BS_NEED_MORE;
20310}
20311
20312/* ===========================================================================
20313 * Compress as much as possible from the input stream, return the current
20314 * block state.
20315 * This function does not perform lazy evaluation of matches and inserts
20316 * new strings in the dictionary only for unmatched strings or for short
20317 * matches. It is used only for the fast compression options.
20318 */
20319function deflate_fast(s, flush) {
20320 let hash_head; /* head of the hash chain */
20321 let bflush; /* set if current block must be flushed */
20322
20323 for (; ;) {
20324 /* Make sure that we always have enough lookahead, except
20325 * at the end of the input file. We need MAX_MATCH bytes
20326 * for the next match, plus MIN_MATCH bytes to insert the
20327 * string following the next match.
20328 */
20329 if (s.lookahead < MIN_LOOKAHEAD) {
20330 fill_window(s);
20331 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
20332 return BS_NEED_MORE;
20333 }
20334 if (s.lookahead === 0) {
20335 break; /* flush the current block */
20336 }
20337 }
20338
20339 /* Insert the string window[strstart .. strstart+2] in the
20340 * dictionary, and set hash_head to the head of the hash chain:
20341 */
20342 hash_head = 0/*NIL*/;
20343 if (s.lookahead >= MIN_MATCH$1) {
20344 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
20345 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
20346 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
20347 s.head[s.ins_h] = s.strstart;
20348 /***/
20349 }
20350
20351 /* Find the longest match, discarding those <= prev_length.
20352 * At this point we have always match_length < MIN_MATCH
20353 */
20354 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
20355 /* To simplify the code, we prevent matches with the string
20356 * of window index 0 (in particular we have to avoid a match
20357 * of the string with itself at the start of the input file).
20358 */
20359 s.match_length = longest_match(s, hash_head);
20360 /* longest_match() sets match_start */
20361 }
20362 if (s.match_length >= MIN_MATCH$1) {
20363 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
20364
20365 /*** _tr_tally_dist(s, s.strstart - s.match_start,
20366 s.match_length - MIN_MATCH, bflush); ***/
20367 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
20368
20369 s.lookahead -= s.match_length;
20370
20371 /* Insert new strings in the hash table only if the match length
20372 * is not too large. This saves time but degrades compression.
20373 */
20374 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
20375 s.match_length--; /* string at strstart already in table */
20376 do {
20377 s.strstart++;
20378 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
20379 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
20380 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
20381 s.head[s.ins_h] = s.strstart;
20382 /***/
20383 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
20384 * always MIN_MATCH bytes ahead.
20385 */
20386 } while (--s.match_length !== 0);
20387 s.strstart++;
20388 } else {
20389 s.strstart += s.match_length;
20390 s.match_length = 0;
20391 s.ins_h = s.window[s.strstart];
20392 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
20393 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
20394
20395 //#if MIN_MATCH != 3
20396 // Call UPDATE_HASH() MIN_MATCH-3 more times
20397 //#endif
20398 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
20399 * matter since it will be recomputed at next deflate call.
20400 */
20401 }
20402 } else {
20403 /* No match, output a literal byte */
20404 //Tracevv((stderr,"%c", s.window[s.strstart]));
20405 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
20406 bflush = _tr_tally(s, 0, s.window[s.strstart]);
20407
20408 s.lookahead--;
20409 s.strstart++;
20410 }
20411 if (bflush) {
20412 /*** FLUSH_BLOCK(s, 0); ***/
20413 flush_block_only(s, false);
20414 if (s.strm.avail_out === 0) {
20415 return BS_NEED_MORE;
20416 }
20417 /***/
20418 }
20419 }
20420 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
20421 if (flush === Z_FINISH) {
20422 /*** FLUSH_BLOCK(s, 1); ***/
20423 flush_block_only(s, true);
20424 if (s.strm.avail_out === 0) {
20425 return BS_FINISH_STARTED;
20426 }
20427 /***/
20428 return BS_FINISH_DONE;
20429 }
20430 if (s.last_lit) {
20431 /*** FLUSH_BLOCK(s, 0); ***/
20432 flush_block_only(s, false);
20433 if (s.strm.avail_out === 0) {
20434 return BS_NEED_MORE;
20435 }
20436 /***/
20437 }
20438 return BS_BLOCK_DONE;
20439}
20440
20441/* ===========================================================================
20442 * Same as above, but achieves better compression. We use a lazy
20443 * evaluation for matches: a match is finally adopted only if there is
20444 * no better match at the next window position.
20445 */
20446function deflate_slow(s, flush) {
20447 let hash_head; /* head of hash chain */
20448 let bflush; /* set if current block must be flushed */
20449
20450 let max_insert;
20451
20452 /* Process the input block. */
20453 for (; ;) {
20454 /* Make sure that we always have enough lookahead, except
20455 * at the end of the input file. We need MAX_MATCH bytes
20456 * for the next match, plus MIN_MATCH bytes to insert the
20457 * string following the next match.
20458 */
20459 if (s.lookahead < MIN_LOOKAHEAD) {
20460 fill_window(s);
20461 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
20462 return BS_NEED_MORE;
20463 }
20464 if (s.lookahead === 0) { break; } /* flush the current block */
20465 }
20466
20467 /* Insert the string window[strstart .. strstart+2] in the
20468 * dictionary, and set hash_head to the head of the hash chain:
20469 */
20470 hash_head = 0/*NIL*/;
20471 if (s.lookahead >= MIN_MATCH$1) {
20472 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
20473 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
20474 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
20475 s.head[s.ins_h] = s.strstart;
20476 /***/
20477 }
20478
20479 /* Find the longest match, discarding those <= prev_length.
20480 */
20481 s.prev_length = s.match_length;
20482 s.prev_match = s.match_start;
20483 s.match_length = MIN_MATCH$1 - 1;
20484
20485 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
20486 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
20487 /* To simplify the code, we prevent matches with the string
20488 * of window index 0 (in particular we have to avoid a match
20489 * of the string with itself at the start of the input file).
20490 */
20491 s.match_length = longest_match(s, hash_head);
20492 /* longest_match() sets match_start */
20493
20494 if (s.match_length <= 5 &&
20495 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
20496
20497 /* If prev_match is also MIN_MATCH, match_start is garbage
20498 * but we will ignore the current match anyway.
20499 */
20500 s.match_length = MIN_MATCH$1 - 1;
20501 }
20502 }
20503 /* If there was a match at the previous step and the current
20504 * match is not better, output the previous match:
20505 */
20506 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
20507 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
20508 /* Do not insert strings in hash table beyond this. */
20509
20510 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
20511
20512 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
20513 s.prev_length - MIN_MATCH, bflush);***/
20514 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
20515 /* Insert in hash table all strings up to the end of the match.
20516 * strstart-1 and strstart are already inserted. If there is not
20517 * enough lookahead, the last two strings are not inserted in
20518 * the hash table.
20519 */
20520 s.lookahead -= s.prev_length - 1;
20521 s.prev_length -= 2;
20522 do {
20523 if (++s.strstart <= max_insert) {
20524 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
20525 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
20526 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
20527 s.head[s.ins_h] = s.strstart;
20528 /***/
20529 }
20530 } while (--s.prev_length !== 0);
20531 s.match_available = 0;
20532 s.match_length = MIN_MATCH$1 - 1;
20533 s.strstart++;
20534
20535 if (bflush) {
20536 /*** FLUSH_BLOCK(s, 0); ***/
20537 flush_block_only(s, false);
20538 if (s.strm.avail_out === 0) {
20539 return BS_NEED_MORE;
20540 }
20541 /***/
20542 }
20543
20544 } else if (s.match_available) {
20545 /* If there was no match at the previous position, output a
20546 * single literal. If there was a match but the current match
20547 * is longer, truncate the previous match to a single literal.
20548 */
20549 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
20550 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
20551 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
20552
20553 if (bflush) {
20554 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
20555 flush_block_only(s, false);
20556 /***/
20557 }
20558 s.strstart++;
20559 s.lookahead--;
20560 if (s.strm.avail_out === 0) {
20561 return BS_NEED_MORE;
20562 }
20563 } else {
20564 /* There is no previous match to compare with, wait for
20565 * the next step to decide.
20566 */
20567 s.match_available = 1;
20568 s.strstart++;
20569 s.lookahead--;
20570 }
20571 }
20572 //Assert (flush != Z_NO_FLUSH, "no flush?");
20573 if (s.match_available) {
20574 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
20575 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
20576 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
20577
20578 s.match_available = 0;
20579 }
20580 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
20581 if (flush === Z_FINISH) {
20582 /*** FLUSH_BLOCK(s, 1); ***/
20583 flush_block_only(s, true);
20584 if (s.strm.avail_out === 0) {
20585 return BS_FINISH_STARTED;
20586 }
20587 /***/
20588 return BS_FINISH_DONE;
20589 }
20590 if (s.last_lit) {
20591 /*** FLUSH_BLOCK(s, 0); ***/
20592 flush_block_only(s, false);
20593 if (s.strm.avail_out === 0) {
20594 return BS_NEED_MORE;
20595 }
20596 /***/
20597 }
20598
20599 return BS_BLOCK_DONE;
20600}
20601
20602
20603/* ===========================================================================
20604 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
20605 * one. Do not maintain a hash table. (It will be regenerated if this run of
20606 * deflate switches away from Z_RLE.)
20607 */
20608function deflate_rle(s, flush) {
20609 let bflush; /* set if current block must be flushed */
20610 let prev; /* byte at distance one to match */
20611 let scan, strend; /* scan goes up to strend for length of run */
20612
20613 const _win = s.window;
20614
20615 for (; ;) {
20616 /* Make sure that we always have enough lookahead, except
20617 * at the end of the input file. We need MAX_MATCH bytes
20618 * for the longest run, plus one for the unrolled loop.
20619 */
20620 if (s.lookahead <= MAX_MATCH$1) {
20621 fill_window(s);
20622 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
20623 return BS_NEED_MORE;
20624 }
20625 if (s.lookahead === 0) { break; } /* flush the current block */
20626 }
20627
20628 /* See how many times the previous byte repeats */
20629 s.match_length = 0;
20630 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
20631 scan = s.strstart - 1;
20632 prev = _win[scan];
20633 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
20634 strend = s.strstart + MAX_MATCH$1;
20635 do {
20636 /*jshint noempty:false*/
20637 } while (prev === _win[++scan] && prev === _win[++scan] &&
20638 prev === _win[++scan] && prev === _win[++scan] &&
20639 prev === _win[++scan] && prev === _win[++scan] &&
20640 prev === _win[++scan] && prev === _win[++scan] &&
20641 scan < strend);
20642 s.match_length = MAX_MATCH$1 - (strend - scan);
20643 if (s.match_length > s.lookahead) {
20644 s.match_length = s.lookahead;
20645 }
20646 }
20647 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
20648 }
20649
20650 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
20651 if (s.match_length >= MIN_MATCH$1) {
20652 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
20653
20654 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
20655 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
20656
20657 s.lookahead -= s.match_length;
20658 s.strstart += s.match_length;
20659 s.match_length = 0;
20660 } else {
20661 /* No match, output a literal byte */
20662 //Tracevv((stderr,"%c", s->window[s->strstart]));
20663 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
20664 bflush = _tr_tally(s, 0, s.window[s.strstart]);
20665
20666 s.lookahead--;
20667 s.strstart++;
20668 }
20669 if (bflush) {
20670 /*** FLUSH_BLOCK(s, 0); ***/
20671 flush_block_only(s, false);
20672 if (s.strm.avail_out === 0) {
20673 return BS_NEED_MORE;
20674 }
20675 /***/
20676 }
20677 }
20678 s.insert = 0;
20679 if (flush === Z_FINISH) {
20680 /*** FLUSH_BLOCK(s, 1); ***/
20681 flush_block_only(s, true);
20682 if (s.strm.avail_out === 0) {
20683 return BS_FINISH_STARTED;
20684 }
20685 /***/
20686 return BS_FINISH_DONE;
20687 }
20688 if (s.last_lit) {
20689 /*** FLUSH_BLOCK(s, 0); ***/
20690 flush_block_only(s, false);
20691 if (s.strm.avail_out === 0) {
20692 return BS_NEED_MORE;
20693 }
20694 /***/
20695 }
20696 return BS_BLOCK_DONE;
20697}
20698
20699/* ===========================================================================
20700 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
20701 * (It will be regenerated if this run of deflate switches away from Huffman.)
20702 */
20703function deflate_huff(s, flush) {
20704 let bflush; /* set if current block must be flushed */
20705
20706 for (; ;) {
20707 /* Make sure that we have a literal to write. */
20708 if (s.lookahead === 0) {
20709 fill_window(s);
20710 if (s.lookahead === 0) {
20711 if (flush === Z_NO_FLUSH) {
20712 return BS_NEED_MORE;
20713 }
20714 break; /* flush the current block */
20715 }
20716 }
20717
20718 /* Output a literal byte */
20719 s.match_length = 0;
20720 //Tracevv((stderr,"%c", s->window[s->strstart]));
20721 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
20722 bflush = _tr_tally(s, 0, s.window[s.strstart]);
20723 s.lookahead--;
20724 s.strstart++;
20725 if (bflush) {
20726 /*** FLUSH_BLOCK(s, 0); ***/
20727 flush_block_only(s, false);
20728 if (s.strm.avail_out === 0) {
20729 return BS_NEED_MORE;
20730 }
20731 /***/
20732 }
20733 }
20734 s.insert = 0;
20735 if (flush === Z_FINISH) {
20736 /*** FLUSH_BLOCK(s, 1); ***/
20737 flush_block_only(s, true);
20738 if (s.strm.avail_out === 0) {
20739 return BS_FINISH_STARTED;
20740 }
20741 /***/
20742 return BS_FINISH_DONE;
20743 }
20744 if (s.last_lit) {
20745 /*** FLUSH_BLOCK(s, 0); ***/
20746 flush_block_only(s, false);
20747 if (s.strm.avail_out === 0) {
20748 return BS_NEED_MORE;
20749 }
20750 /***/
20751 }
20752 return BS_BLOCK_DONE;
20753}
20754
20755/* Values for max_lazy_match, good_match and max_chain_length, depending on
20756 * the desired pack level (0..9). The values given below have been tuned to
20757 * exclude worst case performance for pathological files. Better values may be
20758 * found for specific files.
20759 */
20760class Config {
20761 constructor(good_length, max_lazy, nice_length, max_chain, func) {
20762 this.good_length = good_length;
20763 this.max_lazy = max_lazy;
20764 this.nice_length = nice_length;
20765 this.max_chain = max_chain;
20766 this.func = func;
20767 }
20768}
20769const configuration_table = [
20770 /* good lazy nice chain */
20771 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
20772 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
20773 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
20774 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
20775
20776 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
20777 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
20778 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
20779 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
20780 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
20781 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
20782];
20783
20784
20785/* ===========================================================================
20786 * Initialize the "longest match" routines for a new zlib stream
20787 */
20788function lm_init(s) {
20789 s.window_size = 2 * s.w_size;
20790
20791 /*** CLEAR_HASH(s); ***/
20792 zero$2(s.head); // Fill with NIL (= 0);
20793
20794 /* Set the default configuration parameters:
20795 */
20796 s.max_lazy_match = configuration_table[s.level].max_lazy;
20797 s.good_match = configuration_table[s.level].good_length;
20798 s.nice_match = configuration_table[s.level].nice_length;
20799 s.max_chain_length = configuration_table[s.level].max_chain;
20800
20801 s.strstart = 0;
20802 s.block_start = 0;
20803 s.lookahead = 0;
20804 s.insert = 0;
20805 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
20806 s.match_available = 0;
20807 s.ins_h = 0;
20808}
20809
20810class DeflateState {
20811 constructor() {
20812 this.strm = null; /* pointer back to this zlib stream */
20813 this.status = 0; /* as the name implies */
20814 this.pending_buf = null; /* output still pending */
20815 this.pending_buf_size = 0; /* size of pending_buf */
20816 this.pending_out = 0; /* next pending byte to output to the stream */
20817 this.pending = 0; /* nb of bytes in the pending buffer */
20818 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
20819 this.gzhead = null; /* gzip header information to write */
20820 this.gzindex = 0; /* where in extra, name, or comment */
20821 this.method = Z_DEFLATED; /* can only be DEFLATED */
20822 this.last_flush = -1; /* value of flush param for previous deflate call */
20823
20824 this.w_size = 0; /* LZ77 window size (32K by default) */
20825 this.w_bits = 0; /* log2(w_size) (8..16) */
20826 this.w_mask = 0; /* w_size - 1 */
20827
20828 this.window = null;
20829 /* Sliding window. Input bytes are read into the second half of the window,
20830 * and move to the first half later to keep a dictionary of at least wSize
20831 * bytes. With this organization, matches are limited to a distance of
20832 * wSize-MAX_MATCH bytes, but this ensures that IO is always
20833 * performed with a length multiple of the block size.
20834 */
20835
20836 this.window_size = 0;
20837 /* Actual size of window: 2*wSize, except when the user input buffer
20838 * is directly used as sliding window.
20839 */
20840
20841 this.prev = null;
20842 /* Link to older string with same hash index. To limit the size of this
20843 * array to 64K, this link is maintained only for the last 32K strings.
20844 * An index in this array is thus a window index modulo 32K.
20845 */
20846
20847 this.head = null; /* Heads of the hash chains or NIL. */
20848
20849 this.ins_h = 0; /* hash index of string to be inserted */
20850 this.hash_size = 0; /* number of elements in hash table */
20851 this.hash_bits = 0; /* log2(hash_size) */
20852 this.hash_mask = 0; /* hash_size-1 */
20853
20854 this.hash_shift = 0;
20855 /* Number of bits by which ins_h must be shifted at each input
20856 * step. It must be such that after MIN_MATCH steps, the oldest
20857 * byte no longer takes part in the hash key, that is:
20858 * hash_shift * MIN_MATCH >= hash_bits
20859 */
20860
20861 this.block_start = 0;
20862 /* Window position at the beginning of the current output block. Gets
20863 * negative when the window is moved backwards.
20864 */
20865
20866 this.match_length = 0; /* length of best match */
20867 this.prev_match = 0; /* previous match */
20868 this.match_available = 0; /* set if previous match exists */
20869 this.strstart = 0; /* start of string to insert */
20870 this.match_start = 0; /* start of matching string */
20871 this.lookahead = 0; /* number of valid bytes ahead in window */
20872
20873 this.prev_length = 0;
20874 /* Length of the best match at previous step. Matches not greater than this
20875 * are discarded. This is used in the lazy match evaluation.
20876 */
20877
20878 this.max_chain_length = 0;
20879 /* To speed up deflation, hash chains are never searched beyond this
20880 * length. A higher limit improves compression ratio but degrades the
20881 * speed.
20882 */
20883
20884 this.max_lazy_match = 0;
20885 /* Attempt to find a better match only when the current match is strictly
20886 * smaller than this value. This mechanism is used only for compression
20887 * levels >= 4.
20888 */
20889 // That's alias to max_lazy_match, don't use directly
20890 //this.max_insert_length = 0;
20891 /* Insert new strings in the hash table only if the match length is not
20892 * greater than this length. This saves time but degrades compression.
20893 * max_insert_length is used only for compression levels <= 3.
20894 */
20895
20896 this.level = 0; /* compression level (1..9) */
20897 this.strategy = 0; /* favor or force Huffman coding*/
20898
20899 this.good_match = 0;
20900 /* Use a faster search when the previous match is longer than this */
20901
20902 this.nice_match = 0; /* Stop searching when current match exceeds this */
20903
20904 /* used by trees.c: */
20905
20906 /* Didn't use ct_data typedef below to suppress compiler warning */
20907
20908 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
20909 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
20910 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
20911
20912 // Use flat array of DOUBLE size, with interleaved fata,
20913 // because JS does not support effective
20914 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
20915 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
20916 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
20917 zero$2(this.dyn_ltree);
20918 zero$2(this.dyn_dtree);
20919 zero$2(this.bl_tree);
20920
20921 this.l_desc = null; /* desc. for literal tree */
20922 this.d_desc = null; /* desc. for distance tree */
20923 this.bl_desc = null; /* desc. for bit length tree */
20924
20925 //ush bl_count[MAX_BITS+1];
20926 this.bl_count = new Buf16(MAX_BITS$1 + 1);
20927 /* number of codes at each bit length for an optimal tree */
20928
20929 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
20930 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
20931 zero$2(this.heap);
20932
20933 this.heap_len = 0; /* number of elements in the heap */
20934 this.heap_max = 0; /* element of largest frequency */
20935 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
20936 * The same heap array is used to build all trees.
20937 */
20938
20939 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
20940 zero$2(this.depth);
20941 /* Depth of each subtree used as tie breaker for trees of equal frequency
20942 */
20943
20944 this.l_buf = 0; /* buffer index for literals or lengths */
20945
20946 this.lit_bufsize = 0;
20947 /* Size of match buffer for literals/lengths. There are 4 reasons for
20948 * limiting lit_bufsize to 64K:
20949 * - frequencies can be kept in 16 bit counters
20950 * - if compression is not successful for the first block, all input
20951 * data is still in the window so we can still emit a stored block even
20952 * when input comes from standard input. (This can also be done for
20953 * all blocks if lit_bufsize is not greater than 32K.)
20954 * - if compression is not successful for a file smaller than 64K, we can
20955 * even emit a stored file instead of a stored block (saving 5 bytes).
20956 * This is applicable only for zip (not gzip or zlib).
20957 * - creating new Huffman trees less frequently may not provide fast
20958 * adaptation to changes in the input data statistics. (Take for
20959 * example a binary file with poorly compressible code followed by
20960 * a highly compressible string table.) Smaller buffer sizes give
20961 * fast adaptation but have of course the overhead of transmitting
20962 * trees more frequently.
20963 * - I can't count above 4
20964 */
20965
20966 this.last_lit = 0; /* running index in l_buf */
20967
20968 this.d_buf = 0;
20969 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
20970 * the same number of elements. To use different lengths, an extra flag
20971 * array would be necessary.
20972 */
20973
20974 this.opt_len = 0; /* bit length of current block with optimal trees */
20975 this.static_len = 0; /* bit length of current block with static trees */
20976 this.matches = 0; /* number of string matches in current block */
20977 this.insert = 0; /* bytes at end of window left to insert */
20978
20979
20980 this.bi_buf = 0;
20981 /* Output buffer. bits are inserted starting at the bottom (least
20982 * significant bits).
20983 */
20984 this.bi_valid = 0;
20985 /* Number of valid bits in bi_buf. All bits above the last valid bit
20986 * are always zero.
20987 */
20988
20989 // Used for window memory init. We safely ignore it for JS. That makes
20990 // sense only for pointers and memory check tools.
20991 //this.high_water = 0;
20992 /* High water mark offset in window for initialized bytes -- bytes above
20993 * this are set to zero in order to avoid memory check warnings when
20994 * longest match routines access bytes past the input. This is then
20995 * updated to the new high water mark.
20996 */
20997 }
20998}
20999
21000function deflateResetKeep(strm) {
21001 let s;
21002
21003 if (!strm || !strm.state) {
21004 return err(strm, Z_STREAM_ERROR);
21005 }
21006
21007 strm.total_in = strm.total_out = 0;
21008 strm.data_type = Z_UNKNOWN;
21009
21010 s = strm.state;
21011 s.pending = 0;
21012 s.pending_out = 0;
21013
21014 if (s.wrap < 0) {
21015 s.wrap = -s.wrap;
21016 /* was made negative by deflate(..., Z_FINISH); */
21017 }
21018 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
21019 strm.adler = (s.wrap === 2) ?
21020 0 // crc32(0, Z_NULL, 0)
21021 :
21022 1; // adler32(0, Z_NULL, 0)
21023 s.last_flush = Z_NO_FLUSH;
21024 _tr_init(s);
21025 return Z_OK;
21026}
21027
21028
21029function deflateReset(strm) {
21030 const ret = deflateResetKeep(strm);
21031 if (ret === Z_OK) {
21032 lm_init(strm.state);
21033 }
21034 return ret;
21035}
21036
21037
21038function deflateSetHeader(strm, head) {
21039 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
21040 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
21041 strm.state.gzhead = head;
21042 return Z_OK;
21043}
21044
21045
21046function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
21047 if (!strm) { // === Z_NULL
21048 return Z_STREAM_ERROR;
21049 }
21050 let wrap = 1;
21051
21052 if (level === Z_DEFAULT_COMPRESSION) {
21053 level = 6;
21054 }
21055
21056 if (windowBits < 0) { /* suppress zlib wrapper */
21057 wrap = 0;
21058 windowBits = -windowBits;
21059 }
21060
21061 else if (windowBits > 15) {
21062 wrap = 2; /* write gzip wrapper instead */
21063 windowBits -= 16;
21064 }
21065
21066
21067 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
21068 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
21069 strategy < 0 || strategy > Z_FIXED) {
21070 return err(strm, Z_STREAM_ERROR);
21071 }
21072
21073
21074 if (windowBits === 8) {
21075 windowBits = 9;
21076 }
21077 /* until 256-byte window bug fixed */
21078
21079 const s = new DeflateState();
21080
21081 strm.state = s;
21082 s.strm = strm;
21083
21084 s.wrap = wrap;
21085 s.gzhead = null;
21086 s.w_bits = windowBits;
21087 s.w_size = 1 << s.w_bits;
21088 s.w_mask = s.w_size - 1;
21089
21090 s.hash_bits = memLevel + 7;
21091 s.hash_size = 1 << s.hash_bits;
21092 s.hash_mask = s.hash_size - 1;
21093 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
21094 s.window = new Buf8(s.w_size * 2);
21095 s.head = new Buf16(s.hash_size);
21096 s.prev = new Buf16(s.w_size);
21097
21098 // Don't need mem init magic for JS.
21099 //s.high_water = 0; /* nothing written to s->window yet */
21100
21101 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
21102
21103 s.pending_buf_size = s.lit_bufsize * 4;
21104
21105 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
21106 //s->pending_buf = (uchf *) overlay;
21107 s.pending_buf = new Buf8(s.pending_buf_size);
21108
21109 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
21110 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
21111 s.d_buf = 1 * s.lit_bufsize;
21112
21113 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
21114 s.l_buf = (1 + 2) * s.lit_bufsize;
21115
21116 s.level = level;
21117 s.strategy = strategy;
21118 s.method = method;
21119
21120 return deflateReset(strm);
21121}
21122
21123
21124function deflate(strm, flush) {
21125 let old_flush, s;
21126 let beg, val; // for gzip header write only
21127
21128 if (!strm || !strm.state ||
21129 flush > Z_BLOCK || flush < 0) {
21130 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
21131 }
21132
21133 s = strm.state;
21134
21135 if (!strm.output ||
21136 (!strm.input && strm.avail_in !== 0) ||
21137 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
21138 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
21139 }
21140
21141 s.strm = strm; /* just in case */
21142 old_flush = s.last_flush;
21143 s.last_flush = flush;
21144
21145 /* Write the header */
21146 if (s.status === INIT_STATE) {
21147
21148 if (s.wrap === 2) { // GZIP header
21149 strm.adler = 0; //crc32(0L, Z_NULL, 0);
21150 put_byte(s, 31);
21151 put_byte(s, 139);
21152 put_byte(s, 8);
21153 if (!s.gzhead) { // s->gzhead == Z_NULL
21154 put_byte(s, 0);
21155 put_byte(s, 0);
21156 put_byte(s, 0);
21157 put_byte(s, 0);
21158 put_byte(s, 0);
21159 put_byte(s, s.level === 9 ? 2 :
21160 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
21161 4 : 0));
21162 put_byte(s, OS_CODE);
21163 s.status = BUSY_STATE;
21164 }
21165 else {
21166 put_byte(s, (s.gzhead.text ? 1 : 0) +
21167 (s.gzhead.hcrc ? 2 : 0) +
21168 (!s.gzhead.extra ? 0 : 4) +
21169 (!s.gzhead.name ? 0 : 8) +
21170 (!s.gzhead.comment ? 0 : 16)
21171 );
21172 put_byte(s, s.gzhead.time & 0xff);
21173 put_byte(s, (s.gzhead.time >> 8) & 0xff);
21174 put_byte(s, (s.gzhead.time >> 16) & 0xff);
21175 put_byte(s, (s.gzhead.time >> 24) & 0xff);
21176 put_byte(s, s.level === 9 ? 2 :
21177 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
21178 4 : 0));
21179 put_byte(s, s.gzhead.os & 0xff);
21180 if (s.gzhead.extra && s.gzhead.extra.length) {
21181 put_byte(s, s.gzhead.extra.length & 0xff);
21182 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
21183 }
21184 if (s.gzhead.hcrc) {
21185 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
21186 }
21187 s.gzindex = 0;
21188 s.status = EXTRA_STATE;
21189 }
21190 }
21191 else // DEFLATE header
21192 {
21193 let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
21194 let level_flags = -1;
21195
21196 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
21197 level_flags = 0;
21198 } else if (s.level < 6) {
21199 level_flags = 1;
21200 } else if (s.level === 6) {
21201 level_flags = 2;
21202 } else {
21203 level_flags = 3;
21204 }
21205 header |= (level_flags << 6);
21206 if (s.strstart !== 0) { header |= PRESET_DICT; }
21207 header += 31 - (header % 31);
21208
21209 s.status = BUSY_STATE;
21210 putShortMSB(s, header);
21211
21212 /* Save the adler32 of the preset dictionary: */
21213 if (s.strstart !== 0) {
21214 putShortMSB(s, strm.adler >>> 16);
21215 putShortMSB(s, strm.adler & 0xffff);
21216 }
21217 strm.adler = 1; // adler32(0L, Z_NULL, 0);
21218 }
21219 }
21220
21221 //#ifdef GZIP
21222 if (s.status === EXTRA_STATE) {
21223 if (s.gzhead.extra/* != Z_NULL*/) {
21224 beg = s.pending; /* start of bytes to update crc */
21225
21226 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
21227 if (s.pending === s.pending_buf_size) {
21228 if (s.gzhead.hcrc && s.pending > beg) {
21229 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21230 }
21231 flush_pending(strm);
21232 beg = s.pending;
21233 if (s.pending === s.pending_buf_size) {
21234 break;
21235 }
21236 }
21237 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
21238 s.gzindex++;
21239 }
21240 if (s.gzhead.hcrc && s.pending > beg) {
21241 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21242 }
21243 if (s.gzindex === s.gzhead.extra.length) {
21244 s.gzindex = 0;
21245 s.status = NAME_STATE;
21246 }
21247 }
21248 else {
21249 s.status = NAME_STATE;
21250 }
21251 }
21252 if (s.status === NAME_STATE) {
21253 if (s.gzhead.name/* != Z_NULL*/) {
21254 beg = s.pending; /* start of bytes to update crc */
21255 //int val;
21256
21257 do {
21258 if (s.pending === s.pending_buf_size) {
21259 if (s.gzhead.hcrc && s.pending > beg) {
21260 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21261 }
21262 flush_pending(strm);
21263 beg = s.pending;
21264 if (s.pending === s.pending_buf_size) {
21265 val = 1;
21266 break;
21267 }
21268 }
21269 // JS specific: little magic to add zero terminator to end of string
21270 if (s.gzindex < s.gzhead.name.length) {
21271 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
21272 } else {
21273 val = 0;
21274 }
21275 put_byte(s, val);
21276 } while (val !== 0);
21277
21278 if (s.gzhead.hcrc && s.pending > beg) {
21279 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21280 }
21281 if (val === 0) {
21282 s.gzindex = 0;
21283 s.status = COMMENT_STATE;
21284 }
21285 }
21286 else {
21287 s.status = COMMENT_STATE;
21288 }
21289 }
21290 if (s.status === COMMENT_STATE) {
21291 if (s.gzhead.comment/* != Z_NULL*/) {
21292 beg = s.pending; /* start of bytes to update crc */
21293 //int val;
21294
21295 do {
21296 if (s.pending === s.pending_buf_size) {
21297 if (s.gzhead.hcrc && s.pending > beg) {
21298 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21299 }
21300 flush_pending(strm);
21301 beg = s.pending;
21302 if (s.pending === s.pending_buf_size) {
21303 val = 1;
21304 break;
21305 }
21306 }
21307 // JS specific: little magic to add zero terminator to end of string
21308 if (s.gzindex < s.gzhead.comment.length) {
21309 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
21310 } else {
21311 val = 0;
21312 }
21313 put_byte(s, val);
21314 } while (val !== 0);
21315
21316 if (s.gzhead.hcrc && s.pending > beg) {
21317 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
21318 }
21319 if (val === 0) {
21320 s.status = HCRC_STATE;
21321 }
21322 }
21323 else {
21324 s.status = HCRC_STATE;
21325 }
21326 }
21327 if (s.status === HCRC_STATE) {
21328 if (s.gzhead.hcrc) {
21329 if (s.pending + 2 > s.pending_buf_size) {
21330 flush_pending(strm);
21331 }
21332 if (s.pending + 2 <= s.pending_buf_size) {
21333 put_byte(s, strm.adler & 0xff);
21334 put_byte(s, (strm.adler >> 8) & 0xff);
21335 strm.adler = 0; //crc32(0L, Z_NULL, 0);
21336 s.status = BUSY_STATE;
21337 }
21338 }
21339 else {
21340 s.status = BUSY_STATE;
21341 }
21342 }
21343 //#endif
21344
21345 /* Flush as much pending output as possible */
21346 if (s.pending !== 0) {
21347 flush_pending(strm);
21348 if (strm.avail_out === 0) {
21349 /* Since avail_out is 0, deflate will be called again with
21350 * more output space, but possibly with both pending and
21351 * avail_in equal to zero. There won't be anything to do,
21352 * but this is not an error situation so make sure we
21353 * return OK instead of BUF_ERROR at next call of deflate:
21354 */
21355 s.last_flush = -1;
21356 return Z_OK;
21357 }
21358
21359 /* Make sure there is something to do and avoid duplicate consecutive
21360 * flushes. For repeated and useless calls with Z_FINISH, we keep
21361 * returning Z_STREAM_END instead of Z_BUF_ERROR.
21362 */
21363 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
21364 flush !== Z_FINISH) {
21365 return err(strm, Z_BUF_ERROR);
21366 }
21367
21368 /* User must not provide more input after the first FINISH: */
21369 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
21370 return err(strm, Z_BUF_ERROR);
21371 }
21372
21373 /* Start a new block or continue the current one.
21374 */
21375 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
21376 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
21377 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
21378 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
21379 configuration_table[s.level].func(s, flush));
21380
21381 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
21382 s.status = FINISH_STATE;
21383 }
21384 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
21385 if (strm.avail_out === 0) {
21386 s.last_flush = -1;
21387 /* avoid BUF_ERROR next call, see above */
21388 }
21389 return Z_OK;
21390 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
21391 * of deflate should use the same flush parameter to make sure
21392 * that the flush is complete. So we don't have to output an
21393 * empty block here, this will be done at next call. This also
21394 * ensures that for a very small output buffer, we emit at most
21395 * one empty block.
21396 */
21397 }
21398 if (bstate === BS_BLOCK_DONE) {
21399 if (flush === Z_PARTIAL_FLUSH) {
21400 _tr_align(s);
21401 }
21402 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
21403
21404 _tr_stored_block(s, 0, 0, false);
21405 /* For a full flush, this empty block will be recognized
21406 * as a special marker by inflate_sync().
21407 */
21408 if (flush === Z_FULL_FLUSH) {
21409 /*** CLEAR_HASH(s); ***/ /* forget history */
21410 zero$2(s.head); // Fill with NIL (= 0);
21411
21412 if (s.lookahead === 0) {
21413 s.strstart = 0;
21414 s.block_start = 0;
21415 s.insert = 0;
21416 }
21417 }
21418 }
21419 flush_pending(strm);
21420 if (strm.avail_out === 0) {
21421 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
21422 return Z_OK;
21423 }
21424 }
21425 }
21426 //Assert(strm->avail_out > 0, "bug2");
21427 //if (strm.avail_out <= 0) { throw new Error("bug2");}
21428
21429 if (flush !== Z_FINISH) { return Z_OK; }
21430 if (s.wrap <= 0) { return Z_STREAM_END; }
21431
21432 /* Write the trailer */
21433 if (s.wrap === 2) {
21434 put_byte(s, strm.adler & 0xff);
21435 put_byte(s, (strm.adler >> 8) & 0xff);
21436 put_byte(s, (strm.adler >> 16) & 0xff);
21437 put_byte(s, (strm.adler >> 24) & 0xff);
21438 put_byte(s, strm.total_in & 0xff);
21439 put_byte(s, (strm.total_in >> 8) & 0xff);
21440 put_byte(s, (strm.total_in >> 16) & 0xff);
21441 put_byte(s, (strm.total_in >> 24) & 0xff);
21442 }
21443 else {
21444 putShortMSB(s, strm.adler >>> 16);
21445 putShortMSB(s, strm.adler & 0xffff);
21446 }
21447
21448 flush_pending(strm);
21449 /* If avail_out is zero, the application will call deflate again
21450 * to flush the rest.
21451 */
21452 if (s.wrap > 0) { s.wrap = -s.wrap; }
21453 /* write the trailer only once! */
21454 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
21455}
21456
21457function deflateEnd(strm) {
21458 let status;
21459
21460 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
21461 return Z_STREAM_ERROR;
21462 }
21463
21464 status = strm.state.status;
21465 if (status !== INIT_STATE &&
21466 status !== EXTRA_STATE &&
21467 status !== NAME_STATE &&
21468 status !== COMMENT_STATE &&
21469 status !== HCRC_STATE &&
21470 status !== BUSY_STATE &&
21471 status !== FINISH_STATE
21472 ) {
21473 return err(strm, Z_STREAM_ERROR);
21474 }
21475
21476 strm.state = null;
21477
21478 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
21479}
21480
21481
21482/* =========================================================================
21483 * Initializes the compression dictionary from the given byte
21484 * sequence without producing any compressed output.
21485 */
21486function deflateSetDictionary(strm, dictionary) {
21487 const dictLength = dictionary.length;
21488
21489 let s;
21490 let str, n;
21491 let wrap;
21492 let avail;
21493 let next;
21494 let input;
21495 let tmpDict;
21496
21497 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
21498 return Z_STREAM_ERROR;
21499 }
21500
21501 s = strm.state;
21502 wrap = s.wrap;
21503
21504 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
21505 return Z_STREAM_ERROR;
21506 }
21507
21508 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
21509 if (wrap === 1) {
21510 /* adler32(strm->adler, dictionary, dictLength); */
21511 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
21512 }
21513
21514 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
21515
21516 /* if dictionary would fill window, just replace the history */
21517 if (dictLength >= s.w_size) {
21518 if (wrap === 0) { /* already empty otherwise */
21519 /*** CLEAR_HASH(s); ***/
21520 zero$2(s.head); // Fill with NIL (= 0);
21521 s.strstart = 0;
21522 s.block_start = 0;
21523 s.insert = 0;
21524 }
21525 /* use the tail */
21526 // dictionary = dictionary.slice(dictLength - s.w_size);
21527 tmpDict = new Buf8(s.w_size);
21528 arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
21529 dictionary = tmpDict;
21530 dictLength = s.w_size;
21531 }
21532 /* insert dictionary into window and hash */
21533 avail = strm.avail_in;
21534 next = strm.next_in;
21535 input = strm.input;
21536 strm.avail_in = dictLength;
21537 strm.next_in = 0;
21538 strm.input = dictionary;
21539 fill_window(s);
21540 while (s.lookahead >= MIN_MATCH$1) {
21541 str = s.strstart;
21542 n = s.lookahead - (MIN_MATCH$1 - 1);
21543 do {
21544 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
21545 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
21546
21547 s.prev[str & s.w_mask] = s.head[s.ins_h];
21548
21549 s.head[s.ins_h] = str;
21550 str++;
21551 } while (--n);
21552 s.strstart = str;
21553 s.lookahead = MIN_MATCH$1 - 1;
21554 fill_window(s);
21555 }
21556 s.strstart += s.lookahead;
21557 s.block_start = s.strstart;
21558 s.insert = s.lookahead;
21559 s.lookahead = 0;
21560 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
21561 s.match_available = 0;
21562 strm.next_in = next;
21563 strm.input = input;
21564 strm.avail_in = avail;
21565 s.wrap = wrap;
21566 return Z_OK;
21567}
21568
21569/* Not implemented
21570exports.deflateBound = deflateBound;
21571exports.deflateCopy = deflateCopy;
21572exports.deflateParams = deflateParams;
21573exports.deflatePending = deflatePending;
21574exports.deflatePrime = deflatePrime;
21575exports.deflateTune = deflateTune;
21576*/
21577
21578// String encode/decode helpers
21579
21580try {
21581 String.fromCharCode.apply(null, [ 0 ]);
21582} catch (__) {
21583}
21584try {
21585 String.fromCharCode.apply(null, new Uint8Array(1));
21586} catch (__) {
21587}
21588
21589
21590// Table with utf8 lengths (calculated by first byte of sequence)
21591// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
21592// because max possible codepoint is 0x10ffff
21593const _utf8len = new Buf8(256);
21594for (let q = 0; q < 256; q++) {
21595 _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
21596}
21597_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
21598
21599
21600// convert string to array (typed, when possible)
21601function string2buf (str) {
21602 let c, c2, m_pos, i, buf_len = 0;
21603 const str_len = str.length;
21604
21605 // count binary size
21606 for (m_pos = 0; m_pos < str_len; m_pos++) {
21607 c = str.charCodeAt(m_pos);
21608 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
21609 c2 = str.charCodeAt(m_pos + 1);
21610 if ((c2 & 0xfc00) === 0xdc00) {
21611 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
21612 m_pos++;
21613 }
21614 }
21615 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
21616 }
21617
21618 // allocate buffer
21619 const buf = new Buf8(buf_len);
21620
21621 // convert
21622 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
21623 c = str.charCodeAt(m_pos);
21624 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
21625 c2 = str.charCodeAt(m_pos + 1);
21626 if ((c2 & 0xfc00) === 0xdc00) {
21627 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
21628 m_pos++;
21629 }
21630 }
21631 if (c < 0x80) {
21632 /* one byte */
21633 buf[i++] = c;
21634 } else if (c < 0x800) {
21635 /* two bytes */
21636 buf[i++] = 0xC0 | c >>> 6;
21637 buf[i++] = 0x80 | c & 0x3f;
21638 } else if (c < 0x10000) {
21639 /* three bytes */
21640 buf[i++] = 0xE0 | c >>> 12;
21641 buf[i++] = 0x80 | c >>> 6 & 0x3f;
21642 buf[i++] = 0x80 | c & 0x3f;
21643 } else {
21644 /* four bytes */
21645 buf[i++] = 0xf0 | c >>> 18;
21646 buf[i++] = 0x80 | c >>> 12 & 0x3f;
21647 buf[i++] = 0x80 | c >>> 6 & 0x3f;
21648 buf[i++] = 0x80 | c & 0x3f;
21649 }
21650 }
21651
21652 return buf;
21653}
21654
21655
21656// Convert binary string (typed, when possible)
21657function binstring2buf (str) {
21658 const buf = new Buf8(str.length);
21659 for (let i = 0, len = buf.length; i < len; i++) {
21660 buf[i] = str.charCodeAt(i);
21661 }
21662 return buf;
21663}
21664
21665// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21666// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21667//
21668// This software is provided 'as-is', without any express or implied
21669// warranty. In no event will the authors be held liable for any damages
21670// arising from the use of this software.
21671//
21672// Permission is granted to anyone to use this software for any purpose,
21673// including commercial applications, and to alter it and redistribute it
21674// freely, subject to the following restrictions:
21675//
21676// 1. The origin of this software must not be misrepresented; you must not
21677// claim that you wrote the original software. If you use this software
21678// in a product, an acknowledgment in the product documentation would be
21679// appreciated but is not required.
21680// 2. Altered source versions must be plainly marked as such, and must not be
21681// misrepresented as being the original software.
21682// 3. This notice may not be removed or altered from any source distribution.
21683
21684class ZStream {
21685 constructor() {
21686 /* next input byte */
21687 this.input = null; // JS specific, because we have no pointers
21688 this.next_in = 0;
21689 /* number of bytes available at input */
21690 this.avail_in = 0;
21691 /* total number of input bytes read so far */
21692 this.total_in = 0;
21693 /* next output byte should be put there */
21694 this.output = null; // JS specific, because we have no pointers
21695 this.next_out = 0;
21696 /* remaining free space at output */
21697 this.avail_out = 0;
21698 /* total number of bytes output so far */
21699 this.total_out = 0;
21700 /* last error message, NULL if no error */
21701 this.msg = ''/*Z_NULL*/;
21702 /* not visible by applications */
21703 this.state = null;
21704 /* best guess about the data type: binary or text */
21705 this.data_type = 2/*Z_UNKNOWN*/;
21706 /* adler32 value of the uncompressed data */
21707 this.adler = 0;
21708 }
21709}
21710
21711/* ===========================================================================*/
21712
21713
21714/**
21715 * class Deflate
21716 *
21717 * Generic JS-style wrapper for zlib calls. If you don't need
21718 * streaming behaviour - use more simple functions: [[deflate]],
21719 * [[deflateRaw]] and [[gzip]].
21720 **/
21721
21722/* internal
21723 * Deflate.chunks -> Array
21724 *
21725 * Chunks of output data, if [[Deflate#onData]] not overridden.
21726 **/
21727
21728/**
21729 * Deflate.result -> Uint8Array|Array
21730 *
21731 * Compressed result, generated by default [[Deflate#onData]]
21732 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
21733 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
21734 * push a chunk with explicit flush (call [[Deflate#push]] with
21735 * `Z_SYNC_FLUSH` param).
21736 **/
21737
21738/**
21739 * Deflate.err -> Number
21740 *
21741 * Error code after deflate finished. 0 (Z_OK) on success.
21742 * You will not need it in real life, because deflate errors
21743 * are possible only on wrong options or bad `onData` / `onEnd`
21744 * custom handlers.
21745 **/
21746
21747/**
21748 * Deflate.msg -> String
21749 *
21750 * Error message, if [[Deflate.err]] != 0
21751 **/
21752
21753
21754/**
21755 * new Deflate(options)
21756 * - options (Object): zlib deflate options.
21757 *
21758 * Creates new deflator instance with specified params. Throws exception
21759 * on bad params. Supported options:
21760 *
21761 * - `level`
21762 * - `windowBits`
21763 * - `memLevel`
21764 * - `strategy`
21765 * - `dictionary`
21766 *
21767 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
21768 * for more information on these.
21769 *
21770 * Additional options, for internal needs:
21771 *
21772 * - `chunkSize` - size of generated data chunks (16K by default)
21773 * - `raw` (Boolean) - do raw deflate
21774 * - `gzip` (Boolean) - create gzip wrapper
21775 * - `to` (String) - if equal to 'string', then result will be "binary string"
21776 * (each char code [0..255])
21777 * - `header` (Object) - custom header for gzip
21778 * - `text` (Boolean) - true if compressed data believed to be text
21779 * - `time` (Number) - modification time, unix timestamp
21780 * - `os` (Number) - operation system code
21781 * - `extra` (Array) - array of bytes with extra data (max 65536)
21782 * - `name` (String) - file name (binary string)
21783 * - `comment` (String) - comment (binary string)
21784 * - `hcrc` (Boolean) - true if header crc should be added
21785 *
21786 * ##### Example:
21787 *
21788 * ```javascript
21789 * var pako = require('pako')
21790 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
21791 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
21792 *
21793 * var deflate = new pako.Deflate({ level: 3});
21794 *
21795 * deflate.push(chunk1, false);
21796 * deflate.push(chunk2, true); // true -> last chunk
21797 *
21798 * if (deflate.err) { throw new Error(deflate.err); }
21799 *
21800 * console.log(deflate.result);
21801 * ```
21802 **/
21803
21804class Deflate {
21805 constructor(options) {
21806 this.options = {
21807 level: Z_DEFAULT_COMPRESSION,
21808 method: Z_DEFLATED,
21809 chunkSize: 16384,
21810 windowBits: 15,
21811 memLevel: 8,
21812 strategy: Z_DEFAULT_STRATEGY,
21813 ...(options || {})
21814 };
21815
21816 const opt = this.options;
21817
21818 if (opt.raw && (opt.windowBits > 0)) {
21819 opt.windowBits = -opt.windowBits;
21820 }
21821
21822 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
21823 opt.windowBits += 16;
21824 }
21825
21826 this.err = 0; // error code, if happens (0 = Z_OK)
21827 this.msg = ''; // error message
21828 this.ended = false; // used to avoid multiple onEnd() calls
21829 this.chunks = []; // chunks of compressed data
21830
21831 this.strm = new ZStream();
21832 this.strm.avail_out = 0;
21833
21834 var status = deflateInit2(
21835 this.strm,
21836 opt.level,
21837 opt.method,
21838 opt.windowBits,
21839 opt.memLevel,
21840 opt.strategy
21841 );
21842
21843 if (status !== Z_OK) {
21844 throw new Error(msg[status]);
21845 }
21846
21847 if (opt.header) {
21848 deflateSetHeader(this.strm, opt.header);
21849 }
21850
21851 if (opt.dictionary) {
21852 let dict;
21853 // Convert data if needed
21854 if (typeof opt.dictionary === 'string') {
21855 // If we need to compress text, change encoding to utf8.
21856 dict = string2buf(opt.dictionary);
21857 } else if (opt.dictionary instanceof ArrayBuffer) {
21858 dict = new Uint8Array(opt.dictionary);
21859 } else {
21860 dict = opt.dictionary;
21861 }
21862
21863 status = deflateSetDictionary(this.strm, dict);
21864
21865 if (status !== Z_OK) {
21866 throw new Error(msg[status]);
21867 }
21868
21869 this._dict_set = true;
21870 }
21871 }
21872
21873 /**
21874 * Deflate#push(data[, mode]) -> Boolean
21875 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
21876 * converted to utf8 byte sequence.
21877 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
21878 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
21879 *
21880 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
21881 * new compressed chunks. Returns `true` on success. The last data block must have
21882 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
21883 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
21884 * can use mode Z_SYNC_FLUSH, keeping the compression context.
21885 *
21886 * On fail call [[Deflate#onEnd]] with error code and return false.
21887 *
21888 * We strongly recommend to use `Uint8Array` on input for best speed (output
21889 * array format is detected automatically). Also, don't skip last param and always
21890 * use the same type in your code (boolean or number). That will improve JS speed.
21891 *
21892 * For regular `Array`-s make sure all elements are [0..255].
21893 *
21894 * ##### Example
21895 *
21896 * ```javascript
21897 * push(chunk, false); // push one of data chunks
21898 * ...
21899 * push(chunk, true); // push last chunk
21900 * ```
21901 **/
21902 push(data, mode) {
21903 const { strm, options: { chunkSize } } = this;
21904 var status, _mode;
21905
21906 if (this.ended) { return false; }
21907
21908 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
21909
21910 // Convert data if needed
21911 if (typeof data === 'string') {
21912 // If we need to compress text, change encoding to utf8.
21913 strm.input = string2buf(data);
21914 } else if (data instanceof ArrayBuffer) {
21915 strm.input = new Uint8Array(data);
21916 } else {
21917 strm.input = data;
21918 }
21919
21920 strm.next_in = 0;
21921 strm.avail_in = strm.input.length;
21922
21923 do {
21924 if (strm.avail_out === 0) {
21925 strm.output = new Buf8(chunkSize);
21926 strm.next_out = 0;
21927 strm.avail_out = chunkSize;
21928 }
21929 status = deflate(strm, _mode); /* no bad return value */
21930
21931 if (status !== Z_STREAM_END && status !== Z_OK) {
21932 this.onEnd(status);
21933 this.ended = true;
21934 return false;
21935 }
21936 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
21937 this.onData(shrinkBuf(strm.output, strm.next_out));
21938 }
21939 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
21940
21941 // Finalize on the last chunk.
21942 if (_mode === Z_FINISH) {
21943 status = deflateEnd(this.strm);
21944 this.onEnd(status);
21945 this.ended = true;
21946 return status === Z_OK;
21947 }
21948
21949 // callback interim results if Z_SYNC_FLUSH.
21950 if (_mode === Z_SYNC_FLUSH) {
21951 this.onEnd(Z_OK);
21952 strm.avail_out = 0;
21953 return true;
21954 }
21955
21956 return true;
21957 };
21958 /**
21959 * Deflate#onData(chunk) -> Void
21960 * - chunk (Uint8Array|Array|String): output data. Type of array depends
21961 * on js engine support. When string output requested, each chunk
21962 * will be string.
21963 *
21964 * By default, stores data blocks in `chunks[]` property and glue
21965 * those in `onEnd`. Override this handler, if you need another behaviour.
21966 **/
21967 onData(chunk) {
21968 this.chunks.push(chunk);
21969 };
21970
21971 /**
21972 * Deflate#onEnd(status) -> Void
21973 * - status (Number): deflate status. 0 (Z_OK) on success,
21974 * other if not.
21975 *
21976 * Called once after you tell deflate that the input stream is
21977 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
21978 * or if an error happened. By default - join collected chunks,
21979 * free memory and fill `results` / `err` properties.
21980 **/
21981 onEnd(status) {
21982 // On success - join
21983 if (status === Z_OK) {
21984 this.result = flattenChunks(this.chunks);
21985 }
21986 this.chunks = [];
21987 this.err = status;
21988 this.msg = this.strm.msg;
21989 };
21990}
21991
21992// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21993// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21994//
21995// This software is provided 'as-is', without any express or implied
21996// warranty. In no event will the authors be held liable for any damages
21997// arising from the use of this software.
21998//
21999// Permission is granted to anyone to use this software for any purpose,
22000// including commercial applications, and to alter it and redistribute it
22001// freely, subject to the following restrictions:
22002//
22003// 1. The origin of this software must not be misrepresented; you must not
22004// claim that you wrote the original software. If you use this software
22005// in a product, an acknowledgment in the product documentation would be
22006// appreciated but is not required.
22007// 2. Altered source versions must be plainly marked as such, and must not be
22008// misrepresented as being the original software.
22009// 3. This notice may not be removed or altered from any source distribution.
22010
22011// See state defs from inflate.js
22012const BAD = 30; /* got a data error -- remain here until reset */
22013const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
22014
22015/*
22016 Decode literal, length, and distance codes and write out the resulting
22017 literal and match bytes until either not enough input or output is
22018 available, an end-of-block is encountered, or a data error is encountered.
22019 When large enough input and output buffers are supplied to inflate(), for
22020 example, a 16K input buffer and a 64K output buffer, more than 95% of the
22021 inflate execution time is spent in this routine.
22022
22023 Entry assumptions:
22024
22025 state.mode === LEN
22026 strm.avail_in >= 6
22027 strm.avail_out >= 258
22028 start >= strm.avail_out
22029 state.bits < 8
22030
22031 On return, state.mode is one of:
22032
22033 LEN -- ran out of enough output space or enough available input
22034 TYPE -- reached end of block code, inflate() to interpret next block
22035 BAD -- error in block data
22036
22037 Notes:
22038
22039 - The maximum input bits used by a length/distance pair is 15 bits for the
22040 length code, 5 bits for the length extra, 15 bits for the distance code,
22041 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
22042 Therefore if strm.avail_in >= 6, then there is enough input to avoid
22043 checking for available input while decoding.
22044
22045 - The maximum bytes that a single length/distance pair can output is 258
22046 bytes, which is the maximum length that can be coded. inflate_fast()
22047 requires strm.avail_out >= 258 for each loop to avoid checking for
22048 output space.
22049 */
22050function inflate_fast(strm, start) {
22051 let _in; /* local strm.input */
22052 let _out; /* local strm.output */
22053 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
22054 let hold; /* local strm.hold */
22055 let bits; /* local strm.bits */
22056 let here; /* retrieved table entry */
22057 let op; /* code bits, operation, extra bits, or */
22058 /* window position, window bytes to copy */
22059 let len; /* match length, unused bytes */
22060 let dist; /* match distance */
22061 let from; /* where to copy match from */
22062 let from_source;
22063
22064
22065
22066 /* copy state to local variables */
22067 const state = strm.state;
22068 //here = state.here;
22069 _in = strm.next_in;
22070 const input = strm.input;
22071 const last = _in + (strm.avail_in - 5);
22072 _out = strm.next_out;
22073 const output = strm.output;
22074 const beg = _out - (start - strm.avail_out);
22075 const end = _out + (strm.avail_out - 257);
22076 //#ifdef INFLATE_STRICT
22077 const dmax = state.dmax;
22078 //#endif
22079 const wsize = state.wsize;
22080 const whave = state.whave;
22081 const wnext = state.wnext;
22082 const s_window = state.window;
22083 hold = state.hold;
22084 bits = state.bits;
22085 const lcode = state.lencode;
22086 const dcode = state.distcode;
22087 const lmask = (1 << state.lenbits) - 1;
22088 const dmask = (1 << state.distbits) - 1;
22089
22090
22091 /* decode literals and length/distances until end-of-block or not enough
22092 input data or output space */
22093
22094 top:
22095 do {
22096 if (bits < 15) {
22097 hold += input[_in++] << bits;
22098 bits += 8;
22099 hold += input[_in++] << bits;
22100 bits += 8;
22101 }
22102
22103 here = lcode[hold & lmask];
22104
22105 dolen:
22106 for (;;) { // Goto emulation
22107 op = here >>> 24/*here.bits*/;
22108 hold >>>= op;
22109 bits -= op;
22110 op = here >>> 16 & 0xff/*here.op*/;
22111 if (op === 0) { /* literal */
22112 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
22113 // "inflate: literal '%c'\n" :
22114 // "inflate: literal 0x%02x\n", here.val));
22115 output[_out++] = here & 0xffff/*here.val*/;
22116 } else if (op & 16) { /* length base */
22117 len = here & 0xffff/*here.val*/;
22118 op &= 15; /* number of extra bits */
22119 if (op) {
22120 if (bits < op) {
22121 hold += input[_in++] << bits;
22122 bits += 8;
22123 }
22124 len += hold & (1 << op) - 1;
22125 hold >>>= op;
22126 bits -= op;
22127 }
22128 //Tracevv((stderr, "inflate: length %u\n", len));
22129 if (bits < 15) {
22130 hold += input[_in++] << bits;
22131 bits += 8;
22132 hold += input[_in++] << bits;
22133 bits += 8;
22134 }
22135 here = dcode[hold & dmask];
22136
22137 dodist:
22138 for (;;) { // goto emulation
22139 op = here >>> 24/*here.bits*/;
22140 hold >>>= op;
22141 bits -= op;
22142 op = here >>> 16 & 0xff/*here.op*/;
22143
22144 if (op & 16) { /* distance base */
22145 dist = here & 0xffff/*here.val*/;
22146 op &= 15; /* number of extra bits */
22147 if (bits < op) {
22148 hold += input[_in++] << bits;
22149 bits += 8;
22150 if (bits < op) {
22151 hold += input[_in++] << bits;
22152 bits += 8;
22153 }
22154 }
22155 dist += hold & (1 << op) - 1;
22156 //#ifdef INFLATE_STRICT
22157 if (dist > dmax) {
22158 strm.msg = "invalid distance too far back";
22159 state.mode = BAD;
22160 break top;
22161 }
22162 //#endif
22163 hold >>>= op;
22164 bits -= op;
22165 //Tracevv((stderr, "inflate: distance %u\n", dist));
22166 op = _out - beg; /* max distance in output */
22167 if (dist > op) { /* see if copy from window */
22168 op = dist - op; /* distance back in window */
22169 if (op > whave) {
22170 if (state.sane) {
22171 strm.msg = "invalid distance too far back";
22172 state.mode = BAD;
22173 break top;
22174 }
22175
22176 // (!) This block is disabled in zlib defaults,
22177 // don't enable it for binary compatibility
22178 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
22179 // if (len <= op - whave) {
22180 // do {
22181 // output[_out++] = 0;
22182 // } while (--len);
22183 // continue top;
22184 // }
22185 // len -= op - whave;
22186 // do {
22187 // output[_out++] = 0;
22188 // } while (--op > whave);
22189 // if (op === 0) {
22190 // from = _out - dist;
22191 // do {
22192 // output[_out++] = output[from++];
22193 // } while (--len);
22194 // continue top;
22195 // }
22196 //#endif
22197 }
22198 from = 0; // window index
22199 from_source = s_window;
22200 if (wnext === 0) { /* very common case */
22201 from += wsize - op;
22202 if (op < len) { /* some from window */
22203 len -= op;
22204 do {
22205 output[_out++] = s_window[from++];
22206 } while (--op);
22207 from = _out - dist; /* rest from output */
22208 from_source = output;
22209 }
22210 } else if (wnext < op) { /* wrap around window */
22211 from += wsize + wnext - op;
22212 op -= wnext;
22213 if (op < len) { /* some from end of window */
22214 len -= op;
22215 do {
22216 output[_out++] = s_window[from++];
22217 } while (--op);
22218 from = 0;
22219 if (wnext < len) { /* some from start of window */
22220 op = wnext;
22221 len -= op;
22222 do {
22223 output[_out++] = s_window[from++];
22224 } while (--op);
22225 from = _out - dist; /* rest from output */
22226 from_source = output;
22227 }
22228 }
22229 } else { /* contiguous in window */
22230 from += wnext - op;
22231 if (op < len) { /* some from window */
22232 len -= op;
22233 do {
22234 output[_out++] = s_window[from++];
22235 } while (--op);
22236 from = _out - dist; /* rest from output */
22237 from_source = output;
22238 }
22239 }
22240 while (len > 2) {
22241 output[_out++] = from_source[from++];
22242 output[_out++] = from_source[from++];
22243 output[_out++] = from_source[from++];
22244 len -= 3;
22245 }
22246 if (len) {
22247 output[_out++] = from_source[from++];
22248 if (len > 1) {
22249 output[_out++] = from_source[from++];
22250 }
22251 }
22252 } else {
22253 from = _out - dist; /* copy direct from output */
22254 do { /* minimum length is three */
22255 output[_out++] = output[from++];
22256 output[_out++] = output[from++];
22257 output[_out++] = output[from++];
22258 len -= 3;
22259 } while (len > 2);
22260 if (len) {
22261 output[_out++] = output[from++];
22262 if (len > 1) {
22263 output[_out++] = output[from++];
22264 }
22265 }
22266 }
22267 } else if ((op & 64) === 0) { /* 2nd level distance code */
22268 here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
22269 continue dodist;
22270 } else {
22271 strm.msg = "invalid distance code";
22272 state.mode = BAD;
22273 break top;
22274 }
22275
22276 break; // need to emulate goto via "continue"
22277 }
22278 } else if ((op & 64) === 0) { /* 2nd level length code */
22279 here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
22280 continue dolen;
22281 } else if (op & 32) { /* end-of-block */
22282 //Tracevv((stderr, "inflate: end of block\n"));
22283 state.mode = TYPE;
22284 break top;
22285 } else {
22286 strm.msg = "invalid literal/length code";
22287 state.mode = BAD;
22288 break top;
22289 }
22290
22291 break; // need to emulate goto via "continue"
22292 }
22293 } while (_in < last && _out < end);
22294
22295 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
22296 len = bits >> 3;
22297 _in -= len;
22298 bits -= len << 3;
22299 hold &= (1 << bits) - 1;
22300
22301 /* update state and return */
22302 strm.next_in = _in;
22303 strm.next_out = _out;
22304 strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
22305 strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
22306 state.hold = hold;
22307 state.bits = bits;
22308 return;
22309}
22310
22311const MAXBITS = 15;
22312const ENOUGH_LENS = 852;
22313const ENOUGH_DISTS = 592;
22314//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
22315
22316const CODES = 0;
22317const LENS = 1;
22318const DISTS = 2;
22319
22320const lbase = [ /* Length codes 257..285 base */
22321 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
22322 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
22323];
22324
22325const lext = [ /* Length codes 257..285 extra */
22326 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
22327 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
22328];
22329
22330const dbase = [ /* Distance codes 0..29 base */
22331 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
22332 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
22333 8193, 12289, 16385, 24577, 0, 0
22334];
22335
22336const dext = [ /* Distance codes 0..29 extra */
22337 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
22338 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
22339 28, 28, 29, 29, 64, 64
22340];
22341
22342function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
22343 const bits = opts.bits;
22344 //here = opts.here; /* table entry for duplication */
22345
22346 let len = 0; /* a code's length in bits */
22347 let sym = 0; /* index of code symbols */
22348 let min = 0, max = 0; /* minimum and maximum code lengths */
22349 let root = 0; /* number of index bits for root table */
22350 let curr = 0; /* number of index bits for current table */
22351 let drop = 0; /* code bits to drop for sub-table */
22352 let left = 0; /* number of prefix codes available */
22353 let used = 0; /* code entries in table used */
22354 let huff = 0; /* Huffman code */
22355 let incr; /* for incrementing code, index */
22356 let fill; /* index for replicating entries */
22357 let low; /* low bits for current root entry */
22358 let next; /* next available space in table */
22359 let base = null; /* base value table to use */
22360 let base_index = 0;
22361 // var shoextra; /* extra bits table to use */
22362 let end; /* use base and extra for symbol > end */
22363 const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
22364 const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
22365 let extra = null;
22366 let extra_index = 0;
22367
22368 let here_bits, here_op, here_val;
22369
22370 /*
22371 Process a set of code lengths to create a canonical Huffman code. The
22372 code lengths are lens[0..codes-1]. Each length corresponds to the
22373 symbols 0..codes-1. The Huffman code is generated by first sorting the
22374 symbols by length from short to long, and retaining the symbol order
22375 for codes with equal lengths. Then the code starts with all zero bits
22376 for the first code of the shortest length, and the codes are integer
22377 increments for the same length, and zeros are appended as the length
22378 increases. For the deflate format, these bits are stored backwards
22379 from their more natural integer increment ordering, and so when the
22380 decoding tables are built in the large loop below, the integer codes
22381 are incremented backwards.
22382
22383 This routine assumes, but does not check, that all of the entries in
22384 lens[] are in the range 0..MAXBITS. The caller must assure this.
22385 1..MAXBITS is interpreted as that code length. zero means that that
22386 symbol does not occur in this code.
22387
22388 The codes are sorted by computing a count of codes for each length,
22389 creating from that a table of starting indices for each length in the
22390 sorted table, and then entering the symbols in order in the sorted
22391 table. The sorted table is work[], with that space being provided by
22392 the caller.
22393
22394 The length counts are used for other purposes as well, i.e. finding
22395 the minimum and maximum length codes, determining if there are any
22396 codes at all, checking for a valid set of lengths, and looking ahead
22397 at length counts to determine sub-table sizes when building the
22398 decoding tables.
22399 */
22400
22401 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
22402 for (len = 0; len <= MAXBITS; len++) {
22403 count[len] = 0;
22404 }
22405 for (sym = 0; sym < codes; sym++) {
22406 count[lens[lens_index + sym]]++;
22407 }
22408
22409 /* bound code lengths, force root to be within code lengths */
22410 root = bits;
22411 for (max = MAXBITS; max >= 1; max--) {
22412 if (count[max] !== 0) {
22413 break;
22414 }
22415 }
22416 if (root > max) {
22417 root = max;
22418 }
22419 if (max === 0) { /* no symbols to code at all */
22420 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
22421 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
22422 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
22423 table[table_index++] = 1 << 24 | 64 << 16 | 0;
22424
22425
22426 //table.op[opts.table_index] = 64;
22427 //table.bits[opts.table_index] = 1;
22428 //table.val[opts.table_index++] = 0;
22429 table[table_index++] = 1 << 24 | 64 << 16 | 0;
22430
22431 opts.bits = 1;
22432 return 0; /* no symbols, but wait for decoding to report error */
22433 }
22434 for (min = 1; min < max; min++) {
22435 if (count[min] !== 0) {
22436 break;
22437 }
22438 }
22439 if (root < min) {
22440 root = min;
22441 }
22442
22443 /* check for an over-subscribed or incomplete set of lengths */
22444 left = 1;
22445 for (len = 1; len <= MAXBITS; len++) {
22446 left <<= 1;
22447 left -= count[len];
22448 if (left < 0) {
22449 return -1;
22450 } /* over-subscribed */
22451 }
22452 if (left > 0 && (type === CODES || max !== 1)) {
22453 return -1; /* incomplete set */
22454 }
22455
22456 /* generate offsets into symbol table for each length for sorting */
22457 offs[1] = 0;
22458 for (len = 1; len < MAXBITS; len++) {
22459 offs[len + 1] = offs[len] + count[len];
22460 }
22461
22462 /* sort symbols by length, by symbol order within each length */
22463 for (sym = 0; sym < codes; sym++) {
22464 if (lens[lens_index + sym] !== 0) {
22465 work[offs[lens[lens_index + sym]]++] = sym;
22466 }
22467 }
22468
22469 /*
22470 Create and fill in decoding tables. In this loop, the table being
22471 filled is at next and has curr index bits. The code being used is huff
22472 with length len. That code is converted to an index by dropping drop
22473 bits off of the bottom. For codes where len is less than drop + curr,
22474 those top drop + curr - len bits are incremented through all values to
22475 fill the table with replicated entries.
22476
22477 root is the number of index bits for the root table. When len exceeds
22478 root, sub-tables are created pointed to by the root entry with an index
22479 of the low root bits of huff. This is saved in low to check for when a
22480 new sub-table should be started. drop is zero when the root table is
22481 being filled, and drop is root when sub-tables are being filled.
22482
22483 When a new sub-table is needed, it is necessary to look ahead in the
22484 code lengths to determine what size sub-table is needed. The length
22485 counts are used for this, and so count[] is decremented as codes are
22486 entered in the tables.
22487
22488 used keeps track of how many table entries have been allocated from the
22489 provided *table space. It is checked for LENS and DIST tables against
22490 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
22491 the initial root table size constants. See the comments in inftrees.h
22492 for more information.
22493
22494 sym increments through all symbols, and the loop terminates when
22495 all codes of length max, i.e. all codes, have been processed. This
22496 routine permits incomplete codes, so another loop after this one fills
22497 in the rest of the decoding tables with invalid code markers.
22498 */
22499
22500 /* set up for code type */
22501 // poor man optimization - use if-else instead of switch,
22502 // to avoid deopts in old v8
22503 if (type === CODES) {
22504 base = extra = work; /* dummy value--not used */
22505 end = 19;
22506
22507 } else if (type === LENS) {
22508 base = lbase;
22509 base_index -= 257;
22510 extra = lext;
22511 extra_index -= 257;
22512 end = 256;
22513
22514 } else { /* DISTS */
22515 base = dbase;
22516 extra = dext;
22517 end = -1;
22518 }
22519
22520 /* initialize opts for loop */
22521 huff = 0; /* starting code */
22522 sym = 0; /* starting code symbol */
22523 len = min; /* starting code length */
22524 next = table_index; /* current table to fill in */
22525 curr = root; /* current table index bits */
22526 drop = 0; /* current bits to drop from code for index */
22527 low = -1; /* trigger new sub-table when len > root */
22528 used = 1 << root; /* use root table entries */
22529 const mask = used - 1; /* mask for comparing low */
22530
22531 /* check available table space */
22532 if (type === LENS && used > ENOUGH_LENS ||
22533 type === DISTS && used > ENOUGH_DISTS) {
22534 return 1;
22535 }
22536
22537 /* process all codes and make table entries */
22538 for (;;) {
22539 /* create table entry */
22540 here_bits = len - drop;
22541 if (work[sym] < end) {
22542 here_op = 0;
22543 here_val = work[sym];
22544 } else if (work[sym] > end) {
22545 here_op = extra[extra_index + work[sym]];
22546 here_val = base[base_index + work[sym]];
22547 } else {
22548 here_op = 32 + 64; /* end of block */
22549 here_val = 0;
22550 }
22551
22552 /* replicate for those indices with low len bits equal to huff */
22553 incr = 1 << len - drop;
22554 fill = 1 << curr;
22555 min = fill; /* save offset to next table */
22556 do {
22557 fill -= incr;
22558 table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;
22559 } while (fill !== 0);
22560
22561 /* backwards increment the len-bit code huff */
22562 incr = 1 << len - 1;
22563 while (huff & incr) {
22564 incr >>= 1;
22565 }
22566 if (incr !== 0) {
22567 huff &= incr - 1;
22568 huff += incr;
22569 } else {
22570 huff = 0;
22571 }
22572
22573 /* go to next symbol, update count, len */
22574 sym++;
22575 if (--count[len] === 0) {
22576 if (len === max) {
22577 break;
22578 }
22579 len = lens[lens_index + work[sym]];
22580 }
22581
22582 /* create new sub-table if needed */
22583 if (len > root && (huff & mask) !== low) {
22584 /* if first time, transition to sub-tables */
22585 if (drop === 0) {
22586 drop = root;
22587 }
22588
22589 /* increment past last table */
22590 next += min; /* here min is 1 << curr */
22591
22592 /* determine length of next table */
22593 curr = len - drop;
22594 left = 1 << curr;
22595 while (curr + drop < max) {
22596 left -= count[curr + drop];
22597 if (left <= 0) {
22598 break;
22599 }
22600 curr++;
22601 left <<= 1;
22602 }
22603
22604 /* check for enough space */
22605 used += 1 << curr;
22606 if (type === LENS && used > ENOUGH_LENS ||
22607 type === DISTS && used > ENOUGH_DISTS) {
22608 return 1;
22609 }
22610
22611 /* point entry in root table to sub-table */
22612 low = huff & mask;
22613 /*table.op[low] = curr;
22614 table.bits[low] = root;
22615 table.val[low] = next - opts.table_index;*/
22616 table[low] = root << 24 | curr << 16 | next - table_index |0;
22617 }
22618 }
22619
22620 /* fill in remaining table entry if code is incomplete (guaranteed to have
22621 at most one remaining entry, since if the code is incomplete, the
22622 maximum code length that was allowed to get this far is one bit) */
22623 if (huff !== 0) {
22624 //table.op[next + huff] = 64; /* invalid code marker */
22625 //table.bits[next + huff] = len - drop;
22626 //table.val[next + huff] = 0;
22627 table[next + huff] = len - drop << 24 | 64 << 16 |0;
22628 }
22629
22630 /* set return parameters */
22631 //opts.table_index += used;
22632 opts.bits = root;
22633 return 0;
22634}
22635
22636const CODES$1 = 0;
22637const LENS$1 = 1;
22638const DISTS$1 = 2;
22639
22640/* STATES ====================================================================*/
22641/* ===========================================================================*/
22642
22643
22644const HEAD = 1; /* i: waiting for magic header */
22645const FLAGS = 2; /* i: waiting for method and flags (gzip) */
22646const TIME = 3; /* i: waiting for modification time (gzip) */
22647const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
22648const EXLEN = 5; /* i: waiting for extra length (gzip) */
22649const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
22650const NAME = 7; /* i: waiting for end of file name (gzip) */
22651const COMMENT = 8; /* i: waiting for end of comment (gzip) */
22652const HCRC = 9; /* i: waiting for header crc (gzip) */
22653const DICTID = 10; /* i: waiting for dictionary check value */
22654const DICT = 11; /* waiting for inflateSetDictionary() call */
22655const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
22656const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
22657const STORED = 14; /* i: waiting for stored size (length and complement) */
22658const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
22659const COPY = 16; /* i/o: waiting for input or output to copy stored block */
22660const TABLE = 17; /* i: waiting for dynamic block table lengths */
22661const LENLENS = 18; /* i: waiting for code length code lengths */
22662const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
22663const LEN_ = 20; /* i: same as LEN below, but only first time in */
22664const LEN = 21; /* i: waiting for length/lit/eob code */
22665const LENEXT = 22; /* i: waiting for length extra bits */
22666const DIST = 23; /* i: waiting for distance code */
22667const DISTEXT = 24; /* i: waiting for distance extra bits */
22668const MATCH = 25; /* o: waiting for output space to copy string */
22669const LIT = 26; /* o: waiting for output space to write literal */
22670const CHECK = 27; /* i: waiting for 32-bit check value */
22671const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
22672const DONE = 29; /* finished check, done -- remain here until reset */
22673const BAD$1 = 30; /* got a data error -- remain here until reset */
22674//const MEM = 31; /* got an inflate() memory error -- remain here until reset */
22675const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
22676
22677/* ===========================================================================*/
22678
22679
22680
22681const ENOUGH_LENS$1 = 852;
22682const ENOUGH_DISTS$1 = 592;
22683
22684
22685function zswap32(q) {
22686 return (((q >>> 24) & 0xff) +
22687 ((q >>> 8) & 0xff00) +
22688 ((q & 0xff00) << 8) +
22689 ((q & 0xff) << 24));
22690}
22691
22692
22693class InflateState {
22694 constructor() {
22695 this.mode = 0; /* current inflate mode */
22696 this.last = false; /* true if processing last block */
22697 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
22698 this.havedict = false; /* true if dictionary provided */
22699 this.flags = 0; /* gzip header method and flags (0 if zlib) */
22700 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
22701 this.check = 0; /* protected copy of check value */
22702 this.total = 0; /* protected copy of output count */
22703 // TODO: may be {}
22704 this.head = null; /* where to save gzip header information */
22705
22706 /* sliding window */
22707 this.wbits = 0; /* log base 2 of requested window size */
22708 this.wsize = 0; /* window size or zero if not using window */
22709 this.whave = 0; /* valid bytes in the window */
22710 this.wnext = 0; /* window write index */
22711 this.window = null; /* allocated sliding window, if needed */
22712
22713 /* bit accumulator */
22714 this.hold = 0; /* input bit accumulator */
22715 this.bits = 0; /* number of bits in "in" */
22716
22717 /* for string and stored block copying */
22718 this.length = 0; /* literal or length of data to copy */
22719 this.offset = 0; /* distance back to copy string from */
22720
22721 /* for table and code decoding */
22722 this.extra = 0; /* extra bits needed */
22723
22724 /* fixed and dynamic code tables */
22725 this.lencode = null; /* starting table for length/literal codes */
22726 this.distcode = null; /* starting table for distance codes */
22727 this.lenbits = 0; /* index bits for lencode */
22728 this.distbits = 0; /* index bits for distcode */
22729
22730 /* dynamic table building */
22731 this.ncode = 0; /* number of code length code lengths */
22732 this.nlen = 0; /* number of length code lengths */
22733 this.ndist = 0; /* number of distance code lengths */
22734 this.have = 0; /* number of code lengths in lens[] */
22735 this.next = null; /* next available space in codes[] */
22736
22737 this.lens = new Buf16(320); /* temporary storage for code lengths */
22738 this.work = new Buf16(288); /* work area for code table building */
22739
22740 /*
22741 because we don't have pointers in js, we use lencode and distcode directly
22742 as buffers so we don't need codes
22743 */
22744 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
22745 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
22746 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
22747 this.sane = 0; /* if false, allow invalid distance too far */
22748 this.back = 0; /* bits back of last unprocessed length/lit */
22749 this.was = 0; /* initial length of match */
22750 }
22751}
22752
22753function inflateResetKeep(strm) {
22754 let state;
22755
22756 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
22757 state = strm.state;
22758 strm.total_in = strm.total_out = state.total = 0;
22759 strm.msg = ''; /*Z_NULL*/
22760 if (state.wrap) { /* to support ill-conceived Java test suite */
22761 strm.adler = state.wrap & 1;
22762 }
22763 state.mode = HEAD;
22764 state.last = 0;
22765 state.havedict = 0;
22766 state.dmax = 32768;
22767 state.head = null/*Z_NULL*/;
22768 state.hold = 0;
22769 state.bits = 0;
22770 //state.lencode = state.distcode = state.next = state.codes;
22771 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
22772 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
22773
22774 state.sane = 1;
22775 state.back = -1;
22776 //Tracev((stderr, "inflate: reset\n"));
22777 return Z_OK;
22778}
22779
22780function inflateReset(strm) {
22781 let state;
22782
22783 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
22784 state = strm.state;
22785 state.wsize = 0;
22786 state.whave = 0;
22787 state.wnext = 0;
22788 return inflateResetKeep(strm);
22789
22790}
22791
22792function inflateReset2(strm, windowBits) {
22793 let wrap;
22794 let state;
22795
22796 /* get the state */
22797 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
22798 state = strm.state;
22799
22800 /* extract wrap request from windowBits parameter */
22801 if (windowBits < 0) {
22802 wrap = 0;
22803 windowBits = -windowBits;
22804 }
22805 else {
22806 wrap = (windowBits >> 4) + 1;
22807 if (windowBits < 48) {
22808 windowBits &= 15;
22809 }
22810 }
22811
22812 /* set number of window bits, free window if different */
22813 if (windowBits && (windowBits < 8 || windowBits > 15)) {
22814 return Z_STREAM_ERROR;
22815 }
22816 if (state.window !== null && state.wbits !== windowBits) {
22817 state.window = null;
22818 }
22819
22820 /* update state and reset the rest of it */
22821 state.wrap = wrap;
22822 state.wbits = windowBits;
22823 return inflateReset(strm);
22824}
22825
22826function inflateInit2(strm, windowBits) {
22827 let ret;
22828 let state;
22829
22830 if (!strm) { return Z_STREAM_ERROR; }
22831 //strm.msg = Z_NULL; /* in case we return an error */
22832
22833 state = new InflateState();
22834
22835 //if (state === Z_NULL) return Z_MEM_ERROR;
22836 //Tracev((stderr, "inflate: allocated\n"));
22837 strm.state = state;
22838 state.window = null/*Z_NULL*/;
22839 ret = inflateReset2(strm, windowBits);
22840 if (ret !== Z_OK) {
22841 strm.state = null/*Z_NULL*/;
22842 }
22843 return ret;
22844}
22845
22846
22847/*
22848 Return state with length and distance decoding tables and index sizes set to
22849 fixed code decoding. Normally this returns fixed tables from inffixed.h.
22850 If BUILDFIXED is defined, then instead this routine builds the tables the
22851 first time it's called, and returns those tables the first time and
22852 thereafter. This reduces the size of the code by about 2K bytes, in
22853 exchange for a little execution time. However, BUILDFIXED should not be
22854 used for threaded applications, since the rewriting of the tables and virgin
22855 may not be thread-safe.
22856 */
22857let virgin = true;
22858
22859let lenfix, distfix; // We have no pointers in JS, so keep tables separate
22860
22861function fixedtables(state) {
22862 /* build fixed huffman tables if first call (may not be thread safe) */
22863 if (virgin) {
22864 let sym;
22865
22866 lenfix = new Buf32(512);
22867 distfix = new Buf32(32);
22868
22869 /* literal/length table */
22870 sym = 0;
22871 while (sym < 144) { state.lens[sym++] = 8; }
22872 while (sym < 256) { state.lens[sym++] = 9; }
22873 while (sym < 280) { state.lens[sym++] = 7; }
22874 while (sym < 288) { state.lens[sym++] = 8; }
22875
22876 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
22877
22878 /* distance table */
22879 sym = 0;
22880 while (sym < 32) { state.lens[sym++] = 5; }
22881
22882 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
22883
22884 /* do this just once */
22885 virgin = false;
22886 }
22887
22888 state.lencode = lenfix;
22889 state.lenbits = 9;
22890 state.distcode = distfix;
22891 state.distbits = 5;
22892}
22893
22894
22895/*
22896 Update the window with the last wsize (normally 32K) bytes written before
22897 returning. If window does not exist yet, create it. This is only called
22898 when a window is already in use, or when output has been written during this
22899 inflate call, but the end of the deflate stream has not been reached yet.
22900 It is also called to create a window for dictionary data when a dictionary
22901 is loaded.
22902
22903 Providing output buffers larger than 32K to inflate() should provide a speed
22904 advantage, since only the last 32K of output is copied to the sliding window
22905 upon return from inflate(), and since all distances after the first 32K of
22906 output will fall in the output data, making match copies simpler and faster.
22907 The advantage may be dependent on the size of the processor's data caches.
22908 */
22909function updatewindow(strm, src, end, copy) {
22910 let dist;
22911 const state = strm.state;
22912
22913 /* if it hasn't been done already, allocate space for the window */
22914 if (state.window === null) {
22915 state.wsize = 1 << state.wbits;
22916 state.wnext = 0;
22917 state.whave = 0;
22918
22919 state.window = new Buf8(state.wsize);
22920 }
22921
22922 /* copy state->wsize or less output bytes into the circular window */
22923 if (copy >= state.wsize) {
22924 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
22925 state.wnext = 0;
22926 state.whave = state.wsize;
22927 }
22928 else {
22929 dist = state.wsize - state.wnext;
22930 if (dist > copy) {
22931 dist = copy;
22932 }
22933 //zmemcpy(state->window + state->wnext, end - copy, dist);
22934 arraySet(state.window, src, end - copy, dist, state.wnext);
22935 copy -= dist;
22936 if (copy) {
22937 //zmemcpy(state->window, end - copy, copy);
22938 arraySet(state.window, src, end - copy, copy, 0);
22939 state.wnext = copy;
22940 state.whave = state.wsize;
22941 }
22942 else {
22943 state.wnext += dist;
22944 if (state.wnext === state.wsize) { state.wnext = 0; }
22945 if (state.whave < state.wsize) { state.whave += dist; }
22946 }
22947 }
22948 return 0;
22949}
22950
22951function inflate(strm, flush) {
22952 let state;
22953 let input, output; // input/output buffers
22954 let next; /* next input INDEX */
22955 let put; /* next output INDEX */
22956 let have, left; /* available input and output */
22957 let hold; /* bit buffer */
22958 let bits; /* bits in bit buffer */
22959 let _in, _out; /* save starting available input and output */
22960 let copy; /* number of stored or match bytes to copy */
22961 let from; /* where to copy match bytes from */
22962 let from_source;
22963 let here = 0; /* current decoding table entry */
22964 let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
22965 //var last; /* parent table entry */
22966 let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
22967 let len; /* length to copy for repeats, bits to drop */
22968 let ret; /* return code */
22969 let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
22970 let opts;
22971
22972 let n; // temporary var for NEED_BITS
22973
22974 const order = /* permutation of code lengths */
22975 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
22976
22977
22978 if (!strm || !strm.state || !strm.output ||
22979 (!strm.input && strm.avail_in !== 0)) {
22980 return Z_STREAM_ERROR;
22981 }
22982
22983 state = strm.state;
22984 if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */
22985
22986
22987 //--- LOAD() ---
22988 put = strm.next_out;
22989 output = strm.output;
22990 left = strm.avail_out;
22991 next = strm.next_in;
22992 input = strm.input;
22993 have = strm.avail_in;
22994 hold = state.hold;
22995 bits = state.bits;
22996 //---
22997
22998 _in = have;
22999 _out = left;
23000 ret = Z_OK;
23001
23002 inf_leave: // goto emulation
23003 for (;;) {
23004 switch (state.mode) {
23005 case HEAD:
23006 if (state.wrap === 0) {
23007 state.mode = TYPEDO;
23008 break;
23009 }
23010 //=== NEEDBITS(16);
23011 while (bits < 16) {
23012 if (have === 0) { break inf_leave; }
23013 have--;
23014 hold += input[next++] << bits;
23015 bits += 8;
23016 }
23017 //===//
23018 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
23019 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
23020 //=== CRC2(state.check, hold);
23021 hbuf[0] = hold & 0xff;
23022 hbuf[1] = (hold >>> 8) & 0xff;
23023 state.check = crc32(state.check, hbuf, 2, 0);
23024 //===//
23025
23026 //=== INITBITS();
23027 hold = 0;
23028 bits = 0;
23029 //===//
23030 state.mode = FLAGS;
23031 break;
23032 }
23033 state.flags = 0; /* expect zlib header */
23034 if (state.head) {
23035 state.head.done = false;
23036 }
23037 if (!(state.wrap & 1) || /* check if zlib header allowed */
23038 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
23039 strm.msg = 'incorrect header check';
23040 state.mode = BAD$1;
23041 break;
23042 }
23043 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
23044 strm.msg = 'unknown compression method';
23045 state.mode = BAD$1;
23046 break;
23047 }
23048 //--- DROPBITS(4) ---//
23049 hold >>>= 4;
23050 bits -= 4;
23051 //---//
23052 len = (hold & 0x0f)/*BITS(4)*/ + 8;
23053 if (state.wbits === 0) {
23054 state.wbits = len;
23055 }
23056 else if (len > state.wbits) {
23057 strm.msg = 'invalid window size';
23058 state.mode = BAD$1;
23059 break;
23060 }
23061 state.dmax = 1 << len;
23062 //Tracev((stderr, "inflate: zlib header ok\n"));
23063 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
23064 state.mode = hold & 0x200 ? DICTID : TYPE$1;
23065 //=== INITBITS();
23066 hold = 0;
23067 bits = 0;
23068 //===//
23069 break;
23070 case FLAGS:
23071 //=== NEEDBITS(16); */
23072 while (bits < 16) {
23073 if (have === 0) { break inf_leave; }
23074 have--;
23075 hold += input[next++] << bits;
23076 bits += 8;
23077 }
23078 //===//
23079 state.flags = hold;
23080 if ((state.flags & 0xff) !== Z_DEFLATED) {
23081 strm.msg = 'unknown compression method';
23082 state.mode = BAD$1;
23083 break;
23084 }
23085 if (state.flags & 0xe000) {
23086 strm.msg = 'unknown header flags set';
23087 state.mode = BAD$1;
23088 break;
23089 }
23090 if (state.head) {
23091 state.head.text = ((hold >> 8) & 1);
23092 }
23093 if (state.flags & 0x0200) {
23094 //=== CRC2(state.check, hold);
23095 hbuf[0] = hold & 0xff;
23096 hbuf[1] = (hold >>> 8) & 0xff;
23097 state.check = crc32(state.check, hbuf, 2, 0);
23098 //===//
23099 }
23100 //=== INITBITS();
23101 hold = 0;
23102 bits = 0;
23103 //===//
23104 state.mode = TIME;
23105 /* falls through */
23106 case TIME:
23107 //=== NEEDBITS(32); */
23108 while (bits < 32) {
23109 if (have === 0) { break inf_leave; }
23110 have--;
23111 hold += input[next++] << bits;
23112 bits += 8;
23113 }
23114 //===//
23115 if (state.head) {
23116 state.head.time = hold;
23117 }
23118 if (state.flags & 0x0200) {
23119 //=== CRC4(state.check, hold)
23120 hbuf[0] = hold & 0xff;
23121 hbuf[1] = (hold >>> 8) & 0xff;
23122 hbuf[2] = (hold >>> 16) & 0xff;
23123 hbuf[3] = (hold >>> 24) & 0xff;
23124 state.check = crc32(state.check, hbuf, 4, 0);
23125 //===
23126 }
23127 //=== INITBITS();
23128 hold = 0;
23129 bits = 0;
23130 //===//
23131 state.mode = OS;
23132 /* falls through */
23133 case OS:
23134 //=== NEEDBITS(16); */
23135 while (bits < 16) {
23136 if (have === 0) { break inf_leave; }
23137 have--;
23138 hold += input[next++] << bits;
23139 bits += 8;
23140 }
23141 //===//
23142 if (state.head) {
23143 state.head.xflags = (hold & 0xff);
23144 state.head.os = (hold >> 8);
23145 }
23146 if (state.flags & 0x0200) {
23147 //=== CRC2(state.check, hold);
23148 hbuf[0] = hold & 0xff;
23149 hbuf[1] = (hold >>> 8) & 0xff;
23150 state.check = crc32(state.check, hbuf, 2, 0);
23151 //===//
23152 }
23153 //=== INITBITS();
23154 hold = 0;
23155 bits = 0;
23156 //===//
23157 state.mode = EXLEN;
23158 /* falls through */
23159 case EXLEN:
23160 if (state.flags & 0x0400) {
23161 //=== NEEDBITS(16); */
23162 while (bits < 16) {
23163 if (have === 0) { break inf_leave; }
23164 have--;
23165 hold += input[next++] << bits;
23166 bits += 8;
23167 }
23168 //===//
23169 state.length = hold;
23170 if (state.head) {
23171 state.head.extra_len = hold;
23172 }
23173 if (state.flags & 0x0200) {
23174 //=== CRC2(state.check, hold);
23175 hbuf[0] = hold & 0xff;
23176 hbuf[1] = (hold >>> 8) & 0xff;
23177 state.check = crc32(state.check, hbuf, 2, 0);
23178 //===//
23179 }
23180 //=== INITBITS();
23181 hold = 0;
23182 bits = 0;
23183 //===//
23184 }
23185 else if (state.head) {
23186 state.head.extra = null/*Z_NULL*/;
23187 }
23188 state.mode = EXTRA;
23189 /* falls through */
23190 case EXTRA:
23191 if (state.flags & 0x0400) {
23192 copy = state.length;
23193 if (copy > have) { copy = have; }
23194 if (copy) {
23195 if (state.head) {
23196 len = state.head.extra_len - state.length;
23197 if (!state.head.extra) {
23198 // Use untyped array for more convenient processing later
23199 state.head.extra = new Array(state.head.extra_len);
23200 }
23201 arraySet(
23202 state.head.extra,
23203 input,
23204 next,
23205 // extra field is limited to 65536 bytes
23206 // - no need for additional size check
23207 copy,
23208 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
23209 len
23210 );
23211 //zmemcpy(state.head.extra + len, next,
23212 // len + copy > state.head.extra_max ?
23213 // state.head.extra_max - len : copy);
23214 }
23215 if (state.flags & 0x0200) {
23216 state.check = crc32(state.check, input, copy, next);
23217 }
23218 have -= copy;
23219 next += copy;
23220 state.length -= copy;
23221 }
23222 if (state.length) { break inf_leave; }
23223 }
23224 state.length = 0;
23225 state.mode = NAME;
23226 /* falls through */
23227 case NAME:
23228 if (state.flags & 0x0800) {
23229 if (have === 0) { break inf_leave; }
23230 copy = 0;
23231 do {
23232 // TODO: 2 or 1 bytes?
23233 len = input[next + copy++];
23234 /* use constant limit because in js we should not preallocate memory */
23235 if (state.head && len &&
23236 (state.length < 65536 /*state.head.name_max*/)) {
23237 state.head.name += String.fromCharCode(len);
23238 }
23239 } while (len && copy < have);
23240
23241 if (state.flags & 0x0200) {
23242 state.check = crc32(state.check, input, copy, next);
23243 }
23244 have -= copy;
23245 next += copy;
23246 if (len) { break inf_leave; }
23247 }
23248 else if (state.head) {
23249 state.head.name = null;
23250 }
23251 state.length = 0;
23252 state.mode = COMMENT;
23253 /* falls through */
23254 case COMMENT:
23255 if (state.flags & 0x1000) {
23256 if (have === 0) { break inf_leave; }
23257 copy = 0;
23258 do {
23259 len = input[next + copy++];
23260 /* use constant limit because in js we should not preallocate memory */
23261 if (state.head && len &&
23262 (state.length < 65536 /*state.head.comm_max*/)) {
23263 state.head.comment += String.fromCharCode(len);
23264 }
23265 } while (len && copy < have);
23266 if (state.flags & 0x0200) {
23267 state.check = crc32(state.check, input, copy, next);
23268 }
23269 have -= copy;
23270 next += copy;
23271 if (len) { break inf_leave; }
23272 }
23273 else if (state.head) {
23274 state.head.comment = null;
23275 }
23276 state.mode = HCRC;
23277 /* falls through */
23278 case HCRC:
23279 if (state.flags & 0x0200) {
23280 //=== NEEDBITS(16); */
23281 while (bits < 16) {
23282 if (have === 0) { break inf_leave; }
23283 have--;
23284 hold += input[next++] << bits;
23285 bits += 8;
23286 }
23287 //===//
23288 if (hold !== (state.check & 0xffff)) {
23289 strm.msg = 'header crc mismatch';
23290 state.mode = BAD$1;
23291 break;
23292 }
23293 //=== INITBITS();
23294 hold = 0;
23295 bits = 0;
23296 //===//
23297 }
23298 if (state.head) {
23299 state.head.hcrc = ((state.flags >> 9) & 1);
23300 state.head.done = true;
23301 }
23302 strm.adler = state.check = 0;
23303 state.mode = TYPE$1;
23304 break;
23305 case DICTID:
23306 //=== NEEDBITS(32); */
23307 while (bits < 32) {
23308 if (have === 0) { break inf_leave; }
23309 have--;
23310 hold += input[next++] << bits;
23311 bits += 8;
23312 }
23313 //===//
23314 strm.adler = state.check = zswap32(hold);
23315 //=== INITBITS();
23316 hold = 0;
23317 bits = 0;
23318 //===//
23319 state.mode = DICT;
23320 /* falls through */
23321 case DICT:
23322 if (state.havedict === 0) {
23323 //--- RESTORE() ---
23324 strm.next_out = put;
23325 strm.avail_out = left;
23326 strm.next_in = next;
23327 strm.avail_in = have;
23328 state.hold = hold;
23329 state.bits = bits;
23330 //---
23331 return Z_NEED_DICT;
23332 }
23333 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
23334 state.mode = TYPE$1;
23335 /* falls through */
23336 case TYPE$1:
23337 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
23338 /* falls through */
23339 case TYPEDO:
23340 if (state.last) {
23341 //--- BYTEBITS() ---//
23342 hold >>>= bits & 7;
23343 bits -= bits & 7;
23344 //---//
23345 state.mode = CHECK;
23346 break;
23347 }
23348 //=== NEEDBITS(3); */
23349 while (bits < 3) {
23350 if (have === 0) { break inf_leave; }
23351 have--;
23352 hold += input[next++] << bits;
23353 bits += 8;
23354 }
23355 //===//
23356 state.last = (hold & 0x01)/*BITS(1)*/;
23357 //--- DROPBITS(1) ---//
23358 hold >>>= 1;
23359 bits -= 1;
23360 //---//
23361
23362 switch ((hold & 0x03)/*BITS(2)*/) {
23363 case 0: /* stored block */
23364 //Tracev((stderr, "inflate: stored block%s\n",
23365 // state.last ? " (last)" : ""));
23366 state.mode = STORED;
23367 break;
23368 case 1: /* fixed block */
23369 fixedtables(state);
23370 //Tracev((stderr, "inflate: fixed codes block%s\n",
23371 // state.last ? " (last)" : ""));
23372 state.mode = LEN_; /* decode codes */
23373 if (flush === Z_TREES) {
23374 //--- DROPBITS(2) ---//
23375 hold >>>= 2;
23376 bits -= 2;
23377 //---//
23378 break inf_leave;
23379 }
23380 break;
23381 case 2: /* dynamic block */
23382 //Tracev((stderr, "inflate: dynamic codes block%s\n",
23383 // state.last ? " (last)" : ""));
23384 state.mode = TABLE;
23385 break;
23386 case 3:
23387 strm.msg = 'invalid block type';
23388 state.mode = BAD$1;
23389 }
23390 //--- DROPBITS(2) ---//
23391 hold >>>= 2;
23392 bits -= 2;
23393 //---//
23394 break;
23395 case STORED:
23396 //--- BYTEBITS() ---// /* go to byte boundary */
23397 hold >>>= bits & 7;
23398 bits -= bits & 7;
23399 //---//
23400 //=== NEEDBITS(32); */
23401 while (bits < 32) {
23402 if (have === 0) { break inf_leave; }
23403 have--;
23404 hold += input[next++] << bits;
23405 bits += 8;
23406 }
23407 //===//
23408 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
23409 strm.msg = 'invalid stored block lengths';
23410 state.mode = BAD$1;
23411 break;
23412 }
23413 state.length = hold & 0xffff;
23414 //Tracev((stderr, "inflate: stored length %u\n",
23415 // state.length));
23416 //=== INITBITS();
23417 hold = 0;
23418 bits = 0;
23419 //===//
23420 state.mode = COPY_;
23421 if (flush === Z_TREES) { break inf_leave; }
23422 /* falls through */
23423 case COPY_:
23424 state.mode = COPY;
23425 /* falls through */
23426 case COPY:
23427 copy = state.length;
23428 if (copy) {
23429 if (copy > have) { copy = have; }
23430 if (copy > left) { copy = left; }
23431 if (copy === 0) { break inf_leave; }
23432 //--- zmemcpy(put, next, copy); ---
23433 arraySet(output, input, next, copy, put);
23434 //---//
23435 have -= copy;
23436 next += copy;
23437 left -= copy;
23438 put += copy;
23439 state.length -= copy;
23440 break;
23441 }
23442 //Tracev((stderr, "inflate: stored end\n"));
23443 state.mode = TYPE$1;
23444 break;
23445 case TABLE:
23446 //=== NEEDBITS(14); */
23447 while (bits < 14) {
23448 if (have === 0) { break inf_leave; }
23449 have--;
23450 hold += input[next++] << bits;
23451 bits += 8;
23452 }
23453 //===//
23454 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
23455 //--- DROPBITS(5) ---//
23456 hold >>>= 5;
23457 bits -= 5;
23458 //---//
23459 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
23460 //--- DROPBITS(5) ---//
23461 hold >>>= 5;
23462 bits -= 5;
23463 //---//
23464 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
23465 //--- DROPBITS(4) ---//
23466 hold >>>= 4;
23467 bits -= 4;
23468 //---//
23469//#ifndef PKZIP_BUG_WORKAROUND
23470 if (state.nlen > 286 || state.ndist > 30) {
23471 strm.msg = 'too many length or distance symbols';
23472 state.mode = BAD$1;
23473 break;
23474 }
23475//#endif
23476 //Tracev((stderr, "inflate: table sizes ok\n"));
23477 state.have = 0;
23478 state.mode = LENLENS;
23479 /* falls through */
23480 case LENLENS:
23481 while (state.have < state.ncode) {
23482 //=== NEEDBITS(3);
23483 while (bits < 3) {
23484 if (have === 0) { break inf_leave; }
23485 have--;
23486 hold += input[next++] << bits;
23487 bits += 8;
23488 }
23489 //===//
23490 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
23491 //--- DROPBITS(3) ---//
23492 hold >>>= 3;
23493 bits -= 3;
23494 //---//
23495 }
23496 while (state.have < 19) {
23497 state.lens[order[state.have++]] = 0;
23498 }
23499 // We have separate tables & no pointers. 2 commented lines below not needed.
23500 //state.next = state.codes;
23501 //state.lencode = state.next;
23502 // Switch to use dynamic table
23503 state.lencode = state.lendyn;
23504 state.lenbits = 7;
23505
23506 opts = { bits: state.lenbits };
23507 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
23508 state.lenbits = opts.bits;
23509
23510 if (ret) {
23511 strm.msg = 'invalid code lengths set';
23512 state.mode = BAD$1;
23513 break;
23514 }
23515 //Tracev((stderr, "inflate: code lengths ok\n"));
23516 state.have = 0;
23517 state.mode = CODELENS;
23518 /* falls through */
23519 case CODELENS:
23520 while (state.have < state.nlen + state.ndist) {
23521 for (;;) {
23522 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
23523 here_bits = here >>> 24;
23524 here_op = (here >>> 16) & 0xff;
23525 here_val = here & 0xffff;
23526
23527 if ((here_bits) <= bits) { break; }
23528 //--- PULLBYTE() ---//
23529 if (have === 0) { break inf_leave; }
23530 have--;
23531 hold += input[next++] << bits;
23532 bits += 8;
23533 //---//
23534 }
23535 if (here_val < 16) {
23536 //--- DROPBITS(here.bits) ---//
23537 hold >>>= here_bits;
23538 bits -= here_bits;
23539 //---//
23540 state.lens[state.have++] = here_val;
23541 }
23542 else {
23543 if (here_val === 16) {
23544 //=== NEEDBITS(here.bits + 2);
23545 n = here_bits + 2;
23546 while (bits < n) {
23547 if (have === 0) { break inf_leave; }
23548 have--;
23549 hold += input[next++] << bits;
23550 bits += 8;
23551 }
23552 //===//
23553 //--- DROPBITS(here.bits) ---//
23554 hold >>>= here_bits;
23555 bits -= here_bits;
23556 //---//
23557 if (state.have === 0) {
23558 strm.msg = 'invalid bit length repeat';
23559 state.mode = BAD$1;
23560 break;
23561 }
23562 len = state.lens[state.have - 1];
23563 copy = 3 + (hold & 0x03);//BITS(2);
23564 //--- DROPBITS(2) ---//
23565 hold >>>= 2;
23566 bits -= 2;
23567 //---//
23568 }
23569 else if (here_val === 17) {
23570 //=== NEEDBITS(here.bits + 3);
23571 n = here_bits + 3;
23572 while (bits < n) {
23573 if (have === 0) { break inf_leave; }
23574 have--;
23575 hold += input[next++] << bits;
23576 bits += 8;
23577 }
23578 //===//
23579 //--- DROPBITS(here.bits) ---//
23580 hold >>>= here_bits;
23581 bits -= here_bits;
23582 //---//
23583 len = 0;
23584 copy = 3 + (hold & 0x07);//BITS(3);
23585 //--- DROPBITS(3) ---//
23586 hold >>>= 3;
23587 bits -= 3;
23588 //---//
23589 }
23590 else {
23591 //=== NEEDBITS(here.bits + 7);
23592 n = here_bits + 7;
23593 while (bits < n) {
23594 if (have === 0) { break inf_leave; }
23595 have--;
23596 hold += input[next++] << bits;
23597 bits += 8;
23598 }
23599 //===//
23600 //--- DROPBITS(here.bits) ---//
23601 hold >>>= here_bits;
23602 bits -= here_bits;
23603 //---//
23604 len = 0;
23605 copy = 11 + (hold & 0x7f);//BITS(7);
23606 //--- DROPBITS(7) ---//
23607 hold >>>= 7;
23608 bits -= 7;
23609 //---//
23610 }
23611 if (state.have + copy > state.nlen + state.ndist) {
23612 strm.msg = 'invalid bit length repeat';
23613 state.mode = BAD$1;
23614 break;
23615 }
23616 while (copy--) {
23617 state.lens[state.have++] = len;
23618 }
23619 }
23620 }
23621
23622 /* handle error breaks in while */
23623 if (state.mode === BAD$1) { break; }
23624
23625 /* check for end-of-block code (better have one) */
23626 if (state.lens[256] === 0) {
23627 strm.msg = 'invalid code -- missing end-of-block';
23628 state.mode = BAD$1;
23629 break;
23630 }
23631
23632 /* build code tables -- note: do not change the lenbits or distbits
23633 values here (9 and 6) without reading the comments in inftrees.h
23634 concerning the ENOUGH constants, which depend on those values */
23635 state.lenbits = 9;
23636
23637 opts = { bits: state.lenbits };
23638 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
23639 // We have separate tables & no pointers. 2 commented lines below not needed.
23640 // state.next_index = opts.table_index;
23641 state.lenbits = opts.bits;
23642 // state.lencode = state.next;
23643
23644 if (ret) {
23645 strm.msg = 'invalid literal/lengths set';
23646 state.mode = BAD$1;
23647 break;
23648 }
23649
23650 state.distbits = 6;
23651 //state.distcode.copy(state.codes);
23652 // Switch to use dynamic table
23653 state.distcode = state.distdyn;
23654 opts = { bits: state.distbits };
23655 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
23656 // We have separate tables & no pointers. 2 commented lines below not needed.
23657 // state.next_index = opts.table_index;
23658 state.distbits = opts.bits;
23659 // state.distcode = state.next;
23660
23661 if (ret) {
23662 strm.msg = 'invalid distances set';
23663 state.mode = BAD$1;
23664 break;
23665 }
23666 //Tracev((stderr, 'inflate: codes ok\n'));
23667 state.mode = LEN_;
23668 if (flush === Z_TREES) { break inf_leave; }
23669 /* falls through */
23670 case LEN_:
23671 state.mode = LEN;
23672 /* falls through */
23673 case LEN:
23674 if (have >= 6 && left >= 258) {
23675 //--- RESTORE() ---
23676 strm.next_out = put;
23677 strm.avail_out = left;
23678 strm.next_in = next;
23679 strm.avail_in = have;
23680 state.hold = hold;
23681 state.bits = bits;
23682 //---
23683 inflate_fast(strm, _out);
23684 //--- LOAD() ---
23685 put = strm.next_out;
23686 output = strm.output;
23687 left = strm.avail_out;
23688 next = strm.next_in;
23689 input = strm.input;
23690 have = strm.avail_in;
23691 hold = state.hold;
23692 bits = state.bits;
23693 //---
23694
23695 if (state.mode === TYPE$1) {
23696 state.back = -1;
23697 }
23698 break;
23699 }
23700 state.back = 0;
23701 for (;;) {
23702 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
23703 here_bits = here >>> 24;
23704 here_op = (here >>> 16) & 0xff;
23705 here_val = here & 0xffff;
23706
23707 if (here_bits <= bits) { break; }
23708 //--- PULLBYTE() ---//
23709 if (have === 0) { break inf_leave; }
23710 have--;
23711 hold += input[next++] << bits;
23712 bits += 8;
23713 //---//
23714 }
23715 if (here_op && (here_op & 0xf0) === 0) {
23716 last_bits = here_bits;
23717 last_op = here_op;
23718 last_val = here_val;
23719 for (;;) {
23720 here = state.lencode[last_val +
23721 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
23722 here_bits = here >>> 24;
23723 here_op = (here >>> 16) & 0xff;
23724 here_val = here & 0xffff;
23725
23726 if ((last_bits + here_bits) <= bits) { break; }
23727 //--- PULLBYTE() ---//
23728 if (have === 0) { break inf_leave; }
23729 have--;
23730 hold += input[next++] << bits;
23731 bits += 8;
23732 //---//
23733 }
23734 //--- DROPBITS(last.bits) ---//
23735 hold >>>= last_bits;
23736 bits -= last_bits;
23737 //---//
23738 state.back += last_bits;
23739 }
23740 //--- DROPBITS(here.bits) ---//
23741 hold >>>= here_bits;
23742 bits -= here_bits;
23743 //---//
23744 state.back += here_bits;
23745 state.length = here_val;
23746 if (here_op === 0) {
23747 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
23748 // "inflate: literal '%c'\n" :
23749 // "inflate: literal 0x%02x\n", here.val));
23750 state.mode = LIT;
23751 break;
23752 }
23753 if (here_op & 32) {
23754 //Tracevv((stderr, "inflate: end of block\n"));
23755 state.back = -1;
23756 state.mode = TYPE$1;
23757 break;
23758 }
23759 if (here_op & 64) {
23760 strm.msg = 'invalid literal/length code';
23761 state.mode = BAD$1;
23762 break;
23763 }
23764 state.extra = here_op & 15;
23765 state.mode = LENEXT;
23766 /* falls through */
23767 case LENEXT:
23768 if (state.extra) {
23769 //=== NEEDBITS(state.extra);
23770 n = state.extra;
23771 while (bits < n) {
23772 if (have === 0) { break inf_leave; }
23773 have--;
23774 hold += input[next++] << bits;
23775 bits += 8;
23776 }
23777 //===//
23778 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
23779 //--- DROPBITS(state.extra) ---//
23780 hold >>>= state.extra;
23781 bits -= state.extra;
23782 //---//
23783 state.back += state.extra;
23784 }
23785 //Tracevv((stderr, "inflate: length %u\n", state.length));
23786 state.was = state.length;
23787 state.mode = DIST;
23788 /* falls through */
23789 case DIST:
23790 for (;;) {
23791 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
23792 here_bits = here >>> 24;
23793 here_op = (here >>> 16) & 0xff;
23794 here_val = here & 0xffff;
23795
23796 if ((here_bits) <= bits) { break; }
23797 //--- PULLBYTE() ---//
23798 if (have === 0) { break inf_leave; }
23799 have--;
23800 hold += input[next++] << bits;
23801 bits += 8;
23802 //---//
23803 }
23804 if ((here_op & 0xf0) === 0) {
23805 last_bits = here_bits;
23806 last_op = here_op;
23807 last_val = here_val;
23808 for (;;) {
23809 here = state.distcode[last_val +
23810 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
23811 here_bits = here >>> 24;
23812 here_op = (here >>> 16) & 0xff;
23813 here_val = here & 0xffff;
23814
23815 if ((last_bits + here_bits) <= bits) { break; }
23816 //--- PULLBYTE() ---//
23817 if (have === 0) { break inf_leave; }
23818 have--;
23819 hold += input[next++] << bits;
23820 bits += 8;
23821 //---//
23822 }
23823 //--- DROPBITS(last.bits) ---//
23824 hold >>>= last_bits;
23825 bits -= last_bits;
23826 //---//
23827 state.back += last_bits;
23828 }
23829 //--- DROPBITS(here.bits) ---//
23830 hold >>>= here_bits;
23831 bits -= here_bits;
23832 //---//
23833 state.back += here_bits;
23834 if (here_op & 64) {
23835 strm.msg = 'invalid distance code';
23836 state.mode = BAD$1;
23837 break;
23838 }
23839 state.offset = here_val;
23840 state.extra = (here_op) & 15;
23841 state.mode = DISTEXT;
23842 /* falls through */
23843 case DISTEXT:
23844 if (state.extra) {
23845 //=== NEEDBITS(state.extra);
23846 n = state.extra;
23847 while (bits < n) {
23848 if (have === 0) { break inf_leave; }
23849 have--;
23850 hold += input[next++] << bits;
23851 bits += 8;
23852 }
23853 //===//
23854 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
23855 //--- DROPBITS(state.extra) ---//
23856 hold >>>= state.extra;
23857 bits -= state.extra;
23858 //---//
23859 state.back += state.extra;
23860 }
23861//#ifdef INFLATE_STRICT
23862 if (state.offset > state.dmax) {
23863 strm.msg = 'invalid distance too far back';
23864 state.mode = BAD$1;
23865 break;
23866 }
23867//#endif
23868 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
23869 state.mode = MATCH;
23870 /* falls through */
23871 case MATCH:
23872 if (left === 0) { break inf_leave; }
23873 copy = _out - left;
23874 if (state.offset > copy) { /* copy from window */
23875 copy = state.offset - copy;
23876 if (copy > state.whave) {
23877 if (state.sane) {
23878 strm.msg = 'invalid distance too far back';
23879 state.mode = BAD$1;
23880 break;
23881 }
23882// (!) This block is disabled in zlib defaults,
23883// don't enable it for binary compatibility
23884//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
23885// Trace((stderr, "inflate.c too far\n"));
23886// copy -= state.whave;
23887// if (copy > state.length) { copy = state.length; }
23888// if (copy > left) { copy = left; }
23889// left -= copy;
23890// state.length -= copy;
23891// do {
23892// output[put++] = 0;
23893// } while (--copy);
23894// if (state.length === 0) { state.mode = LEN; }
23895// break;
23896//#endif
23897 }
23898 if (copy > state.wnext) {
23899 copy -= state.wnext;
23900 from = state.wsize - copy;
23901 }
23902 else {
23903 from = state.wnext - copy;
23904 }
23905 if (copy > state.length) { copy = state.length; }
23906 from_source = state.window;
23907 }
23908 else { /* copy from output */
23909 from_source = output;
23910 from = put - state.offset;
23911 copy = state.length;
23912 }
23913 if (copy > left) { copy = left; }
23914 left -= copy;
23915 state.length -= copy;
23916 do {
23917 output[put++] = from_source[from++];
23918 } while (--copy);
23919 if (state.length === 0) { state.mode = LEN; }
23920 break;
23921 case LIT:
23922 if (left === 0) { break inf_leave; }
23923 output[put++] = state.length;
23924 left--;
23925 state.mode = LEN;
23926 break;
23927 case CHECK:
23928 if (state.wrap) {
23929 //=== NEEDBITS(32);
23930 while (bits < 32) {
23931 if (have === 0) { break inf_leave; }
23932 have--;
23933 // Use '|' instead of '+' to make sure that result is signed
23934 hold |= input[next++] << bits;
23935 bits += 8;
23936 }
23937 //===//
23938 _out -= left;
23939 strm.total_out += _out;
23940 state.total += _out;
23941 if (_out) {
23942 strm.adler = state.check =
23943 /*UPDATE(state.check, put - _out, _out);*/
23944 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
23945
23946 }
23947 _out = left;
23948 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
23949 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
23950 strm.msg = 'incorrect data check';
23951 state.mode = BAD$1;
23952 break;
23953 }
23954 //=== INITBITS();
23955 hold = 0;
23956 bits = 0;
23957 //===//
23958 //Tracev((stderr, "inflate: check matches trailer\n"));
23959 }
23960 state.mode = LENGTH;
23961 /* falls through */
23962 case LENGTH:
23963 if (state.wrap && state.flags) {
23964 //=== NEEDBITS(32);
23965 while (bits < 32) {
23966 if (have === 0) { break inf_leave; }
23967 have--;
23968 hold += input[next++] << bits;
23969 bits += 8;
23970 }
23971 //===//
23972 if (hold !== (state.total & 0xffffffff)) {
23973 strm.msg = 'incorrect length check';
23974 state.mode = BAD$1;
23975 break;
23976 }
23977 //=== INITBITS();
23978 hold = 0;
23979 bits = 0;
23980 //===//
23981 //Tracev((stderr, "inflate: length matches trailer\n"));
23982 }
23983 state.mode = DONE;
23984 /* falls through */
23985 case DONE:
23986 ret = Z_STREAM_END;
23987 break inf_leave;
23988 case BAD$1:
23989 ret = Z_DATA_ERROR;
23990 break inf_leave;
23991 // case MEM:
23992 // return Z_MEM_ERROR;
23993 case SYNC:
23994 /* falls through */
23995 default:
23996 return Z_STREAM_ERROR;
23997 }
23998 }
23999
24000 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
24001
24002 /*
24003 Return from inflate(), updating the total counts and the check value.
24004 If there was no progress during the inflate() call, return a buffer
24005 error. Call updatewindow() to create and/or update the window state.
24006 Note: a memory error from inflate() is non-recoverable.
24007 */
24008
24009 //--- RESTORE() ---
24010 strm.next_out = put;
24011 strm.avail_out = left;
24012 strm.next_in = next;
24013 strm.avail_in = have;
24014 state.hold = hold;
24015 state.bits = bits;
24016 //---
24017
24018 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
24019 (state.mode < CHECK || flush !== Z_FINISH))) {
24020 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
24021 }
24022 _in -= strm.avail_in;
24023 _out -= strm.avail_out;
24024 strm.total_in += _in;
24025 strm.total_out += _out;
24026 state.total += _out;
24027 if (state.wrap && _out) {
24028 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
24029 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
24030 }
24031 strm.data_type = state.bits + (state.last ? 64 : 0) +
24032 (state.mode === TYPE$1 ? 128 : 0) +
24033 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
24034 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
24035 ret = Z_BUF_ERROR;
24036 }
24037 return ret;
24038}
24039
24040function inflateEnd(strm) {
24041
24042 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
24043 return Z_STREAM_ERROR;
24044 }
24045
24046 const state = strm.state;
24047 if (state.window) {
24048 state.window = null;
24049 }
24050 strm.state = null;
24051 return Z_OK;
24052}
24053
24054function inflateGetHeader(strm, head) {
24055 let state;
24056
24057 /* check state */
24058 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
24059 state = strm.state;
24060 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
24061
24062 /* save header structure */
24063 state.head = head;
24064 head.done = false;
24065 return Z_OK;
24066}
24067
24068function inflateSetDictionary(strm, dictionary) {
24069 const dictLength = dictionary.length;
24070
24071 let state;
24072 let dictid;
24073
24074 /* check state */
24075 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
24076 state = strm.state;
24077
24078 if (state.wrap !== 0 && state.mode !== DICT) {
24079 return Z_STREAM_ERROR;
24080 }
24081
24082 /* check for correct dictionary identifier */
24083 if (state.mode === DICT) {
24084 dictid = 1; /* adler32(0, null, 0)*/
24085 /* dictid = adler32(dictid, dictionary, dictLength); */
24086 dictid = adler32(dictid, dictionary, dictLength, 0);
24087 if (dictid !== state.check) {
24088 return Z_DATA_ERROR;
24089 }
24090 }
24091 /* copy dictionary to window using updatewindow(), which will amend the
24092 existing dictionary if appropriate */
24093 updatewindow(strm, dictionary, dictLength, dictLength);
24094 // if (ret) {
24095 // state.mode = MEM;
24096 // return Z_MEM_ERROR;
24097 // }
24098 state.havedict = 1;
24099 // Tracev((stderr, "inflate: dictionary set\n"));
24100 return Z_OK;
24101}
24102
24103/* Not implemented
24104exports.inflateCopy = inflateCopy;
24105exports.inflateGetDictionary = inflateGetDictionary;
24106exports.inflateMark = inflateMark;
24107exports.inflatePrime = inflatePrime;
24108exports.inflateSync = inflateSync;
24109exports.inflateSyncPoint = inflateSyncPoint;
24110exports.inflateUndermine = inflateUndermine;
24111*/
24112
24113// (C) 1995-2013 Jean-loup Gailly and Mark Adler
24114// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
24115//
24116// This software is provided 'as-is', without any express or implied
24117// warranty. In no event will the authors be held liable for any damages
24118// arising from the use of this software.
24119//
24120// Permission is granted to anyone to use this software for any purpose,
24121// including commercial applications, and to alter it and redistribute it
24122// freely, subject to the following restrictions:
24123//
24124// 1. The origin of this software must not be misrepresented; you must not
24125// claim that you wrote the original software. If you use this software
24126// in a product, an acknowledgment in the product documentation would be
24127// appreciated but is not required.
24128// 2. Altered source versions must be plainly marked as such, and must not be
24129// misrepresented as being the original software.
24130// 3. This notice may not be removed or altered from any source distribution.
24131
24132class GZheader {
24133 constructor() {
24134 /* true if compressed data believed to be text */
24135 this.text = 0;
24136 /* modification time */
24137 this.time = 0;
24138 /* extra flags (not used when writing a gzip file) */
24139 this.xflags = 0;
24140 /* operating system */
24141 this.os = 0;
24142 /* pointer to extra field or Z_NULL if none */
24143 this.extra = null;
24144 /* extra field length (valid if extra != Z_NULL) */
24145 this.extra_len = 0; // Actually, we don't need it in JS,
24146 // but leave for few code modifications
24147
24148 //
24149 // Setup limits is not necessary because in js we should not preallocate memory
24150 // for inflate use constant limit in 65536 bytes
24151 //
24152
24153 /* space at extra (only when reading header) */
24154 // this.extra_max = 0;
24155 /* pointer to zero-terminated file name or Z_NULL */
24156 this.name = '';
24157 /* space at name (only when reading header) */
24158 // this.name_max = 0;
24159 /* pointer to zero-terminated comment or Z_NULL */
24160 this.comment = '';
24161 /* space at comment (only when reading header) */
24162 // this.comm_max = 0;
24163 /* true if there was or will be a header crc */
24164 this.hcrc = 0;
24165 /* true when done reading gzip header (not used when writing a gzip file) */
24166 this.done = false;
24167 }
24168}
24169
24170/**
24171 * class Inflate
24172 *
24173 * Generic JS-style wrapper for zlib calls. If you don't need
24174 * streaming behaviour - use more simple functions: [[inflate]]
24175 * and [[inflateRaw]].
24176 **/
24177
24178/* internal
24179 * inflate.chunks -> Array
24180 *
24181 * Chunks of output data, if [[Inflate#onData]] not overridden.
24182 **/
24183
24184/**
24185 * Inflate.result -> Uint8Array|Array|String
24186 *
24187 * Uncompressed result, generated by default [[Inflate#onData]]
24188 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
24189 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
24190 * push a chunk with explicit flush (call [[Inflate#push]] with
24191 * `Z_SYNC_FLUSH` param).
24192 **/
24193
24194/**
24195 * Inflate.err -> Number
24196 *
24197 * Error code after inflate finished. 0 (Z_OK) on success.
24198 * Should be checked if broken data possible.
24199 **/
24200
24201/**
24202 * Inflate.msg -> String
24203 *
24204 * Error message, if [[Inflate.err]] != 0
24205 **/
24206
24207
24208/**
24209 * new Inflate(options)
24210 * - options (Object): zlib inflate options.
24211 *
24212 * Creates new inflator instance with specified params. Throws exception
24213 * on bad params. Supported options:
24214 *
24215 * - `windowBits`
24216 * - `dictionary`
24217 *
24218 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
24219 * for more information on these.
24220 *
24221 * Additional options, for internal needs:
24222 *
24223 * - `chunkSize` - size of generated data chunks (16K by default)
24224 * - `raw` (Boolean) - do raw inflate
24225 * - `to` (String) - if equal to 'string', then result will be converted
24226 * from utf8 to utf16 (javascript) string. When string output requested,
24227 * chunk length can differ from `chunkSize`, depending on content.
24228 *
24229 * By default, when no options set, autodetect deflate/gzip data format via
24230 * wrapper header.
24231 *
24232 * ##### Example:
24233 *
24234 * ```javascript
24235 * var pako = require('pako')
24236 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
24237 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
24238 *
24239 * var inflate = new pako.Inflate({ level: 3});
24240 *
24241 * inflate.push(chunk1, false);
24242 * inflate.push(chunk2, true); // true -> last chunk
24243 *
24244 * if (inflate.err) { throw new Error(inflate.err); }
24245 *
24246 * console.log(inflate.result);
24247 * ```
24248 **/
24249class Inflate {
24250 constructor(options) {
24251 this.options = {
24252 chunkSize: 16384,
24253 windowBits: 0,
24254 ...(options || {})
24255 };
24256
24257 const opt = this.options;
24258
24259 // Force window size for `raw` data, if not set directly,
24260 // because we have no header for autodetect.
24261 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
24262 opt.windowBits = -opt.windowBits;
24263 if (opt.windowBits === 0) { opt.windowBits = -15; }
24264 }
24265
24266 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
24267 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
24268 !(options && options.windowBits)) {
24269 opt.windowBits += 32;
24270 }
24271
24272 // Gzip header has no info about windows size, we can do autodetect only
24273 // for deflate. So, if window size not set, force it to max when gzip possible
24274 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
24275 // bit 3 (16) -> gzipped data
24276 // bit 4 (32) -> autodetect gzip/deflate
24277 if ((opt.windowBits & 15) === 0) {
24278 opt.windowBits |= 15;
24279 }
24280 }
24281
24282 this.err = 0; // error code, if happens (0 = Z_OK)
24283 this.msg = ''; // error message
24284 this.ended = false; // used to avoid multiple onEnd() calls
24285 this.chunks = []; // chunks of compressed data
24286
24287 this.strm = new ZStream();
24288 this.strm.avail_out = 0;
24289
24290 let status = inflateInit2(
24291 this.strm,
24292 opt.windowBits
24293 );
24294
24295 if (status !== Z_OK) {
24296 throw new Error(msg[status]);
24297 }
24298
24299 this.header = new GZheader();
24300
24301 inflateGetHeader(this.strm, this.header);
24302
24303 // Setup dictionary
24304 if (opt.dictionary) {
24305 // Convert data if needed
24306 if (typeof opt.dictionary === 'string') {
24307 opt.dictionary = string2buf(opt.dictionary);
24308 } else if (opt.dictionary instanceof ArrayBuffer) {
24309 opt.dictionary = new Uint8Array(opt.dictionary);
24310 }
24311 if (opt.raw) { //In raw mode we need to set the dictionary early
24312 status = inflateSetDictionary(this.strm, opt.dictionary);
24313 if (status !== Z_OK) {
24314 throw new Error(msg[status]);
24315 }
24316 }
24317 }
24318 }
24319 /**
24320 * Inflate#push(data[, mode]) -> Boolean
24321 * - data (Uint8Array|Array|ArrayBuffer|String): input data
24322 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
24323 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
24324 *
24325 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
24326 * new output chunks. Returns `true` on success. The last data block must have
24327 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
24328 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
24329 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
24330 *
24331 * On fail call [[Inflate#onEnd]] with error code and return false.
24332 *
24333 * We strongly recommend to use `Uint8Array` on input for best speed (output
24334 * format is detected automatically). Also, don't skip last param and always
24335 * use the same type in your code (boolean or number). That will improve JS speed.
24336 *
24337 * For regular `Array`-s make sure all elements are [0..255].
24338 *
24339 * ##### Example
24340 *
24341 * ```javascript
24342 * push(chunk, false); // push one of data chunks
24343 * ...
24344 * push(chunk, true); // push last chunk
24345 * ```
24346 **/
24347 push(data, mode) {
24348 const { strm, options: { chunkSize, dictionary } } = this;
24349 let status, _mode;
24350
24351 // Flag to properly process Z_BUF_ERROR on testing inflate call
24352 // when we check that all output data was flushed.
24353 let allowBufError = false;
24354
24355 if (this.ended) { return false; }
24356 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
24357
24358 // Convert data if needed
24359 if (typeof data === 'string') {
24360 // Only binary strings can be decompressed on practice
24361 strm.input = binstring2buf(data);
24362 } else if (data instanceof ArrayBuffer) {
24363 strm.input = new Uint8Array(data);
24364 } else {
24365 strm.input = data;
24366 }
24367
24368 strm.next_in = 0;
24369 strm.avail_in = strm.input.length;
24370
24371 do {
24372 if (strm.avail_out === 0) {
24373 strm.output = new Buf8(chunkSize);
24374 strm.next_out = 0;
24375 strm.avail_out = chunkSize;
24376 }
24377
24378 status = inflate(strm, Z_NO_FLUSH); /* no bad return value */
24379
24380 if (status === Z_NEED_DICT && dictionary) {
24381 status = inflateSetDictionary(this.strm, dictionary);
24382 }
24383
24384 if (status === Z_BUF_ERROR && allowBufError === true) {
24385 status = Z_OK;
24386 allowBufError = false;
24387 }
24388
24389 if (status !== Z_STREAM_END && status !== Z_OK) {
24390 this.onEnd(status);
24391 this.ended = true;
24392 return false;
24393 }
24394
24395 if (strm.next_out) {
24396 if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
24397 this.onData(shrinkBuf(strm.output, strm.next_out));
24398 }
24399 }
24400
24401 // When no more input data, we should check that internal inflate buffers
24402 // are flushed. The only way to do it when avail_out = 0 - run one more
24403 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
24404 // Here we set flag to process this error properly.
24405 //
24406 // NOTE. Deflate does not return error in this case and does not needs such
24407 // logic.
24408 if (strm.avail_in === 0 && strm.avail_out === 0) {
24409 allowBufError = true;
24410 }
24411
24412 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
24413
24414 if (status === Z_STREAM_END) {
24415 _mode = Z_FINISH;
24416 }
24417
24418 // Finalize on the last chunk.
24419 if (_mode === Z_FINISH) {
24420 status = inflateEnd(this.strm);
24421 this.onEnd(status);
24422 this.ended = true;
24423 return status === Z_OK;
24424 }
24425
24426 // callback interim results if Z_SYNC_FLUSH.
24427 if (_mode === Z_SYNC_FLUSH) {
24428 this.onEnd(Z_OK);
24429 strm.avail_out = 0;
24430 return true;
24431 }
24432
24433 return true;
24434 };
24435
24436 /**
24437 * Inflate#onData(chunk) -> Void
24438 * - chunk (Uint8Array|Array|String): output data. Type of array depends
24439 * on js engine support. When string output requested, each chunk
24440 * will be string.
24441 *
24442 * By default, stores data blocks in `chunks[]` property and glue
24443 * those in `onEnd`. Override this handler, if you need another behaviour.
24444 **/
24445 onData(chunk) {
24446 this.chunks.push(chunk);
24447 };
24448
24449
24450
24451 /**
24452 * Inflate#onEnd(status) -> Void
24453 * - status (Number): inflate status. 0 (Z_OK) on success,
24454 * other if not.
24455 *
24456 * Called either after you tell inflate that the input stream is
24457 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
24458 * or if an error happened. By default - join collected chunks,
24459 * free memory and fill `results` / `err` properties.
24460 **/
24461 onEnd(status) {
24462 // On success - join
24463 if (status === Z_OK) {
24464 this.result = flattenChunks(this.chunks);
24465 }
24466 this.chunks = [];
24467 this.err = status;
24468 this.msg = this.strm.msg;
24469 };
24470}
24471
24472/*
24473node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
24474
24475Copyright (C) 2012 Eli Skeggs
24476
24477This library is free software; you can redistribute it and/or
24478modify it under the terms of the GNU Lesser General Public
24479License as published by the Free Software Foundation; either
24480version 2.1 of the License, or (at your option) any later version.
24481
24482This library is distributed in the hope that it will be useful,
24483but WITHOUT ANY WARRANTY; without even the implied warranty of
24484MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24485Lesser General Public License for more details.
24486
24487You should have received a copy of the GNU Lesser General Public
24488License along with this library; if not, see
24489http://www.gnu.org/licenses/lgpl-2.1.html
24490
24491Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
24492
24493Based on micro-bunzip by Rob Landley (rob@landley.net).
24494
24495Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
24496which also acknowledges contributions by Mike Burrows, David Wheeler,
24497Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
24498Robert Sedgewick, and Jon L. Bentley.
24499*/
24500
24501var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
24502
24503// offset in bytes
24504var BitReader = function(stream) {
24505 this.stream = stream;
24506 this.bitOffset = 0;
24507 this.curByte = 0;
24508 this.hasByte = false;
24509};
24510
24511BitReader.prototype._ensureByte = function() {
24512 if (!this.hasByte) {
24513 this.curByte = this.stream.readByte();
24514 this.hasByte = true;
24515 }
24516};
24517
24518// reads bits from the buffer
24519BitReader.prototype.read = function(bits) {
24520 var result = 0;
24521 while (bits > 0) {
24522 this._ensureByte();
24523 var remaining = 8 - this.bitOffset;
24524 // if we're in a byte
24525 if (bits >= remaining) {
24526 result <<= remaining;
24527 result |= BITMASK[remaining] & this.curByte;
24528 this.hasByte = false;
24529 this.bitOffset = 0;
24530 bits -= remaining;
24531 } else {
24532 result <<= bits;
24533 var shift = remaining - bits;
24534 result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;
24535 this.bitOffset += bits;
24536 bits = 0;
24537 }
24538 }
24539 return result;
24540};
24541
24542// seek to an arbitrary point in the buffer (expressed in bits)
24543BitReader.prototype.seek = function(pos) {
24544 var n_bit = pos % 8;
24545 var n_byte = (pos - n_bit) / 8;
24546 this.bitOffset = n_bit;
24547 this.stream.seek(n_byte);
24548 this.hasByte = false;
24549};
24550
24551// reads 6 bytes worth of data using the read method
24552BitReader.prototype.pi = function() {
24553 var buf = new Uint8Array(6), i;
24554 for (i = 0; i < buf.length; i++) {
24555 buf[i] = this.read(8);
24556 }
24557 return bufToHex(buf);
24558};
24559
24560function bufToHex(buf) {
24561 return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
24562}
24563
24564var bitreader = BitReader;
24565
24566/* very simple input/output stream interface */
24567var Stream = function() {
24568};
24569
24570// input streams //////////////
24571/** Returns the next byte, or -1 for EOF. */
24572Stream.prototype.readByte = function() {
24573 throw new Error("abstract method readByte() not implemented");
24574};
24575/** Attempts to fill the buffer; returns number of bytes read, or
24576 * -1 for EOF. */
24577Stream.prototype.read = function(buffer, bufOffset, length) {
24578 var bytesRead = 0;
24579 while (bytesRead < length) {
24580 var c = this.readByte();
24581 if (c < 0) { // EOF
24582 return (bytesRead===0) ? -1 : bytesRead;
24583 }
24584 buffer[bufOffset++] = c;
24585 bytesRead++;
24586 }
24587 return bytesRead;
24588};
24589Stream.prototype.seek = function(new_pos) {
24590 throw new Error("abstract method seek() not implemented");
24591};
24592
24593// output streams ///////////
24594Stream.prototype.writeByte = function(_byte) {
24595 throw new Error("abstract method readByte() not implemented");
24596};
24597Stream.prototype.write = function(buffer, bufOffset, length) {
24598 var i;
24599 for (i=0; i<length; i++) {
24600 this.writeByte(buffer[bufOffset++]);
24601 }
24602 return length;
24603};
24604Stream.prototype.flush = function() {
24605};
24606
24607var stream$1 = Stream;
24608
24609/* CRC32, used in Bzip2 implementation.
24610 * This is a port of CRC32.java from the jbzip2 implementation at
24611 * https://code.google.com/p/jbzip2
24612 * which is:
24613 * Copyright (c) 2011 Matthew Francis
24614 *
24615 * Permission is hereby granted, free of charge, to any person
24616 * obtaining a copy of this software and associated documentation
24617 * files (the "Software"), to deal in the Software without
24618 * restriction, including without limitation the rights to use,
24619 * copy, modify, merge, publish, distribute, sublicense, and/or sell
24620 * copies of the Software, and to permit persons to whom the
24621 * Software is furnished to do so, subject to the following
24622 * conditions:
24623 *
24624 * The above copyright notice and this permission notice shall be
24625 * included in all copies or substantial portions of the Software.
24626 *
24627 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24628 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
24629 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24630 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
24631 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24632 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24633 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24634 * OTHER DEALINGS IN THE SOFTWARE.
24635 * This JavaScript implementation is:
24636 * Copyright (c) 2013 C. Scott Ananian
24637 * with the same licensing terms as Matthew Francis' original implementation.
24638 */
24639var crc32$1 = (function() {
24640
24641 /**
24642 * A static CRC lookup table
24643 */
24644 var crc32Lookup = new Uint32Array([
24645 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
24646 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
24647 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
24648 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
24649 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
24650 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
24651 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
24652 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
24653 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
24654 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
24655 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
24656 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
24657 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
24658 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
24659 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
24660 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
24661 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
24662 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
24663 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
24664 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
24665 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
24666 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
24667 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
24668 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
24669 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
24670 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
24671 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
24672 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
24673 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
24674 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
24675 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
24676 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
24677 ]);
24678
24679 var CRC32 = function() {
24680 /**
24681 * The current CRC
24682 */
24683 var crc = 0xffffffff;
24684
24685 /**
24686 * @return The current CRC
24687 */
24688 this.getCRC = function() {
24689 return (~crc) >>> 0; // return an unsigned value
24690 };
24691
24692 /**
24693 * Update the CRC with a single byte
24694 * @param value The value to update the CRC with
24695 */
24696 this.updateCRC = function(value) {
24697 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
24698 };
24699
24700 /**
24701 * Update the CRC with a sequence of identical bytes
24702 * @param value The value to update the CRC with
24703 * @param count The number of bytes
24704 */
24705 this.updateCRCRun = function(value, count) {
24706 while (count-- > 0) {
24707 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
24708 }
24709 };
24710 };
24711 return CRC32;
24712})();
24713
24714/*
24715seek-bzip - a pure-javascript module for seeking within bzip2 data
24716
24717Copyright (C) 2013 C. Scott Ananian
24718Copyright (C) 2012 Eli Skeggs
24719Copyright (C) 2011 Kevin Kwok
24720
24721This library is free software; you can redistribute it and/or
24722modify it under the terms of the GNU Lesser General Public
24723License as published by the Free Software Foundation; either
24724version 2.1 of the License, or (at your option) any later version.
24725
24726This library is distributed in the hope that it will be useful,
24727but WITHOUT ANY WARRANTY; without even the implied warranty of
24728MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24729Lesser General Public License for more details.
24730
24731You should have received a copy of the GNU Lesser General Public
24732License along with this library; if not, see
24733http://www.gnu.org/licenses/lgpl-2.1.html
24734
24735Adapted from node-bzip, copyright 2012 Eli Skeggs.
24736Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
24737
24738Based on micro-bunzip by Rob Landley (rob@landley.net).
24739
24740Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
24741which also acknowledges contributions by Mike Burrows, David Wheeler,
24742Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
24743Robert Sedgewick, and Jon L. Bentley.
24744*/
24745
24746
24747
24748
24749
24750var MAX_HUFCODE_BITS = 20;
24751var MAX_SYMBOLS = 258;
24752var SYMBOL_RUNA = 0;
24753var SYMBOL_RUNB = 1;
24754var MIN_GROUPS = 2;
24755var MAX_GROUPS = 6;
24756var GROUP_SIZE = 50;
24757
24758var WHOLEPI = "314159265359";
24759var SQRTPI = "177245385090";
24760
24761var mtf = function(array, index) {
24762 var src = array[index], i;
24763 for (i = index; i > 0; i--) {
24764 array[i] = array[i-1];
24765 }
24766 array[0] = src;
24767 return src;
24768};
24769
24770var Err = {
24771 OK: 0,
24772 LAST_BLOCK: -1,
24773 NOT_BZIP_DATA: -2,
24774 UNEXPECTED_INPUT_EOF: -3,
24775 UNEXPECTED_OUTPUT_EOF: -4,
24776 DATA_ERROR: -5,
24777 OUT_OF_MEMORY: -6,
24778 OBSOLETE_INPUT: -7,
24779 END_OF_BLOCK: -8
24780};
24781var ErrorMessages = {};
24782ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
24783ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
24784ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
24785ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
24786ErrorMessages[Err.DATA_ERROR] = "Data error";
24787ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
24788ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
24789
24790var _throw = function(status, optDetail) {
24791 var msg = ErrorMessages[status] || 'unknown error';
24792 if (optDetail) { msg += ': '+optDetail; }
24793 var e = new TypeError(msg);
24794 e.errorCode = status;
24795 throw e;
24796};
24797
24798var Bunzip = function(inputStream, outputStream) {
24799 this.writePos = this.writeCurrent = this.writeCount = 0;
24800
24801 this._start_bunzip(inputStream, outputStream);
24802};
24803Bunzip.prototype._init_block = function() {
24804 var moreBlocks = this._get_next_block();
24805 if ( !moreBlocks ) {
24806 this.writeCount = -1;
24807 return false; /* no more blocks */
24808 }
24809 this.blockCRC = new crc32$1();
24810 return true;
24811};
24812/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
24813Bunzip.prototype._start_bunzip = function(inputStream, outputStream) {
24814 /* Ensure that file starts with "BZh['1'-'9']." */
24815 var buf = new Uint8Array(4);
24816 if (inputStream.read(buf, 0, 4) !== 4 ||
24817 String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')
24818 _throw(Err.NOT_BZIP_DATA, 'bad magic');
24819
24820 var level = buf[3] - 0x30;
24821 if (level < 1 || level > 9)
24822 _throw(Err.NOT_BZIP_DATA, 'level out of range');
24823
24824 this.reader = new bitreader(inputStream);
24825
24826 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
24827 uncompressed data. Allocate intermediate buffer for block. */
24828 this.dbufSize = 100000 * level;
24829 this.nextoutput = 0;
24830 this.outputStream = outputStream;
24831 this.streamCRC = 0;
24832};
24833Bunzip.prototype._get_next_block = function() {
24834 var i, j, k;
24835 var reader = this.reader;
24836 // this is get_next_block() function from micro-bunzip:
24837 /* Read in header signature and CRC, then validate signature.
24838 (last block signature means CRC is for whole file, return now) */
24839 var h = reader.pi();
24840 if (h === SQRTPI) { // last block
24841 return false; /* no more blocks */
24842 }
24843 if (h !== WHOLEPI)
24844 _throw(Err.NOT_BZIP_DATA);
24845 this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
24846 this.streamCRC = (this.targetBlockCRC ^
24847 ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;
24848 /* We can add support for blockRandomised if anybody complains. There was
24849 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
24850 it didn't actually work. */
24851 if (reader.read(1))
24852 _throw(Err.OBSOLETE_INPUT);
24853 var origPointer = reader.read(24);
24854 if (origPointer > this.dbufSize)
24855 _throw(Err.DATA_ERROR, 'initial position out of bounds');
24856 /* mapping table: if some byte values are never used (encoding things
24857 like ascii text), the compression code removes the gaps to have fewer
24858 symbols to deal with, and writes a sparse bitfield indicating which
24859 values were present. We make a translation table to convert the symbols
24860 back to the corresponding bytes. */
24861 var t = reader.read(16);
24862 var symToByte = new Uint8Array(256), symTotal = 0;
24863 for (i = 0; i < 16; i++) {
24864 if (t & (1 << (0xF - i))) {
24865 var o = i * 16;
24866 k = reader.read(16);
24867 for (j = 0; j < 16; j++)
24868 if (k & (1 << (0xF - j)))
24869 symToByte[symTotal++] = o + j;
24870 }
24871 }
24872
24873 /* How many different huffman coding groups does this block use? */
24874 var groupCount = reader.read(3);
24875 if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)
24876 _throw(Err.DATA_ERROR);
24877 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
24878 group. Read in the group selector list, which is stored as MTF encoded
24879 bit runs. (MTF=Move To Front, as each value is used it's moved to the
24880 start of the list.) */
24881 var nSelectors = reader.read(15);
24882 if (nSelectors === 0)
24883 _throw(Err.DATA_ERROR);
24884
24885 var mtfSymbol = new Uint8Array(256);
24886 for (i = 0; i < groupCount; i++)
24887 mtfSymbol[i] = i;
24888
24889 var selectors = new Uint8Array(nSelectors); // was 32768...
24890
24891 for (i = 0; i < nSelectors; i++) {
24892 /* Get next value */
24893 for (j = 0; reader.read(1); j++)
24894 if (j >= groupCount) _throw(Err.DATA_ERROR);
24895 /* Decode MTF to get the next selector */
24896 selectors[i] = mtf(mtfSymbol, j);
24897 }
24898
24899 /* Read the huffman coding tables for each group, which code for symTotal
24900 literal symbols, plus two run symbols (RUNA, RUNB) */
24901 var symCount = symTotal + 2;
24902 var groups = [], hufGroup;
24903 for (j = 0; j < groupCount; j++) {
24904 var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
24905 /* Read huffman code lengths for each symbol. They're stored in
24906 a way similar to mtf; record a starting value for the first symbol,
24907 and an offset from the previous value for everys symbol after that. */
24908 t = reader.read(5); // lengths
24909 for (i = 0; i < symCount; i++) {
24910 for (;;) {
24911 if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
24912 /* If first bit is 0, stop. Else second bit indicates whether
24913 to increment or decrement the value. */
24914 if(!reader.read(1))
24915 break;
24916 if(!reader.read(1))
24917 t++;
24918 else
24919 t--;
24920 }
24921 length[i] = t;
24922 }
24923
24924 /* Find largest and smallest lengths in this group */
24925 var minLen, maxLen;
24926 minLen = maxLen = length[0];
24927 for (i = 1; i < symCount; i++) {
24928 if (length[i] > maxLen)
24929 maxLen = length[i];
24930 else if (length[i] < minLen)
24931 minLen = length[i];
24932 }
24933
24934 /* Calculate permute[], base[], and limit[] tables from length[].
24935 *
24936 * permute[] is the lookup table for converting huffman coded symbols
24937 * into decoded symbols. base[] is the amount to subtract from the
24938 * value of a huffman symbol of a given length when using permute[].
24939 *
24940 * limit[] indicates the largest numerical value a symbol with a given
24941 * number of bits can have. This is how the huffman codes can vary in
24942 * length: each code with a value>limit[length] needs another bit.
24943 */
24944 hufGroup = {};
24945 groups.push(hufGroup);
24946 hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
24947 hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
24948 hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
24949 hufGroup.minLen = minLen;
24950 hufGroup.maxLen = maxLen;
24951 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
24952 var pp = 0;
24953 for (i = minLen; i <= maxLen; i++) {
24954 temp[i] = hufGroup.limit[i] = 0;
24955 for (t = 0; t < symCount; t++)
24956 if (length[t] === i)
24957 hufGroup.permute[pp++] = t;
24958 }
24959 /* Count symbols coded for at each bit length */
24960 for (i = 0; i < symCount; i++)
24961 temp[length[i]]++;
24962 /* Calculate limit[] (the largest symbol-coding value at each bit
24963 * length, which is (previous limit<<1)+symbols at this level), and
24964 * base[] (number of symbols to ignore at each bit length, which is
24965 * limit minus the cumulative count of symbols coded for already). */
24966 pp = t = 0;
24967 for (i = minLen; i < maxLen; i++) {
24968 pp += temp[i];
24969 /* We read the largest possible symbol size and then unget bits
24970 after determining how many we need, and those extra bits could
24971 be set to anything. (They're noise from future symbols.) At
24972 each level we're really only interested in the first few bits,
24973 so here we set all the trailing to-be-ignored bits to 1 so they
24974 don't affect the value>limit[length] comparison. */
24975 hufGroup.limit[i] = pp - 1;
24976 pp <<= 1;
24977 t += temp[i];
24978 hufGroup.base[i + 1] = pp - t;
24979 }
24980 hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
24981 hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
24982 hufGroup.base[minLen] = 0;
24983 }
24984 /* We've finished reading and digesting the block header. Now read this
24985 block's huffman coded symbols from the file and undo the huffman coding
24986 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
24987
24988 /* Initialize symbol occurrence counters and symbol Move To Front table */
24989 var byteCount = new Uint32Array(256);
24990 for (i = 0; i < 256; i++)
24991 mtfSymbol[i] = i;
24992 /* Loop through compressed symbols. */
24993 var runPos = 0, dbufCount = 0, selector = 0, uc;
24994 var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
24995 symCount = 0;
24996 for (;;) {
24997 /* Determine which huffman coding group to use. */
24998 if (!(symCount--)) {
24999 symCount = GROUP_SIZE - 1;
25000 if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }
25001 hufGroup = groups[selectors[selector++]];
25002 }
25003 /* Read next huffman-coded symbol. */
25004 i = hufGroup.minLen;
25005 j = reader.read(i);
25006 for (;;i++) {
25007 if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }
25008 if (j <= hufGroup.limit[i])
25009 break;
25010 j = (j << 1) | reader.read(1);
25011 }
25012 /* Huffman decode value to get nextSym (with bounds checking) */
25013 j -= hufGroup.base[i];
25014 if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }
25015 var nextSym = hufGroup.permute[j];
25016 /* We have now decoded the symbol, which indicates either a new literal
25017 byte, or a repeated run of the most recent literal byte. First,
25018 check if nextSym indicates a repeated run, and if so loop collecting
25019 how many times to repeat the last literal. */
25020 if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
25021 /* If this is the start of a new run, zero out counter */
25022 if (!runPos){
25023 runPos = 1;
25024 t = 0;
25025 }
25026 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
25027 each bit position, add 1 or 2 instead. For example,
25028 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
25029 You can make any bit pattern that way using 1 less symbol than
25030 the basic or 0/1 method (except all bits 0, which would use no
25031 symbols, but a run of length 0 doesn't mean anything in this
25032 context). Thus space is saved. */
25033 if (nextSym === SYMBOL_RUNA)
25034 t += runPos;
25035 else
25036 t += 2 * runPos;
25037 runPos <<= 1;
25038 continue;
25039 }
25040 /* When we hit the first non-run symbol after a run, we now know
25041 how many times to repeat the last literal, so append that many
25042 copies to our buffer of decoded symbols (dbuf) now. (The last
25043 literal used is the one at the head of the mtfSymbol array.) */
25044 if (runPos){
25045 runPos = 0;
25046 if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }
25047 uc = symToByte[mtfSymbol[0]];
25048 byteCount[uc] += t;
25049 while (t--)
25050 dbuf[dbufCount++] = uc;
25051 }
25052 /* Is this the terminating symbol? */
25053 if (nextSym > symTotal)
25054 break;
25055 /* At this point, nextSym indicates a new literal character. Subtract
25056 one to get the position in the MTF array at which this literal is
25057 currently to be found. (Note that the result can't be -1 or 0,
25058 because 0 and 1 are RUNA and RUNB. But another instance of the
25059 first symbol in the mtf array, position 0, would have been handled
25060 as part of a run above. Therefore 1 unused mtf position minus
25061 2 non-literal nextSym values equals -1.) */
25062 if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }
25063 i = nextSym - 1;
25064 uc = mtf(mtfSymbol, i);
25065 uc = symToByte[uc];
25066 /* We have our literal byte. Save it into dbuf. */
25067 byteCount[uc]++;
25068 dbuf[dbufCount++] = uc;
25069 }
25070 /* At this point, we've read all the huffman-coded symbols (and repeated
25071 runs) for this block from the input stream, and decoded them into the
25072 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
25073 Now undo the Burrows-Wheeler transform on dbuf.
25074 See http://dogma.net/markn/articles/bwt/bwt.htm
25075 */
25076 if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }
25077 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
25078 j = 0;
25079 for (i = 0; i < 256; i++) {
25080 k = j + byteCount[i];
25081 byteCount[i] = j;
25082 j = k;
25083 }
25084 /* Figure out what order dbuf would be in if we sorted it. */
25085 for (i = 0; i < dbufCount; i++) {
25086 uc = dbuf[i] & 0xff;
25087 dbuf[byteCount[uc]] |= (i << 8);
25088 byteCount[uc]++;
25089 }
25090 /* Decode first byte by hand to initialize "previous" byte. Note that it
25091 doesn't get output, and if the first three characters are identical
25092 it doesn't qualify as a run (hence writeRunCountdown=5). */
25093 var pos = 0, current = 0, run = 0;
25094 if (dbufCount) {
25095 pos = dbuf[origPointer];
25096 current = (pos & 0xff);
25097 pos >>= 8;
25098 run = -1;
25099 }
25100 this.writePos = pos;
25101 this.writeCurrent = current;
25102 this.writeCount = dbufCount;
25103 this.writeRun = run;
25104
25105 return true; /* more blocks to come */
25106};
25107/* Undo burrows-wheeler transform on intermediate buffer to produce output.
25108 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
25109 data are written to outbuf. Return value is number of bytes written or
25110 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
25111 are ignored, data is written to out_fd and return is RETVAL_OK or error.
25112*/
25113Bunzip.prototype._read_bunzip = function(outputBuffer, len) {
25114 var copies, previous, outbyte;
25115 /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
25116 decoded, which results in this returning RETVAL_LAST_BLOCK, also
25117 equal to -1... Confusing, I'm returning 0 here to indicate no
25118 bytes written into the buffer */
25119 if (this.writeCount < 0) { return 0; }
25120 var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;
25121 var dbufCount = this.writeCount; this.outputsize;
25122 var run = this.writeRun;
25123
25124 while (dbufCount) {
25125 dbufCount--;
25126 previous = current;
25127 pos = dbuf[pos];
25128 current = pos & 0xff;
25129 pos >>= 8;
25130 if (run++ === 3){
25131 copies = current;
25132 outbyte = previous;
25133 current = -1;
25134 } else {
25135 copies = 1;
25136 outbyte = current;
25137 }
25138 this.blockCRC.updateCRCRun(outbyte, copies);
25139 while (copies--) {
25140 this.outputStream.writeByte(outbyte);
25141 this.nextoutput++;
25142 }
25143 if (current != previous)
25144 run = 0;
25145 }
25146 this.writeCount = dbufCount;
25147 // check CRC
25148 if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
25149 _throw(Err.DATA_ERROR, "Bad block CRC "+
25150 "(got "+this.blockCRC.getCRC().toString(16)+
25151 " expected "+this.targetBlockCRC.toString(16)+")");
25152 }
25153 return this.nextoutput;
25154};
25155
25156var coerceInputStream = function(input) {
25157 if ('readByte' in input) { return input; }
25158 var inputStream = new stream$1();
25159 inputStream.pos = 0;
25160 inputStream.readByte = function() { return input[this.pos++]; };
25161 inputStream.seek = function(pos) { this.pos = pos; };
25162 inputStream.eof = function() { return this.pos >= input.length; };
25163 return inputStream;
25164};
25165var coerceOutputStream = function(output) {
25166 var outputStream = new stream$1();
25167 var resizeOk = true;
25168 if (output) {
25169 if (typeof(output)==='number') {
25170 outputStream.buffer = new Uint8Array(output);
25171 resizeOk = false;
25172 } else if ('writeByte' in output) {
25173 return output;
25174 } else {
25175 outputStream.buffer = output;
25176 resizeOk = false;
25177 }
25178 } else {
25179 outputStream.buffer = new Uint8Array(16384);
25180 }
25181 outputStream.pos = 0;
25182 outputStream.writeByte = function(_byte) {
25183 if (resizeOk && this.pos >= this.buffer.length) {
25184 var newBuffer = new Uint8Array(this.buffer.length*2);
25185 newBuffer.set(this.buffer);
25186 this.buffer = newBuffer;
25187 }
25188 this.buffer[this.pos++] = _byte;
25189 };
25190 outputStream.getBuffer = function() {
25191 // trim buffer
25192 if (this.pos !== this.buffer.length) {
25193 if (!resizeOk)
25194 throw new TypeError('outputsize does not match decoded input');
25195 var newBuffer = new Uint8Array(this.pos);
25196 newBuffer.set(this.buffer.subarray(0, this.pos));
25197 this.buffer = newBuffer;
25198 }
25199 return this.buffer;
25200 };
25201 outputStream._coerced = true;
25202 return outputStream;
25203};
25204
25205/* Static helper functions */
25206// 'input' can be a stream or a buffer
25207// 'output' can be a stream or a buffer or a number (buffer size)
25208const decode$2 = function(input, output, multistream) {
25209 // make a stream from a buffer, if necessary
25210 var inputStream = coerceInputStream(input);
25211 var outputStream = coerceOutputStream(output);
25212
25213 var bz = new Bunzip(inputStream, outputStream);
25214 while (true) {
25215 if ('eof' in inputStream && inputStream.eof()) break;
25216 if (bz._init_block()) {
25217 bz._read_bunzip();
25218 } else {
25219 var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
25220 if (targetStreamCRC !== bz.streamCRC) {
25221 _throw(Err.DATA_ERROR, "Bad stream CRC "+
25222 "(got "+bz.streamCRC.toString(16)+
25223 " expected "+targetStreamCRC.toString(16)+")");
25224 }
25225 if (multistream &&
25226 'eof' in inputStream &&
25227 !inputStream.eof()) {
25228 // note that start_bunzip will also resync the bit reader to next byte
25229 bz._start_bunzip(inputStream, outputStream);
25230 } else break;
25231 }
25232 }
25233 if ('getBuffer' in outputStream)
25234 return outputStream.getBuffer();
25235};
25236const decodeBlock = function(input, pos, output) {
25237 // make a stream from a buffer, if necessary
25238 var inputStream = coerceInputStream(input);
25239 var outputStream = coerceOutputStream(output);
25240 var bz = new Bunzip(inputStream, outputStream);
25241 bz.reader.seek(pos);
25242 /* Fill the decode buffer for the block */
25243 var moreBlocks = bz._get_next_block();
25244 if (moreBlocks) {
25245 /* Init the CRC for writing */
25246 bz.blockCRC = new crc32$1();
25247
25248 /* Zero this so the current byte from before the seek is not written */
25249 bz.writeCopies = 0;
25250
25251 /* Decompress the block and write to stdout */
25252 bz._read_bunzip();
25253 // XXX keep writing?
25254 }
25255 if ('getBuffer' in outputStream)
25256 return outputStream.getBuffer();
25257};
25258/* Reads bzip2 file from stream or buffer `input`, and invoke
25259 * `callback(position, size)` once for each bzip2 block,
25260 * where position gives the starting position (in *bits*)
25261 * and size gives uncompressed size of the block (in *bytes*). */
25262const table = function(input, callback, multistream) {
25263 // make a stream from a buffer, if necessary
25264 var inputStream = new stream$1();
25265 inputStream.delegate = coerceInputStream(input);
25266 inputStream.pos = 0;
25267 inputStream.readByte = function() {
25268 this.pos++;
25269 return this.delegate.readByte();
25270 };
25271 if (inputStream.delegate.eof) {
25272 inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
25273 }
25274 var outputStream = new stream$1();
25275 outputStream.pos = 0;
25276 outputStream.writeByte = function() { this.pos++; };
25277
25278 var bz = new Bunzip(inputStream, outputStream);
25279 var blockSize = bz.dbufSize;
25280 while (true) {
25281 if ('eof' in inputStream && inputStream.eof()) break;
25282
25283 var position = inputStream.pos*8 + bz.reader.bitOffset;
25284 if (bz.reader.hasByte) { position -= 8; }
25285
25286 if (bz._init_block()) {
25287 var start = outputStream.pos;
25288 bz._read_bunzip();
25289 callback(position, outputStream.pos - start);
25290 } else {
25291 bz.reader.read(32); // (but we ignore the crc)
25292 if (multistream &&
25293 'eof' in inputStream &&
25294 !inputStream.eof()) {
25295 // note that start_bunzip will also resync the bit reader to next byte
25296 bz._start_bunzip(inputStream, outputStream);
25297 console.assert(bz.dbufSize === blockSize,
25298 "shouldn't change block size within multistream file");
25299 } else break;
25300 }
25301 }
25302};
25303
25304var lib = {
25305 Bunzip,
25306 Stream: stream$1,
25307 Err,
25308 decode: decode$2,
25309 decodeBlock,
25310 table
25311};
25312var lib_4 = lib.decode;
25313
25314// GPG4Browsers - An OpenPGP implementation in javascript
25315
25316/**
25317 * Implementation of the Compressed Data Packet (Tag 8)
25318 *
25319 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
25320 * The Compressed Data packet contains compressed data. Typically,
25321 * this packet is found as the contents of an encrypted packet, or following
25322 * a Signature or One-Pass Signature packet, and contains a literal data packet.
25323 */
25324class CompressedDataPacket {
25325 /**
25326 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25327 */
25328 constructor(config = defaultConfig) {
25329 /**
25330 * Packet type
25331 * @type {module:enums.packet}
25332 */
25333 this.tag = enums.packet.compressedData;
25334 /**
25335 * List of packets
25336 * @type {PacketList}
25337 */
25338 this.packets = null;
25339 /**
25340 * Compression algorithm
25341 * @type {compression}
25342 */
25343 this.algorithm = enums.read(enums.compression, config.compression);
25344
25345 /**
25346 * Compressed packet data
25347 * @type {Uint8Array | ReadableStream<Uint8Array>}
25348 */
25349 this.compressed = null;
25350
25351 /**
25352 * zip/zlib compression level, between 1 and 9
25353 */
25354 this.deflateLevel = config.deflateLevel;
25355 }
25356
25357 /**
25358 * Parsing function for the packet.
25359 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
25360 */
25361 async read(bytes, config, streaming) {
25362 await stream.parse(bytes, async reader => {
25363
25364 // One octet that gives the algorithm used to compress the packet.
25365 this.algorithm = enums.read(enums.compression, await reader.readByte());
25366
25367 // Compressed data, which makes up the remainder of the packet.
25368 this.compressed = reader.remainder();
25369
25370 await this.decompress(streaming);
25371 });
25372 }
25373
25374
25375 /**
25376 * Return the compressed packet.
25377 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
25378 */
25379 write() {
25380 if (this.compressed === null) {
25381 this.compress();
25382 }
25383
25384 return util.concat([new Uint8Array([enums.write(enums.compression, this.algorithm)]), this.compressed]);
25385 }
25386
25387
25388 /**
25389 * Decompression method for decompressing the compressed data
25390 * read by read_packet
25391 */
25392 async decompress(streaming) {
25393
25394 if (!decompress_fns[this.algorithm]) {
25395 throw new Error(this.algorithm + ' decompression not supported');
25396 }
25397
25398 await this.packets.read(decompress_fns[this.algorithm](this.compressed), {
25399 LiteralDataPacket,
25400 OnePassSignaturePacket,
25401 SignaturePacket
25402 }, streaming);
25403 }
25404
25405 /**
25406 * Compress the packet data (member decompressedData)
25407 */
25408 compress() {
25409 if (!compress_fns[this.algorithm]) {
25410 throw new Error(this.algorithm + ' compression not supported');
25411 }
25412
25413 this.compressed = compress_fns[this.algorithm](this.packets.write(), this.deflateLevel);
25414 }
25415}
25416
25417//////////////////////////
25418// //
25419// Helper functions //
25420// //
25421//////////////////////////
25422
25423
25424const nodeZlib = util.getNodeZlib();
25425
25426function uncompressed(data) {
25427 return data;
25428}
25429
25430function node_zlib(func, options = {}) {
25431 return function (data) {
25432 return stream.nodeToWeb(stream.webToNode(data).pipe(func(options)));
25433 };
25434}
25435
25436function pako_zlib(constructor, options = {}) {
25437 return function(data) {
25438 const obj = new constructor(options);
25439 return stream.transform(data, value => {
25440 if (value.length) {
25441 obj.push(value, Z_SYNC_FLUSH);
25442 return obj.result;
25443 }
25444 }, () => {
25445 if (constructor === Deflate) {
25446 obj.push([], Z_FINISH);
25447 return obj.result;
25448 }
25449 });
25450 };
25451}
25452
25453function bzip2(func) {
25454 return function(data) {
25455 return stream.fromAsync(async () => func(await stream.readToEnd(data)));
25456 };
25457}
25458
25459const compress_fns = nodeZlib ? {
25460 zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.createDeflateRaw, { level })(compressed),
25461 zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.createDeflate, { level })(compressed)
25462} : {
25463 zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),
25464 zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)
25465};
25466
25467const decompress_fns = nodeZlib ? {
25468 uncompressed: uncompressed,
25469 zip: /*#__PURE__*/ node_zlib(nodeZlib.createInflateRaw),
25470 zlib: /*#__PURE__*/ node_zlib(nodeZlib.createInflate),
25471 bzip2: /*#__PURE__*/ bzip2(lib_4)
25472} : {
25473 uncompressed: uncompressed,
25474 zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),
25475 zlib: /*#__PURE__*/ pako_zlib(Inflate),
25476 bzip2: /*#__PURE__*/ bzip2(lib_4)
25477};
25478
25479// GPG4Browsers - An OpenPGP implementation in javascript
25480
25481const VERSION = 1; // A one-octet version number of the data packet.
25482
25483/**
25484 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
25485 *
25486 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
25487 * The Symmetrically Encrypted Integrity Protected Data packet is
25488 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
25489 * created for OpenPGP that addresses the problem of detecting a modification to
25490 * encrypted data. It is used in combination with a Modification Detection Code
25491 * packet.
25492 */
25493class SymEncryptedIntegrityProtectedDataPacket {
25494 constructor() {
25495 this.tag = enums.packet.symEncryptedIntegrityProtectedData;
25496 this.version = VERSION;
25497 /** The encrypted payload. */
25498 this.encrypted = null; // string
25499 /**
25500 * If after decrypting the packet this is set to true,
25501 * a modification has been detected and thus the contents
25502 * should be discarded.
25503 * @type {Boolean}
25504 */
25505 this.modification = false;
25506 this.packets = null;
25507 }
25508
25509 async read(bytes) {
25510 await stream.parse(bytes, async reader => {
25511
25512 // - A one-octet version number. The only currently defined value is 1.
25513 if (await reader.readByte() !== VERSION) {
25514 throw new Error('Invalid packet version.');
25515 }
25516
25517 // - Encrypted data, the output of the selected symmetric-key cipher
25518 // operating in Cipher Feedback mode with shift amount equal to the
25519 // block size of the cipher (CFB-n where n is the block size).
25520 this.encrypted = reader.remainder();
25521 });
25522 }
25523
25524 write() {
25525 return util.concat([new Uint8Array([VERSION]), this.encrypted]);
25526 }
25527
25528 /**
25529 * Encrypt the payload in the packet.
25530 * @param {String} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used e.g. 'aes128'
25531 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25532 * @param {Boolean} streaming - Whether to set this.encrypted to a stream
25533 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25534 * @returns {Boolean}
25535 * @async
25536 */
25537 async encrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) {
25538 let bytes = this.packets.write();
25539 if (!streaming) bytes = await stream.readToEnd(bytes);
25540 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
25541 const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
25542
25543 const tohash = util.concat([prefix, bytes, mdc]);
25544 const hash = await mod.hash.sha1(stream.passiveClone(tohash));
25545 const plaintext = util.concat([tohash, hash]);
25546
25547 this.encrypted = await mod.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(mod.cipher[sessionKeyAlgorithm].blockSize), config);
25548 return true;
25549 }
25550
25551 /**
25552 * Decrypts the encrypted data contained in the packet.
25553 * @param {String} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used e.g. 'aes128'
25554 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25555 * @param {Boolean} streaming - Whether to read this.encrypted as a stream
25556 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25557 * @returns {Boolean}
25558 * @async
25559 */
25560 async decrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) {
25561 let encrypted = stream.clone(this.encrypted);
25562 if (!streaming) encrypted = await stream.readToEnd(encrypted);
25563 const decrypted = await mod.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(mod.cipher[sessionKeyAlgorithm].blockSize));
25564
25565 // there must be a modification detection code packet as the
25566 // last packet and everything gets hashed except the hash itself
25567 const realHash = stream.slice(stream.passiveClone(decrypted), -20);
25568 const tohash = stream.slice(decrypted, 0, -20);
25569 const verifyHash = Promise.all([
25570 stream.readToEnd(await mod.hash.sha1(stream.passiveClone(tohash))),
25571 stream.readToEnd(realHash)
25572 ]).then(([hash, mdc]) => {
25573 if (!util.equalsUint8Array(hash, mdc)) {
25574 throw new Error('Modification detected.');
25575 }
25576 return new Uint8Array();
25577 });
25578 const bytes = stream.slice(tohash, mod.cipher[sessionKeyAlgorithm].blockSize + 2); // Remove random prefix
25579 let packetbytes = stream.slice(bytes, 0, -2); // Remove MDC packet
25580 packetbytes = stream.concat([packetbytes, stream.fromAsync(() => verifyHash)]);
25581 if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {
25582 packetbytes = await stream.readToEnd(packetbytes);
25583 }
25584 await this.packets.read(packetbytes, {
25585 LiteralDataPacket,
25586 CompressedDataPacket,
25587 OnePassSignaturePacket,
25588 SignaturePacket
25589 }, streaming);
25590 return true;
25591 }
25592}
25593
25594// OpenPGP.js - An OpenPGP implementation in javascript
25595
25596const VERSION$1 = 1; // A one-octet version number of the data packet.
25597
25598/**
25599 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
25600 * Additional Data (AEAD) Protected Data Packet
25601 *
25602 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
25603 * AEAD Protected Data Packet
25604 */
25605class AEADEncryptedDataPacket {
25606 constructor() {
25607 this.tag = enums.packet.AEADEncryptedData;
25608 this.version = VERSION$1;
25609 this.cipherAlgo = null;
25610 this.aeadAlgorithm = 'eax';
25611 this.aeadAlgo = null;
25612 this.chunkSizeByte = null;
25613 this.iv = null;
25614 this.encrypted = null;
25615 this.packets = null;
25616 }
25617
25618 /**
25619 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
25620 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
25621 */
25622 async read(bytes) {
25623 await stream.parse(bytes, async reader => {
25624 if (await reader.readByte() !== VERSION$1) { // The only currently defined value is 1.
25625 throw new Error('Invalid packet version.');
25626 }
25627 this.cipherAlgo = await reader.readByte();
25628 this.aeadAlgo = await reader.readByte();
25629 this.chunkSizeByte = await reader.readByte();
25630 const mode = mod[enums.read(enums.aead, this.aeadAlgo)];
25631 this.iv = await reader.readBytes(mode.ivLength);
25632 this.encrypted = reader.remainder();
25633 });
25634 }
25635
25636 /**
25637 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
25638 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
25639 */
25640 write() {
25641 return util.concat([new Uint8Array([this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte]), this.iv, this.encrypted]);
25642 }
25643
25644 /**
25645 * Decrypt the encrypted payload.
25646 * @param {String} sessionKeyAlgorithm - The session key's cipher algorithm e.g. 'aes128'
25647 * @param {Uint8Array} key - The session key used to encrypt the payload
25648 * @param {Boolean} streaming - Whether the top-level function will return a stream
25649 * @throws {Error} if decryption was not successful
25650 * @async
25651 */
25652 async decrypt(sessionKeyAlgorithm, key, streaming) {
25653 await this.packets.read(await this.crypt('decrypt', key, stream.clone(this.encrypted), streaming), {
25654 LiteralDataPacket,
25655 CompressedDataPacket,
25656 OnePassSignaturePacket,
25657 SignaturePacket
25658 }, streaming);
25659 }
25660
25661 /**
25662 * Encrypt the packet list payload.
25663 * @param {String} sessionKeyAlgorithm - The session key's cipher algorithm e.g. 'aes128'
25664 * @param {Uint8Array} key - The session key used to encrypt the payload
25665 * @param {Boolean} streaming - Whether the top-level function will return a stream
25666 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25667 * @throws {Error} if encryption was not successful
25668 * @async
25669 */
25670 async encrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) {
25671 this.cipherAlgo = enums.write(enums.symmetric, sessionKeyAlgorithm);
25672 this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm);
25673 const mode = mod[enums.read(enums.aead, this.aeadAlgo)];
25674 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
25675 this.chunkSizeByte = config.aeadChunkSizeByte;
25676 const data = this.packets.write();
25677 this.encrypted = await this.crypt('encrypt', key, data, streaming);
25678 }
25679
25680 /**
25681 * En/decrypt the payload.
25682 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
25683 * @param {Uint8Array} key - The session key used to en/decrypt the payload
25684 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
25685 * @param {Boolean} streaming - Whether the top-level function will return a stream
25686 * @returns {Uint8Array | ReadableStream<Uint8Array>}
25687 * @async
25688 */
25689 async crypt(fn, key, data, streaming) {
25690 const cipher = enums.read(enums.symmetric, this.cipherAlgo);
25691 const mode = mod[enums.read(enums.aead, this.aeadAlgo)];
25692 const modeInstance = await mode(cipher, key);
25693 const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
25694 const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
25695 const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
25696 const adataBuffer = new ArrayBuffer(21);
25697 const adataArray = new Uint8Array(adataBuffer, 0, 13);
25698 const adataTagArray = new Uint8Array(adataBuffer);
25699 const adataView = new DataView(adataBuffer);
25700 const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
25701 adataArray.set([0xC0 | this.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0);
25702 let chunkIndex = 0;
25703 let latestPromise = Promise.resolve();
25704 let cryptedBytes = 0;
25705 let queuedBytes = 0;
25706 const iv = this.iv;
25707 return stream.transformPair(data, async (readable, writable) => {
25708 const reader = stream.getReader(readable);
25709 const buffer = new stream.TransformStream({}, {
25710 highWaterMark: streaming ? util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6) : Infinity,
25711 size: array => array.length
25712 });
25713 stream.pipe(buffer.readable, writable);
25714 const writer = stream.getWriter(buffer.writable);
25715 try {
25716 while (true) {
25717 let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
25718 const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
25719 chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
25720 let cryptedPromise;
25721 let done;
25722 if (!chunkIndex || chunk.length) {
25723 reader.unshift(finalChunk);
25724 cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
25725 queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
25726 } else {
25727 // After the last chunk, we either encrypt a final, empty
25728 // data chunk to get the final authentication tag or
25729 // validate that final authentication tag.
25730 adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
25731 cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
25732 queuedBytes += tagLengthIfEncrypting;
25733 done = true;
25734 }
25735 cryptedBytes += chunk.length - tagLengthIfDecrypting;
25736 // eslint-disable-next-line no-loop-func
25737 latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
25738 await writer.ready;
25739 await writer.write(crypted);
25740 queuedBytes -= crypted.length;
25741 }).catch(err => writer.abort(err));
25742 if (done || queuedBytes > writer.desiredSize) {
25743 await latestPromise; // Respect backpressure
25744 }
25745 if (!done) {
25746 adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
25747 } else {
25748 await writer.close();
25749 break;
25750 }
25751 }
25752 } catch (e) {
25753 await writer.abort(e);
25754 }
25755 });
25756 }
25757}
25758
25759// GPG4Browsers - An OpenPGP implementation in javascript
25760
25761/**
25762 * Public-Key Encrypted Session Key Packets (Tag 1)
25763 *
25764 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
25765 * A Public-Key Encrypted Session Key packet holds the session key
25766 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
25767 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
25768 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
25769 * message is encrypted with the session key, and the session key is itself
25770 * encrypted and stored in the Encrypted Session Key packet(s). The
25771 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
25772 * Session Key packet for each OpenPGP key to which the message is encrypted.
25773 * The recipient of the message finds a session key that is encrypted to their
25774 * public key, decrypts the session key, and then uses the session key to
25775 * decrypt the message.
25776 */
25777class PublicKeyEncryptedSessionKeyPacket {
25778 constructor() {
25779 this.tag = enums.packet.publicKeyEncryptedSessionKey;
25780 this.version = 3;
25781
25782 this.publicKeyId = new Keyid();
25783 this.publicKeyAlgorithm = null;
25784
25785 this.sessionKey = null;
25786 this.sessionKeyAlgorithm = null;
25787
25788 /** @type {Object} */
25789 this.encrypted = {};
25790 }
25791
25792 /**
25793 * Parsing function for a publickey encrypted session key packet (tag 1).
25794 *
25795 * @param {Uint8Array} bytes - Payload of a tag 1 packet
25796 */
25797 read(bytes) {
25798 this.version = bytes[0];
25799 this.publicKeyId.read(bytes.subarray(1, bytes.length));
25800 this.publicKeyAlgorithm = enums.read(enums.publicKey, bytes[9]);
25801
25802 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
25803 this.encrypted = mod.parseEncSessionKeyParams(algo, bytes.subarray(10));
25804 }
25805
25806 /**
25807 * Create a binary representation of a tag 1 packet
25808 *
25809 * @returns {Uint8Array} The Uint8Array representation.
25810 */
25811 write() {
25812 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
25813
25814 const arr = [
25815 new Uint8Array([this.version]),
25816 this.publicKeyId.write(),
25817 new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)]),
25818 mod.serializeParams(algo, this.encrypted)
25819 ];
25820
25821 return util.concatUint8Array(arr);
25822 }
25823
25824 /**
25825 * Encrypt session key packet
25826 * @param {PublicKeyPacket} key - Public key
25827 * @returns {Boolean}
25828 * @async
25829 */
25830 async encrypt(key) {
25831 const data = util.concatUint8Array([
25832 new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]),
25833 this.sessionKey,
25834 util.writeChecksum(this.sessionKey)
25835 ]);
25836 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
25837 this.encrypted = await mod.publicKeyEncrypt(
25838 algo, key.publicParams, data, key.getFingerprintBytes());
25839 return true;
25840 }
25841
25842 /**
25843 * Decrypts the session key (only for public key encrypted session key
25844 * packets (tag 1)
25845 *
25846 * @param {SecretKeyPacket} key
25847 * Private key with secret params unlocked
25848 * @returns {Boolean}
25849 * @async
25850 */
25851 async decrypt(key) {
25852 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
25853 const keyAlgo = enums.write(enums.publicKey, key.algorithm);
25854 // check that session key algo matches the secret key algo
25855 if (algo !== keyAlgo) {
25856 throw new Error('Decryption error');
25857 }
25858 const decoded = await mod.publicKeyDecrypt(algo, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes());
25859 const checksum = decoded.subarray(decoded.length - 2);
25860 const sessionKey = decoded.subarray(1, decoded.length - 2);
25861 if (!util.equalsUint8Array(checksum, util.writeChecksum(sessionKey))) {
25862 throw new Error('Decryption error');
25863 } else {
25864 this.sessionKey = sessionKey;
25865 this.sessionKeyAlgorithm = enums.read(enums.symmetric, decoded[0]);
25866 }
25867 return true;
25868 }
25869}
25870
25871// GPG4Browsers - An OpenPGP implementation in javascript
25872
25873class S2K {
25874 /**
25875 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25876 */
25877 constructor(config = defaultConfig) {
25878 /** @type {module:enums.hash} */
25879 this.algorithm = 'sha256';
25880 /** @type {module:enums.s2k} */
25881 this.type = 'iterated';
25882 /** @type {Integer} */
25883 this.c = config.s2kIterationCountByte;
25884 /** Eight bytes of salt in a binary string.
25885 * @type {String}
25886 */
25887 this.salt = null;
25888 }
25889
25890 get_count() {
25891 // Exponent bias, defined in RFC4880
25892 const expbias = 6;
25893
25894 return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
25895 }
25896
25897 /**
25898 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
25899 * @param {String} bytes - Payload of string-to-key specifier
25900 * @returns {Integer} Actual length of the object.
25901 */
25902 read(bytes) {
25903 let i = 0;
25904 this.type = enums.read(enums.s2k, bytes[i++]);
25905 this.algorithm = bytes[i++];
25906 if (this.type !== 'gnu') {
25907 this.algorithm = enums.read(enums.hash, this.algorithm);
25908 }
25909
25910 switch (this.type) {
25911 case 'simple':
25912 break;
25913
25914 case 'salted':
25915 this.salt = bytes.subarray(i, i + 8);
25916 i += 8;
25917 break;
25918
25919 case 'iterated':
25920 this.salt = bytes.subarray(i, i + 8);
25921 i += 8;
25922
25923 // Octet 10: count, a one-octet, coded value
25924 this.c = bytes[i++];
25925 break;
25926
25927 case 'gnu':
25928 if (util.uint8ArrayToStr(bytes.subarray(i, i + 3)) === "GNU") {
25929 i += 3; // GNU
25930 const gnuExtType = 1000 + bytes[i++];
25931 if (gnuExtType === 1001) {
25932 this.type = 'gnu-dummy';
25933 // GnuPG extension mode 1001 -- don't write secret key at all
25934 } else {
25935 throw new Error("Unknown s2k gnu protection mode.");
25936 }
25937 } else {
25938 throw new Error("Unknown s2k type.");
25939 }
25940 break;
25941
25942 default:
25943 throw new Error("Unknown s2k type.");
25944 }
25945
25946 return i;
25947 }
25948
25949 /**
25950 * Serializes s2k information
25951 * @returns {Uint8Array} Binary representation of s2k.
25952 */
25953 write() {
25954 if (this.type === 'gnu-dummy') {
25955 return new Uint8Array([101, 0, ...util.strToUint8Array('GNU'), 1]);
25956 }
25957
25958 const arr = [new Uint8Array([enums.write(enums.s2k, this.type), enums.write(enums.hash, this.algorithm)])];
25959
25960 switch (this.type) {
25961 case 'simple':
25962 break;
25963 case 'salted':
25964 arr.push(this.salt);
25965 break;
25966 case 'iterated':
25967 arr.push(this.salt);
25968 arr.push(new Uint8Array([this.c]));
25969 break;
25970 case 'gnu':
25971 throw new Error("GNU s2k type not supported.");
25972 default:
25973 throw new Error("Unknown s2k type.");
25974 }
25975
25976 return util.concatUint8Array(arr);
25977 }
25978
25979 /**
25980 * Produces a key using the specified passphrase and the defined
25981 * hashAlgorithm
25982 * @param {String} passphrase - Passphrase containing user input
25983 * @returns {Uint8Array} Produced key with a length corresponding to.
25984 * hashAlgorithm hash length
25985 */
25986 async produce_key(passphrase, numBytes) {
25987 passphrase = util.encodeUtf8(passphrase);
25988 const algorithm = enums.write(enums.hash, this.algorithm);
25989
25990 const arr = [];
25991 let rlength = 0;
25992
25993 let prefixlen = 0;
25994 while (rlength < numBytes) {
25995 let toHash;
25996 switch (this.type) {
25997 case 'simple':
25998 toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
25999 break;
26000 case 'salted':
26001 toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
26002 break;
26003 case 'iterated': {
26004 const data = util.concatUint8Array([this.salt, passphrase]);
26005 let datalen = data.length;
26006 const count = Math.max(this.get_count(), datalen);
26007 toHash = new Uint8Array(prefixlen + count);
26008 toHash.set(data, prefixlen);
26009 for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
26010 toHash.copyWithin(pos, prefixlen, pos);
26011 }
26012 break;
26013 }
26014 case 'gnu':
26015 throw new Error("GNU s2k type not supported.");
26016 default:
26017 throw new Error("Unknown s2k type.");
26018 }
26019 const result = await mod.hash.digest(algorithm, toHash);
26020 arr.push(result);
26021 rlength += result.length;
26022 prefixlen++;
26023 }
26024
26025 return util.concatUint8Array(arr).subarray(0, numBytes);
26026 }
26027}
26028
26029// GPG4Browsers - An OpenPGP implementation in javascript
26030
26031/**
26032 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
26033 *
26034 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
26035 * The Symmetric-Key Encrypted Session Key packet holds the
26036 * symmetric-key encryption of a session key used to encrypt a message.
26037 * Zero or more Public-Key Encrypted Session Key packets and/or
26038 * Symmetric-Key Encrypted Session Key packets may precede a
26039 * Symmetrically Encrypted Data packet that holds an encrypted message.
26040 * The message is encrypted with a session key, and the session key is
26041 * itself encrypted and stored in the Encrypted Session Key packet or
26042 * the Symmetric-Key Encrypted Session Key packet.
26043 */
26044class SymEncryptedSessionKeyPacket {
26045 /**
26046 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26047 */
26048 constructor(config = defaultConfig) {
26049 this.tag = enums.packet.symEncryptedSessionKey;
26050 this.version = config.aeadProtect ? 5 : 4;
26051 this.sessionKey = null;
26052 this.sessionKeyEncryptionAlgorithm = null;
26053 this.sessionKeyAlgorithm = 'aes256';
26054 this.aeadAlgorithm = enums.read(enums.aead, config.aeadMode);
26055 this.encrypted = null;
26056 this.s2k = null;
26057 this.iv = null;
26058 }
26059
26060 /**
26061 * Parsing function for a symmetric encrypted session key packet (tag 3).
26062 *
26063 * @param {Uint8Array} bytes - Payload of a tag 3 packet
26064 */
26065 read(bytes) {
26066 let offset = 0;
26067
26068 // A one-octet version number. The only currently defined version is 4.
26069 this.version = bytes[offset++];
26070
26071 // A one-octet number describing the symmetric algorithm used.
26072 const algo = enums.read(enums.symmetric, bytes[offset++]);
26073
26074 if (this.version === 5) {
26075 // A one-octet AEAD algorithm.
26076 this.aeadAlgorithm = enums.read(enums.aead, bytes[offset++]);
26077 }
26078
26079 // A string-to-key (S2K) specifier, length as defined above.
26080 this.s2k = new S2K();
26081 offset += this.s2k.read(bytes.subarray(offset, bytes.length));
26082
26083 if (this.version === 5) {
26084 const mode = mod[this.aeadAlgorithm];
26085
26086 // A starting initialization vector of size specified by the AEAD
26087 // algorithm.
26088 this.iv = bytes.subarray(offset, offset += mode.ivLength);
26089 }
26090
26091 // The encrypted session key itself, which is decrypted with the
26092 // string-to-key object. This is optional in version 4.
26093 if (this.version === 5 || offset < bytes.length) {
26094 this.encrypted = bytes.subarray(offset, bytes.length);
26095 this.sessionKeyEncryptionAlgorithm = algo;
26096 } else {
26097 this.sessionKeyAlgorithm = algo;
26098 }
26099 }
26100
26101 /**
26102 * Create a binary representation of a tag 3 packet
26103 *
26104 * @returns {Uint8Array} The Uint8Array representation.
26105 */
26106 write() {
26107 const algo = this.encrypted === null ?
26108 this.sessionKeyAlgorithm :
26109 this.sessionKeyEncryptionAlgorithm;
26110
26111 let bytes;
26112
26113 if (this.version === 5) {
26114 bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo), enums.write(enums.aead, this.aeadAlgorithm)]), this.s2k.write(), this.iv, this.encrypted]);
26115 } else {
26116 bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo)]), this.s2k.write()]);
26117
26118 if (this.encrypted !== null) {
26119 bytes = util.concatUint8Array([bytes, this.encrypted]);
26120 }
26121 }
26122
26123 return bytes;
26124 }
26125
26126 /**
26127 * Decrypts the session key
26128 * @param {String} passphrase - The passphrase in string form
26129 * @throws {Error} if decryption was not successful
26130 * @async
26131 */
26132 async decrypt(passphrase) {
26133 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
26134 this.sessionKeyEncryptionAlgorithm :
26135 this.sessionKeyAlgorithm;
26136
26137 const length = mod.cipher[algo].keySize;
26138 const key = await this.s2k.produce_key(passphrase, length);
26139
26140 if (this.version === 5) {
26141 const mode = mod[this.aeadAlgorithm];
26142 const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]);
26143 const modeInstance = await mode(algo, key);
26144 this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
26145 } else if (this.encrypted !== null) {
26146 const decrypted = await mod.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(mod.cipher[algo].blockSize));
26147
26148 this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0]);
26149 this.sessionKey = decrypted.subarray(1, decrypted.length);
26150 } else {
26151 this.sessionKey = key;
26152 }
26153 }
26154
26155 /**
26156 * Encrypts the session key
26157 * @param {String} passphrase - The passphrase in string form
26158 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26159 * @throws {Error} if encryption was not successful
26160 * @async
26161 */
26162 async encrypt(passphrase, config = defaultConfig) {
26163 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
26164 this.sessionKeyEncryptionAlgorithm :
26165 this.sessionKeyAlgorithm;
26166
26167 this.sessionKeyEncryptionAlgorithm = algo;
26168
26169 this.s2k = new S2K(config);
26170 this.s2k.salt = await mod.random.getRandomBytes(8);
26171
26172 const length = mod.cipher[algo].keySize;
26173 const key = await this.s2k.produce_key(passphrase, length);
26174
26175 if (this.sessionKey === null) {
26176 this.sessionKey = await mod.generateSessionKey(this.sessionKeyAlgorithm);
26177 }
26178
26179 if (this.version === 5) {
26180 const mode = mod[this.aeadAlgorithm];
26181 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
26182 const adata = new Uint8Array([0xC0 | this.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]);
26183 const modeInstance = await mode(algo, key);
26184 this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);
26185 } else {
26186 const algo_enum = new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]);
26187 const private_key = util.concatUint8Array([algo_enum, this.sessionKey]);
26188 this.encrypted = await mod.cfb.encrypt(algo, key, private_key, new Uint8Array(mod.cipher[algo].blockSize), config);
26189 }
26190 }
26191}
26192
26193// GPG4Browsers - An OpenPGP implementation in javascript
26194
26195/**
26196 * Implementation of the Literal Data Packet (Tag 11)
26197 *
26198 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
26199 * A Literal Data packet contains the body of a message; data that is not to be
26200 * further interpreted.
26201 */
26202class LiteralDataPacket {
26203 /**
26204 * @param {Date} date - The creation date of the literal package
26205 */
26206 constructor(date = new Date()) {
26207 this.tag = enums.packet.literalData;
26208 this.format = 'utf8'; // default format for literal data packets
26209 this.date = util.normalizeDate(date);
26210 this.text = null; // textual data representation
26211 this.data = null; // literal data representation
26212 this.filename = '';
26213 }
26214
26215 /**
26216 * Set the packet data to a javascript native string, end of line
26217 * will be normalized to \r\n and by default text is converted to UTF8
26218 * @param {String | ReadableStream<String>} text - Any native javascript string
26219 * @param {utf8|binary|text|mime} [format] - The format of the string of bytes
26220 */
26221 setText(text, format = 'utf8') {
26222 this.format = format;
26223 this.text = text;
26224 this.data = null;
26225 }
26226
26227 /**
26228 * Returns literal data packets as native JavaScript string
26229 * with normalized end of line to \n
26230 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
26231 * @returns {String | ReadableStream<String>} Literal data as text.
26232 */
26233 getText(clone = false) {
26234 if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
26235 this.text = util.decodeUtf8(util.nativeEOL(this.getBytes(clone)));
26236 }
26237 return this.text;
26238 }
26239
26240 /**
26241 * Set the packet data to value represented by the provided string of bytes.
26242 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
26243 * @param {utf8|binary|text|mime} format - The format of the string of bytes
26244 */
26245 setBytes(bytes, format) {
26246 this.format = format;
26247 this.data = bytes;
26248 this.text = null;
26249 }
26250
26251
26252 /**
26253 * Get the byte sequence representing the literal packet data
26254 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
26255 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
26256 */
26257 getBytes(clone = false) {
26258 if (this.data === null) {
26259 // encode UTF8 and normalize EOL to \r\n
26260 this.data = util.canonicalizeEOL(util.encodeUtf8(this.text));
26261 }
26262 if (clone) {
26263 return stream.passiveClone(this.data);
26264 }
26265 return this.data;
26266 }
26267
26268
26269 /**
26270 * Sets the filename of the literal packet data
26271 * @param {String} filename - Any native javascript string
26272 */
26273 setFilename(filename) {
26274 this.filename = filename;
26275 }
26276
26277
26278 /**
26279 * Get the filename of the literal packet data
26280 * @returns {String} Filename.
26281 */
26282 getFilename() {
26283 return this.filename;
26284 }
26285
26286
26287 /**
26288 * Parsing function for a literal data packet (tag 11).
26289 *
26290 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
26291 * @returns {LiteralDataPacket} Object representation.
26292 */
26293 async read(bytes) {
26294 await stream.parse(bytes, async reader => {
26295 // - A one-octet field that describes how the data is formatted.
26296 const format = enums.read(enums.literal, await reader.readByte());
26297
26298 const filename_len = await reader.readByte();
26299 this.filename = util.decodeUtf8(await reader.readBytes(filename_len));
26300
26301 this.date = util.readDate(await reader.readBytes(4));
26302
26303 const data = reader.remainder();
26304
26305 this.setBytes(data, format);
26306 });
26307 }
26308
26309 /**
26310 * Creates a Uint8Array representation of the packet, excluding the data
26311 *
26312 * @returns {Uint8Array} Uint8Array representation of the packet.
26313 */
26314 writeHeader() {
26315 const filename = util.encodeUtf8(this.filename);
26316 const filename_length = new Uint8Array([filename.length]);
26317
26318 const format = new Uint8Array([enums.write(enums.literal, this.format)]);
26319 const date = util.writeDate(this.date);
26320
26321 return util.concatUint8Array([format, filename_length, filename, date]);
26322 }
26323
26324 /**
26325 * Creates a Uint8Array representation of the packet
26326 *
26327 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
26328 */
26329 write() {
26330 const header = this.writeHeader();
26331 const data = this.getBytes();
26332
26333 return util.concat([header, data]);
26334 }
26335}
26336
26337// GPG4Browsers - An OpenPGP implementation in javascript
26338
26339/**
26340 * Implementation of the Key Material Packet (Tag 5,6,7,14)
26341 *
26342 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
26343 * A key material packet contains all the information about a public or
26344 * private key. There are four variants of this packet type, and two
26345 * major versions.
26346 *
26347 * A Public-Key packet starts a series of packets that forms an OpenPGP
26348 * key (sometimes called an OpenPGP certificate).
26349 */
26350class PublicKeyPacket {
26351 /**
26352 * @param {Date} [date] - Creation date
26353 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26354 */
26355 constructor(date = new Date(), config = defaultConfig) {
26356 /**
26357 * Packet type
26358 * @type {module:enums.packet}
26359 */
26360 this.tag = enums.packet.publicKey;
26361 /**
26362 * Packet version
26363 * @type {Integer}
26364 */
26365 this.version = config.v5Keys ? 5 : 4;
26366 /**
26367 * Key creation date.
26368 * @type {Date}
26369 */
26370 this.created = util.normalizeDate(date);
26371 /**
26372 * Public key algorithm.
26373 * @type {String}
26374 */
26375 this.algorithm = null;
26376 /**
26377 * Algorithm specific public params
26378 * @type {Object}
26379 */
26380 this.publicParams = null;
26381 /**
26382 * Time until expiration in days (V3 only)
26383 * @type {Integer}
26384 */
26385 this.expirationTimeV3 = 0;
26386 /**
26387 * Fingerprint in lowercase hex
26388 * @type {String}
26389 */
26390 this.fingerprint = null;
26391 /**
26392 * Keyid
26393 * @type {module:type/keyid~Keyid}
26394 */
26395 this.keyid = null;
26396 }
26397
26398 /**
26399 * 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}
26400 * called by read_tag&lt;num&gt;
26401 * @param {Uint8Array} bytes - Input array to read the packet from
26402 * @returns {Object} This object with attributes set by the parser.
26403 */
26404 read(bytes) {
26405 let pos = 0;
26406 // A one-octet version number (3, 4 or 5).
26407 this.version = bytes[pos++];
26408
26409 if (this.version === 4 || this.version === 5) {
26410 // - A four-octet number denoting the time that the key was created.
26411 this.created = util.readDate(bytes.subarray(pos, pos + 4));
26412 pos += 4;
26413
26414 // - A one-octet number denoting the public-key algorithm of this key.
26415 this.algorithm = enums.read(enums.publicKey, bytes[pos++]);
26416 const algo = enums.write(enums.publicKey, this.algorithm);
26417
26418 if (this.version === 5) {
26419 // - A four-octet scalar octet count for the following key material.
26420 pos += 4;
26421 }
26422
26423 // - A series of values comprising the key material.
26424 try {
26425 const { read, publicParams } = mod.parsePublicKeyParams(algo, bytes.subarray(pos));
26426 this.publicParams = publicParams;
26427 pos += read;
26428 } catch (err) {
26429 throw new Error('Error reading MPIs');
26430 }
26431
26432 return pos;
26433 }
26434 throw new Error('Version ' + this.version + ' of the key packet is unsupported.');
26435 }
26436
26437 /**
26438 * Creates an OpenPGP public key packet for the given key.
26439 * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
26440 */
26441 write() {
26442 const arr = [];
26443 // Version
26444 arr.push(new Uint8Array([this.version]));
26445 arr.push(util.writeDate(this.created));
26446 // A one-octet number denoting the public-key algorithm of this key
26447 const algo = enums.write(enums.publicKey, this.algorithm);
26448 arr.push(new Uint8Array([algo]));
26449
26450 const params = mod.serializeParams(algo, this.publicParams);
26451 if (this.version === 5) {
26452 // A four-octet scalar octet count for the following key material
26453 arr.push(util.writeNumber(params.length, 4));
26454 }
26455 // Algorithm-specific params
26456 arr.push(params);
26457 return util.concatUint8Array(arr);
26458 }
26459
26460 /**
26461 * Write packet in order to be hashed; either for a signature or a fingerprint.
26462 */
26463 writeForHash(version) {
26464 const bytes = this.writePublicKey();
26465
26466 if (version === 5) {
26467 return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);
26468 }
26469 return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);
26470 }
26471
26472 /**
26473 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
26474 * @returns {Boolean|null}
26475 */
26476 isDecrypted() {
26477 return null;
26478 }
26479
26480 /**
26481 * Returns the creation time of the key
26482 * @returns {Date}
26483 */
26484 getCreationTime() {
26485 return this.created;
26486 }
26487
26488 /**
26489 * Calculates the key id of the key
26490 * @returns {module:type/keyid~Keyid} A 8 byte key id.
26491 */
26492 getKeyId() {
26493 if (this.keyid) {
26494 return this.keyid;
26495 }
26496 this.keyid = new Keyid();
26497 if (this.version === 5) {
26498 this.keyid.read(util.hexToUint8Array(this.getFingerprint()).subarray(0, 8));
26499 } else if (this.version === 4) {
26500 this.keyid.read(util.hexToUint8Array(this.getFingerprint()).subarray(12, 20));
26501 }
26502 return this.keyid;
26503 }
26504
26505 /**
26506 * Calculates the fingerprint of the key
26507 * @returns {Uint8Array} A Uint8Array containing the fingerprint.
26508 */
26509 getFingerprintBytes() {
26510 if (this.fingerprint) {
26511 return this.fingerprint;
26512 }
26513 const toHash = this.writeForHash(this.version);
26514 if (this.version === 5) {
26515 this.fingerprint = Sha256.bytes(toHash);
26516 } else if (this.version === 4) {
26517 this.fingerprint = Sha1.bytes(toHash);
26518 }
26519 return this.fingerprint;
26520 }
26521
26522 /**
26523 * Calculates the fingerprint of the key
26524 * @returns {String} A string containing the fingerprint in lowercase hex.
26525 */
26526 getFingerprint() {
26527 return util.uint8ArrayToHex(this.getFingerprintBytes());
26528 }
26529
26530 /**
26531 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
26532 * @returns {Boolean} Whether the two keys have the same version and public key data.
26533 */
26534 hasSameFingerprintAs(other) {
26535 return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
26536 }
26537
26538 /**
26539 * Returns algorithm information
26540 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
26541 */
26542 getAlgorithmInfo() {
26543 const result = {};
26544 result.algorithm = this.algorithm;
26545 // RSA, DSA or ElGamal public modulo
26546 const modulo = this.publicParams.n || this.publicParams.p;
26547 if (modulo) {
26548 result.bits = modulo.length * 8;
26549 } else {
26550 result.curve = this.publicParams.oid.getName();
26551 }
26552 return result;
26553 }
26554}
26555
26556/**
26557 * Alias of read()
26558 * @see PublicKeyPacket#read
26559 */
26560PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
26561
26562/**
26563 * Alias of write()
26564 * @see PublicKeyPacket#write
26565 */
26566PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;
26567
26568// GPG4Browsers - An OpenPGP implementation in javascript
26569
26570/**
26571 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
26572 *
26573 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
26574 * The Symmetrically Encrypted Data packet contains data encrypted with a
26575 * symmetric-key algorithm. When it has been decrypted, it contains other
26576 * packets (usually a literal data packet or compressed data packet, but in
26577 * theory other Symmetrically Encrypted Data packets or sequences of packets
26578 * that form whole OpenPGP messages).
26579 */
26580class SymmetricallyEncryptedDataPacket {
26581 constructor() {
26582 /**
26583 * Packet type
26584 * @type {module:enums.packet}
26585 */
26586 this.tag = enums.packet.symmetricallyEncryptedData;
26587 /**
26588 * Encrypted secret-key data
26589 */
26590 this.encrypted = null;
26591 /**
26592 * Decrypted packets contained within.
26593 * @type {PacketList}
26594 */
26595 this.packets = null;
26596 }
26597
26598 read(bytes) {
26599 this.encrypted = bytes;
26600 }
26601
26602 write() {
26603 return this.encrypted;
26604 }
26605
26606 /**
26607 * Decrypt the symmetrically-encrypted packet data
26608 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
26609 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
26610 * @param {Uint8Array} key - The key of cipher blocksize length to be used
26611 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26612
26613 * @throws {Error} if decryption was not successful
26614 * @async
26615 */
26616 async decrypt(sessionKeyAlgorithm, key, streaming, config = defaultConfig) {
26617 // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
26618 if (!config.allowUnauthenticatedMessages) {
26619 throw new Error('Message is not authenticated.');
26620 }
26621
26622 const encrypted = await stream.readToEnd(stream.clone(this.encrypted));
26623 const decrypted = await mod.cfb.decrypt(sessionKeyAlgorithm, key,
26624 encrypted.subarray(mod.cipher[sessionKeyAlgorithm].blockSize + 2),
26625 encrypted.subarray(2, mod.cipher[sessionKeyAlgorithm].blockSize + 2)
26626 );
26627
26628 await this.packets.read(decrypted, {
26629 LiteralDataPacket,
26630 CompressedDataPacket,
26631 OnePassSignaturePacket,
26632 SignaturePacket
26633 }, streaming);
26634 }
26635
26636 /**
26637 * Encrypt the symmetrically-encrypted packet data
26638 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
26639 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
26640 * @param {Uint8Array} key - The key of cipher blocksize length to be used
26641 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26642 * @throws {Error} if encryption was not successful
26643 * @async
26644 */
26645 async encrypt(algo, key, streaming, config = defaultConfig) {
26646 const data = this.packets.write();
26647
26648 const prefix = await mod.getPrefixRandom(algo);
26649 const FRE = await mod.cfb.encrypt(algo, key, prefix, new Uint8Array(mod.cipher[algo].blockSize), config);
26650 const ciphertext = await mod.cfb.encrypt(algo, key, data, FRE.subarray(2), config);
26651 this.encrypted = util.concat([FRE, ciphertext]);
26652 }
26653}
26654
26655// GPG4Browsers - An OpenPGP implementation in javascript
26656
26657/**
26658 * Implementation of the strange "Marker packet" (Tag 10)
26659 *
26660 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
26661 * An experimental version of PGP used this packet as the Literal
26662 * packet, but no released version of PGP generated Literal packets with this
26663 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
26664 * the Marker packet.
26665 *
26666 * Such a packet MUST be ignored when received.
26667 */
26668class MarkerPacket {
26669 constructor() {
26670 this.tag = enums.packet.marker;
26671 }
26672
26673 /**
26674 * Parsing function for a literal data packet (tag 10).
26675 *
26676 * @param {String} input - Payload of a tag 10 packet
26677 * @param {Integer} position
26678 * Position to start reading from the input string
26679 * @param {Integer} len
26680 * Length of the packet or the remaining length of
26681 * input at position
26682 * @returns {MarkerPacket} Object representation.
26683 */
26684 read(bytes) {
26685 if (bytes[0] === 0x50 && // P
26686 bytes[1] === 0x47 && // G
26687 bytes[2] === 0x50) { // P
26688 return true;
26689 }
26690 // marker packet does not contain "PGP"
26691 return false;
26692 }
26693}
26694
26695// GPG4Browsers - An OpenPGP implementation in javascript
26696
26697/**
26698 * A Public-Subkey packet (tag 14) has exactly the same format as a
26699 * Public-Key packet, but denotes a subkey. One or more subkeys may be
26700 * associated with a top-level key. By convention, the top-level key
26701 * provides signature services, and the subkeys provide encryption
26702 * services.
26703 * @extends PublicKeyPacket
26704 */
26705class PublicSubkeyPacket extends PublicKeyPacket {
26706 /**
26707 * @param {Date} [date] - Creation date
26708 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26709 */
26710 constructor(date, config) {
26711 super(date, config);
26712 this.tag = enums.packet.publicSubkey;
26713 }
26714}
26715
26716// GPG4Browsers - An OpenPGP implementation in javascript
26717
26718function readSimpleLength(bytes) {
26719 let len = 0;
26720 let offset;
26721 const type = bytes[0];
26722
26723
26724 if (type < 192) {
26725 [len] = bytes;
26726 offset = 1;
26727 } else if (type < 255) {
26728 len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
26729 offset = 2;
26730 } else if (type === 255) {
26731 len = util.readNumber(bytes.subarray(1, 1 + 4));
26732 offset = 5;
26733 }
26734
26735 return {
26736 len: len,
26737 offset: offset
26738 };
26739}
26740
26741/**
26742 * Encodes a given integer of length to the openpgp length specifier to a
26743 * string
26744 *
26745 * @param {Integer} length - The length to encode
26746 * @returns {Uint8Array} String with openpgp length representation.
26747 */
26748function writeSimpleLength(length) {
26749 if (length < 192) {
26750 return new Uint8Array([length]);
26751 } else if (length > 191 && length < 8384) {
26752 /*
26753 * let a = (total data packet length) - 192 let bc = two octet
26754 * representation of a let d = b + 192
26755 */
26756 return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
26757 }
26758 return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
26759}
26760
26761function writePartialLength(power) {
26762 if (power < 0 || power > 30) {
26763 throw new Error('Partial Length power must be between 1 and 30');
26764 }
26765 return new Uint8Array([224 + power]);
26766}
26767
26768function writeTag(tag_type) {
26769 /* we're only generating v4 packet headers here */
26770 return new Uint8Array([0xC0 | tag_type]);
26771}
26772
26773/**
26774 * Writes a packet header version 4 with the given tag_type and length to a
26775 * string
26776 *
26777 * @param {Integer} tag_type - Tag type
26778 * @param {Integer} length - Length of the payload
26779 * @returns {String} String of the header.
26780 */
26781function writeHeader(tag_type, length) {
26782 /* we're only generating v4 packet headers here */
26783 return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
26784}
26785
26786/**
26787 * Whether the packet type supports partial lengths per RFC4880
26788 * @param {Integer} tag_type - Tag type
26789 * @returns {Boolean} String of the header.
26790 */
26791function supportsStreaming(tag_type) {
26792 return [
26793 enums.packet.literalData,
26794 enums.packet.compressedData,
26795 enums.packet.symmetricallyEncryptedData,
26796 enums.packet.symEncryptedIntegrityProtectedData,
26797 enums.packet.AEADEncryptedData
26798 ].includes(tag_type);
26799}
26800
26801/**
26802 * Generic static Packet Parser function
26803 *
26804 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
26805 * @param {Function} callback - Function to call with the parsed packet
26806 * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
26807 */
26808async function readPackets(input, streaming, callback) {
26809 const reader = stream.getReader(input);
26810 let writer;
26811 let callbackReturned;
26812 try {
26813 const peekedBytes = await reader.peekBytes(2);
26814 // some sanity checks
26815 if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
26816 throw new Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");
26817 }
26818 const headerByte = await reader.readByte();
26819 let tag = -1;
26820 let format = -1;
26821 let packet_length;
26822
26823 format = 0; // 0 = old format; 1 = new format
26824 if ((headerByte & 0x40) !== 0) {
26825 format = 1;
26826 }
26827
26828 let packet_length_type;
26829 if (format) {
26830 // new format header
26831 tag = headerByte & 0x3F; // bit 5-0
26832 } else {
26833 // old format header
26834 tag = (headerByte & 0x3F) >> 2; // bit 5-2
26835 packet_length_type = headerByte & 0x03; // bit 1-0
26836 }
26837
26838 const packetSupportsStreaming = supportsStreaming(tag);
26839 let packet = null;
26840 if (streaming && packetSupportsStreaming) {
26841 const transform = new stream.TransformStream();
26842 writer = stream.getWriter(transform.writable);
26843 packet = transform.readable;
26844 callbackReturned = callback({ tag, packet });
26845 } else {
26846 packet = [];
26847 }
26848
26849 let wasPartialLength;
26850 do {
26851 if (!format) {
26852 // 4.2.1. Old Format Packet Lengths
26853 switch (packet_length_type) {
26854 case 0:
26855 // The packet has a one-octet length. The header is 2 octets
26856 // long.
26857 packet_length = await reader.readByte();
26858 break;
26859 case 1:
26860 // The packet has a two-octet length. The header is 3 octets
26861 // long.
26862 packet_length = (await reader.readByte() << 8) | await reader.readByte();
26863 break;
26864 case 2:
26865 // The packet has a four-octet length. The header is 5
26866 // octets long.
26867 packet_length = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
26868 8) | await reader.readByte();
26869 break;
26870 default:
26871 // 3 - The packet is of indeterminate length. The header is 1
26872 // octet long, and the implementation must determine how long
26873 // the packet is. If the packet is in a file, this means that
26874 // the packet extends until the end of the file. In general,
26875 // an implementation SHOULD NOT use indeterminate-length
26876 // packets except where the end of the data will be clear
26877 // from the context, and even then it is better to use a
26878 // definite length, or a new format header. The new format
26879 // headers described below have a mechanism for precisely
26880 // encoding data of indeterminate length.
26881 packet_length = Infinity;
26882 break;
26883 }
26884 } else { // 4.2.2. New Format Packet Lengths
26885 // 4.2.2.1. One-Octet Lengths
26886 const lengthByte = await reader.readByte();
26887 wasPartialLength = false;
26888 if (lengthByte < 192) {
26889 packet_length = lengthByte;
26890 // 4.2.2.2. Two-Octet Lengths
26891 } else if (lengthByte >= 192 && lengthByte < 224) {
26892 packet_length = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
26893 // 4.2.2.4. Partial Body Lengths
26894 } else if (lengthByte > 223 && lengthByte < 255) {
26895 packet_length = 1 << (lengthByte & 0x1F);
26896 wasPartialLength = true;
26897 if (!packetSupportsStreaming) {
26898 throw new TypeError('This packet type does not support partial lengths.');
26899 }
26900 // 4.2.2.3. Five-Octet Lengths
26901 } else {
26902 packet_length = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
26903 8) | await reader.readByte();
26904 }
26905 }
26906 if (packet_length > 0) {
26907 let bytesRead = 0;
26908 while (true) {
26909 if (writer) await writer.ready;
26910 const { done, value } = await reader.read();
26911 if (done) {
26912 if (packet_length === Infinity) break;
26913 throw new Error('Unexpected end of packet');
26914 }
26915 const chunk = packet_length === Infinity ? value : value.subarray(0, packet_length - bytesRead);
26916 if (writer) await writer.write(chunk);
26917 else packet.push(chunk);
26918 bytesRead += value.length;
26919 if (bytesRead >= packet_length) {
26920 reader.unshift(value.subarray(packet_length - bytesRead + value.length));
26921 break;
26922 }
26923 }
26924 }
26925 } while (wasPartialLength);
26926
26927 // If this was not a packet that "supports streaming", we peek to check
26928 // whether it is the last packet in the message. We peek 2 bytes instead
26929 // of 1 because the beginning of this function also peeks 2 bytes, and we
26930 // want to cut a `subarray` of the correct length into `web-stream-tools`'
26931 // `externalBuffer` as a tiny optimization here.
26932 //
26933 // If it *was* a streaming packet (i.e. the data packets), we peek at the
26934 // entire remainder of the stream, in order to forward errors in the
26935 // remainder of the stream to the packet data. (Note that this means we
26936 // read/peek at all signature packets before closing the literal data
26937 // packet, for example.) This forwards MDC errors to the literal data
26938 // stream, for example, so that they don't get lost / forgotten on
26939 // decryptedMessage.packets.stream, which we never look at.
26940 //
26941 // An example of what we do when stream-parsing a message containing
26942 // [ one-pass signature packet, literal data packet, signature packet ]:
26943 // 1. Read the one-pass signature packet
26944 // 2. Peek 2 bytes of the literal data packet
26945 // 3. Parse the one-pass signature packet
26946 //
26947 // 4. Read the literal data packet, simultaneously stream-parsing it
26948 // 5. Peek until the end of the message
26949 // 6. Finish parsing the literal data packet
26950 //
26951 // 7. Read the signature packet again (we already peeked at it in step 5)
26952 // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
26953 // 9. Parse the signature packet
26954 //
26955 // Note that this means that if there's an error in the very end of the
26956 // stream, such as an MDC error, we throw in step 5 instead of in step 8
26957 // (or never), which is the point of this exercise.
26958 const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);
26959 if (writer) {
26960 await writer.ready;
26961 await writer.close();
26962 } else {
26963 packet = util.concatUint8Array(packet);
26964 await callback({ tag, packet });
26965 }
26966 return !nextPacket || !nextPacket.length;
26967 } catch (e) {
26968 if (writer) {
26969 await writer.abort(e);
26970 return true;
26971 } else {
26972 throw e;
26973 }
26974 } finally {
26975 if (writer) {
26976 await callbackReturned;
26977 }
26978 reader.releaseLock();
26979 }
26980}
26981
26982// GPG4Browsers - An OpenPGP implementation in javascript
26983
26984/**
26985 * Implementation of the User Attribute Packet (Tag 17)
26986 *
26987 * The User Attribute packet is a variation of the User ID packet. It
26988 * is capable of storing more types of data than the User ID packet,
26989 * which is limited to text. Like the User ID packet, a User Attribute
26990 * packet may be certified by the key owner ("self-signed") or any other
26991 * key owner who cares to certify it. Except as noted, a User Attribute
26992 * packet may be used anywhere that a User ID packet may be used.
26993 *
26994 * While User Attribute packets are not a required part of the OpenPGP
26995 * standard, implementations SHOULD provide at least enough
26996 * compatibility to properly handle a certification signature on the
26997 * User Attribute packet. A simple way to do this is by treating the
26998 * User Attribute packet as a User ID packet with opaque contents, but
26999 * an implementation may use any method desired.
27000 */
27001class UserAttributePacket {
27002 constructor() {
27003 this.tag = enums.packet.userAttribute;
27004 this.attributes = [];
27005 }
27006
27007 /**
27008 * parsing function for a user attribute packet (tag 17).
27009 * @param {Uint8Array} input - Payload of a tag 17 packet
27010 */
27011 read(bytes) {
27012 let i = 0;
27013 while (i < bytes.length) {
27014 const len = readSimpleLength(bytes.subarray(i, bytes.length));
27015 i += len.offset;
27016
27017 this.attributes.push(util.uint8ArrayToStr(bytes.subarray(i, i + len.len)));
27018 i += len.len;
27019 }
27020 }
27021
27022 /**
27023 * Creates a binary representation of the user attribute packet
27024 * @returns {Uint8Array} String representation.
27025 */
27026 write() {
27027 const arr = [];
27028 for (let i = 0; i < this.attributes.length; i++) {
27029 arr.push(writeSimpleLength(this.attributes[i].length));
27030 arr.push(util.strToUint8Array(this.attributes[i]));
27031 }
27032 return util.concatUint8Array(arr);
27033 }
27034
27035 /**
27036 * Compare for equality
27037 * @param {UserAttributePacket} usrAttr
27038 * @returns {Boolean} True if equal.
27039 */
27040 equals(usrAttr) {
27041 if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
27042 return false;
27043 }
27044 return this.attributes.every(function(attr, index) {
27045 return attr === usrAttr.attributes[index];
27046 });
27047 }
27048}
27049
27050// GPG4Browsers - An OpenPGP implementation in javascript
27051
27052/**
27053 * Implementation of the Signature Packet (Tag 2)
27054 *
27055 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
27056 * A Signature packet describes a binding between some public key and
27057 * some data. The most common signatures are a signature of a file or a
27058 * block of text, and a signature that is a certification of a User ID.
27059 */
27060class SignaturePacket {
27061 /**
27062 * @param {Date} date - The creation date of the signature
27063 */
27064 constructor(date = new Date()) {
27065 this.tag = enums.packet.signature;
27066 this.version = 4; // This is set to 5 below if we sign with a V5 key.
27067 this.signatureType = null;
27068 this.hashAlgorithm = null;
27069 this.publicKeyAlgorithm = null;
27070
27071 this.signatureData = null;
27072 this.unhashedSubpackets = [];
27073 this.signedHashValue = null;
27074
27075 this.created = util.normalizeDate(date);
27076 this.signatureExpirationTime = null;
27077 this.signatureNeverExpires = true;
27078 this.exportable = null;
27079 this.trustLevel = null;
27080 this.trustAmount = null;
27081 this.regularExpression = null;
27082 this.revocable = null;
27083 this.keyExpirationTime = null;
27084 this.keyNeverExpires = null;
27085 this.preferredSymmetricAlgorithms = null;
27086 this.revocationKeyClass = null;
27087 this.revocationKeyAlgorithm = null;
27088 this.revocationKeyFingerprint = null;
27089 this.issuerKeyId = new Keyid();
27090 this.rawNotations = [];
27091 this.notations = {};
27092 this.preferredHashAlgorithms = null;
27093 this.preferredCompressionAlgorithms = null;
27094 this.keyServerPreferences = null;
27095 this.preferredKeyServer = null;
27096 this.isPrimaryUserID = null;
27097 this.policyURI = null;
27098 this.keyFlags = null;
27099 this.signersUserId = null;
27100 this.reasonForRevocationFlag = null;
27101 this.reasonForRevocationString = null;
27102 this.features = null;
27103 this.signatureTargetPublicKeyAlgorithm = null;
27104 this.signatureTargetHashAlgorithm = null;
27105 this.signatureTargetHash = null;
27106 this.embeddedSignature = null;
27107 this.issuerKeyVersion = null;
27108 this.issuerFingerprint = null;
27109 this.preferredAeadAlgorithms = null;
27110
27111 this.verified = null;
27112 this.revoked = null;
27113 }
27114
27115 /**
27116 * parsing function for a signature packet (tag 2).
27117 * @param {String} bytes - Payload of a tag 2 packet
27118 * @returns {SignaturePacket} Object representation.
27119 */
27120 read(bytes) {
27121 let i = 0;
27122 this.version = bytes[i++];
27123
27124 if (this.version !== 4 && this.version !== 5) {
27125 throw new Error('Version ' + this.version + ' of the signature is unsupported.');
27126 }
27127
27128 this.signatureType = bytes[i++];
27129 this.publicKeyAlgorithm = bytes[i++];
27130 this.hashAlgorithm = bytes[i++];
27131
27132 // hashed subpackets
27133 i += this.read_sub_packets(bytes.subarray(i, bytes.length), true);
27134
27135 // A V4 signature hashes the packet body
27136 // starting from its first field, the version number, through the end
27137 // of the hashed subpacket data. Thus, the fields hashed are the
27138 // signature version, the signature type, the public-key algorithm, the
27139 // hash algorithm, the hashed subpacket length, and the hashed
27140 // subpacket body.
27141 this.signatureData = bytes.subarray(0, i);
27142
27143 // unhashed subpackets
27144 i += this.read_sub_packets(bytes.subarray(i, bytes.length), false);
27145
27146 // Two-octet field holding left 16 bits of signed hash value.
27147 this.signedHashValue = bytes.subarray(i, i + 2);
27148 i += 2;
27149
27150 this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));
27151 }
27152
27153 /**
27154 * @returns {Uint8Array | ReadableStream<Uint8Array>}
27155 */
27156 write_params() {
27157 if (this.params instanceof Promise) {
27158 return stream.fromAsync(
27159 async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params)
27160 );
27161 }
27162 return mod.serializeParams(this.publicKeyAlgorithm, this.params);
27163 }
27164
27165 write() {
27166 const arr = [];
27167 arr.push(this.signatureData);
27168 arr.push(this.write_unhashed_sub_packets());
27169 arr.push(this.signedHashValue);
27170 arr.push(this.write_params());
27171 return util.concat(arr);
27172 }
27173
27174 /**
27175 * Signs provided data. This needs to be done prior to serialization.
27176 * @param {SecretKeyPacket} key - Private key used to sign the message.
27177 * @param {Object} data - Contains packets to be signed.
27178 * @param {Boolean} [detached] - Whether to create a detached signature
27179 * @param {Boolean} [streaming] - Whether to process data as a stream
27180 * @throws {Error} if signing failed
27181 * @async
27182 */
27183 async sign(key, data, detached = false, streaming = false) {
27184 const signatureType = enums.write(enums.signature, this.signatureType);
27185 const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm);
27186 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
27187
27188 if (key.version === 5) {
27189 this.version = 5;
27190 }
27191 const arr = [new Uint8Array([this.version, signatureType, publicKeyAlgorithm, hashAlgorithm])];
27192
27193 this.issuerKeyVersion = key.version;
27194 this.issuerFingerprint = key.getFingerprintBytes();
27195 this.issuerKeyId = key.getKeyId();
27196
27197 // Add hashed subpackets
27198 arr.push(this.write_hashed_sub_packets());
27199
27200 this.signatureData = util.concat(arr);
27201
27202 const toHash = this.toHash(signatureType, data, detached);
27203 const hash = await this.hash(signatureType, data, toHash, detached);
27204
27205 this.signedHashValue = stream.slice(stream.clone(hash), 0, 2);
27206 const signed = async () => mod.signature.sign(
27207 publicKeyAlgorithm, hashAlgorithm, key.publicParams, key.privateParams, toHash, await stream.readToEnd(hash)
27208 );
27209 if (streaming) {
27210 this.params = signed();
27211 } else {
27212 this.params = await signed();
27213
27214 // Store the fact that this signature is valid, e.g. for when we call `await
27215 // getLatestValidSignature(this.revocationSignatures, key, data)` later.
27216 // Note that this only holds up if the key and data passed to verify are the
27217 // same as the ones passed to sign.
27218 this.verified = true;
27219 }
27220 }
27221
27222 /**
27223 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
27224 * @returns {Uint8Array} Subpacket data.
27225 */
27226 write_hashed_sub_packets() {
27227 const sub = enums.signatureSubpacket;
27228 const arr = [];
27229 let bytes;
27230 if (this.created !== null) {
27231 arr.push(write_sub_packet(sub.signatureCreationTime, util.writeDate(this.created)));
27232 }
27233 if (this.signatureExpirationTime !== null) {
27234 arr.push(write_sub_packet(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4)));
27235 }
27236 if (this.exportable !== null) {
27237 arr.push(write_sub_packet(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0])));
27238 }
27239 if (this.trustLevel !== null) {
27240 bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
27241 arr.push(write_sub_packet(sub.trustSignature, bytes));
27242 }
27243 if (this.regularExpression !== null) {
27244 arr.push(write_sub_packet(sub.regularExpression, this.regularExpression));
27245 }
27246 if (this.revocable !== null) {
27247 arr.push(write_sub_packet(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
27248 }
27249 if (this.keyExpirationTime !== null) {
27250 arr.push(write_sub_packet(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4)));
27251 }
27252 if (this.preferredSymmetricAlgorithms !== null) {
27253 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredSymmetricAlgorithms));
27254 arr.push(write_sub_packet(sub.preferredSymmetricAlgorithms, bytes));
27255 }
27256 if (this.revocationKeyClass !== null) {
27257 bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
27258 bytes = util.concat([bytes, this.revocationKeyFingerprint]);
27259 arr.push(write_sub_packet(sub.revocationKey, bytes));
27260 }
27261 this.rawNotations.forEach(([{ name, value, humanReadable }]) => {
27262 bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
27263 // 2 octets of name length
27264 bytes.push(util.writeNumber(name.length, 2));
27265 // 2 octets of value length
27266 bytes.push(util.writeNumber(value.length, 2));
27267 bytes.push(util.strToUint8Array(name));
27268 bytes.push(value);
27269 bytes = util.concat(bytes);
27270 arr.push(write_sub_packet(sub.notationData, bytes));
27271 });
27272 if (this.preferredHashAlgorithms !== null) {
27273 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredHashAlgorithms));
27274 arr.push(write_sub_packet(sub.preferredHashAlgorithms, bytes));
27275 }
27276 if (this.preferredCompressionAlgorithms !== null) {
27277 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredCompressionAlgorithms));
27278 arr.push(write_sub_packet(sub.preferredCompressionAlgorithms, bytes));
27279 }
27280 if (this.keyServerPreferences !== null) {
27281 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyServerPreferences));
27282 arr.push(write_sub_packet(sub.keyServerPreferences, bytes));
27283 }
27284 if (this.preferredKeyServer !== null) {
27285 arr.push(write_sub_packet(sub.preferredKeyServer, util.strToUint8Array(this.preferredKeyServer)));
27286 }
27287 if (this.isPrimaryUserID !== null) {
27288 arr.push(write_sub_packet(sub.primaryUserId, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
27289 }
27290 if (this.policyURI !== null) {
27291 arr.push(write_sub_packet(sub.policyUri, util.strToUint8Array(this.policyURI)));
27292 }
27293 if (this.keyFlags !== null) {
27294 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.keyFlags));
27295 arr.push(write_sub_packet(sub.keyFlags, bytes));
27296 }
27297 if (this.signersUserId !== null) {
27298 arr.push(write_sub_packet(sub.signersUserId, util.strToUint8Array(this.signersUserId)));
27299 }
27300 if (this.reasonForRevocationFlag !== null) {
27301 bytes = util.strToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
27302 arr.push(write_sub_packet(sub.reasonForRevocation, bytes));
27303 }
27304 if (this.features !== null) {
27305 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.features));
27306 arr.push(write_sub_packet(sub.features, bytes));
27307 }
27308 if (this.signatureTargetPublicKeyAlgorithm !== null) {
27309 bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
27310 bytes.push(util.strToUint8Array(this.signatureTargetHash));
27311 bytes = util.concat(bytes);
27312 arr.push(write_sub_packet(sub.signatureTarget, bytes));
27313 }
27314 if (this.preferredAeadAlgorithms !== null) {
27315 bytes = util.strToUint8Array(util.uint8ArrayToStr(this.preferredAeadAlgorithms));
27316 arr.push(write_sub_packet(sub.preferredAeadAlgorithms, bytes));
27317 }
27318
27319 const result = util.concat(arr);
27320 const length = util.writeNumber(result.length, 2);
27321
27322 return util.concat([length, result]);
27323 }
27324
27325 /**
27326 * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets
27327 * @returns {Uint8Array} Subpacket data.
27328 */
27329 write_unhashed_sub_packets() {
27330 const sub = enums.signatureSubpacket;
27331 const arr = [];
27332 let bytes;
27333 if (!this.issuerKeyId.isNull() && this.issuerKeyVersion !== 5) {
27334 // If the version of [the] key is greater than 4, this subpacket
27335 // MUST NOT be included in the signature.
27336 arr.push(write_sub_packet(sub.issuer, this.issuerKeyId.write()));
27337 }
27338 if (this.embeddedSignature !== null) {
27339 arr.push(write_sub_packet(sub.embeddedSignature, this.embeddedSignature.write()));
27340 }
27341 if (this.issuerFingerprint !== null) {
27342 bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
27343 bytes = util.concat(bytes);
27344 arr.push(write_sub_packet(sub.issuerFingerprint, bytes));
27345 }
27346 this.unhashedSubpackets.forEach(data => {
27347 arr.push(writeSimpleLength(data.length));
27348 arr.push(data);
27349 });
27350
27351 const result = util.concat(arr);
27352 const length = util.writeNumber(result.length, 2);
27353
27354 return util.concat([length, result]);
27355 }
27356
27357 // V4 signature sub packets
27358
27359 read_sub_packet(bytes, trusted = true) {
27360 let mypos = 0;
27361
27362 const read_array = (prop, bytes) => {
27363 this[prop] = [];
27364
27365 for (let i = 0; i < bytes.length; i++) {
27366 this[prop].push(bytes[i]);
27367 }
27368 };
27369
27370 // The leftmost bit denotes a "critical" packet
27371 const critical = bytes[mypos] & 0x80;
27372 const type = bytes[mypos] & 0x7F;
27373
27374 // GPG puts the Issuer and Signature subpackets in the unhashed area.
27375 // Tampering with those invalidates the signature, so we can trust them.
27376 // Ignore all other unhashed subpackets.
27377 if (!trusted && ![
27378 enums.signatureSubpacket.issuer,
27379 enums.signatureSubpacket.issuerFingerprint,
27380 enums.signatureSubpacket.embeddedSignature
27381 ].includes(type)) {
27382 this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
27383 return;
27384 }
27385
27386 mypos++;
27387
27388 // subpacket type
27389 switch (type) {
27390 case 2:
27391 // Signature Creation Time
27392 this.created = util.readDate(bytes.subarray(mypos, bytes.length));
27393 break;
27394 case 3: {
27395 // Signature Expiration Time in seconds
27396 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
27397
27398 this.signatureNeverExpires = seconds === 0;
27399 this.signatureExpirationTime = seconds;
27400
27401 break;
27402 }
27403 case 4:
27404 // Exportable Certification
27405 this.exportable = bytes[mypos++] === 1;
27406 break;
27407 case 5:
27408 // Trust Signature
27409 this.trustLevel = bytes[mypos++];
27410 this.trustAmount = bytes[mypos++];
27411 break;
27412 case 6:
27413 // Regular Expression
27414 this.regularExpression = bytes[mypos];
27415 break;
27416 case 7:
27417 // Revocable
27418 this.revocable = bytes[mypos++] === 1;
27419 break;
27420 case 9: {
27421 // Key Expiration Time in seconds
27422 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
27423
27424 this.keyExpirationTime = seconds;
27425 this.keyNeverExpires = seconds === 0;
27426
27427 break;
27428 }
27429 case 11:
27430 // Preferred Symmetric Algorithms
27431 read_array('preferredSymmetricAlgorithms', bytes.subarray(mypos, bytes.length));
27432 break;
27433 case 12:
27434 // Revocation Key
27435 // (1 octet of class, 1 octet of public-key algorithm ID, 20
27436 // octets of
27437 // fingerprint)
27438 this.revocationKeyClass = bytes[mypos++];
27439 this.revocationKeyAlgorithm = bytes[mypos++];
27440 this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
27441 break;
27442
27443 case 16:
27444 // Issuer
27445 this.issuerKeyId.read(bytes.subarray(mypos, bytes.length));
27446 break;
27447
27448 case 20: {
27449 // Notation Data
27450 const humanReadable = !!(bytes[mypos] & 0x80);
27451
27452 // We extract key/value tuple from the byte stream.
27453 mypos += 4;
27454 const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
27455 mypos += 2;
27456 const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
27457 mypos += 2;
27458
27459 const name = util.uint8ArrayToStr(bytes.subarray(mypos, mypos + m));
27460 const value = bytes.subarray(mypos + m, mypos + m + n);
27461
27462 this.rawNotations.push({ name, humanReadable, value, critical });
27463
27464 if (humanReadable) {
27465 this.notations[name] = util.uint8ArrayToStr(value);
27466 }
27467 break;
27468 }
27469 case 21:
27470 // Preferred Hash Algorithms
27471 read_array('preferredHashAlgorithms', bytes.subarray(mypos, bytes.length));
27472 break;
27473 case 22:
27474 // Preferred Compression Algorithms
27475 read_array('preferredCompressionAlgorithms', bytes.subarray(mypos, bytes.length));
27476 break;
27477 case 23:
27478 // Key Server Preferences
27479 read_array('keyServerPreferences', bytes.subarray(mypos, bytes.length));
27480 break;
27481 case 24:
27482 // Preferred Key Server
27483 this.preferredKeyServer = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length));
27484 break;
27485 case 25:
27486 // Primary User ID
27487 this.isPrimaryUserID = bytes[mypos++] !== 0;
27488 break;
27489 case 26:
27490 // Policy URI
27491 this.policyURI = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length));
27492 break;
27493 case 27:
27494 // Key Flags
27495 read_array('keyFlags', bytes.subarray(mypos, bytes.length));
27496 break;
27497 case 28:
27498 // Signer's User ID
27499 this.signersUserId = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length));
27500 break;
27501 case 29:
27502 // Reason for Revocation
27503 this.reasonForRevocationFlag = bytes[mypos++];
27504 this.reasonForRevocationString = util.uint8ArrayToStr(bytes.subarray(mypos, bytes.length));
27505 break;
27506 case 30:
27507 // Features
27508 read_array('features', bytes.subarray(mypos, bytes.length));
27509 break;
27510 case 31: {
27511 // Signature Target
27512 // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
27513 this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
27514 this.signatureTargetHashAlgorithm = bytes[mypos++];
27515
27516 const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm);
27517
27518 this.signatureTargetHash = util.uint8ArrayToStr(bytes.subarray(mypos, mypos + len));
27519 break;
27520 }
27521 case 32:
27522 // Embedded Signature
27523 this.embeddedSignature = new SignaturePacket();
27524 this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
27525 break;
27526 case 33:
27527 // Issuer Fingerprint
27528 this.issuerKeyVersion = bytes[mypos++];
27529 this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
27530 if (this.issuerKeyVersion === 5) {
27531 this.issuerKeyId.read(this.issuerFingerprint);
27532 } else {
27533 this.issuerKeyId.read(this.issuerFingerprint.subarray(-8));
27534 }
27535 break;
27536 case 34:
27537 // Preferred AEAD Algorithms
27538 read_array.call(this, 'preferredAeadAlgorithms', bytes.subarray(mypos, bytes.length));
27539 break;
27540 default: {
27541 const err = new Error("Unknown signature subpacket type " + type + " @:" + mypos);
27542 if (critical) {
27543 throw err;
27544 } else {
27545 util.printDebug(err);
27546 }
27547 }
27548 }
27549 }
27550
27551 read_sub_packets(bytes, trusted = true, config) {
27552 // Two-octet scalar octet count for following subpacket data.
27553 const subpacket_length = util.readNumber(bytes.subarray(0, 2));
27554
27555 let i = 2;
27556
27557 // subpacket data set (zero or more subpackets)
27558 while (i < 2 + subpacket_length) {
27559 const len = readSimpleLength(bytes.subarray(i, bytes.length));
27560 i += len.offset;
27561
27562 this.read_sub_packet(bytes.subarray(i, i + len.len), trusted, config);
27563
27564 i += len.len;
27565 }
27566
27567 return i;
27568 }
27569
27570 // Produces data to produce signature on
27571 toSign(type, data) {
27572 const t = enums.signature;
27573
27574 switch (type) {
27575 case t.binary:
27576 if (data.text !== null) {
27577 return util.encodeUtf8(data.getText(true));
27578 }
27579 return data.getBytes(true);
27580
27581 case t.text: {
27582 const bytes = data.getBytes(true);
27583 // normalize EOL to \r\n
27584 return util.canonicalizeEOL(bytes);
27585 }
27586 case t.standalone:
27587 return new Uint8Array(0);
27588
27589 case t.certGeneric:
27590 case t.certPersona:
27591 case t.certCasual:
27592 case t.certPositive:
27593 case t.certRevocation: {
27594 let packet;
27595 let tag;
27596
27597 if (data.userId) {
27598 tag = 0xB4;
27599 packet = data.userId;
27600 } else if (data.userAttribute) {
27601 tag = 0xD1;
27602 packet = data.userAttribute;
27603 } else {
27604 throw new Error('Either a userId or userAttribute packet needs to be ' +
27605 'supplied for certification.');
27606 }
27607
27608 const bytes = packet.write();
27609
27610 return util.concat([this.toSign(t.key, data),
27611 new Uint8Array([tag]),
27612 util.writeNumber(bytes.length, 4),
27613 bytes]);
27614 }
27615 case t.subkeyBinding:
27616 case t.subkeyRevocation:
27617 case t.keyBinding:
27618 return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
27619 key: data.bind
27620 })]);
27621
27622 case t.key:
27623 if (data.key === undefined) {
27624 throw new Error('Key packet is required for this signature.');
27625 }
27626 return data.key.writeForHash(this.version);
27627
27628 case t.keyRevocation:
27629 return this.toSign(t.key, data);
27630 case t.timestamp:
27631 return new Uint8Array(0);
27632 case t.thirdParty:
27633 throw new Error('Not implemented');
27634 default:
27635 throw new Error('Unknown signature type.');
27636 }
27637 }
27638
27639 calculateTrailer(data, detached) {
27640 let length = 0;
27641 return stream.transform(stream.clone(this.signatureData), value => {
27642 length += value.length;
27643 }, () => {
27644 const arr = [];
27645 if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
27646 if (detached) {
27647 arr.push(new Uint8Array(6));
27648 } else {
27649 arr.push(data.writeHeader());
27650 }
27651 }
27652 arr.push(new Uint8Array([this.version, 0xFF]));
27653 if (this.version === 5) {
27654 arr.push(new Uint8Array(4));
27655 }
27656 arr.push(util.writeNumber(length, 4));
27657 // For v5, this should really be writeNumber(length, 8) rather than the
27658 // hardcoded 4 zero bytes above
27659 return util.concat(arr);
27660 });
27661 }
27662
27663 toHash(signatureType, data, detached = false) {
27664 const bytes = this.toSign(signatureType, data);
27665
27666 return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
27667 }
27668
27669 async hash(signatureType, data, toHash, detached = false, streaming = true) {
27670 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
27671 if (!toHash) toHash = this.toHash(signatureType, data, detached);
27672 if (!streaming && util.isStream(toHash)) {
27673 return stream.fromAsync(async () => this.hash(signatureType, data, await stream.readToEnd(toHash), detached));
27674 }
27675 return mod.hash.digest(hashAlgorithm, toHash);
27676 }
27677
27678 /**
27679 * verifies the signature packet. Note: not all signature types are implemented
27680 * @param {PublicSubkeyPacket|PublicKeyPacket|
27681 * SecretSubkeyPacket|SecretKeyPacket} key the public key to verify the signature
27682 * @param {module:enums.signature} signatureType - Expected signature type
27683 * @param {String|Object} data - Data which on the signature applies
27684 * @param {Boolean} [detached] - Whether to verify a detached signature
27685 * @param {Boolean} [streaming] - Whether to process data as a stream
27686 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27687 * @throws {Error} if signature validation failed
27688 * @async
27689 */
27690 async verify(key, signatureType, data, detached = false, streaming = false, config = defaultConfig) {
27691 const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm);
27692 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
27693
27694 if (publicKeyAlgorithm !== enums.write(enums.publicKey, key.algorithm)) {
27695 throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
27696 }
27697
27698 let toHash;
27699 let hash;
27700 if (this.hashed) {
27701 hash = await this.hashed;
27702 } else {
27703 toHash = this.toHash(signatureType, data, detached);
27704 if (!streaming) toHash = await stream.readToEnd(toHash);
27705 hash = await this.hash(signatureType, data, toHash);
27706 }
27707 hash = await stream.readToEnd(hash);
27708 if (this.signedHashValue[0] !== hash[0] ||
27709 this.signedHashValue[1] !== hash[1]) {
27710 throw new Error('Message digest did not match');
27711 }
27712
27713 this.params = await this.params;
27714
27715 const verified = await mod.signature.verify(
27716 publicKeyAlgorithm, hashAlgorithm, this.params, key.publicParams,
27717 toHash, hash
27718 );
27719 if (!verified) {
27720 throw new Error('Signature verification failed');
27721 }
27722 if (config.rejectHashAlgorithms.has(hashAlgorithm)) {
27723 throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, hashAlgorithm).toUpperCase());
27724 }
27725 if (config.rejectMessageHashAlgorithms.has(hashAlgorithm) &&
27726 [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
27727 throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, hashAlgorithm).toUpperCase());
27728 }
27729 this.rawNotations.forEach(({ name, critical }) => {
27730 if (critical && (config.knownNotations.indexOf(name) < 0)) {
27731 throw new Error(`Unknown critical notation: ${name}`);
27732 }
27733 });
27734 if (this.revocationKeyClass !== null) {
27735 throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
27736 }
27737 this.verified = true;
27738 }
27739
27740 /**
27741 * Verifies signature expiration date
27742 * @param {Date} [date] - Use the given date for verification instead of the current time
27743 * @returns {Boolean} True if expired.
27744 */
27745 isExpired(date = new Date()) {
27746 const normDate = util.normalizeDate(date);
27747 if (normDate !== null) {
27748 const expirationTime = this.getExpirationTime();
27749 return !(this.created <= normDate && normDate <= expirationTime);
27750 }
27751 return false;
27752 }
27753
27754 /**
27755 * Returns the expiration time of the signature or Infinity if signature does not expire
27756 * @returns {Date} Expiration time.
27757 */
27758 getExpirationTime() {
27759 return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity;
27760 }
27761}
27762
27763/**
27764 * Creates a string representation of a sub signature packet
27765 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
27766 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
27767 * @param {Integer} type - Subpacket signature type.
27768 * @param {String} data - Data to be included
27769 * @returns {String} A string-representation of a sub signature packet.
27770 * @private
27771 */
27772function write_sub_packet(type, data) {
27773 const arr = [];
27774 arr.push(writeSimpleLength(data.length + 1));
27775 arr.push(new Uint8Array([type]));
27776 arr.push(data);
27777 return util.concat(arr);
27778}
27779
27780// GPG4Browsers - An OpenPGP implementation in javascript
27781
27782/**
27783 * Implementation of the One-Pass Signature Packets (Tag 4)
27784 *
27785 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
27786 * The One-Pass Signature packet precedes the signed data and contains
27787 * enough information to allow the receiver to begin calculating any
27788 * hashes needed to verify the signature. It allows the Signature
27789 * packet to be placed at the end of the message, so that the signer
27790 * can compute the entire signed message in one pass.
27791 */
27792class OnePassSignaturePacket {
27793 constructor() {
27794 /**
27795 * Packet type
27796 * @type {module:enums.packet}
27797 */
27798 this.tag = enums.packet.onePassSignature;
27799 /** A one-octet version number. The current version is 3. */
27800 this.version = null;
27801 /**
27802 * A one-octet signature type.
27803 * Signature types are described in
27804 * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
27805 */
27806 this.signatureType = null;
27807 /**
27808 * A one-octet number describing the hash algorithm used.
27809 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
27810 */
27811 this.hashAlgorithm = null;
27812 /**
27813 * A one-octet number describing the public-key algorithm used.
27814 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
27815 */
27816 this.publicKeyAlgorithm = null;
27817 /** An eight-octet number holding the Key ID of the signing key. */
27818 this.issuerKeyId = null;
27819 /**
27820 * A one-octet number holding a flag showing whether the signature is nested.
27821 * A zero value indicates that the next packet is another One-Pass Signature packet
27822 * that describes another signature to be applied to the same message data.
27823 */
27824 this.flags = null;
27825 }
27826
27827 /**
27828 * parsing function for a one-pass signature packet (tag 4).
27829 * @param {Uint8Array} bytes - Payload of a tag 4 packet
27830 * @returns {OnePassSignaturePacket} Object representation.
27831 */
27832 read(bytes) {
27833 let mypos = 0;
27834 // A one-octet version number. The current version is 3.
27835 this.version = bytes[mypos++];
27836
27837 // A one-octet signature type. Signature types are described in
27838 // Section 5.2.1.
27839 this.signatureType = bytes[mypos++];
27840
27841 // A one-octet number describing the hash algorithm used.
27842 this.hashAlgorithm = bytes[mypos++];
27843
27844 // A one-octet number describing the public-key algorithm used.
27845 this.publicKeyAlgorithm = bytes[mypos++];
27846
27847 // An eight-octet number holding the Key ID of the signing key.
27848 this.issuerKeyId = new Keyid();
27849 this.issuerKeyId.read(bytes.subarray(mypos, mypos + 8));
27850 mypos += 8;
27851
27852 // A one-octet number holding a flag showing whether the signature
27853 // is nested. A zero value indicates that the next packet is
27854 // another One-Pass Signature packet that describes another
27855 // signature to be applied to the same message data.
27856 this.flags = bytes[mypos++];
27857 return this;
27858 }
27859
27860 /**
27861 * creates a string representation of a one-pass signature packet
27862 * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
27863 */
27864 write() {
27865 const start = new Uint8Array([3, enums.write(enums.signature, this.signatureType),
27866 enums.write(enums.hash, this.hashAlgorithm),
27867 enums.write(enums.publicKey, this.publicKeyAlgorithm)]);
27868
27869 const end = new Uint8Array([this.flags]);
27870
27871 return util.concatUint8Array([start, this.issuerKeyId.write(), end]);
27872 }
27873
27874 calculateTrailer(...args) {
27875 return stream.fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
27876 }
27877
27878 async verify() {
27879 const correspondingSig = await this.correspondingSig;
27880 if (!correspondingSig || correspondingSig.tag !== enums.packet.signature) {
27881 throw new Error('Corresponding signature packet missing');
27882 }
27883 if (
27884 correspondingSig.signatureType !== this.signatureType ||
27885 correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
27886 correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
27887 !correspondingSig.issuerKeyId.equals(this.issuerKeyId)
27888 ) {
27889 throw new Error('Corresponding signature packet does not match one-pass signature packet');
27890 }
27891 correspondingSig.hashed = this.hashed;
27892 return correspondingSig.verify.apply(correspondingSig, arguments);
27893 }
27894}
27895
27896OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
27897OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
27898OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;
27899
27900// GPG4Browsers - An OpenPGP implementation in javascript
27901
27902/**
27903 * A Secret-Key packet contains all the information that is found in a
27904 * Public-Key packet, including the public-key material, but also
27905 * includes the secret-key material after all the public-key fields.
27906 * @extends PublicKeyPacket
27907 */
27908class SecretKeyPacket extends PublicKeyPacket {
27909 /**
27910 * @param {Date} [date] - Creation date
27911 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27912 */
27913 constructor(date = new Date(), config = defaultConfig) {
27914 super(date, config);
27915 /**
27916 * Packet type
27917 * @type {module:enums.packet}
27918 */
27919 this.tag = enums.packet.secretKey;
27920 /**
27921 * Secret-key data
27922 */
27923 this.keyMaterial = null;
27924 /**
27925 * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
27926 */
27927 this.isEncrypted = null;
27928 /**
27929 * S2K usage
27930 * @type {Integer}
27931 */
27932 this.s2k_usage = 0;
27933 /**
27934 * S2K object
27935 * @type {type/s2k}
27936 */
27937 this.s2k = null;
27938 /**
27939 * Symmetric algorithm
27940 * @type {String}
27941 */
27942 this.symmetric = null;
27943 /**
27944 * AEAD algorithm
27945 * @type {String}
27946 */
27947 this.aead = null;
27948 /**
27949 * Decrypted private parameters, referenced by name
27950 * @type {Object}
27951 */
27952 this.privateParams = null;
27953 }
27954
27955 // 5.5.3. Secret-Key Packet Formats
27956
27957 /**
27958 * Internal parser for private keys as specified in
27959 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
27960 * @param {String} bytes - Input string to read the packet from
27961 */
27962 read(bytes) {
27963 // - A Public-Key or Public-Subkey packet, as described above.
27964 let i = this.readPublicKey(bytes);
27965
27966 // - One octet indicating string-to-key usage conventions. Zero
27967 // indicates that the secret-key data is not encrypted. 255 or 254
27968 // indicates that a string-to-key specifier is being given. Any
27969 // other value is a symmetric-key encryption algorithm identifier.
27970 this.s2k_usage = bytes[i++];
27971
27972 // - Only for a version 5 packet, a one-octet scalar octet count of
27973 // the next 4 optional fields.
27974 if (this.version === 5) {
27975 i++;
27976 }
27977
27978 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
27979 // one-octet symmetric encryption algorithm.
27980 if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) {
27981 this.symmetric = bytes[i++];
27982 this.symmetric = enums.read(enums.symmetric, this.symmetric);
27983
27984 // - [Optional] If string-to-key usage octet was 253, a one-octet
27985 // AEAD algorithm.
27986 if (this.s2k_usage === 253) {
27987 this.aead = bytes[i++];
27988 this.aead = enums.read(enums.aead, this.aead);
27989 }
27990
27991 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
27992 // string-to-key specifier. The length of the string-to-key
27993 // specifier is implied by its type, as described above.
27994 this.s2k = new S2K();
27995 i += this.s2k.read(bytes.subarray(i, bytes.length));
27996
27997 if (this.s2k.type === 'gnu-dummy') {
27998 return;
27999 }
28000 } else if (this.s2k_usage) {
28001 this.symmetric = this.s2k_usage;
28002 this.symmetric = enums.read(enums.symmetric, this.symmetric);
28003 }
28004
28005 // - [Optional] If secret data is encrypted (string-to-key usage octet
28006 // not zero), an Initial Vector (IV) of the same length as the
28007 // cipher's block size.
28008 if (this.s2k_usage) {
28009 this.iv = bytes.subarray(
28010 i,
28011 i + mod.cipher[this.symmetric].blockSize
28012 );
28013
28014 i += this.iv.length;
28015 }
28016
28017 // - Only for a version 5 packet, a four-octet scalar octet count for
28018 // the following key material.
28019 if (this.version === 5) {
28020 i += 4;
28021 }
28022
28023 // - Plain or encrypted multiprecision integers comprising the secret
28024 // key data. These algorithm-specific fields are as described
28025 // below.
28026 this.keyMaterial = bytes.subarray(i);
28027 this.isEncrypted = !!this.s2k_usage;
28028
28029 if (!this.isEncrypted) {
28030 const cleartext = this.keyMaterial.subarray(0, -2);
28031 if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
28032 throw new Error('Key checksum mismatch');
28033 }
28034 try {
28035 const algo = enums.write(enums.publicKey, this.algorithm);
28036 const { privateParams } = mod.parsePrivateKeyParams(algo, cleartext, this.publicParams);
28037 this.privateParams = privateParams;
28038 } catch (err) {
28039 throw new Error('Error reading MPIs');
28040 }
28041 }
28042 }
28043
28044 /**
28045 * Creates an OpenPGP key packet for the given key.
28046 * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
28047 */
28048 write() {
28049 const arr = [this.writePublicKey()];
28050
28051 arr.push(new Uint8Array([this.s2k_usage]));
28052
28053 const optionalFieldsArr = [];
28054 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
28055 // one- octet symmetric encryption algorithm.
28056 if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) {
28057 optionalFieldsArr.push(enums.write(enums.symmetric, this.symmetric));
28058
28059 // - [Optional] If string-to-key usage octet was 253, a one-octet
28060 // AEAD algorithm.
28061 if (this.s2k_usage === 253) {
28062 optionalFieldsArr.push(enums.write(enums.aead, this.aead));
28063 }
28064
28065 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
28066 // string-to-key specifier. The length of the string-to-key
28067 // specifier is implied by its type, as described above.
28068 optionalFieldsArr.push(...this.s2k.write());
28069 }
28070
28071 // - [Optional] If secret data is encrypted (string-to-key usage octet
28072 // not zero), an Initial Vector (IV) of the same length as the
28073 // cipher's block size.
28074 if (this.s2k_usage && this.s2k.type !== 'gnu-dummy') {
28075 optionalFieldsArr.push(...this.iv);
28076 }
28077
28078 if (this.version === 5) {
28079 arr.push(new Uint8Array([optionalFieldsArr.length]));
28080 }
28081 arr.push(new Uint8Array(optionalFieldsArr));
28082
28083 if (!this.isDummy()) {
28084 if (!this.s2k_usage) {
28085 const algo = enums.write(enums.publicKey, this.algorithm);
28086 const cleartextParams = mod.serializeParams(algo, this.privateParams);
28087 this.keyMaterial = util.concatUint8Array([
28088 cleartextParams,
28089 util.writeChecksum(cleartextParams)
28090 ]);
28091 }
28092
28093 if (this.version === 5) {
28094 arr.push(util.writeNumber(this.keyMaterial.length, 4));
28095 }
28096 arr.push(this.keyMaterial);
28097 }
28098
28099 return util.concatUint8Array(arr);
28100 }
28101
28102 /**
28103 * Check whether secret-key data is available in decrypted form.
28104 * Returns false for gnu-dummy keys and null for public keys.
28105 * @returns {Boolean|null}
28106 */
28107 isDecrypted() {
28108 return this.isEncrypted === false;
28109 }
28110
28111 /**
28112 * Check whether this is a gnu-dummy key
28113 * @returns {Boolean}
28114 */
28115 isDummy() {
28116 return !!(this.s2k && this.s2k.type === 'gnu-dummy');
28117 }
28118
28119 /**
28120 * Remove private key material, converting the key to a dummy one.
28121 * The resulting key cannot be used for signing/decrypting but can still verify signatures.
28122 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28123 */
28124 makeDummy(config = defaultConfig) {
28125 if (this.isDummy()) {
28126 return;
28127 }
28128 if (this.isDecrypted()) {
28129 this.clearPrivateParams();
28130 }
28131 this.isEncrypted = null;
28132 this.keyMaterial = null;
28133 this.s2k = new S2K(config);
28134 this.s2k.algorithm = 0;
28135 this.s2k.c = 0;
28136 this.s2k.type = 'gnu-dummy';
28137 this.s2k_usage = 254;
28138 this.symmetric = 'aes256';
28139 }
28140
28141 /**
28142 * Encrypt the payload. By default, we use aes256 and iterated, salted string
28143 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
28144 * and the passphrase is empty or undefined, the key will be set as not encrypted.
28145 * This can be used to remove passphrase protection after calling decrypt().
28146 * @param {String} passphrase
28147 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28148 * @throws {Error} if encryption was not successful
28149 * @async
28150 */
28151 async encrypt(passphrase, config = defaultConfig) {
28152 if (this.isDummy()) {
28153 return;
28154 }
28155
28156 if (!this.isDecrypted()) {
28157 throw new Error('Key packet is already encrypted');
28158 }
28159
28160 if (this.isDecrypted() && !passphrase) {
28161 this.s2k_usage = 0;
28162 return;
28163 } else if (!passphrase) {
28164 throw new Error('The key must be decrypted before removing passphrase protection.');
28165 }
28166
28167 this.s2k = new S2K(config);
28168 this.s2k.salt = await mod.random.getRandomBytes(8);
28169 const algo = enums.write(enums.publicKey, this.algorithm);
28170 const cleartext = mod.serializeParams(algo, this.privateParams);
28171 this.symmetric = 'aes256';
28172 const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
28173 const blockLen = mod.cipher[this.symmetric].blockSize;
28174 this.iv = await mod.random.getRandomBytes(blockLen);
28175
28176 if (config.aeadProtect) {
28177 this.s2k_usage = 253;
28178 this.aead = 'eax';
28179 const mode = mod[this.aead];
28180 const modeInstance = await mode(this.symmetric, key);
28181 this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
28182 } else {
28183 this.s2k_usage = 254;
28184 this.keyMaterial = await mod.cfb.encrypt(this.symmetric, key, util.concatUint8Array([
28185 cleartext,
28186 await mod.hash.sha1(cleartext, config)
28187 ]), this.iv, config);
28188 }
28189 }
28190
28191 /**
28192 * Decrypts the private key params which are needed to use the key.
28193 * {@link SecretKeyPacket.isDecrypted} should be false, as
28194 * otherwise calls to this function will throw an error.
28195 * @param {String} passphrase - The passphrase for this private key as string
28196 * @throws {Error} if decryption was not successful
28197 * @async
28198 */
28199 async decrypt(passphrase) {
28200 if (this.isDummy()) {
28201 return false;
28202 }
28203
28204 if (this.isDecrypted()) {
28205 throw new Error('Key packet is already decrypted.');
28206 }
28207
28208 let key;
28209 if (this.s2k_usage === 254 || this.s2k_usage === 253) {
28210 key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
28211 } else if (this.s2k_usage === 255) {
28212 throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
28213 } else {
28214 throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
28215 }
28216
28217 let cleartext;
28218 if (this.s2k_usage === 253) {
28219 const mode = mod[this.aead];
28220 try {
28221 const modeInstance = await mode(this.symmetric, key);
28222 cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
28223 } catch (err) {
28224 if (err.message === 'Authentication tag mismatch') {
28225 throw new Error('Incorrect key passphrase: ' + err.message);
28226 }
28227 throw err;
28228 }
28229 } else {
28230 const cleartextWithHash = await mod.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
28231
28232 cleartext = cleartextWithHash.subarray(0, -20);
28233 const hash = await mod.hash.sha1(cleartext);
28234
28235 if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
28236 throw new Error('Incorrect key passphrase');
28237 }
28238 }
28239
28240 try {
28241 const algo = enums.write(enums.publicKey, this.algorithm);
28242 const { privateParams } = mod.parsePrivateKeyParams(algo, cleartext, this.publicParams);
28243 this.privateParams = privateParams;
28244 } catch (err) {
28245 throw new Error('Error reading MPIs');
28246 }
28247 this.isEncrypted = false;
28248 this.keyMaterial = null;
28249 this.s2k_usage = 0;
28250 }
28251
28252 /**
28253 * Checks that the key parameters are consistent
28254 * @throws {Error} if validation was not successful
28255 * @async
28256 */
28257 async validate() {
28258 if (this.isDummy()) {
28259 return;
28260 }
28261
28262 if (!this.isDecrypted()) {
28263 throw new Error('Key is not decrypted');
28264 }
28265
28266 const algo = enums.write(enums.publicKey, this.algorithm);
28267
28268 let validParams;
28269 try {
28270 // this can throw if some parameters are undefined
28271 validParams = await mod.validateParams(algo, this.publicParams, this.privateParams);
28272 } catch (_) {
28273 validParams = false;
28274 }
28275 if (!validParams) {
28276 throw new Error('Key is invalid');
28277 }
28278 }
28279
28280 async generate(bits, curve) {
28281 const algo = enums.write(enums.publicKey, this.algorithm);
28282 const { privateParams, publicParams } = await mod.generateParams(algo, bits, curve);
28283 this.privateParams = privateParams;
28284 this.publicParams = publicParams;
28285 this.isEncrypted = false;
28286 }
28287
28288 /**
28289 * Clear private key parameters
28290 */
28291 clearPrivateParams() {
28292 if (this.isDummy()) {
28293 return;
28294 }
28295
28296 Object.keys(this.privateParams).forEach(name => {
28297 const param = this.privateParams[name];
28298 param.fill(0);
28299 delete this.privateParams[name];
28300 });
28301 this.privateParams = null;
28302 this.isEncrypted = true;
28303 }
28304}
28305
28306async function produceEncryptionKey(s2k, passphrase, algorithm) {
28307 return s2k.produce_key(
28308 passphrase,
28309 mod.cipher[algorithm].keySize
28310 );
28311}
28312
28313var emailAddresses = createCommonjsModule(function (module) {
28314// email-addresses.js - RFC 5322 email address parser
28315// v 3.1.0
28316//
28317// http://tools.ietf.org/html/rfc5322
28318//
28319// This library does not validate email addresses.
28320// emailAddresses attempts to parse addresses using the (fairly liberal)
28321// grammar specified in RFC 5322.
28322//
28323// email-addresses returns {
28324// ast: <an abstract syntax tree based on rfc5322>,
28325// addresses: [{
28326// node: <node in ast for this address>,
28327// name: <display-name>,
28328// address: <addr-spec>,
28329// local: <local-part>,
28330// domain: <domain>
28331// }, ...]
28332// }
28333//
28334// emailAddresses.parseOneAddress and emailAddresses.parseAddressList
28335// work as you might expect. Try it out.
28336//
28337// Many thanks to Dominic Sayers and his documentation on the is_email function,
28338// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
28339
28340(function (global) {
28341
28342function parse5322(opts) {
28343
28344 // tokenizing functions
28345
28346 function inStr() { return pos < len; }
28347 function curTok() { return parseString[pos]; }
28348 function getPos() { return pos; }
28349 function setPos(i) { pos = i; }
28350 function nextTok() { pos += 1; }
28351 function initialize() {
28352 pos = 0;
28353 len = parseString.length;
28354 }
28355
28356 // parser helper functions
28357
28358 function o(name, value) {
28359 return {
28360 name: name,
28361 tokens: value || "",
28362 semantic: value || "",
28363 children: []
28364 };
28365 }
28366
28367 function wrap(name, ast) {
28368 var n;
28369 if (ast === null) { return null; }
28370 n = o(name);
28371 n.tokens = ast.tokens;
28372 n.semantic = ast.semantic;
28373 n.children.push(ast);
28374 return n;
28375 }
28376
28377 function add(parent, child) {
28378 if (child !== null) {
28379 parent.tokens += child.tokens;
28380 parent.semantic += child.semantic;
28381 }
28382 parent.children.push(child);
28383 return parent;
28384 }
28385
28386 function compareToken(fxnCompare) {
28387 var tok;
28388 if (!inStr()) { return null; }
28389 tok = curTok();
28390 if (fxnCompare(tok)) {
28391 nextTok();
28392 return o('token', tok);
28393 }
28394 return null;
28395 }
28396
28397 function literal(lit) {
28398 return function literalFunc() {
28399 return wrap('literal', compareToken(function (tok) {
28400 return tok === lit;
28401 }));
28402 };
28403 }
28404
28405 function and() {
28406 var args = arguments;
28407 return function andFunc() {
28408 var i, s, result, start;
28409 start = getPos();
28410 s = o('and');
28411 for (i = 0; i < args.length; i += 1) {
28412 result = args[i]();
28413 if (result === null) {
28414 setPos(start);
28415 return null;
28416 }
28417 add(s, result);
28418 }
28419 return s;
28420 };
28421 }
28422
28423 function or() {
28424 var args = arguments;
28425 return function orFunc() {
28426 var i, result, start;
28427 start = getPos();
28428 for (i = 0; i < args.length; i += 1) {
28429 result = args[i]();
28430 if (result !== null) {
28431 return result;
28432 }
28433 setPos(start);
28434 }
28435 return null;
28436 };
28437 }
28438
28439 function opt(prod) {
28440 return function optFunc() {
28441 var result, start;
28442 start = getPos();
28443 result = prod();
28444 if (result !== null) {
28445 return result;
28446 }
28447 else {
28448 setPos(start);
28449 return o('opt');
28450 }
28451 };
28452 }
28453
28454 function invis(prod) {
28455 return function invisFunc() {
28456 var result = prod();
28457 if (result !== null) {
28458 result.semantic = "";
28459 }
28460 return result;
28461 };
28462 }
28463
28464 function colwsp(prod) {
28465 return function collapseSemanticWhitespace() {
28466 var result = prod();
28467 if (result !== null && result.semantic.length > 0) {
28468 result.semantic = " ";
28469 }
28470 return result;
28471 };
28472 }
28473
28474 function star(prod, minimum) {
28475 return function starFunc() {
28476 var s, result, count, start, min;
28477 start = getPos();
28478 s = o('star');
28479 count = 0;
28480 min = minimum === undefined ? 0 : minimum;
28481 while ((result = prod()) !== null) {
28482 count = count + 1;
28483 add(s, result);
28484 }
28485 if (count >= min) {
28486 return s;
28487 }
28488 else {
28489 setPos(start);
28490 return null;
28491 }
28492 };
28493 }
28494
28495 // One expects names to get normalized like this:
28496 // " First Last " -> "First Last"
28497 // "First Last" -> "First Last"
28498 // "First Last" -> "First Last"
28499 function collapseWhitespace(s) {
28500 return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
28501 }
28502
28503 // UTF-8 pseudo-production (RFC 6532)
28504 // RFC 6532 extends RFC 5322 productions to include UTF-8
28505 // using the following productions:
28506 // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
28507 // UTF8-2 = <Defined in Section 4 of RFC3629>
28508 // UTF8-3 = <Defined in Section 4 of RFC3629>
28509 // UTF8-4 = <Defined in Section 4 of RFC3629>
28510 //
28511 // For reference, the extended RFC 5322 productions are:
28512 // VCHAR =/ UTF8-non-ascii
28513 // ctext =/ UTF8-non-ascii
28514 // atext =/ UTF8-non-ascii
28515 // qtext =/ UTF8-non-ascii
28516 // dtext =/ UTF8-non-ascii
28517 function isUTF8NonAscii(tok) {
28518 // In JavaScript, we just deal directly with Unicode code points,
28519 // so we aren't checking individual bytes for UTF-8 encoding.
28520 // Just check that the character is non-ascii.
28521 return tok.charCodeAt(0) >= 128;
28522 }
28523
28524
28525 // common productions (RFC 5234)
28526 // http://tools.ietf.org/html/rfc5234
28527 // B.1. Core Rules
28528
28529 // CR = %x0D
28530 // ; carriage return
28531 function cr() { return wrap('cr', literal('\r')()); }
28532
28533 // CRLF = CR LF
28534 // ; Internet standard newline
28535 function crlf() { return wrap('crlf', and(cr, lf)()); }
28536
28537 // DQUOTE = %x22
28538 // ; " (Double Quote)
28539 function dquote() { return wrap('dquote', literal('"')()); }
28540
28541 // HTAB = %x09
28542 // ; horizontal tab
28543 function htab() { return wrap('htab', literal('\t')()); }
28544
28545 // LF = %x0A
28546 // ; linefeed
28547 function lf() { return wrap('lf', literal('\n')()); }
28548
28549 // SP = %x20
28550 function sp() { return wrap('sp', literal(' ')()); }
28551
28552 // VCHAR = %x21-7E
28553 // ; visible (printing) characters
28554 function vchar() {
28555 return wrap('vchar', compareToken(function vcharFunc(tok) {
28556 var code = tok.charCodeAt(0);
28557 var accept = (0x21 <= code && code <= 0x7E);
28558 if (opts.rfc6532) {
28559 accept = accept || isUTF8NonAscii(tok);
28560 }
28561 return accept;
28562 }));
28563 }
28564
28565 // WSP = SP / HTAB
28566 // ; white space
28567 function wsp() { return wrap('wsp', or(sp, htab)()); }
28568
28569
28570 // email productions (RFC 5322)
28571 // http://tools.ietf.org/html/rfc5322
28572 // 3.2.1. Quoted characters
28573
28574 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
28575 function quotedPair() {
28576 var qp = wrap('quoted-pair',
28577 or(
28578 and(literal('\\'), or(vchar, wsp)),
28579 obsQP
28580 )());
28581 if (qp === null) { return null; }
28582 // a quoted pair will be two characters, and the "\" character
28583 // should be semantically "invisible" (RFC 5322 3.2.1)
28584 qp.semantic = qp.semantic[1];
28585 return qp;
28586 }
28587
28588 // 3.2.2. Folding White Space and Comments
28589
28590 // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
28591 function fws() {
28592 return wrap('fws', or(
28593 obsFws,
28594 and(
28595 opt(and(
28596 star(wsp),
28597 invis(crlf)
28598 )),
28599 star(wsp, 1)
28600 )
28601 )());
28602 }
28603
28604 // ctext = %d33-39 / ; Printable US-ASCII
28605 // %d42-91 / ; characters not including
28606 // %d93-126 / ; "(", ")", or "\"
28607 // obs-ctext
28608 function ctext() {
28609 return wrap('ctext', or(
28610 function ctextFunc1() {
28611 return compareToken(function ctextFunc2(tok) {
28612 var code = tok.charCodeAt(0);
28613 var accept =
28614 (33 <= code && code <= 39) ||
28615 (42 <= code && code <= 91) ||
28616 (93 <= code && code <= 126);
28617 if (opts.rfc6532) {
28618 accept = accept || isUTF8NonAscii(tok);
28619 }
28620 return accept;
28621 });
28622 },
28623 obsCtext
28624 )());
28625 }
28626
28627 // ccontent = ctext / quoted-pair / comment
28628 function ccontent() {
28629 return wrap('ccontent', or(ctext, quotedPair, comment)());
28630 }
28631
28632 // comment = "(" *([FWS] ccontent) [FWS] ")"
28633 function comment() {
28634 return wrap('comment', and(
28635 literal('('),
28636 star(and(opt(fws), ccontent)),
28637 opt(fws),
28638 literal(')')
28639 )());
28640 }
28641
28642 // CFWS = (1*([FWS] comment) [FWS]) / FWS
28643 function cfws() {
28644 return wrap('cfws', or(
28645 and(
28646 star(
28647 and(opt(fws), comment),
28648 1
28649 ),
28650 opt(fws)
28651 ),
28652 fws
28653 )());
28654 }
28655
28656 // 3.2.3. Atom
28657
28658 //atext = ALPHA / DIGIT / ; Printable US-ASCII
28659 // "!" / "#" / ; characters not including
28660 // "$" / "%" / ; specials. Used for atoms.
28661 // "&" / "'" /
28662 // "*" / "+" /
28663 // "-" / "/" /
28664 // "=" / "?" /
28665 // "^" / "_" /
28666 // "`" / "{" /
28667 // "|" / "}" /
28668 // "~"
28669 function atext() {
28670 return wrap('atext', compareToken(function atextFunc(tok) {
28671 var accept =
28672 ('a' <= tok && tok <= 'z') ||
28673 ('A' <= tok && tok <= 'Z') ||
28674 ('0' <= tok && tok <= '9') ||
28675 (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
28676 '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
28677 if (opts.rfc6532) {
28678 accept = accept || isUTF8NonAscii(tok);
28679 }
28680 return accept;
28681 }));
28682 }
28683
28684 // atom = [CFWS] 1*atext [CFWS]
28685 function atom() {
28686 return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
28687 }
28688
28689 // dot-atom-text = 1*atext *("." 1*atext)
28690 function dotAtomText() {
28691 var s, maybeText;
28692 s = wrap('dot-atom-text', star(atext, 1)());
28693 if (s === null) { return s; }
28694 maybeText = star(and(literal('.'), star(atext, 1)))();
28695 if (maybeText !== null) {
28696 add(s, maybeText);
28697 }
28698 return s;
28699 }
28700
28701 // dot-atom = [CFWS] dot-atom-text [CFWS]
28702 function dotAtom() {
28703 return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
28704 }
28705
28706 // 3.2.4. Quoted Strings
28707
28708 // qtext = %d33 / ; Printable US-ASCII
28709 // %d35-91 / ; characters not including
28710 // %d93-126 / ; "\" or the quote character
28711 // obs-qtext
28712 function qtext() {
28713 return wrap('qtext', or(
28714 function qtextFunc1() {
28715 return compareToken(function qtextFunc2(tok) {
28716 var code = tok.charCodeAt(0);
28717 var accept =
28718 (33 === code) ||
28719 (35 <= code && code <= 91) ||
28720 (93 <= code && code <= 126);
28721 if (opts.rfc6532) {
28722 accept = accept || isUTF8NonAscii(tok);
28723 }
28724 return accept;
28725 });
28726 },
28727 obsQtext
28728 )());
28729 }
28730
28731 // qcontent = qtext / quoted-pair
28732 function qcontent() {
28733 return wrap('qcontent', or(qtext, quotedPair)());
28734 }
28735
28736 // quoted-string = [CFWS]
28737 // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
28738 // [CFWS]
28739 function quotedString() {
28740 return wrap('quoted-string', and(
28741 invis(opt(cfws)),
28742 invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
28743 invis(opt(cfws))
28744 )());
28745 }
28746
28747 // 3.2.5 Miscellaneous Tokens
28748
28749 // word = atom / quoted-string
28750 function word() {
28751 return wrap('word', or(atom, quotedString)());
28752 }
28753
28754 // phrase = 1*word / obs-phrase
28755 function phrase() {
28756 return wrap('phrase', or(obsPhrase, star(word, 1))());
28757 }
28758
28759 // 3.4. Address Specification
28760 // address = mailbox / group
28761 function address() {
28762 return wrap('address', or(mailbox, group)());
28763 }
28764
28765 // mailbox = name-addr / addr-spec
28766 function mailbox() {
28767 return wrap('mailbox', or(nameAddr, addrSpec)());
28768 }
28769
28770 // name-addr = [display-name] angle-addr
28771 function nameAddr() {
28772 return wrap('name-addr', and(opt(displayName), angleAddr)());
28773 }
28774
28775 // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
28776 // obs-angle-addr
28777 function angleAddr() {
28778 return wrap('angle-addr', or(
28779 and(
28780 invis(opt(cfws)),
28781 literal('<'),
28782 addrSpec,
28783 literal('>'),
28784 invis(opt(cfws))
28785 ),
28786 obsAngleAddr
28787 )());
28788 }
28789
28790 // group = display-name ":" [group-list] ";" [CFWS]
28791 function group() {
28792 return wrap('group', and(
28793 displayName,
28794 literal(':'),
28795 opt(groupList),
28796 literal(';'),
28797 invis(opt(cfws))
28798 )());
28799 }
28800
28801 // display-name = phrase
28802 function displayName() {
28803 return wrap('display-name', function phraseFixedSemantic() {
28804 var result = phrase();
28805 if (result !== null) {
28806 result.semantic = collapseWhitespace(result.semantic);
28807 }
28808 return result;
28809 }());
28810 }
28811
28812 // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
28813 function mailboxList() {
28814 return wrap('mailbox-list', or(
28815 and(
28816 mailbox,
28817 star(and(literal(','), mailbox))
28818 ),
28819 obsMboxList
28820 )());
28821 }
28822
28823 // address-list = (address *("," address)) / obs-addr-list
28824 function addressList() {
28825 return wrap('address-list', or(
28826 and(
28827 address,
28828 star(and(literal(','), address))
28829 ),
28830 obsAddrList
28831 )());
28832 }
28833
28834 // group-list = mailbox-list / CFWS / obs-group-list
28835 function groupList() {
28836 return wrap('group-list', or(
28837 mailboxList,
28838 invis(cfws),
28839 obsGroupList
28840 )());
28841 }
28842
28843 // 3.4.1 Addr-Spec Specification
28844
28845 // local-part = dot-atom / quoted-string / obs-local-part
28846 function localPart() {
28847 // note: quoted-string, dotAtom are proper subsets of obs-local-part
28848 // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
28849 return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
28850 }
28851
28852 // dtext = %d33-90 / ; Printable US-ASCII
28853 // %d94-126 / ; characters not including
28854 // obs-dtext ; "[", "]", or "\"
28855 function dtext() {
28856 return wrap('dtext', or(
28857 function dtextFunc1() {
28858 return compareToken(function dtextFunc2(tok) {
28859 var code = tok.charCodeAt(0);
28860 var accept =
28861 (33 <= code && code <= 90) ||
28862 (94 <= code && code <= 126);
28863 if (opts.rfc6532) {
28864 accept = accept || isUTF8NonAscii(tok);
28865 }
28866 return accept;
28867 });
28868 },
28869 obsDtext
28870 )()
28871 );
28872 }
28873
28874 // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
28875 function domainLiteral() {
28876 return wrap('domain-literal', and(
28877 invis(opt(cfws)),
28878 literal('['),
28879 star(and(opt(fws), dtext)),
28880 opt(fws),
28881 literal(']'),
28882 invis(opt(cfws))
28883 )());
28884 }
28885
28886 // domain = dot-atom / domain-literal / obs-domain
28887 function domain() {
28888 return wrap('domain', function domainCheckTLD() {
28889 var result = or(obsDomain, dotAtom, domainLiteral)();
28890 if (opts.rejectTLD) {
28891 if (result && result.semantic && result.semantic.indexOf('.') < 0) {
28892 return null;
28893 }
28894 }
28895 // strip all whitespace from domains
28896 if (result) {
28897 result.semantic = result.semantic.replace(/\s+/g, '');
28898 }
28899 return result;
28900 }());
28901 }
28902
28903 // addr-spec = local-part "@" domain
28904 function addrSpec() {
28905 return wrap('addr-spec', and(
28906 localPart, literal('@'), domain
28907 )());
28908 }
28909
28910 // 3.6.2 Originator Fields
28911 // Below we only parse the field body, not the name of the field
28912 // like "From:", "Sender:", or "Reply-To:". Other libraries that
28913 // parse email headers can parse those and defer to these productions
28914 // for the "RFC 5322" part.
28915
28916 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
28917 // from = "From:" (mailbox-list / address-list) CRLF
28918 function fromSpec() {
28919 return wrap('from', or(
28920 mailboxList,
28921 addressList
28922 )());
28923 }
28924
28925 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
28926 // sender = "Sender:" (mailbox / address) CRLF
28927 function senderSpec() {
28928 return wrap('sender', or(
28929 mailbox,
28930 address
28931 )());
28932 }
28933
28934 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
28935 // reply-to = "Reply-To:" address-list CRLF
28936 function replyToSpec() {
28937 return wrap('reply-to', addressList());
28938 }
28939
28940 // 4.1. Miscellaneous Obsolete Tokens
28941
28942 // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
28943 // %d11 / ; characters that do not
28944 // %d12 / ; include the carriage
28945 // %d14-31 / ; return, line feed, and
28946 // %d127 ; white space characters
28947 function obsNoWsCtl() {
28948 return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
28949 var code = tok.charCodeAt(0);
28950 return ((1 <= code && code <= 8) ||
28951 (11 === code || 12 === code) ||
28952 (14 <= code && code <= 31) ||
28953 (127 === code));
28954 }));
28955 }
28956
28957 // obs-ctext = obs-NO-WS-CTL
28958 function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
28959
28960 // obs-qtext = obs-NO-WS-CTL
28961 function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
28962
28963 // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
28964 function obsQP() {
28965 return opts.strict ? null : wrap('obs-qp', and(
28966 literal('\\'),
28967 or(literal('\0'), obsNoWsCtl, lf, cr)
28968 )());
28969 }
28970
28971 // obs-phrase = word *(word / "." / CFWS)
28972 function obsPhrase() {
28973 if (opts.strict ) return null;
28974 return opts.atInDisplayName ? wrap('obs-phrase', and(
28975 word,
28976 star(or(word, literal('.'), literal('@'), colwsp(cfws)))
28977 )()) :
28978 wrap('obs-phrase', and(
28979 word,
28980 star(or(word, literal('.'), colwsp(cfws)))
28981 )());
28982 }
28983
28984 // 4.2. Obsolete Folding White Space
28985
28986 // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
28987 // obs-FWS = 1*([CRLF] WSP)
28988 function obsFws() {
28989 return opts.strict ? null : wrap('obs-FWS', star(
28990 and(invis(opt(crlf)), wsp),
28991 1
28992 )());
28993 }
28994
28995 // 4.4. Obsolete Addressing
28996
28997 // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
28998 function obsAngleAddr() {
28999 return opts.strict ? null : wrap('obs-angle-addr', and(
29000 invis(opt(cfws)),
29001 literal('<'),
29002 obsRoute,
29003 addrSpec,
29004 literal('>'),
29005 invis(opt(cfws))
29006 )());
29007 }
29008
29009 // obs-route = obs-domain-list ":"
29010 function obsRoute() {
29011 return opts.strict ? null : wrap('obs-route', and(
29012 obsDomainList,
29013 literal(':')
29014 )());
29015 }
29016
29017 // obs-domain-list = *(CFWS / ",") "@" domain
29018 // *("," [CFWS] ["@" domain])
29019 function obsDomainList() {
29020 return opts.strict ? null : wrap('obs-domain-list', and(
29021 star(or(invis(cfws), literal(','))),
29022 literal('@'),
29023 domain,
29024 star(and(
29025 literal(','),
29026 invis(opt(cfws)),
29027 opt(and(literal('@'), domain))
29028 ))
29029 )());
29030 }
29031
29032 // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
29033 function obsMboxList() {
29034 return opts.strict ? null : wrap('obs-mbox-list', and(
29035 star(and(
29036 invis(opt(cfws)),
29037 literal(',')
29038 )),
29039 mailbox,
29040 star(and(
29041 literal(','),
29042 opt(and(
29043 mailbox,
29044 invis(cfws)
29045 ))
29046 ))
29047 )());
29048 }
29049
29050 // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
29051 function obsAddrList() {
29052 return opts.strict ? null : wrap('obs-addr-list', and(
29053 star(and(
29054 invis(opt(cfws)),
29055 literal(',')
29056 )),
29057 address,
29058 star(and(
29059 literal(','),
29060 opt(and(
29061 address,
29062 invis(cfws)
29063 ))
29064 ))
29065 )());
29066 }
29067
29068 // obs-group-list = 1*([CFWS] ",") [CFWS]
29069 function obsGroupList() {
29070 return opts.strict ? null : wrap('obs-group-list', and(
29071 star(and(
29072 invis(opt(cfws)),
29073 literal(',')
29074 ), 1),
29075 invis(opt(cfws))
29076 )());
29077 }
29078
29079 // obs-local-part = word *("." word)
29080 function obsLocalPart() {
29081 return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
29082 }
29083
29084 // obs-domain = atom *("." atom)
29085 function obsDomain() {
29086 return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
29087 }
29088
29089 // obs-dtext = obs-NO-WS-CTL / quoted-pair
29090 function obsDtext() {
29091 return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
29092 }
29093
29094 /////////////////////////////////////////////////////
29095
29096 // ast analysis
29097
29098 function findNode(name, root) {
29099 var i, stack, node;
29100 if (root === null || root === undefined) { return null; }
29101 stack = [root];
29102 while (stack.length > 0) {
29103 node = stack.pop();
29104 if (node.name === name) {
29105 return node;
29106 }
29107 for (i = node.children.length - 1; i >= 0; i -= 1) {
29108 stack.push(node.children[i]);
29109 }
29110 }
29111 return null;
29112 }
29113
29114 function findAllNodes(name, root) {
29115 var i, stack, node, result;
29116 if (root === null || root === undefined) { return null; }
29117 stack = [root];
29118 result = [];
29119 while (stack.length > 0) {
29120 node = stack.pop();
29121 if (node.name === name) {
29122 result.push(node);
29123 }
29124 for (i = node.children.length - 1; i >= 0; i -= 1) {
29125 stack.push(node.children[i]);
29126 }
29127 }
29128 return result;
29129 }
29130
29131 function findAllNodesNoChildren(names, root) {
29132 var i, stack, node, result, namesLookup;
29133 if (root === null || root === undefined) { return null; }
29134 stack = [root];
29135 result = [];
29136 namesLookup = {};
29137 for (i = 0; i < names.length; i += 1) {
29138 namesLookup[names[i]] = true;
29139 }
29140
29141 while (stack.length > 0) {
29142 node = stack.pop();
29143 if (node.name in namesLookup) {
29144 result.push(node);
29145 // don't look at children (hence findAllNodesNoChildren)
29146 } else {
29147 for (i = node.children.length - 1; i >= 0; i -= 1) {
29148 stack.push(node.children[i]);
29149 }
29150 }
29151 }
29152 return result;
29153 }
29154
29155 function giveResult(ast) {
29156 var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
29157 if (ast === null) {
29158 return null;
29159 }
29160 addresses = [];
29161
29162 // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
29163 groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
29164 for (i = 0; i < groupsAndMailboxes.length; i += 1) {
29165 groupOrMailbox = groupsAndMailboxes[i];
29166 if (groupOrMailbox.name === 'group') {
29167 addresses.push(giveResultGroup(groupOrMailbox));
29168 } else if (groupOrMailbox.name === 'mailbox') {
29169 addresses.push(giveResultMailbox(groupOrMailbox));
29170 }
29171 }
29172
29173 result = {
29174 ast: ast,
29175 addresses: addresses,
29176 };
29177 if (opts.simple) {
29178 result = simplifyResult(result);
29179 }
29180 if (opts.oneResult) {
29181 return oneResult(result);
29182 }
29183 if (opts.simple) {
29184 return result && result.addresses;
29185 } else {
29186 return result;
29187 }
29188 }
29189
29190 function giveResultGroup(group) {
29191 var i;
29192 var groupName = findNode('display-name', group);
29193 var groupResultMailboxes = [];
29194 var mailboxes = findAllNodesNoChildren(['mailbox'], group);
29195 for (i = 0; i < mailboxes.length; i += 1) {
29196 groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
29197 }
29198 return {
29199 node: group,
29200 parts: {
29201 name: groupName,
29202 },
29203 type: group.name, // 'group'
29204 name: grabSemantic(groupName),
29205 addresses: groupResultMailboxes,
29206 };
29207 }
29208
29209 function giveResultMailbox(mailbox) {
29210 var name = findNode('display-name', mailbox);
29211 var aspec = findNode('addr-spec', mailbox);
29212 var cfws = findAllNodes('cfws', mailbox);
29213 var comments = findAllNodesNoChildren(['comment'], mailbox);
29214
29215
29216 var local = findNode('local-part', aspec);
29217 var domain = findNode('domain', aspec);
29218 return {
29219 node: mailbox,
29220 parts: {
29221 name: name,
29222 address: aspec,
29223 local: local,
29224 domain: domain,
29225 comments: cfws
29226 },
29227 type: mailbox.name, // 'mailbox'
29228 name: grabSemantic(name),
29229 address: grabSemantic(aspec),
29230 local: grabSemantic(local),
29231 domain: grabSemantic(domain),
29232 comments: concatComments(comments),
29233 groupName: grabSemantic(mailbox.groupName),
29234 };
29235 }
29236
29237 function grabSemantic(n) {
29238 return n !== null && n !== undefined ? n.semantic : null;
29239 }
29240
29241 function simplifyResult(result) {
29242 var i;
29243 if (result && result.addresses) {
29244 for (i = 0; i < result.addresses.length; i += 1) {
29245 delete result.addresses[i].node;
29246 }
29247 }
29248 return result;
29249 }
29250
29251 function concatComments(comments) {
29252 var result = '';
29253 if (comments) {
29254 for (var i = 0; i < comments.length; i += 1) {
29255 result += grabSemantic(comments[i]);
29256 }
29257 }
29258 return result;
29259 }
29260
29261 function oneResult(result) {
29262 if (!result) { return null; }
29263 if (!opts.partial && result.addresses.length > 1) { return null; }
29264 return result.addresses && result.addresses[0];
29265 }
29266
29267 /////////////////////////////////////////////////////
29268
29269 var parseString, pos, len, parsed, startProduction;
29270
29271 opts = handleOpts(opts, {});
29272 if (opts === null) { return null; }
29273
29274 parseString = opts.input;
29275
29276 startProduction = {
29277 'address': address,
29278 'address-list': addressList,
29279 'angle-addr': angleAddr,
29280 'from': fromSpec,
29281 'group': group,
29282 'mailbox': mailbox,
29283 'mailbox-list': mailboxList,
29284 'reply-to': replyToSpec,
29285 'sender': senderSpec,
29286 }[opts.startAt] || addressList;
29287
29288 if (!opts.strict) {
29289 initialize();
29290 opts.strict = true;
29291 parsed = startProduction(parseString);
29292 if (opts.partial || !inStr()) {
29293 return giveResult(parsed);
29294 }
29295 opts.strict = false;
29296 }
29297
29298 initialize();
29299 parsed = startProduction(parseString);
29300 if (!opts.partial && inStr()) { return null; }
29301 return giveResult(parsed);
29302}
29303
29304function parseOneAddressSimple(opts) {
29305 return parse5322(handleOpts(opts, {
29306 oneResult: true,
29307 rfc6532: true,
29308 simple: true,
29309 startAt: 'address-list',
29310 }));
29311}
29312
29313function parseAddressListSimple(opts) {
29314 return parse5322(handleOpts(opts, {
29315 rfc6532: true,
29316 simple: true,
29317 startAt: 'address-list',
29318 }));
29319}
29320
29321function parseFromSimple(opts) {
29322 return parse5322(handleOpts(opts, {
29323 rfc6532: true,
29324 simple: true,
29325 startAt: 'from',
29326 }));
29327}
29328
29329function parseSenderSimple(opts) {
29330 return parse5322(handleOpts(opts, {
29331 oneResult: true,
29332 rfc6532: true,
29333 simple: true,
29334 startAt: 'sender',
29335 }));
29336}
29337
29338function parseReplyToSimple(opts) {
29339 return parse5322(handleOpts(opts, {
29340 rfc6532: true,
29341 simple: true,
29342 startAt: 'reply-to',
29343 }));
29344}
29345
29346function handleOpts(opts, defs) {
29347 function isString(str) {
29348 return Object.prototype.toString.call(str) === '[object String]';
29349 }
29350
29351 function isObject(o) {
29352 return o === Object(o);
29353 }
29354
29355 function isNullUndef(o) {
29356 return o === null || o === undefined;
29357 }
29358
29359 var defaults, o;
29360
29361 if (isString(opts)) {
29362 opts = { input: opts };
29363 } else if (!isObject(opts)) {
29364 return null;
29365 }
29366
29367 if (!isString(opts.input)) { return null; }
29368 if (!defs) { return null; }
29369
29370 defaults = {
29371 oneResult: false,
29372 partial: false,
29373 rejectTLD: false,
29374 rfc6532: false,
29375 simple: false,
29376 startAt: 'address-list',
29377 strict: false,
29378 atInDisplayName: false
29379 };
29380
29381 for (o in defaults) {
29382 if (isNullUndef(opts[o])) {
29383 opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
29384 }
29385 }
29386 return opts;
29387}
29388
29389parse5322.parseOneAddress = parseOneAddressSimple;
29390parse5322.parseAddressList = parseAddressListSimple;
29391parse5322.parseFrom = parseFromSimple;
29392parse5322.parseSender = parseSenderSimple;
29393parse5322.parseReplyTo = parseReplyToSimple;
29394
29395{
29396 module.exports = parse5322;
29397}
29398
29399}());
29400});
29401
29402// GPG4Browsers - An OpenPGP implementation in javascript
29403
29404/**
29405 * Implementation of the User ID Packet (Tag 13)
29406 *
29407 * A User ID packet consists of UTF-8 text that is intended to represent
29408 * the name and email address of the key holder. By convention, it
29409 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
29410 * restrictions on its content. The packet length in the header
29411 * specifies the length of the User ID.
29412 */
29413class UserIDPacket {
29414 constructor() {
29415 this.tag = enums.packet.userID;
29416 /** A string containing the user id. Usually in the form
29417 * John Doe <john@example.com>
29418 * @type {String}
29419 */
29420 this.userid = '';
29421
29422 this.name = '';
29423 this.email = '';
29424 this.comment = '';
29425 }
29426
29427 /**
29428 * Create UserIDPacket instance from object
29429 * @param {Object} userId - Object specifying userId name, email and comment
29430 * @returns {UserIDPacket}
29431 * @static
29432 */
29433 static fromObject(userId) {
29434 if (util.isString(userId) ||
29435 (userId.name && !util.isString(userId.name)) ||
29436 (userId.email && !util.isEmailAddress(userId.email)) ||
29437 (userId.comment && !util.isString(userId.comment))) {
29438 throw new Error('Invalid user ID format');
29439 }
29440 const packet = new UserIDPacket();
29441 Object.assign(packet, userId);
29442 const components = [];
29443 if (packet.name) components.push(packet.name);
29444 if (packet.comment) components.push(`(${packet.comment})`);
29445 if (packet.email) components.push(`<${packet.email}>`);
29446 packet.userid = components.join(' ');
29447 return packet;
29448 }
29449
29450 /**
29451 * Parsing function for a user id packet (tag 13).
29452 * @param {Uint8Array} input - Payload of a tag 13 packet
29453 */
29454 read(bytes, config = defaultConfig) {
29455 const userid = util.decodeUtf8(bytes);
29456 if (userid.length > config.maxUseridLength) {
29457 throw new Error('User ID string is too long');
29458 }
29459 try {
29460 const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userid, atInDisplayName: true });
29461 this.comment = comments.replace(/^\(|\)$/g, '');
29462 this.name = name;
29463 this.email = email;
29464 } catch (e) {}
29465 this.userid = userid;
29466 }
29467
29468 /**
29469 * Creates a binary representation of the user id packet
29470 * @returns {Uint8Array} Binary representation.
29471 */
29472 write() {
29473 return util.encodeUtf8(this.userid);
29474 }
29475}
29476
29477// GPG4Browsers - An OpenPGP implementation in javascript
29478
29479/**
29480 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
29481 * Key packet and has exactly the same format.
29482 * @extends SecretKeyPacket
29483 */
29484class SecretSubkeyPacket extends SecretKeyPacket {
29485 /**
29486 * @param {Date} [date] - Creation date
29487 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29488 */
29489 constructor(date = new Date(), config = defaultConfig) {
29490 super(date, config);
29491 this.tag = enums.packet.secretSubkey;
29492 }
29493}
29494
29495/* eslint class-methods-use-this: ["error", { "exceptMethods": ["read"] }] */
29496
29497/**
29498 * Implementation of the Trust Packet (Tag 12)
29499 *
29500 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
29501 * The Trust packet is used only within keyrings and is not normally
29502 * exported. Trust packets contain data that record the user's
29503 * specifications of which key holders are trustworthy introducers,
29504 * along with other information that implementing software uses for
29505 * trust information. The format of Trust packets is defined by a given
29506 * implementation.
29507 *
29508 * Trust packets SHOULD NOT be emitted to output streams that are
29509 * transferred to other users, and they SHOULD be ignored on any input
29510 * other than local keyring files.
29511 */
29512class TrustPacket {
29513 constructor() {
29514 this.tag = enums.packet.trust;
29515 }
29516
29517 /**
29518 * Parsing function for a trust packet (tag 12).
29519 * Currently not implemented as we ignore trust packets
29520 * @param {String} byptes - Payload of a tag 12 packet
29521 */
29522 read() {} // TODO
29523}
29524
29525/**
29526 * @fileoverview Exports all OpenPGP packet types
29527 * @module packet/all_packets
29528 * @private
29529 */
29530
29531/**
29532 * Allocate a new packet
29533 * @function newPacketFromTag
29534 * @param {String} tag - Property name from {@link module:enums.packet}
29535 * @returns {Object} New packet object with type based on tag.
29536 */
29537function newPacketFromTag(tag, allowedPackets) {
29538 const className = packetClassFromTagName(tag);
29539 if (!allowedPackets[className]) {
29540 throw new Error('Packet not allowed in this context: ' + className);
29541 }
29542 return new allowedPackets[className]();
29543}
29544
29545/**
29546 * Convert tag name to class name
29547 * @param {String} tag - Property name from {@link module:enums.packet}
29548 * @returns {String}
29549 * @private
29550 */
29551function packetClassFromTagName(tag) {
29552 return tag.substr(0, 1).toUpperCase() + tag.substr(1) + 'Packet';
29553}
29554
29555/**
29556 * This class represents a list of openpgp packets.
29557 * Take care when iterating over it - the packets themselves
29558 * are stored as numerical indices.
29559 * @extends Array
29560 */
29561class PacketList extends Array {
29562 /**
29563 * Reads a stream of binary data and interprets it as a list of packets.
29564 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - A Uint8Array of bytes.
29565 */
29566 async read(bytes, allowedPackets, streaming, config = defaultConfig) {
29567 this.stream = stream.transformPair(bytes, async (readable, writable) => {
29568 const writer = stream.getWriter(writable);
29569 try {
29570 while (true) {
29571 await writer.ready;
29572 const done = await readPackets(readable, streaming, async parsed => {
29573 try {
29574 const tag = enums.read(enums.packet, parsed.tag);
29575 const packet = newPacketFromTag(tag, allowedPackets);
29576 packet.packets = new PacketList();
29577 packet.fromStream = util.isStream(parsed.packet);
29578 await packet.read(parsed.packet, config, streaming);
29579 await writer.write(packet);
29580 } catch (e) {
29581 if (!config.tolerant || supportsStreaming(parsed.tag)) {
29582 // The packets that support streaming are the ones that contain
29583 // message data. Those are also the ones we want to be more strict
29584 // about and throw on parse errors for.
29585 await writer.abort(e);
29586 }
29587 util.printDebugError(e);
29588 }
29589 });
29590 if (done) {
29591 await writer.ready;
29592 await writer.close();
29593 return;
29594 }
29595 }
29596 } catch (e) {
29597 await writer.abort(e);
29598 }
29599 });
29600
29601 // Wait until first few packets have been read
29602 const reader = stream.getReader(this.stream);
29603 while (true) {
29604 const { done, value } = await reader.read();
29605 if (!done) {
29606 this.push(value);
29607 } else {
29608 this.stream = null;
29609 }
29610 if (done || supportsStreaming(value.tag)) {
29611 break;
29612 }
29613 }
29614 reader.releaseLock();
29615 }
29616
29617 /**
29618 * Creates a binary representation of openpgp objects contained within the
29619 * class instance.
29620 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
29621 */
29622 write() {
29623 const arr = [];
29624
29625 for (let i = 0; i < this.length; i++) {
29626 const packetbytes = this[i].write();
29627 if (util.isStream(packetbytes) && supportsStreaming(this[i].tag)) {
29628 let buffer = [];
29629 let bufferLength = 0;
29630 const minLength = 512;
29631 arr.push(writeTag(this[i].tag));
29632 arr.push(stream.transform(packetbytes, value => {
29633 buffer.push(value);
29634 bufferLength += value.length;
29635 if (bufferLength >= minLength) {
29636 const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
29637 const chunkSize = 2 ** powerOf2;
29638 const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
29639 buffer = [bufferConcat.subarray(1 + chunkSize)];
29640 bufferLength = buffer[0].length;
29641 return bufferConcat.subarray(0, 1 + chunkSize);
29642 }
29643 }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
29644 } else {
29645 if (util.isStream(packetbytes)) {
29646 let length = 0;
29647 arr.push(stream.transform(stream.clone(packetbytes), value => {
29648 length += value.length;
29649 }, () => writeHeader(this[i].tag, length)));
29650 } else {
29651 arr.push(writeHeader(this[i].tag, packetbytes.length));
29652 }
29653 arr.push(packetbytes);
29654 }
29655 }
29656
29657 return util.concat(arr);
29658 }
29659
29660 /**
29661 * Adds a packet to the list. This is the only supported method of doing so;
29662 * writing to packetlist[i] directly will result in an error.
29663 * @param {Object} packet - Packet to push
29664 */
29665 push(packet) {
29666 if (!packet) {
29667 return;
29668 }
29669
29670 packet.packets = packet.packets || new PacketList();
29671
29672 super.push(packet);
29673 }
29674
29675 /**
29676 * Creates a new PacketList with all packets from the given types
29677 */
29678 filterByTag(...args) {
29679 const filtered = new PacketList();
29680
29681 const handle = tag => packetType => tag === packetType;
29682
29683 for (let i = 0; i < this.length; i++) {
29684 if (args.some(handle(this[i].tag))) {
29685 filtered.push(this[i]);
29686 }
29687 }
29688
29689 return filtered;
29690 }
29691
29692 /**
29693 * Traverses packet tree and returns first matching packet
29694 * @param {module:enums.packet} type - The packet type
29695 * @returns {Packet|undefined}
29696 */
29697 findPacket(type) {
29698 return this.find(packet => packet.tag === type);
29699 }
29700
29701 /**
29702 * Returns array of found indices by tag
29703 */
29704 indexOfTag(...args) {
29705 const tagIndex = [];
29706 const that = this;
29707
29708 const handle = tag => packetType => tag === packetType;
29709
29710 for (let i = 0; i < this.length; i++) {
29711 if (args.some(handle(that[i].tag))) {
29712 tagIndex.push(i);
29713 }
29714 }
29715 return tagIndex;
29716 }
29717
29718 /**
29719 * Concatenates packetlist or array of packets
29720 */
29721 concat(packetlist) {
29722 if (packetlist) {
29723 for (let i = 0; i < packetlist.length; i++) {
29724 this.push(packetlist[i]);
29725 }
29726 }
29727 return this;
29728 }
29729}
29730
29731// GPG4Browsers - An OpenPGP implementation in javascript
29732
29733/**
29734 * Class that represents an OpenPGP signature.
29735 */
29736class Signature {
29737 /**
29738 * @param {PacketList} packetlist - The signature packets
29739 */
29740 constructor(packetlist) {
29741 this.packets = packetlist || new PacketList();
29742 }
29743
29744 /**
29745 * Returns binary encoded signature
29746 * @returns {ReadableStream<Uint8Array>} Binary signature.
29747 */
29748 write() {
29749 return this.packets.write();
29750 }
29751
29752 /**
29753 * Returns ASCII armored text of signature
29754 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29755 * @returns {ReadableStream<String>} ASCII armor.
29756 */
29757 armor(config = defaultConfig) {
29758 return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);
29759 }
29760}
29761
29762/**
29763 * reads an (optionally armored) OpenPGP signature and returns a signature object
29764 * @param {Object} options
29765 * @param {String | ReadableStream<String>} [options.armoredSignature] - Armored signature to be parsed
29766 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binarySignature] - Binary signature to be parsed
29767 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29768 * @returns {Signature} New signature object.
29769 * @async
29770 * @static
29771 */
29772async function readSignature({ armoredSignature, binarySignature, config }) {
29773 config = { ...defaultConfig, ...config };
29774 let input = armoredSignature || binarySignature;
29775 if (!input) {
29776 throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
29777 }
29778 if (armoredSignature) {
29779 const { type, data } = await unarmor(input, config);
29780 if (type !== enums.armor.signature) {
29781 throw new Error('Armored text not of type signature');
29782 }
29783 input = data;
29784 }
29785 const packetlist = new PacketList();
29786 await packetlist.read(input, { SignaturePacket }, undefined, config);
29787 return new Signature(packetlist);
29788}
29789
29790/**
29791 * @fileoverview Provides helpers methods for key module
29792 * @module key/helper
29793 * @private
29794 */
29795
29796const allowedKeyPackets = {
29797 PublicKeyPacket,
29798 PublicSubkeyPacket,
29799 SecretKeyPacket,
29800 SecretSubkeyPacket,
29801 UserIDPacket,
29802 UserAttributePacket,
29803 SignaturePacket
29804};
29805
29806async function generateSecretSubkey(options, config) {
29807 const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
29808 secretSubkeyPacket.packets = null;
29809 secretSubkeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm);
29810 await secretSubkeyPacket.generate(options.rsaBits, options.curve);
29811 return secretSubkeyPacket;
29812}
29813
29814async function generateSecretKey(options, config) {
29815 const secretKeyPacket = new SecretKeyPacket(options.date, config);
29816 secretKeyPacket.packets = null;
29817 secretKeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm);
29818 await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
29819 return secretKeyPacket;
29820}
29821
29822/**
29823 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
29824 * @param {Array<SignaturePacket>} signatures - List of signatures
29825 * @param {Date} date - Use the given date instead of the current time
29826 * @param {Object} config - full configuration
29827 * @returns {SignaturePacket} The latest valid signature.
29828 * @async
29829 */
29830async function getLatestValidSignature(signatures, primaryKey, signatureType, dataToVerify, date = new Date(), config) {
29831 let signature;
29832 let exception;
29833 for (let i = signatures.length - 1; i >= 0; i--) {
29834 try {
29835 if (
29836 (!signature || signatures[i].created >= signature.created) &&
29837 // check binding signature is not expired (ie, check for V4 expiration time)
29838 !signatures[i].isExpired(date)
29839 ) {
29840 // check binding signature is verified
29841 signatures[i].verified || await signatures[i].verify(primaryKey, signatureType, dataToVerify, undefined, undefined, config);
29842 signature = signatures[i];
29843 }
29844 } catch (e) {
29845 exception = e;
29846 }
29847 }
29848 if (!signature) {
29849 throw util.wrapError(
29850 `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${primaryKey.getKeyId().toHex()}`
29851 .replace('certGeneric ', 'self-')
29852 .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase())
29853 , exception);
29854 }
29855 return signature;
29856}
29857
29858function isDataExpired(keyPacket, signature, date = new Date()) {
29859 const normDate = util.normalizeDate(date);
29860 if (normDate !== null) {
29861 const expirationTime = getExpirationTime(keyPacket, signature);
29862 return !(keyPacket.created <= normDate && normDate <= expirationTime) ||
29863 (signature && signature.isExpired(date));
29864 }
29865 return false;
29866}
29867
29868/**
29869 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
29870 * @param {SecretSubkeyPacket} subkey - Subkey key packet
29871 * @param {SecretKeyPacket} primaryKey - Primary key packet
29872 * @param {Object} options
29873 * @param {Object} config - Full configuration
29874 */
29875async function createBindingSignature(subkey, primaryKey, options, config) {
29876 const dataToSign = {};
29877 dataToSign.key = primaryKey;
29878 dataToSign.bind = subkey;
29879 const subkeySignaturePacket = new SignaturePacket(options.date);
29880 subkeySignaturePacket.signatureType = enums.signature.subkeyBinding;
29881 subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm;
29882 subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, subkey, undefined, undefined, config);
29883 if (options.sign) {
29884 subkeySignaturePacket.keyFlags = [enums.keyFlags.signData];
29885 subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
29886 signatureType: enums.signature.keyBinding
29887 }, options.date, undefined, undefined, undefined, config);
29888 } else {
29889 subkeySignaturePacket.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
29890 }
29891 if (options.keyExpirationTime > 0) {
29892 subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime;
29893 subkeySignaturePacket.keyNeverExpires = false;
29894 }
29895 await subkeySignaturePacket.sign(primaryKey, dataToSign);
29896 return subkeySignaturePacket;
29897}
29898
29899/**
29900 * Returns the preferred signature hash algorithm of a key
29901 * @param {Key} [key] - The key to get preferences from
29902 * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing
29903 * @param {Date} [date] - Use the given date for verification instead of the current time
29904 * @param {Object} [userId] - User ID
29905 * @param {Object} config - full configuration
29906 * @returns {String}
29907 * @async
29908 */
29909async function getPreferredHashAlgo$1(key, keyPacket, date = new Date(), userId = {}, config) {
29910 let hash_algo = config.preferHashAlgorithm;
29911 let pref_algo = hash_algo;
29912 if (key) {
29913 const primaryUser = await key.getPrimaryUser(date, userId, config);
29914 if (primaryUser.selfCertification.preferredHashAlgorithms) {
29915 [pref_algo] = primaryUser.selfCertification.preferredHashAlgorithms;
29916 hash_algo = mod.hash.getHashByteLength(hash_algo) <= mod.hash.getHashByteLength(pref_algo) ?
29917 pref_algo : hash_algo;
29918 }
29919 }
29920 switch (Object.getPrototypeOf(keyPacket)) {
29921 case SecretKeyPacket.prototype:
29922 case PublicKeyPacket.prototype:
29923 case SecretSubkeyPacket.prototype:
29924 case PublicSubkeyPacket.prototype:
29925 switch (keyPacket.algorithm) {
29926 case 'ecdh':
29927 case 'ecdsa':
29928 case 'eddsa':
29929 pref_algo = mod.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid);
29930 }
29931 }
29932 return mod.hash.getHashByteLength(hash_algo) <= mod.hash.getHashByteLength(pref_algo) ?
29933 pref_algo : hash_algo;
29934}
29935
29936/**
29937 * Returns the preferred symmetric/aead algorithm for a set of keys
29938 * @param {symmetric|aead} type - Type of preference to return
29939 * @param {Array<Key>} keys - Set of keys
29940 * @param {Date} [date] - Use the given date for verification instead of the current time
29941 * @param {Array} [userIds] - User IDs
29942 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29943 * @returns {module:enums.symmetric} Preferred symmetric algorithm.
29944 * @async
29945 */
29946async function getPreferredAlgo(type, keys, date = new Date(), userIds = [], config = defaultConfig) {
29947 const prefProperty = type === 'symmetric' ? 'preferredSymmetricAlgorithms' : 'preferredAeadAlgorithms';
29948 const defaultAlgo = type === 'symmetric' ? enums.symmetric.aes128 : enums.aead.eax;
29949 const prioMap = {};
29950 await Promise.all(keys.map(async function(key, i) {
29951 const primaryUser = await key.getPrimaryUser(date, userIds[i], config);
29952 if (!primaryUser.selfCertification[prefProperty]) {
29953 return defaultAlgo;
29954 }
29955 primaryUser.selfCertification[prefProperty].forEach(function(algo, index) {
29956 const entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo });
29957 entry.prio += 64 >> index;
29958 entry.count++;
29959 });
29960 }));
29961 let prefAlgo = { prio: 0, algo: defaultAlgo };
29962 Object.values(prioMap).forEach(({ prio, count, algo }) => {
29963 try {
29964 if (algo !== enums[type].plaintext &&
29965 algo !== enums[type].idea && // not implemented
29966 enums.read(enums[type], algo) && // known algorithm
29967 count === keys.length && // available for all keys
29968 prio > prefAlgo.prio) {
29969 prefAlgo = prioMap[algo];
29970 }
29971 } catch (e) {}
29972 });
29973 return prefAlgo.algo;
29974}
29975
29976/**
29977 * Create signature packet
29978 * @param {Object} dataToSign - Contains packets to be signed
29979 * @param {SecretKeyPacket|
29980 * SecretSubkeyPacket} signingKeyPacket secret key packet for signing
29981 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
29982 * @param {Date} [date] - Override the creationtime of the signature
29983 * @param {Object} [userId] - User ID
29984 * @param {Object} [detached] - Whether to create a detached signature packet
29985 * @param {Boolean} [streaming] - Whether to process data as a stream
29986 * @param {Object} config - full configuration
29987 * @returns {SignaturePacket} Signature packet.
29988 * @async
29989 */
29990async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userId, detached = false, streaming = false, config) {
29991 if (signingKeyPacket.isDummy()) {
29992 throw new Error('Cannot sign with a gnu-dummy key.');
29993 }
29994 if (!signingKeyPacket.isDecrypted()) {
29995 throw new Error('Private key is not decrypted.');
29996 }
29997 const signaturePacket = new SignaturePacket(date);
29998 Object.assign(signaturePacket, signatureProperties);
29999 signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
30000 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(privateKey, signingKeyPacket, date, userId, config);
30001 await signaturePacket.sign(signingKeyPacket, dataToSign, detached, streaming);
30002 return signaturePacket;
30003}
30004
30005/**
30006 * Merges signatures from source[attr] to dest[attr]
30007 * @param {Object} source
30008 * @param {Object} dest
30009 * @param {String} attr
30010 * @param {Function} checkFn - optional, signature only merged if true
30011 */
30012async function mergeSignatures(source, dest, attr, checkFn) {
30013 source = source[attr];
30014 if (source) {
30015 if (!dest[attr].length) {
30016 dest[attr] = source;
30017 } else {
30018 await Promise.all(source.map(async function(sourceSig) {
30019 if (!sourceSig.isExpired() && (!checkFn || await checkFn(sourceSig)) &&
30020 !dest[attr].some(function(destSig) {
30021 return util.equalsUint8Array(destSig.write_params(), sourceSig.write_params());
30022 })) {
30023 dest[attr].push(sourceSig);
30024 }
30025 }));
30026 }
30027 }
30028}
30029
30030/**
30031 * Checks if a given certificate or binding signature is revoked
30032 * @param {SecretKeyPacket|
30033 * PublicKeyPacket} primaryKey The primary key packet
30034 * @param {Object} dataToVerify - The data to check
30035 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
30036 * @param {SignaturePacket} signature - The certificate or signature to check
30037 * @param {PublicSubkeyPacket|
30038 * SecretSubkeyPacket|
30039 * PublicKeyPacket|
30040 * SecretKeyPacket} key, optional The key packet to check the signature
30041 * @param {Date} date - Use the given date instead of the current time
30042 * @param {Object} config - Full configuration
30043 * @returns {Boolean} True if the signature revokes the data.
30044 * @async
30045 */
30046async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
30047 key = key || primaryKey;
30048 const normDate = util.normalizeDate(date);
30049 const revocationKeyIds = [];
30050 await Promise.all(revocations.map(async function(revocationSignature) {
30051 try {
30052 if (
30053 // Note: a third-party revocation signature could legitimately revoke a
30054 // self-signature if the signature has an authorized revocation key.
30055 // However, we don't support passing authorized revocation keys, nor
30056 // verifying such revocation signatures. Instead, we indicate an error
30057 // when parsing a key with an authorized revocation key, and ignore
30058 // third-party revocation signatures here. (It could also be revoking a
30059 // third-party key certification, which should only affect
30060 // `verifyAllCertifications`.)
30061 (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) &&
30062 !(config.revocationsExpire && revocationSignature.isExpired(normDate))
30063 ) {
30064 revocationSignature.verified || await revocationSignature.verify(key, signatureType, dataToVerify, undefined, undefined, config);
30065
30066 // TODO get an identifier of the revoked object instead
30067 revocationKeyIds.push(revocationSignature.issuerKeyId);
30068 }
30069 } catch (e) {}
30070 }));
30071 // TODO further verify that this is the signature that should be revoked
30072 if (signature) {
30073 signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true :
30074 signature.revoked || false;
30075 return signature.revoked;
30076 }
30077 return revocationKeyIds.length > 0;
30078}
30079
30080function getExpirationTime(keyPacket, signature) {
30081 let expirationTime;
30082 // check V4 expiration time
30083 if (signature.keyNeverExpires === false) {
30084 expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
30085 }
30086 return expirationTime ? new Date(expirationTime) : Infinity;
30087}
30088
30089/**
30090 * Returns whether aead is supported by all keys in the set
30091 * @param {Array<Key>} keys - Set of keys
30092 * @param {Date} [date] - Use the given date for verification instead of the current time
30093 * @param {Array} [userIds] - User IDs
30094 * @param {Object} config - full configuration
30095 * @returns {Boolean}
30096 * @async
30097 */
30098async function isAeadSupported(keys, date = new Date(), userIds = [], config = defaultConfig) {
30099 let supported = true;
30100 // TODO replace when Promise.some or Promise.any are implemented
30101 await Promise.all(keys.map(async function(key, i) {
30102 const primaryUser = await key.getPrimaryUser(date, userIds[i], config);
30103 if (!primaryUser.selfCertification.features ||
30104 !(primaryUser.selfCertification.features[0] & enums.features.aead)) {
30105 supported = false;
30106 }
30107 }));
30108 return supported;
30109}
30110
30111function sanitizeKeyOptions(options, subkeyDefaults = {}) {
30112 options.type = options.type || subkeyDefaults.type;
30113 options.curve = options.curve || subkeyDefaults.curve;
30114 options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
30115 options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
30116 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
30117 options.date = options.date || subkeyDefaults.date;
30118
30119 options.sign = options.sign || false;
30120
30121 switch (options.type) {
30122 case 'ecc':
30123 try {
30124 options.curve = enums.write(enums.curve, options.curve);
30125 } catch (e) {
30126 throw new Error('Invalid curve');
30127 }
30128 if (options.curve === enums.curve.ed25519 || options.curve === enums.curve.curve25519) {
30129 options.curve = options.sign ? enums.curve.ed25519 : enums.curve.curve25519;
30130 }
30131 if (options.sign) {
30132 options.algorithm = options.curve === enums.curve.ed25519 ? enums.publicKey.eddsa : enums.publicKey.ecdsa;
30133 } else {
30134 options.algorithm = enums.publicKey.ecdh;
30135 }
30136 break;
30137 case 'rsa':
30138 options.algorithm = enums.publicKey.rsaEncryptSign;
30139 break;
30140 default:
30141 throw new Error(`Unsupported key type ${options.type}`);
30142 }
30143 return options;
30144}
30145
30146function isValidSigningKeyPacket(keyPacket, signature) {
30147 if (!signature.verified || signature.revoked !== false) { // Sanity check
30148 throw new Error('Signature not verified');
30149 }
30150 return keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.rsaEncrypt) &&
30151 keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.elgamal) &&
30152 keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.ecdh) &&
30153 (!signature.keyFlags ||
30154 (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);
30155}
30156
30157function isValidEncryptionKeyPacket(keyPacket, signature) {
30158 if (!signature.verified || signature.revoked !== false) { // Sanity check
30159 throw new Error('Signature not verified');
30160 }
30161 return keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.dsa) &&
30162 keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.rsaSign) &&
30163 keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.ecdsa) &&
30164 keyPacket.algorithm !== enums.read(enums.publicKey, enums.publicKey.eddsa) &&
30165 (!signature.keyFlags ||
30166 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
30167 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);
30168}
30169
30170function isValidDecryptionKeyPacket(signature, config) {
30171 if (!signature.verified) { // Sanity check
30172 throw new Error('Signature not verified');
30173 }
30174
30175 if (config.allowInsecureDecryptionWithSigningKeys) {
30176 // This is only relevant for RSA keys, all other signing ciphers cannot decrypt
30177 return true;
30178 }
30179
30180 return !signature.keyFlags ||
30181 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
30182 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
30183}
30184
30185/**
30186 * @module key/User
30187 * @private
30188 */
30189
30190/**
30191 * Class that represents an user ID or attribute packet and the relevant signatures.
30192 */
30193class User {
30194 constructor(userPacket) {
30195 if (!(this instanceof User)) {
30196 return new User(userPacket);
30197 }
30198 this.userId = userPacket.tag === enums.packet.userID ? userPacket : null;
30199 this.userAttribute = userPacket.tag === enums.packet.userAttribute ? userPacket : null;
30200 this.selfCertifications = [];
30201 this.otherCertifications = [];
30202 this.revocationSignatures = [];
30203 }
30204
30205 /**
30206 * Transforms structured user data to packetlist
30207 * @returns {PacketList}
30208 */
30209 toPacketlist() {
30210 const packetlist = new PacketList();
30211 packetlist.push(this.userId || this.userAttribute);
30212 packetlist.concat(this.revocationSignatures);
30213 packetlist.concat(this.selfCertifications);
30214 packetlist.concat(this.otherCertifications);
30215 return packetlist;
30216 }
30217
30218 /**
30219 * Signs user
30220 * @param {SecretKeyPacket|
30221 * PublicKeyPacket} primaryKey The primary key packet
30222 * @param {Array<Key>} privateKeys - Decrypted private keys for signing
30223 * @param {Object} config - Full configuration
30224 * @returns {Key} New user with new certificate signatures.
30225 * @async
30226 */
30227 async sign(primaryKey, privateKeys, config) {
30228 const dataToSign = {
30229 userId: this.userId,
30230 userAttribute: this.userAttribute,
30231 key: primaryKey
30232 };
30233 const user = new User(dataToSign.userId || dataToSign.userAttribute);
30234 user.otherCertifications = await Promise.all(privateKeys.map(async function(privateKey) {
30235 if (privateKey.isPublic()) {
30236 throw new Error('Need private key for signing');
30237 }
30238 if (privateKey.hasSameFingerprintAs(primaryKey)) {
30239 throw new Error('Not implemented for self signing');
30240 }
30241 const signingKey = await privateKey.getSigningKey(undefined, undefined, undefined, config);
30242 return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
30243 // Most OpenPGP implementations use generic certification (0x10)
30244 signatureType: enums.signature.certGeneric,
30245 keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
30246 }, undefined, undefined, undefined, undefined, config);
30247 }));
30248 await user.update(this, primaryKey);
30249 return user;
30250 }
30251
30252 /**
30253 * Checks if a given certificate of the user is revoked
30254 * @param {SecretKeyPacket|
30255 * PublicKeyPacket} primaryKey The primary key packet
30256 * @param {SignaturePacket} certificate - The certificate to verify
30257 * @param {PublicSubkeyPacket|
30258 * SecretSubkeyPacket|
30259 * PublicKeyPacket|
30260 * SecretKeyPacket} key, optional The key to verify the signature
30261 * @param {Date} date - Use the given date instead of the current time
30262 * @param {Object} config - Full configuration
30263 * @returns {Boolean} True if the certificate is revoked.
30264 * @async
30265 */
30266 async isRevoked(primaryKey, certificate, key, date = new Date(), config) {
30267 return isDataRevoked(
30268 primaryKey, enums.signature.certRevocation, {
30269 key: primaryKey,
30270 userId: this.userId,
30271 userAttribute: this.userAttribute
30272 }, this.revocationSignatures, certificate, key, date, config
30273 );
30274 }
30275
30276 /**
30277 * Verifies the user certificate. Throws if the user certificate is invalid.
30278 * @param {SecretKeyPacket|
30279 * PublicKeyPacket} primaryKey The primary key packet
30280 * @param {SignaturePacket} certificate - A certificate of this user
30281 * @param {Array<Key>} keys - Array of keys to verify certificate signatures
30282 * @param {Date} date - Use the given date instead of the current time
30283 * @param {Object} config - Full configuration
30284 * @returns {true|null} Status of the certificate.
30285 * @async
30286 */
30287 async verifyCertificate(primaryKey, certificate, keys, date = new Date(), config) {
30288 const that = this;
30289 const keyid = certificate.issuerKeyId;
30290 const dataToVerify = {
30291 userId: this.userId,
30292 userAttribute: this.userAttribute,
30293 key: primaryKey
30294 };
30295 const results = await Promise.all(keys.map(async function(key) {
30296 if (!key.getKeyIds().some(id => id.equals(keyid))) {
30297 return null;
30298 }
30299 const signingKey = await key.getSigningKey(keyid, date, undefined, config);
30300 if (certificate.revoked || await that.isRevoked(primaryKey, certificate, signingKey.keyPacket, date, config)) {
30301 throw new Error('User certificate is revoked');
30302 }
30303 try {
30304 certificate.verified || await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, undefined, undefined, config);
30305 } catch (e) {
30306 throw util.wrapError('User certificate is invalid', e);
30307 }
30308 if (certificate.isExpired(date)) {
30309 throw new Error('User certificate is expired');
30310 }
30311 return true;
30312 }));
30313 return results.find(result => result !== null) || null;
30314 }
30315
30316 /**
30317 * Verifies all user certificates
30318 * @param {SecretKeyPacket|
30319 * PublicKeyPacket} primaryKey The primary key packet
30320 * @param {Array<Key>} keys - Array of keys to verify certificate signatures
30321 * @param {Date} date - Use the given date instead of the current time
30322 * @param {Object} config - Full configuration
30323 * @returns {Promise<Array<{keyid: module:type/keyid~Keyid,
30324 * valid: Boolean}>>} List of signer's keyid and validity of signature
30325 * @async
30326 */
30327 async verifyAllCertifications(primaryKey, keys, date = new Date(), config) {
30328 const that = this;
30329 const certifications = this.selfCertifications.concat(this.otherCertifications);
30330 return Promise.all(certifications.map(async function(certification) {
30331 return {
30332 keyid: certification.issuerKeyId,
30333 valid: await that.verifyCertificate(primaryKey, certification, keys, date, config).catch(() => false)
30334 };
30335 }));
30336 }
30337
30338 /**
30339 * Verify User. Checks for existence of self signatures, revocation signatures
30340 * and validity of self signature.
30341 * @param {SecretKeyPacket|
30342 * PublicKeyPacket} primaryKey The primary key packet
30343 * @param {Date} date - Use the given date instead of the current time
30344 * @param {Object} config - Full configuration
30345 * @returns {true} Status of user.
30346 * @throws {Error} if there are no valid self signatures.
30347 * @async
30348 */
30349 async verify(primaryKey, date = new Date(), config) {
30350 if (!this.selfCertifications.length) {
30351 throw new Error('No self-certifications');
30352 }
30353 const that = this;
30354 const dataToVerify = {
30355 userId: this.userId,
30356 userAttribute: this.userAttribute,
30357 key: primaryKey
30358 };
30359 // TODO replace when Promise.some or Promise.any are implemented
30360 let exception;
30361 for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
30362 try {
30363 const selfCertification = this.selfCertifications[i];
30364 if (selfCertification.revoked || await that.isRevoked(primaryKey, selfCertification, undefined, date, config)) {
30365 throw new Error('Self-certification is revoked');
30366 }
30367 try {
30368 selfCertification.verified || await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, undefined, undefined, config);
30369 } catch (e) {
30370 throw util.wrapError('Self-certification is invalid', e);
30371 }
30372 if (selfCertification.isExpired(date)) {
30373 throw new Error('Self-certification is expired');
30374 }
30375 return true;
30376 } catch (e) {
30377 exception = e;
30378 }
30379 }
30380 throw exception;
30381 }
30382
30383 /**
30384 * Update user with new components from specified user
30385 * @param {User} user - Source user to merge
30386 * @param {SecretKeyPacket|
30387 * SecretSubkeyPacket} primaryKey primary key used for validation
30388 * @param {Object} config - Full configuration
30389 * @returns {undefined}
30390 * @async
30391 */
30392 async update(user, primaryKey, config) {
30393 const dataToVerify = {
30394 userId: this.userId,
30395 userAttribute: this.userAttribute,
30396 key: primaryKey
30397 };
30398 // self signatures
30399 await mergeSignatures(user, this, 'selfCertifications', async function(srcSelfSig) {
30400 try {
30401 srcSelfSig.verified || await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, undefined, undefined, config);
30402 return true;
30403 } catch (e) {
30404 return false;
30405 }
30406 });
30407 // other signatures
30408 await mergeSignatures(user, this, 'otherCertifications');
30409 // revocation signatures
30410 await mergeSignatures(user, this, 'revocationSignatures', function(srcRevSig) {
30411 return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, undefined, config);
30412 });
30413 }
30414}
30415
30416/**
30417 * @module key/SubKey
30418 * @private
30419 */
30420
30421/**
30422 * Class that represents a subkey packet and the relevant signatures.
30423 * @borrows PublicSubkeyPacket#getKeyId as SubKey#getKeyId
30424 * @borrows PublicSubkeyPacket#getFingerprint as SubKey#getFingerprint
30425 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as SubKey#hasSameFingerprintAs
30426 * @borrows PublicSubkeyPacket#getAlgorithmInfo as SubKey#getAlgorithmInfo
30427 * @borrows PublicSubkeyPacket#getCreationTime as SubKey#getCreationTime
30428 * @borrows PublicSubkeyPacket#isDecrypted as SubKey#isDecrypted
30429 */
30430class SubKey {
30431 constructor(subKeyPacket) {
30432 if (!(this instanceof SubKey)) {
30433 return new SubKey(subKeyPacket);
30434 }
30435 this.keyPacket = subKeyPacket;
30436 this.bindingSignatures = [];
30437 this.revocationSignatures = [];
30438 }
30439
30440 /**
30441 * Transforms structured subkey data to packetlist
30442 * @returns {PacketList}
30443 */
30444 toPacketlist() {
30445 const packetlist = new PacketList();
30446 packetlist.push(this.keyPacket);
30447 packetlist.concat(this.revocationSignatures);
30448 packetlist.concat(this.bindingSignatures);
30449 return packetlist;
30450 }
30451
30452 /**
30453 * Checks if a binding signature of a subkey is revoked
30454 * @param {SecretKeyPacket|
30455 * PublicKeyPacket} primaryKey The primary key packet
30456 * @param {SignaturePacket} signature - The binding signature to verify
30457 * @param {PublicSubkeyPacket|
30458 * SecretSubkeyPacket|
30459 * PublicKeyPacket|
30460 * SecretKeyPacket} key, optional The key to verify the signature
30461 * @param {Date} date - Use the given date instead of the current time
30462 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30463 * @returns {Boolean} True if the binding signature is revoked.
30464 * @async
30465 */
30466 async isRevoked(primaryKey, signature, key, date = new Date(), config = defaultConfig) {
30467 return isDataRevoked(
30468 primaryKey, enums.signature.subkeyRevocation, {
30469 key: primaryKey,
30470 bind: this.keyPacket
30471 }, this.revocationSignatures, signature, key, date, config
30472 );
30473 }
30474
30475 /**
30476 * Verify subkey. Checks for revocation signatures, expiration time
30477 * and valid binding signature.
30478 * @param {SecretKeyPacket|
30479 * PublicKeyPacket} primaryKey The primary key packet
30480 * @param {Date} date - Use the given date instead of the current time
30481 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30482 * @returns {SignaturePacket}
30483 * @throws {Error} if the subkey is invalid.
30484 * @async
30485 */
30486 async verify(primaryKey, date = new Date(), config = defaultConfig) {
30487 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
30488 // check subkey binding signatures
30489 const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
30490 // check binding signature is not revoked
30491 if (bindingSignature.revoked || await this.isRevoked(primaryKey, bindingSignature, null, date, config)) {
30492 throw new Error('Subkey is revoked');
30493 }
30494 // check for expiration time
30495 if (isDataExpired(this.keyPacket, bindingSignature, date)) {
30496 throw new Error('Subkey is expired');
30497 }
30498 return bindingSignature;
30499 }
30500
30501 /**
30502 * Returns the expiration time of the subkey or Infinity if key does not expire
30503 * Returns null if the subkey is invalid.
30504 * @param {SecretKeyPacket|
30505 * PublicKeyPacket} primaryKey The primary key packet
30506 * @param {Date} date - Use the given date instead of the current time
30507 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30508 * @returns {Date | Infinity | null}
30509 * @async
30510 */
30511 async getExpirationTime(primaryKey, date = new Date(), config = defaultConfig) {
30512 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
30513 let bindingSignature;
30514 try {
30515 bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
30516 } catch (e) {
30517 return null;
30518 }
30519 const keyExpiry = getExpirationTime(this.keyPacket, bindingSignature);
30520 const sigExpiry = bindingSignature.getExpirationTime();
30521 return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
30522 }
30523
30524 /**
30525 * Update subkey with new components from specified subkey
30526 * @param {SubKey} subKey - Source subkey to merge
30527 * @param {SecretKeyPacket|
30528 SecretSubkeyPacket} primaryKey primary key used for validation
30529 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30530 * @throws {Error} if update failed
30531 * @async
30532 */
30533 async update(subKey, primaryKey, config = defaultConfig) {
30534 if (!this.hasSameFingerprintAs(subKey)) {
30535 throw new Error('SubKey update method: fingerprints of subkeys not equal');
30536 }
30537 // key packet
30538 if (this.keyPacket.tag === enums.packet.publicSubkey &&
30539 subKey.keyPacket.tag === enums.packet.secretSubkey) {
30540 this.keyPacket = subKey.keyPacket;
30541 }
30542 // update missing binding signatures
30543 const that = this;
30544 const dataToVerify = { key: primaryKey, bind: that.keyPacket };
30545 await mergeSignatures(subKey, this, 'bindingSignatures', async function(srcBindSig) {
30546 for (let i = 0; i < that.bindingSignatures.length; i++) {
30547 if (that.bindingSignatures[i].issuerKeyId.equals(srcBindSig.issuerKeyId)) {
30548 if (srcBindSig.created > that.bindingSignatures[i].created) {
30549 that.bindingSignatures[i] = srcBindSig;
30550 }
30551 return false;
30552 }
30553 }
30554 try {
30555 srcBindSig.verified || await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, undefined, undefined, config);
30556 return true;
30557 } catch (e) {
30558 return false;
30559 }
30560 });
30561 // revocation signatures
30562 await mergeSignatures(subKey, this, 'revocationSignatures', function(srcRevSig) {
30563 return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, undefined, config);
30564 });
30565 }
30566
30567 /**
30568 * Revokes the subkey
30569 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
30570 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
30571 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
30572 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
30573 * @param {Date} date - optional, override the creationtime of the revocation signature
30574 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30575 * @returns {SubKey} New subkey with revocation signature.
30576 * @async
30577 */
30578 async revoke(
30579 primaryKey,
30580 {
30581 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
30582 string: reasonForRevocationString = ''
30583 } = {},
30584 date = new Date(),
30585 config = defaultConfig
30586 ) {
30587 const dataToSign = { key: primaryKey, bind: this.keyPacket };
30588 const subKey = new SubKey(this.keyPacket);
30589 subKey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
30590 signatureType: enums.signature.subkeyRevocation,
30591 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
30592 reasonForRevocationString
30593 }, date, undefined, undefined, undefined, config));
30594 await subKey.update(this, primaryKey);
30595 return subKey;
30596 }
30597
30598 hasSameFingerprintAs(other) {
30599 return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
30600 }
30601}
30602
30603['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
30604 SubKey.prototype[name] =
30605 function() {
30606 return this.keyPacket[name]();
30607 };
30608});
30609
30610// GPG4Browsers - An OpenPGP implementation in javascript
30611
30612/**
30613 * Class that represents an OpenPGP key. Must contain a primary key.
30614 * Can contain additional subkeys, signatures, user ids, user attributes.
30615 * @borrows PublicKeyPacket#getKeyId as Key#getKeyId
30616 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
30617 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
30618 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
30619 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
30620 */
30621class Key {
30622 /**
30623 * @param {PacketList} packetlist - The packets that form this key
30624 */
30625 constructor(packetlist) {
30626 if (!(this instanceof Key)) {
30627 return new Key(packetlist);
30628 }
30629 // same data as in packetlist but in structured form
30630 this.keyPacket = null;
30631 this.revocationSignatures = [];
30632 this.directSignatures = [];
30633 this.users = [];
30634 this.subKeys = [];
30635 this.packetlist2structure(packetlist);
30636 if (!this.keyPacket) {
30637 throw new Error('Invalid key: need at least key packet');
30638 }
30639 }
30640
30641 get primaryKey() {
30642 return this.keyPacket;
30643 }
30644
30645 /**
30646 * Transforms packetlist to structured key data
30647 * @param {PacketList} packetlist - The packets that form a key
30648 */
30649 packetlist2structure(packetlist) {
30650 let user;
30651 let primaryKeyId;
30652 let subKey;
30653 for (let i = 0; i < packetlist.length; i++) {
30654 switch (packetlist[i].tag) {
30655 case enums.packet.publicKey:
30656 case enums.packet.secretKey:
30657 if (this.keyPacket) {
30658 throw new Error('Key block contains multiple keys');
30659 }
30660 this.keyPacket = packetlist[i];
30661 primaryKeyId = this.getKeyId();
30662 break;
30663 case enums.packet.userID:
30664 case enums.packet.userAttribute:
30665 user = new User(packetlist[i]);
30666 this.users.push(user);
30667 break;
30668 case enums.packet.publicSubkey:
30669 case enums.packet.secretSubkey:
30670 user = null;
30671 subKey = new SubKey(packetlist[i]);
30672 this.subKeys.push(subKey);
30673 break;
30674 case enums.packet.signature:
30675 switch (packetlist[i].signatureType) {
30676 case enums.signature.certGeneric:
30677 case enums.signature.certPersona:
30678 case enums.signature.certCasual:
30679 case enums.signature.certPositive:
30680 if (!user) {
30681 util.printDebug('Dropping certification signatures without preceding user packet');
30682 continue;
30683 }
30684 if (packetlist[i].issuerKeyId.equals(primaryKeyId)) {
30685 user.selfCertifications.push(packetlist[i]);
30686 } else {
30687 user.otherCertifications.push(packetlist[i]);
30688 }
30689 break;
30690 case enums.signature.certRevocation:
30691 if (user) {
30692 user.revocationSignatures.push(packetlist[i]);
30693 } else {
30694 this.directSignatures.push(packetlist[i]);
30695 }
30696 break;
30697 case enums.signature.key:
30698 this.directSignatures.push(packetlist[i]);
30699 break;
30700 case enums.signature.subkeyBinding:
30701 if (!subKey) {
30702 util.printDebug('Dropping subkey binding signature without preceding subkey packet');
30703 continue;
30704 }
30705 subKey.bindingSignatures.push(packetlist[i]);
30706 break;
30707 case enums.signature.keyRevocation:
30708 this.revocationSignatures.push(packetlist[i]);
30709 break;
30710 case enums.signature.subkeyRevocation:
30711 if (!subKey) {
30712 util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
30713 continue;
30714 }
30715 subKey.revocationSignatures.push(packetlist[i]);
30716 break;
30717 }
30718 break;
30719 }
30720 }
30721 }
30722
30723 /**
30724 * Transforms structured key data to packetlist
30725 * @returns {PacketList} The packets that form a key.
30726 */
30727 toPacketlist() {
30728 const packetlist = new PacketList();
30729 packetlist.push(this.keyPacket);
30730 packetlist.concat(this.revocationSignatures);
30731 packetlist.concat(this.directSignatures);
30732 this.users.map(user => packetlist.concat(user.toPacketlist()));
30733 this.subKeys.map(subKey => packetlist.concat(subKey.toPacketlist()));
30734 return packetlist;
30735 }
30736
30737 /**
30738 * Clones the key object
30739 * @returns {Key} Shallow clone of the key.
30740 * @async
30741 */
30742 async clone() {
30743 return new Key(this.toPacketlist());
30744 }
30745
30746 /**
30747 * Returns an array containing all public or private subkeys matching keyId;
30748 * If keyId is not present, returns all subkeys.
30749 * @param {type/keyid} keyId
30750 * @returns {Array<SubKey>}
30751 */
30752 getSubkeys(keyId = null) {
30753 const subKeys = [];
30754 this.subKeys.forEach(subKey => {
30755 if (!keyId || subKey.getKeyId().equals(keyId, true)) {
30756 subKeys.push(subKey);
30757 }
30758 });
30759 return subKeys;
30760 }
30761
30762 /**
30763 * Returns an array containing all public or private keys matching keyId.
30764 * If keyId is not present, returns all keys starting with the primary key.
30765 * @param {type/keyid} keyId
30766 * @returns {Array<Key|SubKey>}
30767 */
30768 getKeys(keyId = null) {
30769 const keys = [];
30770 if (!keyId || this.getKeyId().equals(keyId, true)) {
30771 keys.push(this);
30772 }
30773 return keys.concat(this.getSubkeys(keyId));
30774 }
30775
30776 /**
30777 * Returns key IDs of all keys
30778 * @returns {Array<module:type/keyid~Keyid>}
30779 */
30780 getKeyIds() {
30781 return this.getKeys().map(key => key.getKeyId());
30782 }
30783
30784 /**
30785 * Returns userids
30786 * @returns {Array<string>} Array of userids.
30787 */
30788 getUserIds() {
30789 return this.users.map(user => {
30790 return user.userId ? user.userId.userid : null;
30791 }).filter(userid => userid !== null);
30792 }
30793
30794 /**
30795 * Returns true if this is a public key
30796 * @returns {Boolean}
30797 */
30798 isPublic() {
30799 return this.keyPacket.tag === enums.packet.publicKey;
30800 }
30801
30802 /**
30803 * Returns true if this is a private key
30804 * @returns {Boolean}
30805 */
30806 isPrivate() {
30807 return this.keyPacket.tag === enums.packet.secretKey;
30808 }
30809
30810 /**
30811 * Returns key as public key (shallow copy)
30812 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30813 * @returns {Key} New public Key.
30814 */
30815 toPublic() {
30816 const packetlist = new PacketList();
30817 const keyPackets = this.toPacketlist();
30818 let bytes;
30819 let pubKeyPacket;
30820 let pubSubkeyPacket;
30821 for (let i = 0; i < keyPackets.length; i++) {
30822 switch (keyPackets[i].tag) {
30823 case enums.packet.secretKey:
30824 bytes = keyPackets[i].writePublicKey();
30825 pubKeyPacket = new PublicKeyPacket();
30826 pubKeyPacket.read(bytes);
30827 packetlist.push(pubKeyPacket);
30828 break;
30829 case enums.packet.secretSubkey:
30830 bytes = keyPackets[i].writePublicKey();
30831 pubSubkeyPacket = new PublicSubkeyPacket();
30832 pubSubkeyPacket.read(bytes);
30833 packetlist.push(pubSubkeyPacket);
30834 break;
30835 default:
30836 packetlist.push(keyPackets[i]);
30837 }
30838 }
30839 return new Key(packetlist);
30840 }
30841
30842 /**
30843 * Returns ASCII armored text of key
30844 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30845 * @returns {ReadableStream<String>} ASCII armor.
30846 */
30847 armor(config = defaultConfig) {
30848 const type = this.isPublic() ? enums.armor.publicKey : enums.armor.privateKey;
30849 return armor(type, this.toPacketlist().write(), undefined, undefined, undefined, config);
30850 }
30851
30852 /**
30853 * Returns last created key or key by given keyId that is available for signing and verification
30854 * @param {module:type/keyid~Keyid} keyId, optional
30855 * @param {Date} [date] - Use the given date for verification instead of the current time
30856 * @param {Object} userId, optional user ID
30857 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30858 * @returns {Key|SubKey|null} Key or null if no signing key has been found.
30859 * @async
30860 */
30861 async getSigningKey(keyId = null, date = new Date(), userId = {}, config = defaultConfig) {
30862 await this.verifyPrimaryKey(date, userId, config);
30863 const primaryKey = this.keyPacket;
30864 const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
30865 let exception;
30866 for (let i = 0; i < subKeys.length; i++) {
30867 if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
30868 try {
30869 await subKeys[i].verify(primaryKey, date, config);
30870 const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
30871 const bindingSignature = await getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
30872 if (
30873 bindingSignature &&
30874 bindingSignature.embeddedSignature &&
30875 isValidSigningKeyPacket(subKeys[i].keyPacket, bindingSignature) &&
30876 await getLatestValidSignature([bindingSignature.embeddedSignature], subKeys[i].keyPacket, enums.signature.keyBinding, dataToVerify, date, config)
30877 ) {
30878 return subKeys[i];
30879 }
30880 } catch (e) {
30881 exception = e;
30882 }
30883 }
30884 }
30885 const primaryUser = await this.getPrimaryUser(date, userId, config);
30886 if ((!keyId || primaryKey.getKeyId().equals(keyId)) &&
30887 isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification)) {
30888 return this;
30889 }
30890 throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyId().toHex(), exception);
30891 }
30892
30893 /**
30894 * Returns last created key or key by given keyId that is available for encryption or decryption
30895 * @param {module:type/keyid~Keyid} keyId, optional
30896 * @param {Date} date, optional
30897 * @param {String} userId, optional
30898 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30899 * @returns {Key|SubKey|null} Key or null if no encryption key has been found.
30900 * @async
30901 */
30902 async getEncryptionKey(keyId, date = new Date(), userId = {}, config = defaultConfig) {
30903 await this.verifyPrimaryKey(date, userId, config);
30904 const primaryKey = this.keyPacket;
30905 // V4: by convention subkeys are preferred for encryption service
30906 const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
30907 let exception;
30908 for (let i = 0; i < subKeys.length; i++) {
30909 if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
30910 try {
30911 await subKeys[i].verify(primaryKey, date, config);
30912 const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
30913 const bindingSignature = await getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
30914 if (bindingSignature && isValidEncryptionKeyPacket(subKeys[i].keyPacket, bindingSignature)) {
30915 return subKeys[i];
30916 }
30917 } catch (e) {
30918 exception = e;
30919 }
30920 }
30921 }
30922 // if no valid subkey for encryption, evaluate primary key
30923 const primaryUser = await this.getPrimaryUser(date, userId, config);
30924 if ((!keyId || primaryKey.getKeyId().equals(keyId)) &&
30925 isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
30926 return this;
30927 }
30928 throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyId().toHex(), exception);
30929 }
30930
30931 /**
30932 * Returns all keys that are available for decryption, matching the keyId when given
30933 * This is useful to retrieve keys for session key decryption
30934 * @param {module:type/keyid~Keyid} keyId, optional
30935 * @param {Date} date, optional
30936 * @param {String} userId, optional
30937 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30938 * @returns {Array<Key|SubKey>} Array of decryption keys.
30939 * @async
30940 */
30941 async getDecryptionKeys(keyId, date = new Date(), userId = {}, config = defaultConfig) {
30942 const primaryKey = this.keyPacket;
30943 const keys = [];
30944 for (let i = 0; i < this.subKeys.length; i++) {
30945 if (!keyId || this.subKeys[i].getKeyId().equals(keyId, true)) {
30946 try {
30947 const dataToVerify = { key: primaryKey, bind: this.subKeys[i].keyPacket };
30948 const bindingSignature = await getLatestValidSignature(this.subKeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
30949 if (bindingSignature && isValidDecryptionKeyPacket(bindingSignature, config)) {
30950 keys.push(this.subKeys[i]);
30951 }
30952 } catch (e) {}
30953 }
30954 }
30955
30956 // evaluate primary key
30957 const primaryUser = await this.getPrimaryUser(date, userId, config);
30958 if ((!keyId || primaryKey.getKeyId().equals(keyId, true)) &&
30959 isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {
30960 keys.push(this);
30961 }
30962
30963 return keys;
30964 }
30965
30966 /**
30967 * Encrypts all secret key and subkey packets matching keyId
30968 * @param {String|Array<String>} passphrases - If multiple passphrases, then should be in same order as packets each should encrypt
30969 * @param {module:type/keyid~Keyid} keyId
30970 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30971 * @throws {Error} if encryption failed for any key or subkey
30972 * @async
30973 */
30974 async encrypt(passphrases, keyId = null, config = defaultConfig) {
30975 if (!this.isPrivate()) {
30976 throw new Error("Nothing to encrypt in a public key");
30977 }
30978
30979 const keys = this.getKeys(keyId);
30980 passphrases = util.isArray(passphrases) ? passphrases : new Array(keys.length).fill(passphrases);
30981 if (passphrases.length !== keys.length) {
30982 throw new Error("Invalid number of passphrases for key");
30983 }
30984
30985 await Promise.all(keys.map(async function(key, i) {
30986 const { keyPacket } = key;
30987 await keyPacket.encrypt(passphrases[i], config);
30988 keyPacket.clearPrivateParams();
30989 }));
30990 }
30991
30992 /**
30993 * Decrypts all secret key and subkey packets matching keyId
30994 * @param {String|Array<String>} passphrases
30995 * @param {module:type/keyid~Keyid} keyId
30996 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30997 * @throws {Error} if any matching key or subkey packets did not decrypt successfully
30998 * @async
30999 */
31000 async decrypt(passphrases, keyId = null, config = defaultConfig) {
31001 if (!this.isPrivate()) {
31002 throw new Error("Nothing to decrypt in a public key");
31003 }
31004 passphrases = util.isArray(passphrases) ? passphrases : [passphrases];
31005
31006 await Promise.all(this.getKeys(keyId).map(async function(key) {
31007 let decrypted = false;
31008 let error = null;
31009 await Promise.all(passphrases.map(async function(passphrase) {
31010 try {
31011 await key.keyPacket.decrypt(passphrase);
31012 // If we are decrypting a single key packet, we also validate it directly
31013 if (keyId) await key.keyPacket.validate();
31014 decrypted = true;
31015 } catch (e) {
31016 error = e;
31017 }
31018 }));
31019 if (!decrypted) {
31020 throw error;
31021 }
31022 }));
31023
31024 if (!keyId) {
31025 // The full key should be decrypted and we can validate it all
31026 await this.validate(config);
31027 }
31028 }
31029
31030 /**
31031 * Returns true if the primary key or any subkey is decrypted.
31032 * A dummy key is considered encrypted.
31033 */
31034 isDecrypted() {
31035 return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
31036 }
31037
31038 /**
31039 * Check whether the private and public primary key parameters correspond
31040 * Together with verification of binding signatures, this guarantees key integrity
31041 * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
31042 * otherwise all encryption subkeys are validated
31043 * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
31044 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31045 * @throws {Error} if validation was not successful and the key cannot be trusted
31046 * @async
31047 */
31048 async validate(config = defaultConfig) {
31049 if (!this.isPrivate()) {
31050 throw new Error("Cannot validate a public key");
31051 }
31052
31053 let signingKeyPacket;
31054 if (!this.primaryKey.isDummy()) {
31055 signingKeyPacket = this.primaryKey;
31056 } else {
31057 /**
31058 * It is enough to validate any signing keys
31059 * since its binding signatures are also checked
31060 */
31061 const signingKey = await this.getSigningKey(null, null, undefined, config);
31062 // This could again be a dummy key
31063 if (signingKey && !signingKey.keyPacket.isDummy()) {
31064 signingKeyPacket = signingKey.keyPacket;
31065 }
31066 }
31067
31068 if (signingKeyPacket) {
31069 return signingKeyPacket.validate();
31070 } else {
31071 const keys = this.getKeys();
31072 const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
31073 if (allDummies) {
31074 throw new Error("Cannot validate an all-gnu-dummy key");
31075 }
31076
31077 return Promise.all(keys.map(async key => key.keyPacket.validate()));
31078 }
31079 }
31080
31081 /**
31082 * Clear private key parameters
31083 */
31084 clearPrivateParams() {
31085 if (!this.isPrivate()) {
31086 throw new Error("Can't clear private parameters of a public key");
31087 }
31088 this.getKeys().forEach(({ keyPacket }) => {
31089 if (keyPacket.isDecrypted()) {
31090 keyPacket.clearPrivateParams();
31091 }
31092 });
31093 }
31094
31095 /**
31096 * Checks if a signature on a key is revoked
31097 * @param {SignaturePacket} signature - The signature to verify
31098 * @param {PublicSubkeyPacket|
31099 * SecretSubkeyPacket|
31100 * PublicKeyPacket|
31101 * SecretKeyPacket} key, optional The key to verify the signature
31102 * @param {Date} date - Use the given date instead of the current time
31103 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31104 * @returns {Boolean} True if the certificate is revoked.
31105 * @async
31106 */
31107 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
31108 return isDataRevoked(
31109 this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config
31110 );
31111 }
31112
31113 /**
31114 * Verify primary key. Checks for revocation signatures, expiration time
31115 * and valid self signature. Throws if the primary key is invalid.
31116 * @param {Date} [date] - Use the given date for verification instead of the current time
31117 * @param {Object} [userId] - User ID
31118 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31119 * @throws {Error} If key verification failed
31120 * @async
31121 */
31122 async verifyPrimaryKey(date = new Date(), userId = {}, config = defaultConfig) {
31123 const primaryKey = this.keyPacket;
31124 // check for key revocation signatures
31125 if (await this.isRevoked(null, null, date, config)) {
31126 throw new Error('Primary key is revoked');
31127 }
31128 // check for valid, unrevoked, unexpired self signature
31129 const { selfCertification } = await this.getPrimaryUser(date, userId, config);
31130 // check for expiration time
31131 if (isDataExpired(primaryKey, selfCertification, date)) {
31132 throw new Error('Primary key is expired');
31133 }
31134 }
31135
31136 /**
31137 * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater.
31138 * When `capabilities` is null, defaults to returning the expiry date of the primary key.
31139 * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid.
31140 * Returns Infinity if the key doesn't expire.
31141 * @param {encrypt|sign|encrypt_sign} capabilities, optional
31142 * @param {module:type/keyid~Keyid} keyId, optional
31143 * @param {Object} userId, optional user ID
31144 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31145 * @returns {Date | Infinity | null}
31146 * @async
31147 */
31148 async getExpirationTime(capabilities, keyId, userId, config = defaultConfig) {
31149 const primaryUser = await this.getPrimaryUser(null, userId, config);
31150 const selfCert = primaryUser.selfCertification;
31151 const keyExpiry = getExpirationTime(this.keyPacket, selfCert);
31152 const sigExpiry = selfCert.getExpirationTime();
31153 let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
31154 if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') {
31155 const encryptKey =
31156 await this.getEncryptionKey(keyId, expiry, userId, config).catch(() => {}) ||
31157 await this.getEncryptionKey(keyId, null, userId, config).catch(() => {});
31158 if (!encryptKey) return null;
31159 const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket, undefined, config);
31160 if (encryptExpiry < expiry) expiry = encryptExpiry;
31161 }
31162 if (capabilities === 'sign' || capabilities === 'encrypt_sign') {
31163 const signKey =
31164 await this.getSigningKey(keyId, expiry, userId, config).catch(() => {}) ||
31165 await this.getSigningKey(keyId, null, userId, config).catch(() => {});
31166 if (!signKey) return null;
31167 const signExpiry = await signKey.getExpirationTime(this.keyPacket, undefined, config);
31168 if (signExpiry < expiry) expiry = signExpiry;
31169 }
31170 return expiry;
31171 }
31172
31173 /**
31174 * Returns primary user and most significant (latest valid) self signature
31175 * - if multiple primary users exist, returns the one with the latest self signature
31176 * - otherwise, returns the user with the latest self signature
31177 * @param {Date} [date] - Use the given date for verification instead of the current time
31178 * @param {Object} [userId] - User ID to get instead of the primary user, if it exists
31179 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31180 * @returns {Promise<{user: User,
31181 * selfCertification: SignaturePacket}>} The primary user and the self signature
31182 * @async
31183 */
31184 async getPrimaryUser(date = new Date(), userId = {}, config = defaultConfig) {
31185 const primaryKey = this.keyPacket;
31186 const users = [];
31187 let exception;
31188 for (let i = 0; i < this.users.length; i++) {
31189 try {
31190 const user = this.users[i];
31191 if (!user.userId) {
31192 continue;
31193 }
31194 if (
31195 (userId.name !== undefined && user.userId.name !== userId.name) ||
31196 (userId.email !== undefined && user.userId.email !== userId.email) ||
31197 (userId.comment !== undefined && user.userId.comment !== userId.comment)
31198 ) {
31199 throw new Error('Could not find user that matches that user ID');
31200 }
31201 const dataToVerify = { userId: user.userId, key: primaryKey };
31202 const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);
31203 users.push({ index: i, user, selfCertification });
31204 } catch (e) {
31205 exception = e;
31206 }
31207 }
31208 if (!users.length) {
31209 throw exception || new Error('Could not find primary user');
31210 }
31211 await Promise.all(users.map(async function (a) {
31212 return a.user.revoked || a.user.isRevoked(primaryKey, a.selfCertification, null, date, config);
31213 }));
31214 // sort by primary user flag and signature creation time
31215 const primaryUser = users.sort(function(a, b) {
31216 const A = a.selfCertification;
31217 const B = b.selfCertification;
31218 return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
31219 }).pop();
31220 const { user, selfCertification: cert } = primaryUser;
31221 if (cert.revoked || await user.isRevoked(primaryKey, cert, null, date, config)) {
31222 throw new Error('Primary user is revoked');
31223 }
31224 return primaryUser;
31225 }
31226
31227 /**
31228 * Update key with new components from specified key with same key ID:
31229 * users, subkeys, certificates are merged into the destination key,
31230 * duplicates and expired signatures are ignored.
31231 *
31232 * If the specified key is a private key and the destination key is public,
31233 * the destination key is transformed to a private key.
31234 * @param {Key} key - Source key to merge
31235 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31236 * @returns {undefined}
31237 * @async
31238 */
31239 async update(key, config = defaultConfig) {
31240 if (!this.hasSameFingerprintAs(key)) {
31241 throw new Error('Key update method: fingerprints of keys not equal');
31242 }
31243 if (this.isPublic() && key.isPrivate()) {
31244 // check for equal subkey packets
31245 const equal = (this.subKeys.length === key.subKeys.length) &&
31246 (this.subKeys.every(destSubKey => {
31247 return key.subKeys.some(srcSubKey => {
31248 return destSubKey.hasSameFingerprintAs(srcSubKey);
31249 });
31250 }));
31251 if (!equal) {
31252 throw new Error('Cannot update public key with private key if subkey mismatch');
31253 }
31254 this.keyPacket = key.keyPacket;
31255 }
31256 // revocation signatures
31257 await mergeSignatures(key, this, 'revocationSignatures', srcRevSig => {
31258 return isDataRevoked(this.keyPacket, enums.signature.keyRevocation, this, [srcRevSig], null, key.keyPacket, undefined, config);
31259 });
31260 // direct signatures
31261 await mergeSignatures(key, this, 'directSignatures');
31262 // TODO replace when Promise.some or Promise.any are implemented
31263 // users
31264 await Promise.all(key.users.map(async srcUser => {
31265 let found = false;
31266 await Promise.all(this.users.map(async dstUser => {
31267 if ((srcUser.userId && dstUser.userId &&
31268 (srcUser.userId.userid === dstUser.userId.userid)) ||
31269 (srcUser.userAttribute && (srcUser.userAttribute.equals(dstUser.userAttribute)))) {
31270 await dstUser.update(srcUser, this.keyPacket, config);
31271 found = true;
31272 }
31273 }));
31274 if (!found) {
31275 this.users.push(srcUser);
31276 }
31277 }));
31278 // TODO replace when Promise.some or Promise.any are implemented
31279 // subkeys
31280 await Promise.all(key.subKeys.map(async srcSubKey => {
31281 let found = false;
31282 await Promise.all(this.subKeys.map(async dstSubKey => {
31283 if (dstSubKey.hasSameFingerprintAs(srcSubKey)) {
31284 await dstSubKey.update(srcSubKey, this.keyPacket, config);
31285 found = true;
31286 }
31287 }));
31288 if (!found) {
31289 this.subKeys.push(srcSubKey);
31290 }
31291 }));
31292 }
31293
31294 /**
31295 * Revokes the key
31296 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
31297 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
31298 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
31299 * @param {Date} date - optional, override the creationtime of the revocation signature
31300 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31301 * @returns {Key} New key with revocation signature.
31302 * @async
31303 */
31304 async revoke(
31305 {
31306 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
31307 string: reasonForRevocationString = ''
31308 } = {},
31309 date = new Date(),
31310 config = defaultConfig
31311 ) {
31312 if (this.isPublic()) {
31313 throw new Error('Need private key for revoking');
31314 }
31315 const dataToSign = { key: this.keyPacket };
31316 const key = await this.clone();
31317 key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, {
31318 signatureType: enums.signature.keyRevocation,
31319 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
31320 reasonForRevocationString
31321 }, date, undefined, undefined, undefined, config));
31322 return key;
31323 }
31324
31325 /**
31326 * Get revocation certificate from a revoked key.
31327 * (To get a revocation certificate for an unrevoked key, call revoke() first.)
31328 * @param {Date} date - Use the given date instead of the current time
31329 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31330 * @returns {String} Armored revocation certificate.
31331 * @async
31332 */
31333 async getRevocationCertificate(date = new Date(), config = defaultConfig) {
31334 const dataToVerify = { key: this.keyPacket };
31335 const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);
31336 const packetlist = new PacketList();
31337 packetlist.push(revocationSignature);
31338 return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');
31339 }
31340
31341 /**
31342 * Applies a revocation certificate to a key
31343 * This adds the first signature packet in the armored text to the key,
31344 * if it is a valid revocation signature.
31345 * @param {String} revocationCertificate - armored revocation certificate
31346 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31347 * @returns {Key} New revoked key.
31348 * @async
31349 */
31350 async applyRevocationCertificate(revocationCertificate, config = defaultConfig) {
31351 const input = await unarmor(revocationCertificate, config);
31352 const packetlist = new PacketList();
31353 await packetlist.read(input.data, { SignaturePacket }, undefined, config);
31354 const revocationSignature = packetlist.findPacket(enums.packet.signature);
31355 if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
31356 throw new Error('Could not find revocation signature packet');
31357 }
31358 if (!revocationSignature.issuerKeyId.equals(this.getKeyId())) {
31359 throw new Error('Revocation signature does not match key');
31360 }
31361 if (revocationSignature.isExpired()) {
31362 throw new Error('Revocation signature is expired');
31363 }
31364 try {
31365 await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, undefined, undefined, config);
31366 } catch (e) {
31367 throw util.wrapError('Could not verify revocation signature', e);
31368 }
31369 const key = await this.clone();
31370 key.revocationSignatures.push(revocationSignature);
31371 return key;
31372 }
31373
31374 /**
31375 * Signs primary user of key
31376 * @param {Array<Key>} privateKeys - decrypted private keys for signing
31377 * @param {Date} [date] - Use the given date for verification instead of the current time
31378 * @param {Object} [userId] - User ID to get instead of the primary user, if it exists
31379 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31380 * @returns {Key} New public key with new certificate signature.
31381 * @async
31382 */
31383 async signPrimaryUser(privateKeys, date, userId, config = defaultConfig) {
31384 const { index, user } = await this.getPrimaryUser(date, userId, config);
31385 const userSign = await user.sign(this.keyPacket, privateKeys, config);
31386 const key = await this.clone();
31387 key.users[index] = userSign;
31388 return key;
31389 }
31390
31391 /**
31392 * Signs all users of key
31393 * @param {Array<Key>} privateKeys - decrypted private keys for signing
31394 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31395 * @returns {Key} New public key with new certificate signature.
31396 * @async
31397 */
31398 async signAllUsers(privateKeys, config = defaultConfig) {
31399 const that = this;
31400 const key = await this.clone();
31401 key.users = await Promise.all(this.users.map(function(user) {
31402 return user.sign(that.keyPacket, privateKeys, config);
31403 }));
31404 return key;
31405 }
31406
31407 /**
31408 * Verifies primary user of key
31409 * - if no arguments are given, verifies the self certificates;
31410 * - otherwise, verifies all certificates signed with given keys.
31411 * @param {Array<Key>} keys - array of keys to verify certificate signatures
31412 * @param {Date} [date] - Use the given date for verification instead of the current time
31413 * @param {Object} [userId] - User ID to get instead of the primary user, if it exists
31414 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31415 * @returns {Promise<Array<{keyid: module:type/keyid~Keyid,
31416 * valid: Boolean}>>} List of signer's keyid and validity of signature
31417 * @async
31418 */
31419 async verifyPrimaryUser(keys, date, userId, config = defaultConfig) {
31420 const primaryKey = this.keyPacket;
31421 const { user } = await this.getPrimaryUser(date, userId, config);
31422 const results = keys ? await user.verifyAllCertifications(primaryKey, keys, undefined, config) :
31423 [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }];
31424 return results;
31425 }
31426
31427 /**
31428 * Verifies all users of key
31429 * - if no arguments are given, verifies the self certificates;
31430 * - otherwise, verifies all certificates signed with given keys.
31431 * @param {Array<Key>} keys - array of keys to verify certificate signatures
31432 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31433 * @returns {Promise<Array<{userid: String,
31434 * keyid: module:type/keyid~Keyid,
31435 * valid: Boolean}>>} list of userid, signer's keyid and validity of signature
31436 * @async
31437 */
31438 async verifyAllUsers(keys, config = defaultConfig) {
31439 const results = [];
31440 const primaryKey = this.keyPacket;
31441 await Promise.all(this.users.map(async function(user) {
31442 const signatures = keys ? await user.verifyAllCertifications(primaryKey, keys, undefined, config) :
31443 [{ keyid: primaryKey.keyid, valid: await user.verify(primaryKey, undefined, config).catch(() => false) }];
31444 signatures.forEach(signature => {
31445 results.push({
31446 userid: user.userId.userid,
31447 keyid: signature.keyid,
31448 valid: signature.valid
31449 });
31450 });
31451 }));
31452 return results;
31453 }
31454
31455 /**
31456 * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
31457 * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
31458 * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA
31459 * @param {String} options.curve (optional) Elliptic curve for ECC keys
31460 * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys
31461 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
31462 * @param {Date} options.date (optional) Override the creation date of the key and the key signatures
31463 * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
31464 * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}
31465 * @returns {Key}
31466 * @async
31467 */
31468 async addSubkey(options = {}) {
31469 const config = { ...defaultConfig, ...options.config };
31470 if (!this.isPrivate()) {
31471 throw new Error("Cannot add a subkey to a public key");
31472 }
31473 if (options.passphrase) {
31474 throw new Error("Subkey could not be encrypted here, please encrypt whole key");
31475 }
31476 if (options.rsaBits < config.minRsaBits) {
31477 throw new Error(`rsaBits should be at least ${config.minRsaBits}, got: ${options.rsaBits}`);
31478 }
31479 const secretKeyPacket = this.primaryKey;
31480 if (secretKeyPacket.isDummy()) {
31481 throw new Error("Cannot add subkey to gnu-dummy primary key");
31482 }
31483 if (!secretKeyPacket.isDecrypted()) {
31484 throw new Error("Key is not decrypted");
31485 }
31486 const defaultOptions = secretKeyPacket.getAlgorithmInfo();
31487 defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA
31488 defaultOptions.rsaBits = defaultOptions.bits || 4096;
31489 defaultOptions.curve = defaultOptions.curve || 'curve25519';
31490 options = sanitizeKeyOptions(options, defaultOptions);
31491 const keyPacket = await generateSecretSubkey(options);
31492 const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config);
31493 const packetList = this.toPacketlist();
31494 packetList.push(keyPacket);
31495 packetList.push(bindingSignature);
31496 return new Key(packetList);
31497 }
31498}
31499
31500['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
31501 Key.prototype[name] =
31502 SubKey.prototype[name];
31503});
31504
31505// OpenPGP.js - An OpenPGP implementation in javascript
31506
31507/**
31508 * Generates a new OpenPGP key. Supports RSA and ECC keys.
31509 * By default, primary and subkeys will be of same type.
31510 * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA
31511 * @param {String} options.curve Elliptic curve for ECC keys
31512 * @param {Integer} options.rsaBits Number of bits for RSA keys
31513 * @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' }
31514 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
31515 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
31516 * @param {Date} options.date Creation date of the key and the key signatures
31517 * @param {Object} config - Full configuration
31518 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
31519 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
31520 * @returns {Key}
31521 * @async
31522 * @static
31523 * @private
31524 */
31525async function generate$2(options, config) {
31526 options.sign = true; // primary key is always a signing key
31527 options = sanitizeKeyOptions(options);
31528 options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
31529 let promises = [generateSecretKey(options, config)];
31530 promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
31531 return Promise.all(promises).then(packets => wrapKeyObject(packets[0], packets.slice(1), options, config));
31532}
31533
31534/**
31535 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
31536 * @param {Key} options.privateKey The private key to reformat
31537 * @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' }
31538 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
31539 * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires
31540 * @param {Date} options.date Override the creation date of the key and the key signatures
31541 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
31542 * @param {Object} config - Full configuration
31543 *
31544 * @returns {Key}
31545 * @async
31546 * @static
31547 * @private
31548 */
31549async function reformat(options, config) {
31550 options = sanitize(options);
31551
31552 if (options.privateKey.primaryKey.isDummy()) {
31553 throw new Error('Cannot reformat a gnu-dummy primary key');
31554 }
31555
31556 const isDecrypted = options.privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
31557 if (!isDecrypted) {
31558 throw new Error('Key is not decrypted');
31559 }
31560
31561 const packetlist = options.privateKey.toPacketlist();
31562 let secretKeyPacket;
31563 const secretSubkeyPackets = [];
31564 for (let i = 0; i < packetlist.length; i++) {
31565 if (packetlist[i].tag === enums.packet.secretKey) {
31566 secretKeyPacket = packetlist[i];
31567 } else if (packetlist[i].tag === enums.packet.secretSubkey) {
31568 secretSubkeyPackets.push(packetlist[i]);
31569 }
31570 }
31571 if (!secretKeyPacket) {
31572 throw new Error('Key does not contain a secret key packet');
31573 }
31574
31575 if (!options.subkeys) {
31576 options.subkeys = await Promise.all(secretSubkeyPackets.map(async secretSubkeyPacket => ({
31577 sign: await options.privateKey.getSigningKey(secretSubkeyPacket.getKeyId(), null, undefined, config).catch(() => {}) &&
31578 !await options.privateKey.getEncryptionKey(secretSubkeyPacket.getKeyId(), null, undefined, config).catch(() => {})
31579 })));
31580 }
31581
31582 if (options.subkeys.length !== secretSubkeyPackets.length) {
31583 throw new Error('Number of subkey options does not match number of subkeys');
31584 }
31585
31586 options.subkeys = options.subkeys.map(function(subkey, index) { return sanitize(options.subkeys[index], options); });
31587
31588 return wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
31589
31590 function sanitize(options, subkeyDefaults = {}) {
31591 options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
31592 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
31593 options.date = options.date || subkeyDefaults.date;
31594
31595 return options;
31596 }
31597}
31598
31599
31600async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
31601 // set passphrase protection
31602 if (options.passphrase) {
31603 await secretKeyPacket.encrypt(options.passphrase, config);
31604 }
31605
31606 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
31607 const subkeyPassphrase = options.subkeys[index].passphrase;
31608 if (subkeyPassphrase) {
31609 await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
31610 }
31611 }));
31612
31613 const packetlist = new PacketList();
31614
31615 packetlist.push(secretKeyPacket);
31616
31617 await Promise.all(options.userIds.map(async function(userId, index) {
31618 function createdPreferredAlgos(algos, configAlgo) {
31619 if (configAlgo) { // Not `uncompressed` / `plaintext`
31620 const configIndex = algos.indexOf(configAlgo);
31621 if (configIndex >= 1) { // If it is included and not in first place,
31622 algos.splice(configIndex, 1); // remove it.
31623 }
31624 if (configIndex !== 0) { // If it was included and not in first place, or wasn't included,
31625 algos.unshift(configAlgo); // add it to the front.
31626 }
31627 }
31628 return algos;
31629 }
31630
31631 const userIdPacket = UserIDPacket.fromObject(userId);
31632 const dataToSign = {};
31633 dataToSign.userId = userIdPacket;
31634 dataToSign.key = secretKeyPacket;
31635 const signaturePacket = new SignaturePacket(options.date);
31636 signaturePacket.signatureType = enums.signature.certGeneric;
31637 signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
31638 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, secretKeyPacket, undefined, undefined, config);
31639 signaturePacket.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
31640 signaturePacket.preferredSymmetricAlgorithms = createdPreferredAlgos([
31641 // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
31642 enums.symmetric.aes256,
31643 enums.symmetric.aes128,
31644 enums.symmetric.aes192
31645 ], config.encryptionCipher);
31646 if (config.aeadProtect) {
31647 signaturePacket.preferredAeadAlgorithms = createdPreferredAlgos([
31648 enums.aead.eax,
31649 enums.aead.ocb
31650 ], config.aeadMode);
31651 }
31652 signaturePacket.preferredHashAlgorithms = createdPreferredAlgos([
31653 // prefer fast asm.js implementations (SHA-256)
31654 enums.hash.sha256,
31655 enums.hash.sha512
31656 ], config.preferHashAlgorithm);
31657 signaturePacket.preferredCompressionAlgorithms = createdPreferredAlgos([
31658 enums.compression.zlib,
31659 enums.compression.zip,
31660 enums.compression.uncompressed
31661 ], config.compression);
31662 if (index === 0) {
31663 signaturePacket.isPrimaryUserID = true;
31664 }
31665 // integrity protection always enabled
31666 signaturePacket.features = [0];
31667 signaturePacket.features[0] |= enums.features.modificationDetection;
31668 if (config.aeadProtect) {
31669 signaturePacket.features[0] |= enums.features.aead;
31670 }
31671 if (config.v5Keys) {
31672 signaturePacket.features[0] |= enums.features.v5Keys;
31673 }
31674 if (options.keyExpirationTime > 0) {
31675 signaturePacket.keyExpirationTime = options.keyExpirationTime;
31676 signaturePacket.keyNeverExpires = false;
31677 }
31678 await signaturePacket.sign(secretKeyPacket, dataToSign);
31679
31680 return { userIdPacket, signaturePacket };
31681 })).then(list => {
31682 list.forEach(({ userIdPacket, signaturePacket }) => {
31683 packetlist.push(userIdPacket);
31684 packetlist.push(signaturePacket);
31685 });
31686 });
31687
31688 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
31689 const subkeyOptions = options.subkeys[index];
31690 const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
31691 return { secretSubkeyPacket, subkeySignaturePacket };
31692 })).then(packets => {
31693 packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
31694 packetlist.push(secretSubkeyPacket);
31695 packetlist.push(subkeySignaturePacket);
31696 });
31697 });
31698
31699 // Add revocation signature packet for creating a revocation certificate.
31700 // This packet should be removed before returning the key.
31701 const dataToSign = { key: secretKeyPacket };
31702 packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, {
31703 signatureType: enums.signature.keyRevocation,
31704 reasonForRevocationFlag: enums.reasonForRevocation.noReason,
31705 reasonForRevocationString: ''
31706 }, options.date, undefined, undefined, undefined, config));
31707
31708 // set passphrase protection
31709 if (options.passphrase) {
31710 secretKeyPacket.clearPrivateParams();
31711 }
31712
31713 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
31714 const subkeyPassphrase = options.subkeys[index].passphrase;
31715 if (subkeyPassphrase) {
31716 secretSubkeyPacket.clearPrivateParams();
31717 }
31718 }));
31719
31720 return new Key(packetlist);
31721}
31722
31723/**
31724 * Reads an (optionally armored) OpenPGP key and returns a key object
31725 * @param {Object} options
31726 * @param {String | ReadableStream<String>} [options.armoredKey] - Armored key to be parsed
31727 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryKey] - Binary key to be parsed
31728 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31729 * @returns {Key} Key object.
31730 * @async
31731 * @static
31732 */
31733async function readKey({ armoredKey, binaryKey, config }) {
31734 config = { ...defaultConfig, ...config };
31735 if (!armoredKey && !binaryKey) {
31736 throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
31737 }
31738 let input;
31739 if (armoredKey) {
31740 const { type, data } = await unarmor(armoredKey, config);
31741 if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
31742 throw new Error('Armored text not of type key');
31743 }
31744 input = data;
31745 } else {
31746 input = binaryKey;
31747 }
31748 const packetlist = new PacketList();
31749 await packetlist.read(input, allowedKeyPackets, undefined, config);
31750 return new Key(packetlist);
31751}
31752
31753/**
31754 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
31755 * @param {Object} options
31756 * @param {String | ReadableStream<String>} [options.armoredKeys] - Armored keys to be parsed
31757 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryKeys] - Binary keys to be parsed
31758 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31759 * @returns {Array<Key>} Key objects.
31760 * @async
31761 * @static
31762 */
31763async function readKeys({ armoredKeys, binaryKeys, config }) {
31764 config = { ...defaultConfig, ...config };
31765 let input = armoredKeys || binaryKeys;
31766 if (!input) {
31767 throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
31768 }
31769 if (armoredKeys) {
31770 const { type, data } = await unarmor(armoredKeys, config);
31771 if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
31772 throw new Error('Armored text not of type key');
31773 }
31774 input = data;
31775 }
31776 const keys = [];
31777 const packetlist = new PacketList();
31778 await packetlist.read(input, allowedKeyPackets, undefined, config);
31779 const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
31780 if (keyIndex.length === 0) {
31781 throw new Error('No key packet found');
31782 }
31783 for (let i = 0; i < keyIndex.length; i++) {
31784 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
31785 const newKey = new Key(oneKeyList);
31786 keys.push(newKey);
31787 }
31788 return keys;
31789}
31790
31791// GPG4Browsers - An OpenPGP implementation in javascript
31792
31793
31794/**
31795 * Class that represents an OpenPGP message.
31796 * Can be an encrypted message, signed message, compressed message or literal message
31797 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
31798 */
31799class Message {
31800 /**
31801 * @param {PacketList} packetlist - The packets that form this message
31802 */
31803 constructor(packetlist) {
31804 this.packets = packetlist || new PacketList();
31805 }
31806
31807 /**
31808 * Returns the key IDs of the keys to which the session key is encrypted
31809 * @returns {Array<module:type/keyid~Keyid>} Array of keyid objects.
31810 */
31811 getEncryptionKeyIds() {
31812 const keyIds = [];
31813 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
31814 pkESKeyPacketlist.forEach(function(packet) {
31815 keyIds.push(packet.publicKeyId);
31816 });
31817 return keyIds;
31818 }
31819
31820 /**
31821 * Returns the key IDs of the keys that signed the message
31822 * @returns {Array<module:type/keyid~Keyid>} Array of keyid objects.
31823 */
31824 getSigningKeyIds() {
31825 const keyIds = [];
31826 const msg = this.unwrapCompressed();
31827 // search for one pass signatures
31828 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
31829 onePassSigList.forEach(function(packet) {
31830 keyIds.push(packet.issuerKeyId);
31831 });
31832 // if nothing found look for signature packets
31833 if (!keyIds.length) {
31834 const signatureList = msg.packets.filterByTag(enums.packet.signature);
31835 signatureList.forEach(function(packet) {
31836 keyIds.push(packet.issuerKeyId);
31837 });
31838 }
31839 return keyIds;
31840 }
31841
31842 /**
31843 * Decrypt the message. Either a private key, a session key, or a password must be specified.
31844 * @param {Array<Key>} [privateKeys] - Private keys with decrypted secret data
31845 * @param {Array<String>} [passwords] - Passwords used to decrypt
31846 * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
31847 * @param {Boolean} [streaming] - Whether to process data as a stream
31848 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31849 * @returns {Message} New message with decrypted content.
31850 * @async
31851 */
31852 async decrypt(privateKeys, passwords, sessionKeys, streaming, config = defaultConfig) {
31853 const keyObjs = sessionKeys || await this.decryptSessionKeys(privateKeys, passwords, config);
31854
31855 const symEncryptedPacketlist = this.packets.filterByTag(
31856 enums.packet.symmetricallyEncryptedData,
31857 enums.packet.symEncryptedIntegrityProtectedData,
31858 enums.packet.AEADEncryptedData
31859 );
31860
31861 if (symEncryptedPacketlist.length === 0) {
31862 return this;
31863 }
31864
31865 const symEncryptedPacket = symEncryptedPacketlist[0];
31866 let exception = null;
31867 const decryptedPromise = Promise.all(keyObjs.map(async keyObj => {
31868 if (!keyObj || !util.isUint8Array(keyObj.data) || !util.isString(keyObj.algorithm)) {
31869 throw new Error('Invalid session key for decryption.');
31870 }
31871
31872 try {
31873 await symEncryptedPacket.decrypt(keyObj.algorithm, keyObj.data, streaming, config);
31874 } catch (e) {
31875 util.printDebugError(e);
31876 exception = e;
31877 }
31878 }));
31879 // We don't await stream.cancel here because it only returns when the other copy is canceled too.
31880 stream.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
31881 symEncryptedPacket.encrypted = null;
31882 await decryptedPromise;
31883
31884 if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
31885 throw exception || new Error('Decryption failed.');
31886 }
31887
31888 const resultMsg = new Message(symEncryptedPacket.packets);
31889 symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
31890
31891 return resultMsg;
31892 }
31893
31894 /**
31895 * Decrypt encrypted session keys either with private keys or passwords.
31896 * @param {Array<Key>} [privateKeys] - Private keys with decrypted secret data
31897 * @param {Array<String>} [passwords] - Passwords used to decrypt
31898 * @param {Object} [config] - Full configuration, defaults to openpgp.config
31899 * @returns {Promise<Array<{ data: Uint8Array,
31900 algorithm: String }>>} array of object with potential sessionKey, algorithm pairs
31901 * @async
31902 */
31903 async decryptSessionKeys(privateKeys, passwords, config = defaultConfig) {
31904 let keyPackets = [];
31905
31906 let exception;
31907 if (passwords) {
31908 const symESKeyPacketlist = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
31909 if (!symESKeyPacketlist) {
31910 throw new Error('No symmetrically encrypted session key packet found.');
31911 }
31912 await Promise.all(passwords.map(async function(password, i) {
31913 let packets;
31914 if (i) {
31915 packets = new PacketList();
31916 await packets.read(symESKeyPacketlist.write(), { SymEncryptedSessionKeyPacket });
31917 } else {
31918 packets = symESKeyPacketlist;
31919 }
31920 await Promise.all(packets.map(async function(keyPacket) {
31921 try {
31922 await keyPacket.decrypt(password);
31923 keyPackets.push(keyPacket);
31924 } catch (err) {
31925 util.printDebugError(err);
31926 }
31927 }));
31928 }));
31929 } else if (privateKeys) {
31930 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
31931 if (!pkESKeyPacketlist) {
31932 throw new Error('No public key encrypted session key packet found.');
31933 }
31934 await Promise.all(pkESKeyPacketlist.map(async function(keyPacket) {
31935 await Promise.all(privateKeys.map(async function(privateKey) {
31936 let algos = [
31937 enums.symmetric.aes256, // Old OpenPGP.js default fallback
31938 enums.symmetric.aes128, // RFC4880bis fallback
31939 enums.symmetric.tripledes, // RFC4880 fallback
31940 enums.symmetric.cast5 // Golang OpenPGP fallback
31941 ];
31942 try {
31943 const primaryUser = await privateKey.getPrimaryUser(undefined, undefined, config); // TODO: Pass userId from somewhere.
31944 if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
31945 algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
31946 }
31947 } catch (e) {}
31948
31949 // do not check key expiration to allow decryption of old messages
31950 const privateKeyPackets = (await privateKey.getDecryptionKeys(keyPacket.publicKeyId, null, undefined, config)).map(key => key.keyPacket);
31951 await Promise.all(privateKeyPackets.map(async function(privateKeyPacket) {
31952 if (!privateKeyPacket || privateKeyPacket.isDummy()) {
31953 return;
31954 }
31955 if (!privateKeyPacket.isDecrypted()) {
31956 throw new Error('Private key is not decrypted.');
31957 }
31958 try {
31959 await keyPacket.decrypt(privateKeyPacket);
31960 if (!algos.includes(enums.write(enums.symmetric, keyPacket.sessionKeyAlgorithm))) {
31961 throw new Error('A non-preferred symmetric algorithm was used.');
31962 }
31963 keyPackets.push(keyPacket);
31964 } catch (err) {
31965 util.printDebugError(err);
31966 exception = err;
31967 }
31968 }));
31969 }));
31970 stream.cancel(keyPacket.encrypted); // Don't keep copy of encrypted data in memory.
31971 keyPacket.encrypted = null;
31972 }));
31973 } else {
31974 throw new Error('No key or password specified.');
31975 }
31976
31977 if (keyPackets.length) {
31978 // Return only unique session keys
31979 if (keyPackets.length > 1) {
31980 const seen = {};
31981 keyPackets = keyPackets.filter(function(item) {
31982 const k = item.sessionKeyAlgorithm + util.uint8ArrayToStr(item.sessionKey);
31983 if (seen.hasOwnProperty(k)) {
31984 return false;
31985 }
31986 seen[k] = true;
31987 return true;
31988 });
31989 }
31990
31991 return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }));
31992 }
31993 throw exception || new Error('Session key decryption failed.');
31994 }
31995
31996 /**
31997 * Get literal data that is the body of the message
31998 * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
31999 */
32000 getLiteralData() {
32001 const msg = this.unwrapCompressed();
32002 const literal = msg.packets.findPacket(enums.packet.literalData);
32003 return (literal && literal.getBytes()) || null;
32004 }
32005
32006 /**
32007 * Get filename from literal data packet
32008 * @returns {(String|null)} Filename of literal data packet as string.
32009 */
32010 getFilename() {
32011 const msg = this.unwrapCompressed();
32012 const literal = msg.packets.findPacket(enums.packet.literalData);
32013 return (literal && literal.getFilename()) || null;
32014 }
32015
32016 /**
32017 * Get literal data as text
32018 * @returns {(String|null)} Literal body of the message interpreted as text.
32019 */
32020 getText() {
32021 const msg = this.unwrapCompressed();
32022 const literal = msg.packets.findPacket(enums.packet.literalData);
32023 if (literal) {
32024 return literal.getText();
32025 }
32026 return null;
32027 }
32028
32029 /**
32030 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.
32031 * @param {Array<Key>} [keys] - Public key(s) to select algorithm preferences for
32032 * @param {Date} [date] - Date to select algorithm preferences at
32033 * @param {Array<Object>} [userIds] - User IDs to select algorithm preferences for
32034 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32035 * @returns {{ data: Uint8Array, algorithm: String }} Object with session key data and algorithm.
32036 * @async
32037 */
32038 static async generateSessionKey(keys = [], date = new Date(), userIds = [], config = defaultConfig) {
32039 const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', keys, date, userIds, config));
32040 const aeadAlgorithm = config.aeadProtect && await isAeadSupported(keys, date, userIds, config) ?
32041 enums.read(enums.aead, await getPreferredAlgo('aead', keys, date, userIds, config)) :
32042 undefined;
32043 const sessionKeyData = await mod.generateSessionKey(algorithm);
32044 return { data: sessionKeyData, algorithm, aeadAlgorithm };
32045 }
32046
32047 /**
32048 * Encrypt the message either with public keys, passwords, or both at once.
32049 * @param {Array<Key>} [keys] - Public key(s) for message encryption
32050 * @param {Array<String>} [passwords] - Password(s) for message encryption
32051 * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
32052 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
32053 * @param {Array<module:type/keyid~Keyid>} [encryptionKeyIds] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i]
32054 * @param {Date} [date] - Override the creation date of the literal package
32055 * @param {Array<Object>} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
32056 * @param {Boolean} [streaming] - Whether to process data as a stream
32057 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32058 * @returns {Message} New message with encrypted content.
32059 * @async
32060 */
32061 async encrypt(keys, passwords, sessionKey, wildcard = false, encryptionKeyIds = [], date = new Date(), userIds = [], streaming, config = defaultConfig) {
32062 if (sessionKey) {
32063 if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
32064 throw new Error('Invalid session key for encryption.');
32065 }
32066 } else if (keys && keys.length) {
32067 sessionKey = await Message.generateSessionKey(keys, date, userIds, config);
32068 } else if (passwords && passwords.length) {
32069 sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);
32070 } else {
32071 throw new Error('No keys, passwords, or session key provided.');
32072 }
32073
32074 const { data: sessionKeyData, algorithm, aeadAlgorithm } = sessionKey;
32075
32076 const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, keys, passwords, wildcard, encryptionKeyIds, date, userIds, config);
32077
32078 let symEncryptedPacket;
32079 if (aeadAlgorithm) {
32080 symEncryptedPacket = new AEADEncryptedDataPacket();
32081 symEncryptedPacket.aeadAlgorithm = aeadAlgorithm;
32082 } else {
32083 symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();
32084 }
32085 symEncryptedPacket.packets = this.packets;
32086
32087 await symEncryptedPacket.encrypt(algorithm, sessionKeyData, streaming, config);
32088
32089 msg.packets.push(symEncryptedPacket);
32090 symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
32091 return msg;
32092 }
32093
32094 /**
32095 * Encrypt a session key either with public keys, passwords, or both at once.
32096 * @param {Uint8Array} sessionKey - session key for encryption
32097 * @param {String} algorithm - session key algorithm
32098 * @param {String} [aeadAlgorithm] - Aead algorithm, e.g. 'eax' or 'ocb'
32099 * @param {Array<Key>} [publicKeys] - Public key(s) for message encryption
32100 * @param {Array<String>} [passwords] - For message encryption
32101 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
32102 * @param {Array<module:type/keyid~Keyid>} [encryptionKeyIds] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i]
32103 * @param {Date} [date] - Override the date
32104 * @param {Array} [userIds] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
32105 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32106 * @returns {Message} New message with encrypted content.
32107 * @async
32108 */
32109 static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, encryptionKeyIds = [], date = new Date(), userIds = [], config = defaultConfig) {
32110 const packetlist = new PacketList();
32111
32112 if (publicKeys) {
32113 const results = await Promise.all(publicKeys.map(async function(publicKey, i) {
32114 const encryptionKey = await publicKey.getEncryptionKey(encryptionKeyIds[i], date, userIds, config);
32115 const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();
32116 pkESKeyPacket.publicKeyId = wildcard ? Keyid.wildcard() : encryptionKey.getKeyId();
32117 pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
32118 pkESKeyPacket.sessionKey = sessionKey;
32119 pkESKeyPacket.sessionKeyAlgorithm = algorithm;
32120 await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
32121 delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
32122 return pkESKeyPacket;
32123 }));
32124 packetlist.concat(results);
32125 }
32126 if (passwords) {
32127 const testDecrypt = async function(keyPacket, password) {
32128 try {
32129 await keyPacket.decrypt(password);
32130 return 1;
32131 } catch (e) {
32132 return 0;
32133 }
32134 };
32135
32136 const sum = (accumulator, currentValue) => accumulator + currentValue;
32137
32138 const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {
32139 const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);
32140 symEncryptedSessionKeyPacket.sessionKey = sessionKey;
32141 symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
32142 if (aeadAlgorithm) {
32143 symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
32144 }
32145 await symEncryptedSessionKeyPacket.encrypt(password, config);
32146
32147 if (config.passwordCollisionCheck) {
32148 const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
32149 if (results.reduce(sum) !== 1) {
32150 return encryptPassword(sessionKey, algorithm, password);
32151 }
32152 }
32153
32154 delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
32155 return symEncryptedSessionKeyPacket;
32156 };
32157
32158 const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));
32159 packetlist.concat(results);
32160 }
32161
32162 return new Message(packetlist);
32163 }
32164
32165 /**
32166 * Sign the message (the literal data packet of the message)
32167 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
32168 * @param {Signature} [signature] - Any existing detached signature to add to the message
32169 * @param {Array<module:type/keyid~Keyid>} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
32170 * @param {Date} [date] - Override the creation time of the signature
32171 * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
32172 * @param {Boolean} [streaming] - Whether to process data as a stream
32173 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32174 * @returns {Message} New message with signed content.
32175 * @async
32176 */
32177 async sign(privateKeys = [], signature = null, signingKeyIds = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) {
32178 const packetlist = new PacketList();
32179
32180 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
32181 if (!literalDataPacket) {
32182 throw new Error('No literal data packet to sign.');
32183 }
32184
32185 let i;
32186 let existingSigPacketlist;
32187 // If data packet was created from Uint8Array, use binary, otherwise use text
32188 const signatureType = literalDataPacket.text === null ?
32189 enums.signature.binary : enums.signature.text;
32190
32191 if (signature) {
32192 existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
32193 for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
32194 const signaturePacket = existingSigPacketlist[i];
32195 const onePassSig = new OnePassSignaturePacket();
32196 onePassSig.signatureType = signaturePacket.signatureType;
32197 onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
32198 onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
32199 onePassSig.issuerKeyId = signaturePacket.issuerKeyId;
32200 if (!privateKeys.length && i === 0) {
32201 onePassSig.flags = 1;
32202 }
32203 packetlist.push(onePassSig);
32204 }
32205 }
32206
32207 await Promise.all(Array.from(privateKeys).reverse().map(async function (privateKey, i) {
32208 if (privateKey.isPublic()) {
32209 throw new Error('Need private key for signing');
32210 }
32211 const signingKeyId = signingKeyIds[privateKeys.length - 1 - i];
32212 const signingKey = await privateKey.getSigningKey(signingKeyId, date, userIds, config);
32213 const onePassSig = new OnePassSignaturePacket();
32214 onePassSig.signatureType = signatureType;
32215 onePassSig.hashAlgorithm = await getPreferredHashAlgo$1(privateKey, signingKey.keyPacket, date, userIds, config);
32216 onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
32217 onePassSig.issuerKeyId = signingKey.getKeyId();
32218 if (i === privateKeys.length - 1) {
32219 onePassSig.flags = 1;
32220 }
32221 return onePassSig;
32222 })).then(onePassSignatureList => {
32223 onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
32224 });
32225
32226 packetlist.push(literalDataPacket);
32227 packetlist.concat(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, false, streaming, config));
32228
32229 return new Message(packetlist);
32230 }
32231
32232 /**
32233 * Compresses the message (the literal and -if signed- signature data packets of the message)
32234 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32235 * @returns {Message} New message with compressed content.
32236 */
32237 compress(config = defaultConfig) {
32238 if (config.compression === enums.compression.uncompressed) {
32239 return this;
32240 }
32241
32242 const compressed = new CompressedDataPacket(config);
32243 compressed.packets = this.packets;
32244
32245 const packetList = new PacketList();
32246 packetList.push(compressed);
32247
32248 return new Message(packetList);
32249 }
32250
32251 /**
32252 * Create a detached signature for the message (the literal data packet of the message)
32253 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
32254 * @param {Signature} [signature] - Any existing detached signature
32255 * @param {Array<module:type/keyid~Keyid>} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
32256 * @param {Date} [date] - Override the creation time of the signature
32257 * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
32258 * @param {Boolean} [streaming] - Whether to process data as a stream
32259 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32260 * @returns {Signature} New detached signature of message content.
32261 * @async
32262 */
32263 async signDetached(privateKeys = [], signature = null, signingKeyIds = [], date = new Date(), userIds = [], streaming = false, config = defaultConfig) {
32264 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
32265 if (!literalDataPacket) {
32266 throw new Error('No literal data packet to sign.');
32267 }
32268 return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, true, streaming, config));
32269 }
32270
32271 /**
32272 * Verify message signatures
32273 * @param {Array<Key>} keys - Array of keys to verify signatures
32274 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
32275 * @param {Boolean} [streaming] - Whether to process data as a stream
32276 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32277 * @returns {Array<({keyid: module:type/keyid~Keyid, valid: Boolean})>} List of signer's keyid and validity of signature.
32278 * @async
32279 */
32280 async verify(keys, date = new Date(), streaming, config = defaultConfig) {
32281 const msg = this.unwrapCompressed();
32282 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
32283 if (literalDataList.length !== 1) {
32284 throw new Error('Can only verify message with one literal data packet.');
32285 }
32286 if (!streaming) {
32287 msg.packets.concat(await stream.readToEnd(msg.packets.stream, _ => _));
32288 }
32289 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
32290 const signatureList = msg.packets.filterByTag(enums.packet.signature);
32291 if (streaming && onePassSigList.length && !signatureList.length && msg.packets.stream) {
32292 await Promise.all(onePassSigList.map(async onePassSig => {
32293 onePassSig.correspondingSig = new Promise((resolve, reject) => {
32294 onePassSig.correspondingSigResolve = resolve;
32295 onePassSig.correspondingSigReject = reject;
32296 });
32297 onePassSig.signatureData = stream.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
32298 onePassSig.hashed = stream.readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false, streaming));
32299 onePassSig.hashed.catch(() => {});
32300 }));
32301 msg.packets.stream = stream.transformPair(msg.packets.stream, async (readable, writable) => {
32302 const reader = stream.getReader(readable);
32303 const writer = stream.getWriter(writable);
32304 try {
32305 for (let i = 0; i < onePassSigList.length; i++) {
32306 const { value: signature } = await reader.read();
32307 onePassSigList[i].correspondingSigResolve(signature);
32308 }
32309 await reader.readToEnd();
32310 await writer.ready;
32311 await writer.close();
32312 } catch (e) {
32313 onePassSigList.forEach(onePassSig => {
32314 onePassSig.correspondingSigReject(e);
32315 });
32316 await writer.abort(e);
32317 }
32318 });
32319 return createVerificationObjects(onePassSigList, literalDataList, keys, date, false, streaming, config);
32320 }
32321 return createVerificationObjects(signatureList, literalDataList, keys, date, false, streaming, config);
32322 }
32323
32324 /**
32325 * Verify detached message signature
32326 * @param {Array<Key>} keys - Array of keys to verify signatures
32327 * @param {Signature} signature
32328 * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
32329 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32330 * @returns {Array<({keyid: module:type/keyid~Keyid, valid: Boolean})>} List of signer's keyid and validity of signature.
32331 * @async
32332 */
32333 verifyDetached(signature, keys, date = new Date(), streaming, config = defaultConfig) {
32334 const msg = this.unwrapCompressed();
32335 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
32336 if (literalDataList.length !== 1) {
32337 throw new Error('Can only verify message with one literal data packet.');
32338 }
32339 const signatureList = signature.packets;
32340 return createVerificationObjects(signatureList, literalDataList, keys, date, true, undefined, config);
32341 }
32342
32343 /**
32344 * Unwrap compressed message
32345 * @returns {Message} Message Content of compressed message.
32346 */
32347 unwrapCompressed() {
32348 const compressed = this.packets.filterByTag(enums.packet.compressedData);
32349 if (compressed.length) {
32350 return new Message(compressed[0].packets);
32351 }
32352 return this;
32353 }
32354
32355 /**
32356 * Append signature to unencrypted message object
32357 * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
32358 */
32359 async appendSignature(detachedSignature) {
32360 await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, { SignaturePacket });
32361 }
32362
32363 /**
32364 * Returns binary encoded message
32365 * @returns {ReadableStream<Uint8Array>} Binary message.
32366 */
32367 write() {
32368 return this.packets.write();
32369 }
32370
32371 /**
32372 * Returns ASCII armored text of message
32373 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32374 * @returns {ReadableStream<String>} ASCII armor.
32375 */
32376 armor(config = defaultConfig) {
32377 return armor(enums.armor.message, this.write(), null, null, null, config);
32378 }
32379
32380 /**
32381 * Creates new message object from text.
32382 * @param {String | ReadableStream<String>} text - The message contents
32383 * @param {String} [filename=""] - Name of the file (if any)
32384 * @param {Date} [date=current date] - Date of the message, or modification date of the file
32385 * @param {'utf8'|'binary'|'text'|'mime'} [type='utf8'] - Data packet type
32386 * @returns {Message} New message object.
32387 * @static
32388 */
32389 static fromText(text, filename, date = new Date(), type = 'utf8') {
32390 const streamType = util.isStream(text);
32391 if (streamType === 'node') {
32392 text = stream.nodeToWeb(text);
32393 }
32394 const literalDataPacket = new LiteralDataPacket(date);
32395 // text will be converted to UTF8
32396 literalDataPacket.setText(text, type);
32397 if (filename !== undefined) {
32398 literalDataPacket.setFilename(filename);
32399 }
32400 const literalDataPacketlist = new PacketList();
32401 literalDataPacketlist.push(literalDataPacket);
32402 const message = new Message(literalDataPacketlist);
32403 message.fromStream = streamType;
32404 return message;
32405 }
32406
32407 /**
32408 * Creates new message object from binary data.
32409 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The message contents
32410 * @param {String} [filename=""] - Name of the file (if any)
32411 * @param {Date} [date=current date] - Date of the message, or modification date of the file
32412 * @param {'utf8'|'binary'|'text'|'mime'} [type='binary'] - Data packet type
32413 * @returns {Message} New message object.
32414 * @static
32415 */
32416 static fromBinary(bytes, filename, date = new Date(), type = 'binary') {
32417 const streamType = util.isStream(bytes);
32418 if (!util.isUint8Array(bytes) && !streamType) {
32419 throw new Error('Data must be in the form of a Uint8Array or Stream');
32420 }
32421 if (streamType === 'node') {
32422 bytes = stream.nodeToWeb(bytes);
32423 }
32424
32425 const literalDataPacket = new LiteralDataPacket(date);
32426 literalDataPacket.setBytes(bytes, type);
32427 if (filename !== undefined) {
32428 literalDataPacket.setFilename(filename);
32429 }
32430 const literalDataPacketlist = new PacketList();
32431 literalDataPacketlist.push(literalDataPacket);
32432 const message = new Message(literalDataPacketlist);
32433 message.fromStream = streamType;
32434 return message;
32435 }
32436}
32437
32438/**
32439 * Create signature packets for the message
32440 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
32441 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
32442 * @param {Signature} [signature] - Any existing detached signature to append
32443 * @param {Array<module:type/keyid~Keyid>} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
32444 * @param {Date} [date] - Override the creationtime of the signature
32445 * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
32446 * @param {Boolean} [detached] - Whether to create detached signature packets
32447 * @param {Boolean} [streaming] - Whether to process data as a stream
32448 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32449 * @returns {PacketList} List of signature packets.
32450 * @async
32451 * @private
32452 */
32453async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, signingKeyIds = [], date = new Date(), userIds = [], detached = false, streaming = false, config = defaultConfig) {
32454 const packetlist = new PacketList();
32455
32456 // If data packet was created from Uint8Array, use binary, otherwise use text
32457 const signatureType = literalDataPacket.text === null ?
32458 enums.signature.binary : enums.signature.text;
32459
32460 await Promise.all(privateKeys.map(async (privateKey, i) => {
32461 const userId = userIds[i];
32462 if (privateKey.isPublic()) {
32463 throw new Error('Need private key for signing');
32464 }
32465 const signingKey = await privateKey.getSigningKey(signingKeyIds[i], date, userId, config);
32466 return createSignaturePacket(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId, detached, streaming, config);
32467 })).then(signatureList => {
32468 signatureList.forEach(signaturePacket => packetlist.push(signaturePacket));
32469 });
32470
32471 if (signature) {
32472 const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
32473 packetlist.concat(existingSigPacketlist);
32474 }
32475 return packetlist;
32476}
32477
32478/**
32479 * Create object containing signer's keyid and validity of signature
32480 * @param {SignaturePacket} signature - Signature packets
32481 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
32482 * @param {Array<Key>} keys - Array of keys to verify signatures
32483 * @param {Date} date - Verify the signature against the given date,
32484 * i.e. check signature creation time < date < expiration time
32485 * @param {Boolean} [detached] - Whether to verify detached signature packets
32486 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32487 * @returns {Promise<Array<{keyid: module:type/keyid~Keyid,
32488 * valid: Boolean|null}>>} list of signer's keyid and validity of signature
32489 * @async
32490 * @private
32491 */
32492async function createVerificationObject(signature, literalDataList, keys, date = new Date(), detached = false, streaming = false, config = defaultConfig) {
32493 let primaryKey = null;
32494 let signingKey = null;
32495 await Promise.all(keys.map(async function(key) {
32496 // Look for the unique key that matches issuerKeyId of signature
32497 try {
32498 signingKey = await key.getSigningKey(signature.issuerKeyId, null, undefined, config);
32499 primaryKey = key;
32500 } catch (e) {}
32501 }));
32502
32503 const signaturePacket = signature.correspondingSig || signature;
32504 const verifiedSig = {
32505 keyid: signature.issuerKeyId,
32506 verified: (async () => {
32507 if (!signingKey) {
32508 return null;
32509 }
32510 await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0], detached, streaming, config);
32511 const sig = await signaturePacket;
32512 if (sig.isExpired(date) || !(
32513 sig.created >= signingKey.getCreationTime() &&
32514 sig.created < await (signingKey === primaryKey ?
32515 signingKey.getExpirationTime(undefined, undefined, undefined, config) :
32516 signingKey.getExpirationTime(primaryKey, date, undefined, config)
32517 )
32518 )) {
32519 throw new Error('Signature is expired');
32520 }
32521 return true;
32522 })(),
32523 signature: (async () => {
32524 const sig = await signaturePacket;
32525 const packetlist = new PacketList();
32526 packetlist.push(sig);
32527 return new Signature(packetlist);
32528 })()
32529 };
32530
32531 // Mark potential promise rejections as "handled". This is needed because in
32532 // some cases, we reject them before the user has a reasonable chance to
32533 // handle them (e.g. `await readToEnd(result.data); await result.verified` and
32534 // the data stream errors).
32535 verifiedSig.signature.catch(() => {});
32536 verifiedSig.verified.catch(() => {});
32537
32538 return verifiedSig;
32539}
32540
32541/**
32542 * Create list of objects containing signer's keyid and validity of signature
32543 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
32544 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
32545 * @param {Array<Key>} keys - Array of keys to verify signatures
32546 * @param {Date} date - Verify the signature against the given date,
32547 * i.e. check signature creation time < date < expiration time
32548 * @param {Boolean} [detached] - Whether to verify detached signature packets
32549 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32550 * @returns {Promise<Array<{keyid: module:type/keyid~Keyid,
32551 * valid: Boolean}>>} list of signer's keyid and validity of signature
32552 * @async
32553 * @private
32554 */
32555async function createVerificationObjects(signatureList, literalDataList, keys, date = new Date(), detached = false, streaming = false, config = defaultConfig) {
32556 return Promise.all(signatureList.filter(function(signature) {
32557 return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
32558 }).map(async function(signature) {
32559 return createVerificationObject(signature, literalDataList, keys, date, detached, streaming, config);
32560 }));
32561}
32562
32563/**
32564 * Reads an (optionally armored) OpenPGP message and returns a Message object
32565 * @param {Object} options
32566 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
32567 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
32568 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32569 * @returns {Message} New message object.
32570 * @async
32571 * @static
32572 */
32573async function readMessage({ armoredMessage, binaryMessage, config }) {
32574 config = { ...defaultConfig, ...config };
32575 let input = armoredMessage || binaryMessage;
32576 if (!input) {
32577 throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
32578 }
32579 const streamType = util.isStream(input);
32580 if (streamType === 'node') {
32581 input = stream.nodeToWeb(input);
32582 }
32583 if (armoredMessage) {
32584 const { type, data } = await unarmor(input, config);
32585 if (type !== enums.armor.message) {
32586 throw new Error('Armored text not of type message');
32587 }
32588 input = data;
32589 }
32590 const packetlist = new PacketList();
32591 await packetlist.read(input, {
32592 LiteralDataPacket,
32593 CompressedDataPacket,
32594 AEADEncryptedDataPacket,
32595 SymEncryptedIntegrityProtectedDataPacket,
32596 SymmetricallyEncryptedDataPacket,
32597 PublicKeyEncryptedSessionKeyPacket,
32598 SymEncryptedSessionKeyPacket,
32599 OnePassSignaturePacket,
32600 SignaturePacket
32601 }, streamType, config);
32602 const message = new Message(packetlist);
32603 message.fromStream = streamType;
32604 return message;
32605}
32606
32607// GPG4Browsers - An OpenPGP implementation in javascript
32608
32609/**
32610 * Class that represents an OpenPGP cleartext signed message.
32611 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
32612 */
32613class CleartextMessage {
32614 /**
32615 * @param {String} text - The cleartext of the signed message
32616 * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
32617 */
32618 constructor(text, signature) {
32619 // normalize EOL to canonical form <CR><LF>
32620 this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
32621 if (signature && !(signature instanceof Signature)) {
32622 throw new Error('Invalid signature input');
32623 }
32624 this.signature = signature || new Signature(new PacketList());
32625 }
32626
32627 /**
32628 * Returns the key IDs of the keys that signed the cleartext message
32629 * @returns {Array<module:type/keyid~Keyid>} Array of keyid objects.
32630 */
32631 getSigningKeyIds() {
32632 const keyIds = [];
32633 const signatureList = this.signature.packets;
32634 signatureList.forEach(function(packet) {
32635 keyIds.push(packet.issuerKeyId);
32636 });
32637 return keyIds;
32638 }
32639
32640 /**
32641 * Sign the cleartext message
32642 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
32643 * @param {Signature} [signature] - Any existing detached signature
32644 * @param {Array<module:type/keyid~Keyid>} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
32645 * @param {Date} [date] - The creation time of the signature that should be created
32646 * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
32647 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32648 * @returns {CleartextMessage} New cleartext message with signed content.
32649 * @async
32650 */
32651 async sign(privateKeys, signature = null, signingKeyIds = [], date = new Date(), userIds = [], config = defaultConfig) {
32652 return new CleartextMessage(this.text, await this.signDetached(privateKeys, signature, signingKeyIds, date, userIds, config));
32653 }
32654
32655 /**
32656 * Sign the cleartext message
32657 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
32658 * @param {Signature} [signature] - Any existing detached signature
32659 * @param {Array<module:type/keyid~Keyid>} [signingKeyIds] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
32660 * @param {Date} [date] - The creation time of the signature that should be created
32661 * @param {Array} [userIds] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
32662 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32663 * @returns {Signature} New detached signature of message content.
32664 * @async
32665 */
32666 async signDetached(privateKeys, signature = null, signingKeyIds = [], date = new Date(), userIds = [], config = defaultConfig) {
32667 const literalDataPacket = new LiteralDataPacket();
32668 literalDataPacket.setText(this.text);
32669
32670 return new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIds, date, userIds, true, undefined, config));
32671 }
32672
32673 /**
32674 * Verify signatures of cleartext signed message
32675 * @param {Array<Key>} keys - Array of keys to verify signatures
32676 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
32677 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32678 * @returns {Array<{keyid: module:type/keyid~Keyid, valid: Boolean}>} List of signer's keyid and validity of signature.
32679 * @async
32680 */
32681 verify(keys, date = new Date(), config = defaultConfig) {
32682 return this.verifyDetached(this.signature, keys, date, config);
32683 }
32684
32685 /**
32686 * Verify signatures of cleartext signed message
32687 * @param {Array<Key>} keys - Array of keys to verify signatures
32688 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
32689 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32690 * @returns {Array<{keyid: module:type/keyid~Keyid, valid: Boolean}>} List of signer's keyid and validity of signature.
32691 * @async
32692 */
32693 verifyDetached(signature, keys, date = new Date(), config = defaultConfig) {
32694 const signatureList = signature.packets;
32695 const literalDataPacket = new LiteralDataPacket();
32696 // we assume that cleartext signature is generated based on UTF8 cleartext
32697 literalDataPacket.setText(this.text);
32698 return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, undefined, config);
32699 }
32700
32701 /**
32702 * Get cleartext
32703 * @returns {String} Cleartext of message.
32704 */
32705 getText() {
32706 // normalize end of line to \n
32707 return this.text.replace(/\r\n/g, '\n');
32708 }
32709
32710 /**
32711 * Returns ASCII armored text of cleartext signed message
32712 * @param {Object} [config] - Full configuration, defaults to openpgp.config
32713 * @returns {String | ReadableStream<String>} ASCII armor.
32714 */
32715 armor(config = defaultConfig) {
32716 let hashes = this.signature.packets.map(function(packet) {
32717 return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();
32718 });
32719 hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });
32720 const body = {
32721 hash: hashes.join(),
32722 text: this.text,
32723 data: this.signature.packets.write()
32724 };
32725 return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
32726 }
32727
32728 /**
32729 * Creates a new CleartextMessage object from text
32730 * @param {String} text
32731 * @static
32732 */
32733 static fromText(text) {
32734 return new CleartextMessage(text);
32735 }
32736}
32737
32738
32739/**
32740 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
32741 * @param {Object} options
32742 * @param {String | ReadableStream<String>} options.cleartextMessage - Text to be parsed
32743 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32744 * @returns {CleartextMessage} New cleartext message object.
32745 * @async
32746 * @static
32747 */
32748async function readCleartextMessage({ cleartextMessage, config }) {
32749 config = { ...defaultConfig, ...config };
32750 if (!cleartextMessage) {
32751 throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
32752 }
32753 const input = await unarmor(cleartextMessage);
32754 if (input.type !== enums.armor.signed) {
32755 throw new Error('No cleartext signed message.');
32756 }
32757 const packetlist = new PacketList();
32758 await packetlist.read(input.data, { SignaturePacket }, undefined, config);
32759 verifyHeaders$1(input.headers, packetlist);
32760 const signature = new Signature(packetlist);
32761 return new CleartextMessage(input.text, signature);
32762}
32763
32764/**
32765 * Compare hash algorithm specified in the armor header with signatures
32766 * @param {Array<String>} headers - Armor headers
32767 * @param {PacketList} packetlist - The packetlist with signature packets
32768 * @private
32769 */
32770function verifyHeaders$1(headers, packetlist) {
32771 const checkHashAlgos = function(hashAlgos) {
32772 const check = packet => algo => packet.hashAlgorithm === algo;
32773
32774 for (let i = 0; i < packetlist.length; i++) {
32775 if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
32776 return false;
32777 }
32778 }
32779 return true;
32780 };
32781
32782 let oneHeader = null;
32783 let hashAlgos = [];
32784 headers.forEach(function(header) {
32785 oneHeader = header.match(/Hash: (.+)/); // get header value
32786 if (oneHeader) {
32787 oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
32788 oneHeader = oneHeader.split(',');
32789 oneHeader = oneHeader.map(function(hash) {
32790 hash = hash.toLowerCase();
32791 try {
32792 return enums.write(enums.hash, hash);
32793 } catch (e) {
32794 throw new Error('Unknown hash algorithm in armor header: ' + hash);
32795 }
32796 });
32797 hashAlgos = hashAlgos.concat(oneHeader);
32798 } else {
32799 throw new Error('Only "Hash" header allowed in cleartext signed message');
32800 }
32801 });
32802
32803 if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
32804 throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
32805 } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
32806 throw new Error('Hash algorithm mismatch in armor header and signature');
32807 }
32808}
32809
32810// OpenPGP.js - An OpenPGP implementation in javascript
32811
32812let toNativeReadable;
32813if (globalThis.ReadableStream) {
32814 try {
32815 toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);
32816 } catch (e) {}
32817}
32818
32819//////////////////////
32820// //
32821// Key handling //
32822// //
32823//////////////////////
32824
32825
32826/**
32827 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.
32828 * @param {Object} options
32829 * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA
32830 * @param {Object|Array<Object>} options.userIds - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
32831 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key
32832 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
32833 * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:
32834 * curve25519 (default), p256, p384, p521, secp256k1,
32835 * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
32836 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
32837 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
32838 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey, default to main key options. e.g. `[{sign: true, passphrase: '123'}]`
32839 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
32840 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32841 * @returns {Object} The generated key object in the form:
32842 * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
32843 * @async
32844 * @static
32845 */
32846function generateKey({ userIds = [], passphrase = "", type = "ecc", rsaBits = 4096, curve = "curve25519", keyExpirationTime = 0, date = new Date(), subkeys = [{}], config }) {
32847 config = { ...defaultConfig, ...config };
32848 userIds = toArray$1(userIds);
32849 const options = { userIds, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };
32850 if (type === "rsa" && rsaBits < config.minRsaBits) {
32851 throw new Error(`rsaBits should be at least ${config.minRsaBits}, got: ${rsaBits}`);
32852 }
32853
32854 return generate$2(options, config).then(async key => {
32855 const revocationCertificate = await key.getRevocationCertificate(date, config);
32856 key.revocationSignatures = [];
32857
32858 return {
32859
32860 key: key,
32861 privateKeyArmored: key.armor(config),
32862 publicKeyArmored: key.toPublic().armor(config),
32863 revocationCertificate: revocationCertificate
32864
32865 };
32866 }).catch(onError.bind(null, 'Error generating keypair'));
32867}
32868
32869/**
32870 * Reformats signature packets for a key and rewraps key object.
32871 * @param {Object} options
32872 * @param {Key} options.privateKey - Private key to reformat
32873 * @param {Object|Array<Object>} options.userIds - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
32874 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key
32875 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
32876 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32877 * @returns {Object} The generated key object in the form:
32878 * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
32879 * @async
32880 * @static
32881 */
32882function reformatKey({ privateKey, userIds = [], passphrase = "", keyExpirationTime = 0, date, config }) {
32883 config = { ...defaultConfig, ...config };
32884 userIds = toArray$1(userIds);
32885 const options = { privateKey, userIds, passphrase, keyExpirationTime, date };
32886
32887 return reformat(options, config).then(async key => {
32888 const revocationCertificate = await key.getRevocationCertificate(date, config);
32889 key.revocationSignatures = [];
32890
32891 return {
32892
32893 key: key,
32894 privateKeyArmored: key.armor(config),
32895 publicKeyArmored: key.toPublic().armor(config),
32896 revocationCertificate: revocationCertificate
32897
32898 };
32899 }).catch(onError.bind(null, 'Error reformatting keypair'));
32900}
32901
32902/**
32903 * Revokes a key. Requires either a private key or a revocation certificate.
32904 * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
32905 * @param {Object} options
32906 * @param {Key} options.key - Public or private key to revoke
32907 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
32908 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
32909 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
32910 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
32911 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32912 * @returns {Object} The revoked key object in the form:
32913 * `{ privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String }`
32914 * (if private key is passed) or `{ publicKey:Key, publicKeyArmored:String }` (otherwise)
32915 * @async
32916 * @static
32917 */
32918function revokeKey({ key, revocationCertificate, reasonForRevocation, config }) {
32919 config = { ...defaultConfig, ...config };
32920 return Promise.resolve().then(() => {
32921 if (revocationCertificate) {
32922 return key.applyRevocationCertificate(revocationCertificate, config);
32923 } else {
32924 return key.revoke(reasonForRevocation, undefined, config);
32925 }
32926 }).then(async key => {
32927 if (key.isPrivate()) {
32928 const publicKey = key.toPublic();
32929 return {
32930 privateKey: key,
32931 privateKeyArmored: key.armor(config),
32932 publicKey: publicKey,
32933 publicKeyArmored: publicKey.armor(config)
32934 };
32935 }
32936 return {
32937 publicKey: key,
32938 publicKeyArmored: key.armor(config)
32939 };
32940 }).catch(onError.bind(null, 'Error revoking key'));
32941}
32942
32943/**
32944 * Unlock a private key with the given passphrase.
32945 * This method does not change the original key.
32946 * @param {Object} options
32947 * @param {Key} options.privateKey - The private key to decrypt
32948 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
32949 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32950 * @returns {Key} The unlocked key object.
32951 * @async
32952 */
32953async function decryptKey({ privateKey, passphrase, config }) {
32954 config = { ...defaultConfig, ...config };
32955 const key = await privateKey.clone();
32956 // shallow clone is enough since the encrypted material is not changed in place by decryption
32957 key.getKeys().forEach(k => {
32958 k.keyPacket = Object.create(
32959 Object.getPrototypeOf(k.keyPacket),
32960 Object.getOwnPropertyDescriptors(k.keyPacket)
32961 );
32962 });
32963 try {
32964 await key.decrypt(passphrase, undefined, config);
32965 return key;
32966 } catch (err) {
32967 key.clearPrivateParams();
32968 return onError('Error decrypting private key', err);
32969 }
32970}
32971
32972/**
32973 * Lock a private key with the given passphrase.
32974 * This method does not change the original key.
32975 * @param {Object} options
32976 * @param {Key} options.privateKey - The private key to encrypt
32977 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
32978 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
32979 * @returns {Key} The locked key object.
32980 * @async
32981 */
32982async function encryptKey({ privateKey, passphrase, config }) {
32983 config = { ...defaultConfig, ...config };
32984 const key = await privateKey.clone();
32985 key.getKeys().forEach(k => {
32986 // shallow clone the key packets
32987 k.keyPacket = Object.create(
32988 Object.getPrototypeOf(k.keyPacket),
32989 Object.getOwnPropertyDescriptors(k.keyPacket)
32990 );
32991 if (!k.keyPacket.isDecrypted()) return;
32992 // deep clone the private params, which are cleared during encryption
32993 const privateParams = {};
32994 Object.keys(k.keyPacket.privateParams).forEach(name => {
32995 privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
32996 });
32997 k.keyPacket.privateParams = privateParams;
32998 });
32999 try {
33000 await key.encrypt(passphrase, undefined, config);
33001 return key;
33002 } catch (err) {
33003 key.clearPrivateParams();
33004 return onError('Error encrypting private key', err);
33005 }
33006}
33007
33008
33009///////////////////////////////////////////
33010// //
33011// Message encryption and decryption //
33012// //
33013///////////////////////////////////////////
33014
33015
33016/**
33017 * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords
33018 * must be specified. If private keys are specified, those will be used to sign the message.
33019 * @param {Object} options
33020 * @param {Message} options.message - Message to be encrypted as created by {@link Message.fromText} or {@link Message.fromBinary}
33021 * @param {Key|Array<Key>} [options.publicKeys] - Array of keys or single key, used to encrypt the message
33022 * @param {Key|Array<Key>} [options.privateKeys] - Private keys for signing. If omitted message will not be signed
33023 * @param {String|Array<String>} [options.passwords] - Array of passwords or a single password to encrypt the message
33024 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
33025 * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false)
33026 * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream
33027 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
33028 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
33029 * @param {Array<module:type/keyid~Keyid>} [options.signingKeyIds=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIds[i]` corresponds to `privateKeys[i]`
33030 * @param {Array<module:type/keyid~Keyid>} [options.encryptionKeyIds=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIds[i]` corresponds to `publicKeys[i]`
33031 * @param {Date} [options.date=current date] - Override the creation date of the message signature
33032 * @param {Array<Object>} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`
33033 * @param {Array<Object>} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`
33034 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33035 * @returns {String|ReadableStream<String>|NodeStream<String>|Uint8Array|ReadableStream<Uint8Array>|NodeStream<Uint8Array>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
33036 * @async
33037 * @static
33038 */
33039function encrypt$4({ message, publicKeys, privateKeys, passwords, sessionKey, armor = true, streaming = message && message.fromStream, detached = false, signature = null, wildcard = false, signingKeyIds = [], encryptionKeyIds = [], date = new Date(), fromUserIds = [], toUserIds = [], config }) {
33040 config = { ...defaultConfig, ...config };
33041 checkMessage(message); publicKeys = toArray$1(publicKeys); privateKeys = toArray$1(privateKeys); passwords = toArray$1(passwords); fromUserIds = toArray$1(fromUserIds); toUserIds = toArray$1(toUserIds);
33042 if (detached) {
33043 throw new Error("detached option has been removed from openpgp.encrypt. Separately call openpgp.sign instead. Don't forget to remove privateKeys option as well.");
33044 }
33045
33046 return Promise.resolve().then(async function() {
33047 if (!privateKeys) {
33048 privateKeys = [];
33049 }
33050 if (privateKeys.length || signature) { // sign the message only if private keys or signature is specified
33051 message = await message.sign(privateKeys, signature, signingKeyIds, date, fromUserIds, message.fromStream, config);
33052 }
33053 message = message.compress(config);
33054 message = await message.encrypt(publicKeys, passwords, sessionKey, wildcard, encryptionKeyIds, date, toUserIds, streaming, config);
33055 const data = armor ? message.armor(config) : message.write();
33056 return convertStream(data, streaming, armor ? 'utf8' : 'binary');
33057 }).catch(onError.bind(null, 'Error encrypting message'));
33058}
33059
33060/**
33061 * Decrypts a message with the user's private key, a session key or a password. Either a private key,
33062 * a session key or a password must be specified.
33063 * @param {Object} options
33064 * @param {Message} options.message - The message object with the encrypted data
33065 * @param {Key|Array<Key>} [options.privateKeys] - Private keys with decrypted secret key data or session key
33066 * @param {String|Array<String>} [options.passwords] - Passwords to decrypt the message
33067 * @param {Object|Array<Object>} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
33068 * @param {Key|Array<Key>} [options.publicKeys] - Array of public keys or single key, to verify signatures
33069 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
33070 * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
33071 * @param {Signature} [options.signature] - Detached signature for verification
33072 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
33073 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33074 * @returns {Object} Object containing decrypted and verified message in the form:
33075 *
33076 * {
33077 * data: String|ReadableStream<String>|NodeStream, (if format was 'utf8', the default)
33078 * data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if format was 'binary')
33079 * filename: String,
33080 * signatures: [
33081 * {
33082 * keyid: module:type/keyid~Keyid,
33083 * verified: Promise<Boolean>,
33084 * valid: Boolean (if streaming was false)
33085 * }, ...
33086 * ]
33087 * }
33088 * @async
33089 * @static
33090 */
33091function decrypt$4({ message, privateKeys, passwords, sessionKeys, publicKeys, format = 'utf8', streaming = message && message.fromStream, signature = null, date = new Date(), config }) {
33092 config = { ...defaultConfig, ...config };
33093 checkMessage(message); publicKeys = toArray$1(publicKeys); privateKeys = toArray$1(privateKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys);
33094
33095 return message.decrypt(privateKeys, passwords, sessionKeys, streaming, config).then(async function(decrypted) {
33096 if (!publicKeys) {
33097 publicKeys = [];
33098 }
33099
33100 const result = {};
33101 result.signatures = signature ? await decrypted.verifyDetached(signature, publicKeys, date, streaming, config) : await decrypted.verify(publicKeys, date, streaming, config);
33102 result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
33103 result.filename = decrypted.getFilename();
33104 linkStreams(result, message);
33105 result.data = await convertStream(result.data, streaming, format);
33106 if (!streaming) await prepareSignatures(result.signatures);
33107 return result;
33108 }).catch(onError.bind(null, 'Error decrypting message'));
33109}
33110
33111
33112//////////////////////////////////////////
33113// //
33114// Message signing and verification //
33115// //
33116//////////////////////////////////////////
33117
33118
33119/**
33120 * Signs a message.
33121 * @param {Object} options
33122 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
33123 * @param {Key|Array<Key>} options.privateKeys - Array of keys or single key with decrypted secret key data to sign cleartext
33124 * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false)
33125 * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
33126 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
33127 * @param {Array<module:type/keyid~Keyid>} [options.signingKeyIds=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIds[i] corresponds to privateKeys[i]
33128 * @param {Date} [options.date=current date] - Override the creation date of the signature
33129 * @param {Array<Object>} [options.fromUserIds=primary user IDs] - Array of user IDs to sign with, one per key in `privateKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`
33130 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33131 * @returns {String|ReadableStream<String>|NodeStream<String>|Uint8Array|ReadableStream<Uint8Array>|NodeStream<Uint8Array>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
33132 * @async
33133 * @static
33134 */
33135function sign$5({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, signingKeyIds = [], date = new Date(), fromUserIds = [], config }) {
33136 config = { ...defaultConfig, ...config };
33137 checkCleartextOrMessage(message);
33138 if (message instanceof CleartextMessage && !armor) throw new Error("Can't sign non-armored cleartext message");
33139 if (message instanceof CleartextMessage && detached) throw new Error("Can't sign detached cleartext message");
33140 privateKeys = toArray$1(privateKeys); fromUserIds = toArray$1(fromUserIds);
33141
33142 return Promise.resolve().then(async function() {
33143 let signature;
33144 if (message instanceof CleartextMessage) {
33145 signature = await message.sign(privateKeys, undefined, signingKeyIds, date, fromUserIds, config);
33146 } else if (detached) {
33147 signature = await message.signDetached(privateKeys, undefined, signingKeyIds, date, fromUserIds, message.fromStream, config);
33148 } else {
33149 signature = await message.sign(privateKeys, undefined, signingKeyIds, date, fromUserIds, message.fromStream, config);
33150 }
33151 signature = armor ? signature.armor(config) : signature.write();
33152 if (detached) {
33153 signature = stream.transformPair(message.packets.write(), async (readable, writable) => {
33154 await Promise.all([
33155 stream.pipe(signature, writable),
33156 stream.readToEnd(readable).catch(() => {})
33157 ]);
33158 });
33159 }
33160 return convertStream(signature, streaming, armor ? 'utf8' : 'binary');
33161 }).catch(onError.bind(null, 'Error signing message'));
33162}
33163
33164/**
33165 * Verifies signatures of cleartext signed message
33166 * @param {Object} options
33167 * @param {Key|Array<Key>} options.publicKeys - Array of publicKeys or single key, to verify signatures
33168 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
33169 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
33170 * @param {'web'|'ponyfill'|'node'|false} [options.streaming=type of stream `message` was created from, if any] - Whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
33171 * @param {Signature} [options.signature] - Detached signature for verification
33172 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
33173 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33174 * @returns {Object} Object containing verified message in the form:
33175 *
33176 * {
33177 * data: String|ReadableStream<String>|NodeStream, (if `message` was a CleartextMessage)
33178 * data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if `message` was a Message)
33179 * signatures: [
33180 * {
33181 * keyid: module:type/keyid~Keyid,
33182 * verified: Promise<Boolean>,
33183 * valid: Boolean (if `streaming` was false)
33184 * }, ...
33185 * ]
33186 * }
33187 * @async
33188 * @static
33189 */
33190function verify$5({ message, publicKeys, format = 'utf8', streaming = message && message.fromStream, signature = null, date = new Date(), config }) {
33191 config = { ...defaultConfig, ...config };
33192 checkCleartextOrMessage(message);
33193 if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary");
33194 publicKeys = toArray$1(publicKeys);
33195
33196 return Promise.resolve().then(async function() {
33197 const result = {};
33198 if (message instanceof CleartextMessage) {
33199 result.signatures = signature ? await message.verifyDetached(signature, publicKeys, date, config) : await message.verify(publicKeys, date, config);
33200 } else {
33201 result.signatures = signature ? await message.verifyDetached(signature, publicKeys, date, streaming, config) : await message.verify(publicKeys, date, streaming, config);
33202 }
33203 result.data = format === 'binary' ? message.getLiteralData() : message.getText();
33204 if (streaming) linkStreams(result, message);
33205 result.data = await convertStream(result.data, streaming, format);
33206 if (!streaming) await prepareSignatures(result.signatures);
33207 return result;
33208 }).catch(onError.bind(null, 'Error verifying signed message'));
33209}
33210
33211
33212///////////////////////////////////////////////
33213// //
33214// Session key encryption and decryption //
33215// //
33216///////////////////////////////////////////////
33217
33218/**
33219 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account.
33220 * @param {Object} options
33221 * @param {Key|Array<Key>} options.publicKeys - Array of public keys or single key used to select algorithm preferences for
33222 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
33223 * @param {Array} [options.toUserIds=primary user IDs] - User IDs to select algorithm preferences for
33224 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33225 * @returns {{ data: Uint8Array, algorithm: String }} Object with session key data and algorithm.
33226 * @async
33227 * @static
33228 */
33229function generateSessionKey$1({ publicKeys, date = new Date(), toUserIds = [], config }) {
33230 config = { ...defaultConfig, ...config };
33231 publicKeys = toArray$1(publicKeys); toUserIds = toArray$1(toUserIds);
33232
33233 return Promise.resolve().then(async function() {
33234
33235 return Message.generateSessionKey(publicKeys, date, toUserIds, config);
33236
33237 }).catch(onError.bind(null, 'Error generating session key'));
33238}
33239
33240/**
33241 * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys
33242 * or passwords must be specified.
33243 * @param {Object} options
33244 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
33245 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
33246 * @param {String} [options.aeadAlgorithm] - Aead algorithm, e.g. 'eax' or 'ocb'
33247 * @param {Key|Array<Key>} [options.publicKeys] - Array of public keys or single key, used to encrypt the key
33248 * @param {String|Array<String>} [options.passwords] - Passwords for the message
33249 * @param {Boolean} [options.armor=true] - Whether the return values should be ascii armored (true, the default) or binary (false)
33250 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
33251 * @param {Array<module:type/keyid~Keyid>} [options.encryptionKeyIds=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIds[i] corresponds to publicKeys[i]
33252 * @param {Date} [options.date=current date] - Override the date
33253 * @param {Array} [options.toUserIds=primary user IDs] - Array of user IDs to encrypt for, one per key in `publicKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`
33254 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33255 * @returns {String|Uint8Array} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
33256 * @async
33257 * @static
33258 */
33259function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, armor = true, wildcard = false, encryptionKeyIds = [], date = new Date(), toUserIds = [], config }) {
33260 config = { ...defaultConfig, ...config };
33261 checkBinary(data); checkString(algorithm, 'algorithm'); publicKeys = toArray$1(publicKeys); passwords = toArray$1(passwords); toUserIds = toArray$1(toUserIds);
33262
33263 return Promise.resolve().then(async function() {
33264
33265 const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, encryptionKeyIds, date, toUserIds, config);
33266 return armor ? message.armor(config) : message.write();
33267
33268 }).catch(onError.bind(null, 'Error encrypting session key'));
33269}
33270
33271/**
33272 * Decrypt symmetric session keys with a private key or password. Either a private key or
33273 * a password must be specified.
33274 * @param {Object} options
33275 * @param {Message} options.message - A message object containing the encrypted session key packets
33276 * @param {Key|Array<Key>} [options.privateKeys] - Private keys with decrypted secret key data
33277 * @param {String|Array<String>} [options.passwords] - Passwords to decrypt the session key
33278 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
33279 * @returns {Object|undefined} Array of decrypted session key, algorithm pairs in the form:
33280 * { data:Uint8Array, algorithm:String }
33281 * or 'undefined' if no key packets found
33282 * @async
33283 * @static
33284 */
33285function decryptSessionKeys({ message, privateKeys, passwords, config }) {
33286 config = { ...defaultConfig, ...config };
33287 checkMessage(message); privateKeys = toArray$1(privateKeys); passwords = toArray$1(passwords);
33288
33289 return Promise.resolve().then(async function() {
33290
33291 return message.decryptSessionKeys(privateKeys, passwords, config);
33292
33293 }).catch(onError.bind(null, 'Error decrypting session keys'));
33294}
33295
33296
33297//////////////////////////
33298// //
33299// Helper functions //
33300// //
33301//////////////////////////
33302
33303
33304/**
33305 * Input validation
33306 * @private
33307 */
33308function checkString(data, name) {
33309 if (!util.isString(data)) {
33310 throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
33311 }
33312}
33313function checkBinary(data, name) {
33314 if (!util.isUint8Array(data)) {
33315 throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
33316 }
33317}
33318function checkMessage(message) {
33319 if (!(message instanceof Message)) {
33320 throw new Error('Parameter [message] needs to be of type Message');
33321 }
33322}
33323function checkCleartextOrMessage(message) {
33324 if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
33325 throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
33326 }
33327}
33328
33329/**
33330 * Normalize parameter to an array if it is not undefined.
33331 * @param {Object} param - the parameter to be normalized
33332 * @returns {Array<Object>|undefined} The resulting array or undefined.
33333 * @private
33334 */
33335function toArray$1(param) {
33336 if (param && !util.isArray(param)) {
33337 param = [param];
33338 }
33339 return param;
33340}
33341
33342/**
33343 * Convert data to or from Stream
33344 * @param {Object} data - the data to convert
33345 * @param {'web'|'ponyfill'|'node'|false} [options.streaming] - Whether to return a ReadableStream, and of what type
33346 * @param {'utf8'|'binary'} [options.encoding] - How to return data in Node Readable streams
33347 * @returns {Object} The data in the respective format.
33348 * @private
33349 */
33350async function convertStream(data, streaming, encoding = 'utf8') {
33351 let streamType = util.isStream(data);
33352 if (!streaming && streamType) {
33353 return stream.readToEnd(data);
33354 }
33355 if (streaming && !streamType) {
33356 data = stream.toStream(data);
33357 streamType = util.isStream(data);
33358 }
33359 if (streaming === 'node') {
33360 data = stream.webToNode(data);
33361 if (encoding !== 'binary') data.setEncoding(encoding);
33362 return data;
33363 }
33364 if (streaming === 'web' && streamType === 'ponyfill' && toNativeReadable) {
33365 return toNativeReadable(data);
33366 }
33367 return data;
33368}
33369
33370/**
33371 * Link result.data to the message stream for cancellation.
33372 * Also, forward errors in the message to result.data.
33373 * @param {Object} result - the data to convert
33374 * @param {Message} message - message object
33375 * @returns {Object}
33376 * @private
33377 */
33378function linkStreams(result, message) {
33379 result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {
33380 await stream.pipe(result.data, writable, {
33381 preventClose: true
33382 });
33383 const writer = stream.getWriter(writable);
33384 try {
33385 // Forward errors in the message stream to result.data.
33386 await stream.readToEnd(readable, _ => _);
33387 await writer.close();
33388 } catch (e) {
33389 await writer.abort(e);
33390 }
33391 });
33392}
33393
33394/**
33395 * Wait until signature objects have been verified
33396 * @param {Object} signatures - list of signatures
33397 * @private
33398 */
33399async function prepareSignatures(signatures) {
33400 await Promise.all(signatures.map(async signature => {
33401 signature.signature = await signature.signature;
33402 try {
33403 signature.valid = await signature.verified;
33404 } catch (e) {
33405 signature.valid = false;
33406 signature.error = e;
33407 util.printDebugError(e);
33408 }
33409 }));
33410}
33411
33412
33413/**
33414 * Global error handler that logs the stack trace and rethrows a high lvl error message.
33415 * @param {String} message - A human readable high level error Message
33416 * @param {Error} error - The internal error that caused the failure
33417 * @private
33418 */
33419function onError(message, error) {
33420 // log the stack trace
33421 util.printDebugError(error);
33422
33423 // update error message
33424 try {
33425 error.message = message + ': ' + error.message;
33426 } catch (e) {}
33427
33428 throw error;
33429}
33430
33431var bn = createCommonjsModule(function (module) {
33432(function (module, exports) {
33433
33434 // Utils
33435 function assert (val, msg) {
33436 if (!val) throw new Error(msg || 'Assertion failed');
33437 }
33438
33439 // Could use `inherits` module, but don't want to move from single file
33440 // architecture yet.
33441 function inherits (ctor, superCtor) {
33442 ctor.super_ = superCtor;
33443 var TempCtor = function () {};
33444 TempCtor.prototype = superCtor.prototype;
33445 ctor.prototype = new TempCtor();
33446 ctor.prototype.constructor = ctor;
33447 }
33448
33449 // BN
33450
33451 function BN (number, base, endian) {
33452 if (BN.isBN(number)) {
33453 return number;
33454 }
33455
33456 this.negative = 0;
33457 this.words = null;
33458 this.length = 0;
33459
33460 // Reduction context
33461 this.red = null;
33462
33463 if (number !== null) {
33464 if (base === 'le' || base === 'be') {
33465 endian = base;
33466 base = 10;
33467 }
33468
33469 this._init(number || 0, base || 10, endian || 'be');
33470 }
33471 }
33472 if (typeof module === 'object') {
33473 module.exports = BN;
33474 } else {
33475 exports.BN = BN;
33476 }
33477
33478 BN.BN = BN;
33479 BN.wordSize = 26;
33480
33481 var Buffer;
33482 try {
33483 Buffer = buffer__default['default'].Buffer;
33484 } catch (e) {
33485 }
33486
33487 BN.isBN = function isBN (num) {
33488 if (num instanceof BN) {
33489 return true;
33490 }
33491
33492 return num !== null && typeof num === 'object' &&
33493 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
33494 };
33495
33496 BN.max = function max (left, right) {
33497 if (left.cmp(right) > 0) return left;
33498 return right;
33499 };
33500
33501 BN.min = function min (left, right) {
33502 if (left.cmp(right) < 0) return left;
33503 return right;
33504 };
33505
33506 BN.prototype._init = function init (number, base, endian) {
33507 if (typeof number === 'number') {
33508 return this._initNumber(number, base, endian);
33509 }
33510
33511 if (typeof number === 'object') {
33512 return this._initArray(number, base, endian);
33513 }
33514
33515 if (base === 'hex') {
33516 base = 16;
33517 }
33518 assert(base === (base | 0) && base >= 2 && base <= 36);
33519
33520 number = number.toString().replace(/\s+/g, '');
33521 var start = 0;
33522 if (number[0] === '-') {
33523 start++;
33524 }
33525
33526 if (base === 16) {
33527 this._parseHex(number, start);
33528 } else {
33529 this._parseBase(number, base, start);
33530 }
33531
33532 if (number[0] === '-') {
33533 this.negative = 1;
33534 }
33535
33536 this.strip();
33537
33538 if (endian !== 'le') return;
33539
33540 this._initArray(this.toArray(), base, endian);
33541 };
33542
33543 BN.prototype._initNumber = function _initNumber (number, base, endian) {
33544 if (number < 0) {
33545 this.negative = 1;
33546 number = -number;
33547 }
33548 if (number < 0x4000000) {
33549 this.words = [ number & 0x3ffffff ];
33550 this.length = 1;
33551 } else if (number < 0x10000000000000) {
33552 this.words = [
33553 number & 0x3ffffff,
33554 (number / 0x4000000) & 0x3ffffff
33555 ];
33556 this.length = 2;
33557 } else {
33558 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
33559 this.words = [
33560 number & 0x3ffffff,
33561 (number / 0x4000000) & 0x3ffffff,
33562 1
33563 ];
33564 this.length = 3;
33565 }
33566
33567 if (endian !== 'le') return;
33568
33569 // Reverse the bytes
33570 this._initArray(this.toArray(), base, endian);
33571 };
33572
33573 BN.prototype._initArray = function _initArray (number, base, endian) {
33574 // Perhaps a Uint8Array
33575 assert(typeof number.length === 'number');
33576 if (number.length <= 0) {
33577 this.words = [ 0 ];
33578 this.length = 1;
33579 return this;
33580 }
33581
33582 this.length = Math.ceil(number.length / 3);
33583 this.words = new Array(this.length);
33584 for (var i = 0; i < this.length; i++) {
33585 this.words[i] = 0;
33586 }
33587
33588 var j, w;
33589 var off = 0;
33590 if (endian === 'be') {
33591 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
33592 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
33593 this.words[j] |= (w << off) & 0x3ffffff;
33594 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
33595 off += 24;
33596 if (off >= 26) {
33597 off -= 26;
33598 j++;
33599 }
33600 }
33601 } else if (endian === 'le') {
33602 for (i = 0, j = 0; i < number.length; i += 3) {
33603 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
33604 this.words[j] |= (w << off) & 0x3ffffff;
33605 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
33606 off += 24;
33607 if (off >= 26) {
33608 off -= 26;
33609 j++;
33610 }
33611 }
33612 }
33613 return this.strip();
33614 };
33615
33616 function parseHex (str, start, end) {
33617 var r = 0;
33618 var len = Math.min(str.length, end);
33619 for (var i = start; i < len; i++) {
33620 var c = str.charCodeAt(i) - 48;
33621
33622 r <<= 4;
33623
33624 // 'a' - 'f'
33625 if (c >= 49 && c <= 54) {
33626 r |= c - 49 + 0xa;
33627
33628 // 'A' - 'F'
33629 } else if (c >= 17 && c <= 22) {
33630 r |= c - 17 + 0xa;
33631
33632 // '0' - '9'
33633 } else {
33634 r |= c & 0xf;
33635 }
33636 }
33637 return r;
33638 }
33639
33640 BN.prototype._parseHex = function _parseHex (number, start) {
33641 // Create possibly bigger array to ensure that it fits the number
33642 this.length = Math.ceil((number.length - start) / 6);
33643 this.words = new Array(this.length);
33644 for (var i = 0; i < this.length; i++) {
33645 this.words[i] = 0;
33646 }
33647
33648 var j, w;
33649 // Scan 24-bit chunks and add them to the number
33650 var off = 0;
33651 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
33652 w = parseHex(number, i, i + 6);
33653 this.words[j] |= (w << off) & 0x3ffffff;
33654 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
33655 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
33656 off += 24;
33657 if (off >= 26) {
33658 off -= 26;
33659 j++;
33660 }
33661 }
33662 if (i + 6 !== start) {
33663 w = parseHex(number, start, i + 6);
33664 this.words[j] |= (w << off) & 0x3ffffff;
33665 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
33666 }
33667 this.strip();
33668 };
33669
33670 function parseBase (str, start, end, mul) {
33671 var r = 0;
33672 var len = Math.min(str.length, end);
33673 for (var i = start; i < len; i++) {
33674 var c = str.charCodeAt(i) - 48;
33675
33676 r *= mul;
33677
33678 // 'a'
33679 if (c >= 49) {
33680 r += c - 49 + 0xa;
33681
33682 // 'A'
33683 } else if (c >= 17) {
33684 r += c - 17 + 0xa;
33685
33686 // '0' - '9'
33687 } else {
33688 r += c;
33689 }
33690 }
33691 return r;
33692 }
33693
33694 BN.prototype._parseBase = function _parseBase (number, base, start) {
33695 // Initialize as zero
33696 this.words = [ 0 ];
33697 this.length = 1;
33698
33699 // Find length of limb in base
33700 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
33701 limbLen++;
33702 }
33703 limbLen--;
33704 limbPow = (limbPow / base) | 0;
33705
33706 var total = number.length - start;
33707 var mod = total % limbLen;
33708 var end = Math.min(total, total - mod) + start;
33709
33710 var word = 0;
33711 for (var i = start; i < end; i += limbLen) {
33712 word = parseBase(number, i, i + limbLen, base);
33713
33714 this.imuln(limbPow);
33715 if (this.words[0] + word < 0x4000000) {
33716 this.words[0] += word;
33717 } else {
33718 this._iaddn(word);
33719 }
33720 }
33721
33722 if (mod !== 0) {
33723 var pow = 1;
33724 word = parseBase(number, i, number.length, base);
33725
33726 for (i = 0; i < mod; i++) {
33727 pow *= base;
33728 }
33729
33730 this.imuln(pow);
33731 if (this.words[0] + word < 0x4000000) {
33732 this.words[0] += word;
33733 } else {
33734 this._iaddn(word);
33735 }
33736 }
33737 };
33738
33739 BN.prototype.copy = function copy (dest) {
33740 dest.words = new Array(this.length);
33741 for (var i = 0; i < this.length; i++) {
33742 dest.words[i] = this.words[i];
33743 }
33744 dest.length = this.length;
33745 dest.negative = this.negative;
33746 dest.red = this.red;
33747 };
33748
33749 BN.prototype.clone = function clone () {
33750 var r = new BN(null);
33751 this.copy(r);
33752 return r;
33753 };
33754
33755 BN.prototype._expand = function _expand (size) {
33756 while (this.length < size) {
33757 this.words[this.length++] = 0;
33758 }
33759 return this;
33760 };
33761
33762 // Remove leading `0` from `this`
33763 BN.prototype.strip = function strip () {
33764 while (this.length > 1 && this.words[this.length - 1] === 0) {
33765 this.length--;
33766 }
33767 return this._normSign();
33768 };
33769
33770 BN.prototype._normSign = function _normSign () {
33771 // -0 = 0
33772 if (this.length === 1 && this.words[0] === 0) {
33773 this.negative = 0;
33774 }
33775 return this;
33776 };
33777
33778 BN.prototype.inspect = function inspect () {
33779 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
33780 };
33781
33782 /*
33783
33784 var zeros = [];
33785 var groupSizes = [];
33786 var groupBases = [];
33787
33788 var s = '';
33789 var i = -1;
33790 while (++i < BN.wordSize) {
33791 zeros[i] = s;
33792 s += '0';
33793 }
33794 groupSizes[0] = 0;
33795 groupSizes[1] = 0;
33796 groupBases[0] = 0;
33797 groupBases[1] = 0;
33798 var base = 2 - 1;
33799 while (++base < 36 + 1) {
33800 var groupSize = 0;
33801 var groupBase = 1;
33802 while (groupBase < (1 << BN.wordSize) / base) {
33803 groupBase *= base;
33804 groupSize += 1;
33805 }
33806 groupSizes[base] = groupSize;
33807 groupBases[base] = groupBase;
33808 }
33809
33810 */
33811
33812 var zeros = [
33813 '',
33814 '0',
33815 '00',
33816 '000',
33817 '0000',
33818 '00000',
33819 '000000',
33820 '0000000',
33821 '00000000',
33822 '000000000',
33823 '0000000000',
33824 '00000000000',
33825 '000000000000',
33826 '0000000000000',
33827 '00000000000000',
33828 '000000000000000',
33829 '0000000000000000',
33830 '00000000000000000',
33831 '000000000000000000',
33832 '0000000000000000000',
33833 '00000000000000000000',
33834 '000000000000000000000',
33835 '0000000000000000000000',
33836 '00000000000000000000000',
33837 '000000000000000000000000',
33838 '0000000000000000000000000'
33839 ];
33840
33841 var groupSizes = [
33842 0, 0,
33843 25, 16, 12, 11, 10, 9, 8,
33844 8, 7, 7, 7, 7, 6, 6,
33845 6, 6, 6, 6, 6, 5, 5,
33846 5, 5, 5, 5, 5, 5, 5,
33847 5, 5, 5, 5, 5, 5, 5
33848 ];
33849
33850 var groupBases = [
33851 0, 0,
33852 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
33853 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
33854 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
33855 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
33856 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
33857 ];
33858
33859 BN.prototype.toString = function toString (base, padding) {
33860 base = base || 10;
33861 padding = padding | 0 || 1;
33862
33863 var out;
33864 if (base === 16 || base === 'hex') {
33865 out = '';
33866 var off = 0;
33867 var carry = 0;
33868 for (var i = 0; i < this.length; i++) {
33869 var w = this.words[i];
33870 var word = (((w << off) | carry) & 0xffffff).toString(16);
33871 carry = (w >>> (24 - off)) & 0xffffff;
33872 if (carry !== 0 || i !== this.length - 1) {
33873 out = zeros[6 - word.length] + word + out;
33874 } else {
33875 out = word + out;
33876 }
33877 off += 2;
33878 if (off >= 26) {
33879 off -= 26;
33880 i--;
33881 }
33882 }
33883 if (carry !== 0) {
33884 out = carry.toString(16) + out;
33885 }
33886 while (out.length % padding !== 0) {
33887 out = '0' + out;
33888 }
33889 if (this.negative !== 0) {
33890 out = '-' + out;
33891 }
33892 return out;
33893 }
33894
33895 if (base === (base | 0) && base >= 2 && base <= 36) {
33896 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
33897 var groupSize = groupSizes[base];
33898 // var groupBase = Math.pow(base, groupSize);
33899 var groupBase = groupBases[base];
33900 out = '';
33901 var c = this.clone();
33902 c.negative = 0;
33903 while (!c.isZero()) {
33904 var r = c.modn(groupBase).toString(base);
33905 c = c.idivn(groupBase);
33906
33907 if (!c.isZero()) {
33908 out = zeros[groupSize - r.length] + r + out;
33909 } else {
33910 out = r + out;
33911 }
33912 }
33913 if (this.isZero()) {
33914 out = '0' + out;
33915 }
33916 while (out.length % padding !== 0) {
33917 out = '0' + out;
33918 }
33919 if (this.negative !== 0) {
33920 out = '-' + out;
33921 }
33922 return out;
33923 }
33924
33925 assert(false, 'Base should be between 2 and 36');
33926 };
33927
33928 BN.prototype.toNumber = function toNumber () {
33929 var ret = this.words[0];
33930 if (this.length === 2) {
33931 ret += this.words[1] * 0x4000000;
33932 } else if (this.length === 3 && this.words[2] === 0x01) {
33933 // NOTE: at this stage it is known that the top bit is set
33934 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
33935 } else if (this.length > 2) {
33936 assert(false, 'Number can only safely store up to 53 bits');
33937 }
33938 return (this.negative !== 0) ? -ret : ret;
33939 };
33940
33941 BN.prototype.toJSON = function toJSON () {
33942 return this.toString(16);
33943 };
33944
33945 BN.prototype.toBuffer = function toBuffer (endian, length) {
33946 assert(typeof Buffer !== 'undefined');
33947 return this.toArrayLike(Buffer, endian, length);
33948 };
33949
33950 BN.prototype.toArray = function toArray (endian, length) {
33951 return this.toArrayLike(Array, endian, length);
33952 };
33953
33954 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
33955 var byteLength = this.byteLength();
33956 var reqLength = length || Math.max(1, byteLength);
33957 assert(byteLength <= reqLength, 'byte array longer than desired length');
33958 assert(reqLength > 0, 'Requested array length <= 0');
33959
33960 this.strip();
33961 var littleEndian = endian === 'le';
33962 var res = new ArrayType(reqLength);
33963
33964 var b, i;
33965 var q = this.clone();
33966 if (!littleEndian) {
33967 // Assume big-endian
33968 for (i = 0; i < reqLength - byteLength; i++) {
33969 res[i] = 0;
33970 }
33971
33972 for (i = 0; !q.isZero(); i++) {
33973 b = q.andln(0xff);
33974 q.iushrn(8);
33975
33976 res[reqLength - i - 1] = b;
33977 }
33978 } else {
33979 for (i = 0; !q.isZero(); i++) {
33980 b = q.andln(0xff);
33981 q.iushrn(8);
33982
33983 res[i] = b;
33984 }
33985
33986 for (; i < reqLength; i++) {
33987 res[i] = 0;
33988 }
33989 }
33990
33991 return res;
33992 };
33993
33994 if (Math.clz32) {
33995 BN.prototype._countBits = function _countBits (w) {
33996 return 32 - Math.clz32(w);
33997 };
33998 } else {
33999 BN.prototype._countBits = function _countBits (w) {
34000 var t = w;
34001 var r = 0;
34002 if (t >= 0x1000) {
34003 r += 13;
34004 t >>>= 13;
34005 }
34006 if (t >= 0x40) {
34007 r += 7;
34008 t >>>= 7;
34009 }
34010 if (t >= 0x8) {
34011 r += 4;
34012 t >>>= 4;
34013 }
34014 if (t >= 0x02) {
34015 r += 2;
34016 t >>>= 2;
34017 }
34018 return r + t;
34019 };
34020 }
34021
34022 BN.prototype._zeroBits = function _zeroBits (w) {
34023 // Short-cut
34024 if (w === 0) return 26;
34025
34026 var t = w;
34027 var r = 0;
34028 if ((t & 0x1fff) === 0) {
34029 r += 13;
34030 t >>>= 13;
34031 }
34032 if ((t & 0x7f) === 0) {
34033 r += 7;
34034 t >>>= 7;
34035 }
34036 if ((t & 0xf) === 0) {
34037 r += 4;
34038 t >>>= 4;
34039 }
34040 if ((t & 0x3) === 0) {
34041 r += 2;
34042 t >>>= 2;
34043 }
34044 if ((t & 0x1) === 0) {
34045 r++;
34046 }
34047 return r;
34048 };
34049
34050 // Return number of used bits in a BN
34051 BN.prototype.bitLength = function bitLength () {
34052 var w = this.words[this.length - 1];
34053 var hi = this._countBits(w);
34054 return (this.length - 1) * 26 + hi;
34055 };
34056
34057 function toBitArray (num) {
34058 var w = new Array(num.bitLength());
34059
34060 for (var bit = 0; bit < w.length; bit++) {
34061 var off = (bit / 26) | 0;
34062 var wbit = bit % 26;
34063
34064 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
34065 }
34066
34067 return w;
34068 }
34069
34070 // Number of trailing zero bits
34071 BN.prototype.zeroBits = function zeroBits () {
34072 if (this.isZero()) return 0;
34073
34074 var r = 0;
34075 for (var i = 0; i < this.length; i++) {
34076 var b = this._zeroBits(this.words[i]);
34077 r += b;
34078 if (b !== 26) break;
34079 }
34080 return r;
34081 };
34082
34083 BN.prototype.byteLength = function byteLength () {
34084 return Math.ceil(this.bitLength() / 8);
34085 };
34086
34087 BN.prototype.toTwos = function toTwos (width) {
34088 if (this.negative !== 0) {
34089 return this.abs().inotn(width).iaddn(1);
34090 }
34091 return this.clone();
34092 };
34093
34094 BN.prototype.fromTwos = function fromTwos (width) {
34095 if (this.testn(width - 1)) {
34096 return this.notn(width).iaddn(1).ineg();
34097 }
34098 return this.clone();
34099 };
34100
34101 BN.prototype.isNeg = function isNeg () {
34102 return this.negative !== 0;
34103 };
34104
34105 // Return negative clone of `this`
34106 BN.prototype.neg = function neg () {
34107 return this.clone().ineg();
34108 };
34109
34110 BN.prototype.ineg = function ineg () {
34111 if (!this.isZero()) {
34112 this.negative ^= 1;
34113 }
34114
34115 return this;
34116 };
34117
34118 // Or `num` with `this` in-place
34119 BN.prototype.iuor = function iuor (num) {
34120 while (this.length < num.length) {
34121 this.words[this.length++] = 0;
34122 }
34123
34124 for (var i = 0; i < num.length; i++) {
34125 this.words[i] = this.words[i] | num.words[i];
34126 }
34127
34128 return this.strip();
34129 };
34130
34131 BN.prototype.ior = function ior (num) {
34132 assert((this.negative | num.negative) === 0);
34133 return this.iuor(num);
34134 };
34135
34136 // Or `num` with `this`
34137 BN.prototype.or = function or (num) {
34138 if (this.length > num.length) return this.clone().ior(num);
34139 return num.clone().ior(this);
34140 };
34141
34142 BN.prototype.uor = function uor (num) {
34143 if (this.length > num.length) return this.clone().iuor(num);
34144 return num.clone().iuor(this);
34145 };
34146
34147 // And `num` with `this` in-place
34148 BN.prototype.iuand = function iuand (num) {
34149 // b = min-length(num, this)
34150 var b;
34151 if (this.length > num.length) {
34152 b = num;
34153 } else {
34154 b = this;
34155 }
34156
34157 for (var i = 0; i < b.length; i++) {
34158 this.words[i] = this.words[i] & num.words[i];
34159 }
34160
34161 this.length = b.length;
34162
34163 return this.strip();
34164 };
34165
34166 BN.prototype.iand = function iand (num) {
34167 assert((this.negative | num.negative) === 0);
34168 return this.iuand(num);
34169 };
34170
34171 // And `num` with `this`
34172 BN.prototype.and = function and (num) {
34173 if (this.length > num.length) return this.clone().iand(num);
34174 return num.clone().iand(this);
34175 };
34176
34177 BN.prototype.uand = function uand (num) {
34178 if (this.length > num.length) return this.clone().iuand(num);
34179 return num.clone().iuand(this);
34180 };
34181
34182 // Xor `num` with `this` in-place
34183 BN.prototype.iuxor = function iuxor (num) {
34184 // a.length > b.length
34185 var a;
34186 var b;
34187 if (this.length > num.length) {
34188 a = this;
34189 b = num;
34190 } else {
34191 a = num;
34192 b = this;
34193 }
34194
34195 for (var i = 0; i < b.length; i++) {
34196 this.words[i] = a.words[i] ^ b.words[i];
34197 }
34198
34199 if (this !== a) {
34200 for (; i < a.length; i++) {
34201 this.words[i] = a.words[i];
34202 }
34203 }
34204
34205 this.length = a.length;
34206
34207 return this.strip();
34208 };
34209
34210 BN.prototype.ixor = function ixor (num) {
34211 assert((this.negative | num.negative) === 0);
34212 return this.iuxor(num);
34213 };
34214
34215 // Xor `num` with `this`
34216 BN.prototype.xor = function xor (num) {
34217 if (this.length > num.length) return this.clone().ixor(num);
34218 return num.clone().ixor(this);
34219 };
34220
34221 BN.prototype.uxor = function uxor (num) {
34222 if (this.length > num.length) return this.clone().iuxor(num);
34223 return num.clone().iuxor(this);
34224 };
34225
34226 // Not ``this`` with ``width`` bitwidth
34227 BN.prototype.inotn = function inotn (width) {
34228 assert(typeof width === 'number' && width >= 0);
34229
34230 var bytesNeeded = Math.ceil(width / 26) | 0;
34231 var bitsLeft = width % 26;
34232
34233 // Extend the buffer with leading zeroes
34234 this._expand(bytesNeeded);
34235
34236 if (bitsLeft > 0) {
34237 bytesNeeded--;
34238 }
34239
34240 // Handle complete words
34241 for (var i = 0; i < bytesNeeded; i++) {
34242 this.words[i] = ~this.words[i] & 0x3ffffff;
34243 }
34244
34245 // Handle the residue
34246 if (bitsLeft > 0) {
34247 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
34248 }
34249
34250 // And remove leading zeroes
34251 return this.strip();
34252 };
34253
34254 BN.prototype.notn = function notn (width) {
34255 return this.clone().inotn(width);
34256 };
34257
34258 // Set `bit` of `this`
34259 BN.prototype.setn = function setn (bit, val) {
34260 assert(typeof bit === 'number' && bit >= 0);
34261
34262 var off = (bit / 26) | 0;
34263 var wbit = bit % 26;
34264
34265 this._expand(off + 1);
34266
34267 if (val) {
34268 this.words[off] = this.words[off] | (1 << wbit);
34269 } else {
34270 this.words[off] = this.words[off] & ~(1 << wbit);
34271 }
34272
34273 return this.strip();
34274 };
34275
34276 // Add `num` to `this` in-place
34277 BN.prototype.iadd = function iadd (num) {
34278 var r;
34279
34280 // negative + positive
34281 if (this.negative !== 0 && num.negative === 0) {
34282 this.negative = 0;
34283 r = this.isub(num);
34284 this.negative ^= 1;
34285 return this._normSign();
34286
34287 // positive + negative
34288 } else if (this.negative === 0 && num.negative !== 0) {
34289 num.negative = 0;
34290 r = this.isub(num);
34291 num.negative = 1;
34292 return r._normSign();
34293 }
34294
34295 // a.length > b.length
34296 var a, b;
34297 if (this.length > num.length) {
34298 a = this;
34299 b = num;
34300 } else {
34301 a = num;
34302 b = this;
34303 }
34304
34305 var carry = 0;
34306 for (var i = 0; i < b.length; i++) {
34307 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
34308 this.words[i] = r & 0x3ffffff;
34309 carry = r >>> 26;
34310 }
34311 for (; carry !== 0 && i < a.length; i++) {
34312 r = (a.words[i] | 0) + carry;
34313 this.words[i] = r & 0x3ffffff;
34314 carry = r >>> 26;
34315 }
34316
34317 this.length = a.length;
34318 if (carry !== 0) {
34319 this.words[this.length] = carry;
34320 this.length++;
34321 // Copy the rest of the words
34322 } else if (a !== this) {
34323 for (; i < a.length; i++) {
34324 this.words[i] = a.words[i];
34325 }
34326 }
34327
34328 return this;
34329 };
34330
34331 // Add `num` to `this`
34332 BN.prototype.add = function add (num) {
34333 var res;
34334 if (num.negative !== 0 && this.negative === 0) {
34335 num.negative = 0;
34336 res = this.sub(num);
34337 num.negative ^= 1;
34338 return res;
34339 } else if (num.negative === 0 && this.negative !== 0) {
34340 this.negative = 0;
34341 res = num.sub(this);
34342 this.negative = 1;
34343 return res;
34344 }
34345
34346 if (this.length > num.length) return this.clone().iadd(num);
34347
34348 return num.clone().iadd(this);
34349 };
34350
34351 // Subtract `num` from `this` in-place
34352 BN.prototype.isub = function isub (num) {
34353 // this - (-num) = this + num
34354 if (num.negative !== 0) {
34355 num.negative = 0;
34356 var r = this.iadd(num);
34357 num.negative = 1;
34358 return r._normSign();
34359
34360 // -this - num = -(this + num)
34361 } else if (this.negative !== 0) {
34362 this.negative = 0;
34363 this.iadd(num);
34364 this.negative = 1;
34365 return this._normSign();
34366 }
34367
34368 // At this point both numbers are positive
34369 var cmp = this.cmp(num);
34370
34371 // Optimization - zeroify
34372 if (cmp === 0) {
34373 this.negative = 0;
34374 this.length = 1;
34375 this.words[0] = 0;
34376 return this;
34377 }
34378
34379 // a > b
34380 var a, b;
34381 if (cmp > 0) {
34382 a = this;
34383 b = num;
34384 } else {
34385 a = num;
34386 b = this;
34387 }
34388
34389 var carry = 0;
34390 for (var i = 0; i < b.length; i++) {
34391 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
34392 carry = r >> 26;
34393 this.words[i] = r & 0x3ffffff;
34394 }
34395 for (; carry !== 0 && i < a.length; i++) {
34396 r = (a.words[i] | 0) + carry;
34397 carry = r >> 26;
34398 this.words[i] = r & 0x3ffffff;
34399 }
34400
34401 // Copy rest of the words
34402 if (carry === 0 && i < a.length && a !== this) {
34403 for (; i < a.length; i++) {
34404 this.words[i] = a.words[i];
34405 }
34406 }
34407
34408 this.length = Math.max(this.length, i);
34409
34410 if (a !== this) {
34411 this.negative = 1;
34412 }
34413
34414 return this.strip();
34415 };
34416
34417 // Subtract `num` from `this`
34418 BN.prototype.sub = function sub (num) {
34419 return this.clone().isub(num);
34420 };
34421
34422 function smallMulTo (self, num, out) {
34423 out.negative = num.negative ^ self.negative;
34424 var len = (self.length + num.length) | 0;
34425 out.length = len;
34426 len = (len - 1) | 0;
34427
34428 // Peel one iteration (compiler can't do it, because of code complexity)
34429 var a = self.words[0] | 0;
34430 var b = num.words[0] | 0;
34431 var r = a * b;
34432
34433 var lo = r & 0x3ffffff;
34434 var carry = (r / 0x4000000) | 0;
34435 out.words[0] = lo;
34436
34437 for (var k = 1; k < len; k++) {
34438 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
34439 // note that ncarry could be >= 0x3ffffff
34440 var ncarry = carry >>> 26;
34441 var rword = carry & 0x3ffffff;
34442 var maxJ = Math.min(k, num.length - 1);
34443 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
34444 var i = (k - j) | 0;
34445 a = self.words[i] | 0;
34446 b = num.words[j] | 0;
34447 r = a * b + rword;
34448 ncarry += (r / 0x4000000) | 0;
34449 rword = r & 0x3ffffff;
34450 }
34451 out.words[k] = rword | 0;
34452 carry = ncarry | 0;
34453 }
34454 if (carry !== 0) {
34455 out.words[k] = carry | 0;
34456 } else {
34457 out.length--;
34458 }
34459
34460 return out.strip();
34461 }
34462
34463 // TODO(indutny): it may be reasonable to omit it for users who don't need
34464 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
34465 // multiplication (like elliptic secp256k1).
34466 var comb10MulTo = function comb10MulTo (self, num, out) {
34467 var a = self.words;
34468 var b = num.words;
34469 var o = out.words;
34470 var c = 0;
34471 var lo;
34472 var mid;
34473 var hi;
34474 var a0 = a[0] | 0;
34475 var al0 = a0 & 0x1fff;
34476 var ah0 = a0 >>> 13;
34477 var a1 = a[1] | 0;
34478 var al1 = a1 & 0x1fff;
34479 var ah1 = a1 >>> 13;
34480 var a2 = a[2] | 0;
34481 var al2 = a2 & 0x1fff;
34482 var ah2 = a2 >>> 13;
34483 var a3 = a[3] | 0;
34484 var al3 = a3 & 0x1fff;
34485 var ah3 = a3 >>> 13;
34486 var a4 = a[4] | 0;
34487 var al4 = a4 & 0x1fff;
34488 var ah4 = a4 >>> 13;
34489 var a5 = a[5] | 0;
34490 var al5 = a5 & 0x1fff;
34491 var ah5 = a5 >>> 13;
34492 var a6 = a[6] | 0;
34493 var al6 = a6 & 0x1fff;
34494 var ah6 = a6 >>> 13;
34495 var a7 = a[7] | 0;
34496 var al7 = a7 & 0x1fff;
34497 var ah7 = a7 >>> 13;
34498 var a8 = a[8] | 0;
34499 var al8 = a8 & 0x1fff;
34500 var ah8 = a8 >>> 13;
34501 var a9 = a[9] | 0;
34502 var al9 = a9 & 0x1fff;
34503 var ah9 = a9 >>> 13;
34504 var b0 = b[0] | 0;
34505 var bl0 = b0 & 0x1fff;
34506 var bh0 = b0 >>> 13;
34507 var b1 = b[1] | 0;
34508 var bl1 = b1 & 0x1fff;
34509 var bh1 = b1 >>> 13;
34510 var b2 = b[2] | 0;
34511 var bl2 = b2 & 0x1fff;
34512 var bh2 = b2 >>> 13;
34513 var b3 = b[3] | 0;
34514 var bl3 = b3 & 0x1fff;
34515 var bh3 = b3 >>> 13;
34516 var b4 = b[4] | 0;
34517 var bl4 = b4 & 0x1fff;
34518 var bh4 = b4 >>> 13;
34519 var b5 = b[5] | 0;
34520 var bl5 = b5 & 0x1fff;
34521 var bh5 = b5 >>> 13;
34522 var b6 = b[6] | 0;
34523 var bl6 = b6 & 0x1fff;
34524 var bh6 = b6 >>> 13;
34525 var b7 = b[7] | 0;
34526 var bl7 = b7 & 0x1fff;
34527 var bh7 = b7 >>> 13;
34528 var b8 = b[8] | 0;
34529 var bl8 = b8 & 0x1fff;
34530 var bh8 = b8 >>> 13;
34531 var b9 = b[9] | 0;
34532 var bl9 = b9 & 0x1fff;
34533 var bh9 = b9 >>> 13;
34534
34535 out.negative = self.negative ^ num.negative;
34536 out.length = 19;
34537 /* k = 0 */
34538 lo = Math.imul(al0, bl0);
34539 mid = Math.imul(al0, bh0);
34540 mid = (mid + Math.imul(ah0, bl0)) | 0;
34541 hi = Math.imul(ah0, bh0);
34542 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34543 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
34544 w0 &= 0x3ffffff;
34545 /* k = 1 */
34546 lo = Math.imul(al1, bl0);
34547 mid = Math.imul(al1, bh0);
34548 mid = (mid + Math.imul(ah1, bl0)) | 0;
34549 hi = Math.imul(ah1, bh0);
34550 lo = (lo + Math.imul(al0, bl1)) | 0;
34551 mid = (mid + Math.imul(al0, bh1)) | 0;
34552 mid = (mid + Math.imul(ah0, bl1)) | 0;
34553 hi = (hi + Math.imul(ah0, bh1)) | 0;
34554 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34555 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
34556 w1 &= 0x3ffffff;
34557 /* k = 2 */
34558 lo = Math.imul(al2, bl0);
34559 mid = Math.imul(al2, bh0);
34560 mid = (mid + Math.imul(ah2, bl0)) | 0;
34561 hi = Math.imul(ah2, bh0);
34562 lo = (lo + Math.imul(al1, bl1)) | 0;
34563 mid = (mid + Math.imul(al1, bh1)) | 0;
34564 mid = (mid + Math.imul(ah1, bl1)) | 0;
34565 hi = (hi + Math.imul(ah1, bh1)) | 0;
34566 lo = (lo + Math.imul(al0, bl2)) | 0;
34567 mid = (mid + Math.imul(al0, bh2)) | 0;
34568 mid = (mid + Math.imul(ah0, bl2)) | 0;
34569 hi = (hi + Math.imul(ah0, bh2)) | 0;
34570 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34571 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
34572 w2 &= 0x3ffffff;
34573 /* k = 3 */
34574 lo = Math.imul(al3, bl0);
34575 mid = Math.imul(al3, bh0);
34576 mid = (mid + Math.imul(ah3, bl0)) | 0;
34577 hi = Math.imul(ah3, bh0);
34578 lo = (lo + Math.imul(al2, bl1)) | 0;
34579 mid = (mid + Math.imul(al2, bh1)) | 0;
34580 mid = (mid + Math.imul(ah2, bl1)) | 0;
34581 hi = (hi + Math.imul(ah2, bh1)) | 0;
34582 lo = (lo + Math.imul(al1, bl2)) | 0;
34583 mid = (mid + Math.imul(al1, bh2)) | 0;
34584 mid = (mid + Math.imul(ah1, bl2)) | 0;
34585 hi = (hi + Math.imul(ah1, bh2)) | 0;
34586 lo = (lo + Math.imul(al0, bl3)) | 0;
34587 mid = (mid + Math.imul(al0, bh3)) | 0;
34588 mid = (mid + Math.imul(ah0, bl3)) | 0;
34589 hi = (hi + Math.imul(ah0, bh3)) | 0;
34590 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34591 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
34592 w3 &= 0x3ffffff;
34593 /* k = 4 */
34594 lo = Math.imul(al4, bl0);
34595 mid = Math.imul(al4, bh0);
34596 mid = (mid + Math.imul(ah4, bl0)) | 0;
34597 hi = Math.imul(ah4, bh0);
34598 lo = (lo + Math.imul(al3, bl1)) | 0;
34599 mid = (mid + Math.imul(al3, bh1)) | 0;
34600 mid = (mid + Math.imul(ah3, bl1)) | 0;
34601 hi = (hi + Math.imul(ah3, bh1)) | 0;
34602 lo = (lo + Math.imul(al2, bl2)) | 0;
34603 mid = (mid + Math.imul(al2, bh2)) | 0;
34604 mid = (mid + Math.imul(ah2, bl2)) | 0;
34605 hi = (hi + Math.imul(ah2, bh2)) | 0;
34606 lo = (lo + Math.imul(al1, bl3)) | 0;
34607 mid = (mid + Math.imul(al1, bh3)) | 0;
34608 mid = (mid + Math.imul(ah1, bl3)) | 0;
34609 hi = (hi + Math.imul(ah1, bh3)) | 0;
34610 lo = (lo + Math.imul(al0, bl4)) | 0;
34611 mid = (mid + Math.imul(al0, bh4)) | 0;
34612 mid = (mid + Math.imul(ah0, bl4)) | 0;
34613 hi = (hi + Math.imul(ah0, bh4)) | 0;
34614 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34615 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
34616 w4 &= 0x3ffffff;
34617 /* k = 5 */
34618 lo = Math.imul(al5, bl0);
34619 mid = Math.imul(al5, bh0);
34620 mid = (mid + Math.imul(ah5, bl0)) | 0;
34621 hi = Math.imul(ah5, bh0);
34622 lo = (lo + Math.imul(al4, bl1)) | 0;
34623 mid = (mid + Math.imul(al4, bh1)) | 0;
34624 mid = (mid + Math.imul(ah4, bl1)) | 0;
34625 hi = (hi + Math.imul(ah4, bh1)) | 0;
34626 lo = (lo + Math.imul(al3, bl2)) | 0;
34627 mid = (mid + Math.imul(al3, bh2)) | 0;
34628 mid = (mid + Math.imul(ah3, bl2)) | 0;
34629 hi = (hi + Math.imul(ah3, bh2)) | 0;
34630 lo = (lo + Math.imul(al2, bl3)) | 0;
34631 mid = (mid + Math.imul(al2, bh3)) | 0;
34632 mid = (mid + Math.imul(ah2, bl3)) | 0;
34633 hi = (hi + Math.imul(ah2, bh3)) | 0;
34634 lo = (lo + Math.imul(al1, bl4)) | 0;
34635 mid = (mid + Math.imul(al1, bh4)) | 0;
34636 mid = (mid + Math.imul(ah1, bl4)) | 0;
34637 hi = (hi + Math.imul(ah1, bh4)) | 0;
34638 lo = (lo + Math.imul(al0, bl5)) | 0;
34639 mid = (mid + Math.imul(al0, bh5)) | 0;
34640 mid = (mid + Math.imul(ah0, bl5)) | 0;
34641 hi = (hi + Math.imul(ah0, bh5)) | 0;
34642 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34643 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
34644 w5 &= 0x3ffffff;
34645 /* k = 6 */
34646 lo = Math.imul(al6, bl0);
34647 mid = Math.imul(al6, bh0);
34648 mid = (mid + Math.imul(ah6, bl0)) | 0;
34649 hi = Math.imul(ah6, bh0);
34650 lo = (lo + Math.imul(al5, bl1)) | 0;
34651 mid = (mid + Math.imul(al5, bh1)) | 0;
34652 mid = (mid + Math.imul(ah5, bl1)) | 0;
34653 hi = (hi + Math.imul(ah5, bh1)) | 0;
34654 lo = (lo + Math.imul(al4, bl2)) | 0;
34655 mid = (mid + Math.imul(al4, bh2)) | 0;
34656 mid = (mid + Math.imul(ah4, bl2)) | 0;
34657 hi = (hi + Math.imul(ah4, bh2)) | 0;
34658 lo = (lo + Math.imul(al3, bl3)) | 0;
34659 mid = (mid + Math.imul(al3, bh3)) | 0;
34660 mid = (mid + Math.imul(ah3, bl3)) | 0;
34661 hi = (hi + Math.imul(ah3, bh3)) | 0;
34662 lo = (lo + Math.imul(al2, bl4)) | 0;
34663 mid = (mid + Math.imul(al2, bh4)) | 0;
34664 mid = (mid + Math.imul(ah2, bl4)) | 0;
34665 hi = (hi + Math.imul(ah2, bh4)) | 0;
34666 lo = (lo + Math.imul(al1, bl5)) | 0;
34667 mid = (mid + Math.imul(al1, bh5)) | 0;
34668 mid = (mid + Math.imul(ah1, bl5)) | 0;
34669 hi = (hi + Math.imul(ah1, bh5)) | 0;
34670 lo = (lo + Math.imul(al0, bl6)) | 0;
34671 mid = (mid + Math.imul(al0, bh6)) | 0;
34672 mid = (mid + Math.imul(ah0, bl6)) | 0;
34673 hi = (hi + Math.imul(ah0, bh6)) | 0;
34674 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34675 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
34676 w6 &= 0x3ffffff;
34677 /* k = 7 */
34678 lo = Math.imul(al7, bl0);
34679 mid = Math.imul(al7, bh0);
34680 mid = (mid + Math.imul(ah7, bl0)) | 0;
34681 hi = Math.imul(ah7, bh0);
34682 lo = (lo + Math.imul(al6, bl1)) | 0;
34683 mid = (mid + Math.imul(al6, bh1)) | 0;
34684 mid = (mid + Math.imul(ah6, bl1)) | 0;
34685 hi = (hi + Math.imul(ah6, bh1)) | 0;
34686 lo = (lo + Math.imul(al5, bl2)) | 0;
34687 mid = (mid + Math.imul(al5, bh2)) | 0;
34688 mid = (mid + Math.imul(ah5, bl2)) | 0;
34689 hi = (hi + Math.imul(ah5, bh2)) | 0;
34690 lo = (lo + Math.imul(al4, bl3)) | 0;
34691 mid = (mid + Math.imul(al4, bh3)) | 0;
34692 mid = (mid + Math.imul(ah4, bl3)) | 0;
34693 hi = (hi + Math.imul(ah4, bh3)) | 0;
34694 lo = (lo + Math.imul(al3, bl4)) | 0;
34695 mid = (mid + Math.imul(al3, bh4)) | 0;
34696 mid = (mid + Math.imul(ah3, bl4)) | 0;
34697 hi = (hi + Math.imul(ah3, bh4)) | 0;
34698 lo = (lo + Math.imul(al2, bl5)) | 0;
34699 mid = (mid + Math.imul(al2, bh5)) | 0;
34700 mid = (mid + Math.imul(ah2, bl5)) | 0;
34701 hi = (hi + Math.imul(ah2, bh5)) | 0;
34702 lo = (lo + Math.imul(al1, bl6)) | 0;
34703 mid = (mid + Math.imul(al1, bh6)) | 0;
34704 mid = (mid + Math.imul(ah1, bl6)) | 0;
34705 hi = (hi + Math.imul(ah1, bh6)) | 0;
34706 lo = (lo + Math.imul(al0, bl7)) | 0;
34707 mid = (mid + Math.imul(al0, bh7)) | 0;
34708 mid = (mid + Math.imul(ah0, bl7)) | 0;
34709 hi = (hi + Math.imul(ah0, bh7)) | 0;
34710 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34711 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
34712 w7 &= 0x3ffffff;
34713 /* k = 8 */
34714 lo = Math.imul(al8, bl0);
34715 mid = Math.imul(al8, bh0);
34716 mid = (mid + Math.imul(ah8, bl0)) | 0;
34717 hi = Math.imul(ah8, bh0);
34718 lo = (lo + Math.imul(al7, bl1)) | 0;
34719 mid = (mid + Math.imul(al7, bh1)) | 0;
34720 mid = (mid + Math.imul(ah7, bl1)) | 0;
34721 hi = (hi + Math.imul(ah7, bh1)) | 0;
34722 lo = (lo + Math.imul(al6, bl2)) | 0;
34723 mid = (mid + Math.imul(al6, bh2)) | 0;
34724 mid = (mid + Math.imul(ah6, bl2)) | 0;
34725 hi = (hi + Math.imul(ah6, bh2)) | 0;
34726 lo = (lo + Math.imul(al5, bl3)) | 0;
34727 mid = (mid + Math.imul(al5, bh3)) | 0;
34728 mid = (mid + Math.imul(ah5, bl3)) | 0;
34729 hi = (hi + Math.imul(ah5, bh3)) | 0;
34730 lo = (lo + Math.imul(al4, bl4)) | 0;
34731 mid = (mid + Math.imul(al4, bh4)) | 0;
34732 mid = (mid + Math.imul(ah4, bl4)) | 0;
34733 hi = (hi + Math.imul(ah4, bh4)) | 0;
34734 lo = (lo + Math.imul(al3, bl5)) | 0;
34735 mid = (mid + Math.imul(al3, bh5)) | 0;
34736 mid = (mid + Math.imul(ah3, bl5)) | 0;
34737 hi = (hi + Math.imul(ah3, bh5)) | 0;
34738 lo = (lo + Math.imul(al2, bl6)) | 0;
34739 mid = (mid + Math.imul(al2, bh6)) | 0;
34740 mid = (mid + Math.imul(ah2, bl6)) | 0;
34741 hi = (hi + Math.imul(ah2, bh6)) | 0;
34742 lo = (lo + Math.imul(al1, bl7)) | 0;
34743 mid = (mid + Math.imul(al1, bh7)) | 0;
34744 mid = (mid + Math.imul(ah1, bl7)) | 0;
34745 hi = (hi + Math.imul(ah1, bh7)) | 0;
34746 lo = (lo + Math.imul(al0, bl8)) | 0;
34747 mid = (mid + Math.imul(al0, bh8)) | 0;
34748 mid = (mid + Math.imul(ah0, bl8)) | 0;
34749 hi = (hi + Math.imul(ah0, bh8)) | 0;
34750 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34751 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
34752 w8 &= 0x3ffffff;
34753 /* k = 9 */
34754 lo = Math.imul(al9, bl0);
34755 mid = Math.imul(al9, bh0);
34756 mid = (mid + Math.imul(ah9, bl0)) | 0;
34757 hi = Math.imul(ah9, bh0);
34758 lo = (lo + Math.imul(al8, bl1)) | 0;
34759 mid = (mid + Math.imul(al8, bh1)) | 0;
34760 mid = (mid + Math.imul(ah8, bl1)) | 0;
34761 hi = (hi + Math.imul(ah8, bh1)) | 0;
34762 lo = (lo + Math.imul(al7, bl2)) | 0;
34763 mid = (mid + Math.imul(al7, bh2)) | 0;
34764 mid = (mid + Math.imul(ah7, bl2)) | 0;
34765 hi = (hi + Math.imul(ah7, bh2)) | 0;
34766 lo = (lo + Math.imul(al6, bl3)) | 0;
34767 mid = (mid + Math.imul(al6, bh3)) | 0;
34768 mid = (mid + Math.imul(ah6, bl3)) | 0;
34769 hi = (hi + Math.imul(ah6, bh3)) | 0;
34770 lo = (lo + Math.imul(al5, bl4)) | 0;
34771 mid = (mid + Math.imul(al5, bh4)) | 0;
34772 mid = (mid + Math.imul(ah5, bl4)) | 0;
34773 hi = (hi + Math.imul(ah5, bh4)) | 0;
34774 lo = (lo + Math.imul(al4, bl5)) | 0;
34775 mid = (mid + Math.imul(al4, bh5)) | 0;
34776 mid = (mid + Math.imul(ah4, bl5)) | 0;
34777 hi = (hi + Math.imul(ah4, bh5)) | 0;
34778 lo = (lo + Math.imul(al3, bl6)) | 0;
34779 mid = (mid + Math.imul(al3, bh6)) | 0;
34780 mid = (mid + Math.imul(ah3, bl6)) | 0;
34781 hi = (hi + Math.imul(ah3, bh6)) | 0;
34782 lo = (lo + Math.imul(al2, bl7)) | 0;
34783 mid = (mid + Math.imul(al2, bh7)) | 0;
34784 mid = (mid + Math.imul(ah2, bl7)) | 0;
34785 hi = (hi + Math.imul(ah2, bh7)) | 0;
34786 lo = (lo + Math.imul(al1, bl8)) | 0;
34787 mid = (mid + Math.imul(al1, bh8)) | 0;
34788 mid = (mid + Math.imul(ah1, bl8)) | 0;
34789 hi = (hi + Math.imul(ah1, bh8)) | 0;
34790 lo = (lo + Math.imul(al0, bl9)) | 0;
34791 mid = (mid + Math.imul(al0, bh9)) | 0;
34792 mid = (mid + Math.imul(ah0, bl9)) | 0;
34793 hi = (hi + Math.imul(ah0, bh9)) | 0;
34794 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34795 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
34796 w9 &= 0x3ffffff;
34797 /* k = 10 */
34798 lo = Math.imul(al9, bl1);
34799 mid = Math.imul(al9, bh1);
34800 mid = (mid + Math.imul(ah9, bl1)) | 0;
34801 hi = Math.imul(ah9, bh1);
34802 lo = (lo + Math.imul(al8, bl2)) | 0;
34803 mid = (mid + Math.imul(al8, bh2)) | 0;
34804 mid = (mid + Math.imul(ah8, bl2)) | 0;
34805 hi = (hi + Math.imul(ah8, bh2)) | 0;
34806 lo = (lo + Math.imul(al7, bl3)) | 0;
34807 mid = (mid + Math.imul(al7, bh3)) | 0;
34808 mid = (mid + Math.imul(ah7, bl3)) | 0;
34809 hi = (hi + Math.imul(ah7, bh3)) | 0;
34810 lo = (lo + Math.imul(al6, bl4)) | 0;
34811 mid = (mid + Math.imul(al6, bh4)) | 0;
34812 mid = (mid + Math.imul(ah6, bl4)) | 0;
34813 hi = (hi + Math.imul(ah6, bh4)) | 0;
34814 lo = (lo + Math.imul(al5, bl5)) | 0;
34815 mid = (mid + Math.imul(al5, bh5)) | 0;
34816 mid = (mid + Math.imul(ah5, bl5)) | 0;
34817 hi = (hi + Math.imul(ah5, bh5)) | 0;
34818 lo = (lo + Math.imul(al4, bl6)) | 0;
34819 mid = (mid + Math.imul(al4, bh6)) | 0;
34820 mid = (mid + Math.imul(ah4, bl6)) | 0;
34821 hi = (hi + Math.imul(ah4, bh6)) | 0;
34822 lo = (lo + Math.imul(al3, bl7)) | 0;
34823 mid = (mid + Math.imul(al3, bh7)) | 0;
34824 mid = (mid + Math.imul(ah3, bl7)) | 0;
34825 hi = (hi + Math.imul(ah3, bh7)) | 0;
34826 lo = (lo + Math.imul(al2, bl8)) | 0;
34827 mid = (mid + Math.imul(al2, bh8)) | 0;
34828 mid = (mid + Math.imul(ah2, bl8)) | 0;
34829 hi = (hi + Math.imul(ah2, bh8)) | 0;
34830 lo = (lo + Math.imul(al1, bl9)) | 0;
34831 mid = (mid + Math.imul(al1, bh9)) | 0;
34832 mid = (mid + Math.imul(ah1, bl9)) | 0;
34833 hi = (hi + Math.imul(ah1, bh9)) | 0;
34834 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34835 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
34836 w10 &= 0x3ffffff;
34837 /* k = 11 */
34838 lo = Math.imul(al9, bl2);
34839 mid = Math.imul(al9, bh2);
34840 mid = (mid + Math.imul(ah9, bl2)) | 0;
34841 hi = Math.imul(ah9, bh2);
34842 lo = (lo + Math.imul(al8, bl3)) | 0;
34843 mid = (mid + Math.imul(al8, bh3)) | 0;
34844 mid = (mid + Math.imul(ah8, bl3)) | 0;
34845 hi = (hi + Math.imul(ah8, bh3)) | 0;
34846 lo = (lo + Math.imul(al7, bl4)) | 0;
34847 mid = (mid + Math.imul(al7, bh4)) | 0;
34848 mid = (mid + Math.imul(ah7, bl4)) | 0;
34849 hi = (hi + Math.imul(ah7, bh4)) | 0;
34850 lo = (lo + Math.imul(al6, bl5)) | 0;
34851 mid = (mid + Math.imul(al6, bh5)) | 0;
34852 mid = (mid + Math.imul(ah6, bl5)) | 0;
34853 hi = (hi + Math.imul(ah6, bh5)) | 0;
34854 lo = (lo + Math.imul(al5, bl6)) | 0;
34855 mid = (mid + Math.imul(al5, bh6)) | 0;
34856 mid = (mid + Math.imul(ah5, bl6)) | 0;
34857 hi = (hi + Math.imul(ah5, bh6)) | 0;
34858 lo = (lo + Math.imul(al4, bl7)) | 0;
34859 mid = (mid + Math.imul(al4, bh7)) | 0;
34860 mid = (mid + Math.imul(ah4, bl7)) | 0;
34861 hi = (hi + Math.imul(ah4, bh7)) | 0;
34862 lo = (lo + Math.imul(al3, bl8)) | 0;
34863 mid = (mid + Math.imul(al3, bh8)) | 0;
34864 mid = (mid + Math.imul(ah3, bl8)) | 0;
34865 hi = (hi + Math.imul(ah3, bh8)) | 0;
34866 lo = (lo + Math.imul(al2, bl9)) | 0;
34867 mid = (mid + Math.imul(al2, bh9)) | 0;
34868 mid = (mid + Math.imul(ah2, bl9)) | 0;
34869 hi = (hi + Math.imul(ah2, bh9)) | 0;
34870 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34871 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
34872 w11 &= 0x3ffffff;
34873 /* k = 12 */
34874 lo = Math.imul(al9, bl3);
34875 mid = Math.imul(al9, bh3);
34876 mid = (mid + Math.imul(ah9, bl3)) | 0;
34877 hi = Math.imul(ah9, bh3);
34878 lo = (lo + Math.imul(al8, bl4)) | 0;
34879 mid = (mid + Math.imul(al8, bh4)) | 0;
34880 mid = (mid + Math.imul(ah8, bl4)) | 0;
34881 hi = (hi + Math.imul(ah8, bh4)) | 0;
34882 lo = (lo + Math.imul(al7, bl5)) | 0;
34883 mid = (mid + Math.imul(al7, bh5)) | 0;
34884 mid = (mid + Math.imul(ah7, bl5)) | 0;
34885 hi = (hi + Math.imul(ah7, bh5)) | 0;
34886 lo = (lo + Math.imul(al6, bl6)) | 0;
34887 mid = (mid + Math.imul(al6, bh6)) | 0;
34888 mid = (mid + Math.imul(ah6, bl6)) | 0;
34889 hi = (hi + Math.imul(ah6, bh6)) | 0;
34890 lo = (lo + Math.imul(al5, bl7)) | 0;
34891 mid = (mid + Math.imul(al5, bh7)) | 0;
34892 mid = (mid + Math.imul(ah5, bl7)) | 0;
34893 hi = (hi + Math.imul(ah5, bh7)) | 0;
34894 lo = (lo + Math.imul(al4, bl8)) | 0;
34895 mid = (mid + Math.imul(al4, bh8)) | 0;
34896 mid = (mid + Math.imul(ah4, bl8)) | 0;
34897 hi = (hi + Math.imul(ah4, bh8)) | 0;
34898 lo = (lo + Math.imul(al3, bl9)) | 0;
34899 mid = (mid + Math.imul(al3, bh9)) | 0;
34900 mid = (mid + Math.imul(ah3, bl9)) | 0;
34901 hi = (hi + Math.imul(ah3, bh9)) | 0;
34902 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34903 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
34904 w12 &= 0x3ffffff;
34905 /* k = 13 */
34906 lo = Math.imul(al9, bl4);
34907 mid = Math.imul(al9, bh4);
34908 mid = (mid + Math.imul(ah9, bl4)) | 0;
34909 hi = Math.imul(ah9, bh4);
34910 lo = (lo + Math.imul(al8, bl5)) | 0;
34911 mid = (mid + Math.imul(al8, bh5)) | 0;
34912 mid = (mid + Math.imul(ah8, bl5)) | 0;
34913 hi = (hi + Math.imul(ah8, bh5)) | 0;
34914 lo = (lo + Math.imul(al7, bl6)) | 0;
34915 mid = (mid + Math.imul(al7, bh6)) | 0;
34916 mid = (mid + Math.imul(ah7, bl6)) | 0;
34917 hi = (hi + Math.imul(ah7, bh6)) | 0;
34918 lo = (lo + Math.imul(al6, bl7)) | 0;
34919 mid = (mid + Math.imul(al6, bh7)) | 0;
34920 mid = (mid + Math.imul(ah6, bl7)) | 0;
34921 hi = (hi + Math.imul(ah6, bh7)) | 0;
34922 lo = (lo + Math.imul(al5, bl8)) | 0;
34923 mid = (mid + Math.imul(al5, bh8)) | 0;
34924 mid = (mid + Math.imul(ah5, bl8)) | 0;
34925 hi = (hi + Math.imul(ah5, bh8)) | 0;
34926 lo = (lo + Math.imul(al4, bl9)) | 0;
34927 mid = (mid + Math.imul(al4, bh9)) | 0;
34928 mid = (mid + Math.imul(ah4, bl9)) | 0;
34929 hi = (hi + Math.imul(ah4, bh9)) | 0;
34930 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34931 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
34932 w13 &= 0x3ffffff;
34933 /* k = 14 */
34934 lo = Math.imul(al9, bl5);
34935 mid = Math.imul(al9, bh5);
34936 mid = (mid + Math.imul(ah9, bl5)) | 0;
34937 hi = Math.imul(ah9, bh5);
34938 lo = (lo + Math.imul(al8, bl6)) | 0;
34939 mid = (mid + Math.imul(al8, bh6)) | 0;
34940 mid = (mid + Math.imul(ah8, bl6)) | 0;
34941 hi = (hi + Math.imul(ah8, bh6)) | 0;
34942 lo = (lo + Math.imul(al7, bl7)) | 0;
34943 mid = (mid + Math.imul(al7, bh7)) | 0;
34944 mid = (mid + Math.imul(ah7, bl7)) | 0;
34945 hi = (hi + Math.imul(ah7, bh7)) | 0;
34946 lo = (lo + Math.imul(al6, bl8)) | 0;
34947 mid = (mid + Math.imul(al6, bh8)) | 0;
34948 mid = (mid + Math.imul(ah6, bl8)) | 0;
34949 hi = (hi + Math.imul(ah6, bh8)) | 0;
34950 lo = (lo + Math.imul(al5, bl9)) | 0;
34951 mid = (mid + Math.imul(al5, bh9)) | 0;
34952 mid = (mid + Math.imul(ah5, bl9)) | 0;
34953 hi = (hi + Math.imul(ah5, bh9)) | 0;
34954 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34955 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
34956 w14 &= 0x3ffffff;
34957 /* k = 15 */
34958 lo = Math.imul(al9, bl6);
34959 mid = Math.imul(al9, bh6);
34960 mid = (mid + Math.imul(ah9, bl6)) | 0;
34961 hi = Math.imul(ah9, bh6);
34962 lo = (lo + Math.imul(al8, bl7)) | 0;
34963 mid = (mid + Math.imul(al8, bh7)) | 0;
34964 mid = (mid + Math.imul(ah8, bl7)) | 0;
34965 hi = (hi + Math.imul(ah8, bh7)) | 0;
34966 lo = (lo + Math.imul(al7, bl8)) | 0;
34967 mid = (mid + Math.imul(al7, bh8)) | 0;
34968 mid = (mid + Math.imul(ah7, bl8)) | 0;
34969 hi = (hi + Math.imul(ah7, bh8)) | 0;
34970 lo = (lo + Math.imul(al6, bl9)) | 0;
34971 mid = (mid + Math.imul(al6, bh9)) | 0;
34972 mid = (mid + Math.imul(ah6, bl9)) | 0;
34973 hi = (hi + Math.imul(ah6, bh9)) | 0;
34974 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34975 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
34976 w15 &= 0x3ffffff;
34977 /* k = 16 */
34978 lo = Math.imul(al9, bl7);
34979 mid = Math.imul(al9, bh7);
34980 mid = (mid + Math.imul(ah9, bl7)) | 0;
34981 hi = Math.imul(ah9, bh7);
34982 lo = (lo + Math.imul(al8, bl8)) | 0;
34983 mid = (mid + Math.imul(al8, bh8)) | 0;
34984 mid = (mid + Math.imul(ah8, bl8)) | 0;
34985 hi = (hi + Math.imul(ah8, bh8)) | 0;
34986 lo = (lo + Math.imul(al7, bl9)) | 0;
34987 mid = (mid + Math.imul(al7, bh9)) | 0;
34988 mid = (mid + Math.imul(ah7, bl9)) | 0;
34989 hi = (hi + Math.imul(ah7, bh9)) | 0;
34990 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
34991 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
34992 w16 &= 0x3ffffff;
34993 /* k = 17 */
34994 lo = Math.imul(al9, bl8);
34995 mid = Math.imul(al9, bh8);
34996 mid = (mid + Math.imul(ah9, bl8)) | 0;
34997 hi = Math.imul(ah9, bh8);
34998 lo = (lo + Math.imul(al8, bl9)) | 0;
34999 mid = (mid + Math.imul(al8, bh9)) | 0;
35000 mid = (mid + Math.imul(ah8, bl9)) | 0;
35001 hi = (hi + Math.imul(ah8, bh9)) | 0;
35002 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
35003 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
35004 w17 &= 0x3ffffff;
35005 /* k = 18 */
35006 lo = Math.imul(al9, bl9);
35007 mid = Math.imul(al9, bh9);
35008 mid = (mid + Math.imul(ah9, bl9)) | 0;
35009 hi = Math.imul(ah9, bh9);
35010 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
35011 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
35012 w18 &= 0x3ffffff;
35013 o[0] = w0;
35014 o[1] = w1;
35015 o[2] = w2;
35016 o[3] = w3;
35017 o[4] = w4;
35018 o[5] = w5;
35019 o[6] = w6;
35020 o[7] = w7;
35021 o[8] = w8;
35022 o[9] = w9;
35023 o[10] = w10;
35024 o[11] = w11;
35025 o[12] = w12;
35026 o[13] = w13;
35027 o[14] = w14;
35028 o[15] = w15;
35029 o[16] = w16;
35030 o[17] = w17;
35031 o[18] = w18;
35032 if (c !== 0) {
35033 o[19] = c;
35034 out.length++;
35035 }
35036 return out;
35037 };
35038
35039 // Polyfill comb
35040 if (!Math.imul) {
35041 comb10MulTo = smallMulTo;
35042 }
35043
35044 function bigMulTo (self, num, out) {
35045 out.negative = num.negative ^ self.negative;
35046 out.length = self.length + num.length;
35047
35048 var carry = 0;
35049 var hncarry = 0;
35050 for (var k = 0; k < out.length - 1; k++) {
35051 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
35052 // note that ncarry could be >= 0x3ffffff
35053 var ncarry = hncarry;
35054 hncarry = 0;
35055 var rword = carry & 0x3ffffff;
35056 var maxJ = Math.min(k, num.length - 1);
35057 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
35058 var i = k - j;
35059 var a = self.words[i] | 0;
35060 var b = num.words[j] | 0;
35061 var r = a * b;
35062
35063 var lo = r & 0x3ffffff;
35064 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
35065 lo = (lo + rword) | 0;
35066 rword = lo & 0x3ffffff;
35067 ncarry = (ncarry + (lo >>> 26)) | 0;
35068
35069 hncarry += ncarry >>> 26;
35070 ncarry &= 0x3ffffff;
35071 }
35072 out.words[k] = rword;
35073 carry = ncarry;
35074 ncarry = hncarry;
35075 }
35076 if (carry !== 0) {
35077 out.words[k] = carry;
35078 } else {
35079 out.length--;
35080 }
35081
35082 return out.strip();
35083 }
35084
35085 function jumboMulTo (self, num, out) {
35086 var fftm = new FFTM();
35087 return fftm.mulp(self, num, out);
35088 }
35089
35090 BN.prototype.mulTo = function mulTo (num, out) {
35091 var res;
35092 var len = this.length + num.length;
35093 if (this.length === 10 && num.length === 10) {
35094 res = comb10MulTo(this, num, out);
35095 } else if (len < 63) {
35096 res = smallMulTo(this, num, out);
35097 } else if (len < 1024) {
35098 res = bigMulTo(this, num, out);
35099 } else {
35100 res = jumboMulTo(this, num, out);
35101 }
35102
35103 return res;
35104 };
35105
35106 // Cooley-Tukey algorithm for FFT
35107 // slightly revisited to rely on looping instead of recursion
35108
35109 function FFTM (x, y) {
35110 this.x = x;
35111 this.y = y;
35112 }
35113
35114 FFTM.prototype.makeRBT = function makeRBT (N) {
35115 var t = new Array(N);
35116 var l = BN.prototype._countBits(N) - 1;
35117 for (var i = 0; i < N; i++) {
35118 t[i] = this.revBin(i, l, N);
35119 }
35120
35121 return t;
35122 };
35123
35124 // Returns binary-reversed representation of `x`
35125 FFTM.prototype.revBin = function revBin (x, l, N) {
35126 if (x === 0 || x === N - 1) return x;
35127
35128 var rb = 0;
35129 for (var i = 0; i < l; i++) {
35130 rb |= (x & 1) << (l - i - 1);
35131 x >>= 1;
35132 }
35133
35134 return rb;
35135 };
35136
35137 // Performs "tweedling" phase, therefore 'emulating'
35138 // behaviour of the recursive algorithm
35139 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
35140 for (var i = 0; i < N; i++) {
35141 rtws[i] = rws[rbt[i]];
35142 itws[i] = iws[rbt[i]];
35143 }
35144 };
35145
35146 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
35147 this.permute(rbt, rws, iws, rtws, itws, N);
35148
35149 for (var s = 1; s < N; s <<= 1) {
35150 var l = s << 1;
35151
35152 var rtwdf = Math.cos(2 * Math.PI / l);
35153 var itwdf = Math.sin(2 * Math.PI / l);
35154
35155 for (var p = 0; p < N; p += l) {
35156 var rtwdf_ = rtwdf;
35157 var itwdf_ = itwdf;
35158
35159 for (var j = 0; j < s; j++) {
35160 var re = rtws[p + j];
35161 var ie = itws[p + j];
35162
35163 var ro = rtws[p + j + s];
35164 var io = itws[p + j + s];
35165
35166 var rx = rtwdf_ * ro - itwdf_ * io;
35167
35168 io = rtwdf_ * io + itwdf_ * ro;
35169 ro = rx;
35170
35171 rtws[p + j] = re + ro;
35172 itws[p + j] = ie + io;
35173
35174 rtws[p + j + s] = re - ro;
35175 itws[p + j + s] = ie - io;
35176
35177 /* jshint maxdepth : false */
35178 if (j !== l) {
35179 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
35180
35181 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
35182 rtwdf_ = rx;
35183 }
35184 }
35185 }
35186 }
35187 };
35188
35189 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
35190 var N = Math.max(m, n) | 1;
35191 var odd = N & 1;
35192 var i = 0;
35193 for (N = N / 2 | 0; N; N = N >>> 1) {
35194 i++;
35195 }
35196
35197 return 1 << i + 1 + odd;
35198 };
35199
35200 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
35201 if (N <= 1) return;
35202
35203 for (var i = 0; i < N / 2; i++) {
35204 var t = rws[i];
35205
35206 rws[i] = rws[N - i - 1];
35207 rws[N - i - 1] = t;
35208
35209 t = iws[i];
35210
35211 iws[i] = -iws[N - i - 1];
35212 iws[N - i - 1] = -t;
35213 }
35214 };
35215
35216 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
35217 var carry = 0;
35218 for (var i = 0; i < N / 2; i++) {
35219 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
35220 Math.round(ws[2 * i] / N) +
35221 carry;
35222
35223 ws[i] = w & 0x3ffffff;
35224
35225 if (w < 0x4000000) {
35226 carry = 0;
35227 } else {
35228 carry = w / 0x4000000 | 0;
35229 }
35230 }
35231
35232 return ws;
35233 };
35234
35235 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
35236 var carry = 0;
35237 for (var i = 0; i < len; i++) {
35238 carry = carry + (ws[i] | 0);
35239
35240 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
35241 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
35242 }
35243
35244 // Pad with zeroes
35245 for (i = 2 * len; i < N; ++i) {
35246 rws[i] = 0;
35247 }
35248
35249 assert(carry === 0);
35250 assert((carry & ~0x1fff) === 0);
35251 };
35252
35253 FFTM.prototype.stub = function stub (N) {
35254 var ph = new Array(N);
35255 for (var i = 0; i < N; i++) {
35256 ph[i] = 0;
35257 }
35258
35259 return ph;
35260 };
35261
35262 FFTM.prototype.mulp = function mulp (x, y, out) {
35263 var N = 2 * this.guessLen13b(x.length, y.length);
35264
35265 var rbt = this.makeRBT(N);
35266
35267 var _ = this.stub(N);
35268
35269 var rws = new Array(N);
35270 var rwst = new Array(N);
35271 var iwst = new Array(N);
35272
35273 var nrws = new Array(N);
35274 var nrwst = new Array(N);
35275 var niwst = new Array(N);
35276
35277 var rmws = out.words;
35278 rmws.length = N;
35279
35280 this.convert13b(x.words, x.length, rws, N);
35281 this.convert13b(y.words, y.length, nrws, N);
35282
35283 this.transform(rws, _, rwst, iwst, N, rbt);
35284 this.transform(nrws, _, nrwst, niwst, N, rbt);
35285
35286 for (var i = 0; i < N; i++) {
35287 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
35288 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
35289 rwst[i] = rx;
35290 }
35291
35292 this.conjugate(rwst, iwst, N);
35293 this.transform(rwst, iwst, rmws, _, N, rbt);
35294 this.conjugate(rmws, _, N);
35295 this.normalize13b(rmws, N);
35296
35297 out.negative = x.negative ^ y.negative;
35298 out.length = x.length + y.length;
35299 return out.strip();
35300 };
35301
35302 // Multiply `this` by `num`
35303 BN.prototype.mul = function mul (num) {
35304 var out = new BN(null);
35305 out.words = new Array(this.length + num.length);
35306 return this.mulTo(num, out);
35307 };
35308
35309 // Multiply employing FFT
35310 BN.prototype.mulf = function mulf (num) {
35311 var out = new BN(null);
35312 out.words = new Array(this.length + num.length);
35313 return jumboMulTo(this, num, out);
35314 };
35315
35316 // In-place Multiplication
35317 BN.prototype.imul = function imul (num) {
35318 return this.clone().mulTo(num, this);
35319 };
35320
35321 BN.prototype.imuln = function imuln (num) {
35322 assert(typeof num === 'number');
35323 assert(num < 0x4000000);
35324
35325 // Carry
35326 var carry = 0;
35327 for (var i = 0; i < this.length; i++) {
35328 var w = (this.words[i] | 0) * num;
35329 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
35330 carry >>= 26;
35331 carry += (w / 0x4000000) | 0;
35332 // NOTE: lo is 27bit maximum
35333 carry += lo >>> 26;
35334 this.words[i] = lo & 0x3ffffff;
35335 }
35336
35337 if (carry !== 0) {
35338 this.words[i] = carry;
35339 this.length++;
35340 }
35341
35342 return this;
35343 };
35344
35345 BN.prototype.muln = function muln (num) {
35346 return this.clone().imuln(num);
35347 };
35348
35349 // `this` * `this`
35350 BN.prototype.sqr = function sqr () {
35351 return this.mul(this);
35352 };
35353
35354 // `this` * `this` in-place
35355 BN.prototype.isqr = function isqr () {
35356 return this.imul(this.clone());
35357 };
35358
35359 // Math.pow(`this`, `num`)
35360 BN.prototype.pow = function pow (num) {
35361 var w = toBitArray(num);
35362 if (w.length === 0) return new BN(1);
35363
35364 // Skip leading zeroes
35365 var res = this;
35366 for (var i = 0; i < w.length; i++, res = res.sqr()) {
35367 if (w[i] !== 0) break;
35368 }
35369
35370 if (++i < w.length) {
35371 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
35372 if (w[i] === 0) continue;
35373
35374 res = res.mul(q);
35375 }
35376 }
35377
35378 return res;
35379 };
35380
35381 // Shift-left in-place
35382 BN.prototype.iushln = function iushln (bits) {
35383 assert(typeof bits === 'number' && bits >= 0);
35384 var r = bits % 26;
35385 var s = (bits - r) / 26;
35386 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
35387 var i;
35388
35389 if (r !== 0) {
35390 var carry = 0;
35391
35392 for (i = 0; i < this.length; i++) {
35393 var newCarry = this.words[i] & carryMask;
35394 var c = ((this.words[i] | 0) - newCarry) << r;
35395 this.words[i] = c | carry;
35396 carry = newCarry >>> (26 - r);
35397 }
35398
35399 if (carry) {
35400 this.words[i] = carry;
35401 this.length++;
35402 }
35403 }
35404
35405 if (s !== 0) {
35406 for (i = this.length - 1; i >= 0; i--) {
35407 this.words[i + s] = this.words[i];
35408 }
35409
35410 for (i = 0; i < s; i++) {
35411 this.words[i] = 0;
35412 }
35413
35414 this.length += s;
35415 }
35416
35417 return this.strip();
35418 };
35419
35420 BN.prototype.ishln = function ishln (bits) {
35421 // TODO(indutny): implement me
35422 assert(this.negative === 0);
35423 return this.iushln(bits);
35424 };
35425
35426 // Shift-right in-place
35427 // NOTE: `hint` is a lowest bit before trailing zeroes
35428 // NOTE: if `extended` is present - it will be filled with destroyed bits
35429 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
35430 assert(typeof bits === 'number' && bits >= 0);
35431 var h;
35432 if (hint) {
35433 h = (hint - (hint % 26)) / 26;
35434 } else {
35435 h = 0;
35436 }
35437
35438 var r = bits % 26;
35439 var s = Math.min((bits - r) / 26, this.length);
35440 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
35441 var maskedWords = extended;
35442
35443 h -= s;
35444 h = Math.max(0, h);
35445
35446 // Extended mode, copy masked part
35447 if (maskedWords) {
35448 for (var i = 0; i < s; i++) {
35449 maskedWords.words[i] = this.words[i];
35450 }
35451 maskedWords.length = s;
35452 }
35453
35454 if (s === 0) ; else if (this.length > s) {
35455 this.length -= s;
35456 for (i = 0; i < this.length; i++) {
35457 this.words[i] = this.words[i + s];
35458 }
35459 } else {
35460 this.words[0] = 0;
35461 this.length = 1;
35462 }
35463
35464 var carry = 0;
35465 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
35466 var word = this.words[i] | 0;
35467 this.words[i] = (carry << (26 - r)) | (word >>> r);
35468 carry = word & mask;
35469 }
35470
35471 // Push carried bits as a mask
35472 if (maskedWords && carry !== 0) {
35473 maskedWords.words[maskedWords.length++] = carry;
35474 }
35475
35476 if (this.length === 0) {
35477 this.words[0] = 0;
35478 this.length = 1;
35479 }
35480
35481 return this.strip();
35482 };
35483
35484 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
35485 // TODO(indutny): implement me
35486 assert(this.negative === 0);
35487 return this.iushrn(bits, hint, extended);
35488 };
35489
35490 // Shift-left
35491 BN.prototype.shln = function shln (bits) {
35492 return this.clone().ishln(bits);
35493 };
35494
35495 BN.prototype.ushln = function ushln (bits) {
35496 return this.clone().iushln(bits);
35497 };
35498
35499 // Shift-right
35500 BN.prototype.shrn = function shrn (bits) {
35501 return this.clone().ishrn(bits);
35502 };
35503
35504 BN.prototype.ushrn = function ushrn (bits) {
35505 return this.clone().iushrn(bits);
35506 };
35507
35508 // Test if n bit is set
35509 BN.prototype.testn = function testn (bit) {
35510 assert(typeof bit === 'number' && bit >= 0);
35511 var r = bit % 26;
35512 var s = (bit - r) / 26;
35513 var q = 1 << r;
35514
35515 // Fast case: bit is much higher than all existing words
35516 if (this.length <= s) return false;
35517
35518 // Check bit and return
35519 var w = this.words[s];
35520
35521 return !!(w & q);
35522 };
35523
35524 // Return only lowers bits of number (in-place)
35525 BN.prototype.imaskn = function imaskn (bits) {
35526 assert(typeof bits === 'number' && bits >= 0);
35527 var r = bits % 26;
35528 var s = (bits - r) / 26;
35529
35530 assert(this.negative === 0, 'imaskn works only with positive numbers');
35531
35532 if (this.length <= s) {
35533 return this;
35534 }
35535
35536 if (r !== 0) {
35537 s++;
35538 }
35539 this.length = Math.min(s, this.length);
35540
35541 if (r !== 0) {
35542 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
35543 this.words[this.length - 1] &= mask;
35544 }
35545
35546 return this.strip();
35547 };
35548
35549 // Return only lowers bits of number
35550 BN.prototype.maskn = function maskn (bits) {
35551 return this.clone().imaskn(bits);
35552 };
35553
35554 // Add plain number `num` to `this`
35555 BN.prototype.iaddn = function iaddn (num) {
35556 assert(typeof num === 'number');
35557 assert(num < 0x4000000);
35558 if (num < 0) return this.isubn(-num);
35559
35560 // Possible sign change
35561 if (this.negative !== 0) {
35562 if (this.length === 1 && (this.words[0] | 0) < num) {
35563 this.words[0] = num - (this.words[0] | 0);
35564 this.negative = 0;
35565 return this;
35566 }
35567
35568 this.negative = 0;
35569 this.isubn(num);
35570 this.negative = 1;
35571 return this;
35572 }
35573
35574 // Add without checks
35575 return this._iaddn(num);
35576 };
35577
35578 BN.prototype._iaddn = function _iaddn (num) {
35579 this.words[0] += num;
35580
35581 // Carry
35582 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
35583 this.words[i] -= 0x4000000;
35584 if (i === this.length - 1) {
35585 this.words[i + 1] = 1;
35586 } else {
35587 this.words[i + 1]++;
35588 }
35589 }
35590 this.length = Math.max(this.length, i + 1);
35591
35592 return this;
35593 };
35594
35595 // Subtract plain number `num` from `this`
35596 BN.prototype.isubn = function isubn (num) {
35597 assert(typeof num === 'number');
35598 assert(num < 0x4000000);
35599 if (num < 0) return this.iaddn(-num);
35600
35601 if (this.negative !== 0) {
35602 this.negative = 0;
35603 this.iaddn(num);
35604 this.negative = 1;
35605 return this;
35606 }
35607
35608 this.words[0] -= num;
35609
35610 if (this.length === 1 && this.words[0] < 0) {
35611 this.words[0] = -this.words[0];
35612 this.negative = 1;
35613 } else {
35614 // Carry
35615 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
35616 this.words[i] += 0x4000000;
35617 this.words[i + 1] -= 1;
35618 }
35619 }
35620
35621 return this.strip();
35622 };
35623
35624 BN.prototype.addn = function addn (num) {
35625 return this.clone().iaddn(num);
35626 };
35627
35628 BN.prototype.subn = function subn (num) {
35629 return this.clone().isubn(num);
35630 };
35631
35632 BN.prototype.iabs = function iabs () {
35633 this.negative = 0;
35634
35635 return this;
35636 };
35637
35638 BN.prototype.abs = function abs () {
35639 return this.clone().iabs();
35640 };
35641
35642 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
35643 var len = num.length + shift;
35644 var i;
35645
35646 this._expand(len);
35647
35648 var w;
35649 var carry = 0;
35650 for (i = 0; i < num.length; i++) {
35651 w = (this.words[i + shift] | 0) + carry;
35652 var right = (num.words[i] | 0) * mul;
35653 w -= right & 0x3ffffff;
35654 carry = (w >> 26) - ((right / 0x4000000) | 0);
35655 this.words[i + shift] = w & 0x3ffffff;
35656 }
35657 for (; i < this.length - shift; i++) {
35658 w = (this.words[i + shift] | 0) + carry;
35659 carry = w >> 26;
35660 this.words[i + shift] = w & 0x3ffffff;
35661 }
35662
35663 if (carry === 0) return this.strip();
35664
35665 // Subtraction overflow
35666 assert(carry === -1);
35667 carry = 0;
35668 for (i = 0; i < this.length; i++) {
35669 w = -(this.words[i] | 0) + carry;
35670 carry = w >> 26;
35671 this.words[i] = w & 0x3ffffff;
35672 }
35673 this.negative = 1;
35674
35675 return this.strip();
35676 };
35677
35678 BN.prototype._wordDiv = function _wordDiv (num, mode) {
35679 var shift = this.length - num.length;
35680
35681 var a = this.clone();
35682 var b = num;
35683
35684 // Normalize
35685 var bhi = b.words[b.length - 1] | 0;
35686 var bhiBits = this._countBits(bhi);
35687 shift = 26 - bhiBits;
35688 if (shift !== 0) {
35689 b = b.ushln(shift);
35690 a.iushln(shift);
35691 bhi = b.words[b.length - 1] | 0;
35692 }
35693
35694 // Initialize quotient
35695 var m = a.length - b.length;
35696 var q;
35697
35698 if (mode !== 'mod') {
35699 q = new BN(null);
35700 q.length = m + 1;
35701 q.words = new Array(q.length);
35702 for (var i = 0; i < q.length; i++) {
35703 q.words[i] = 0;
35704 }
35705 }
35706
35707 var diff = a.clone()._ishlnsubmul(b, 1, m);
35708 if (diff.negative === 0) {
35709 a = diff;
35710 if (q) {
35711 q.words[m] = 1;
35712 }
35713 }
35714
35715 for (var j = m - 1; j >= 0; j--) {
35716 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
35717 (a.words[b.length + j - 1] | 0);
35718
35719 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
35720 // (0x7ffffff)
35721 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
35722
35723 a._ishlnsubmul(b, qj, j);
35724 while (a.negative !== 0) {
35725 qj--;
35726 a.negative = 0;
35727 a._ishlnsubmul(b, 1, j);
35728 if (!a.isZero()) {
35729 a.negative ^= 1;
35730 }
35731 }
35732 if (q) {
35733 q.words[j] = qj;
35734 }
35735 }
35736 if (q) {
35737 q.strip();
35738 }
35739 a.strip();
35740
35741 // Denormalize
35742 if (mode !== 'div' && shift !== 0) {
35743 a.iushrn(shift);
35744 }
35745
35746 return {
35747 div: q || null,
35748 mod: a
35749 };
35750 };
35751
35752 // NOTE: 1) `mode` can be set to `mod` to request mod only,
35753 // to `div` to request div only, or be absent to
35754 // request both div & mod
35755 // 2) `positive` is true if unsigned mod is requested
35756 BN.prototype.divmod = function divmod (num, mode, positive) {
35757 assert(!num.isZero());
35758
35759 if (this.isZero()) {
35760 return {
35761 div: new BN(0),
35762 mod: new BN(0)
35763 };
35764 }
35765
35766 var div, mod, res;
35767 if (this.negative !== 0 && num.negative === 0) {
35768 res = this.neg().divmod(num, mode);
35769
35770 if (mode !== 'mod') {
35771 div = res.div.neg();
35772 }
35773
35774 if (mode !== 'div') {
35775 mod = res.mod.neg();
35776 if (positive && mod.negative !== 0) {
35777 mod.iadd(num);
35778 }
35779 }
35780
35781 return {
35782 div: div,
35783 mod: mod
35784 };
35785 }
35786
35787 if (this.negative === 0 && num.negative !== 0) {
35788 res = this.divmod(num.neg(), mode);
35789
35790 if (mode !== 'mod') {
35791 div = res.div.neg();
35792 }
35793
35794 return {
35795 div: div,
35796 mod: res.mod
35797 };
35798 }
35799
35800 if ((this.negative & num.negative) !== 0) {
35801 res = this.neg().divmod(num.neg(), mode);
35802
35803 if (mode !== 'div') {
35804 mod = res.mod.neg();
35805 if (positive && mod.negative !== 0) {
35806 mod.isub(num);
35807 }
35808 }
35809
35810 return {
35811 div: res.div,
35812 mod: mod
35813 };
35814 }
35815
35816 // Both numbers are positive at this point
35817
35818 // Strip both numbers to approximate shift value
35819 if (num.length > this.length || this.cmp(num) < 0) {
35820 return {
35821 div: new BN(0),
35822 mod: this
35823 };
35824 }
35825
35826 // Very short reduction
35827 if (num.length === 1) {
35828 if (mode === 'div') {
35829 return {
35830 div: this.divn(num.words[0]),
35831 mod: null
35832 };
35833 }
35834
35835 if (mode === 'mod') {
35836 return {
35837 div: null,
35838 mod: new BN(this.modn(num.words[0]))
35839 };
35840 }
35841
35842 return {
35843 div: this.divn(num.words[0]),
35844 mod: new BN(this.modn(num.words[0]))
35845 };
35846 }
35847
35848 return this._wordDiv(num, mode);
35849 };
35850
35851 // Find `this` / `num`
35852 BN.prototype.div = function div (num) {
35853 return this.divmod(num, 'div', false).div;
35854 };
35855
35856 // Find `this` % `num`
35857 BN.prototype.mod = function mod (num) {
35858 return this.divmod(num, 'mod', false).mod;
35859 };
35860
35861 BN.prototype.umod = function umod (num) {
35862 return this.divmod(num, 'mod', true).mod;
35863 };
35864
35865 // Find Round(`this` / `num`)
35866 BN.prototype.divRound = function divRound (num) {
35867 var dm = this.divmod(num);
35868
35869 // Fast case - exact division
35870 if (dm.mod.isZero()) return dm.div;
35871
35872 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
35873
35874 var half = num.ushrn(1);
35875 var r2 = num.andln(1);
35876 var cmp = mod.cmp(half);
35877
35878 // Round down
35879 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
35880
35881 // Round up
35882 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
35883 };
35884
35885 BN.prototype.modn = function modn (num) {
35886 assert(num <= 0x3ffffff);
35887 var p = (1 << 26) % num;
35888
35889 var acc = 0;
35890 for (var i = this.length - 1; i >= 0; i--) {
35891 acc = (p * acc + (this.words[i] | 0)) % num;
35892 }
35893
35894 return acc;
35895 };
35896
35897 // In-place division by number
35898 BN.prototype.idivn = function idivn (num) {
35899 assert(num <= 0x3ffffff);
35900
35901 var carry = 0;
35902 for (var i = this.length - 1; i >= 0; i--) {
35903 var w = (this.words[i] | 0) + carry * 0x4000000;
35904 this.words[i] = (w / num) | 0;
35905 carry = w % num;
35906 }
35907
35908 return this.strip();
35909 };
35910
35911 BN.prototype.divn = function divn (num) {
35912 return this.clone().idivn(num);
35913 };
35914
35915 BN.prototype.egcd = function egcd (p) {
35916 assert(p.negative === 0);
35917 assert(!p.isZero());
35918
35919 var x = this;
35920 var y = p.clone();
35921
35922 if (x.negative !== 0) {
35923 x = x.umod(p);
35924 } else {
35925 x = x.clone();
35926 }
35927
35928 // A * x + B * y = x
35929 var A = new BN(1);
35930 var B = new BN(0);
35931
35932 // C * x + D * y = y
35933 var C = new BN(0);
35934 var D = new BN(1);
35935
35936 var g = 0;
35937
35938 while (x.isEven() && y.isEven()) {
35939 x.iushrn(1);
35940 y.iushrn(1);
35941 ++g;
35942 }
35943
35944 var yp = y.clone();
35945 var xp = x.clone();
35946
35947 while (!x.isZero()) {
35948 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
35949 if (i > 0) {
35950 x.iushrn(i);
35951 while (i-- > 0) {
35952 if (A.isOdd() || B.isOdd()) {
35953 A.iadd(yp);
35954 B.isub(xp);
35955 }
35956
35957 A.iushrn(1);
35958 B.iushrn(1);
35959 }
35960 }
35961
35962 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
35963 if (j > 0) {
35964 y.iushrn(j);
35965 while (j-- > 0) {
35966 if (C.isOdd() || D.isOdd()) {
35967 C.iadd(yp);
35968 D.isub(xp);
35969 }
35970
35971 C.iushrn(1);
35972 D.iushrn(1);
35973 }
35974 }
35975
35976 if (x.cmp(y) >= 0) {
35977 x.isub(y);
35978 A.isub(C);
35979 B.isub(D);
35980 } else {
35981 y.isub(x);
35982 C.isub(A);
35983 D.isub(B);
35984 }
35985 }
35986
35987 return {
35988 a: C,
35989 b: D,
35990 gcd: y.iushln(g)
35991 };
35992 };
35993
35994 // This is reduced incarnation of the binary EEA
35995 // above, designated to invert members of the
35996 // _prime_ fields F(p) at a maximal speed
35997 BN.prototype._invmp = function _invmp (p) {
35998 assert(p.negative === 0);
35999 assert(!p.isZero());
36000
36001 var a = this;
36002 var b = p.clone();
36003
36004 if (a.negative !== 0) {
36005 a = a.umod(p);
36006 } else {
36007 a = a.clone();
36008 }
36009
36010 var x1 = new BN(1);
36011 var x2 = new BN(0);
36012
36013 var delta = b.clone();
36014
36015 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
36016 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
36017 if (i > 0) {
36018 a.iushrn(i);
36019 while (i-- > 0) {
36020 if (x1.isOdd()) {
36021 x1.iadd(delta);
36022 }
36023
36024 x1.iushrn(1);
36025 }
36026 }
36027
36028 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
36029 if (j > 0) {
36030 b.iushrn(j);
36031 while (j-- > 0) {
36032 if (x2.isOdd()) {
36033 x2.iadd(delta);
36034 }
36035
36036 x2.iushrn(1);
36037 }
36038 }
36039
36040 if (a.cmp(b) >= 0) {
36041 a.isub(b);
36042 x1.isub(x2);
36043 } else {
36044 b.isub(a);
36045 x2.isub(x1);
36046 }
36047 }
36048
36049 var res;
36050 if (a.cmpn(1) === 0) {
36051 res = x1;
36052 } else {
36053 res = x2;
36054 }
36055
36056 if (res.cmpn(0) < 0) {
36057 res.iadd(p);
36058 }
36059
36060 return res;
36061 };
36062
36063 BN.prototype.gcd = function gcd (num) {
36064 if (this.isZero()) return num.abs();
36065 if (num.isZero()) return this.abs();
36066
36067 var a = this.clone();
36068 var b = num.clone();
36069 a.negative = 0;
36070 b.negative = 0;
36071
36072 // Remove common factor of two
36073 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
36074 a.iushrn(1);
36075 b.iushrn(1);
36076 }
36077
36078 do {
36079 while (a.isEven()) {
36080 a.iushrn(1);
36081 }
36082 while (b.isEven()) {
36083 b.iushrn(1);
36084 }
36085
36086 var r = a.cmp(b);
36087 if (r < 0) {
36088 // Swap `a` and `b` to make `a` always bigger than `b`
36089 var t = a;
36090 a = b;
36091 b = t;
36092 } else if (r === 0 || b.cmpn(1) === 0) {
36093 break;
36094 }
36095
36096 a.isub(b);
36097 } while (true);
36098
36099 return b.iushln(shift);
36100 };
36101
36102 // Invert number in the field F(num)
36103 BN.prototype.invm = function invm (num) {
36104 return this.egcd(num).a.umod(num);
36105 };
36106
36107 BN.prototype.isEven = function isEven () {
36108 return (this.words[0] & 1) === 0;
36109 };
36110
36111 BN.prototype.isOdd = function isOdd () {
36112 return (this.words[0] & 1) === 1;
36113 };
36114
36115 // And first word and num
36116 BN.prototype.andln = function andln (num) {
36117 return this.words[0] & num;
36118 };
36119
36120 // Increment at the bit position in-line
36121 BN.prototype.bincn = function bincn (bit) {
36122 assert(typeof bit === 'number');
36123 var r = bit % 26;
36124 var s = (bit - r) / 26;
36125 var q = 1 << r;
36126
36127 // Fast case: bit is much higher than all existing words
36128 if (this.length <= s) {
36129 this._expand(s + 1);
36130 this.words[s] |= q;
36131 return this;
36132 }
36133
36134 // Add bit and propagate, if needed
36135 var carry = q;
36136 for (var i = s; carry !== 0 && i < this.length; i++) {
36137 var w = this.words[i] | 0;
36138 w += carry;
36139 carry = w >>> 26;
36140 w &= 0x3ffffff;
36141 this.words[i] = w;
36142 }
36143 if (carry !== 0) {
36144 this.words[i] = carry;
36145 this.length++;
36146 }
36147 return this;
36148 };
36149
36150 BN.prototype.isZero = function isZero () {
36151 return this.length === 1 && this.words[0] === 0;
36152 };
36153
36154 BN.prototype.cmpn = function cmpn (num) {
36155 var negative = num < 0;
36156
36157 if (this.negative !== 0 && !negative) return -1;
36158 if (this.negative === 0 && negative) return 1;
36159
36160 this.strip();
36161
36162 var res;
36163 if (this.length > 1) {
36164 res = 1;
36165 } else {
36166 if (negative) {
36167 num = -num;
36168 }
36169
36170 assert(num <= 0x3ffffff, 'Number is too big');
36171
36172 var w = this.words[0] | 0;
36173 res = w === num ? 0 : w < num ? -1 : 1;
36174 }
36175 if (this.negative !== 0) return -res | 0;
36176 return res;
36177 };
36178
36179 // Compare two numbers and return:
36180 // 1 - if `this` > `num`
36181 // 0 - if `this` == `num`
36182 // -1 - if `this` < `num`
36183 BN.prototype.cmp = function cmp (num) {
36184 if (this.negative !== 0 && num.negative === 0) return -1;
36185 if (this.negative === 0 && num.negative !== 0) return 1;
36186
36187 var res = this.ucmp(num);
36188 if (this.negative !== 0) return -res | 0;
36189 return res;
36190 };
36191
36192 // Unsigned comparison
36193 BN.prototype.ucmp = function ucmp (num) {
36194 // At this point both numbers have the same sign
36195 if (this.length > num.length) return 1;
36196 if (this.length < num.length) return -1;
36197
36198 var res = 0;
36199 for (var i = this.length - 1; i >= 0; i--) {
36200 var a = this.words[i] | 0;
36201 var b = num.words[i] | 0;
36202
36203 if (a === b) continue;
36204 if (a < b) {
36205 res = -1;
36206 } else if (a > b) {
36207 res = 1;
36208 }
36209 break;
36210 }
36211 return res;
36212 };
36213
36214 BN.prototype.gtn = function gtn (num) {
36215 return this.cmpn(num) === 1;
36216 };
36217
36218 BN.prototype.gt = function gt (num) {
36219 return this.cmp(num) === 1;
36220 };
36221
36222 BN.prototype.gten = function gten (num) {
36223 return this.cmpn(num) >= 0;
36224 };
36225
36226 BN.prototype.gte = function gte (num) {
36227 return this.cmp(num) >= 0;
36228 };
36229
36230 BN.prototype.ltn = function ltn (num) {
36231 return this.cmpn(num) === -1;
36232 };
36233
36234 BN.prototype.lt = function lt (num) {
36235 return this.cmp(num) === -1;
36236 };
36237
36238 BN.prototype.lten = function lten (num) {
36239 return this.cmpn(num) <= 0;
36240 };
36241
36242 BN.prototype.lte = function lte (num) {
36243 return this.cmp(num) <= 0;
36244 };
36245
36246 BN.prototype.eqn = function eqn (num) {
36247 return this.cmpn(num) === 0;
36248 };
36249
36250 BN.prototype.eq = function eq (num) {
36251 return this.cmp(num) === 0;
36252 };
36253
36254 //
36255 // A reduce context, could be using montgomery or something better, depending
36256 // on the `m` itself.
36257 //
36258 BN.red = function red (num) {
36259 return new Red(num);
36260 };
36261
36262 BN.prototype.toRed = function toRed (ctx) {
36263 assert(!this.red, 'Already a number in reduction context');
36264 assert(this.negative === 0, 'red works only with positives');
36265 return ctx.convertTo(this)._forceRed(ctx);
36266 };
36267
36268 BN.prototype.fromRed = function fromRed () {
36269 assert(this.red, 'fromRed works only with numbers in reduction context');
36270 return this.red.convertFrom(this);
36271 };
36272
36273 BN.prototype._forceRed = function _forceRed (ctx) {
36274 this.red = ctx;
36275 return this;
36276 };
36277
36278 BN.prototype.forceRed = function forceRed (ctx) {
36279 assert(!this.red, 'Already a number in reduction context');
36280 return this._forceRed(ctx);
36281 };
36282
36283 BN.prototype.redAdd = function redAdd (num) {
36284 assert(this.red, 'redAdd works only with red numbers');
36285 return this.red.add(this, num);
36286 };
36287
36288 BN.prototype.redIAdd = function redIAdd (num) {
36289 assert(this.red, 'redIAdd works only with red numbers');
36290 return this.red.iadd(this, num);
36291 };
36292
36293 BN.prototype.redSub = function redSub (num) {
36294 assert(this.red, 'redSub works only with red numbers');
36295 return this.red.sub(this, num);
36296 };
36297
36298 BN.prototype.redISub = function redISub (num) {
36299 assert(this.red, 'redISub works only with red numbers');
36300 return this.red.isub(this, num);
36301 };
36302
36303 BN.prototype.redShl = function redShl (num) {
36304 assert(this.red, 'redShl works only with red numbers');
36305 return this.red.shl(this, num);
36306 };
36307
36308 BN.prototype.redMul = function redMul (num) {
36309 assert(this.red, 'redMul works only with red numbers');
36310 this.red._verify2(this, num);
36311 return this.red.mul(this, num);
36312 };
36313
36314 BN.prototype.redIMul = function redIMul (num) {
36315 assert(this.red, 'redMul works only with red numbers');
36316 this.red._verify2(this, num);
36317 return this.red.imul(this, num);
36318 };
36319
36320 BN.prototype.redSqr = function redSqr () {
36321 assert(this.red, 'redSqr works only with red numbers');
36322 this.red._verify1(this);
36323 return this.red.sqr(this);
36324 };
36325
36326 BN.prototype.redISqr = function redISqr () {
36327 assert(this.red, 'redISqr works only with red numbers');
36328 this.red._verify1(this);
36329 return this.red.isqr(this);
36330 };
36331
36332 // Square root over p
36333 BN.prototype.redSqrt = function redSqrt () {
36334 assert(this.red, 'redSqrt works only with red numbers');
36335 this.red._verify1(this);
36336 return this.red.sqrt(this);
36337 };
36338
36339 BN.prototype.redInvm = function redInvm () {
36340 assert(this.red, 'redInvm works only with red numbers');
36341 this.red._verify1(this);
36342 return this.red.invm(this);
36343 };
36344
36345 // Return negative clone of `this` % `red modulo`
36346 BN.prototype.redNeg = function redNeg () {
36347 assert(this.red, 'redNeg works only with red numbers');
36348 this.red._verify1(this);
36349 return this.red.neg(this);
36350 };
36351
36352 BN.prototype.redPow = function redPow (num) {
36353 assert(this.red && !num.red, 'redPow(normalNum)');
36354 this.red._verify1(this);
36355 return this.red.pow(this, num);
36356 };
36357
36358 // Prime numbers with efficient reduction
36359 var primes = {
36360 k256: null,
36361 p224: null,
36362 p192: null,
36363 p25519: null
36364 };
36365
36366 // Pseudo-Mersenne prime
36367 function MPrime (name, p) {
36368 // P = 2 ^ N - K
36369 this.name = name;
36370 this.p = new BN(p, 16);
36371 this.n = this.p.bitLength();
36372 this.k = new BN(1).iushln(this.n).isub(this.p);
36373
36374 this.tmp = this._tmp();
36375 }
36376
36377 MPrime.prototype._tmp = function _tmp () {
36378 var tmp = new BN(null);
36379 tmp.words = new Array(Math.ceil(this.n / 13));
36380 return tmp;
36381 };
36382
36383 MPrime.prototype.ireduce = function ireduce (num) {
36384 // Assumes that `num` is less than `P^2`
36385 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
36386 var r = num;
36387 var rlen;
36388
36389 do {
36390 this.split(r, this.tmp);
36391 r = this.imulK(r);
36392 r = r.iadd(this.tmp);
36393 rlen = r.bitLength();
36394 } while (rlen > this.n);
36395
36396 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
36397 if (cmp === 0) {
36398 r.words[0] = 0;
36399 r.length = 1;
36400 } else if (cmp > 0) {
36401 r.isub(this.p);
36402 } else {
36403 r.strip();
36404 }
36405
36406 return r;
36407 };
36408
36409 MPrime.prototype.split = function split (input, out) {
36410 input.iushrn(this.n, 0, out);
36411 };
36412
36413 MPrime.prototype.imulK = function imulK (num) {
36414 return num.imul(this.k);
36415 };
36416
36417 function K256 () {
36418 MPrime.call(
36419 this,
36420 'k256',
36421 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
36422 }
36423 inherits(K256, MPrime);
36424
36425 K256.prototype.split = function split (input, output) {
36426 // 256 = 9 * 26 + 22
36427 var mask = 0x3fffff;
36428
36429 var outLen = Math.min(input.length, 9);
36430 for (var i = 0; i < outLen; i++) {
36431 output.words[i] = input.words[i];
36432 }
36433 output.length = outLen;
36434
36435 if (input.length <= 9) {
36436 input.words[0] = 0;
36437 input.length = 1;
36438 return;
36439 }
36440
36441 // Shift by 9 limbs
36442 var prev = input.words[9];
36443 output.words[output.length++] = prev & mask;
36444
36445 for (i = 10; i < input.length; i++) {
36446 var next = input.words[i] | 0;
36447 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
36448 prev = next;
36449 }
36450 prev >>>= 22;
36451 input.words[i - 10] = prev;
36452 if (prev === 0 && input.length > 10) {
36453 input.length -= 10;
36454 } else {
36455 input.length -= 9;
36456 }
36457 };
36458
36459 K256.prototype.imulK = function imulK (num) {
36460 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
36461 num.words[num.length] = 0;
36462 num.words[num.length + 1] = 0;
36463 num.length += 2;
36464
36465 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
36466 var lo = 0;
36467 for (var i = 0; i < num.length; i++) {
36468 var w = num.words[i] | 0;
36469 lo += w * 0x3d1;
36470 num.words[i] = lo & 0x3ffffff;
36471 lo = w * 0x40 + ((lo / 0x4000000) | 0);
36472 }
36473
36474 // Fast length reduction
36475 if (num.words[num.length - 1] === 0) {
36476 num.length--;
36477 if (num.words[num.length - 1] === 0) {
36478 num.length--;
36479 }
36480 }
36481 return num;
36482 };
36483
36484 function P224 () {
36485 MPrime.call(
36486 this,
36487 'p224',
36488 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
36489 }
36490 inherits(P224, MPrime);
36491
36492 function P192 () {
36493 MPrime.call(
36494 this,
36495 'p192',
36496 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
36497 }
36498 inherits(P192, MPrime);
36499
36500 function P25519 () {
36501 // 2 ^ 255 - 19
36502 MPrime.call(
36503 this,
36504 '25519',
36505 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
36506 }
36507 inherits(P25519, MPrime);
36508
36509 P25519.prototype.imulK = function imulK (num) {
36510 // K = 0x13
36511 var carry = 0;
36512 for (var i = 0; i < num.length; i++) {
36513 var hi = (num.words[i] | 0) * 0x13 + carry;
36514 var lo = hi & 0x3ffffff;
36515 hi >>>= 26;
36516
36517 num.words[i] = lo;
36518 carry = hi;
36519 }
36520 if (carry !== 0) {
36521 num.words[num.length++] = carry;
36522 }
36523 return num;
36524 };
36525
36526 // Exported mostly for testing purposes, use plain name instead
36527 BN._prime = function prime (name) {
36528 // Cached version of prime
36529 if (primes[name]) return primes[name];
36530
36531 var prime;
36532 if (name === 'k256') {
36533 prime = new K256();
36534 } else if (name === 'p224') {
36535 prime = new P224();
36536 } else if (name === 'p192') {
36537 prime = new P192();
36538 } else if (name === 'p25519') {
36539 prime = new P25519();
36540 } else {
36541 throw new Error('Unknown prime ' + name);
36542 }
36543 primes[name] = prime;
36544
36545 return prime;
36546 };
36547
36548 //
36549 // Base reduction engine
36550 //
36551 function Red (m) {
36552 if (typeof m === 'string') {
36553 var prime = BN._prime(m);
36554 this.m = prime.p;
36555 this.prime = prime;
36556 } else {
36557 assert(m.gtn(1), 'modulus must be greater than 1');
36558 this.m = m;
36559 this.prime = null;
36560 }
36561 }
36562
36563 Red.prototype._verify1 = function _verify1 (a) {
36564 assert(a.negative === 0, 'red works only with positives');
36565 assert(a.red, 'red works only with red numbers');
36566 };
36567
36568 Red.prototype._verify2 = function _verify2 (a, b) {
36569 assert((a.negative | b.negative) === 0, 'red works only with positives');
36570 assert(a.red && a.red === b.red,
36571 'red works only with red numbers');
36572 };
36573
36574 Red.prototype.imod = function imod (a) {
36575 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
36576 return a.umod(this.m)._forceRed(this);
36577 };
36578
36579 Red.prototype.neg = function neg (a) {
36580 if (a.isZero()) {
36581 return a.clone();
36582 }
36583
36584 return this.m.sub(a)._forceRed(this);
36585 };
36586
36587 Red.prototype.add = function add (a, b) {
36588 this._verify2(a, b);
36589
36590 var res = a.add(b);
36591 if (res.cmp(this.m) >= 0) {
36592 res.isub(this.m);
36593 }
36594 return res._forceRed(this);
36595 };
36596
36597 Red.prototype.iadd = function iadd (a, b) {
36598 this._verify2(a, b);
36599
36600 var res = a.iadd(b);
36601 if (res.cmp(this.m) >= 0) {
36602 res.isub(this.m);
36603 }
36604 return res;
36605 };
36606
36607 Red.prototype.sub = function sub (a, b) {
36608 this._verify2(a, b);
36609
36610 var res = a.sub(b);
36611 if (res.cmpn(0) < 0) {
36612 res.iadd(this.m);
36613 }
36614 return res._forceRed(this);
36615 };
36616
36617 Red.prototype.isub = function isub (a, b) {
36618 this._verify2(a, b);
36619
36620 var res = a.isub(b);
36621 if (res.cmpn(0) < 0) {
36622 res.iadd(this.m);
36623 }
36624 return res;
36625 };
36626
36627 Red.prototype.shl = function shl (a, num) {
36628 this._verify1(a);
36629 return this.imod(a.ushln(num));
36630 };
36631
36632 Red.prototype.imul = function imul (a, b) {
36633 this._verify2(a, b);
36634 return this.imod(a.imul(b));
36635 };
36636
36637 Red.prototype.mul = function mul (a, b) {
36638 this._verify2(a, b);
36639 return this.imod(a.mul(b));
36640 };
36641
36642 Red.prototype.isqr = function isqr (a) {
36643 return this.imul(a, a.clone());
36644 };
36645
36646 Red.prototype.sqr = function sqr (a) {
36647 return this.mul(a, a);
36648 };
36649
36650 Red.prototype.sqrt = function sqrt (a) {
36651 if (a.isZero()) return a.clone();
36652
36653 var mod3 = this.m.andln(3);
36654 assert(mod3 % 2 === 1);
36655
36656 // Fast case
36657 if (mod3 === 3) {
36658 var pow = this.m.add(new BN(1)).iushrn(2);
36659 return this.pow(a, pow);
36660 }
36661
36662 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
36663 //
36664 // Find Q and S, that Q * 2 ^ S = (P - 1)
36665 var q = this.m.subn(1);
36666 var s = 0;
36667 while (!q.isZero() && q.andln(1) === 0) {
36668 s++;
36669 q.iushrn(1);
36670 }
36671 assert(!q.isZero());
36672
36673 var one = new BN(1).toRed(this);
36674 var nOne = one.redNeg();
36675
36676 // Find quadratic non-residue
36677 // NOTE: Max is such because of generalized Riemann hypothesis.
36678 var lpow = this.m.subn(1).iushrn(1);
36679 var z = this.m.bitLength();
36680 z = new BN(2 * z * z).toRed(this);
36681
36682 while (this.pow(z, lpow).cmp(nOne) !== 0) {
36683 z.redIAdd(nOne);
36684 }
36685
36686 var c = this.pow(z, q);
36687 var r = this.pow(a, q.addn(1).iushrn(1));
36688 var t = this.pow(a, q);
36689 var m = s;
36690 while (t.cmp(one) !== 0) {
36691 var tmp = t;
36692 for (var i = 0; tmp.cmp(one) !== 0; i++) {
36693 tmp = tmp.redSqr();
36694 }
36695 assert(i < m);
36696 var b = this.pow(c, new BN(1).iushln(m - i - 1));
36697
36698 r = r.redMul(b);
36699 c = b.redSqr();
36700 t = t.redMul(c);
36701 m = i;
36702 }
36703
36704 return r;
36705 };
36706
36707 Red.prototype.invm = function invm (a) {
36708 var inv = a._invmp(this.m);
36709 if (inv.negative !== 0) {
36710 inv.negative = 0;
36711 return this.imod(inv).redNeg();
36712 } else {
36713 return this.imod(inv);
36714 }
36715 };
36716
36717 Red.prototype.pow = function pow (a, num) {
36718 if (num.isZero()) return new BN(1).toRed(this);
36719 if (num.cmpn(1) === 0) return a.clone();
36720
36721 var windowSize = 4;
36722 var wnd = new Array(1 << windowSize);
36723 wnd[0] = new BN(1).toRed(this);
36724 wnd[1] = a;
36725 for (var i = 2; i < wnd.length; i++) {
36726 wnd[i] = this.mul(wnd[i - 1], a);
36727 }
36728
36729 var res = wnd[0];
36730 var current = 0;
36731 var currentLen = 0;
36732 var start = num.bitLength() % 26;
36733 if (start === 0) {
36734 start = 26;
36735 }
36736
36737 for (i = num.length - 1; i >= 0; i--) {
36738 var word = num.words[i];
36739 for (var j = start - 1; j >= 0; j--) {
36740 var bit = (word >> j) & 1;
36741 if (res !== wnd[0]) {
36742 res = this.sqr(res);
36743 }
36744
36745 if (bit === 0 && current === 0) {
36746 currentLen = 0;
36747 continue;
36748 }
36749
36750 current <<= 1;
36751 current |= bit;
36752 currentLen++;
36753 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
36754
36755 res = this.mul(res, wnd[current]);
36756 currentLen = 0;
36757 current = 0;
36758 }
36759 start = 26;
36760 }
36761
36762 return res;
36763 };
36764
36765 Red.prototype.convertTo = function convertTo (num) {
36766 var r = num.umod(this.m);
36767
36768 return r === num ? r.clone() : r;
36769 };
36770
36771 Red.prototype.convertFrom = function convertFrom (num) {
36772 var res = num.clone();
36773 res.red = null;
36774 return res;
36775 };
36776
36777 //
36778 // Montgomery method engine
36779 //
36780
36781 BN.mont = function mont (num) {
36782 return new Mont(num);
36783 };
36784
36785 function Mont (m) {
36786 Red.call(this, m);
36787
36788 this.shift = this.m.bitLength();
36789 if (this.shift % 26 !== 0) {
36790 this.shift += 26 - (this.shift % 26);
36791 }
36792
36793 this.r = new BN(1).iushln(this.shift);
36794 this.r2 = this.imod(this.r.sqr());
36795 this.rinv = this.r._invmp(this.m);
36796
36797 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
36798 this.minv = this.minv.umod(this.r);
36799 this.minv = this.r.sub(this.minv);
36800 }
36801 inherits(Mont, Red);
36802
36803 Mont.prototype.convertTo = function convertTo (num) {
36804 return this.imod(num.ushln(this.shift));
36805 };
36806
36807 Mont.prototype.convertFrom = function convertFrom (num) {
36808 var r = this.imod(num.mul(this.rinv));
36809 r.red = null;
36810 return r;
36811 };
36812
36813 Mont.prototype.imul = function imul (a, b) {
36814 if (a.isZero() || b.isZero()) {
36815 a.words[0] = 0;
36816 a.length = 1;
36817 return a;
36818 }
36819
36820 var t = a.imul(b);
36821 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
36822 var u = t.isub(c).iushrn(this.shift);
36823 var res = u;
36824
36825 if (u.cmp(this.m) >= 0) {
36826 res = u.isub(this.m);
36827 } else if (u.cmpn(0) < 0) {
36828 res = u.iadd(this.m);
36829 }
36830
36831 return res._forceRed(this);
36832 };
36833
36834 Mont.prototype.mul = function mul (a, b) {
36835 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
36836
36837 var t = a.mul(b);
36838 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
36839 var u = t.isub(c).iushrn(this.shift);
36840 var res = u;
36841 if (u.cmp(this.m) >= 0) {
36842 res = u.isub(this.m);
36843 } else if (u.cmpn(0) < 0) {
36844 res = u.iadd(this.m);
36845 }
36846
36847 return res._forceRed(this);
36848 };
36849
36850 Mont.prototype.invm = function invm (a) {
36851 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
36852 var res = this.imod(a._invmp(this.m).mul(this.r2));
36853 return res._forceRed(this);
36854 };
36855})(module, commonjsGlobal);
36856});
36857
36858var bn$1 = /*#__PURE__*/Object.freeze({
36859 __proto__: null,
36860 'default': bn,
36861 __moduleExports: bn
36862});
36863
36864/**
36865 * @fileoverview
36866 * BigInteger implementation of basic operations
36867 * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
36868 * @module biginteger/bn
36869 * @private
36870 */
36871
36872/**
36873 * @private
36874 */
36875class BigInteger$1 {
36876 /**
36877 * Get a BigInteger (input must be big endian for strings and arrays)
36878 * @param {Number|String|Uint8Array} n - Value to convert
36879 * @throws {Error} on undefined input
36880 */
36881 constructor(n) {
36882 if (n === undefined) {
36883 throw new Error('Invalid BigInteger input');
36884 }
36885
36886 this.value = new bn(n);
36887 }
36888
36889 clone() {
36890 const clone = new BigInteger$1(null);
36891 this.value.copy(clone.value);
36892 return clone;
36893 }
36894
36895 /**
36896 * BigInteger increment in place
36897 */
36898 iinc() {
36899 this.value.iadd(new bn(1));
36900 return this;
36901 }
36902
36903 /**
36904 * BigInteger increment
36905 * @returns {BigInteger} this + 1.
36906 */
36907 inc() {
36908 return this.clone().iinc();
36909 }
36910
36911 /**
36912 * BigInteger decrement in place
36913 */
36914 idec() {
36915 this.value.isub(new bn(1));
36916 return this;
36917 }
36918
36919 /**
36920 * BigInteger decrement
36921 * @returns {BigInteger} this - 1.
36922 */
36923 dec() {
36924 return this.clone().idec();
36925 }
36926
36927
36928 /**
36929 * BigInteger addition in place
36930 * @param {BigInteger} x - Value to add
36931 */
36932 iadd(x) {
36933 this.value.iadd(x.value);
36934 return this;
36935 }
36936
36937 /**
36938 * BigInteger addition
36939 * @param {BigInteger} x - Value to add
36940 * @returns {BigInteger} this + x.
36941 */
36942 add(x) {
36943 return this.clone().iadd(x);
36944 }
36945
36946 /**
36947 * BigInteger subtraction in place
36948 * @param {BigInteger} x - Value to subtract
36949 */
36950 isub(x) {
36951 this.value.isub(x.value);
36952 return this;
36953 }
36954
36955 /**
36956 * BigInteger subtraction
36957 * @param {BigInteger} x - Value to subtract
36958 * @returns {BigInteger} this - x.
36959 */
36960 sub(x) {
36961 return this.clone().isub(x);
36962 }
36963
36964 /**
36965 * BigInteger multiplication in place
36966 * @param {BigInteger} x - Value to multiply
36967 */
36968 imul(x) {
36969 this.value.imul(x.value);
36970 return this;
36971 }
36972
36973 /**
36974 * BigInteger multiplication
36975 * @param {BigInteger} x - Value to multiply
36976 * @returns {BigInteger} this * x.
36977 */
36978 mul(x) {
36979 return this.clone().imul(x);
36980 }
36981
36982 /**
36983 * Compute value modulo m, in place
36984 * @param {BigInteger} m - Modulo
36985 */
36986 imod(m) {
36987 this.value = this.value.umod(m.value);
36988 return this;
36989 }
36990
36991 /**
36992 * Compute value modulo m
36993 * @param {BigInteger} m - Modulo
36994 * @returns {BigInteger} this mod m.
36995 */
36996 mod(m) {
36997 return this.clone().imod(m);
36998 }
36999
37000 /**
37001 * Compute modular exponentiation
37002 * Much faster than this.exp(e).mod(n)
37003 * @param {BigInteger} e - Exponent
37004 * @param {BigInteger} n - Modulo
37005 * @returns {BigInteger} this ** e mod n.
37006 */
37007 modExp(e, n) {
37008 // We use either Montgomery or normal reduction context
37009 // Montgomery requires coprime n and R (montogmery multiplier)
37010 // bn.js picks R as power of 2, so n must be odd
37011 const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value);
37012 const x = this.clone();
37013 x.value = x.value.toRed(nred).redPow(e.value).fromRed();
37014 return x;
37015 }
37016
37017 /**
37018 * Compute the inverse of this value modulo n
37019 * Note: this and and n must be relatively prime
37020 * @param {BigInteger} n - Modulo
37021 * @returns {BigInteger} x such that this*x = 1 mod n
37022 * @throws {Error} if the inverse does not exist
37023 */
37024 modInv(n) {
37025 // invm returns a wrong result if the inverse does not exist
37026 if (!this.gcd(n).isOne()) {
37027 throw new Error('Inverse does not exist');
37028 }
37029 return new BigInteger$1(this.value.invm(n.value));
37030 }
37031
37032 /**
37033 * Compute greatest common divisor between this and n
37034 * @param {BigInteger} n - Operand
37035 * @returns {BigInteger} gcd
37036 */
37037 gcd(n) {
37038 return new BigInteger$1(this.value.gcd(n.value));
37039 }
37040
37041 /**
37042 * Shift this to the left by x, in place
37043 * @param {BigInteger} x - Shift value
37044 */
37045 ileftShift(x) {
37046 this.value.ishln(x.value.toNumber());
37047 return this;
37048 }
37049
37050 /**
37051 * Shift this to the left by x
37052 * @param {BigInteger} x - Shift value
37053 * @returns {BigInteger} this << x.
37054 */
37055 leftShift(x) {
37056 return this.clone().ileftShift(x);
37057 }
37058
37059 /**
37060 * Shift this to the right by x, in place
37061 * @param {BigInteger} x - Shift value
37062 */
37063 irightShift(x) {
37064 this.value.ishrn(x.value.toNumber());
37065 return this;
37066 }
37067
37068 /**
37069 * Shift this to the right by x
37070 * @param {BigInteger} x - Shift value
37071 * @returns {BigInteger} this >> x.
37072 */
37073 rightShift(x) {
37074 return this.clone().irightShift(x);
37075 }
37076
37077 /**
37078 * Whether this value is equal to x
37079 * @param {BigInteger} x
37080 * @returns {Boolean}
37081 */
37082 equal(x) {
37083 return this.value.eq(x.value);
37084 }
37085
37086 /**
37087 * Whether this value is less than x
37088 * @param {BigInteger} x
37089 * @returns {Boolean}
37090 */
37091 lt(x) {
37092 return this.value.lt(x.value);
37093 }
37094
37095 /**
37096 * Whether this value is less than or equal to x
37097 * @param {BigInteger} x
37098 * @returns {Boolean}
37099 */
37100 lte(x) {
37101 return this.value.lte(x.value);
37102 }
37103
37104 /**
37105 * Whether this value is greater than x
37106 * @param {BigInteger} x
37107 * @returns {Boolean}
37108 */
37109 gt(x) {
37110 return this.value.gt(x.value);
37111 }
37112
37113 /**
37114 * Whether this value is greater than or equal to x
37115 * @param {BigInteger} x
37116 * @returns {Boolean}
37117 */
37118 gte(x) {
37119 return this.value.gte(x.value);
37120 }
37121
37122 isZero() {
37123 return this.value.isZero();
37124 }
37125
37126 isOne() {
37127 return this.value.eq(new bn(1));
37128 }
37129
37130 isNegative() {
37131 return this.value.isNeg();
37132 }
37133
37134 isEven() {
37135 return this.value.isEven();
37136 }
37137
37138 abs() {
37139 const res = this.clone();
37140 res.value = res.value.abs();
37141 return res;
37142 }
37143
37144 /**
37145 * Get this value as a string
37146 * @returns {String} this value.
37147 */
37148 toString() {
37149 return this.value.toString();
37150 }
37151
37152 /**
37153 * Get this value as an exact Number (max 53 bits)
37154 * Fails if this value is too large
37155 * @returns {Number}
37156 */
37157 toNumber() {
37158 return this.value.toNumber();
37159 }
37160
37161 /**
37162 * Get value of i-th bit
37163 * @param {Number} i - Bit index
37164 * @returns {Number} Bit value.
37165 */
37166 getBit(i) {
37167 return this.value.testn(i) ? 1 : 0;
37168 }
37169
37170 /**
37171 * Compute bit length
37172 * @returns {Number} Bit length.
37173 */
37174 bitLength() {
37175 return this.value.bitLength();
37176 }
37177
37178 /**
37179 * Compute byte length
37180 * @returns {Number} Byte length.
37181 */
37182 byteLength() {
37183 return this.value.byteLength();
37184 }
37185
37186 /**
37187 * Get Uint8Array representation of this number
37188 * @param {String} endian - Endianess of output array (defaults to 'be')
37189 * @param {Number} length - Of output array
37190 * @returns {Uint8Array}
37191 */
37192 toUint8Array(endian = 'be', length) {
37193 return this.value.toArrayLike(Uint8Array, endian, length);
37194 }
37195}
37196
37197var bn_interface = /*#__PURE__*/Object.freeze({
37198 __proto__: null,
37199 'default': BigInteger$1
37200});
37201
37202var utils_1 = createCommonjsModule(function (module, exports) {
37203
37204var utils = exports;
37205
37206function toArray(msg, enc) {
37207 if (Array.isArray(msg))
37208 return msg.slice();
37209 if (!msg)
37210 return [];
37211 var res = [];
37212 if (typeof msg !== 'string') {
37213 for (var i = 0; i < msg.length; i++)
37214 res[i] = msg[i] | 0;
37215 return res;
37216 }
37217 if (enc === 'hex') {
37218 msg = msg.replace(/[^a-z0-9]+/ig, '');
37219 if (msg.length % 2 !== 0)
37220 msg = '0' + msg;
37221 for (var i = 0; i < msg.length; i += 2)
37222 res.push(parseInt(msg[i] + msg[i + 1], 16));
37223 } else {
37224 for (var i = 0; i < msg.length; i++) {
37225 var c = msg.charCodeAt(i);
37226 var hi = c >> 8;
37227 var lo = c & 0xff;
37228 if (hi)
37229 res.push(hi, lo);
37230 else
37231 res.push(lo);
37232 }
37233 }
37234 return res;
37235}
37236utils.toArray = toArray;
37237
37238function zero2(word) {
37239 if (word.length === 1)
37240 return '0' + word;
37241 else
37242 return word;
37243}
37244utils.zero2 = zero2;
37245
37246function toHex(msg) {
37247 var res = '';
37248 for (var i = 0; i < msg.length; i++)
37249 res += zero2(msg[i].toString(16));
37250 return res;
37251}
37252utils.toHex = toHex;
37253
37254utils.encode = function encode(arr, enc) {
37255 if (enc === 'hex')
37256 return toHex(arr);
37257 else
37258 return arr;
37259};
37260});
37261
37262var utils_1$1 = createCommonjsModule(function (module, exports) {
37263
37264var utils = exports;
37265
37266
37267
37268
37269utils.assert = minimalisticAssert;
37270utils.toArray = utils_1.toArray;
37271utils.zero2 = utils_1.zero2;
37272utils.toHex = utils_1.toHex;
37273utils.encode = utils_1.encode;
37274
37275// Represent num in a w-NAF form
37276function getNAF(num, w) {
37277 var naf = [];
37278 var ws = 1 << (w + 1);
37279 var k = num.clone();
37280 while (k.cmpn(1) >= 0) {
37281 var z;
37282 if (k.isOdd()) {
37283 var mod = k.andln(ws - 1);
37284 if (mod > (ws >> 1) - 1)
37285 z = (ws >> 1) - mod;
37286 else
37287 z = mod;
37288 k.isubn(z);
37289 } else {
37290 z = 0;
37291 }
37292 naf.push(z);
37293
37294 // Optimization, shift by word if possible
37295 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
37296 for (var i = 1; i < shift; i++)
37297 naf.push(0);
37298 k.iushrn(shift);
37299 }
37300
37301 return naf;
37302}
37303utils.getNAF = getNAF;
37304
37305// Represent k1, k2 in a Joint Sparse Form
37306function getJSF(k1, k2) {
37307 var jsf = [
37308 [],
37309 []
37310 ];
37311
37312 k1 = k1.clone();
37313 k2 = k2.clone();
37314 var d1 = 0;
37315 var d2 = 0;
37316 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
37317
37318 // First phase
37319 var m14 = (k1.andln(3) + d1) & 3;
37320 var m24 = (k2.andln(3) + d2) & 3;
37321 if (m14 === 3)
37322 m14 = -1;
37323 if (m24 === 3)
37324 m24 = -1;
37325 var u1;
37326 if ((m14 & 1) === 0) {
37327 u1 = 0;
37328 } else {
37329 var m8 = (k1.andln(7) + d1) & 7;
37330 if ((m8 === 3 || m8 === 5) && m24 === 2)
37331 u1 = -m14;
37332 else
37333 u1 = m14;
37334 }
37335 jsf[0].push(u1);
37336
37337 var u2;
37338 if ((m24 & 1) === 0) {
37339 u2 = 0;
37340 } else {
37341 var m8 = (k2.andln(7) + d2) & 7;
37342 if ((m8 === 3 || m8 === 5) && m14 === 2)
37343 u2 = -m24;
37344 else
37345 u2 = m24;
37346 }
37347 jsf[1].push(u2);
37348
37349 // Second phase
37350 if (2 * d1 === u1 + 1)
37351 d1 = 1 - d1;
37352 if (2 * d2 === u2 + 1)
37353 d2 = 1 - d2;
37354 k1.iushrn(1);
37355 k2.iushrn(1);
37356 }
37357
37358 return jsf;
37359}
37360utils.getJSF = getJSF;
37361
37362function cachedProperty(obj, name, computer) {
37363 var key = '_' + name;
37364 obj.prototype[name] = function cachedProperty() {
37365 return this[key] !== undefined ? this[key] :
37366 this[key] = computer.call(this);
37367 };
37368}
37369utils.cachedProperty = cachedProperty;
37370
37371function parseBytes(bytes) {
37372 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
37373 bytes;
37374}
37375utils.parseBytes = parseBytes;
37376
37377function intFromLE(bytes) {
37378 return new bn(bytes, 'hex', 'le');
37379}
37380utils.intFromLE = intFromLE;
37381});
37382
37383var r$1;
37384
37385var brorand = function rand(len) {
37386 if (!r$1)
37387 r$1 = new Rand(null);
37388
37389 return r$1.generate(len);
37390};
37391
37392function Rand(rand) {
37393 this.rand = rand;
37394}
37395var Rand_1 = Rand;
37396
37397Rand.prototype.generate = function generate(len) {
37398 return this._rand(len);
37399};
37400
37401// Emulate crypto API using randy
37402Rand.prototype._rand = function _rand(n) {
37403 if (this.rand.getBytes)
37404 return this.rand.getBytes(n);
37405
37406 var res = new Uint8Array(n);
37407 for (var i = 0; i < res.length; i++)
37408 res[i] = this.rand.getByte();
37409 return res;
37410};
37411
37412if (typeof self === 'object') {
37413 if (self.crypto && self.crypto.getRandomValues) {
37414 // Modern browsers
37415 Rand.prototype._rand = function _rand(n) {
37416 var arr = new Uint8Array(n);
37417 self.crypto.getRandomValues(arr);
37418 return arr;
37419 };
37420 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
37421 // IE
37422 Rand.prototype._rand = function _rand(n) {
37423 var arr = new Uint8Array(n);
37424 self.msCrypto.getRandomValues(arr);
37425 return arr;
37426 };
37427
37428 // Safari's WebWorkers do not have `crypto`
37429 } else if (typeof window === 'object') {
37430 // Old junk
37431 Rand.prototype._rand = function() {
37432 throw new Error('Not implemented yet');
37433 };
37434 }
37435} else {
37436 // Node.js or Web worker with no crypto support
37437 try {
37438 var crypto$2 = crypto__default['default'];
37439 if (typeof crypto$2.randomBytes !== 'function')
37440 throw new Error('Not supported');
37441
37442 Rand.prototype._rand = function _rand(n) {
37443 return crypto$2.randomBytes(n);
37444 };
37445 } catch (e) {
37446 }
37447}
37448brorand.Rand = Rand_1;
37449
37450var getNAF = utils_1$1.getNAF;
37451var getJSF = utils_1$1.getJSF;
37452var assert$2 = utils_1$1.assert;
37453
37454function BaseCurve(type, conf) {
37455 this.type = type;
37456 this.p = new bn(conf.p, 16);
37457
37458 // Use Montgomery, when there is no fast reduction for the prime
37459 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
37460
37461 // Useful for many curves
37462 this.zero = new bn(0).toRed(this.red);
37463 this.one = new bn(1).toRed(this.red);
37464 this.two = new bn(2).toRed(this.red);
37465
37466 // Curve configuration, optional
37467 this.n = conf.n && new bn(conf.n, 16);
37468 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
37469
37470 // Temporary arrays
37471 this._wnafT1 = new Array(4);
37472 this._wnafT2 = new Array(4);
37473 this._wnafT3 = new Array(4);
37474 this._wnafT4 = new Array(4);
37475
37476 // Generalized Greg Maxwell's trick
37477 var adjustCount = this.n && this.p.div(this.n);
37478 if (!adjustCount || adjustCount.cmpn(100) > 0) {
37479 this.redN = null;
37480 } else {
37481 this._maxwellTrick = true;
37482 this.redN = this.n.toRed(this.red);
37483 }
37484}
37485var base = BaseCurve;
37486
37487BaseCurve.prototype.point = function point() {
37488 throw new Error('Not implemented');
37489};
37490
37491BaseCurve.prototype.validate = function validate() {
37492 throw new Error('Not implemented');
37493};
37494
37495BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
37496 assert$2(p.precomputed);
37497 var doubles = p._getDoubles();
37498
37499 var naf = getNAF(k, 1);
37500 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
37501 I /= 3;
37502
37503 // Translate into more windowed form
37504 var repr = [];
37505 for (var j = 0; j < naf.length; j += doubles.step) {
37506 var nafW = 0;
37507 for (var k = j + doubles.step - 1; k >= j; k--)
37508 nafW = (nafW << 1) + naf[k];
37509 repr.push(nafW);
37510 }
37511
37512 var a = this.jpoint(null, null, null);
37513 var b = this.jpoint(null, null, null);
37514 for (var i = I; i > 0; i--) {
37515 for (var j = 0; j < repr.length; j++) {
37516 var nafW = repr[j];
37517 if (nafW === i)
37518 b = b.mixedAdd(doubles.points[j]);
37519 else if (nafW === -i)
37520 b = b.mixedAdd(doubles.points[j].neg());
37521 }
37522 a = a.add(b);
37523 }
37524 return a.toP();
37525};
37526
37527BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
37528 var w = 4;
37529
37530 // Precompute window
37531 var nafPoints = p._getNAFPoints(w);
37532 w = nafPoints.wnd;
37533 var wnd = nafPoints.points;
37534
37535 // Get NAF form
37536 var naf = getNAF(k, w);
37537
37538 // Add `this`*(N+1) for every w-NAF index
37539 var acc = this.jpoint(null, null, null);
37540 for (var i = naf.length - 1; i >= 0; i--) {
37541 // Count zeroes
37542 for (var k = 0; i >= 0 && naf[i] === 0; i--)
37543 k++;
37544 if (i >= 0)
37545 k++;
37546 acc = acc.dblp(k);
37547
37548 if (i < 0)
37549 break;
37550 var z = naf[i];
37551 assert$2(z !== 0);
37552 if (p.type === 'affine') {
37553 // J +- P
37554 if (z > 0)
37555 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
37556 else
37557 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
37558 } else {
37559 // J +- J
37560 if (z > 0)
37561 acc = acc.add(wnd[(z - 1) >> 1]);
37562 else
37563 acc = acc.add(wnd[(-z - 1) >> 1].neg());
37564 }
37565 }
37566 return p.type === 'affine' ? acc.toP() : acc;
37567};
37568
37569BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
37570 points,
37571 coeffs,
37572 len,
37573 jacobianResult) {
37574 var wndWidth = this._wnafT1;
37575 var wnd = this._wnafT2;
37576 var naf = this._wnafT3;
37577
37578 // Fill all arrays
37579 var max = 0;
37580 for (var i = 0; i < len; i++) {
37581 var p = points[i];
37582 var nafPoints = p._getNAFPoints(defW);
37583 wndWidth[i] = nafPoints.wnd;
37584 wnd[i] = nafPoints.points;
37585 }
37586
37587 // Comb small window NAFs
37588 for (var i = len - 1; i >= 1; i -= 2) {
37589 var a = i - 1;
37590 var b = i;
37591 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
37592 naf[a] = getNAF(coeffs[a], wndWidth[a]);
37593 naf[b] = getNAF(coeffs[b], wndWidth[b]);
37594 max = Math.max(naf[a].length, max);
37595 max = Math.max(naf[b].length, max);
37596 continue;
37597 }
37598
37599 var comb = [
37600 points[a], /* 1 */
37601 null, /* 3 */
37602 null, /* 5 */
37603 points[b] /* 7 */
37604 ];
37605
37606 // Try to avoid Projective points, if possible
37607 if (points[a].y.cmp(points[b].y) === 0) {
37608 comb[1] = points[a].add(points[b]);
37609 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
37610 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
37611 comb[1] = points[a].toJ().mixedAdd(points[b]);
37612 comb[2] = points[a].add(points[b].neg());
37613 } else {
37614 comb[1] = points[a].toJ().mixedAdd(points[b]);
37615 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
37616 }
37617
37618 var index = [
37619 -3, /* -1 -1 */
37620 -1, /* -1 0 */
37621 -5, /* -1 1 */
37622 -7, /* 0 -1 */
37623 0, /* 0 0 */
37624 7, /* 0 1 */
37625 5, /* 1 -1 */
37626 1, /* 1 0 */
37627 3 /* 1 1 */
37628 ];
37629
37630 var jsf = getJSF(coeffs[a], coeffs[b]);
37631 max = Math.max(jsf[0].length, max);
37632 naf[a] = new Array(max);
37633 naf[b] = new Array(max);
37634 for (var j = 0; j < max; j++) {
37635 var ja = jsf[0][j] | 0;
37636 var jb = jsf[1][j] | 0;
37637
37638 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
37639 naf[b][j] = 0;
37640 wnd[a] = comb;
37641 }
37642 }
37643
37644 var acc = this.jpoint(null, null, null);
37645 var tmp = this._wnafT4;
37646 for (var i = max; i >= 0; i--) {
37647 var k = 0;
37648
37649 while (i >= 0) {
37650 var zero = true;
37651 for (var j = 0; j < len; j++) {
37652 tmp[j] = naf[j][i] | 0;
37653 if (tmp[j] !== 0)
37654 zero = false;
37655 }
37656 if (!zero)
37657 break;
37658 k++;
37659 i--;
37660 }
37661 if (i >= 0)
37662 k++;
37663 acc = acc.dblp(k);
37664 if (i < 0)
37665 break;
37666
37667 for (var j = 0; j < len; j++) {
37668 var z = tmp[j];
37669 var p;
37670 if (z === 0)
37671 continue;
37672 else if (z > 0)
37673 p = wnd[j][(z - 1) >> 1];
37674 else if (z < 0)
37675 p = wnd[j][(-z - 1) >> 1].neg();
37676
37677 if (p.type === 'affine')
37678 acc = acc.mixedAdd(p);
37679 else
37680 acc = acc.add(p);
37681 }
37682 }
37683 // Zeroify references
37684 for (var i = 0; i < len; i++)
37685 wnd[i] = null;
37686
37687 if (jacobianResult)
37688 return acc;
37689 else
37690 return acc.toP();
37691};
37692
37693function BasePoint(curve, type) {
37694 this.curve = curve;
37695 this.type = type;
37696 this.precomputed = null;
37697}
37698BaseCurve.BasePoint = BasePoint;
37699
37700BasePoint.prototype.eq = function eq(/*other*/) {
37701 throw new Error('Not implemented');
37702};
37703
37704BasePoint.prototype.validate = function validate() {
37705 return this.curve.validate(this);
37706};
37707
37708BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
37709 bytes = utils_1$1.toArray(bytes, enc);
37710
37711 var len = this.p.byteLength();
37712
37713 // uncompressed, hybrid-odd, hybrid-even
37714 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
37715 bytes.length - 1 === 2 * len) {
37716 if (bytes[0] === 0x06)
37717 assert$2(bytes[bytes.length - 1] % 2 === 0);
37718 else if (bytes[0] === 0x07)
37719 assert$2(bytes[bytes.length - 1] % 2 === 1);
37720
37721 var res = this.point(bytes.slice(1, 1 + len),
37722 bytes.slice(1 + len, 1 + 2 * len));
37723
37724 return res;
37725 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
37726 bytes.length - 1 === len) {
37727 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
37728 }
37729 throw new Error('Unknown point format');
37730};
37731
37732BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
37733 return this.encode(enc, true);
37734};
37735
37736BasePoint.prototype._encode = function _encode(compact) {
37737 var len = this.curve.p.byteLength();
37738 var x = this.getX().toArray('be', len);
37739
37740 if (compact)
37741 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
37742
37743 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
37744};
37745
37746BasePoint.prototype.encode = function encode(enc, compact) {
37747 return utils_1$1.encode(this._encode(compact), enc);
37748};
37749
37750BasePoint.prototype.precompute = function precompute(power) {
37751 if (this.precomputed)
37752 return this;
37753
37754 var precomputed = {
37755 doubles: null,
37756 naf: null,
37757 beta: null
37758 };
37759 precomputed.naf = this._getNAFPoints(8);
37760 precomputed.doubles = this._getDoubles(4, power);
37761 precomputed.beta = this._getBeta();
37762 this.precomputed = precomputed;
37763
37764 return this;
37765};
37766
37767BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
37768 if (!this.precomputed)
37769 return false;
37770
37771 var doubles = this.precomputed.doubles;
37772 if (!doubles)
37773 return false;
37774
37775 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
37776};
37777
37778BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
37779 if (this.precomputed && this.precomputed.doubles)
37780 return this.precomputed.doubles;
37781
37782 var doubles = [ this ];
37783 var acc = this;
37784 for (var i = 0; i < power; i += step) {
37785 for (var j = 0; j < step; j++)
37786 acc = acc.dbl();
37787 doubles.push(acc);
37788 }
37789 return {
37790 step: step,
37791 points: doubles
37792 };
37793};
37794
37795BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
37796 if (this.precomputed && this.precomputed.naf)
37797 return this.precomputed.naf;
37798
37799 var res = [ this ];
37800 var max = (1 << wnd) - 1;
37801 var dbl = max === 1 ? null : this.dbl();
37802 for (var i = 1; i < max; i++)
37803 res[i] = res[i - 1].add(dbl);
37804 return {
37805 wnd: wnd,
37806 points: res
37807 };
37808};
37809
37810BasePoint.prototype._getBeta = function _getBeta() {
37811 return null;
37812};
37813
37814BasePoint.prototype.dblp = function dblp(k) {
37815 var r = this;
37816 for (var i = 0; i < k; i++)
37817 r = r.dbl();
37818 return r;
37819};
37820
37821var assert$3 = utils_1$1.assert;
37822
37823function ShortCurve(conf) {
37824 base.call(this, 'short', conf);
37825
37826 this.a = new bn(conf.a, 16).toRed(this.red);
37827 this.b = new bn(conf.b, 16).toRed(this.red);
37828 this.tinv = this.two.redInvm();
37829
37830 this.zeroA = this.a.fromRed().cmpn(0) === 0;
37831 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
37832
37833 // If the curve is endomorphic, precalculate beta and lambda
37834 this.endo = this._getEndomorphism(conf);
37835 this._endoWnafT1 = new Array(4);
37836 this._endoWnafT2 = new Array(4);
37837}
37838inherits(ShortCurve, base);
37839var short_1 = ShortCurve;
37840
37841ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
37842 // No efficient endomorphism
37843 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
37844 return;
37845
37846 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
37847 var beta;
37848 var lambda;
37849 if (conf.beta) {
37850 beta = new bn(conf.beta, 16).toRed(this.red);
37851 } else {
37852 var betas = this._getEndoRoots(this.p);
37853 // Choose the smallest beta
37854 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
37855 beta = beta.toRed(this.red);
37856 }
37857 if (conf.lambda) {
37858 lambda = new bn(conf.lambda, 16);
37859 } else {
37860 // Choose the lambda that is matching selected beta
37861 var lambdas = this._getEndoRoots(this.n);
37862 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
37863 lambda = lambdas[0];
37864 } else {
37865 lambda = lambdas[1];
37866 assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
37867 }
37868 }
37869
37870 // Get basis vectors, used for balanced length-two representation
37871 var basis;
37872 if (conf.basis) {
37873 basis = conf.basis.map(function(vec) {
37874 return {
37875 a: new bn(vec.a, 16),
37876 b: new bn(vec.b, 16)
37877 };
37878 });
37879 } else {
37880 basis = this._getEndoBasis(lambda);
37881 }
37882
37883 return {
37884 beta: beta,
37885 lambda: lambda,
37886 basis: basis
37887 };
37888};
37889
37890ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
37891 // Find roots of for x^2 + x + 1 in F
37892 // Root = (-1 +- Sqrt(-3)) / 2
37893 //
37894 var red = num === this.p ? this.red : bn.mont(num);
37895 var tinv = new bn(2).toRed(red).redInvm();
37896 var ntinv = tinv.redNeg();
37897
37898 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
37899
37900 var l1 = ntinv.redAdd(s).fromRed();
37901 var l2 = ntinv.redSub(s).fromRed();
37902 return [ l1, l2 ];
37903};
37904
37905ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
37906 // aprxSqrt >= sqrt(this.n)
37907 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
37908
37909 // 3.74
37910 // Run EGCD, until r(L + 1) < aprxSqrt
37911 var u = lambda;
37912 var v = this.n.clone();
37913 var x1 = new bn(1);
37914 var y1 = new bn(0);
37915 var x2 = new bn(0);
37916 var y2 = new bn(1);
37917
37918 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
37919 var a0;
37920 var b0;
37921 // First vector
37922 var a1;
37923 var b1;
37924 // Second vector
37925 var a2;
37926 var b2;
37927
37928 var prevR;
37929 var i = 0;
37930 var r;
37931 var x;
37932 while (u.cmpn(0) !== 0) {
37933 var q = v.div(u);
37934 r = v.sub(q.mul(u));
37935 x = x2.sub(q.mul(x1));
37936 var y = y2.sub(q.mul(y1));
37937
37938 if (!a1 && r.cmp(aprxSqrt) < 0) {
37939 a0 = prevR.neg();
37940 b0 = x1;
37941 a1 = r.neg();
37942 b1 = x;
37943 } else if (a1 && ++i === 2) {
37944 break;
37945 }
37946 prevR = r;
37947
37948 v = u;
37949 u = r;
37950 x2 = x1;
37951 x1 = x;
37952 y2 = y1;
37953 y1 = y;
37954 }
37955 a2 = r.neg();
37956 b2 = x;
37957
37958 var len1 = a1.sqr().add(b1.sqr());
37959 var len2 = a2.sqr().add(b2.sqr());
37960 if (len2.cmp(len1) >= 0) {
37961 a2 = a0;
37962 b2 = b0;
37963 }
37964
37965 // Normalize signs
37966 if (a1.negative) {
37967 a1 = a1.neg();
37968 b1 = b1.neg();
37969 }
37970 if (a2.negative) {
37971 a2 = a2.neg();
37972 b2 = b2.neg();
37973 }
37974
37975 return [
37976 { a: a1, b: b1 },
37977 { a: a2, b: b2 }
37978 ];
37979};
37980
37981ShortCurve.prototype._endoSplit = function _endoSplit(k) {
37982 var basis = this.endo.basis;
37983 var v1 = basis[0];
37984 var v2 = basis[1];
37985
37986 var c1 = v2.b.mul(k).divRound(this.n);
37987 var c2 = v1.b.neg().mul(k).divRound(this.n);
37988
37989 var p1 = c1.mul(v1.a);
37990 var p2 = c2.mul(v2.a);
37991 var q1 = c1.mul(v1.b);
37992 var q2 = c2.mul(v2.b);
37993
37994 // Calculate answer
37995 var k1 = k.sub(p1).sub(p2);
37996 var k2 = q1.add(q2).neg();
37997 return { k1: k1, k2: k2 };
37998};
37999
38000ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
38001 x = new bn(x, 16);
38002 if (!x.red)
38003 x = x.toRed(this.red);
38004
38005 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
38006 var y = y2.redSqrt();
38007 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
38008 throw new Error('invalid point');
38009
38010 // XXX Is there any way to tell if the number is odd without converting it
38011 // to non-red form?
38012 var isOdd = y.fromRed().isOdd();
38013 if (odd && !isOdd || !odd && isOdd)
38014 y = y.redNeg();
38015
38016 return this.point(x, y);
38017};
38018
38019ShortCurve.prototype.validate = function validate(point) {
38020 if (point.inf)
38021 return true;
38022
38023 var x = point.x;
38024 var y = point.y;
38025
38026 var ax = this.a.redMul(x);
38027 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
38028 return y.redSqr().redISub(rhs).cmpn(0) === 0;
38029};
38030
38031ShortCurve.prototype._endoWnafMulAdd =
38032 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
38033 var npoints = this._endoWnafT1;
38034 var ncoeffs = this._endoWnafT2;
38035 for (var i = 0; i < points.length; i++) {
38036 var split = this._endoSplit(coeffs[i]);
38037 var p = points[i];
38038 var beta = p._getBeta();
38039
38040 if (split.k1.negative) {
38041 split.k1.ineg();
38042 p = p.neg(true);
38043 }
38044 if (split.k2.negative) {
38045 split.k2.ineg();
38046 beta = beta.neg(true);
38047 }
38048
38049 npoints[i * 2] = p;
38050 npoints[i * 2 + 1] = beta;
38051 ncoeffs[i * 2] = split.k1;
38052 ncoeffs[i * 2 + 1] = split.k2;
38053 }
38054 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
38055
38056 // Clean-up references to points and coefficients
38057 for (var j = 0; j < i * 2; j++) {
38058 npoints[j] = null;
38059 ncoeffs[j] = null;
38060 }
38061 return res;
38062};
38063
38064function Point(curve, x, y, isRed) {
38065 base.BasePoint.call(this, curve, 'affine');
38066 if (x === null && y === null) {
38067 this.x = null;
38068 this.y = null;
38069 this.inf = true;
38070 } else {
38071 this.x = new bn(x, 16);
38072 this.y = new bn(y, 16);
38073 // Force redgomery representation when loading from JSON
38074 if (isRed) {
38075 this.x.forceRed(this.curve.red);
38076 this.y.forceRed(this.curve.red);
38077 }
38078 if (!this.x.red)
38079 this.x = this.x.toRed(this.curve.red);
38080 if (!this.y.red)
38081 this.y = this.y.toRed(this.curve.red);
38082 this.inf = false;
38083 }
38084}
38085inherits(Point, base.BasePoint);
38086
38087ShortCurve.prototype.point = function point(x, y, isRed) {
38088 return new Point(this, x, y, isRed);
38089};
38090
38091ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
38092 return Point.fromJSON(this, obj, red);
38093};
38094
38095Point.prototype._getBeta = function _getBeta() {
38096 if (!this.curve.endo)
38097 return;
38098
38099 var pre = this.precomputed;
38100 if (pre && pre.beta)
38101 return pre.beta;
38102
38103 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
38104 if (pre) {
38105 var curve = this.curve;
38106 var endoMul = function(p) {
38107 return curve.point(p.x.redMul(curve.endo.beta), p.y);
38108 };
38109 pre.beta = beta;
38110 beta.precomputed = {
38111 beta: null,
38112 naf: pre.naf && {
38113 wnd: pre.naf.wnd,
38114 points: pre.naf.points.map(endoMul)
38115 },
38116 doubles: pre.doubles && {
38117 step: pre.doubles.step,
38118 points: pre.doubles.points.map(endoMul)
38119 }
38120 };
38121 }
38122 return beta;
38123};
38124
38125Point.prototype.toJSON = function toJSON() {
38126 if (!this.precomputed)
38127 return [ this.x, this.y ];
38128
38129 return [ this.x, this.y, this.precomputed && {
38130 doubles: this.precomputed.doubles && {
38131 step: this.precomputed.doubles.step,
38132 points: this.precomputed.doubles.points.slice(1)
38133 },
38134 naf: this.precomputed.naf && {
38135 wnd: this.precomputed.naf.wnd,
38136 points: this.precomputed.naf.points.slice(1)
38137 }
38138 } ];
38139};
38140
38141Point.fromJSON = function fromJSON(curve, obj, red) {
38142 if (typeof obj === 'string')
38143 obj = JSON.parse(obj);
38144 var res = curve.point(obj[0], obj[1], red);
38145 if (!obj[2])
38146 return res;
38147
38148 function obj2point(obj) {
38149 return curve.point(obj[0], obj[1], red);
38150 }
38151
38152 var pre = obj[2];
38153 res.precomputed = {
38154 beta: null,
38155 doubles: pre.doubles && {
38156 step: pre.doubles.step,
38157 points: [ res ].concat(pre.doubles.points.map(obj2point))
38158 },
38159 naf: pre.naf && {
38160 wnd: pre.naf.wnd,
38161 points: [ res ].concat(pre.naf.points.map(obj2point))
38162 }
38163 };
38164 return res;
38165};
38166
38167Point.prototype.inspect = function inspect() {
38168 if (this.isInfinity())
38169 return '<EC Point Infinity>';
38170 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
38171 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
38172};
38173
38174Point.prototype.isInfinity = function isInfinity() {
38175 return this.inf;
38176};
38177
38178Point.prototype.add = function add(p) {
38179 // O + P = P
38180 if (this.inf)
38181 return p;
38182
38183 // P + O = P
38184 if (p.inf)
38185 return this;
38186
38187 // P + P = 2P
38188 if (this.eq(p))
38189 return this.dbl();
38190
38191 // P + (-P) = O
38192 if (this.neg().eq(p))
38193 return this.curve.point(null, null);
38194
38195 // P + Q = O
38196 if (this.x.cmp(p.x) === 0)
38197 return this.curve.point(null, null);
38198
38199 var c = this.y.redSub(p.y);
38200 if (c.cmpn(0) !== 0)
38201 c = c.redMul(this.x.redSub(p.x).redInvm());
38202 var nx = c.redSqr().redISub(this.x).redISub(p.x);
38203 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
38204 return this.curve.point(nx, ny);
38205};
38206
38207Point.prototype.dbl = function dbl() {
38208 if (this.inf)
38209 return this;
38210
38211 // 2P = O
38212 var ys1 = this.y.redAdd(this.y);
38213 if (ys1.cmpn(0) === 0)
38214 return this.curve.point(null, null);
38215
38216 var a = this.curve.a;
38217
38218 var x2 = this.x.redSqr();
38219 var dyinv = ys1.redInvm();
38220 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
38221
38222 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
38223 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
38224 return this.curve.point(nx, ny);
38225};
38226
38227Point.prototype.getX = function getX() {
38228 return this.x.fromRed();
38229};
38230
38231Point.prototype.getY = function getY() {
38232 return this.y.fromRed();
38233};
38234
38235Point.prototype.mul = function mul(k) {
38236 k = new bn(k, 16);
38237 if (this.isInfinity())
38238 return this;
38239 else if (this._hasDoubles(k))
38240 return this.curve._fixedNafMul(this, k);
38241 else if (this.curve.endo)
38242 return this.curve._endoWnafMulAdd([ this ], [ k ]);
38243 else
38244 return this.curve._wnafMul(this, k);
38245};
38246
38247Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
38248 var points = [ this, p2 ];
38249 var coeffs = [ k1, k2 ];
38250 if (this.curve.endo)
38251 return this.curve._endoWnafMulAdd(points, coeffs);
38252 else
38253 return this.curve._wnafMulAdd(1, points, coeffs, 2);
38254};
38255
38256Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
38257 var points = [ this, p2 ];
38258 var coeffs = [ k1, k2 ];
38259 if (this.curve.endo)
38260 return this.curve._endoWnafMulAdd(points, coeffs, true);
38261 else
38262 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
38263};
38264
38265Point.prototype.eq = function eq(p) {
38266 return this === p ||
38267 this.inf === p.inf &&
38268 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
38269};
38270
38271Point.prototype.neg = function neg(_precompute) {
38272 if (this.inf)
38273 return this;
38274
38275 var res = this.curve.point(this.x, this.y.redNeg());
38276 if (_precompute && this.precomputed) {
38277 var pre = this.precomputed;
38278 var negate = function(p) {
38279 return p.neg();
38280 };
38281 res.precomputed = {
38282 naf: pre.naf && {
38283 wnd: pre.naf.wnd,
38284 points: pre.naf.points.map(negate)
38285 },
38286 doubles: pre.doubles && {
38287 step: pre.doubles.step,
38288 points: pre.doubles.points.map(negate)
38289 }
38290 };
38291 }
38292 return res;
38293};
38294
38295Point.prototype.toJ = function toJ() {
38296 if (this.inf)
38297 return this.curve.jpoint(null, null, null);
38298
38299 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
38300 return res;
38301};
38302
38303function JPoint(curve, x, y, z) {
38304 base.BasePoint.call(this, curve, 'jacobian');
38305 if (x === null && y === null && z === null) {
38306 this.x = this.curve.one;
38307 this.y = this.curve.one;
38308 this.z = new bn(0);
38309 } else {
38310 this.x = new bn(x, 16);
38311 this.y = new bn(y, 16);
38312 this.z = new bn(z, 16);
38313 }
38314 if (!this.x.red)
38315 this.x = this.x.toRed(this.curve.red);
38316 if (!this.y.red)
38317 this.y = this.y.toRed(this.curve.red);
38318 if (!this.z.red)
38319 this.z = this.z.toRed(this.curve.red);
38320
38321 this.zOne = this.z === this.curve.one;
38322}
38323inherits(JPoint, base.BasePoint);
38324
38325ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
38326 return new JPoint(this, x, y, z);
38327};
38328
38329JPoint.prototype.toP = function toP() {
38330 if (this.isInfinity())
38331 return this.curve.point(null, null);
38332
38333 var zinv = this.z.redInvm();
38334 var zinv2 = zinv.redSqr();
38335 var ax = this.x.redMul(zinv2);
38336 var ay = this.y.redMul(zinv2).redMul(zinv);
38337
38338 return this.curve.point(ax, ay);
38339};
38340
38341JPoint.prototype.neg = function neg() {
38342 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
38343};
38344
38345JPoint.prototype.add = function add(p) {
38346 // O + P = P
38347 if (this.isInfinity())
38348 return p;
38349
38350 // P + O = P
38351 if (p.isInfinity())
38352 return this;
38353
38354 // 12M + 4S + 7A
38355 var pz2 = p.z.redSqr();
38356 var z2 = this.z.redSqr();
38357 var u1 = this.x.redMul(pz2);
38358 var u2 = p.x.redMul(z2);
38359 var s1 = this.y.redMul(pz2.redMul(p.z));
38360 var s2 = p.y.redMul(z2.redMul(this.z));
38361
38362 var h = u1.redSub(u2);
38363 var r = s1.redSub(s2);
38364 if (h.cmpn(0) === 0) {
38365 if (r.cmpn(0) !== 0)
38366 return this.curve.jpoint(null, null, null);
38367 else
38368 return this.dbl();
38369 }
38370
38371 var h2 = h.redSqr();
38372 var h3 = h2.redMul(h);
38373 var v = u1.redMul(h2);
38374
38375 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
38376 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
38377 var nz = this.z.redMul(p.z).redMul(h);
38378
38379 return this.curve.jpoint(nx, ny, nz);
38380};
38381
38382JPoint.prototype.mixedAdd = function mixedAdd(p) {
38383 // O + P = P
38384 if (this.isInfinity())
38385 return p.toJ();
38386
38387 // P + O = P
38388 if (p.isInfinity())
38389 return this;
38390
38391 // 8M + 3S + 7A
38392 var z2 = this.z.redSqr();
38393 var u1 = this.x;
38394 var u2 = p.x.redMul(z2);
38395 var s1 = this.y;
38396 var s2 = p.y.redMul(z2).redMul(this.z);
38397
38398 var h = u1.redSub(u2);
38399 var r = s1.redSub(s2);
38400 if (h.cmpn(0) === 0) {
38401 if (r.cmpn(0) !== 0)
38402 return this.curve.jpoint(null, null, null);
38403 else
38404 return this.dbl();
38405 }
38406
38407 var h2 = h.redSqr();
38408 var h3 = h2.redMul(h);
38409 var v = u1.redMul(h2);
38410
38411 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
38412 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
38413 var nz = this.z.redMul(h);
38414
38415 return this.curve.jpoint(nx, ny, nz);
38416};
38417
38418JPoint.prototype.dblp = function dblp(pow) {
38419 if (pow === 0)
38420 return this;
38421 if (this.isInfinity())
38422 return this;
38423 if (!pow)
38424 return this.dbl();
38425
38426 if (this.curve.zeroA || this.curve.threeA) {
38427 var r = this;
38428 for (var i = 0; i < pow; i++)
38429 r = r.dbl();
38430 return r;
38431 }
38432
38433 // 1M + 2S + 1A + N * (4S + 5M + 8A)
38434 // N = 1 => 6M + 6S + 9A
38435 var a = this.curve.a;
38436 var tinv = this.curve.tinv;
38437
38438 var jx = this.x;
38439 var jy = this.y;
38440 var jz = this.z;
38441 var jz4 = jz.redSqr().redSqr();
38442
38443 // Reuse results
38444 var jyd = jy.redAdd(jy);
38445 for (var i = 0; i < pow; i++) {
38446 var jx2 = jx.redSqr();
38447 var jyd2 = jyd.redSqr();
38448 var jyd4 = jyd2.redSqr();
38449 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
38450
38451 var t1 = jx.redMul(jyd2);
38452 var nx = c.redSqr().redISub(t1.redAdd(t1));
38453 var t2 = t1.redISub(nx);
38454 var dny = c.redMul(t2);
38455 dny = dny.redIAdd(dny).redISub(jyd4);
38456 var nz = jyd.redMul(jz);
38457 if (i + 1 < pow)
38458 jz4 = jz4.redMul(jyd4);
38459
38460 jx = nx;
38461 jz = nz;
38462 jyd = dny;
38463 }
38464
38465 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
38466};
38467
38468JPoint.prototype.dbl = function dbl() {
38469 if (this.isInfinity())
38470 return this;
38471
38472 if (this.curve.zeroA)
38473 return this._zeroDbl();
38474 else if (this.curve.threeA)
38475 return this._threeDbl();
38476 else
38477 return this._dbl();
38478};
38479
38480JPoint.prototype._zeroDbl = function _zeroDbl() {
38481 var nx;
38482 var ny;
38483 var nz;
38484 // Z = 1
38485 if (this.zOne) {
38486 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
38487 // #doubling-mdbl-2007-bl
38488 // 1M + 5S + 14A
38489
38490 // XX = X1^2
38491 var xx = this.x.redSqr();
38492 // YY = Y1^2
38493 var yy = this.y.redSqr();
38494 // YYYY = YY^2
38495 var yyyy = yy.redSqr();
38496 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
38497 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
38498 s = s.redIAdd(s);
38499 // M = 3 * XX + a; a = 0
38500 var m = xx.redAdd(xx).redIAdd(xx);
38501 // T = M ^ 2 - 2*S
38502 var t = m.redSqr().redISub(s).redISub(s);
38503
38504 // 8 * YYYY
38505 var yyyy8 = yyyy.redIAdd(yyyy);
38506 yyyy8 = yyyy8.redIAdd(yyyy8);
38507 yyyy8 = yyyy8.redIAdd(yyyy8);
38508
38509 // X3 = T
38510 nx = t;
38511 // Y3 = M * (S - T) - 8 * YYYY
38512 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
38513 // Z3 = 2*Y1
38514 nz = this.y.redAdd(this.y);
38515 } else {
38516 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
38517 // #doubling-dbl-2009-l
38518 // 2M + 5S + 13A
38519
38520 // A = X1^2
38521 var a = this.x.redSqr();
38522 // B = Y1^2
38523 var b = this.y.redSqr();
38524 // C = B^2
38525 var c = b.redSqr();
38526 // D = 2 * ((X1 + B)^2 - A - C)
38527 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
38528 d = d.redIAdd(d);
38529 // E = 3 * A
38530 var e = a.redAdd(a).redIAdd(a);
38531 // F = E^2
38532 var f = e.redSqr();
38533
38534 // 8 * C
38535 var c8 = c.redIAdd(c);
38536 c8 = c8.redIAdd(c8);
38537 c8 = c8.redIAdd(c8);
38538
38539 // X3 = F - 2 * D
38540 nx = f.redISub(d).redISub(d);
38541 // Y3 = E * (D - X3) - 8 * C
38542 ny = e.redMul(d.redISub(nx)).redISub(c8);
38543 // Z3 = 2 * Y1 * Z1
38544 nz = this.y.redMul(this.z);
38545 nz = nz.redIAdd(nz);
38546 }
38547
38548 return this.curve.jpoint(nx, ny, nz);
38549};
38550
38551JPoint.prototype._threeDbl = function _threeDbl() {
38552 var nx;
38553 var ny;
38554 var nz;
38555 // Z = 1
38556 if (this.zOne) {
38557 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
38558 // #doubling-mdbl-2007-bl
38559 // 1M + 5S + 15A
38560
38561 // XX = X1^2
38562 var xx = this.x.redSqr();
38563 // YY = Y1^2
38564 var yy = this.y.redSqr();
38565 // YYYY = YY^2
38566 var yyyy = yy.redSqr();
38567 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
38568 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
38569 s = s.redIAdd(s);
38570 // M = 3 * XX + a
38571 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
38572 // T = M^2 - 2 * S
38573 var t = m.redSqr().redISub(s).redISub(s);
38574 // X3 = T
38575 nx = t;
38576 // Y3 = M * (S - T) - 8 * YYYY
38577 var yyyy8 = yyyy.redIAdd(yyyy);
38578 yyyy8 = yyyy8.redIAdd(yyyy8);
38579 yyyy8 = yyyy8.redIAdd(yyyy8);
38580 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
38581 // Z3 = 2 * Y1
38582 nz = this.y.redAdd(this.y);
38583 } else {
38584 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
38585 // 3M + 5S
38586
38587 // delta = Z1^2
38588 var delta = this.z.redSqr();
38589 // gamma = Y1^2
38590 var gamma = this.y.redSqr();
38591 // beta = X1 * gamma
38592 var beta = this.x.redMul(gamma);
38593 // alpha = 3 * (X1 - delta) * (X1 + delta)
38594 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
38595 alpha = alpha.redAdd(alpha).redIAdd(alpha);
38596 // X3 = alpha^2 - 8 * beta
38597 var beta4 = beta.redIAdd(beta);
38598 beta4 = beta4.redIAdd(beta4);
38599 var beta8 = beta4.redAdd(beta4);
38600 nx = alpha.redSqr().redISub(beta8);
38601 // Z3 = (Y1 + Z1)^2 - gamma - delta
38602 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
38603 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
38604 var ggamma8 = gamma.redSqr();
38605 ggamma8 = ggamma8.redIAdd(ggamma8);
38606 ggamma8 = ggamma8.redIAdd(ggamma8);
38607 ggamma8 = ggamma8.redIAdd(ggamma8);
38608 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
38609 }
38610
38611 return this.curve.jpoint(nx, ny, nz);
38612};
38613
38614JPoint.prototype._dbl = function _dbl() {
38615 var a = this.curve.a;
38616
38617 // 4M + 6S + 10A
38618 var jx = this.x;
38619 var jy = this.y;
38620 var jz = this.z;
38621 var jz4 = jz.redSqr().redSqr();
38622
38623 var jx2 = jx.redSqr();
38624 var jy2 = jy.redSqr();
38625
38626 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
38627
38628 var jxd4 = jx.redAdd(jx);
38629 jxd4 = jxd4.redIAdd(jxd4);
38630 var t1 = jxd4.redMul(jy2);
38631 var nx = c.redSqr().redISub(t1.redAdd(t1));
38632 var t2 = t1.redISub(nx);
38633
38634 var jyd8 = jy2.redSqr();
38635 jyd8 = jyd8.redIAdd(jyd8);
38636 jyd8 = jyd8.redIAdd(jyd8);
38637 jyd8 = jyd8.redIAdd(jyd8);
38638 var ny = c.redMul(t2).redISub(jyd8);
38639 var nz = jy.redAdd(jy).redMul(jz);
38640
38641 return this.curve.jpoint(nx, ny, nz);
38642};
38643
38644JPoint.prototype.trpl = function trpl() {
38645 if (!this.curve.zeroA)
38646 return this.dbl().add(this);
38647
38648 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
38649 // 5M + 10S + ...
38650
38651 // XX = X1^2
38652 var xx = this.x.redSqr();
38653 // YY = Y1^2
38654 var yy = this.y.redSqr();
38655 // ZZ = Z1^2
38656 var zz = this.z.redSqr();
38657 // YYYY = YY^2
38658 var yyyy = yy.redSqr();
38659 // M = 3 * XX + a * ZZ2; a = 0
38660 var m = xx.redAdd(xx).redIAdd(xx);
38661 // MM = M^2
38662 var mm = m.redSqr();
38663 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
38664 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
38665 e = e.redIAdd(e);
38666 e = e.redAdd(e).redIAdd(e);
38667 e = e.redISub(mm);
38668 // EE = E^2
38669 var ee = e.redSqr();
38670 // T = 16*YYYY
38671 var t = yyyy.redIAdd(yyyy);
38672 t = t.redIAdd(t);
38673 t = t.redIAdd(t);
38674 t = t.redIAdd(t);
38675 // U = (M + E)^2 - MM - EE - T
38676 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
38677 // X3 = 4 * (X1 * EE - 4 * YY * U)
38678 var yyu4 = yy.redMul(u);
38679 yyu4 = yyu4.redIAdd(yyu4);
38680 yyu4 = yyu4.redIAdd(yyu4);
38681 var nx = this.x.redMul(ee).redISub(yyu4);
38682 nx = nx.redIAdd(nx);
38683 nx = nx.redIAdd(nx);
38684 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
38685 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
38686 ny = ny.redIAdd(ny);
38687 ny = ny.redIAdd(ny);
38688 ny = ny.redIAdd(ny);
38689 // Z3 = (Z1 + E)^2 - ZZ - EE
38690 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
38691
38692 return this.curve.jpoint(nx, ny, nz);
38693};
38694
38695JPoint.prototype.mul = function mul(k, kbase) {
38696 k = new bn(k, kbase);
38697
38698 return this.curve._wnafMul(this, k);
38699};
38700
38701JPoint.prototype.eq = function eq(p) {
38702 if (p.type === 'affine')
38703 return this.eq(p.toJ());
38704
38705 if (this === p)
38706 return true;
38707
38708 // x1 * z2^2 == x2 * z1^2
38709 var z2 = this.z.redSqr();
38710 var pz2 = p.z.redSqr();
38711 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
38712 return false;
38713
38714 // y1 * z2^3 == y2 * z1^3
38715 var z3 = z2.redMul(this.z);
38716 var pz3 = pz2.redMul(p.z);
38717 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
38718};
38719
38720JPoint.prototype.eqXToP = function eqXToP(x) {
38721 var zs = this.z.redSqr();
38722 var rx = x.toRed(this.curve.red).redMul(zs);
38723 if (this.x.cmp(rx) === 0)
38724 return true;
38725
38726 var xc = x.clone();
38727 var t = this.curve.redN.redMul(zs);
38728 for (;;) {
38729 xc.iadd(this.curve.n);
38730 if (xc.cmp(this.curve.p) >= 0)
38731 return false;
38732
38733 rx.redIAdd(t);
38734 if (this.x.cmp(rx) === 0)
38735 return true;
38736 }
38737};
38738
38739JPoint.prototype.inspect = function inspect() {
38740 if (this.isInfinity())
38741 return '<EC JPoint Infinity>';
38742 return '<EC JPoint x: ' + this.x.toString(16, 2) +
38743 ' y: ' + this.y.toString(16, 2) +
38744 ' z: ' + this.z.toString(16, 2) + '>';
38745};
38746
38747JPoint.prototype.isInfinity = function isInfinity() {
38748 // XXX This code assumes that zero is always zero in red
38749 return this.z.cmpn(0) === 0;
38750};
38751
38752function MontCurve(conf) {
38753 base.call(this, 'mont', conf);
38754
38755 this.a = new bn(conf.a, 16).toRed(this.red);
38756 this.b = new bn(conf.b, 16).toRed(this.red);
38757 this.i4 = new bn(4).toRed(this.red).redInvm();
38758 this.two = new bn(2).toRed(this.red);
38759 // Note: this implementation is according to the original paper
38760 // by P. Montgomery, NOT the one by D. J. Bernstein.
38761 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
38762}
38763inherits(MontCurve, base);
38764var mont = MontCurve;
38765
38766MontCurve.prototype.validate = function validate(point) {
38767 var x = point.normalize().x;
38768 var x2 = x.redSqr();
38769 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
38770 var y = rhs.redSqrt();
38771
38772 return y.redSqr().cmp(rhs) === 0;
38773};
38774
38775function Point$1(curve, x, z) {
38776 base.BasePoint.call(this, curve, 'projective');
38777 if (x === null && z === null) {
38778 this.x = this.curve.one;
38779 this.z = this.curve.zero;
38780 } else {
38781 this.x = new bn(x, 16);
38782 this.z = new bn(z, 16);
38783 if (!this.x.red)
38784 this.x = this.x.toRed(this.curve.red);
38785 if (!this.z.red)
38786 this.z = this.z.toRed(this.curve.red);
38787 }
38788}
38789inherits(Point$1, base.BasePoint);
38790
38791MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
38792 var bytes = utils_1$1.toArray(bytes, enc);
38793
38794 // TODO Curve448
38795 // Montgomery curve points must be represented in the compressed format
38796 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
38797 if (bytes.length === 33 && bytes[0] === 0x40)
38798 bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
38799 if (bytes.length !== 32)
38800 throw new Error('Unknown point compression format');
38801 return this.point(bytes, 1);
38802};
38803
38804MontCurve.prototype.point = function point(x, z) {
38805 return new Point$1(this, x, z);
38806};
38807
38808MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
38809 return Point$1.fromJSON(this, obj);
38810};
38811
38812Point$1.prototype.precompute = function precompute() {
38813 // No-op
38814};
38815
38816Point$1.prototype._encode = function _encode(compact) {
38817 var len = this.curve.p.byteLength();
38818
38819 // Note: the output should always be little-endian
38820 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
38821 if (compact) {
38822 return [ 0x40 ].concat(this.getX().toArray('le', len));
38823 } else {
38824 return this.getX().toArray('be', len);
38825 }
38826};
38827
38828Point$1.fromJSON = function fromJSON(curve, obj) {
38829 return new Point$1(curve, obj[0], obj[1] || curve.one);
38830};
38831
38832Point$1.prototype.inspect = function inspect() {
38833 if (this.isInfinity())
38834 return '<EC Point Infinity>';
38835 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
38836 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
38837};
38838
38839Point$1.prototype.isInfinity = function isInfinity() {
38840 // XXX This code assumes that zero is always zero in red
38841 return this.z.cmpn(0) === 0;
38842};
38843
38844Point$1.prototype.dbl = function dbl() {
38845 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
38846 // 2M + 2S + 4A
38847
38848 // A = X1 + Z1
38849 var a = this.x.redAdd(this.z);
38850 // AA = A^2
38851 var aa = a.redSqr();
38852 // B = X1 - Z1
38853 var b = this.x.redSub(this.z);
38854 // BB = B^2
38855 var bb = b.redSqr();
38856 // C = AA - BB
38857 var c = aa.redSub(bb);
38858 // X3 = AA * BB
38859 var nx = aa.redMul(bb);
38860 // Z3 = C * (BB + A24 * C)
38861 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
38862 return this.curve.point(nx, nz);
38863};
38864
38865Point$1.prototype.add = function add() {
38866 throw new Error('Not supported on Montgomery curve');
38867};
38868
38869Point$1.prototype.diffAdd = function diffAdd(p, diff) {
38870 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
38871 // 4M + 2S + 6A
38872
38873 // A = X2 + Z2
38874 var a = this.x.redAdd(this.z);
38875 // B = X2 - Z2
38876 var b = this.x.redSub(this.z);
38877 // C = X3 + Z3
38878 var c = p.x.redAdd(p.z);
38879 // D = X3 - Z3
38880 var d = p.x.redSub(p.z);
38881 // DA = D * A
38882 var da = d.redMul(a);
38883 // CB = C * B
38884 var cb = c.redMul(b);
38885 // X5 = Z1 * (DA + CB)^2
38886 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
38887 // Z5 = X1 * (DA - CB)^2
38888 var nz = diff.x.redMul(da.redISub(cb).redSqr());
38889 return this.curve.point(nx, nz);
38890};
38891
38892Point$1.prototype.mul = function mul(k) {
38893 k = new bn(k, 16);
38894
38895 var t = k.clone();
38896 var a = this; // (N / 2) * Q + Q
38897 var b = this.curve.point(null, null); // (N / 2) * Q
38898 var c = this; // Q
38899
38900 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
38901 bits.push(t.andln(1));
38902
38903 for (var i = bits.length - 1; i >= 0; i--) {
38904 if (bits[i] === 0) {
38905 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
38906 a = a.diffAdd(b, c);
38907 // N * Q = 2 * ((N / 2) * Q + Q))
38908 b = b.dbl();
38909 } else {
38910 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
38911 b = a.diffAdd(b, c);
38912 // N * Q + Q = 2 * ((N / 2) * Q + Q)
38913 a = a.dbl();
38914 }
38915 }
38916 return b;
38917};
38918
38919Point$1.prototype.mulAdd = function mulAdd() {
38920 throw new Error('Not supported on Montgomery curve');
38921};
38922
38923Point$1.prototype.jumlAdd = function jumlAdd() {
38924 throw new Error('Not supported on Montgomery curve');
38925};
38926
38927Point$1.prototype.eq = function eq(other) {
38928 return this.getX().cmp(other.getX()) === 0;
38929};
38930
38931Point$1.prototype.normalize = function normalize() {
38932 this.x = this.x.redMul(this.z.redInvm());
38933 this.z = this.curve.one;
38934 return this;
38935};
38936
38937Point$1.prototype.getX = function getX() {
38938 // Normalize coordinates
38939 this.normalize();
38940
38941 return this.x.fromRed();
38942};
38943
38944var assert$4 = utils_1$1.assert;
38945
38946function EdwardsCurve(conf) {
38947 // NOTE: Important as we are creating point in Base.call()
38948 this.twisted = (conf.a | 0) !== 1;
38949 this.mOneA = this.twisted && (conf.a | 0) === -1;
38950 this.extended = this.mOneA;
38951
38952 base.call(this, 'edwards', conf);
38953
38954 this.a = new bn(conf.a, 16).umod(this.red.m);
38955 this.a = this.a.toRed(this.red);
38956 this.c = new bn(conf.c, 16).toRed(this.red);
38957 this.c2 = this.c.redSqr();
38958 this.d = new bn(conf.d, 16).toRed(this.red);
38959 this.dd = this.d.redAdd(this.d);
38960
38961 assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0);
38962 this.oneC = (conf.c | 0) === 1;
38963}
38964inherits(EdwardsCurve, base);
38965var edwards = EdwardsCurve;
38966
38967EdwardsCurve.prototype._mulA = function _mulA(num) {
38968 if (this.mOneA)
38969 return num.redNeg();
38970 else
38971 return this.a.redMul(num);
38972};
38973
38974EdwardsCurve.prototype._mulC = function _mulC(num) {
38975 if (this.oneC)
38976 return num;
38977 else
38978 return this.c.redMul(num);
38979};
38980
38981// Just for compatibility with Short curve
38982EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
38983 return this.point(x, y, z, t);
38984};
38985
38986EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
38987 x = new bn(x, 16);
38988 if (!x.red)
38989 x = x.toRed(this.red);
38990
38991 var x2 = x.redSqr();
38992 var rhs = this.c2.redSub(this.a.redMul(x2));
38993 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
38994
38995 var y2 = rhs.redMul(lhs.redInvm());
38996 var y = y2.redSqrt();
38997 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
38998 throw new Error('invalid point');
38999
39000 var isOdd = y.fromRed().isOdd();
39001 if (odd && !isOdd || !odd && isOdd)
39002 y = y.redNeg();
39003
39004 return this.point(x, y);
39005};
39006
39007EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
39008 y = new bn(y, 16);
39009 if (!y.red)
39010 y = y.toRed(this.red);
39011
39012 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
39013 var y2 = y.redSqr();
39014 var lhs = y2.redSub(this.c2);
39015 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
39016 var x2 = lhs.redMul(rhs.redInvm());
39017
39018 if (x2.cmp(this.zero) === 0) {
39019 if (odd)
39020 throw new Error('invalid point');
39021 else
39022 return this.point(this.zero, y);
39023 }
39024
39025 var x = x2.redSqrt();
39026 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
39027 throw new Error('invalid point');
39028
39029 if (x.fromRed().isOdd() !== odd)
39030 x = x.redNeg();
39031
39032 return this.point(x, y);
39033};
39034
39035EdwardsCurve.prototype.validate = function validate(point) {
39036 if (point.isInfinity())
39037 return true;
39038
39039 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
39040 point.normalize();
39041
39042 var x2 = point.x.redSqr();
39043 var y2 = point.y.redSqr();
39044 var lhs = x2.redMul(this.a).redAdd(y2);
39045 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
39046
39047 return lhs.cmp(rhs) === 0;
39048};
39049
39050function Point$2(curve, x, y, z, t) {
39051 base.BasePoint.call(this, curve, 'projective');
39052 if (x === null && y === null && z === null) {
39053 this.x = this.curve.zero;
39054 this.y = this.curve.one;
39055 this.z = this.curve.one;
39056 this.t = this.curve.zero;
39057 this.zOne = true;
39058 } else {
39059 this.x = new bn(x, 16);
39060 this.y = new bn(y, 16);
39061 this.z = z ? new bn(z, 16) : this.curve.one;
39062 this.t = t && new bn(t, 16);
39063 if (!this.x.red)
39064 this.x = this.x.toRed(this.curve.red);
39065 if (!this.y.red)
39066 this.y = this.y.toRed(this.curve.red);
39067 if (!this.z.red)
39068 this.z = this.z.toRed(this.curve.red);
39069 if (this.t && !this.t.red)
39070 this.t = this.t.toRed(this.curve.red);
39071 this.zOne = this.z === this.curve.one;
39072
39073 // Use extended coordinates
39074 if (this.curve.extended && !this.t) {
39075 this.t = this.x.redMul(this.y);
39076 if (!this.zOne)
39077 this.t = this.t.redMul(this.z.redInvm());
39078 }
39079 }
39080}
39081inherits(Point$2, base.BasePoint);
39082
39083EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
39084 return Point$2.fromJSON(this, obj);
39085};
39086
39087EdwardsCurve.prototype.point = function point(x, y, z, t) {
39088 return new Point$2(this, x, y, z, t);
39089};
39090
39091Point$2.fromJSON = function fromJSON(curve, obj) {
39092 return new Point$2(curve, obj[0], obj[1], obj[2]);
39093};
39094
39095Point$2.prototype.inspect = function inspect() {
39096 if (this.isInfinity())
39097 return '<EC Point Infinity>';
39098 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
39099 ' y: ' + this.y.fromRed().toString(16, 2) +
39100 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
39101};
39102
39103Point$2.prototype.isInfinity = function isInfinity() {
39104 // XXX This code assumes that zero is always zero in red
39105 return this.x.cmpn(0) === 0 &&
39106 (this.y.cmp(this.z) === 0 ||
39107 (this.zOne && this.y.cmp(this.curve.c) === 0));
39108};
39109
39110Point$2.prototype._extDbl = function _extDbl() {
39111 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
39112 // #doubling-dbl-2008-hwcd
39113 // 4M + 4S
39114
39115 // A = X1^2
39116 var a = this.x.redSqr();
39117 // B = Y1^2
39118 var b = this.y.redSqr();
39119 // C = 2 * Z1^2
39120 var c = this.z.redSqr();
39121 c = c.redIAdd(c);
39122 // D = a * A
39123 var d = this.curve._mulA(a);
39124 // E = (X1 + Y1)^2 - A - B
39125 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
39126 // G = D + B
39127 var g = d.redAdd(b);
39128 // F = G - C
39129 var f = g.redSub(c);
39130 // H = D - B
39131 var h = d.redSub(b);
39132 // X3 = E * F
39133 var nx = e.redMul(f);
39134 // Y3 = G * H
39135 var ny = g.redMul(h);
39136 // T3 = E * H
39137 var nt = e.redMul(h);
39138 // Z3 = F * G
39139 var nz = f.redMul(g);
39140 return this.curve.point(nx, ny, nz, nt);
39141};
39142
39143Point$2.prototype._projDbl = function _projDbl() {
39144 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
39145 // #doubling-dbl-2008-bbjlp
39146 // #doubling-dbl-2007-bl
39147 // and others
39148 // Generally 3M + 4S or 2M + 4S
39149
39150 // B = (X1 + Y1)^2
39151 var b = this.x.redAdd(this.y).redSqr();
39152 // C = X1^2
39153 var c = this.x.redSqr();
39154 // D = Y1^2
39155 var d = this.y.redSqr();
39156
39157 var nx;
39158 var ny;
39159 var nz;
39160 if (this.curve.twisted) {
39161 // E = a * C
39162 var e = this.curve._mulA(c);
39163 // F = E + D
39164 var f = e.redAdd(d);
39165 if (this.zOne) {
39166 // X3 = (B - C - D) * (F - 2)
39167 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
39168 // Y3 = F * (E - D)
39169 ny = f.redMul(e.redSub(d));
39170 // Z3 = F^2 - 2 * F
39171 nz = f.redSqr().redSub(f).redSub(f);
39172 } else {
39173 // H = Z1^2
39174 var h = this.z.redSqr();
39175 // J = F - 2 * H
39176 var j = f.redSub(h).redISub(h);
39177 // X3 = (B-C-D)*J
39178 nx = b.redSub(c).redISub(d).redMul(j);
39179 // Y3 = F * (E - D)
39180 ny = f.redMul(e.redSub(d));
39181 // Z3 = F * J
39182 nz = f.redMul(j);
39183 }
39184 } else {
39185 // E = C + D
39186 var e = c.redAdd(d);
39187 // H = (c * Z1)^2
39188 var h = this.curve._mulC(this.z).redSqr();
39189 // J = E - 2 * H
39190 var j = e.redSub(h).redSub(h);
39191 // X3 = c * (B - E) * J
39192 nx = this.curve._mulC(b.redISub(e)).redMul(j);
39193 // Y3 = c * E * (C - D)
39194 ny = this.curve._mulC(e).redMul(c.redISub(d));
39195 // Z3 = E * J
39196 nz = e.redMul(j);
39197 }
39198 return this.curve.point(nx, ny, nz);
39199};
39200
39201Point$2.prototype.dbl = function dbl() {
39202 if (this.isInfinity())
39203 return this;
39204
39205 // Double in extended coordinates
39206 if (this.curve.extended)
39207 return this._extDbl();
39208 else
39209 return this._projDbl();
39210};
39211
39212Point$2.prototype._extAdd = function _extAdd(p) {
39213 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
39214 // #addition-add-2008-hwcd-3
39215 // 8M
39216
39217 // A = (Y1 - X1) * (Y2 - X2)
39218 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
39219 // B = (Y1 + X1) * (Y2 + X2)
39220 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
39221 // C = T1 * k * T2
39222 var c = this.t.redMul(this.curve.dd).redMul(p.t);
39223 // D = Z1 * 2 * Z2
39224 var d = this.z.redMul(p.z.redAdd(p.z));
39225 // E = B - A
39226 var e = b.redSub(a);
39227 // F = D - C
39228 var f = d.redSub(c);
39229 // G = D + C
39230 var g = d.redAdd(c);
39231 // H = B + A
39232 var h = b.redAdd(a);
39233 // X3 = E * F
39234 var nx = e.redMul(f);
39235 // Y3 = G * H
39236 var ny = g.redMul(h);
39237 // T3 = E * H
39238 var nt = e.redMul(h);
39239 // Z3 = F * G
39240 var nz = f.redMul(g);
39241 return this.curve.point(nx, ny, nz, nt);
39242};
39243
39244Point$2.prototype._projAdd = function _projAdd(p) {
39245 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
39246 // #addition-add-2008-bbjlp
39247 // #addition-add-2007-bl
39248 // 10M + 1S
39249
39250 // A = Z1 * Z2
39251 var a = this.z.redMul(p.z);
39252 // B = A^2
39253 var b = a.redSqr();
39254 // C = X1 * X2
39255 var c = this.x.redMul(p.x);
39256 // D = Y1 * Y2
39257 var d = this.y.redMul(p.y);
39258 // E = d * C * D
39259 var e = this.curve.d.redMul(c).redMul(d);
39260 // F = B - E
39261 var f = b.redSub(e);
39262 // G = B + E
39263 var g = b.redAdd(e);
39264 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
39265 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
39266 var nx = a.redMul(f).redMul(tmp);
39267 var ny;
39268 var nz;
39269 if (this.curve.twisted) {
39270 // Y3 = A * G * (D - a * C)
39271 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
39272 // Z3 = F * G
39273 nz = f.redMul(g);
39274 } else {
39275 // Y3 = A * G * (D - C)
39276 ny = a.redMul(g).redMul(d.redSub(c));
39277 // Z3 = c * F * G
39278 nz = this.curve._mulC(f).redMul(g);
39279 }
39280 return this.curve.point(nx, ny, nz);
39281};
39282
39283Point$2.prototype.add = function add(p) {
39284 if (this.isInfinity())
39285 return p;
39286 if (p.isInfinity())
39287 return this;
39288
39289 if (this.curve.extended)
39290 return this._extAdd(p);
39291 else
39292 return this._projAdd(p);
39293};
39294
39295Point$2.prototype.mul = function mul(k) {
39296 if (this._hasDoubles(k))
39297 return this.curve._fixedNafMul(this, k);
39298 else
39299 return this.curve._wnafMul(this, k);
39300};
39301
39302Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) {
39303 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
39304};
39305
39306Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
39307 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
39308};
39309
39310Point$2.prototype.normalize = function normalize() {
39311 if (this.zOne)
39312 return this;
39313
39314 // Normalize coordinates
39315 var zi = this.z.redInvm();
39316 this.x = this.x.redMul(zi);
39317 this.y = this.y.redMul(zi);
39318 if (this.t)
39319 this.t = this.t.redMul(zi);
39320 this.z = this.curve.one;
39321 this.zOne = true;
39322 return this;
39323};
39324
39325Point$2.prototype.neg = function neg() {
39326 return this.curve.point(this.x.redNeg(),
39327 this.y,
39328 this.z,
39329 this.t && this.t.redNeg());
39330};
39331
39332Point$2.prototype.getX = function getX() {
39333 this.normalize();
39334 return this.x.fromRed();
39335};
39336
39337Point$2.prototype.getY = function getY() {
39338 this.normalize();
39339 return this.y.fromRed();
39340};
39341
39342Point$2.prototype.eq = function eq(other) {
39343 return this === other ||
39344 this.getX().cmp(other.getX()) === 0 &&
39345 this.getY().cmp(other.getY()) === 0;
39346};
39347
39348Point$2.prototype.eqXToP = function eqXToP(x) {
39349 var rx = x.toRed(this.curve.red).redMul(this.z);
39350 if (this.x.cmp(rx) === 0)
39351 return true;
39352
39353 var xc = x.clone();
39354 var t = this.curve.redN.redMul(this.z);
39355 for (;;) {
39356 xc.iadd(this.curve.n);
39357 if (xc.cmp(this.curve.p) >= 0)
39358 return false;
39359
39360 rx.redIAdd(t);
39361 if (this.x.cmp(rx) === 0)
39362 return true;
39363 }
39364};
39365
39366// Compatibility with BaseCurve
39367Point$2.prototype.toP = Point$2.prototype.normalize;
39368Point$2.prototype.mixedAdd = Point$2.prototype.add;
39369
39370var curve_1 = createCommonjsModule(function (module, exports) {
39371
39372var curve = exports;
39373
39374curve.base = base;
39375curve.short = short_1;
39376curve.mont = mont;
39377curve.edwards = edwards;
39378});
39379
39380var rotl32$2 = utils.rotl32;
39381var sum32$3 = utils.sum32;
39382var sum32_5$2 = utils.sum32_5;
39383var ft_1$1 = common$1.ft_1;
39384var BlockHash$4 = common.BlockHash;
39385
39386var sha1_K = [
39387 0x5A827999, 0x6ED9EBA1,
39388 0x8F1BBCDC, 0xCA62C1D6
39389];
39390
39391function SHA1() {
39392 if (!(this instanceof SHA1))
39393 return new SHA1();
39394
39395 BlockHash$4.call(this);
39396 this.h = [
39397 0x67452301, 0xefcdab89, 0x98badcfe,
39398 0x10325476, 0xc3d2e1f0 ];
39399 this.W = new Array(80);
39400}
39401
39402utils.inherits(SHA1, BlockHash$4);
39403var _1 = SHA1;
39404
39405SHA1.blockSize = 512;
39406SHA1.outSize = 160;
39407SHA1.hmacStrength = 80;
39408SHA1.padLength = 64;
39409
39410SHA1.prototype._update = function _update(msg, start) {
39411 var W = this.W;
39412
39413 for (var i = 0; i < 16; i++)
39414 W[i] = msg[start + i];
39415
39416 for(; i < W.length; i++)
39417 W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
39418
39419 var a = this.h[0];
39420 var b = this.h[1];
39421 var c = this.h[2];
39422 var d = this.h[3];
39423 var e = this.h[4];
39424
39425 for (i = 0; i < W.length; i++) {
39426 var s = ~~(i / 20);
39427 var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
39428 e = d;
39429 d = c;
39430 c = rotl32$2(b, 30);
39431 b = a;
39432 a = t;
39433 }
39434
39435 this.h[0] = sum32$3(this.h[0], a);
39436 this.h[1] = sum32$3(this.h[1], b);
39437 this.h[2] = sum32$3(this.h[2], c);
39438 this.h[3] = sum32$3(this.h[3], d);
39439 this.h[4] = sum32$3(this.h[4], e);
39440};
39441
39442SHA1.prototype._digest = function digest(enc) {
39443 if (enc === 'hex')
39444 return utils.toHex32(this.h, 'big');
39445 else
39446 return utils.split32(this.h, 'big');
39447};
39448
39449var sha1 = _1;
39450var sha224 = _224;
39451var sha256 = _256;
39452var sha384 = _384;
39453var sha512 = _512;
39454
39455var sha = {
39456 sha1: sha1,
39457 sha224: sha224,
39458 sha256: sha256,
39459 sha384: sha384,
39460 sha512: sha512
39461};
39462
39463function Hmac(hash, key, enc) {
39464 if (!(this instanceof Hmac))
39465 return new Hmac(hash, key, enc);
39466 this.Hash = hash;
39467 this.blockSize = hash.blockSize / 8;
39468 this.outSize = hash.outSize / 8;
39469 this.inner = null;
39470 this.outer = null;
39471
39472 this._init(utils.toArray(key, enc));
39473}
39474var hmac = Hmac;
39475
39476Hmac.prototype._init = function init(key) {
39477 // Shorten key, if needed
39478 if (key.length > this.blockSize)
39479 key = new this.Hash().update(key).digest();
39480 minimalisticAssert(key.length <= this.blockSize);
39481
39482 // Add padding to key
39483 for (var i = key.length; i < this.blockSize; i++)
39484 key.push(0);
39485
39486 for (i = 0; i < key.length; i++)
39487 key[i] ^= 0x36;
39488 this.inner = new this.Hash().update(key);
39489
39490 // 0x36 ^ 0x5c = 0x6a
39491 for (i = 0; i < key.length; i++)
39492 key[i] ^= 0x6a;
39493 this.outer = new this.Hash().update(key);
39494};
39495
39496Hmac.prototype.update = function update(msg, enc) {
39497 this.inner.update(msg, enc);
39498 return this;
39499};
39500
39501Hmac.prototype.digest = function digest(enc) {
39502 this.outer.update(this.inner.digest());
39503 return this.outer.digest(enc);
39504};
39505
39506var hash_1 = createCommonjsModule(function (module, exports) {
39507var hash = exports;
39508
39509hash.utils = utils;
39510hash.common = common;
39511hash.sha = sha;
39512hash.ripemd = ripemd;
39513hash.hmac = hmac;
39514
39515// Proxy hash functions to the main object
39516hash.sha1 = hash.sha.sha1;
39517hash.sha256 = hash.sha.sha256;
39518hash.sha224 = hash.sha.sha224;
39519hash.sha384 = hash.sha.sha384;
39520hash.sha512 = hash.sha.sha512;
39521hash.ripemd160 = hash.ripemd.ripemd160;
39522});
39523
39524var secp256k1 = {
39525 doubles: {
39526 step: 4,
39527 points: [
39528 [
39529 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
39530 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
39531 ],
39532 [
39533 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
39534 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
39535 ],
39536 [
39537 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
39538 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
39539 ],
39540 [
39541 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
39542 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
39543 ],
39544 [
39545 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
39546 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
39547 ],
39548 [
39549 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
39550 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
39551 ],
39552 [
39553 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
39554 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
39555 ],
39556 [
39557 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
39558 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
39559 ],
39560 [
39561 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
39562 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
39563 ],
39564 [
39565 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
39566 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
39567 ],
39568 [
39569 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
39570 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
39571 ],
39572 [
39573 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
39574 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
39575 ],
39576 [
39577 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
39578 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
39579 ],
39580 [
39581 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
39582 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
39583 ],
39584 [
39585 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
39586 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
39587 ],
39588 [
39589 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
39590 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
39591 ],
39592 [
39593 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
39594 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
39595 ],
39596 [
39597 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
39598 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
39599 ],
39600 [
39601 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
39602 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
39603 ],
39604 [
39605 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
39606 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
39607 ],
39608 [
39609 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
39610 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
39611 ],
39612 [
39613 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
39614 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
39615 ],
39616 [
39617 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
39618 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
39619 ],
39620 [
39621 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
39622 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
39623 ],
39624 [
39625 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
39626 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
39627 ],
39628 [
39629 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
39630 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
39631 ],
39632 [
39633 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
39634 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
39635 ],
39636 [
39637 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
39638 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
39639 ],
39640 [
39641 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
39642 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
39643 ],
39644 [
39645 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
39646 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
39647 ],
39648 [
39649 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
39650 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
39651 ],
39652 [
39653 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
39654 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
39655 ],
39656 [
39657 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
39658 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
39659 ],
39660 [
39661 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
39662 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
39663 ],
39664 [
39665 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
39666 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
39667 ],
39668 [
39669 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
39670 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
39671 ],
39672 [
39673 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
39674 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
39675 ],
39676 [
39677 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
39678 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
39679 ],
39680 [
39681 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
39682 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
39683 ],
39684 [
39685 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
39686 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
39687 ],
39688 [
39689 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
39690 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
39691 ],
39692 [
39693 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
39694 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
39695 ],
39696 [
39697 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
39698 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
39699 ],
39700 [
39701 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
39702 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
39703 ],
39704 [
39705 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
39706 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
39707 ],
39708 [
39709 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
39710 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
39711 ],
39712 [
39713 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
39714 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
39715 ],
39716 [
39717 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
39718 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
39719 ],
39720 [
39721 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
39722 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
39723 ],
39724 [
39725 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
39726 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
39727 ],
39728 [
39729 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
39730 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
39731 ],
39732 [
39733 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
39734 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
39735 ],
39736 [
39737 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
39738 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
39739 ],
39740 [
39741 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
39742 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
39743 ],
39744 [
39745 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
39746 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
39747 ],
39748 [
39749 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
39750 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
39751 ],
39752 [
39753 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
39754 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
39755 ],
39756 [
39757 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
39758 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
39759 ],
39760 [
39761 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
39762 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
39763 ],
39764 [
39765 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
39766 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
39767 ],
39768 [
39769 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
39770 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
39771 ],
39772 [
39773 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
39774 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
39775 ],
39776 [
39777 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
39778 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
39779 ],
39780 [
39781 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
39782 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
39783 ],
39784 [
39785 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
39786 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
39787 ]
39788 ]
39789 },
39790 naf: {
39791 wnd: 7,
39792 points: [
39793 [
39794 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
39795 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
39796 ],
39797 [
39798 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
39799 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
39800 ],
39801 [
39802 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
39803 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
39804 ],
39805 [
39806 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
39807 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
39808 ],
39809 [
39810 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
39811 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
39812 ],
39813 [
39814 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
39815 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
39816 ],
39817 [
39818 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
39819 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
39820 ],
39821 [
39822 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
39823 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
39824 ],
39825 [
39826 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
39827 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
39828 ],
39829 [
39830 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
39831 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
39832 ],
39833 [
39834 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
39835 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
39836 ],
39837 [
39838 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
39839 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
39840 ],
39841 [
39842 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
39843 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
39844 ],
39845 [
39846 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
39847 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
39848 ],
39849 [
39850 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
39851 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
39852 ],
39853 [
39854 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
39855 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
39856 ],
39857 [
39858 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
39859 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
39860 ],
39861 [
39862 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
39863 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
39864 ],
39865 [
39866 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
39867 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
39868 ],
39869 [
39870 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
39871 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
39872 ],
39873 [
39874 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
39875 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
39876 ],
39877 [
39878 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
39879 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
39880 ],
39881 [
39882 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
39883 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
39884 ],
39885 [
39886 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
39887 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
39888 ],
39889 [
39890 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
39891 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
39892 ],
39893 [
39894 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
39895 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
39896 ],
39897 [
39898 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
39899 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
39900 ],
39901 [
39902 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
39903 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
39904 ],
39905 [
39906 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
39907 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
39908 ],
39909 [
39910 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
39911 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
39912 ],
39913 [
39914 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
39915 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
39916 ],
39917 [
39918 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
39919 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
39920 ],
39921 [
39922 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
39923 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
39924 ],
39925 [
39926 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
39927 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
39928 ],
39929 [
39930 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
39931 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
39932 ],
39933 [
39934 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
39935 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
39936 ],
39937 [
39938 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
39939 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
39940 ],
39941 [
39942 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
39943 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
39944 ],
39945 [
39946 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
39947 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
39948 ],
39949 [
39950 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
39951 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
39952 ],
39953 [
39954 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
39955 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
39956 ],
39957 [
39958 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
39959 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
39960 ],
39961 [
39962 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
39963 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
39964 ],
39965 [
39966 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
39967 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
39968 ],
39969 [
39970 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
39971 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
39972 ],
39973 [
39974 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
39975 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
39976 ],
39977 [
39978 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
39979 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
39980 ],
39981 [
39982 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
39983 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
39984 ],
39985 [
39986 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
39987 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
39988 ],
39989 [
39990 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
39991 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
39992 ],
39993 [
39994 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
39995 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
39996 ],
39997 [
39998 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
39999 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
40000 ],
40001 [
40002 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
40003 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
40004 ],
40005 [
40006 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
40007 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
40008 ],
40009 [
40010 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
40011 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
40012 ],
40013 [
40014 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
40015 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
40016 ],
40017 [
40018 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
40019 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
40020 ],
40021 [
40022 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
40023 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
40024 ],
40025 [
40026 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
40027 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
40028 ],
40029 [
40030 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
40031 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
40032 ],
40033 [
40034 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
40035 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
40036 ],
40037 [
40038 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
40039 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
40040 ],
40041 [
40042 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
40043 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
40044 ],
40045 [
40046 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
40047 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
40048 ],
40049 [
40050 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
40051 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
40052 ],
40053 [
40054 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
40055 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
40056 ],
40057 [
40058 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
40059 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
40060 ],
40061 [
40062 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
40063 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
40064 ],
40065 [
40066 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
40067 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
40068 ],
40069 [
40070 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
40071 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
40072 ],
40073 [
40074 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
40075 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
40076 ],
40077 [
40078 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
40079 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
40080 ],
40081 [
40082 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
40083 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
40084 ],
40085 [
40086 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
40087 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
40088 ],
40089 [
40090 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
40091 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
40092 ],
40093 [
40094 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
40095 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
40096 ],
40097 [
40098 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
40099 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
40100 ],
40101 [
40102 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
40103 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
40104 ],
40105 [
40106 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
40107 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
40108 ],
40109 [
40110 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
40111 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
40112 ],
40113 [
40114 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
40115 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
40116 ],
40117 [
40118 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
40119 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
40120 ],
40121 [
40122 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
40123 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
40124 ],
40125 [
40126 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
40127 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
40128 ],
40129 [
40130 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
40131 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
40132 ],
40133 [
40134 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
40135 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
40136 ],
40137 [
40138 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
40139 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
40140 ],
40141 [
40142 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
40143 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
40144 ],
40145 [
40146 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
40147 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
40148 ],
40149 [
40150 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
40151 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
40152 ],
40153 [
40154 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
40155 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
40156 ],
40157 [
40158 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
40159 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
40160 ],
40161 [
40162 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
40163 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
40164 ],
40165 [
40166 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
40167 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
40168 ],
40169 [
40170 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
40171 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
40172 ],
40173 [
40174 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
40175 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
40176 ],
40177 [
40178 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
40179 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
40180 ],
40181 [
40182 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
40183 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
40184 ],
40185 [
40186 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
40187 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
40188 ],
40189 [
40190 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
40191 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
40192 ],
40193 [
40194 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
40195 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
40196 ],
40197 [
40198 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
40199 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
40200 ],
40201 [
40202 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
40203 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
40204 ],
40205 [
40206 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
40207 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
40208 ],
40209 [
40210 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
40211 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
40212 ],
40213 [
40214 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
40215 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
40216 ],
40217 [
40218 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
40219 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
40220 ],
40221 [
40222 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
40223 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
40224 ],
40225 [
40226 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
40227 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
40228 ],
40229 [
40230 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
40231 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
40232 ],
40233 [
40234 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
40235 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
40236 ],
40237 [
40238 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
40239 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
40240 ],
40241 [
40242 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
40243 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
40244 ],
40245 [
40246 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
40247 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
40248 ],
40249 [
40250 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
40251 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
40252 ],
40253 [
40254 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
40255 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
40256 ],
40257 [
40258 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
40259 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
40260 ],
40261 [
40262 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
40263 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
40264 ],
40265 [
40266 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
40267 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
40268 ],
40269 [
40270 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
40271 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
40272 ],
40273 [
40274 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
40275 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
40276 ],
40277 [
40278 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
40279 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
40280 ],
40281 [
40282 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
40283 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
40284 ],
40285 [
40286 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
40287 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
40288 ],
40289 [
40290 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
40291 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
40292 ],
40293 [
40294 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
40295 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
40296 ],
40297 [
40298 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
40299 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
40300 ]
40301 ]
40302 }
40303};
40304
40305var curves_1 = createCommonjsModule(function (module, exports) {
40306
40307var curves = exports;
40308
40309
40310
40311
40312
40313var assert = utils_1$1.assert;
40314
40315function PresetCurve(options) {
40316 if (options.type === 'short')
40317 this.curve = new curve_1.short(options);
40318 else if (options.type === 'edwards')
40319 this.curve = new curve_1.edwards(options);
40320 else if (options.type === 'mont')
40321 this.curve = new curve_1.mont(options);
40322 else throw new Error('Unknown curve type.');
40323 this.g = this.curve.g;
40324 this.n = this.curve.n;
40325 this.hash = options.hash;
40326
40327 assert(this.g.validate(), 'Invalid curve');
40328 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
40329}
40330curves.PresetCurve = PresetCurve;
40331
40332function defineCurve(name, options) {
40333 Object.defineProperty(curves, name, {
40334 configurable: true,
40335 enumerable: true,
40336 get: function() {
40337 var curve = new PresetCurve(options);
40338 Object.defineProperty(curves, name, {
40339 configurable: true,
40340 enumerable: true,
40341 value: curve
40342 });
40343 return curve;
40344 }
40345 });
40346}
40347
40348defineCurve('p192', {
40349 type: 'short',
40350 prime: 'p192',
40351 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
40352 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
40353 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
40354 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
40355 hash: hash_1.sha256,
40356 gRed: false,
40357 g: [
40358 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
40359 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
40360 ]
40361});
40362
40363defineCurve('p224', {
40364 type: 'short',
40365 prime: 'p224',
40366 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
40367 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
40368 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
40369 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
40370 hash: hash_1.sha256,
40371 gRed: false,
40372 g: [
40373 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
40374 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
40375 ]
40376});
40377
40378defineCurve('p256', {
40379 type: 'short',
40380 prime: null,
40381 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
40382 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
40383 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
40384 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
40385 hash: hash_1.sha256,
40386 gRed: false,
40387 g: [
40388 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
40389 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
40390 ]
40391});
40392
40393defineCurve('p384', {
40394 type: 'short',
40395 prime: null,
40396 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40397 'fffffffe ffffffff 00000000 00000000 ffffffff',
40398 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40399 'fffffffe ffffffff 00000000 00000000 fffffffc',
40400 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
40401 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
40402 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
40403 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
40404 hash: hash_1.sha384,
40405 gRed: false,
40406 g: [
40407 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
40408 '5502f25d bf55296c 3a545e38 72760ab7',
40409 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
40410 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
40411 ]
40412});
40413
40414defineCurve('p521', {
40415 type: 'short',
40416 prime: null,
40417 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40418 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40419 'ffffffff ffffffff ffffffff ffffffff ffffffff',
40420 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40421 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40422 'ffffffff ffffffff ffffffff ffffffff fffffffc',
40423 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
40424 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
40425 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
40426 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
40427 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
40428 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
40429 hash: hash_1.sha512,
40430 gRed: false,
40431 g: [
40432 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
40433 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
40434 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
40435 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
40436 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
40437 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
40438 ]
40439});
40440
40441// https://tools.ietf.org/html/rfc7748#section-4.1
40442defineCurve('curve25519', {
40443 type: 'mont',
40444 prime: 'p25519',
40445 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
40446 a: '76d06',
40447 b: '1',
40448 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
40449 cofactor: '8',
40450 hash: hash_1.sha256,
40451 gRed: false,
40452 g: [
40453 '9'
40454 ]
40455});
40456
40457defineCurve('ed25519', {
40458 type: 'edwards',
40459 prime: 'p25519',
40460 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
40461 a: '-1',
40462 c: '1',
40463 // -121665 * (121666^(-1)) (mod P)
40464 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
40465 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
40466 cofactor: '8',
40467 hash: hash_1.sha256,
40468 gRed: false,
40469 g: [
40470 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
40471 // 4/5
40472 '6666666666666666666666666666666666666666666666666666666666666658'
40473 ]
40474});
40475
40476// https://tools.ietf.org/html/rfc5639#section-3.4
40477defineCurve('brainpoolP256r1', {
40478 type: 'short',
40479 prime: null,
40480 p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
40481 a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
40482 b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
40483 n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
40484 hash: hash_1.sha256, // or 384, or 512
40485 gRed: false,
40486 g: [
40487 '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
40488 '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
40489 ]
40490});
40491
40492// https://tools.ietf.org/html/rfc5639#section-3.6
40493defineCurve('brainpoolP384r1', {
40494 type: 'short',
40495 prime: null,
40496 p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
40497 'ACD3A729 901D1A71 87470013 3107EC53',
40498 a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
40499 '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
40500 b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
40501 '7CB43902 95DBC994 3AB78696 FA504C11',
40502 n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
40503 'CF3AB6AF 6B7FC310 3B883202 E9046565',
40504 hash: hash_1.sha384, // or 512
40505 gRed: false,
40506 g: [
40507 '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
40508 'E8E826E03436D646AAEF87B2E247D4AF1E',
40509 '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
40510 '280E4646217791811142820341263C5315'
40511 ]
40512});
40513
40514// https://tools.ietf.org/html/rfc5639#section-3.7
40515defineCurve('brainpoolP512r1', {
40516 type: 'short',
40517 prime: null,
40518 p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
40519 '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
40520 a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
40521 '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
40522 b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
40523 '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
40524 n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
40525 '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
40526 hash: hash_1.sha512,
40527 gRed: false,
40528 g: [
40529 '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
40530 '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
40531 '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
40532 '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
40533 ]
40534});
40535
40536// https://en.bitcoin.it/wiki/Secp256k1
40537var pre;
40538try {
40539 pre = secp256k1;
40540} catch (e) {
40541 pre = undefined;
40542}
40543
40544defineCurve('secp256k1', {
40545 type: 'short',
40546 prime: 'k256',
40547 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
40548 a: '0',
40549 b: '7',
40550 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
40551 h: '1',
40552 hash: hash_1.sha256,
40553
40554 // Precomputed endomorphism
40555 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
40556 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
40557 basis: [
40558 {
40559 a: '3086d221a7d46bcde86c90e49284eb15',
40560 b: '-e4437ed6010e88286f547fa90abfe4c3'
40561 },
40562 {
40563 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
40564 b: '3086d221a7d46bcde86c90e49284eb15'
40565 }
40566 ],
40567
40568 gRed: false,
40569 g: [
40570 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
40571 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
40572 pre
40573 ]
40574});
40575});
40576
40577function HmacDRBG(options) {
40578 if (!(this instanceof HmacDRBG))
40579 return new HmacDRBG(options);
40580 this.hash = options.hash;
40581 this.predResist = !!options.predResist;
40582
40583 this.outLen = this.hash.outSize;
40584 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
40585
40586 this._reseed = null;
40587 this.reseedInterval = null;
40588 this.K = null;
40589 this.V = null;
40590
40591 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
40592 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
40593 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
40594 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
40595 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
40596 this._init(entropy, nonce, pers);
40597}
40598var hmacDrbg = HmacDRBG;
40599
40600HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
40601 var seed = entropy.concat(nonce).concat(pers);
40602
40603 this.K = new Array(this.outLen / 8);
40604 this.V = new Array(this.outLen / 8);
40605 for (var i = 0; i < this.V.length; i++) {
40606 this.K[i] = 0x00;
40607 this.V[i] = 0x01;
40608 }
40609
40610 this._update(seed);
40611 this._reseed = 1;
40612 this.reseedInterval = 0x1000000000000; // 2^48
40613};
40614
40615HmacDRBG.prototype._hmac = function hmac() {
40616 return new hash_1.hmac(this.hash, this.K);
40617};
40618
40619HmacDRBG.prototype._update = function update(seed) {
40620 var kmac = this._hmac()
40621 .update(this.V)
40622 .update([ 0x00 ]);
40623 if (seed)
40624 kmac = kmac.update(seed);
40625 this.K = kmac.digest();
40626 this.V = this._hmac().update(this.V).digest();
40627 if (!seed)
40628 return;
40629
40630 this.K = this._hmac()
40631 .update(this.V)
40632 .update([ 0x01 ])
40633 .update(seed)
40634 .digest();
40635 this.V = this._hmac().update(this.V).digest();
40636};
40637
40638HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
40639 // Optional entropy enc
40640 if (typeof entropyEnc !== 'string') {
40641 addEnc = add;
40642 add = entropyEnc;
40643 entropyEnc = null;
40644 }
40645
40646 entropy = utils_1.toArray(entropy, entropyEnc);
40647 add = utils_1.toArray(add, addEnc);
40648
40649 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
40650 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
40651
40652 this._update(entropy.concat(add || []));
40653 this._reseed = 1;
40654};
40655
40656HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
40657 if (this._reseed > this.reseedInterval)
40658 throw new Error('Reseed is required');
40659
40660 // Optional encoding
40661 if (typeof enc !== 'string') {
40662 addEnc = add;
40663 add = enc;
40664 enc = null;
40665 }
40666
40667 // Optional additional data
40668 if (add) {
40669 add = utils_1.toArray(add, addEnc || 'hex');
40670 this._update(add);
40671 }
40672
40673 var temp = [];
40674 while (temp.length < len) {
40675 this.V = this._hmac().update(this.V).digest();
40676 temp = temp.concat(this.V);
40677 }
40678
40679 var res = temp.slice(0, len);
40680 this._update(add);
40681 this._reseed++;
40682 return utils_1.encode(res, enc);
40683};
40684
40685var assert$5 = utils_1$1.assert;
40686
40687function KeyPair(ec, options) {
40688 this.ec = ec;
40689 this.priv = null;
40690 this.pub = null;
40691
40692 // KeyPair(ec, { priv: ..., pub: ... })
40693 if (options.priv)
40694 this._importPrivate(options.priv, options.privEnc);
40695 if (options.pub)
40696 this._importPublic(options.pub, options.pubEnc);
40697}
40698var key = KeyPair;
40699
40700KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
40701 if (pub instanceof KeyPair)
40702 return pub;
40703
40704 return new KeyPair(ec, {
40705 pub: pub,
40706 pubEnc: enc
40707 });
40708};
40709
40710KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
40711 if (priv instanceof KeyPair)
40712 return priv;
40713
40714 return new KeyPair(ec, {
40715 priv: priv,
40716 privEnc: enc
40717 });
40718};
40719
40720// TODO: should not validate for X25519
40721KeyPair.prototype.validate = function validate() {
40722 var pub = this.getPublic();
40723
40724 if (pub.isInfinity())
40725 return { result: false, reason: 'Invalid public key' };
40726 if (!pub.validate())
40727 return { result: false, reason: 'Public key is not a point' };
40728 if (!pub.mul(this.ec.curve.n).isInfinity())
40729 return { result: false, reason: 'Public key * N != O' };
40730
40731 return { result: true, reason: null };
40732};
40733
40734KeyPair.prototype.getPublic = function getPublic(enc, compact) {
40735 if (!this.pub)
40736 this.pub = this.ec.g.mul(this.priv);
40737
40738 if (!enc)
40739 return this.pub;
40740
40741 return this.pub.encode(enc, compact);
40742};
40743
40744KeyPair.prototype.getPrivate = function getPrivate(enc) {
40745 if (enc === 'hex')
40746 return this.priv.toString(16, 2);
40747 else
40748 return this.priv;
40749};
40750
40751KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
40752 this.priv = new bn(key, enc || 16);
40753
40754 // For Curve25519/Curve448 we have a specific procedure.
40755 // TODO Curve448
40756 if (this.ec.curve.type === 'mont') {
40757 var one = this.ec.curve.one;
40758 var mask = one.ushln(255 - 3).sub(one).ushln(3);
40759 this.priv = this.priv.or(one.ushln(255 - 1));
40760 this.priv = this.priv.and(mask);
40761 } else
40762 // Ensure that the priv won't be bigger than n, otherwise we may fail
40763 // in fixed multiplication method
40764 this.priv = this.priv.umod(this.ec.curve.n);
40765};
40766
40767KeyPair.prototype._importPublic = function _importPublic(key, enc) {
40768 if (key.x || key.y) {
40769 // Montgomery points only have an `x` coordinate.
40770 // Weierstrass/Edwards points on the other hand have both `x` and
40771 // `y` coordinates.
40772 if (this.ec.curve.type === 'mont') {
40773 assert$5(key.x, 'Need x coordinate');
40774 } else if (this.ec.curve.type === 'short' ||
40775 this.ec.curve.type === 'edwards') {
40776 assert$5(key.x && key.y, 'Need both x and y coordinate');
40777 }
40778 this.pub = this.ec.curve.point(key.x, key.y);
40779 return;
40780 }
40781 this.pub = this.ec.curve.decodePoint(key, enc);
40782};
40783
40784// ECDH
40785KeyPair.prototype.derive = function derive(pub) {
40786 return pub.mul(this.priv).getX();
40787};
40788
40789// ECDSA
40790KeyPair.prototype.sign = function sign(msg, enc, options) {
40791 return this.ec.sign(msg, this, enc, options);
40792};
40793
40794KeyPair.prototype.verify = function verify(msg, signature) {
40795 return this.ec.verify(msg, signature, this);
40796};
40797
40798KeyPair.prototype.inspect = function inspect() {
40799 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
40800 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
40801};
40802
40803var assert$6 = utils_1$1.assert;
40804
40805function Signature$1(options, enc) {
40806 if (options instanceof Signature$1)
40807 return options;
40808
40809 if (this._importDER(options, enc))
40810 return;
40811
40812 assert$6(options.r && options.s, 'Signature without r or s');
40813 this.r = new bn(options.r, 16);
40814 this.s = new bn(options.s, 16);
40815 if (options.recoveryParam === undefined)
40816 this.recoveryParam = null;
40817 else
40818 this.recoveryParam = options.recoveryParam;
40819}
40820var signature$1 = Signature$1;
40821
40822function Position() {
40823 this.place = 0;
40824}
40825
40826function getLength(buf, p) {
40827 var initial = buf[p.place++];
40828 if (!(initial & 0x80)) {
40829 return initial;
40830 }
40831 var octetLen = initial & 0xf;
40832 var val = 0;
40833 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
40834 val <<= 8;
40835 val |= buf[off];
40836 }
40837 p.place = off;
40838 return val;
40839}
40840
40841function rmPadding(buf) {
40842 var i = 0;
40843 var len = buf.length - 1;
40844 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
40845 i++;
40846 }
40847 if (i === 0) {
40848 return buf;
40849 }
40850 return buf.slice(i);
40851}
40852
40853Signature$1.prototype._importDER = function _importDER(data, enc) {
40854 data = utils_1$1.toArray(data, enc);
40855 var p = new Position();
40856 if (data[p.place++] !== 0x30) {
40857 return false;
40858 }
40859 var len = getLength(data, p);
40860 if ((len + p.place) !== data.length) {
40861 return false;
40862 }
40863 if (data[p.place++] !== 0x02) {
40864 return false;
40865 }
40866 var rlen = getLength(data, p);
40867 var r = data.slice(p.place, rlen + p.place);
40868 p.place += rlen;
40869 if (data[p.place++] !== 0x02) {
40870 return false;
40871 }
40872 var slen = getLength(data, p);
40873 if (data.length !== slen + p.place) {
40874 return false;
40875 }
40876 var s = data.slice(p.place, slen + p.place);
40877 if (r[0] === 0 && (r[1] & 0x80)) {
40878 r = r.slice(1);
40879 }
40880 if (s[0] === 0 && (s[1] & 0x80)) {
40881 s = s.slice(1);
40882 }
40883
40884 this.r = new bn(r);
40885 this.s = new bn(s);
40886 this.recoveryParam = null;
40887
40888 return true;
40889};
40890
40891function constructLength(arr, len) {
40892 if (len < 0x80) {
40893 arr.push(len);
40894 return;
40895 }
40896 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
40897 arr.push(octets | 0x80);
40898 while (--octets) {
40899 arr.push((len >>> (octets << 3)) & 0xff);
40900 }
40901 arr.push(len);
40902}
40903
40904Signature$1.prototype.toDER = function toDER(enc) {
40905 var r = this.r.toArray();
40906 var s = this.s.toArray();
40907
40908 // Pad values
40909 if (r[0] & 0x80)
40910 r = [ 0 ].concat(r);
40911 // Pad values
40912 if (s[0] & 0x80)
40913 s = [ 0 ].concat(s);
40914
40915 r = rmPadding(r);
40916 s = rmPadding(s);
40917
40918 while (!s[0] && !(s[1] & 0x80)) {
40919 s = s.slice(1);
40920 }
40921 var arr = [ 0x02 ];
40922 constructLength(arr, r.length);
40923 arr = arr.concat(r);
40924 arr.push(0x02);
40925 constructLength(arr, s.length);
40926 var backHalf = arr.concat(s);
40927 var res = [ 0x30 ];
40928 constructLength(res, backHalf.length);
40929 res = res.concat(backHalf);
40930 return utils_1$1.encode(res, enc);
40931};
40932
40933var assert$7 = utils_1$1.assert;
40934
40935
40936
40937
40938function EC(options) {
40939 if (!(this instanceof EC))
40940 return new EC(options);
40941
40942 // Shortcut `elliptic.ec(curve-name)`
40943 if (typeof options === 'string') {
40944 assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
40945
40946 options = curves_1[options];
40947 }
40948
40949 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
40950 if (options instanceof curves_1.PresetCurve)
40951 options = { curve: options };
40952
40953 this.curve = options.curve.curve;
40954 this.n = this.curve.n;
40955 this.nh = this.n.ushrn(1);
40956 this.g = this.curve.g;
40957
40958 // Point on curve
40959 this.g = options.curve.g;
40960 this.g.precompute(options.curve.n.bitLength() + 1);
40961
40962 // Hash function for DRBG
40963 this.hash = options.hash || options.curve.hash;
40964}
40965var ec = EC;
40966
40967EC.prototype.keyPair = function keyPair(options) {
40968 return new key(this, options);
40969};
40970
40971EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
40972 return key.fromPrivate(this, priv, enc);
40973};
40974
40975EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
40976 return key.fromPublic(this, pub, enc);
40977};
40978
40979EC.prototype.genKeyPair = function genKeyPair(options) {
40980 if (!options)
40981 options = {};
40982
40983 // Instantiate Hmac_DRBG
40984 var drbg = new hmacDrbg({
40985 hash: this.hash,
40986 pers: options.pers,
40987 persEnc: options.persEnc || 'utf8',
40988 entropy: options.entropy || brorand(this.hash.hmacStrength),
40989 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
40990 nonce: this.n.toArray()
40991 });
40992
40993 // Key generation for curve25519 is simpler
40994 if (this.curve.type === 'mont') {
40995 var priv = new bn(drbg.generate(32));
40996 return this.keyFromPrivate(priv);
40997 }
40998
40999 var bytes = this.n.byteLength();
41000 var ns2 = this.n.sub(new bn(2));
41001 do {
41002 var priv = new bn(drbg.generate(bytes));
41003 if (priv.cmp(ns2) > 0)
41004 continue;
41005
41006 priv.iaddn(1);
41007 return this.keyFromPrivate(priv);
41008 } while (true);
41009};
41010
41011EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
41012 bitSize = bitSize || msg.byteLength() * 8;
41013 var delta = bitSize - this.n.bitLength();
41014 if (delta > 0)
41015 msg = msg.ushrn(delta);
41016 if (!truncOnly && msg.cmp(this.n) >= 0)
41017 return msg.sub(this.n);
41018 else
41019 return msg;
41020};
41021
41022EC.prototype.truncateMsg = function truncateMSG(msg) {
41023 // Bit size is only determined correctly for Uint8Arrays and hex strings
41024 var bitSize;
41025 if (msg instanceof Uint8Array) {
41026 bitSize = msg.byteLength * 8;
41027 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
41028 } else if (typeof msg === 'string') {
41029 bitSize = msg.length * 4;
41030 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
41031 } else {
41032 msg = this._truncateToN(new bn(msg, 16));
41033 }
41034 return msg;
41035};
41036
41037EC.prototype.sign = function sign(msg, key, enc, options) {
41038 if (typeof enc === 'object') {
41039 options = enc;
41040 enc = null;
41041 }
41042 if (!options)
41043 options = {};
41044
41045 key = this.keyFromPrivate(key, enc);
41046 msg = this.truncateMsg(msg);
41047
41048 // Zero-extend key to provide enough entropy
41049 var bytes = this.n.byteLength();
41050 var bkey = key.getPrivate().toArray('be', bytes);
41051
41052 // Zero-extend nonce to have the same byte size as N
41053 var nonce = msg.toArray('be', bytes);
41054
41055 // Instantiate Hmac_DRBG
41056 var drbg = new hmacDrbg({
41057 hash: this.hash,
41058 entropy: bkey,
41059 nonce: nonce,
41060 pers: options.pers,
41061 persEnc: options.persEnc || 'utf8'
41062 });
41063
41064 // Number of bytes to generate
41065 var ns1 = this.n.sub(new bn(1));
41066
41067 for (var iter = 0; true; iter++) {
41068 var k = options.k ?
41069 options.k(iter) :
41070 new bn(drbg.generate(this.n.byteLength()));
41071 k = this._truncateToN(k, true);
41072 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
41073 continue;
41074
41075 var kp = this.g.mul(k);
41076 if (kp.isInfinity())
41077 continue;
41078
41079 var kpX = kp.getX();
41080 var r = kpX.umod(this.n);
41081 if (r.cmpn(0) === 0)
41082 continue;
41083
41084 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
41085 s = s.umod(this.n);
41086 if (s.cmpn(0) === 0)
41087 continue;
41088
41089 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
41090 (kpX.cmp(r) !== 0 ? 2 : 0);
41091
41092 // Use complement of `s`, if it is > `n / 2`
41093 if (options.canonical && s.cmp(this.nh) > 0) {
41094 s = this.n.sub(s);
41095 recoveryParam ^= 1;
41096 }
41097
41098 return new signature$1({ r: r, s: s, recoveryParam: recoveryParam });
41099 }
41100};
41101
41102EC.prototype.verify = function verify(msg, signature, key, enc) {
41103 key = this.keyFromPublic(key, enc);
41104 signature = new signature$1(signature, 'hex');
41105 // Fallback to the old code
41106 var ret = this._verify(this.truncateMsg(msg), signature, key) ||
41107 this._verify(this._truncateToN(new bn(msg, 16)), signature, key);
41108 return ret;
41109};
41110
41111EC.prototype._verify = function _verify(msg, signature, key) {
41112 // Perform primitive values validation
41113 var r = signature.r;
41114 var s = signature.s;
41115 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
41116 return false;
41117 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
41118 return false;
41119
41120 // Validate signature
41121 var sinv = s.invm(this.n);
41122 var u1 = sinv.mul(msg).umod(this.n);
41123 var u2 = sinv.mul(r).umod(this.n);
41124
41125 if (!this.curve._maxwellTrick) {
41126 var p = this.g.mulAdd(u1, key.getPublic(), u2);
41127 if (p.isInfinity())
41128 return false;
41129
41130 return p.getX().umod(this.n).cmp(r) === 0;
41131 }
41132
41133 // NOTE: Greg Maxwell's trick, inspired by:
41134 // https://git.io/vad3K
41135
41136 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
41137 if (p.isInfinity())
41138 return false;
41139
41140 // Compare `p.x` of Jacobian point with `r`,
41141 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
41142 // inverse of `p.z^2`
41143 return p.eqXToP(r);
41144};
41145
41146EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
41147 assert$7((3 & j) === j, 'The recovery param is more than two bits');
41148 signature = new signature$1(signature, enc);
41149
41150 var n = this.n;
41151 var e = new bn(msg);
41152 var r = signature.r;
41153 var s = signature.s;
41154
41155 // A set LSB signifies that the y-coordinate is odd
41156 var isYOdd = j & 1;
41157 var isSecondKey = j >> 1;
41158 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
41159 throw new Error('Unable to find sencond key candinate');
41160
41161 // 1.1. Let x = r + jn.
41162 if (isSecondKey)
41163 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
41164 else
41165 r = this.curve.pointFromX(r, isYOdd);
41166
41167 var rInv = signature.r.invm(n);
41168 var s1 = n.sub(e).mul(rInv).umod(n);
41169 var s2 = s.mul(rInv).umod(n);
41170
41171 // 1.6.1 Compute Q = r^-1 (sR - eG)
41172 // Q = r^-1 (sR + -eG)
41173 return this.g.mulAdd(s1, r, s2);
41174};
41175
41176EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
41177 signature = new signature$1(signature, enc);
41178 if (signature.recoveryParam !== null)
41179 return signature.recoveryParam;
41180
41181 for (var i = 0; i < 4; i++) {
41182 var Qprime;
41183 try {
41184 Qprime = this.recoverPubKey(e, signature, i);
41185 } catch (e) {
41186 continue;
41187 }
41188
41189 if (Qprime.eq(Q))
41190 return i;
41191 }
41192 throw new Error('Unable to find valid recovery factor');
41193};
41194
41195var assert$8 = utils_1$1.assert;
41196var parseBytes = utils_1$1.parseBytes;
41197var cachedProperty = utils_1$1.cachedProperty;
41198
41199/**
41200* @param {EDDSA} eddsa - instance
41201* @param {Object} params - public/private key parameters
41202*
41203* @param {Array<Byte>} [params.secret] - secret seed bytes
41204* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
41205* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
41206*
41207*/
41208function KeyPair$1(eddsa, params) {
41209 this.eddsa = eddsa;
41210 if (params.hasOwnProperty('secret'))
41211 this._secret = parseBytes(params.secret);
41212 if (eddsa.isPoint(params.pub))
41213 this._pub = params.pub;
41214 else {
41215 this._pubBytes = parseBytes(params.pub);
41216 if (this._pubBytes && this._pubBytes.length === 33 &&
41217 this._pubBytes[0] === 0x40)
41218 this._pubBytes = this._pubBytes.slice(1, 33);
41219 if (this._pubBytes && this._pubBytes.length !== 32)
41220 throw new Error('Unknown point compression format');
41221 }
41222}
41223
41224KeyPair$1.fromPublic = function fromPublic(eddsa, pub) {
41225 if (pub instanceof KeyPair$1)
41226 return pub;
41227 return new KeyPair$1(eddsa, { pub: pub });
41228};
41229
41230KeyPair$1.fromSecret = function fromSecret(eddsa, secret) {
41231 if (secret instanceof KeyPair$1)
41232 return secret;
41233 return new KeyPair$1(eddsa, { secret: secret });
41234};
41235
41236KeyPair$1.prototype.secret = function secret() {
41237 return this._secret;
41238};
41239
41240cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() {
41241 return this.eddsa.encodePoint(this.pub());
41242});
41243
41244cachedProperty(KeyPair$1, 'pub', function pub() {
41245 if (this._pubBytes)
41246 return this.eddsa.decodePoint(this._pubBytes);
41247 return this.eddsa.g.mul(this.priv());
41248});
41249
41250cachedProperty(KeyPair$1, 'privBytes', function privBytes() {
41251 var eddsa = this.eddsa;
41252 var hash = this.hash();
41253 var lastIx = eddsa.encodingLength - 1;
41254
41255 // https://tools.ietf.org/html/rfc8032#section-5.1.5
41256 var a = hash.slice(0, eddsa.encodingLength);
41257 a[0] &= 248;
41258 a[lastIx] &= 127;
41259 a[lastIx] |= 64;
41260
41261 return a;
41262});
41263
41264cachedProperty(KeyPair$1, 'priv', function priv() {
41265 return this.eddsa.decodeInt(this.privBytes());
41266});
41267
41268cachedProperty(KeyPair$1, 'hash', function hash() {
41269 return this.eddsa.hash().update(this.secret()).digest();
41270});
41271
41272cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() {
41273 return this.hash().slice(this.eddsa.encodingLength);
41274});
41275
41276KeyPair$1.prototype.sign = function sign(message) {
41277 assert$8(this._secret, 'KeyPair can only verify');
41278 return this.eddsa.sign(message, this);
41279};
41280
41281KeyPair$1.prototype.verify = function verify(message, sig) {
41282 return this.eddsa.verify(message, sig, this);
41283};
41284
41285KeyPair$1.prototype.getSecret = function getSecret(enc) {
41286 assert$8(this._secret, 'KeyPair is public only');
41287 return utils_1$1.encode(this.secret(), enc);
41288};
41289
41290KeyPair$1.prototype.getPublic = function getPublic(enc, compact) {
41291 return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
41292};
41293
41294var key$1 = KeyPair$1;
41295
41296var assert$9 = utils_1$1.assert;
41297var cachedProperty$1 = utils_1$1.cachedProperty;
41298var parseBytes$1 = utils_1$1.parseBytes;
41299
41300/**
41301* @param {EDDSA} eddsa - eddsa instance
41302* @param {Array<Bytes>|Object} sig -
41303* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
41304* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
41305* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
41306* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
41307*/
41308function Signature$2(eddsa, sig) {
41309 this.eddsa = eddsa;
41310
41311 if (typeof sig !== 'object')
41312 sig = parseBytes$1(sig);
41313
41314 if (Array.isArray(sig)) {
41315 sig = {
41316 R: sig.slice(0, eddsa.encodingLength),
41317 S: sig.slice(eddsa.encodingLength)
41318 };
41319 }
41320
41321 assert$9(sig.R && sig.S, 'Signature without R or S');
41322
41323 if (eddsa.isPoint(sig.R))
41324 this._R = sig.R;
41325 if (sig.S instanceof bn)
41326 this._S = sig.S;
41327
41328 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
41329 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
41330}
41331
41332cachedProperty$1(Signature$2, 'S', function S() {
41333 return this.eddsa.decodeInt(this.Sencoded());
41334});
41335
41336cachedProperty$1(Signature$2, 'R', function R() {
41337 return this.eddsa.decodePoint(this.Rencoded());
41338});
41339
41340cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() {
41341 return this.eddsa.encodePoint(this.R());
41342});
41343
41344cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() {
41345 return this.eddsa.encodeInt(this.S());
41346});
41347
41348Signature$2.prototype.toBytes = function toBytes() {
41349 return this.Rencoded().concat(this.Sencoded());
41350};
41351
41352Signature$2.prototype.toHex = function toHex() {
41353 return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase();
41354};
41355
41356var signature$2 = Signature$2;
41357
41358var assert$a = utils_1$1.assert;
41359var parseBytes$2 = utils_1$1.parseBytes;
41360
41361
41362
41363function EDDSA(curve) {
41364 assert$a(curve === 'ed25519', 'only tested with ed25519 so far');
41365
41366 if (!(this instanceof EDDSA))
41367 return new EDDSA(curve);
41368
41369 var curve = curves_1[curve].curve;
41370 this.curve = curve;
41371 this.g = curve.g;
41372 this.g.precompute(curve.n.bitLength() + 1);
41373
41374 this.pointClass = curve.point().constructor;
41375 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
41376 this.hash = hash_1.sha512;
41377}
41378
41379var eddsa$1 = EDDSA;
41380
41381/**
41382* @param {Array|String} message - message bytes
41383* @param {Array|String|KeyPair} secret - secret bytes or a keypair
41384* @returns {Signature} - signature
41385*/
41386EDDSA.prototype.sign = function sign(message, secret) {
41387 message = parseBytes$2(message);
41388 var key = this.keyFromSecret(secret);
41389 var r = this.hashInt(key.messagePrefix(), message);
41390 var R = this.g.mul(r);
41391 var Rencoded = this.encodePoint(R);
41392 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
41393 .mul(key.priv());
41394 var S = r.add(s_).umod(this.curve.n);
41395 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
41396};
41397
41398/**
41399* @param {Array} message - message bytes
41400* @param {Array|String|Signature} sig - sig bytes
41401* @param {Array|String|Point|KeyPair} pub - public key
41402* @returns {Boolean} - true if public key matches sig of message
41403*/
41404EDDSA.prototype.verify = function verify(message, sig, pub) {
41405 message = parseBytes$2(message);
41406 sig = this.makeSignature(sig);
41407 var key = this.keyFromPublic(pub);
41408 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
41409 var SG = this.g.mul(sig.S());
41410 var RplusAh = sig.R().add(key.pub().mul(h));
41411 return RplusAh.eq(SG);
41412};
41413
41414EDDSA.prototype.hashInt = function hashInt() {
41415 var hash = this.hash();
41416 for (var i = 0; i < arguments.length; i++)
41417 hash.update(arguments[i]);
41418 return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n);
41419};
41420
41421EDDSA.prototype.keyPair = function keyPair(options) {
41422 return new key$1(this, options);
41423};
41424
41425EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
41426 return key$1.fromPublic(this, pub);
41427};
41428
41429EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
41430 return key$1.fromSecret(this, secret);
41431};
41432
41433EDDSA.prototype.genKeyPair = function genKeyPair(options) {
41434 if (!options)
41435 options = {};
41436
41437 // Instantiate Hmac_DRBG
41438 var drbg = new hmacDrbg({
41439 hash: this.hash,
41440 pers: options.pers,
41441 persEnc: options.persEnc || 'utf8',
41442 entropy: options.entropy || brorand(this.hash.hmacStrength),
41443 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
41444 nonce: this.curve.n.toArray()
41445 });
41446
41447 return this.keyFromSecret(drbg.generate(32));
41448};
41449
41450EDDSA.prototype.makeSignature = function makeSignature(sig) {
41451 if (sig instanceof signature$2)
41452 return sig;
41453 return new signature$2(this, sig);
41454};
41455
41456/**
41457* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
41458*
41459* EDDSA defines methods for encoding and decoding points and integers. These are
41460* helper convenience methods, that pass along to utility functions implied
41461* parameters.
41462*
41463*/
41464EDDSA.prototype.encodePoint = function encodePoint(point) {
41465 var enc = point.getY().toArray('le', this.encodingLength);
41466 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
41467 return enc;
41468};
41469
41470EDDSA.prototype.decodePoint = function decodePoint(bytes) {
41471 bytes = utils_1$1.parseBytes(bytes);
41472
41473 var lastIx = bytes.length - 1;
41474 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
41475 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
41476
41477 var y = utils_1$1.intFromLE(normed);
41478 return this.curve.pointFromY(y, xIsOdd);
41479};
41480
41481EDDSA.prototype.encodeInt = function encodeInt(num) {
41482 return num.toArray('le', this.encodingLength);
41483};
41484
41485EDDSA.prototype.decodeInt = function decodeInt(bytes) {
41486 return utils_1$1.intFromLE(bytes);
41487};
41488
41489EDDSA.prototype.isPoint = function isPoint(val) {
41490 return val instanceof this.pointClass;
41491};
41492
41493var elliptic_1 = createCommonjsModule(function (module, exports) {
41494
41495var elliptic = exports;
41496
41497elliptic.utils = utils_1$1;
41498elliptic.rand = brorand;
41499elliptic.curve = curve_1;
41500elliptic.curves = curves_1;
41501
41502// Protocols
41503elliptic.ec = ec;
41504elliptic.eddsa = eddsa$1;
41505});
41506
41507var elliptic$1 = /*#__PURE__*/Object.freeze({
41508 __proto__: null,
41509 'default': elliptic_1,
41510 __moduleExports: elliptic_1
41511});
41512
41513exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket;
41514exports.CleartextMessage = CleartextMessage;
41515exports.CompressedDataPacket = CompressedDataPacket;
41516exports.Key = Key;
41517exports.LiteralDataPacket = LiteralDataPacket;
41518exports.MarkerPacket = MarkerPacket;
41519exports.Message = Message;
41520exports.OnePassSignaturePacket = OnePassSignaturePacket;
41521exports.PacketList = PacketList;
41522exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket;
41523exports.PublicKeyPacket = PublicKeyPacket;
41524exports.PublicSubkeyPacket = PublicSubkeyPacket;
41525exports.SecretKeyPacket = SecretKeyPacket;
41526exports.SecretSubkeyPacket = SecretSubkeyPacket;
41527exports.Signature = Signature;
41528exports.SignaturePacket = SignaturePacket;
41529exports.SymEncryptedIntegrityProtectedDataPacket = SymEncryptedIntegrityProtectedDataPacket;
41530exports.SymEncryptedSessionKeyPacket = SymEncryptedSessionKeyPacket;
41531exports.SymmetricallyEncryptedDataPacket = SymmetricallyEncryptedDataPacket;
41532exports.TrustPacket = TrustPacket;
41533exports.UserAttributePacket = UserAttributePacket;
41534exports.UserIDPacket = UserIDPacket;
41535exports.armor = armor;
41536exports.config = defaultConfig;
41537exports.decrypt = decrypt$4;
41538exports.decryptKey = decryptKey;
41539exports.decryptSessionKeys = decryptSessionKeys;
41540exports.encrypt = encrypt$4;
41541exports.encryptKey = encryptKey;
41542exports.encryptSessionKey = encryptSessionKey;
41543exports.enums = enums;
41544exports.generateKey = generateKey;
41545exports.generateSessionKey = generateSessionKey$1;
41546exports.newPacketFromTag = newPacketFromTag;
41547exports.readCleartextMessage = readCleartextMessage;
41548exports.readKey = readKey;
41549exports.readKeys = readKeys;
41550exports.readMessage = readMessage;
41551exports.readSignature = readSignature;
41552exports.reformatKey = reformatKey;
41553exports.revokeKey = revokeKey;
41554exports.sign = sign$5;
41555exports.stream = stream;
41556exports.unarmor = unarmor;
41557exports.verify = verify$5;