diff --git a/bower.json b/bower.json index 3ae011a5..f36546cc 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "openpgp", - "version": "2.6.2", + "version": "3.0.0", "license": "LGPL-3.0+", "homepage": "https://openpgpjs.org/", "authors": [ diff --git a/dist/openpgp.js b/dist/openpgp.js index ed1580ac..cad6a567 100644 --- a/dist/openpgp.js +++ b/dist/openpgp.js @@ -1,2093 +1,2345 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.openpgp = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= len ) throw new Error( "Malformed string, low surrogate expected at position " + i ); - c = ( (c ^ 0xd800) << 10 ) | 0x10000 | ( str.charCodeAt(i) ^ 0xdc00 ); - } - else if ( !utf8 && c >>> 8 ) { - throw new Error("Wide characters are not allowed."); - } - - if ( !utf8 || c <= 0x7f ) { - bytes[j++] = c; - } - else if ( c <= 0x7ff ) { - bytes[j++] = 0xc0 | (c >> 6); - bytes[j++] = 0x80 | (c & 0x3f); - } - else if ( c <= 0xffff ) { - bytes[j++] = 0xe0 | (c >> 12); - bytes[j++] = 0x80 | (c >> 6 & 0x3f); - bytes[j++] = 0x80 | (c & 0x3f); - } - else { - bytes[j++] = 0xf0 | (c >> 18); - bytes[j++] = 0x80 | (c >> 12 & 0x3f); - bytes[j++] = 0x80 | (c >> 6 & 0x3f); - bytes[j++] = 0x80 | (c & 0x3f); - } - } - - return bytes.subarray(0, j); -} - -function hex_to_bytes ( str ) { - var len = str.length; - if ( len & 1 ) { - str = '0'+str; - len++; - } - var bytes = new Uint8Array(len>>1); - for ( var i = 0; i < len; i += 2 ) { - bytes[i>>1] = parseInt( str.substr( i, 2), 16 ); - } - return bytes; -} - -function base64_to_bytes ( str ) { - return string_to_bytes( atob( str ) ); -} - -function bytes_to_string ( bytes, utf8 ) { - utf8 = !!utf8; - - var len = bytes.length, - chars = new Array(len); - - for ( var i = 0, j = 0; i < len; i++ ) { - var b = bytes[i]; - if ( !utf8 || b < 128 ) { - chars[j++] = b; - } - else if ( b >= 192 && b < 224 && i+1 < len ) { - chars[j++] = ( (b & 0x1f) << 6 ) | (bytes[++i] & 0x3f); - } - else if ( b >= 224 && b < 240 && i+2 < len ) { - chars[j++] = ( (b & 0xf) << 12 ) | ( (bytes[++i] & 0x3f) << 6 ) | (bytes[++i] & 0x3f); - } - else if ( b >= 240 && b < 248 && i+3 < len ) { - var c = ( (b & 7) << 18 ) | ( (bytes[++i] & 0x3f) << 12 ) | ( (bytes[++i] & 0x3f) << 6 ) | (bytes[++i] & 0x3f); - if ( c <= 0xffff ) { - chars[j++] = c; - } - else { - c ^= 0x10000; - chars[j++] = 0xd800 | (c >> 10); - chars[j++] = 0xdc00 | (c & 0x3ff); - } - } - else { - throw new Error("Malformed UTF8 character at byte offset " + i); - } - } - - var str = '', - bs = 16384; - for ( var i = 0; i < j; i += bs ) { - str += String.fromCharCode.apply( String, chars.slice( i, i+bs <= j ? i+bs : j ) ); - } - - return str; -} - -function bytes_to_hex ( arr ) { - var str = ''; - for ( var i = 0; i < arr.length; i++ ) { - var h = ( arr[i] & 0xff ).toString(16); - if ( h.length < 2 ) str += '0'; - str += h; - } - return str; -} - -function bytes_to_base64 ( arr ) { - return btoa( bytes_to_string(arr) ); -} - -function pow2_ceil ( a ) { - a -= 1; - a |= a >>> 1; - a |= a >>> 2; - a |= a >>> 4; - a |= a >>> 8; - a |= a >>> 16; - a += 1; - return a; -} - -function is_number ( a ) { - return ( typeof a === 'number' ); -} - -function is_string ( a ) { - return ( typeof a === 'string' ); -} - -function is_buffer ( a ) { - return ( a instanceof ArrayBuffer ); -} - -function is_bytes ( a ) { - return ( a instanceof Uint8Array ); -} - -function is_typed_array ( a ) { - return ( a instanceof Int8Array ) || ( a instanceof Uint8Array ) - || ( a instanceof Int16Array ) || ( a instanceof Uint16Array ) - || ( a instanceof Int32Array ) || ( a instanceof Uint32Array ) - || ( a instanceof Float32Array ) - || ( a instanceof Float64Array ); -} - -function _heap_init ( constructor, options ) { - var heap = options.heap, - size = heap ? heap.byteLength : options.heapSize || 65536; - - if ( size & 0xfff || size <= 0 ) - throw new Error("heap size must be a positive integer and a multiple of 4096"); - - heap = heap || new constructor( new ArrayBuffer(size) ); - - return heap; -} - -function _heap_write ( heap, hpos, data, dpos, dlen ) { - var hlen = heap.length - hpos, - wlen = ( hlen < dlen ) ? hlen : dlen; - - heap.set( data.subarray( dpos, dpos+wlen ), hpos ); - - return wlen; -} - -/** - * Error definitions - */ - -global.IllegalStateError = IllegalStateError; -global.IllegalArgumentError = IllegalArgumentError; -global.SecurityError = SecurityError; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); /** * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}. * @author Artem S Vybornov * @license MIT */ -var AES_asm = function () { - "use strict"; +var AES_asm = exports.AES_asm = function () { + "use strict"; - /** - * Galois Field stuff init flag - */ - var ginit_done = false; + /** + * Galois Field stuff init flag + */ - /** - * Galois Field exponentiation and logarithm tables for 3 (the generator) - */ - var gexp3, glog3; + var ginit_done = false; - /** - * Init Galois Field tables - */ - function ginit () { - gexp3 = [], - glog3 = []; + /** + * Galois Field exponentiation and logarithm tables for 3 (the generator) + */ + var gexp3, glog3; - var a = 1, c, d; - for ( c = 0; c < 255; c++ ) { - gexp3[c] = a; + /** + * Init Galois Field tables + */ + function ginit() { + gexp3 = [], glog3 = []; - // Multiply by three - d = a & 0x80, a <<= 1, a &= 255; - if ( d === 0x80 ) a ^= 0x1b; - a ^= gexp3[c]; + var a = 1, + c, + d; + for (c = 0; c < 255; c++) { + gexp3[c] = a; - // Set the log table value - glog3[gexp3[c]] = c; - } - gexp3[255] = gexp3[0]; - glog3[0] = 0; + // Multiply by three + d = a & 0x80, a <<= 1, a &= 255; + if (d === 0x80) a ^= 0x1b; + a ^= gexp3[c]; - ginit_done = true; + // Set the log table value + glog3[gexp3[c]] = c; + } + gexp3[255] = gexp3[0]; + glog3[0] = 0; + + ginit_done = true; + } + + /** + * Galois Field multiplication + * @param {number} a + * @param {number} b + * @return {number} + */ + function gmul(a, b) { + var c = gexp3[(glog3[a] + glog3[b]) % 255]; + if (a === 0 || b === 0) c = 0; + return c; + } + + /** + * Galois Field reciprocal + * @param {number} a + * @return {number} + */ + function ginv(a) { + var i = gexp3[255 - glog3[a]]; + if (a === 0) i = 0; + return i; + } + + /** + * AES stuff init flag + */ + var aes_init_done = false; + + /** + * Encryption, Decryption, S-Box and KeyTransform tables + * + * @type {number[]} + */ + var aes_sbox; + + /** + * @type {number[]} + */ + var aes_sinv; + + /** + * @type {number[][]} + */ + var aes_enc; + + /** + * @type {number[][]} + */ + var aes_dec; + + /** + * Init AES tables + */ + function aes_init() { + if (!ginit_done) ginit(); + + // Calculates AES S-Box value + function _s(a) { + var c, s, x; + s = x = ginv(a); + for (c = 0; c < 4; c++) { + s = (s << 1 | s >>> 7) & 255; + x ^= s; + } + x ^= 99; + return x; + } + + // Tables + aes_sbox = [], aes_sinv = [], aes_enc = [[], [], [], []], aes_dec = [[], [], [], []]; + + for (var i = 0; i < 256; i++) { + var s = _s(i); + + // S-Box and its inverse + aes_sbox[i] = s; + aes_sinv[s] = i; + + // Ecryption and Decryption tables + aes_enc[0][i] = gmul(2, s) << 24 | s << 16 | s << 8 | gmul(3, s); + aes_dec[0][s] = gmul(14, i) << 24 | gmul(9, i) << 16 | gmul(13, i) << 8 | gmul(11, i); + // Rotate tables + for (var t = 1; t < 4; t++) { + aes_enc[t][i] = aes_enc[t - 1][i] >>> 8 | aes_enc[t - 1][i] << 24; + aes_dec[t][s] = aes_dec[t - 1][s] >>> 8 | aes_dec[t - 1][s] << 24; + } + } + } + + /** + * Asm.js module constructor. + * + *

+ * Heap buffer layout by offset: + *

+   * 0x0000   encryption key schedule
+   * 0x0400   decryption key schedule
+   * 0x0800   sbox
+   * 0x0c00   inv sbox
+   * 0x1000   encryption tables
+   * 0x2000   decryption tables
+   * 0x3000   reserved (future GCM multiplication lookup table)
+   * 0x4000   data
+   * 
+ * Don't touch anything before 0x400. + *

+ * + * @alias AES_asm + * @class + * @param {Object} foreign - ignored + * @param {ArrayBuffer} buffer - heap buffer to link with + */ + var wrapper = function wrapper(foreign, buffer) { + // Init AES stuff for the first time + if (!aes_init_done) aes_init(); + + // Fill up AES tables + var heap = new Uint32Array(buffer); + heap.set(aes_sbox, 0x0800 >> 2); + heap.set(aes_sinv, 0x0c00 >> 2); + for (var i = 0; i < 4; i++) { + heap.set(aes_enc[i], 0x1000 + 0x400 * i >> 2); + heap.set(aes_dec[i], 0x2000 + 0x400 * i >> 2); } /** - * Galois Field multiplication - * @param {int} a - * @param {int} b - * @return {int} + * Calculate AES key schedules. + * @instance + * @memberof AES_asm + * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) + * @param {number} k0 - key vector components + * @param {number} k1 - key vector components + * @param {number} k2 - key vector components + * @param {number} k3 - key vector components + * @param {number} k4 - key vector components + * @param {number} k5 - key vector components + * @param {number} k6 - key vector components + * @param {number} k7 - key vector components */ - function gmul ( a, b ) { - var c = gexp3[ ( glog3[a] + glog3[b] ) % 255 ]; - if ( a === 0 || b === 0 ) c = 0; - return c; + function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) { + var ekeys = heap.subarray(0x000, 60), + dkeys = heap.subarray(0x100, 0x100 + 60); + + // Encryption key schedule + ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]); + for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) { + var k = ekeys[i - 1]; + if (i % ks === 0 || ks === 8 && i % ks === 4) { + k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255]; + } + if (i % ks === 0) { + k = k << 8 ^ k >>> 24 ^ rcon << 24; + rcon = rcon << 1 ^ (rcon & 0x80 ? 0x1b : 0); + } + ekeys[i] = ekeys[i - ks] ^ k; + } + + // Decryption key schedule + for (var j = 0; j < i; j += 4) { + for (var jj = 0; jj < 4; jj++) { + var k = ekeys[i - (4 + j) + (4 - jj) % 4]; + if (j < 4 || j >= i - 4) { + dkeys[j + jj] = k; + } else { + dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] ^ aes_dec[3][aes_sbox[k & 255]]; + } + } + } + + // Set rounds number + asm.set_rounds(ks + 5); } - /** - * Galois Field reciprocal - * @param {int} a - * @return {int} - */ - function ginv ( a ) { - var i = gexp3[ 255 - glog3[a] ]; - if ( a === 0 ) i = 0; - return i; - } + // create library object with necessary properties + var stdlib = { Uint8Array: Uint8Array, Uint32Array: Uint32Array }; - /** - * AES stuff init flag - */ - var aes_init_done = false; + var asm = function (stdlib, foreign, buffer) { + "use asm"; - /** - * Encryption, Decryption, S-Box and KeyTransform tables - */ - var aes_sbox, aes_sinv, aes_enc, aes_dec; + var S0 = 0, + S1 = 0, + S2 = 0, + S3 = 0, + I0 = 0, + I1 = 0, + I2 = 0, + I3 = 0, + N0 = 0, + N1 = 0, + N2 = 0, + N3 = 0, + M0 = 0, + M1 = 0, + M2 = 0, + M3 = 0, + H0 = 0, + H1 = 0, + H2 = 0, + H3 = 0, + R = 0; - /** - * Init AES tables - */ - function aes_init () { - if ( !ginit_done ) ginit(); + var HEAP = new stdlib.Uint32Array(buffer), + DATA = new stdlib.Uint8Array(buffer); - // Calculates AES S-Box value - function _s ( a ) { - var c, s, x; - s = x = ginv(a); - for ( c = 0; c < 4; c++ ) { - s = ( (s << 1) | (s >>> 7) ) & 255; - x ^= s; - } - x ^= 99; - return x; + /** + * AES core + * @param {number} k - precomputed key schedule offset + * @param {number} s - precomputed sbox table offset + * @param {number} t - precomputed round table offset + * @param {number} r - number of inner rounds to perform + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _core(k, s, t, r, x0, x1, x2, x3) { + k = k | 0; + s = s | 0; + t = t | 0; + r = r | 0; + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + var t1 = 0, + t2 = 0, + t3 = 0, + y0 = 0, + y1 = 0, + y2 = 0, + y3 = 0, + i = 0; + + t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00; + + // round 0 + x0 = x0 ^ HEAP[(k | 0) >> 2], x1 = x1 ^ HEAP[(k | 4) >> 2], x2 = x2 ^ HEAP[(k | 8) >> 2], x3 = x3 ^ HEAP[(k | 12) >> 2]; + + // round 1..r + for (i = 16; (i | 0) <= r << 4; i = i + 16 | 0) { + 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], 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], 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], 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]; + x0 = y0, x1 = y1, x2 = y2, x3 = y3; } - // Tables - aes_sbox = [], - aes_sinv = [], - aes_enc = [ [], [], [], [] ], - aes_dec = [ [], [], [], [] ]; + // final round + 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], 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], 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], 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]; + } - for ( var i = 0; i < 256; i++ ) { - var s = _s(i); + /** + * ECB mode encryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _ecb_enc(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; - // S-Box and its inverse - aes_sbox[i] = s; - aes_sinv[s] = i; + _core(0x0000, 0x0800, 0x1000, R, x0, x1, x2, x3); + } - // Ecryption and Decryption tables - aes_enc[0][i] = ( gmul( 2, s ) << 24 ) | ( s << 16 ) | ( s << 8 ) | gmul( 3, s ); - aes_dec[0][s] = ( gmul( 14, i ) << 24 ) | ( gmul( 9, i ) << 16 ) | ( gmul( 13, i ) << 8 ) | gmul( 11, i ); - // Rotate tables - for ( var t = 1; t < 4; t++ ) { - aes_enc[t][i] = ( aes_enc[t-1][i] >>> 8 ) | ( aes_enc[t-1][i] << 24 ); - aes_dec[t][s] = ( aes_dec[t-1][s] >>> 8 ) | ( aes_dec[t-1][s] << 24 ); - } - } - } + /** + * ECB mode decryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _ecb_dec(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; - /** - * Asm.js module constructor. - * - *

- * Heap buffer layout by offset: - *

-     * 0x0000   encryption key schedule
-     * 0x0400   decryption key schedule
-     * 0x0800   sbox
-     * 0x0c00   inv sbox
-     * 0x1000   encryption tables
-     * 0x2000   decryption tables
-     * 0x3000   reserved (future GCM multiplication lookup table)
-     * 0x4000   data
-     * 
- * Don't touch anything before 0x400. - *

- * - * @alias AES_asm - * @class - * @param {GlobalScope} stdlib - global scope object (e.g. window) - * @param {Object} foreign - ignored - * @param {ArrayBuffer} buffer - heap buffer to link with - */ - var wrapper = function ( stdlib, foreign, buffer ) { - // Init AES stuff for the first time - if ( !aes_init_done ) aes_init(); + var t = 0; - // Fill up AES tables - var heap = new Uint32Array(buffer); - heap.set( aes_sbox, 0x0800>>2 ); - heap.set( aes_sinv, 0x0c00>>2 ); - for ( var i = 0; i < 4; i++ ) { - heap.set( aes_enc[i], ( 0x1000 + 0x400 * i )>>2 ); - heap.set( aes_dec[i], ( 0x2000 + 0x400 * i )>>2 ); + _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1); + + t = S1, S1 = S3, S3 = t; + } + + /** + * CBC mode encryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _cbc_enc(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + _core(0x0000, 0x0800, 0x1000, R, I0 ^ x0, I1 ^ x1, I2 ^ x2, I3 ^ x3); + + I0 = S0, I1 = S1, I2 = S2, I3 = S3; + } + + /** + * CBC mode decryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _cbc_dec(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + var t = 0; + + _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1); + + t = S1, S1 = S3, S3 = t; + + S0 = S0 ^ I0, S1 = S1 ^ I1, S2 = S2 ^ I2, S3 = S3 ^ I3; + + I0 = x0, I1 = x1, I2 = x2, I3 = x3; + } + + /** + * CFB mode encryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _cfb_enc(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3); + + I0 = S0 = S0 ^ x0, I1 = S1 = S1 ^ x1, I2 = S2 = S2 ^ x2, I3 = S3 = S3 ^ x3; + } + + /** + * CFB mode decryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _cfb_dec(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3); + + S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3; + + I0 = x0, I1 = x1, I2 = x2, I3 = x3; + } + + /** + * OFB mode encryption / decryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _ofb(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3); + + I0 = S0, I1 = S1, I2 = S2, I3 = S3; + + S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3; + } + + /** + * CTR mode encryption / decryption + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _ctr(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + _core(0x0000, 0x0800, 0x1000, R, N0, N1, N2, N3); + + N3 = ~M3 & N3 | M3 & N3 + 1; + N2 = ~M2 & N2 | M2 & N2 + ((N3 | 0) == 0); + N1 = ~M1 & N1 | M1 & N1 + ((N2 | 0) == 0); + N0 = ~M0 & N0 | M0 & N0 + ((N1 | 0) == 0); + + S0 = S0 ^ x0; + S1 = S1 ^ x1; + S2 = S2 ^ x2; + S3 = S3 ^ x3; + } + + /** + * GCM mode MAC calculation + * @param {number} x0 - 128-bit input block vector + * @param {number} x1 - 128-bit input block vector + * @param {number} x2 - 128-bit input block vector + * @param {number} x3 - 128-bit input block vector + */ + function _gcm_mac(x0, x1, x2, x3) { + x0 = x0 | 0; + x1 = x1 | 0; + x2 = x2 | 0; + x3 = x3 | 0; + + var y0 = 0, + y1 = 0, + y2 = 0, + y3 = 0, + z0 = 0, + z1 = 0, + z2 = 0, + z3 = 0, + i = 0, + c = 0; + + x0 = x0 ^ I0, x1 = x1 ^ I1, x2 = x2 ^ I2, x3 = x3 ^ I3; + + y0 = H0 | 0, y1 = H1 | 0, y2 = H2 | 0, y3 = H3 | 0; + + for (; (i | 0) < 128; i = i + 1 | 0) { + if (y0 >>> 31) { + z0 = z0 ^ x0, z1 = z1 ^ x1, z2 = z2 ^ x2, z3 = z3 ^ x3; + } + + y0 = y0 << 1 | y1 >>> 31, y1 = y1 << 1 | y2 >>> 31, y2 = y2 << 1 | y3 >>> 31, y3 = y3 << 1; + + c = x3 & 1; + + x3 = x3 >>> 1 | x2 << 31, x2 = x2 >>> 1 | x1 << 31, x1 = x1 >>> 1 | x0 << 31, x0 = x0 >>> 1; + + if (c) x0 = x0 ^ 0xe1000000; } - /** - * Calculate AES key schedules. - * @instance - * @memberof AES_asm - * @param {int} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly) - * @param {int} k0..k7 - key vector components - */ - function set_key ( ks, k0, k1, k2, k3, k4, k5, k6, k7 ) { - var ekeys = heap.subarray( 0x000, 60 ), - dkeys = heap.subarray( 0x100, 0x100+60 ); + I0 = z0, I1 = z1, I2 = z2, I3 = z3; + } - // Encryption key schedule - ekeys.set( [ k0, k1, k2, k3, k4, k5, k6, k7 ] ); - for ( var i = ks, rcon = 1; i < 4*ks+28; i++ ) { - var k = ekeys[i-1]; - if ( ( i % ks === 0 ) || ( ks === 8 && i % ks === 4 ) ) { - k = aes_sbox[k>>>24]<<24 ^ aes_sbox[k>>>16&255]<<16 ^ aes_sbox[k>>>8&255]<<8 ^ aes_sbox[k&255]; - } - if ( i % ks === 0 ) { - k = (k << 8) ^ (k >>> 24) ^ (rcon << 24); - rcon = (rcon << 1) ^ ( (rcon & 0x80) ? 0x1b : 0 ); - } - ekeys[i] = ekeys[i-ks] ^ k; - } + /** + * Set the internal rounds number. + * @instance + * @memberof AES_asm + * @param {number} r - number if inner AES rounds + */ + function set_rounds(r) { + r = r | 0; + R = r; + } - // Decryption key schedule - for ( var j = 0; j < i; j += 4 ) { - for ( var jj = 0; jj < 4; jj++ ) { - var k = ekeys[i-(4+j)+(4-jj)%4]; - if ( j < 4 || j >= i-4 ) { - dkeys[j+jj] = k; - } else { - dkeys[j+jj] = aes_dec[0][aes_sbox[k>>>24]] - ^ aes_dec[1][aes_sbox[k>>>16&255]] - ^ aes_dec[2][aes_sbox[k>>>8&255]] - ^ aes_dec[3][aes_sbox[k&255]]; - } - } - } + /** + * Populate the internal state of the module. + * @instance + * @memberof AES_asm + * @param {number} s0 - state vector + * @param {number} s1 - state vector + * @param {number} s2 - state vector + * @param {number} s3 - state vector + */ + function set_state(s0, s1, s2, s3) { + s0 = s0 | 0; + s1 = s1 | 0; + s2 = s2 | 0; + s3 = s3 | 0; - // Set rounds number - asm.set_rounds( ks + 5 ); + S0 = s0, S1 = s1, S2 = s2, S3 = s3; + } + + /** + * Populate the internal iv of the module. + * @instance + * @memberof AES_asm + * @param {number} i0 - iv vector + * @param {number} i1 - iv vector + * @param {number} i2 - iv vector + * @param {number} i3 - iv vector + */ + function set_iv(i0, i1, i2, i3) { + i0 = i0 | 0; + i1 = i1 | 0; + i2 = i2 | 0; + i3 = i3 | 0; + + I0 = i0, I1 = i1, I2 = i2, I3 = i3; + } + + /** + * Set nonce for CTR-family modes. + * @instance + * @memberof AES_asm + * @param {number} n0 - nonce vector + * @param {number} n1 - nonce vector + * @param {number} n2 - nonce vector + * @param {number} n3 - nonce vector + */ + function set_nonce(n0, n1, n2, n3) { + n0 = n0 | 0; + n1 = n1 | 0; + n2 = n2 | 0; + n3 = n3 | 0; + + N0 = n0, N1 = n1, N2 = n2, N3 = n3; + } + + /** + * Set counter mask for CTR-family modes. + * @instance + * @memberof AES_asm + * @param {number} m0 - counter mask vector + * @param {number} m1 - counter mask vector + * @param {number} m2 - counter mask vector + * @param {number} m3 - counter mask vector + */ + function set_mask(m0, m1, m2, m3) { + m0 = m0 | 0; + m1 = m1 | 0; + m2 = m2 | 0; + m3 = m3 | 0; + + M0 = m0, M1 = m1, M2 = m2, M3 = m3; + } + + /** + * Set counter for CTR-family modes. + * @instance + * @memberof AES_asm + * @param {number} c0 - counter vector + * @param {number} c1 - counter vector + * @param {number} c2 - counter vector + * @param {number} c3 - counter vector + */ + function set_counter(c0, c1, c2, c3) { + c0 = c0 | 0; + c1 = c1 | 0; + c2 = c2 | 0; + c3 = c3 | 0; + + N3 = ~M3 & N3 | M3 & c3, N2 = ~M2 & N2 | M2 & c2, N1 = ~M1 & N1 | M1 & c1, N0 = ~M0 & N0 | M0 & c0; + } + + /** + * Store the internal state vector into the heap. + * @instance + * @memberof AES_asm + * @param {number} pos - offset where to put the data + * @return {number} The number of bytes have been written into the heap, always 16. + */ + function get_state(pos) { + pos = pos | 0; + + if (pos & 15) return -1; + + DATA[pos | 0] = S0 >>> 24, DATA[pos | 1] = S0 >>> 16 & 255, DATA[pos | 2] = S0 >>> 8 & 255, DATA[pos | 3] = S0 & 255, DATA[pos | 4] = S1 >>> 24, DATA[pos | 5] = S1 >>> 16 & 255, DATA[pos | 6] = S1 >>> 8 & 255, DATA[pos | 7] = S1 & 255, DATA[pos | 8] = S2 >>> 24, DATA[pos | 9] = S2 >>> 16 & 255, DATA[pos | 10] = S2 >>> 8 & 255, DATA[pos | 11] = S2 & 255, DATA[pos | 12] = S3 >>> 24, DATA[pos | 13] = S3 >>> 16 & 255, DATA[pos | 14] = S3 >>> 8 & 255, DATA[pos | 15] = S3 & 255; + + return 16; + } + + /** + * Store the internal iv vector into the heap. + * @instance + * @memberof AES_asm + * @param {number} pos - offset where to put the data + * @return {number} The number of bytes have been written into the heap, always 16. + */ + function get_iv(pos) { + pos = pos | 0; + + if (pos & 15) return -1; + + DATA[pos | 0] = I0 >>> 24, DATA[pos | 1] = I0 >>> 16 & 255, DATA[pos | 2] = I0 >>> 8 & 255, DATA[pos | 3] = I0 & 255, DATA[pos | 4] = I1 >>> 24, DATA[pos | 5] = I1 >>> 16 & 255, DATA[pos | 6] = I1 >>> 8 & 255, DATA[pos | 7] = I1 & 255, DATA[pos | 8] = I2 >>> 24, DATA[pos | 9] = I2 >>> 16 & 255, DATA[pos | 10] = I2 >>> 8 & 255, DATA[pos | 11] = I2 & 255, DATA[pos | 12] = I3 >>> 24, DATA[pos | 13] = I3 >>> 16 & 255, DATA[pos | 14] = I3 >>> 8 & 255, DATA[pos | 15] = I3 & 255; + + return 16; + } + + /** + * GCM initialization. + * @instance + * @memberof AES_asm + */ + function gcm_init() { + _ecb_enc(0, 0, 0, 0); + H0 = S0, H1 = S1, H2 = S2, H3 = S3; + } + + /** + * Perform ciphering operation on the supplied data. + * @instance + * @memberof AES_asm + * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) + * @param {number} pos - offset of the data being processed + * @param {number} len - length of the data being processed + * @return {number} Actual amount of data have been processed. + */ + function cipher(mode, pos, len) { + mode = mode | 0; + pos = pos | 0; + len = len | 0; + + var ret = 0; + + if (pos & 15) return -1; + + while ((len | 0) >= 16) { + _cipher_modes[mode & 7](DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]); + + DATA[pos | 0] = S0 >>> 24, DATA[pos | 1] = S0 >>> 16 & 255, DATA[pos | 2] = S0 >>> 8 & 255, DATA[pos | 3] = S0 & 255, DATA[pos | 4] = S1 >>> 24, DATA[pos | 5] = S1 >>> 16 & 255, DATA[pos | 6] = S1 >>> 8 & 255, DATA[pos | 7] = S1 & 255, DATA[pos | 8] = S2 >>> 24, DATA[pos | 9] = S2 >>> 16 & 255, DATA[pos | 10] = S2 >>> 8 & 255, DATA[pos | 11] = S2 & 255, DATA[pos | 12] = S3 >>> 24, DATA[pos | 13] = S3 >>> 16 & 255, DATA[pos | 14] = S3 >>> 8 & 255, DATA[pos | 15] = S3 & 255; + + ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0; } - var asm = function ( stdlib, foreign, buffer ) { - "use asm"; - - var S0 = 0, S1 = 0, S2 = 0, S3 = 0, - I0 = 0, I1 = 0, I2 = 0, I3 = 0, - N0 = 0, N1 = 0, N2 = 0, N3 = 0, - M0 = 0, M1 = 0, M2 = 0, M3 = 0, - H0 = 0, H1 = 0, H2 = 0, H3 = 0, - R = 0; - - var HEAP = new stdlib.Uint32Array(buffer), - DATA = new stdlib.Uint8Array(buffer); - - /** - * AES core - * @param {int} k - precomputed key schedule offset - * @param {int} s - precomputed sbox table offset - * @param {int} t - precomputed round table offset - * @param {int} r - number of inner rounds to perform - * @param {int} x0..x3 - 128-bit input block vector - */ - function _core ( k, s, t, r, x0, x1, x2, x3 ) { - k = k|0; - s = s|0; - t = t|0; - r = r|0; - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - var t1 = 0, t2 = 0, t3 = 0, - y0 = 0, y1 = 0, y2 = 0, y3 = 0, - i = 0; - - t1 = t|0x400, t2 = t|0x800, t3 = t|0xc00; - - // round 0 - x0 = x0 ^ HEAP[(k|0)>>2], - x1 = x1 ^ HEAP[(k|4)>>2], - x2 = x2 ^ HEAP[(k|8)>>2], - x3 = x3 ^ HEAP[(k|12)>>2]; - - // round 1..r - for ( i = 16; (i|0) <= (r<<4); i = (i+16)|0 ) { - 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], - 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], - 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], - 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]; - x0 = y0, x1 = y1, x2 = y2, x3 = y3; - } - - // final round - 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], - 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], - 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], - 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]; - } - - /** - * ECB mode encryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _ecb_enc ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - x0, - x1, - x2, - x3 - ); - } - - /** - * ECB mode decryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _ecb_dec ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - } - - - /** - * CBC mode encryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _cbc_enc ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0 ^ x0, - I1 ^ x1, - I2 ^ x2, - I3 ^ x3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - } - - /** - * CBC mode decryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _cbc_dec ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - var t = 0; - - _core( - 0x0400, 0x0c00, 0x2000, - R, - x0, - x3, - x2, - x1 - ); - - t = S1, S1 = S3, S3 = t; - - S0 = S0 ^ I0, - S1 = S1 ^ I1, - S2 = S2 ^ I2, - S3 = S3 ^ I3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * CFB mode encryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _cfb_enc ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0 = S0 ^ x0, - I1 = S1 = S1 ^ x1, - I2 = S2 = S2 ^ x2, - I3 = S3 = S3 ^ x3; - } - - - /** - * CFB mode decryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _cfb_dec ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - - I0 = x0, - I1 = x1, - I2 = x2, - I3 = x3; - } - - /** - * OFB mode encryption / decryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _ofb ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - I0, - I1, - I2, - I3 - ); - - I0 = S0, - I1 = S1, - I2 = S2, - I3 = S3; - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * CTR mode encryption / decryption - * @param {int} x0..x3 - 128-bit input block vector - */ - function _ctr ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - _core( - 0x0000, 0x0800, 0x1000, - R, - N0, - N1, - N2, - N3 - ); - - N3 = ( ~M3 & N3 ) | M3 & ( N3 + 1 ), - N2 = ( ~M2 & N2 ) | M2 & ( N2 + ( (N3|0) == 0 ) ), - N1 = ( ~M1 & N1 ) | M1 & ( N1 + ( (N2|0) == 0 ) ), - N0 = ( ~M0 & N0 ) | M0 & ( N0 + ( (N1|0) == 0 ) ); - - S0 = S0 ^ x0, - S1 = S1 ^ x1, - S2 = S2 ^ x2, - S3 = S3 ^ x3; - } - - /** - * GCM mode MAC calculation - * @param {int} x0..x3 - 128-bit input block vector - */ - function _gcm_mac ( x0, x1, x2, x3 ) { - x0 = x0|0; - x1 = x1|0; - x2 = x2|0; - x3 = x3|0; - - var y0 = 0, y1 = 0, y2 = 0, y3 = 0, - z0 = 0, z1 = 0, z2 = 0, z3 = 0, - i = 0, c = 0; - - x0 = x0 ^ I0, - x1 = x1 ^ I1, - x2 = x2 ^ I2, - x3 = x3 ^ I3; - - y0 = H0|0, - y1 = H1|0, - y2 = H2|0, - y3 = H3|0; - - for ( ; (i|0) < 128; i = (i + 1)|0 ) { - if ( y0 >>> 31 ) { - z0 = z0 ^ x0, - z1 = z1 ^ x1, - z2 = z2 ^ x2, - z3 = z3 ^ x3; - } - - y0 = (y0 << 1) | (y1 >>> 31), - y1 = (y1 << 1) | (y2 >>> 31), - y2 = (y2 << 1) | (y3 >>> 31), - y3 = (y3 << 1); - - c = x3 & 1; - - x3 = (x3 >>> 1) | (x2 << 31), - x2 = (x2 >>> 1) | (x1 << 31), - x1 = (x1 >>> 1) | (x0 << 31), - x0 = (x0 >>> 1); - - if ( c ) x0 = x0 ^ 0xe1000000; - } - - I0 = z0, - I1 = z1, - I2 = z2, - I3 = z3; - } - - /** - * Set the internal rounds number. - * @instance - * @memberof AES_asm - * @param {int} r - number if inner AES rounds - */ - function set_rounds ( r ) { - r = r|0; - R = r; - } - - /** - * Populate the internal state of the module. - * @instance - * @memberof AES_asm - * @param {int} s0...s3 - state vector - */ - function set_state ( s0, s1, s2, s3 ) { - s0 = s0|0; - s1 = s1|0; - s2 = s2|0; - s3 = s3|0; - - S0 = s0, - S1 = s1, - S2 = s2, - S3 = s3; - } - - /** - * Populate the internal iv of the module. - * @instance - * @memberof AES_asm - * @param {int} i0...i3 - iv vector - */ - function set_iv ( i0, i1, i2, i3 ) { - i0 = i0|0; - i1 = i1|0; - i2 = i2|0; - i3 = i3|0; - - I0 = i0, - I1 = i1, - I2 = i2, - I3 = i3; - } - - /** - * Set nonce for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {int} n0..n3 - nonce vector - */ - function set_nonce ( n0, n1, n2, n3 ) { - n0 = n0|0; - n1 = n1|0; - n2 = n2|0; - n3 = n3|0; - - N0 = n0, - N1 = n1, - N2 = n2, - N3 = n3; - } - - /** - * Set counter mask for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {int} m0...m3 - counter mask vector - */ - function set_mask ( m0, m1, m2, m3 ) { - m0 = m0|0; - m1 = m1|0; - m2 = m2|0; - m3 = m3|0; - - M0 = m0, - M1 = m1, - M2 = m2, - M3 = m3; - } - - /** - * Set counter for CTR-family modes. - * @instance - * @memberof AES_asm - * @param {int} c0...c3 - counter vector - */ - function set_counter ( c0, c1, c2, c3 ) { - c0 = c0|0; - c1 = c1|0; - c2 = c2|0; - c3 = c3|0; - - N3 = ( ~M3 & N3 ) | M3 & c3, - N2 = ( ~M2 & N2 ) | M2 & c2, - N1 = ( ~M1 & N1 ) | M1 & c1, - N0 = ( ~M0 & N0 ) | M0 & c0; - } - - /** - * Store the internal state vector into the heap. - * @instance - * @memberof AES_asm - * @param {int} pos - offset where to put the data - * @return {int} The number of bytes have been written into the heap, always 16. - */ - function get_state ( pos ) { - pos = pos|0; - - if ( pos & 15 ) return -1; - - DATA[pos|0] = S0>>>24, - DATA[pos|1] = S0>>>16&255, - DATA[pos|2] = S0>>>8&255, - DATA[pos|3] = S0&255, - DATA[pos|4] = S1>>>24, - DATA[pos|5] = S1>>>16&255, - DATA[pos|6] = S1>>>8&255, - DATA[pos|7] = S1&255, - DATA[pos|8] = S2>>>24, - DATA[pos|9] = S2>>>16&255, - DATA[pos|10] = S2>>>8&255, - DATA[pos|11] = S2&255, - DATA[pos|12] = S3>>>24, - DATA[pos|13] = S3>>>16&255, - DATA[pos|14] = S3>>>8&255, - DATA[pos|15] = S3&255; - - return 16; - } - - /** - * Store the internal iv vector into the heap. - * @instance - * @memberof AES_asm - * @param {int} pos - offset where to put the data - * @return {int} The number of bytes have been written into the heap, always 16. - */ - function get_iv ( pos ) { - pos = pos|0; - - if ( pos & 15 ) return -1; - - DATA[pos|0] = I0>>>24, - DATA[pos|1] = I0>>>16&255, - DATA[pos|2] = I0>>>8&255, - DATA[pos|3] = I0&255, - DATA[pos|4] = I1>>>24, - DATA[pos|5] = I1>>>16&255, - DATA[pos|6] = I1>>>8&255, - DATA[pos|7] = I1&255, - DATA[pos|8] = I2>>>24, - DATA[pos|9] = I2>>>16&255, - DATA[pos|10] = I2>>>8&255, - DATA[pos|11] = I2&255, - DATA[pos|12] = I3>>>24, - DATA[pos|13] = I3>>>16&255, - DATA[pos|14] = I3>>>8&255, - DATA[pos|15] = I3&255; - - return 16; - } - - /** - * GCM initialization. - * @instance - * @memberof AES_asm - */ - function gcm_init ( ) { - _ecb_enc( 0, 0, 0, 0 ); - H0 = S0, - H1 = S1, - H2 = S2, - H3 = S3; - } - - /** - * Perform ciphering operation on the supplied data. - * @instance - * @memberof AES_asm - * @param {int} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {int} pos - offset of the data being processed - * @param {int} len - length of the data being processed - * @return {int} Actual amount of data have been processed. - */ - function cipher ( mode, pos, len ) { - mode = mode|0; - pos = pos|0; - len = len|0; - - var ret = 0; - - if ( pos & 15 ) return -1; - - while ( (len|0) >= 16 ) { - _cipher_modes[mode&7]( - DATA[pos|0]<<24 | DATA[pos|1]<<16 | DATA[pos|2]<<8 | DATA[pos|3], - DATA[pos|4]<<24 | DATA[pos|5]<<16 | DATA[pos|6]<<8 | DATA[pos|7], - DATA[pos|8]<<24 | DATA[pos|9]<<16 | DATA[pos|10]<<8 | DATA[pos|11], - DATA[pos|12]<<24 | DATA[pos|13]<<16 | DATA[pos|14]<<8 | DATA[pos|15] - ); - - DATA[pos|0] = S0>>>24, - DATA[pos|1] = S0>>>16&255, - DATA[pos|2] = S0>>>8&255, - DATA[pos|3] = S0&255, - DATA[pos|4] = S1>>>24, - DATA[pos|5] = S1>>>16&255, - DATA[pos|6] = S1>>>8&255, - DATA[pos|7] = S1&255, - DATA[pos|8] = S2>>>24, - DATA[pos|9] = S2>>>16&255, - DATA[pos|10] = S2>>>8&255, - DATA[pos|11] = S2&255, - DATA[pos|12] = S3>>>24, - DATA[pos|13] = S3>>>16&255, - DATA[pos|14] = S3>>>8&255, - DATA[pos|15] = S3&255; - - ret = (ret + 16)|0, - pos = (pos + 16)|0, - len = (len - 16)|0; - } - - return ret|0; - } - - /** - * Calculates MAC of the supplied data. - * @instance - * @memberof AES_asm - * @param {int} mode - block cipher mode (see {@link AES_asm} mode constants) - * @param {int} pos - offset of the data being processed - * @param {int} len - length of the data being processed - * @return {int} Actual amount of data have been processed. - */ - function mac ( mode, pos, len ) { - mode = mode|0; - pos = pos|0; - len = len|0; - - var ret = 0; - - if ( pos & 15 ) return -1; - - while ( (len|0) >= 16 ) { - _mac_modes[mode&1]( - DATA[pos|0]<<24 | DATA[pos|1]<<16 | DATA[pos|2]<<8 | DATA[pos|3], - DATA[pos|4]<<24 | DATA[pos|5]<<16 | DATA[pos|6]<<8 | DATA[pos|7], - DATA[pos|8]<<24 | DATA[pos|9]<<16 | DATA[pos|10]<<8 | DATA[pos|11], - DATA[pos|12]<<24 | DATA[pos|13]<<16 | DATA[pos|14]<<8 | DATA[pos|15] - ); - - ret = (ret + 16)|0, - pos = (pos + 16)|0, - len = (len - 16)|0; - } - - return ret|0; - } - - /** - * AES cipher modes table (virual methods) - */ - var _cipher_modes = [ _ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr ]; - - /** - * AES MAC modes table (virual methods) - */ - var _mac_modes = [ _cbc_enc, _gcm_mac ]; - - /** - * Asm.js module exports - */ - return { - set_rounds: set_rounds, - set_state: set_state, - set_iv: set_iv, - set_nonce: set_nonce, - set_mask: set_mask, - set_counter:set_counter, - get_state: get_state, - get_iv: get_iv, - gcm_init: gcm_init, - cipher: cipher, - mac: mac - }; - }( stdlib, foreign, buffer ); - - asm.set_key = set_key; - - return asm; - }; - - /** - * AES enciphering mode constants - * @enum {int} - * @const - */ - wrapper.ENC = { - ECB: 0, - CBC: 2, - CFB: 4, - OFB: 6, - CTR: 7 - }, - - /** - * AES deciphering mode constants - * @enum {int} - * @const - */ - wrapper.DEC = { - ECB: 1, - CBC: 3, - CFB: 5, - OFB: 6, - CTR: 7 - }, - - /** - * AES MAC mode constants - * @enum {int} - * @const - */ - wrapper.MAC = { - CBC: 0, - GCM: 1 - }; - - /** - * Heap data offset - * @type {int} - * @const - */ - wrapper.HEAP_DATA = 0x4000; - - return wrapper; + return ret | 0; + } + + /** + * Calculates MAC of the supplied data. + * @instance + * @memberof AES_asm + * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants) + * @param {number} pos - offset of the data being processed + * @param {number} len - length of the data being processed + * @return {number} Actual amount of data have been processed. + */ + function mac(mode, pos, len) { + mode = mode | 0; + pos = pos | 0; + len = len | 0; + + var ret = 0; + + if (pos & 15) return -1; + + while ((len | 0) >= 16) { + _mac_modes[mode & 1](DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]); + + ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0; + } + + return ret | 0; + } + + /** + * AES cipher modes table (virual methods) + */ + var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr]; + + /** + * AES MAC modes table (virual methods) + */ + var _mac_modes = [_cbc_enc, _gcm_mac]; + + /** + * Asm.js module exports + */ + return { + set_rounds: set_rounds, + set_state: set_state, + set_iv: set_iv, + set_nonce: set_nonce, + set_mask: set_mask, + set_counter: set_counter, + get_state: get_state, + get_iv: get_iv, + gcm_init: gcm_init, + cipher: cipher, + mac: mac + }; + }(stdlib, foreign, buffer); + + asm.set_key = set_key; + + return asm; + }; + + /** + * AES enciphering mode constants + * @enum {number} + * @const + */ + wrapper.ENC = { + ECB: 0, + CBC: 2, + CFB: 4, + OFB: 6, + CTR: 7 + }, + + /** + * AES deciphering mode constants + * @enum {number} + * @const + */ + wrapper.DEC = { + ECB: 1, + CBC: 3, + CFB: 5, + OFB: 6, + CTR: 7 + }, + + /** + * AES MAC mode constants + * @enum {number} + * @const + */ + wrapper.MAC = { + CBC: 0, + GCM: 1 + }; + + /** + * Heap data offset + * @type {number} + * @const + */ + wrapper.HEAP_DATA = 0x4000; + + return wrapper; }(); -function AES ( options ) { - options = options || {}; +},{}],2:[function(_dereq_,module,exports){ +'use strict'; - this.heap = _heap_init( Uint8Array, options ).subarray( AES_asm.HEAP_DATA ); - this.asm = options.asm || AES_asm( global, null, this.heap.buffer ); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES = undefined; + +var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +var _aes = _dereq_('./aes.asm'); + +var _utils = _dereq_('../utils'); + +var _errors = _dereq_('../errors'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var AES = exports.AES = function () { + function AES(key, iv, padding, heap, asm) { + (0, _classCallCheck3.default)(this, AES); + + this.nonce = null; + this.counter = 0; + this.counterSize = 0; + + this.heap = (0, _utils._heap_init)(Uint8Array, heap).subarray(_aes.AES_asm.HEAP_DATA); + this.asm = asm || (0, _aes.AES_asm)(null, this.heap.buffer); this.mode = null; this.key = null; - this.reset( options ); -} + this.AES_reset(key, iv, padding); + } -function AES_set_key ( key ) { - if ( key !== undefined ) { - if ( is_buffer(key) || is_bytes(key) ) { - key = new Uint8Array(key); - } - else if ( is_string(key) ) { - key = string_to_bytes(key); - } - else { - throw new TypeError("unexpected key type"); + /** + * @param {Uint8Array} key + */ + + + (0, _createClass3.default)(AES, [{ + key: 'AES_set_key', + value: function AES_set_key(key) { + if (key !== undefined) { + if (!(0, _utils.is_bytes)(key)) { + throw new TypeError('unexpected key type'); } var keylen = key.length; - if ( keylen !== 16 && keylen !== 24 && keylen !== 32 ) - throw new IllegalArgumentError("illegal key size"); + if (keylen !== 16 && keylen !== 24 && keylen !== 32) throw new _errors.IllegalArgumentError('illegal key size'); - var keyview = new DataView( key.buffer, key.byteOffset, key.byteLength ); - this.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 - ); + var keyview = new DataView(key.buffer, key.byteOffset, key.byteLength); + this.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); this.key = key; - } - else if ( !this.key ) { - throw new Error("key is required"); - } -} - -function AES_set_iv ( iv ) { - if ( iv !== undefined ) { - if ( is_buffer(iv) || is_bytes(iv) ) { - iv = new Uint8Array(iv); - } - else if ( is_string(iv) ) { - iv = string_to_bytes(iv); - } - else { - throw new TypeError("unexpected iv type"); - } - - if ( iv.length !== 16 ) - throw new IllegalArgumentError("illegal iv size"); - - var ivview = new DataView( iv.buffer, iv.byteOffset, iv.byteLength ); - - this.iv = iv; - this.asm.set_iv( ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12) ); - } - else { - this.iv = null; - this.asm.set_iv( 0, 0, 0, 0 ); - } -} - -function AES_set_padding ( padding ) { - if ( padding !== undefined ) { - this.padding = !!padding; - } - else { - this.padding = true; - } -} - -function AES_reset ( options ) { - options = options || {}; - - this.result = null; - this.pos = 0; - this.len = 0; - - AES_set_key.call( this, options.key ); - if ( this.hasOwnProperty('iv') ) AES_set_iv.call( this, options.iv ); - if ( this.hasOwnProperty('padding') ) AES_set_padding.call( this, options.padding ); - - return this; -} - -function AES_Encrypt_process ( data ) { - if ( is_string(data) ) - data = string_to_bytes(data); - - if ( is_buffer(data) ) - data = new Uint8Array(data); - - if ( !is_bytes(data) ) - throw new TypeError("data isn't of expected type"); - - var asm = this.asm, - heap = this.heap, - amode = AES_asm.ENC[this.mode], - hpos = AES_asm.HEAP_DATA, - pos = this.pos, - len = this.len, - dpos = 0, - dlen = data.length || 0, - rpos = 0, - rlen = (len + dlen) & -16, - wlen = 0; - - var result = new Uint8Array(rlen); - - while ( dlen > 0 ) { - wlen = _heap_write( heap, pos+len, data, dpos, dlen ); - len += wlen; - dpos += wlen; - dlen -= wlen; - - wlen = asm.cipher( amode, hpos + pos, len ); - - if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos ); - rpos += wlen; - - if ( wlen < len ) { - pos += wlen; - len -= wlen; - } else { - pos = 0; - len = 0; - } + } else if (!this.key) { + throw new Error('key is required'); + } } - this.result = result; - this.pos = pos; - this.len = len; + /** + * This should be mixin instead of inheritance + * + * @param {Uint8Array} nonce + * @param {number} [counter] + * @param {number} [size] + */ - return this; -} - -function AES_Encrypt_finish ( data ) { - var presult = null, - prlen = 0; - - if ( data !== undefined ) { - presult = AES_Encrypt_process.call( this, data ).result; - prlen = presult.length; - } - - var asm = this.asm, - heap = this.heap, - amode = AES_asm.ENC[this.mode], - hpos = AES_asm.HEAP_DATA, - pos = this.pos, - len = this.len, - plen = 16 - len % 16, - rlen = len; - - if ( this.hasOwnProperty('padding') ) { - if ( this.padding ) { - for ( var p = 0; p < plen; ++p ) heap[ pos + len + p ] = plen; - len += plen; - rlen = len; - } - else if ( len % 16 ) { - throw new IllegalArgumentError("data length must be a multiple of the block size"); - } - } - else { - len += plen; - } - - var result = new Uint8Array( prlen + rlen ); - - if ( prlen ) result.set( presult ); - - if ( len ) asm.cipher( amode, hpos + pos, len ); - - if ( rlen ) result.set( heap.subarray( pos, pos + rlen ), prlen ); - - this.result = result; - this.pos = 0; - this.len = 0; - - return this; -} - -function AES_Decrypt_process ( data ) { - if ( is_string(data) ) - data = string_to_bytes(data); - - if ( is_buffer(data) ) - data = new Uint8Array(data); - - if ( !is_bytes(data) ) - throw new TypeError("data isn't of expected type"); - - var asm = this.asm, - heap = this.heap, - amode = AES_asm.DEC[this.mode], - hpos = AES_asm.HEAP_DATA, - pos = this.pos, - len = this.len, - dpos = 0, - dlen = data.length || 0, - rpos = 0, - rlen = (len + dlen) & -16, - plen = 0, - wlen = 0; - - if ( this.hasOwnProperty('padding') && this.padding ) { - plen = len + dlen - rlen || 16; - rlen -= plen; - } - - var result = new Uint8Array(rlen); - - while ( dlen > 0 ) { - wlen = _heap_write( heap, pos+len, data, dpos, dlen ); - len += wlen; - dpos += wlen; - dlen -= wlen; - - wlen = asm.cipher( amode, hpos + pos, len - ( !dlen ? plen : 0 ) ); - - if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos ); - rpos += wlen; - - if ( wlen < len ) { - pos += wlen; - len -= wlen; - } else { - pos = 0; - len = 0; - } - } - - this.result = result; - this.pos = pos; - this.len = len; - - return this; -} - -function AES_Decrypt_finish ( data ) { - var presult = null, - prlen = 0; - - if ( data !== undefined ) { - presult = AES_Decrypt_process.call( this, data ).result; - prlen = presult.length; - } - - var asm = this.asm, - heap = this.heap, - amode = AES_asm.DEC[this.mode], - hpos = AES_asm.HEAP_DATA, - pos = this.pos, - len = this.len, - rlen = len; - - if ( len > 0 ) { - if ( len % 16 ) { - if ( this.hasOwnProperty('padding') ) { - throw new IllegalArgumentError("data length must be a multiple of the block size"); - } else { - len += 16 - len % 16; - } - } - - asm.cipher( amode, hpos + pos, len ); - - if ( this.hasOwnProperty('padding') && this.padding ) { - var pad = heap[ pos + rlen - 1 ]; - if ( pad < 1 || pad > 16 || pad > rlen ) - throw new SecurityError("bad padding"); - - var pcheck = 0; - for ( var i = pad; i > 1; i-- ) pcheck |= pad ^ heap[ pos + rlen - i ]; - if ( pcheck ) - throw new SecurityError("bad padding"); - - rlen -= pad; - } - } - - var result = new Uint8Array( prlen + rlen ); - - if ( prlen > 0 ) { - result.set( presult ); - } - - if ( rlen > 0 ) { - result.set( heap.subarray( pos, pos + rlen ), prlen ); - } - - this.result = result; - this.pos = 0; - this.len = 0; - - return this; -} - -/** - * Cipher Feedback Mode (CFB) - */ - -function AES_CFB ( options ) { - this.iv = null; - - AES.call( this, options ); - - this.mode = 'CFB'; -} - -var AES_CFB_prototype = AES_CFB.prototype; -AES_CFB_prototype.BLOCK_SIZE = 16; -AES_CFB_prototype.reset = AES_reset; -AES_CFB_prototype.encrypt = AES_Encrypt_finish; -AES_CFB_prototype.decrypt = AES_Decrypt_finish; - -function AES_CFB_Encrypt ( options ) { - AES_CFB.call( this, options ); -} - -var AES_CFB_Encrypt_prototype = AES_CFB_Encrypt.prototype; -AES_CFB_Encrypt_prototype.BLOCK_SIZE = 16; -AES_CFB_Encrypt_prototype.reset = AES_reset; -AES_CFB_Encrypt_prototype.process = AES_Encrypt_process; -AES_CFB_Encrypt_prototype.finish = AES_Encrypt_finish; - -function AES_CFB_Decrypt ( options ) { - AES_CFB.call( this, options ); -} - -var AES_CFB_Decrypt_prototype = AES_CFB_Decrypt.prototype; -AES_CFB_Decrypt_prototype.BLOCK_SIZE = 16; -AES_CFB_Decrypt_prototype.reset = AES_reset; -AES_CFB_Decrypt_prototype.process = AES_Decrypt_process; -AES_CFB_Decrypt_prototype.finish = AES_Decrypt_finish; - -/** - * Counter Mode (CTR) - */ - -function AES_CTR ( options ) { - this.nonce = null, - this.counter = 0, - this.counterSize = 0; - - AES.call( this, options ); - - this.mode = 'CTR'; -} - -function AES_CTR_Crypt ( options ) { - AES_CTR.call( this, options ); -} - -function AES_CTR_set_options ( nonce, counter, size ) { - if ( size !== undefined ) { - if ( size < 8 || size > 48 ) - throw new IllegalArgumentError("illegal counter size"); + }, { + key: 'AES_CTR_set_options', + value: function AES_CTR_set_options(nonce, counter, size) { + if (size !== undefined) { + if (size < 8 || size > 48) throw new _errors.IllegalArgumentError('illegal counter size'); this.counterSize = size; - var mask = Math.pow( 2, size ) - 1; - this.asm.set_mask( 0, 0, (mask / 0x100000000)|0, mask|0 ); - } - else { + var mask = Math.pow(2, size) - 1; + this.asm.set_mask(0, 0, mask / 0x100000000 | 0, mask | 0); + } else { this.counterSize = size = 48; - this.asm.set_mask( 0, 0, 0xffff, 0xffffffff ); - } + this.asm.set_mask(0, 0, 0xffff, 0xffffffff); + } - if ( nonce !== undefined ) { - if ( is_buffer(nonce) || is_bytes(nonce) ) { - nonce = new Uint8Array(nonce); - } - else if ( is_string(nonce) ) { - nonce = string_to_bytes(nonce); - } - else { - throw new TypeError("unexpected nonce type"); + if (nonce !== undefined) { + if (!(0, _utils.is_bytes)(nonce)) { + throw new TypeError('unexpected nonce type'); } var len = nonce.length; - if ( !len || len > 16 ) - throw new IllegalArgumentError("illegal nonce size"); + if (!len || len > 16) throw new _errors.IllegalArgumentError('illegal nonce size'); this.nonce = nonce; - var view = new DataView( new ArrayBuffer(16) ); + var view = new DataView(new ArrayBuffer(16)); new Uint8Array(view.buffer).set(nonce); - this.asm.set_nonce( view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12) ); - } - else { - throw new Error("nonce is required"); - } + this.asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)); + } else { + throw new Error('nonce is required'); + } - if ( counter !== undefined ) { - if ( !is_number(counter) ) - throw new TypeError("unexpected counter type"); + if (counter !== undefined) { + if (!(0, _utils.is_number)(counter)) throw new TypeError('unexpected counter type'); - if ( counter < 0 || counter >= Math.pow( 2, size ) ) - throw new IllegalArgumentError("illegal counter value"); + if (counter < 0 || counter >= Math.pow(2, size)) throw new _errors.IllegalArgumentError('illegal counter value'); this.counter = counter; - this.asm.set_counter( 0, 0, (counter / 0x100000000)|0, counter|0 ); + this.asm.set_counter(0, 0, counter / 0x100000000 | 0, counter | 0); + } else { + this.counter = 0; + } } - else { - this.counter = counter = 0; + + /** + * @param {Uint8Array} iv + */ + + }, { + key: 'AES_set_iv', + value: function AES_set_iv(iv) { + if (iv !== undefined) { + if (!(0, _utils.is_bytes)(iv)) { + throw new TypeError('unexpected iv type'); + } + + if (iv.length !== 16) throw new _errors.IllegalArgumentError('illegal iv size'); + + var ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength); + + this.iv = iv; + this.asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); + } else { + this.iv = null; + this.asm.set_iv(0, 0, 0, 0); + } } + + /** + * @param {boolean} padding + */ + + }, { + key: 'AES_set_padding', + value: function AES_set_padding(padding) { + if (padding !== undefined) { + this.padding = !!padding; + } else { + this.padding = true; + } + } + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @param {boolean} [padding] + */ + + }, { + key: 'AES_reset', + value: function AES_reset(key, iv, padding) { + this.result = null; + this.pos = 0; + this.len = 0; + + this.AES_set_key(key); + this.AES_set_iv(iv); + this.AES_set_padding(padding); + + return this; + } + + /** + * @param {Uint8Array} data + */ + + }, { + key: 'AES_Encrypt_process', + value: function AES_Encrypt_process(data) { + if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type"); + + var asm = this.asm, + heap = this.heap, + amode = _aes.AES_asm.ENC[this.mode], + hpos = _aes.AES_asm.HEAP_DATA, + pos = this.pos, + len = this.len, + dpos = 0, + dlen = data.length || 0, + rpos = 0, + rlen = len + dlen & -16, + wlen = 0; + + var result = new Uint8Array(rlen); + + while (dlen > 0) { + wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen); + len += wlen; + dpos += wlen; + dlen -= wlen; + + wlen = asm.cipher(amode, hpos + pos, len); + + if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos); + rpos += wlen; + + if (wlen < len) { + pos += wlen; + len -= wlen; + } else { + pos = 0; + len = 0; + } + } + + this.result = result; + this.pos = pos; + this.len = len; + + return this; + } + + /** + * @param {Uint8Array} data + */ + + }, { + key: 'AES_Encrypt_finish', + value: function AES_Encrypt_finish(data) { + var presult = null, + prlen = 0; + + if (data !== undefined) { + presult = this.AES_Encrypt_process(data).result; + prlen = presult.length; + } + + var asm = this.asm, + heap = this.heap, + amode = _aes.AES_asm.ENC[this.mode], + hpos = _aes.AES_asm.HEAP_DATA, + pos = this.pos, + len = this.len, + plen = 16 - len % 16, + rlen = len; + + if (this.hasOwnProperty('padding')) { + if (this.padding) { + for (var p = 0; p < plen; ++p) { + heap[pos + len + p] = plen; + }len += plen; + rlen = len; + } else if (len % 16) { + throw new _errors.IllegalArgumentError('data length must be a multiple of the block size'); + } + } else { + len += plen; + } + + var result = new Uint8Array(prlen + rlen); + + if (prlen) result.set(presult); + + if (len) asm.cipher(amode, hpos + pos, len); + + if (rlen) result.set(heap.subarray(pos, pos + rlen), prlen); + + this.result = result; + this.pos = 0; + this.len = 0; + + return this; + } + + /** + * @param {Uint8Array} data + */ + + }, { + key: 'AES_Decrypt_process', + value: function AES_Decrypt_process(data) { + if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type"); + + var asm = this.asm, + heap = this.heap, + amode = _aes.AES_asm.DEC[this.mode], + hpos = _aes.AES_asm.HEAP_DATA, + pos = this.pos, + len = this.len, + dpos = 0, + dlen = data.length || 0, + rpos = 0, + rlen = len + dlen & -16, + plen = 0, + wlen = 0; + + if (this.padding) { + plen = len + dlen - rlen || 16; + rlen -= plen; + } + + var result = new Uint8Array(rlen); + + while (dlen > 0) { + wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen); + len += wlen; + dpos += wlen; + dlen -= wlen; + + wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0)); + + if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos); + rpos += wlen; + + if (wlen < len) { + pos += wlen; + len -= wlen; + } else { + pos = 0; + len = 0; + } + } + + this.result = result; + this.pos = pos; + this.len = len; + + return this; + } + + /** + * @param {Uint8Array} data + */ + + }, { + key: 'AES_Decrypt_finish', + value: function AES_Decrypt_finish(data) { + var presult = null, + prlen = 0; + + if (data !== undefined) { + presult = this.AES_Decrypt_process(data).result; + prlen = presult.length; + } + + var asm = this.asm, + heap = this.heap, + amode = _aes.AES_asm.DEC[this.mode], + hpos = _aes.AES_asm.HEAP_DATA, + pos = this.pos, + len = this.len, + rlen = len; + + if (len > 0) { + if (len % 16) { + if (this.hasOwnProperty('padding')) { + throw new _errors.IllegalArgumentError('data length must be a multiple of the block size'); + } else { + len += 16 - len % 16; + } + } + + asm.cipher(amode, hpos + pos, len); + + if (this.hasOwnProperty('padding') && this.padding) { + var pad = heap[pos + rlen - 1]; + if (pad < 1 || pad > 16 || pad > rlen) throw new _errors.SecurityError('bad padding'); + + var pcheck = 0; + for (var i = pad; i > 1; i--) { + pcheck |= pad ^ heap[pos + rlen - i]; + }if (pcheck) throw new _errors.SecurityError('bad padding'); + + rlen -= pad; + } + } + + var result = new Uint8Array(prlen + rlen); + + if (prlen > 0) { + result.set(presult); + } + + if (rlen > 0) { + result.set(heap.subarray(pos, pos + rlen), prlen); + } + + this.result = result; + this.pos = 0; + this.len = 0; + + return this; + } + }]); + return AES; +}(); + +},{"../errors":10,"../utils":15,"./aes.asm":1,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30}],3:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_CFB_Decrypt = exports.AES_CFB_Encrypt = exports.AES_CFB = undefined; + +var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); + +var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); + +var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _aes = _dereq_('../aes'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var AES_CFB = exports.AES_CFB = function (_AES) { + (0, _inherits3.default)(AES_CFB, _AES); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_CFB(key, iv, heap, asm) { + (0, _classCallCheck3.default)(this, AES_CFB); + + var _this = (0, _possibleConstructorReturn3.default)(this, (AES_CFB.__proto__ || (0, _getPrototypeOf2.default)(AES_CFB)).call(this, key, iv, true, heap, asm)); + + delete _this.padding; + + _this.mode = 'CFB'; + _this.BLOCK_SIZE = 16; + return _this; + } + + (0, _createClass3.default)(AES_CFB, [{ + key: 'encrypt', + value: function encrypt(data) { + return this.AES_Encrypt_finish(data); + } + }, { + key: 'decrypt', + value: function decrypt(data) { + return this.AES_Decrypt_finish(data); + } + }]); + return AES_CFB; +}(_aes.AES); /** + * Cipher Feedback Mode (CFB) + */ + +var AES_CFB_Encrypt = exports.AES_CFB_Encrypt = function (_AES_CFB) { + (0, _inherits3.default)(AES_CFB_Encrypt, _AES_CFB); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv=null] + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_CFB_Encrypt(key, iv, heap, asm) { + (0, _classCallCheck3.default)(this, AES_CFB_Encrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_CFB_Encrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_CFB_Encrypt)).call(this, key, iv, heap, asm)); + } + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @param {boolean} [padding] + * @returns {AES_CFB_Encrypt} + */ + + + (0, _createClass3.default)(AES_CFB_Encrypt, [{ + key: 'reset', + value: function reset(key, iv, padding) { + return this.AES_reset(key, iv, padding); + } + + /** + * @param {Uint8Array} data + * @returns {AES_CFB_Encrypt} + */ + + }, { + key: 'process', + value: function process(data) { + return this.AES_Encrypt_process(data); + } + + /** + * @param {Uint8Array} data + * @returns {AES_CFB_Encrypt} + */ + + }, { + key: 'finish', + value: function finish(data) { + return this.AES_Encrypt_finish(data); + } + }]); + return AES_CFB_Encrypt; +}(AES_CFB); + +var AES_CFB_Decrypt = exports.AES_CFB_Decrypt = function (_AES_CFB2) { + (0, _inherits3.default)(AES_CFB_Decrypt, _AES_CFB2); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv=null] + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_CFB_Decrypt(key, iv, heap, asm) { + (0, _classCallCheck3.default)(this, AES_CFB_Decrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_CFB_Decrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_CFB_Decrypt)).call(this, key, iv, heap, asm)); + } + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @param {boolean} [padding] + * @returns {AES_CFB_Decrypt} + */ + + + (0, _createClass3.default)(AES_CFB_Decrypt, [{ + key: 'reset', + value: function reset(key, iv, padding) { + return this.AES_reset(key, iv, padding); + } + + /** + * @param {Uint8Array} data + * @returns {AES_CFB_Decrypt} + */ + + }, { + key: 'process', + value: function process(data) { + return this.AES_Decrypt_process(data); + } + + /** + * @param {Uint8Array} data + * @returns {AES_CFB_Decrypt} + */ + + }, { + key: 'finish', + value: function finish(data) { + return this.AES_Decrypt_finish(data); + } + }]); + return AES_CFB_Decrypt; +}(AES_CFB); + +},{"../aes":2,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],4:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_CFB_Decrypt = exports.AES_CFB_Encrypt = exports.AES_CFB = undefined; + +var _exports = _dereq_('../exports'); + +var _cfb = _dereq_('./cfb'); + +/** + * @param {Uint8Array} data + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @returns {Uint8Array} + */ +/** + * AES-CFB exports + */ + +function AES_CFB_encrypt_bytes(data, key, iv) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + return new _cfb.AES_CFB(key, iv, _exports._AES_heap_instance, _exports._AES_asm_instance).encrypt(data).result; } -function AES_CTR_reset ( options ) { - options = options || {}; - - AES_reset.call( this, options ); - - AES_CTR_set_options.call( this, options.nonce, options.counter, options.counterSize ); - - return this; +/** + * @param {Uint8Array} data + * @param {Uint8Array} key + * @param {Uint8Array} [iv] + * @returns {Uint8Array} + */ +function AES_CFB_decrypt_bytes(data, key, iv) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + return new _cfb.AES_CFB(key, iv, _exports._AES_heap_instance, _exports._AES_asm_instance).decrypt(data).result; } -var AES_CTR_prototype = AES_CTR.prototype; -AES_CTR_prototype.BLOCK_SIZE = 16; -AES_CTR_prototype.reset = AES_CTR_reset; -AES_CTR_prototype.encrypt = AES_Encrypt_finish; -AES_CTR_prototype.decrypt = AES_Encrypt_finish; +_cfb.AES_CFB.encrypt = AES_CFB_encrypt_bytes; +_cfb.AES_CFB.decrypt = AES_CFB_decrypt_bytes; -var AES_CTR_Crypt_prototype = AES_CTR_Crypt.prototype; -AES_CTR_Crypt_prototype.BLOCK_SIZE = 16; -AES_CTR_Crypt_prototype.reset = AES_CTR_reset; -AES_CTR_Crypt_prototype.process = AES_Encrypt_process; -AES_CTR_Crypt_prototype.finish = AES_Encrypt_finish; +exports.AES_CFB = _cfb.AES_CFB; +exports.AES_CFB_Encrypt = _cfb.AES_CFB_Encrypt; +exports.AES_CFB_Decrypt = _cfb.AES_CFB_Decrypt; + +},{"../exports":7,"./cfb":3}],5:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_ECB_Decrypt = exports.AES_ECB_Encrypt = exports.AES_ECB = undefined; + +var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); + +var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); + +var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _aes = _dereq_('../aes'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Electronic Code Book Mode (ECB) + */ +var AES_ECB = exports.AES_ECB = function (_AES) { + (0, _inherits3.default)(AES_ECB, _AES); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_ECB(key, heap, asm) { + (0, _classCallCheck3.default)(this, AES_ECB); + + var _this = (0, _possibleConstructorReturn3.default)(this, (AES_ECB.__proto__ || (0, _getPrototypeOf2.default)(AES_ECB)).call(this, key, undefined, false, heap, asm)); + + _this.mode = 'ECB'; + _this.BLOCK_SIZE = 16; + return _this; + } + + (0, _createClass3.default)(AES_ECB, [{ + key: 'encrypt', + value: function encrypt(data) { + return this.AES_Encrypt_finish(data); + } + }, { + key: 'decrypt', + value: function decrypt(data) { + return this.AES_Decrypt_finish(data); + } + }]); + return AES_ECB; +}(_aes.AES); + +var AES_ECB_Encrypt = exports.AES_ECB_Encrypt = function (_AES_ECB) { + (0, _inherits3.default)(AES_ECB_Encrypt, _AES_ECB); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_ECB_Encrypt(key, heap, asm) { + (0, _classCallCheck3.default)(this, AES_ECB_Encrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_ECB_Encrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_ECB_Encrypt)).call(this, key, heap, asm)); + } + + /** + * @param {Uint8Array} key + * @returns {AES_ECB_Encrypt} + */ + + + (0, _createClass3.default)(AES_ECB_Encrypt, [{ + key: 'reset', + value: function reset(key) { + return this.AES_reset(key, null, true); + } + + /** + * @param {Uint8Array} data + * @returns {AES_ECB_Encrypt} + */ + + }, { + key: 'process', + value: function process(data) { + return this.AES_Encrypt_process(data); + } + + /** + * @param {Uint8Array} data + * @returns {AES_ECB_Encrypt} + */ + + }, { + key: 'finish', + value: function finish(data) { + return this.AES_Encrypt_finish(data); + } + }]); + return AES_ECB_Encrypt; +}(AES_ECB); + +var AES_ECB_Decrypt = exports.AES_ECB_Decrypt = function (_AES_ECB2) { + (0, _inherits3.default)(AES_ECB_Decrypt, _AES_ECB2); + + /** + * @param {Uint8Array} key + * @param {Uint8Array} [heap] + * @param {Uint8Array} [asm] + */ + function AES_ECB_Decrypt(key, heap, asm) { + (0, _classCallCheck3.default)(this, AES_ECB_Decrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_ECB_Decrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_ECB_Decrypt)).call(this, key, heap, asm)); + } + + /** + * @param {Uint8Array} key + * @returns {AES_ECB_Decrypt} + */ + + + (0, _createClass3.default)(AES_ECB_Decrypt, [{ + key: 'reset', + value: function reset(key) { + return this.AES_reset(key, null, true); + } + + /** + * @param {Uint8Array} data + * @returns {AES_ECB_Decrypt} + */ + + }, { + key: 'process', + value: function process(data) { + return this.AES_Decrypt_process(data); + } + + /** + * @param {Uint8Array} data + * @returns {AES_ECB_Decrypt} + */ + + }, { + key: 'finish', + value: function finish(data) { + return this.AES_Decrypt_finish(data); + } + }]); + return AES_ECB_Decrypt; +}(AES_ECB); + +},{"../aes":2,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],6:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_ECB_Decrypt = exports.AES_ECB_Encrypt = exports.AES_ECB = undefined; + +var _exports = _dereq_('../exports'); + +var _ecb = _dereq_('./ecb'); + +/** + * AES-ECB exports + */ + +function AES_ECB_encrypt_bytes(data, key) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + return new _ecb.AES_ECB(key, _exports._AES_heap_instance, _exports._AES_asm_instance).encrypt(data).result; +} + +function AES_ECB_decrypt_bytes(data, key) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + return new _ecb.AES_ECB(key, _exports._AES_heap_instance, _exports._AES_asm_instance).decrypt(data).result; +} + +_ecb.AES_ECB.encrypt = AES_ECB_encrypt_bytes; +_ecb.AES_ECB.decrypt = AES_ECB_decrypt_bytes; + +exports.AES_ECB = _ecb.AES_ECB; +exports.AES_ECB_Encrypt = _ecb.AES_ECB_Encrypt; +exports.AES_ECB_Decrypt = _ecb.AES_ECB_Decrypt; + +},{"../exports":7,"./ecb":5}],7:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports._AES_asm_instance = exports._AES_heap_instance = undefined; + +var _aes = _dereq_('./aes.asm'); + +var _AES_heap_instance = exports._AES_heap_instance = new Uint8Array(0x100000); // 1MB +// shared asm.js module and heap +var _AES_asm_instance = exports._AES_asm_instance = (0, _aes.AES_asm)(null, _AES_heap_instance.buffer); + +},{"./aes.asm":1}],8:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_GCM_Decrypt = exports.AES_GCM_Encrypt = exports.AES_GCM = undefined; + +var _exports = _dereq_('../exports'); + +var _gcm = _dereq_('./gcm'); + +/** + * @param {Uint8Array} data + * @param {Uint8Array} key + * @param {Uint8Array} nonce + * @param {Uint8Array} [adata] + * @param {number} [tagSize] + * @return {Uint8Array} + */ +/** + * AES-GCM exports + */ + +function AES_GCM_encrypt_bytes(data, key, nonce, adata, tagSize) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + if (nonce === undefined) throw new SyntaxError('nonce required'); + return new _gcm.AES_GCM(key, nonce, adata, tagSize, _exports._AES_heap_instance, _exports._AES_asm_instance).encrypt(data).result; +} + +/** + * @param {Uint8Array} data + * @param {Uint8Array} key + * @param {Uint8Array} nonce + * @param {Uint8Array} [adata] + * @param {number} [tagSize] + * @return {Uint8Array} + */ +function AES_GCM_decrypt_bytes(data, key, nonce, adata, tagSize) { + if (data === undefined) throw new SyntaxError('data required'); + if (key === undefined) throw new SyntaxError('key required'); + if (nonce === undefined) throw new SyntaxError('nonce required'); + return new _gcm.AES_GCM(key, nonce, adata, tagSize, _exports._AES_heap_instance, _exports._AES_asm_instance).decrypt(data).result; +} + +_gcm.AES_GCM.encrypt = AES_GCM_encrypt_bytes; +_gcm.AES_GCM.decrypt = AES_GCM_decrypt_bytes; + +exports.AES_GCM = _gcm.AES_GCM; +exports.AES_GCM_Encrypt = _gcm.AES_GCM_Encrypt; +exports.AES_GCM_Decrypt = _gcm.AES_GCM_Decrypt; + +},{"../exports":7,"./gcm":9}],9:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AES_GCM_Decrypt = exports.AES_GCM_Encrypt = exports.AES_GCM = undefined; + +var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); + +var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); + +var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = _dereq_('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn'); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = _dereq_('babel-runtime/helpers/inherits'); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _errors = _dereq_('../../errors'); + +var _utils = _dereq_('../../utils'); + +var _aes = _dereq_('../aes'); + +var _aes2 = _dereq_('../aes.asm'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Galois/Counter mode */ -var _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 +var _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5 -function _gcm_mac_process ( data ) { - var heap = this.heap, - asm = this.asm, - dpos = 0, - dlen = data.length || 0, - wlen = 0; +var AES_GCM = exports.AES_GCM = function (_AES) { + (0, _inherits3.default)(AES_GCM, _AES); - while ( dlen > 0 ) { - wlen = _heap_write( heap, 0, data, dpos, dlen ); + function AES_GCM(key, nonce, adata, tagSize, heap, asm) { + (0, _classCallCheck3.default)(this, AES_GCM); + + var _this = (0, _possibleConstructorReturn3.default)(this, (AES_GCM.__proto__ || (0, _getPrototypeOf2.default)(AES_GCM)).call(this, key, undefined, false, heap, asm)); + + _this.nonce = null; + _this.adata = null; + _this.iv = null; + _this.counter = 1; + _this.tagSize = 16; + _this.mode = 'GCM'; + _this.BLOCK_SIZE = 16; + + _this.reset(key, tagSize, nonce, adata); + return _this; + } + + (0, _createClass3.default)(AES_GCM, [{ + key: 'reset', + value: function reset(key, tagSize, nonce, adata) { + return this.AES_GCM_reset(key, tagSize, nonce, adata); + } + }, { + key: 'encrypt', + value: function encrypt(data) { + return this.AES_GCM_encrypt(data); + } + }, { + key: 'decrypt', + value: function decrypt(data) { + return this.AES_GCM_decrypt(data); + } + }, { + key: 'AES_GCM_Encrypt_process', + value: function AES_GCM_Encrypt_process(data) { + if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type"); + + var dpos = 0, + dlen = data.length || 0, + asm = this.asm, + heap = this.heap, + counter = this.counter, + pos = this.pos, + len = this.len, + rpos = 0, + rlen = len + dlen & -16, + wlen = 0; + + if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow'); + + var result = new Uint8Array(rlen); + + while (dlen > 0) { + wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen); + len += wlen; dpos += wlen; dlen -= wlen; - while ( wlen & 15 ) heap[ wlen++ ] = 0; + wlen = asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len); + wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen); - asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen ); + if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos); + counter += wlen >>> 4; + rpos += wlen; + + if (wlen < len) { + pos += wlen; + len -= wlen; + } else { + pos = 0; + len = 0; + } + } + + this.result = result; + this.counter = counter; + this.pos = pos; + this.len = len; + + return this; } -} + }, { + key: 'AES_GCM_Encrypt_finish', + value: function AES_GCM_Encrypt_finish() { + var asm = this.asm, + heap = this.heap, + counter = this.counter, + tagSize = this.tagSize, + adata = this.adata, + pos = this.pos, + len = this.len; -function AES_GCM ( options ) { - this.nonce = null; - this.adata = null; - this.iv = null; - this.counter = 1; - this.tagSize = 16; + var result = new Uint8Array(len + tagSize); - AES.call( this, options ); + asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len + 15 & -16); + if (len) result.set(heap.subarray(pos, pos + len)); - this.mode = 'GCM'; -} + for (var i = len; i & 15; i++) { + heap[pos + i] = 0; + }asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i); -function AES_GCM_Encrypt ( options ) { - AES_GCM.call( this, options ); -} + var alen = adata !== null ? adata.length : 0, + clen = (counter - 1 << 4) + len; + heap[0] = heap[1] = heap[2] = 0, heap[3] = alen >>> 29, heap[4] = alen >>> 21, heap[5] = alen >>> 13 & 255, heap[6] = alen >>> 5 & 255, heap[7] = alen << 3 & 255, heap[8] = heap[9] = heap[10] = 0, heap[11] = clen >>> 29, heap[12] = clen >>> 21 & 255, heap[13] = clen >>> 13 & 255, heap[14] = clen >>> 5 & 255, heap[15] = clen << 3 & 255; + asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16); + asm.get_iv(_aes2.AES_asm.HEAP_DATA); -function AES_GCM_Decrypt ( options ) { - AES_GCM.call( this, options ); -} + asm.set_counter(0, 0, 0, this.gamma0); + asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16); + result.set(heap.subarray(0, tagSize), len); -function AES_GCM_reset ( options ) { - options = options || {}; + this.result = result; + this.counter = 1; + this.pos = 0; + this.len = 0; - AES_reset.call( this, options ); + return this; + } + }, { + key: 'AES_GCM_Decrypt_process', + value: function AES_GCM_Decrypt_process(data) { + if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type"); - var asm = this.asm, - heap = this.heap; + var dpos = 0, + dlen = data.length || 0, + asm = this.asm, + heap = this.heap, + counter = this.counter, + tagSize = this.tagSize, + pos = this.pos, + len = this.len, + rpos = 0, + rlen = len + dlen > tagSize ? len + dlen - tagSize & -16 : 0, + tlen = len + dlen - rlen, + wlen = 0; - asm.gcm_init(); + if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow'); - var tagSize = options.tagSize; - if ( tagSize !== undefined ) { - if ( !is_number(tagSize) ) - throw new TypeError("tagSize must be a number"); + var result = new Uint8Array(rlen); - if ( tagSize < 4 || tagSize > 16 ) - throw new IllegalArgumentError("illegal tagSize value"); + while (dlen > tlen) { + wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen - tlen); + len += wlen; + dpos += wlen; + dlen -= wlen; + + wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen); + wlen = asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, wlen); + + if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos); + counter += wlen >>> 4; + rpos += wlen; + + pos = 0; + len = 0; + } + + if (dlen > 0) { + len += (0, _utils._heap_write)(heap, 0, data, dpos, dlen); + } + + this.result = result; + this.counter = counter; + this.pos = pos; + this.len = len; + + return this; + } + }, { + key: 'AES_GCM_Decrypt_finish', + value: function AES_GCM_Decrypt_finish() { + var asm = this.asm, + heap = this.heap, + tagSize = this.tagSize, + adata = this.adata, + counter = this.counter, + pos = this.pos, + len = this.len, + rlen = len - tagSize, + wlen = 0; + + if (len < tagSize) throw new _errors.IllegalStateError('authentication tag not found'); + + var result = new Uint8Array(rlen), + atag = new Uint8Array(heap.subarray(pos + rlen, pos + len)); + + for (var i = rlen; i & 15; i++) { + heap[pos + i] = 0; + }wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i); + wlen = asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, i); + if (rlen) result.set(heap.subarray(pos, pos + rlen)); + + var alen = adata !== null ? adata.length : 0, + clen = (counter - 1 << 4) + len - tagSize; + heap[0] = heap[1] = heap[2] = 0, heap[3] = alen >>> 29, heap[4] = alen >>> 21, heap[5] = alen >>> 13 & 255, heap[6] = alen >>> 5 & 255, heap[7] = alen << 3 & 255, heap[8] = heap[9] = heap[10] = 0, heap[11] = clen >>> 29, heap[12] = clen >>> 21 & 255, heap[13] = clen >>> 13 & 255, heap[14] = clen >>> 5 & 255, heap[15] = clen << 3 & 255; + asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16); + asm.get_iv(_aes2.AES_asm.HEAP_DATA); + + asm.set_counter(0, 0, 0, this.gamma0); + asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16); + + var acheck = 0; + for (var i = 0; i < tagSize; ++i) { + acheck |= atag[i] ^ heap[i]; + }if (acheck) throw new _errors.SecurityError('data integrity check failed'); + + this.result = result; + this.counter = 1; + this.pos = 0; + this.len = 0; + + return this; + } + }, { + key: 'AES_GCM_decrypt', + value: function AES_GCM_decrypt(data) { + var result1 = this.AES_GCM_Decrypt_process(data).result; + var result2 = this.AES_GCM_Decrypt_finish().result; + + var result = new Uint8Array(result1.length + result2.length); + if (result1.length) result.set(result1); + if (result2.length) result.set(result2, result1.length); + this.result = result; + + return this; + } + }, { + key: 'AES_GCM_encrypt', + value: function AES_GCM_encrypt(data) { + var result1 = this.AES_GCM_Encrypt_process(data).result; + var result2 = this.AES_GCM_Encrypt_finish().result; + + var result = new Uint8Array(result1.length + result2.length); + if (result1.length) result.set(result1); + if (result2.length) result.set(result2, result1.length); + this.result = result; + + return this; + } + }, { + key: 'AES_GCM_reset', + value: function AES_GCM_reset(key, tagSize, nonce, adata, counter, iv) { + this.AES_reset(key, undefined, false); + + var asm = this.asm; + var heap = this.heap; + + asm.gcm_init(); + + var tagSize = tagSize; + if (tagSize !== undefined) { + if (!(0, _utils.is_number)(tagSize)) throw new TypeError('tagSize must be a number'); + + if (tagSize < 4 || tagSize > 16) throw new _errors.IllegalArgumentError('illegal tagSize value'); this.tagSize = tagSize; - } - else { + } else { this.tagSize = 16; - } + } - var nonce = options.nonce; - if ( nonce !== undefined ) { - if ( is_bytes(nonce) || is_buffer(nonce) ) { - nonce = new Uint8Array(nonce); - } - else if ( is_string(nonce) ) { - nonce = string_to_bytes(nonce); - } - else { - throw new TypeError("unexpected nonce type"); + if (nonce !== undefined) { + if (!(0, _utils.is_bytes)(nonce)) { + throw new TypeError('unexpected nonce type'); } this.nonce = nonce; var noncelen = nonce.length || 0, noncebuf = new Uint8Array(16); - if ( noncelen !== 12 ) { - _gcm_mac_process.call( this, nonce ); + if (noncelen !== 12) { + this._gcm_mac_process(nonce); - heap[0] = heap[1] = heap[2] = heap[3] = heap[4] = heap[5] = heap[6] = heap[7] = heap[8] = heap[9] = heap[10] = 0, - heap[11] = noncelen>>>29, - heap[12] = noncelen>>>21&255, - heap[13] = noncelen>>>13&255, - heap[14] = noncelen>>>5&255, - heap[15] = noncelen<<3&255; - asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 ); + heap[0] = heap[1] = heap[2] = heap[3] = heap[4] = heap[5] = heap[6] = heap[7] = heap[8] = heap[9] = heap[10] = 0, heap[11] = noncelen >>> 29, heap[12] = noncelen >>> 21 & 255, heap[13] = noncelen >>> 13 & 255, heap[14] = noncelen >>> 5 & 255, heap[15] = noncelen << 3 & 255; + asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16); - asm.get_iv( AES_asm.HEAP_DATA ); - asm.set_iv(); + asm.get_iv(_aes2.AES_asm.HEAP_DATA); + asm.set_iv(); - noncebuf.set( heap.subarray( 0, 16 ) ); - } - else { - noncebuf.set(nonce); - noncebuf[15] = 1; + noncebuf.set(heap.subarray(0, 16)); + } else { + noncebuf.set(nonce); + noncebuf[15] = 1; } - var nonceview = new DataView( noncebuf.buffer ); + var nonceview = new DataView(noncebuf.buffer); this.gamma0 = nonceview.getUint32(12); - asm.set_nonce( nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0 ); - asm.set_mask( 0, 0, 0, 0xffffffff ); - } - else { - throw new Error("nonce is required"); - } + asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0); + asm.set_mask(0, 0, 0, 0xffffffff); + } else { + throw new Error('nonce is required'); + } - var adata = options.adata; - if ( adata !== undefined && adata !== null ) { - if ( is_bytes(adata) || is_buffer(adata) ) { - adata = new Uint8Array(adata); - } - else if ( is_string(adata) ) { - adata = string_to_bytes(adata); - } - else { - throw new TypeError("unexpected adata type"); + if (adata !== undefined && adata !== null) { + if (!(0, _utils.is_bytes)(adata)) { + throw new TypeError('unexpected adata type'); } - if ( adata.length > _AES_GCM_data_maxLength ) - throw new IllegalArgumentError("illegal adata length"); + if (adata.length > _AES_GCM_data_maxLength) throw new _errors.IllegalArgumentError('illegal adata length'); - if ( adata.length ) { - this.adata = adata; - _gcm_mac_process.call( this, adata ); + if (adata.length) { + this.adata = adata; + this._gcm_mac_process(adata); + } else { + this.adata = null; } - else { - this.adata = null; - } - } - else { + } else { this.adata = null; - } + } - var counter = options.counter; - if ( counter !== undefined ) { - if ( !is_number(counter) ) - throw new TypeError("counter must be a number"); + if (counter !== undefined) { + if (!(0, _utils.is_number)(counter)) throw new TypeError('counter must be a number'); - if ( counter < 1 || counter > 0xffffffff ) - throw new RangeError("counter must be a positive 32-bit integer"); + if (counter < 1 || counter > 0xffffffff) throw new RangeError('counter must be a positive 32-bit integer'); this.counter = counter; - asm.set_counter( 0, 0, 0, this.gamma0+counter|0 ); - } - else { + asm.set_counter(0, 0, 0, this.gamma0 + counter | 0); + } else { this.counter = 1; - asm.set_counter( 0, 0, 0, this.gamma0+1|0 ); - } + asm.set_counter(0, 0, 0, this.gamma0 + 1 | 0); + } - var iv = options.iv; - if ( iv !== undefined ) { - if ( !is_number(counter) ) - throw new TypeError("counter must be a number"); + if (iv !== undefined) { + if (!(0, _utils.is_number)(iv)) throw new TypeError('iv must be a number'); this.iv = iv; - AES_set_iv.call( this, iv ); + this.AES_set_iv(iv); + } + + return this; } + }, { + key: '_gcm_mac_process', + value: function _gcm_mac_process(data) { + var heap = this.heap, + asm = this.asm, + dpos = 0, + dlen = data.length || 0, + wlen = 0; - return this; -} - -function AES_GCM_Encrypt_process ( data ) { - if ( is_string(data) ) - data = string_to_bytes(data); - - if ( is_buffer(data) ) - data = new Uint8Array(data); - - if ( !is_bytes(data) ) - throw new TypeError("data isn't of expected type"); - - var dpos = 0, - dlen = data.length || 0, - asm = this.asm, - heap = this.heap, - counter = this.counter, - pos = this.pos, - len = this.len, - rpos = 0, - rlen = ( len + dlen ) & -16, - wlen = 0; - - if ( ((counter-1)<<4) + len + dlen > _AES_GCM_data_maxLength ) - throw new RangeError("counter overflow"); - - var result = new Uint8Array(rlen); - - while ( dlen > 0 ) { - wlen = _heap_write( heap, pos+len, data, dpos, dlen ); - len += wlen; + while (dlen > 0) { + wlen = (0, _utils._heap_write)(heap, 0, data, dpos, dlen); dpos += wlen; dlen -= wlen; - wlen = asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len ); - wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen ); - - if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos ); - counter += (wlen>>>4); - rpos += wlen; - - if ( wlen < len ) { - pos += wlen; - len -= wlen; - } else { - pos = 0; - len = 0; - } + while (wlen & 15) { + heap[wlen++] = 0; + }asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, wlen); + } } + }]); + return AES_GCM; +}(_aes.AES); - this.result = result; - this.counter = counter; - this.pos = pos; - this.len = len; +var AES_GCM_Encrypt = exports.AES_GCM_Encrypt = function (_AES_GCM) { + (0, _inherits3.default)(AES_GCM_Encrypt, _AES_GCM); - return this; -} + function AES_GCM_Encrypt(key, nonce, adata, tagSize, heap, asm) { + (0, _classCallCheck3.default)(this, AES_GCM_Encrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_GCM_Encrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_GCM_Encrypt)).call(this, key, nonce, adata, tagSize, heap, asm)); + } -function AES_GCM_Encrypt_finish () { - var asm = this.asm, - heap = this.heap, - counter = this.counter, - tagSize = this.tagSize, - adata = this.adata, - pos = this.pos, - len = this.len; - - var result = new Uint8Array( len + tagSize ); - - asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16 ); - if ( len ) result.set( heap.subarray( pos, pos + len ) ); - - for ( var i = len; i & 15; i++ ) heap[ pos + i ] = 0; - asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i ); - - var alen = ( adata !== null ) ? adata.length : 0, - clen = ( (counter-1) << 4) + len; - heap[0] = heap[1] = heap[2] = 0, - heap[3] = alen>>>29, - heap[4] = alen>>>21, - heap[5] = alen>>>13&255, - heap[6] = alen>>>5&255, - heap[7] = alen<<3&255, - heap[8] = heap[9] = heap[10] = 0, - heap[11] = clen>>>29, - heap[12] = clen>>>21&255, - heap[13] = clen>>>13&255, - heap[14] = clen>>>5&255, - heap[15] = clen<<3&255; - asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 ); - asm.get_iv( AES_asm.HEAP_DATA ); - - asm.set_counter( 0, 0, 0, this.gamma0 ); - asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16 ); - result.set( heap.subarray( 0, tagSize ), len ); - - this.result = result; - this.counter = 1; - this.pos = 0; - this.len = 0; - - return this; -} - -function AES_GCM_encrypt ( data ) { - var result1 = AES_GCM_Encrypt_process.call( this, data ).result, - result2 = AES_GCM_Encrypt_finish.call(this).result; - - var result = new Uint8Array( result1.length + result2.length ); - if ( result1.length ) result.set( result1 ); - if ( result2.length ) result.set( result2, result1.length ); - this.result = result; - - return this; -} - -function AES_GCM_Decrypt_process ( data ) { - if ( is_string(data) ) - data = string_to_bytes(data); - - if ( is_buffer(data) ) - data = new Uint8Array(data); - - if ( !is_bytes(data) ) - throw new TypeError("data isn't of expected type"); - - var dpos = 0, - dlen = data.length || 0, - asm = this.asm, - heap = this.heap, - counter = this.counter, - tagSize = this.tagSize, - pos = this.pos, - len = this.len, - rpos = 0, - rlen = len + dlen > tagSize ? ( len + dlen - tagSize ) & -16 : 0, - tlen = len + dlen - rlen, - wlen = 0; - - if ( ((counter-1)<<4) + len + dlen > _AES_GCM_data_maxLength ) - throw new RangeError("counter overflow"); - - var result = new Uint8Array(rlen); - - while ( dlen > tlen ) { - wlen = _heap_write( heap, pos+len, data, dpos, dlen-tlen ); - len += wlen; - dpos += wlen; - dlen -= wlen; - - wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen ); - wlen = asm.cipher( AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen ); - - if ( wlen ) result.set( heap.subarray( pos, pos+wlen ), rpos ); - counter += (wlen>>>4); - rpos += wlen; - - pos = 0; - len = 0; + (0, _createClass3.default)(AES_GCM_Encrypt, [{ + key: 'process', + value: function process(data) { + return this.AES_GCM_Encrypt_process(data); } - - if ( dlen > 0 ) { - len += _heap_write( heap, 0, data, dpos, dlen ); + }, { + key: 'finish', + value: function finish() { + return this.AES_GCM_Encrypt_finish(); } + }]); + return AES_GCM_Encrypt; +}(AES_GCM); - this.result = result; - this.counter = counter; - this.pos = pos; - this.len = len; +var AES_GCM_Decrypt = exports.AES_GCM_Decrypt = function (_AES_GCM2) { + (0, _inherits3.default)(AES_GCM_Decrypt, _AES_GCM2); - return this; + function AES_GCM_Decrypt(key, nonce, adata, tagSize, heap, asm) { + (0, _classCallCheck3.default)(this, AES_GCM_Decrypt); + return (0, _possibleConstructorReturn3.default)(this, (AES_GCM_Decrypt.__proto__ || (0, _getPrototypeOf2.default)(AES_GCM_Decrypt)).call(this, key, nonce, adata, tagSize, heap, asm)); + } + + (0, _createClass3.default)(AES_GCM_Decrypt, [{ + key: 'process', + value: function process(data) { + return this.AES_GCM_Decrypt_process(data); + } + }, { + key: 'finish', + value: function finish() { + return this.AES_GCM_Decrypt_finish(); + } + }]); + return AES_GCM_Decrypt; +}(AES_GCM); + +},{"../../errors":10,"../../utils":15,"../aes":2,"../aes.asm":1,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],10:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _create = _dereq_('babel-runtime/core-js/object/create'); + +var _create2 = _interopRequireDefault(_create); + +exports.IllegalStateError = IllegalStateError; +exports.IllegalArgumentError = IllegalArgumentError; +exports.SecurityError = SecurityError; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function IllegalStateError() { + var err = Error.apply(this, arguments); + this.message = err.message, this.stack = err.stack; +} +IllegalStateError.prototype = (0, _create2.default)(Error.prototype, { name: { value: 'IllegalStateError' } }); + +function IllegalArgumentError() { + var err = Error.apply(this, arguments); + this.message = err.message, this.stack = err.stack; +} +IllegalArgumentError.prototype = (0, _create2.default)(Error.prototype, { name: { value: 'IllegalArgumentError' } }); + +function SecurityError() { + var err = Error.apply(this, arguments); + this.message = err.message, this.stack = err.stack; +} +SecurityError.prototype = (0, _create2.default)(Error.prototype, { name: { value: 'SecurityError' } }); + +},{"babel-runtime/core-js/object/create":20}],11:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hash_reset = hash_reset; +exports.hash_process = hash_process; +exports.hash_finish = hash_finish; + +var _utils = _dereq_('../utils'); + +var _errors = _dereq_('../errors'); + +function hash_reset() { + this.result = null; + this.pos = 0; + this.len = 0; + + this.asm.reset(); + + return this; } -function AES_GCM_Decrypt_finish () { - var asm = this.asm, - heap = this.heap, - tagSize = this.tagSize, - adata = this.adata, - counter = this.counter, - pos = this.pos, - len = this.len, - rlen = len - tagSize, - wlen = 0; +function hash_process(data) { + if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data'); - if ( len < tagSize ) - throw new IllegalStateError("authentication tag not found"); + if ((0, _utils.is_string)(data)) data = (0, _utils.string_to_bytes)(data); - var result = new Uint8Array(rlen), - atag = new Uint8Array( heap.subarray( pos+rlen, pos+len ) ); + if ((0, _utils.is_buffer)(data)) data = new Uint8Array(data); - for ( var i = rlen; i & 15; i++ ) heap[ pos + i ] = 0; + if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type"); - wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i ); - wlen = asm.cipher( AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i ); - if ( rlen ) result.set( heap.subarray( pos, pos+rlen ) ); + var asm = this.asm, + heap = this.heap, + hpos = this.pos, + hlen = this.len, + dpos = 0, + dlen = data.length, + wlen = 0; - var alen = ( adata !== null ) ? adata.length : 0, - clen = ( (counter-1) << 4) + len - tagSize; - heap[0] = heap[1] = heap[2] = 0, - heap[3] = alen>>>29, - heap[4] = alen>>>21, - heap[5] = alen>>>13&255, - heap[6] = alen>>>5&255, - heap[7] = alen<<3&255, - heap[8] = heap[9] = heap[10] = 0, - heap[11] = clen>>>29, - heap[12] = clen>>>21&255, - heap[13] = clen>>>13&255, - heap[14] = clen>>>5&255, - heap[15] = clen<<3&255; - asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 ); - asm.get_iv( AES_asm.HEAP_DATA ); + while (dlen > 0) { + wlen = (0, _utils._heap_write)(heap, hpos + hlen, data, dpos, dlen); + hlen += wlen; + dpos += wlen; + dlen -= wlen; - asm.set_counter( 0, 0, 0, this.gamma0 ); - asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16 ); + wlen = asm.process(hpos, hlen); - var acheck = 0; - for ( var i = 0; i < tagSize; ++i ) acheck |= atag[i] ^ heap[i]; - if ( acheck ) - throw new SecurityError("data integrity check failed"); + hpos += wlen; + hlen -= wlen; - this.result = result; - this.counter = 1; - this.pos = 0; - this.len = 0; + if (!hlen) hpos = 0; + } - return this; + this.pos = hpos; + this.len = hlen; + + return this; } -function AES_GCM_decrypt ( data ) { - var result1 = AES_GCM_Decrypt_process.call( this, data ).result, - result2 = AES_GCM_Decrypt_finish.call( this ).result; +function hash_finish() { + if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data'); - var result = new Uint8Array( result1.length + result2.length ); - if ( result1.length ) result.set( result1 ); - if ( result2.length ) result.set( result2, result1.length ); - this.result = result; + this.asm.finish(this.pos, this.len, 0); - return this; + this.result = new Uint8Array(this.HASH_SIZE); + this.result.set(this.heap.subarray(0, this.HASH_SIZE)); + + this.pos = 0; + this.len = 0; + + return this; } -var AES_GCM_prototype = AES_GCM.prototype; -AES_GCM_prototype.BLOCK_SIZE = 16; -AES_GCM_prototype.reset = AES_GCM_reset; -AES_GCM_prototype.encrypt = AES_GCM_encrypt; -AES_GCM_prototype.decrypt = AES_GCM_decrypt; +},{"../errors":10,"../utils":15}],12:[function(_dereq_,module,exports){ +'use strict'; -var AES_GCM_Encrypt_prototype = AES_GCM_Encrypt.prototype; -AES_GCM_Encrypt_prototype.BLOCK_SIZE = 16; -AES_GCM_Encrypt_prototype.reset = AES_GCM_reset; -AES_GCM_Encrypt_prototype.process = AES_GCM_Encrypt_process; -AES_GCM_Encrypt_prototype.finish = AES_GCM_Encrypt_finish; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SHA256 = undefined; -var AES_GCM_Decrypt_prototype = AES_GCM_Decrypt.prototype; -AES_GCM_Decrypt_prototype.BLOCK_SIZE = 16; -AES_GCM_Decrypt_prototype.reset = AES_GCM_reset; -AES_GCM_Decrypt_prototype.process = AES_GCM_Decrypt_process; -AES_GCM_Decrypt_prototype.finish = AES_GCM_Decrypt_finish; +var _sha = _dereq_('./sha256'); -// shared asm.js module and heap -var _AES_heap_instance = new Uint8Array(0x100000), - _AES_asm_instance = AES_asm( global, null, _AES_heap_instance.buffer ); +var _utils = _dereq_('../../utils'); /** - * AES-CFB exports + * SHA256 exports */ -function AES_CFB_encrypt_bytes ( data, key, iv ) { - if ( data === undefined ) throw new SyntaxError("data required"); - if ( key === undefined ) throw new SyntaxError("key required"); - return new AES_CFB( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, iv: iv } ).encrypt(data).result; +function sha256_bytes(data) { + if (data === undefined) throw new SyntaxError('data required'); + return (0, _sha.get_sha256_instance)().reset().process(data).finish().result; } -function AES_CFB_decrypt_bytes ( data, key, iv ) { - if ( data === undefined ) throw new SyntaxError("data required"); - if ( key === undefined ) throw new SyntaxError("key required"); - return new AES_CFB( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, iv: iv } ).decrypt(data).result; +function sha256_hex(data) { + var result = sha256_bytes(data); + return (0, _utils.bytes_to_hex)(result); } -exports.AES_CFB = AES_CFB; -exports.AES_CFB.encrypt = AES_CFB_encrypt_bytes; -exports.AES_CFB.decrypt = AES_CFB_decrypt_bytes; - -exports.AES_CFB.Encrypt = AES_CFB_Encrypt; -exports.AES_CFB.Decrypt = AES_CFB_Decrypt; - -/** - * AES-GCM exports - */ - -function AES_GCM_encrypt_bytes ( data, key, nonce, adata, tagSize ) { - if ( data === undefined ) throw new SyntaxError("data required"); - if ( key === undefined ) throw new SyntaxError("key required"); - if ( nonce === undefined ) throw new SyntaxError("nonce required"); - return new AES_GCM( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, nonce: nonce, adata: adata, tagSize: tagSize } ).encrypt(data).result; +function sha256_base64(data) { + var result = sha256_bytes(data); + return (0, _utils.bytes_to_base64)(result); } -function AES_GCM_decrypt_bytes ( data, key, nonce, adata, tagSize ) { - if ( data === undefined ) throw new SyntaxError("data required"); - if ( key === undefined ) throw new SyntaxError("key required"); - if ( nonce === undefined ) throw new SyntaxError("nonce required"); - return new AES_GCM( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, nonce: nonce, adata: adata, tagSize: tagSize } ).decrypt(data).result; -} +var SHA256 = exports.SHA256 = _sha.sha256_constructor; +SHA256.bytes = sha256_bytes; +SHA256.hex = sha256_hex; +SHA256.base64 = sha256_base64; -exports.AES_GCM = AES_GCM; -exports.AES_GCM.encrypt = AES_GCM_encrypt_bytes; -exports.AES_GCM.decrypt = AES_GCM_decrypt_bytes; +},{"../../utils":15,"./sha256":14}],13:[function(_dereq_,module,exports){ +"use strict"; -exports.AES_GCM.Encrypt = AES_GCM_Encrypt; -exports.AES_GCM.Decrypt = AES_GCM_Decrypt; - -function hash_reset () { - this.result = null; - this.pos = 0; - this.len = 0; - - this.asm.reset(); - - return this; -} - -function hash_process ( data ) { - if ( this.result !== null ) - throw new IllegalStateError("state must be reset before processing new data"); - - if ( is_string(data) ) - data = string_to_bytes(data); - - if ( is_buffer(data) ) - data = new Uint8Array(data); - - if ( !is_bytes(data) ) - throw new TypeError("data isn't of expected type"); - - var asm = this.asm, - heap = this.heap, - hpos = this.pos, - hlen = this.len, - dpos = 0, - dlen = data.length, - wlen = 0; - - while ( dlen > 0 ) { - wlen = _heap_write( heap, hpos+hlen, data, dpos, dlen ); - hlen += wlen; - dpos += wlen; - dlen -= wlen; - - wlen = asm.process( hpos, hlen ); - - hpos += wlen; - hlen -= wlen; - - if ( !hlen ) hpos = 0; - } - - this.pos = hpos; - this.len = hlen; - - return this; -} - -function hash_finish () { - if ( this.result !== null ) - throw new IllegalStateError("state must be reset before processing new data"); - - this.asm.finish( this.pos, this.len, 0 ); - - this.result = new Uint8Array(this.HASH_SIZE); - this.result.set( this.heap.subarray( 0, this.HASH_SIZE ) ); - - this.pos = 0; - this.len = 0; - - return this; -} - -function sha256_asm ( stdlib, foreign, buffer ) { +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sha256_asm = sha256_asm; +function sha256_asm(stdlib, foreign, buffer) { "use asm"; // SHA256 state - var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0, - TOTAL0 = 0, TOTAL1 = 0; + + var H0 = 0, + H1 = 0, + H2 = 0, + H3 = 0, + H4 = 0, + H5 = 0, + H6 = 0, + H7 = 0, + TOTAL0 = 0, + TOTAL1 = 0; // HMAC state - var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0, - O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0; + var I0 = 0, + I1 = 0, + I2 = 0, + I3 = 0, + I4 = 0, + I5 = 0, + I6 = 0, + I7 = 0, + O0 = 0, + O1 = 0, + O2 = 0, + O3 = 0, + O4 = 0, + O5 = 0, + O6 = 0, + O7 = 0; // I/O buffer var HEAP = new stdlib.Uint8Array(buffer); - function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) { - w0 = w0|0; - w1 = w1|0; - w2 = w2|0; - w3 = w3|0; - w4 = w4|0; - w5 = w5|0; - w6 = w6|0; - w7 = w7|0; - w8 = w8|0; - w9 = w9|0; - w10 = w10|0; - w11 = w11|0; - w12 = w12|0; - w13 = w13|0; - w14 = w14|0; - w15 = w15|0; + function _core(w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15) { + w0 = w0 | 0; + w1 = w1 | 0; + w2 = w2 | 0; + w3 = w3 | 0; + w4 = w4 | 0; + w5 = w5 | 0; + w6 = w6 | 0; + w7 = w7 | 0; + w8 = w8 | 0; + w9 = w9 | 0; + w10 = w10 | 0; + w11 = w11 | 0; + w12 = w12 | 0; + w13 = w13 | 0; + w14 = w14 | 0; + w15 = w15 | 0; - var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, - t = 0; + var a = 0, + b = 0, + c = 0, + d = 0, + e = 0, + f = 0, + g = 0, + h = 0; a = H0; b = H1; @@ -2099,445 +2351,428 @@ function sha256_asm ( stdlib, foreign, buffer ) { h = H7; // 0 - t = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x428a2f98 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 1 - t = ( w1 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x71374491 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x71374491 | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 2 - t = ( w2 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xb5c0fbcf )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb5c0fbcf | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 3 - t = ( w3 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe9b5dba5 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xe9b5dba5 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 4 - t = ( w4 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x3956c25b )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x3956c25b | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 5 - t = ( w5 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x59f111f1 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x59f111f1 | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 6 - t = ( w6 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x923f82a4 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x923f82a4 | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 7 - t = ( w7 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xab1c5ed5 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xab1c5ed5 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 8 - t = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xd807aa98 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 9 - t = ( w9 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x12835b01 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x12835b01 | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 10 - t = ( w10 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x243185be )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x243185be | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 11 - t = ( w11 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x550c7dc3 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x550c7dc3 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 12 - t = ( w12 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x72be5d74 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x72be5d74 | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 13 - t = ( w13 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x80deb1fe )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x80deb1fe | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 14 - t = ( w14 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x9bdc06a7 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x9bdc06a7 | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 15 - t = ( w15 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xc19bf174 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc19bf174 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 16 - w0 = t = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0; + h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xe49b69c1 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 17 - w1 = t = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xefbe4786 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0; + g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xefbe4786 | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 18 - w2 = t = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x0fc19dc6 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0; + f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x0fc19dc6 | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 19 - w3 = t = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x240ca1cc )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0; + e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x240ca1cc | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 20 - w4 = t = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x2de92c6f )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0; + d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x2de92c6f | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 21 - w5 = t = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x4a7484aa )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0; + c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4a7484aa | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 22 - w6 = t = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x5cb0a9dc )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0; + b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5cb0a9dc | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 23 - w7 = t = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x76f988da )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0; + a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x76f988da | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 24 - w8 = t = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0; + h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x983e5152 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 25 - w9 = t = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa831c66d )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0; + g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa831c66d | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 26 - w10 = t = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xb00327c8 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0; + f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb00327c8 | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 27 - w11 = t = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xbf597fc7 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0; + e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xbf597fc7 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 28 - w12 = t = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xc6e00bf3 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0; + d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xc6e00bf3 | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 29 - w13 = t = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd5a79147 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0; + c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd5a79147 | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 30 - w14 = t = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x06ca6351 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0; + b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x06ca6351 | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 31 - w15 = t = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x14292967 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0; + a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x14292967 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 32 - w0 = t = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0; + h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x27b70a85 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 33 - w1 = t = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x2e1b2138 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0; + g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x2e1b2138 | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 34 - w2 = t = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x4d2c6dfc )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0; + f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x4d2c6dfc | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 35 - w3 = t = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x53380d13 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0; + e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x53380d13 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 36 - w4 = t = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x650a7354 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0; + d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x650a7354 | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 37 - w5 = t = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x766a0abb )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0; + c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x766a0abb | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 38 - w6 = t = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x81c2c92e )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0; + b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x81c2c92e | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 39 - w7 = t = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x92722c85 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0; + a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x92722c85 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 40 - w8 = t = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0; + h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xa2bfe8a1 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 41 - w9 = t = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa81a664b )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0; + g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa81a664b | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 42 - w10 = t = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xc24b8b70 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0; + f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xc24b8b70 | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 43 - w11 = t = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xc76c51a3 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0; + e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xc76c51a3 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 44 - w12 = t = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd192e819 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0; + d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xd192e819 | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 45 - w13 = t = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd6990624 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0; + c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd6990624 | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 46 - w14 = t = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xf40e3585 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0; + b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xf40e3585 | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 47 - w15 = t = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x106aa070 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0; + a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x106aa070 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 48 - w0 = t = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0; + h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x19a4c116 | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 49 - w1 = t = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x1e376c08 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0; + g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x1e376c08 | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 50 - w2 = t = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x2748774c )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0; + f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x2748774c | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 51 - w3 = t = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x34b0bcb5 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0; + e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x34b0bcb5 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 52 - w4 = t = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x391c0cb3 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0; + d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x391c0cb3 | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 53 - w5 = t = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x4ed8aa4a )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0; + c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4ed8aa4a | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 54 - w6 = t = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x5b9cca4f )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0; + b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5b9cca4f | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 55 - w7 = t = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x682e6ff3 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0; + a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x682e6ff3 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; // 56 - w8 = t = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0; + h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x748f82ee | 0; + d = d + h | 0; + h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0; // 57 - w9 = t = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x78a5636f )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0; + g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x78a5636f | 0; + c = c + g | 0; + g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0; // 58 - w10 = t = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x84c87814 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0; + f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x84c87814 | 0; + b = b + f | 0; + f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0; // 59 - w11 = t = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x8cc70208 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0; + e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x8cc70208 | 0; + a = a + e | 0; + e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0; // 60 - w12 = t = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x90befffa )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0; + d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x90befffa | 0; + h = h + d | 0; + d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0; // 61 - w13 = t = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa4506ceb )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0; + c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xa4506ceb | 0; + g = g + c | 0; + c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0; // 62 - w14 = t = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xbef9a3f7 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0; + b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xbef9a3f7 | 0; + f = f + b | 0; + b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0; // 63 - w15 = t = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0; - t = ( t + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xc67178f2 )|0; - h = g; g = f; f = e; e = ( d + t )|0; d = c; c = b; b = a; - a = ( t + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0; + w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0; + a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc67178f2 | 0; + e = e + a | 0; + a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0; - H0 = ( H0 + a )|0; - H1 = ( H1 + b )|0; - H2 = ( H2 + c )|0; - H3 = ( H3 + d )|0; - H4 = ( H4 + e )|0; - H5 = ( H5 + f )|0; - H6 = ( H6 + g )|0; - H7 = ( H7 + h )|0; + H0 = H0 + a | 0; + H1 = H1 + b | 0; + H2 = H2 + c | 0; + H3 = H3 + d | 0; + H4 = H4 + e | 0; + H5 = H5 + f | 0; + H6 = H6 + g | 0; + H7 = H7 + h | 0; } - function _core_heap ( offset ) { - offset = offset|0; + function _core_heap(offset) { + offset = offset | 0; - _core( - HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3], - HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7], - HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11], - HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15], - HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19], - HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23], - HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27], - HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31], - HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35], - HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39], - HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43], - HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47], - HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51], - HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55], - HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59], - HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63] - ); + _core(HEAP[offset | 0] << 24 | HEAP[offset | 1] << 16 | HEAP[offset | 2] << 8 | HEAP[offset | 3], HEAP[offset | 4] << 24 | HEAP[offset | 5] << 16 | HEAP[offset | 6] << 8 | HEAP[offset | 7], HEAP[offset | 8] << 24 | HEAP[offset | 9] << 16 | HEAP[offset | 10] << 8 | HEAP[offset | 11], HEAP[offset | 12] << 24 | HEAP[offset | 13] << 16 | HEAP[offset | 14] << 8 | HEAP[offset | 15], HEAP[offset | 16] << 24 | HEAP[offset | 17] << 16 | HEAP[offset | 18] << 8 | HEAP[offset | 19], HEAP[offset | 20] << 24 | HEAP[offset | 21] << 16 | HEAP[offset | 22] << 8 | HEAP[offset | 23], HEAP[offset | 24] << 24 | HEAP[offset | 25] << 16 | HEAP[offset | 26] << 8 | HEAP[offset | 27], HEAP[offset | 28] << 24 | HEAP[offset | 29] << 16 | HEAP[offset | 30] << 8 | HEAP[offset | 31], HEAP[offset | 32] << 24 | HEAP[offset | 33] << 16 | HEAP[offset | 34] << 8 | HEAP[offset | 35], HEAP[offset | 36] << 24 | HEAP[offset | 37] << 16 | HEAP[offset | 38] << 8 | HEAP[offset | 39], HEAP[offset | 40] << 24 | HEAP[offset | 41] << 16 | HEAP[offset | 42] << 8 | HEAP[offset | 43], HEAP[offset | 44] << 24 | HEAP[offset | 45] << 16 | HEAP[offset | 46] << 8 | HEAP[offset | 47], HEAP[offset | 48] << 24 | HEAP[offset | 49] << 16 | HEAP[offset | 50] << 8 | HEAP[offset | 51], HEAP[offset | 52] << 24 | HEAP[offset | 53] << 16 | HEAP[offset | 54] << 8 | HEAP[offset | 55], HEAP[offset | 56] << 24 | HEAP[offset | 57] << 16 | HEAP[offset | 58] << 8 | HEAP[offset | 59], HEAP[offset | 60] << 24 | HEAP[offset | 61] << 16 | HEAP[offset | 62] << 8 | HEAP[offset | 63]); } // offset — multiple of 32 - function _state_to_heap ( output ) { - output = output|0; + function _state_to_heap(output) { + output = output | 0; - HEAP[output|0] = H0>>>24; - HEAP[output|1] = H0>>>16&255; - HEAP[output|2] = H0>>>8&255; - HEAP[output|3] = H0&255; - HEAP[output|4] = H1>>>24; - HEAP[output|5] = H1>>>16&255; - HEAP[output|6] = H1>>>8&255; - HEAP[output|7] = H1&255; - HEAP[output|8] = H2>>>24; - HEAP[output|9] = H2>>>16&255; - HEAP[output|10] = H2>>>8&255; - HEAP[output|11] = H2&255; - HEAP[output|12] = H3>>>24; - HEAP[output|13] = H3>>>16&255; - HEAP[output|14] = H3>>>8&255; - HEAP[output|15] = H3&255; - HEAP[output|16] = H4>>>24; - HEAP[output|17] = H4>>>16&255; - HEAP[output|18] = H4>>>8&255; - HEAP[output|19] = H4&255; - HEAP[output|20] = H5>>>24; - HEAP[output|21] = H5>>>16&255; - HEAP[output|22] = H5>>>8&255; - HEAP[output|23] = H5&255; - HEAP[output|24] = H6>>>24; - HEAP[output|25] = H6>>>16&255; - HEAP[output|26] = H6>>>8&255; - HEAP[output|27] = H6&255; - HEAP[output|28] = H7>>>24; - HEAP[output|29] = H7>>>16&255; - HEAP[output|30] = H7>>>8&255; - HEAP[output|31] = H7&255; + HEAP[output | 0] = H0 >>> 24; + HEAP[output | 1] = H0 >>> 16 & 255; + HEAP[output | 2] = H0 >>> 8 & 255; + HEAP[output | 3] = H0 & 255; + HEAP[output | 4] = H1 >>> 24; + HEAP[output | 5] = H1 >>> 16 & 255; + HEAP[output | 6] = H1 >>> 8 & 255; + HEAP[output | 7] = H1 & 255; + HEAP[output | 8] = H2 >>> 24; + HEAP[output | 9] = H2 >>> 16 & 255; + HEAP[output | 10] = H2 >>> 8 & 255; + HEAP[output | 11] = H2 & 255; + HEAP[output | 12] = H3 >>> 24; + HEAP[output | 13] = H3 >>> 16 & 255; + HEAP[output | 14] = H3 >>> 8 & 255; + HEAP[output | 15] = H3 & 255; + HEAP[output | 16] = H4 >>> 24; + HEAP[output | 17] = H4 >>> 16 & 255; + HEAP[output | 18] = H4 >>> 8 & 255; + HEAP[output | 19] = H4 & 255; + HEAP[output | 20] = H5 >>> 24; + HEAP[output | 21] = H5 >>> 16 & 255; + HEAP[output | 22] = H5 >>> 8 & 255; + HEAP[output | 23] = H5 & 255; + HEAP[output | 24] = H6 >>> 24; + HEAP[output | 25] = H6 >>> 16 & 255; + HEAP[output | 26] = H6 >>> 8 & 255; + HEAP[output | 27] = H6 & 255; + HEAP[output | 28] = H7 >>> 24; + HEAP[output | 29] = H7 >>> 16 & 255; + HEAP[output | 30] = H7 >>> 8 & 255; + HEAP[output | 31] = H7 & 255; } - function reset () { + function reset() { H0 = 0x6a09e667; H1 = 0xbb67ae85; H2 = 0x3c6ef372; @@ -2549,17 +2784,17 @@ function sha256_asm ( stdlib, foreign, buffer ) { TOTAL0 = TOTAL1 = 0; } - function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) { - h0 = h0|0; - h1 = h1|0; - h2 = h2|0; - h3 = h3|0; - h4 = h4|0; - h5 = h5|0; - h6 = h6|0; - h7 = h7|0; - total0 = total0|0; - total1 = total1|0; + function init(h0, h1, h2, h3, h4, h5, h6, h7, total0, total1) { + h0 = h0 | 0; + h1 = h1 | 0; + h2 = h2 | 0; + h3 = h3 | 0; + h4 = h4 | 0; + h5 = h5 | 0; + h6 = h6 | 0; + h7 = h7 | 0; + total0 = total0 | 0; + total1 = total1 | 0; H0 = h0; H1 = h1; @@ -2574,93 +2809,85 @@ function sha256_asm ( stdlib, foreign, buffer ) { } // offset — multiple of 64 - function process ( offset, length ) { - offset = offset|0; - length = length|0; + function process(offset, length) { + offset = offset | 0; + length = length | 0; var hashed = 0; - if ( offset & 63 ) - return -1; + if (offset & 63) return -1; - while ( (length|0) >= 64 ) { + while ((length | 0) >= 64) { _core_heap(offset); - offset = ( offset + 64 )|0; - length = ( length - 64 )|0; + offset = offset + 64 | 0; + length = length - 64 | 0; - hashed = ( hashed + 64 )|0; + hashed = hashed + 64 | 0; } - TOTAL0 = ( TOTAL0 + hashed )|0; - if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; + TOTAL0 = TOTAL0 + hashed | 0; + if (TOTAL0 >>> 0 < hashed >>> 0) TOTAL1 = TOTAL1 + 1 | 0; - return hashed|0; + return hashed | 0; } // offset — multiple of 64 // output — multiple of 32 - function finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; + function finish(offset, length, output) { + offset = offset | 0; + length = length | 0; + output = output | 0; var hashed = 0, i = 0; - if ( offset & 63 ) - return -1; + if (offset & 63) return -1; - if ( ~output ) - if ( output & 31 ) - return -1; + if (~output) if (output & 31) return -1; - if ( (length|0) >= 64 ) { - hashed = process( offset, length )|0; - if ( (hashed|0) == -1 ) - return -1; + if ((length | 0) >= 64) { + hashed = process(offset, length) | 0; + if ((hashed | 0) == -1) return -1; - offset = ( offset + hashed )|0; - length = ( length - hashed )|0; + offset = offset + hashed | 0; + length = length - hashed | 0; } - hashed = ( hashed + length )|0; - TOTAL0 = ( TOTAL0 + length )|0; - if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0; + hashed = hashed + length | 0; + TOTAL0 = TOTAL0 + length | 0; + if (TOTAL0 >>> 0 < length >>> 0) TOTAL1 = TOTAL1 + 1 | 0; - HEAP[offset|length] = 0x80; + HEAP[offset | length] = 0x80; - if ( (length|0) >= 56 ) { - for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 ) - HEAP[offset|i] = 0x00; - - _core_heap(offset); + if ((length | 0) >= 56) { + for (i = length + 1 | 0; (i | 0) < 64; i = i + 1 | 0) { + HEAP[offset | i] = 0x00; + }_core_heap(offset); length = 0; - HEAP[offset|0] = 0; + HEAP[offset | 0] = 0; } - for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 ) - HEAP[offset|i] = 0; - - HEAP[offset|56] = TOTAL1>>>21&255; - HEAP[offset|57] = TOTAL1>>>13&255; - HEAP[offset|58] = TOTAL1>>>5&255; - HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29; - HEAP[offset|60] = TOTAL0>>>21&255; - HEAP[offset|61] = TOTAL0>>>13&255; - HEAP[offset|62] = TOTAL0>>>5&255; - HEAP[offset|63] = TOTAL0<<3&255; + for (i = length + 1 | 0; (i | 0) < 59; i = i + 1 | 0) { + HEAP[offset | i] = 0; + }HEAP[offset | 56] = TOTAL1 >>> 21 & 255; + HEAP[offset | 57] = TOTAL1 >>> 13 & 255; + HEAP[offset | 58] = TOTAL1 >>> 5 & 255; + HEAP[offset | 59] = TOTAL1 << 3 & 255 | TOTAL0 >>> 29; + HEAP[offset | 60] = TOTAL0 >>> 21 & 255; + HEAP[offset | 61] = TOTAL0 >>> 13 & 255; + HEAP[offset | 62] = TOTAL0 >>> 5 & 255; + HEAP[offset | 63] = TOTAL0 << 3 & 255; _core_heap(offset); - if ( ~output ) - _state_to_heap(output); + if (~output) _state_to_heap(output); - return hashed|0; + return hashed | 0; } - function hmac_reset () { + function hmac_reset() { H0 = I0; H1 = I1; H2 = I2; @@ -2673,7 +2900,7 @@ function sha256_asm ( stdlib, foreign, buffer ) { TOTAL1 = 0; } - function _hmac_opad () { + function _hmac_opad() { H0 = O0; H1 = O1; H2 = O2; @@ -2686,44 +2913,27 @@ function sha256_asm ( stdlib, foreign, buffer ) { TOTAL1 = 0; } - function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) { - p0 = p0|0; - p1 = p1|0; - p2 = p2|0; - p3 = p3|0; - p4 = p4|0; - p5 = p5|0; - p6 = p6|0; - p7 = p7|0; - p8 = p8|0; - p9 = p9|0; - p10 = p10|0; - p11 = p11|0; - p12 = p12|0; - p13 = p13|0; - p14 = p14|0; - p15 = p15|0; + function hmac_init(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) { + p0 = p0 | 0; + p1 = p1 | 0; + p2 = p2 | 0; + p3 = p3 | 0; + p4 = p4 | 0; + p5 = p5 | 0; + p6 = p6 | 0; + p7 = p7 | 0; + p8 = p8 | 0; + p9 = p9 | 0; + p10 = p10 | 0; + p11 = p11 | 0; + p12 = p12 | 0; + p13 = p13 | 0; + p14 = p14 | 0; + p15 = p15 | 0; // opad reset(); - _core( - p0 ^ 0x5c5c5c5c, - p1 ^ 0x5c5c5c5c, - p2 ^ 0x5c5c5c5c, - p3 ^ 0x5c5c5c5c, - p4 ^ 0x5c5c5c5c, - p5 ^ 0x5c5c5c5c, - p6 ^ 0x5c5c5c5c, - p7 ^ 0x5c5c5c5c, - p8 ^ 0x5c5c5c5c, - p9 ^ 0x5c5c5c5c, - p10 ^ 0x5c5c5c5c, - p11 ^ 0x5c5c5c5c, - p12 ^ 0x5c5c5c5c, - p13 ^ 0x5c5c5c5c, - p14 ^ 0x5c5c5c5c, - p15 ^ 0x5c5c5c5c - ); + _core(p0 ^ 0x5c5c5c5c, p1 ^ 0x5c5c5c5c, p2 ^ 0x5c5c5c5c, p3 ^ 0x5c5c5c5c, p4 ^ 0x5c5c5c5c, p5 ^ 0x5c5c5c5c, p6 ^ 0x5c5c5c5c, p7 ^ 0x5c5c5c5c, p8 ^ 0x5c5c5c5c, p9 ^ 0x5c5c5c5c, p10 ^ 0x5c5c5c5c, p11 ^ 0x5c5c5c5c, p12 ^ 0x5c5c5c5c, p13 ^ 0x5c5c5c5c, p14 ^ 0x5c5c5c5c, p15 ^ 0x5c5c5c5c); O0 = H0; O1 = H1; O2 = H2; @@ -2735,24 +2945,7 @@ function sha256_asm ( stdlib, foreign, buffer ) { // ipad reset(); - _core( - p0 ^ 0x36363636, - p1 ^ 0x36363636, - p2 ^ 0x36363636, - p3 ^ 0x36363636, - p4 ^ 0x36363636, - p5 ^ 0x36363636, - p6 ^ 0x36363636, - p7 ^ 0x36363636, - p8 ^ 0x36363636, - p9 ^ 0x36363636, - p10 ^ 0x36363636, - p11 ^ 0x36363636, - p12 ^ 0x36363636, - p13 ^ 0x36363636, - p14 ^ 0x36363636, - p15 ^ 0x36363636 - ); + _core(p0 ^ 0x36363636, p1 ^ 0x36363636, p2 ^ 0x36363636, p3 ^ 0x36363636, p4 ^ 0x36363636, p5 ^ 0x36363636, p6 ^ 0x36363636, p7 ^ 0x36363636, p8 ^ 0x36363636, p9 ^ 0x36363636, p10 ^ 0x36363636, p11 ^ 0x36363636, p12 ^ 0x36363636, p13 ^ 0x36363636, p14 ^ 0x36363636, p15 ^ 0x36363636); I0 = H0; I1 = H1; I2 = H2; @@ -2768,73 +2961,87 @@ function sha256_asm ( stdlib, foreign, buffer ) { // offset — multiple of 64 // output — multiple of 32 - function hmac_finish ( offset, length, output ) { - offset = offset|0; - length = length|0; - output = output|0; + function hmac_finish(offset, length, output) { + offset = offset | 0; + length = length | 0; + output = output | 0; - var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + var t0 = 0, + t1 = 0, + t2 = 0, + t3 = 0, + t4 = 0, + t5 = 0, + t6 = 0, + t7 = 0, hashed = 0; - if ( offset & 63 ) - return -1; + if (offset & 63) return -1; - if ( ~output ) - if ( output & 31 ) - return -1; + if (~output) if (output & 31) return -1; - hashed = finish( offset, length, -1 )|0; + hashed = finish(offset, length, -1) | 0; t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); + _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768); - if ( ~output ) - _state_to_heap(output); + if (~output) _state_to_heap(output); - return hashed|0; + return hashed | 0; } // salt is assumed to be already processed // offset — multiple of 64 // output — multiple of 32 - function pbkdf2_generate_block ( offset, length, block, count, output ) { - offset = offset|0; - length = length|0; - block = block|0; - count = count|0; - output = output|0; + function pbkdf2_generate_block(offset, length, block, count, output) { + offset = offset | 0; + length = length | 0; + block = block | 0; + count = count | 0; + output = output | 0; - var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0; + var h0 = 0, + h1 = 0, + h2 = 0, + h3 = 0, + h4 = 0, + h5 = 0, + h6 = 0, + h7 = 0, + t0 = 0, + t1 = 0, + t2 = 0, + t3 = 0, + t4 = 0, + t5 = 0, + t6 = 0, + t7 = 0; - if ( offset & 63 ) - return -1; + if (offset & 63) return -1; - if ( ~output ) - if ( output & 31 ) - return -1; + if (~output) if (output & 31) return -1; // pad block number into heap // FIXME probable OOB write - HEAP[(offset+length)|0] = block>>>24; - HEAP[(offset+length+1)|0] = block>>>16&255; - HEAP[(offset+length+2)|0] = block>>>8&255; - HEAP[(offset+length+3)|0] = block&255; + HEAP[offset + length | 0] = block >>> 24; + HEAP[offset + length + 1 | 0] = block >>> 16 & 255; + HEAP[offset + length + 2 | 0] = block >>> 8 & 255; + HEAP[offset + length + 3 | 0] = block & 255; // finish first iteration - hmac_finish( offset, (length+4)|0, -1 )|0; + hmac_finish(offset, length + 4 | 0, -1) | 0; h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7; - count = (count-1)|0; + count = count - 1 | 0; // perform the rest iterations - while ( (count|0) > 0 ) { + while ((count | 0) > 0) { hmac_reset(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); + _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768); t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; _hmac_opad(); - _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 ); + _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768); t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7; h0 = h0 ^ H0; @@ -2846,7 +3053,7 @@ function sha256_asm ( stdlib, foreign, buffer ) { h6 = h6 ^ H6; h7 = h7 ^ H7; - count = (count-1)|0; + count = count - 1 | 0; } H0 = h0; @@ -2858,8 +3065,7 @@ function sha256_asm ( stdlib, foreign, buffer ) { H6 = h6; H7 = h7; - if ( ~output ) - _state_to_heap(output); + if (~output) _state_to_heap(output); return 0; } @@ -2878,1230 +3084,21382 @@ function sha256_asm ( stdlib, foreign, buffer ) { // PBKDF2-HMAC-SHA256 pbkdf2_generate_block: pbkdf2_generate_block - } + }; } -var _sha256_block_size = 64, - _sha256_hash_size = 32; +},{}],14:[function(_dereq_,module,exports){ +'use strict'; -function sha256_constructor ( options ) { - options = options || {}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports._sha256_hash_size = exports._sha256_block_size = undefined; +exports.sha256_constructor = sha256_constructor; +exports.get_sha256_instance = get_sha256_instance; - this.heap = _heap_init( Uint8Array, options ); - this.asm = options.asm || sha256_asm( global, null, this.heap.buffer ); +var _sha = _dereq_('./sha256.asm'); - this.BLOCK_SIZE = _sha256_block_size; - this.HASH_SIZE = _sha256_hash_size; +var _hash = _dereq_('../hash'); - this.reset(); +var _utils = _dereq_('../../utils'); + +var _sha256_block_size = exports._sha256_block_size = 64; +var _sha256_hash_size = exports._sha256_hash_size = 32; + +function sha256_constructor(options) { + options = options || {}; + + this.heap = (0, _utils._heap_init)(Uint8Array, options.heap); + this.asm = options.asm || (0, _sha.sha256_asm)({ Uint8Array: Uint8Array }, null, this.heap.buffer); + + this.BLOCK_SIZE = _sha256_block_size; + this.HASH_SIZE = _sha256_hash_size; + + this.reset(); } sha256_constructor.BLOCK_SIZE = _sha256_block_size; sha256_constructor.HASH_SIZE = _sha256_hash_size; +sha256_constructor.NAME = 'sha256'; + var sha256_prototype = sha256_constructor.prototype; -sha256_prototype.reset = hash_reset; -sha256_prototype.process = hash_process; -sha256_prototype.finish = hash_finish; +sha256_prototype.reset = _hash.hash_reset; +sha256_prototype.process = _hash.hash_process; +sha256_prototype.finish = _hash.hash_finish; var sha256_instance = null; -function get_sha256_instance () { - if ( sha256_instance === null ) sha256_instance = new sha256_constructor( { heapSize: 0x100000 } ); - return sha256_instance; +function get_sha256_instance() { + if (sha256_instance === null) sha256_instance = new sha256_constructor({ heapSize: 0x100000 }); + return sha256_instance; } +},{"../../utils":15,"../hash":11,"./sha256.asm":13}],15:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.string_to_bytes = string_to_bytes; +exports.hex_to_bytes = hex_to_bytes; +exports.base64_to_bytes = base64_to_bytes; +exports.bytes_to_string = bytes_to_string; +exports.bytes_to_hex = bytes_to_hex; +exports.bytes_to_base64 = bytes_to_base64; +exports.pow2_ceil = pow2_ceil; +exports.is_number = is_number; +exports.is_string = is_string; +exports.is_buffer = is_buffer; +exports.is_bytes = is_bytes; +exports.is_typed_array = is_typed_array; +exports._heap_init = _heap_init; +exports._heap_write = _heap_write; +var FloatArray = exports.FloatArray = typeof Float64Array !== 'undefined' ? Float64Array : Float32Array; // make PhantomJS happy + /** - * SHA256 exports + * @param {string} str + * @param {boolean} [utf8] + * @return {Uint8Array} */ +function string_to_bytes(str, utf8) { + utf8 = !!utf8; -function sha256_bytes ( data ) { - if ( data === undefined ) throw new SyntaxError("data required"); - return get_sha256_instance().reset().process(data).finish().result; -} + var len = str.length, + bytes = new Uint8Array(utf8 ? 4 * len : len); -function sha256_hex ( data ) { - var result = sha256_bytes(data); - return bytes_to_hex(result); -} + for (var i = 0, j = 0; i < len; i++) { + var c = str.charCodeAt(i); -function sha256_base64 ( data ) { - var result = sha256_bytes(data); - return bytes_to_base64(result); -} + if (utf8 && 0xd800 <= c && c <= 0xdbff) { + if (++i >= len) throw new Error('Malformed string, low surrogate expected at position ' + i); + c = (c ^ 0xd800) << 10 | 0x10000 | str.charCodeAt(i) ^ 0xdc00; + } else if (!utf8 && c >>> 8) { + throw new Error('Wide characters are not allowed.'); + } -sha256_constructor.bytes = sha256_bytes; -sha256_constructor.hex = sha256_hex; -sha256_constructor.base64 = sha256_base64; - -exports.SHA256 = sha256_constructor; - - -'function'==typeof define&&define.amd?define([],function(){return exports}):'object'==typeof module&&module.exports?module.exports=exports:global.asmCrypto=exports; - -return exports; -})( {}, function(){return this}() ); -},{}],2:[function(_dereq_,module,exports){ -(function (process,global){ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version 4.1.1 - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; - -function objectOrFunction(x) { - var type = typeof x; - return x !== null && (type === 'object' || type === 'function'); -} - -function isFunction(x) { - return typeof x === 'function'; -} - -var _isArray = undefined; -if (Array.isArray) { - _isArray = Array.isArray; -} else { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} - -var isArray = _isArray; - -var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; - -var asap = function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (customSchedulerFn) { - customSchedulerFn(flush); + if (!utf8 || c <= 0x7f) { + bytes[j++] = c; + } else if (c <= 0x7ff) { + bytes[j++] = 0xc0 | c >> 6; + bytes[j++] = 0x80 | c & 0x3f; + } else if (c <= 0xffff) { + bytes[j++] = 0xe0 | c >> 12; + bytes[j++] = 0x80 | c >> 6 & 0x3f; + bytes[j++] = 0x80 | c & 0x3f; } else { - scheduleFlush(); + bytes[j++] = 0xf0 | c >> 18; + bytes[j++] = 0x80 | c >> 12 & 0x3f; + bytes[j++] = 0x80 | c >> 6 & 0x3f; + bytes[j++] = 0x80 | c & 0x3f; } } -}; -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; + return bytes.subarray(0, j); } -function setAsap(asapFn) { - asap = asapFn; +function hex_to_bytes(str) { + var len = str.length; + if (len & 1) { + str = '0' + str; + len++; + } + var bytes = new Uint8Array(len >> 1); + for (var i = 0; i < len; i += 2) { + bytes[i >> 1] = parseInt(str.substr(i, 2), 16); + } + return bytes; } -var browserWindow = typeof window !== 'undefined' ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; +function base64_to_bytes(str) { + return string_to_bytes(atob(str)); +} -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; +function bytes_to_string(bytes, utf8) { + utf8 = !!utf8; -// node -function useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details + var len = bytes.length, + chars = new Array(len); + + for (var i = 0, j = 0; i < len; i++) { + var b = bytes[i]; + if (!utf8 || b < 128) { + chars[j++] = b; + } else if (b >= 192 && b < 224 && i + 1 < len) { + chars[j++] = (b & 0x1f) << 6 | bytes[++i] & 0x3f; + } else if (b >= 224 && b < 240 && i + 2 < len) { + chars[j++] = (b & 0xf) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f; + } else if (b >= 240 && b < 248 && i + 3 < len) { + var c = (b & 7) << 18 | (bytes[++i] & 0x3f) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f; + if (c <= 0xffff) { + chars[j++] = c; + } else { + c ^= 0x10000; + chars[j++] = 0xd800 | c >> 10; + chars[j++] = 0xdc00 | c & 0x3ff; + } + } else { + throw new Error('Malformed UTF8 character at byte offset ' + i); + } + } + + var str = '', + bs = 16384; + for (var i = 0; i < j; i += bs) { + str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j)); + } + + return str; +} + +function bytes_to_hex(arr) { + var str = ''; + for (var i = 0; i < arr.length; i++) { + var h = (arr[i] & 0xff).toString(16); + if (h.length < 2) str += '0'; + str += h; + } + return str; +} + +function bytes_to_base64(arr) { + return btoa(bytes_to_string(arr)); +} + +function pow2_ceil(a) { + a -= 1; + a |= a >>> 1; + a |= a >>> 2; + a |= a >>> 4; + a |= a >>> 8; + a |= a >>> 16; + a += 1; + return a; +} + +function is_number(a) { + return typeof a === 'number'; +} + +function is_string(a) { + return typeof a === 'string'; +} + +function is_buffer(a) { + return a instanceof ArrayBuffer; +} + +function is_bytes(a) { + return a instanceof Uint8Array; +} + +function is_typed_array(a) { + return a instanceof Int8Array || a instanceof Uint8Array || a instanceof Int16Array || a instanceof Uint16Array || a instanceof Int32Array || a instanceof Uint32Array || a instanceof Float32Array || a instanceof Float64Array; +} + +function _heap_init(constructor, heap, heapSize) { + var size = heap ? heap.byteLength : heapSize || 65536; + + if (size & 0xfff || size <= 0) throw new Error('heap size must be a positive integer and a multiple of 4096'); + + heap = heap || new constructor(new ArrayBuffer(size)); + + return heap; +} + +function _heap_write(heap, hpos, data, dpos, dlen) { + var hlen = heap.length - hpos, + wlen = hlen < dlen ? hlen : dlen; + + heap.set(data.subarray(dpos, dpos + wlen), hpos); + + return wlen; +} + +},{}],16:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/array/from"), __esModule: true }; +},{"core-js/library/fn/array/from":48}],17:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/get-iterator"), __esModule: true }; +},{"core-js/library/fn/get-iterator":49}],18:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/is-iterable"), __esModule: true }; +},{"core-js/library/fn/is-iterable":50}],19:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/json/stringify"), __esModule: true }; +},{"core-js/library/fn/json/stringify":51}],20:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/object/create"), __esModule: true }; +},{"core-js/library/fn/object/create":52}],21:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/object/define-property"), __esModule: true }; +},{"core-js/library/fn/object/define-property":53}],22:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/object/freeze"), __esModule: true }; +},{"core-js/library/fn/object/freeze":54}],23:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/object/get-prototype-of"), __esModule: true }; +},{"core-js/library/fn/object/get-prototype-of":55}],24:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/object/set-prototype-of"), __esModule: true }; +},{"core-js/library/fn/object/set-prototype-of":56}],25:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/promise"), __esModule: true }; +},{"core-js/library/fn/promise":57}],26:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/symbol"), __esModule: true }; +},{"core-js/library/fn/symbol":58}],27:[function(_dereq_,module,exports){ +module.exports = { "default": _dereq_("core-js/library/fn/symbol/iterator"), __esModule: true }; +},{"core-js/library/fn/symbol/iterator":59}],28:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _promise = _dereq_("../core-js/promise"); + +var _promise2 = _interopRequireDefault(_promise); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (fn) { return function () { - return process.nextTick(flush); + var gen = fn.apply(this, arguments); + return new _promise2.default(function (resolve, reject) { + function step(key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + return _promise2.default.resolve(value).then(function (value) { + step("next", value); + }, function (err) { + step("throw", err); + }); + } + } + + return step("next"); + }); }; +}; +},{"../core-js/promise":25}],29:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +},{}],30:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _defineProperty = _dereq_("../core-js/object/define-property"); + +var _defineProperty2 = _interopRequireDefault(_defineProperty); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + (0, _defineProperty2.default)(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +}(); +},{"../core-js/object/define-property":21}],31:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _setPrototypeOf = _dereq_("../core-js/object/set-prototype-of"); + +var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); + +var _create = _dereq_("../core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _typeof2 = _dereq_("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +},{"../core-js/object/create":20,"../core-js/object/set-prototype-of":24,"../helpers/typeof":34}],32:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = _dereq_("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +},{"../helpers/typeof":34}],33:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _isIterable2 = _dereq_("../core-js/is-iterable"); + +var _isIterable3 = _interopRequireDefault(_isIterable2); + +var _getIterator2 = _dereq_("../core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if ((0, _isIterable3.default)(Object(arr))) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); +},{"../core-js/get-iterator":17,"../core-js/is-iterable":18}],34:[function(_dereq_,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _iterator = _dereq_("../core-js/symbol/iterator"); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _symbol = _dereq_("../core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +},{"../core-js/symbol":26,"../core-js/symbol/iterator":27}],35:[function(_dereq_,module,exports){ +module.exports = _dereq_("regenerator-runtime"); + +},{"regenerator-runtime":299}],36:[function(_dereq_,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -// vertx -function useVertxTimer() { - if (typeof vertxNext !== 'undefined') { - return function () { - vertxNext(flush); +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr((len * 3 / 4) - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0; i < l; i += 4) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],37:[function(_dereq_,module,exports){ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = _dereq_('buffer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; }; } - return useSetTimeout(); -} + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function () { - node.data = iterations = ++iterations % 2; + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; }; -} -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; }; -} -function useSetTimeout() { - // Store setTimeout reference so es6-promise will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var globalSetTimeout = setTimeout; - return function () { - return globalSetTimeout(flush, 1); + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; }; -} -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - callback(arg); - - queue[i] = undefined; - queue[i + 1] = undefined; - } - - len = 0; -} - -function attemptVertx() { - try { - var r = _dereq_; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} - -var scheduleFlush = undefined; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof _dereq_ === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} - -function then(onFulfillment, onRejection) { - var _arguments = arguments; - - var parent = this; - - var child = new this.constructor(noop); - - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } - - var _state = parent._state; - - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; -} - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - let promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -function resolve$1(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - resolve(promise, object); - return promise; -} - -var PROMISE_ID = Math.random().toString(36).substring(16); - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { - try { - then$$1.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then$$1) { - asap(function (promise) { - var sealed = false; - var error = tryThen(then$$1, thenable, function (value) { - if (sealed) { - return; - } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function (reason) { - if (sealed) { - return; - } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); } - }, promise); -} + return this.clone(); + }; -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function (value) { - return resolve(promise, value); - }, function (reason) { - return reject(promise, reason); - }); - } -} + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; -function handleMaybeThenable(promise, maybeThenable, then$$1) { - if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { - handleOwnThenable(promise, maybeThenable); - } else { - if (then$$1 === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - GET_THEN_ERROR.error = null; - } else if (then$$1 === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then$$1)) { - handleForeignThenable(promise, maybeThenable, then$$1); + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; } else { - fulfill(promise, maybeThenable); + b = this; } - } -} -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } + this.length = b.length; - publish(promise); -} + return this.strip(); + }; -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; - promise._result = value; - promise._state = FULFILLED; + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; -function reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; - - parent._onerror = null; - - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { - return; - } - - var child = undefined, - callback = undefined, - detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value.error = null; - } else { - succeeded = true; + a = num; + b = this; } - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; } - } else { - value = detail; - succeeded = true; - } - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch (e) { - reject(promise, e); - } -} - -var id = 0; -function nextId() { - return id++; -} - -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} - -function Enumerator$1(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); - - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } - - if (isArray(input)) { - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(input); - if (this._remaining === 0) { - fulfill(this.promise, this._result); + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; } } - } else { - reject(this.promise, validationError()); - } -} -function validationError() { - return new Error('Array Methods must be provided an Array'); -} + this.length = a.length; -Enumerator$1.prototype._enumerate = function (input) { - for (var i = 0; this._state === PENDING && i < input.length; i++) { - this._eachEntry(input[i], i); - } -}; + return this.strip(); + }; -Enumerator$1.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$1 = c.resolve; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - if (resolve$$1 === resolve$1) { - var _then = getThen(entry); + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; - if (_then === then && entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof _then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise$2) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, _then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function (resolve$$1) { - return resolve$$1(entry); - }), i); + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; } - } else { - this._willSettleAt(resolve$$1(entry), i); - } -}; -Enumerator$1.prototype._settledAt = function (state, i, value) { - var promise = this.promise; - - if (promise._state === PENDING) { - this._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - this._result[i] = value; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; } - } - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } -Enumerator$1.prototype._willSettleAt = function (promise, i) { - var enumerator = this; + // And remove leading zeroes + return this.strip(); + }; - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); -}; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - Example: + var off = (bit / 26) | 0; + var wbit = bit % 26; - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; + this._expand(off + 1); - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: + return this.strip(); + }; - Example: + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -function all$1(entries) { - return new Enumerator$1(this, entries).promise; -} + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - Example: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -function race$1(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!isArray(entries)) { - return new Constructor(function (_, reject) { - return reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function (resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; } - }); + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); } -} -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } - Instead of writing the above, your code now simply becomes the following: + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -function reject$1(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - reject(promise, reason); - return promise; -} + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} + return out.strip(); + } -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } - Terminology - ----------- + return res; + }; - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - A promise can be in one of three states: pending, fulfilled, or rejected. + function FFTM (x, y) { + this.x = x; + this.y = y; + } - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. + return t; + }; + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; - Basic Usage: - ------------ + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + return rb; + }; - // on failure - reject(reason); - }); + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - Advanced Usage: - --------------- + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; } } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) }; - }); + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); } - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - Unlike callbacks, promises are great composable primitives. + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); - return values; - }); - ``` + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise$2(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; + return r; + }; - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew(); + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); + +},{"buffer":39}],38:[function(_dereq_,module,exports){ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + +if (typeof self === 'object') { + if (self.crypto && self.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker with no crypto support + try { + var crypto = _dereq_('crypto'); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { } } -Promise$2.all = all$1; -Promise$2.race = race$1; -Promise$2.resolve = resolve$1; -Promise$2.reject = reject$1; -Promise$2._setScheduler = setScheduler; -Promise$2._setAsap = setAsap; -Promise$2._asap = asap; +},{"crypto":"crypto"}],39:[function(_dereq_,module,exports){ -Promise$2.prototype = { - constructor: Promise$2, +},{}],40:[function(_dereq_,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - let result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure +'use strict' + +var base64 = _dereq_('base64-js') +var ieee754 = _dereq_('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } +} + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return fromObject(value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - let author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure + return fromArrayLike(obj) } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) } - - function failure(reason) { - + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || isArrayBuffer(string)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break } - // success } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: then, + if (found) return i + } + } - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function _catch(onRejection) { - return this.then(null, onRejection); + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') +} + +// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` +function isArrayBufferView (obj) { + return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) +} + +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} + +},{"base64-js":36,"ieee754":278}],41:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.array.fill'); +module.exports = _dereq_('../../modules/_core').Array.fill; + +},{"../../modules/_core":164,"../../modules/es6.array.fill":234}],42:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.array.find'); +module.exports = _dereq_('../../modules/_core').Array.find; + +},{"../../modules/_core":164,"../../modules/es6.array.find":235}],43:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.string.iterator'); +_dereq_('../../modules/es6.array.from'); +module.exports = _dereq_('../../modules/_core').Array.from; + +},{"../../modules/_core":164,"../../modules/es6.array.from":236,"../../modules/es6.string.iterator":240}],44:[function(_dereq_,module,exports){ +_dereq_('../modules/es6.object.to-string'); +_dereq_('../modules/es6.string.iterator'); +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.promise'); +_dereq_('../modules/es7.promise.finally'); +_dereq_('../modules/es7.promise.try'); +module.exports = _dereq_('../modules/_core').Promise; + +},{"../modules/_core":164,"../modules/es6.object.to-string":238,"../modules/es6.promise":239,"../modules/es6.string.iterator":240,"../modules/es7.promise.finally":244,"../modules/es7.promise.try":245,"../modules/web.dom.iterable":248}],45:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.string.repeat'); +module.exports = _dereq_('../../modules/_core').String.repeat; + +},{"../../modules/_core":164,"../../modules/es6.string.repeat":241}],46:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.symbol'); +_dereq_('../../modules/es6.object.to-string'); +_dereq_('../../modules/es7.symbol.async-iterator'); +_dereq_('../../modules/es7.symbol.observable'); +module.exports = _dereq_('../../modules/_core').Symbol; + +},{"../../modules/_core":164,"../../modules/es6.object.to-string":238,"../../modules/es6.symbol":242,"../../modules/es7.symbol.async-iterator":246,"../../modules/es7.symbol.observable":247}],47:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.typed.uint8-array'); +module.exports = _dereq_('../../modules/_core').Uint8Array; + +},{"../../modules/_core":164,"../../modules/es6.typed.uint8-array":243}],48:[function(_dereq_,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"../../modules/_core":67,"../../modules/es6.array.from":136,"../../modules/es6.string.iterator":145,"dup":43}],49:[function(_dereq_,module,exports){ +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.string.iterator'); +module.exports = _dereq_('../modules/core.get-iterator'); + +},{"../modules/core.get-iterator":134,"../modules/es6.string.iterator":145,"../modules/web.dom.iterable":151}],50:[function(_dereq_,module,exports){ +_dereq_('../modules/web.dom.iterable'); +_dereq_('../modules/es6.string.iterator'); +module.exports = _dereq_('../modules/core.is-iterable'); + +},{"../modules/core.is-iterable":135,"../modules/es6.string.iterator":145,"../modules/web.dom.iterable":151}],51:[function(_dereq_,module,exports){ +var core = _dereq_('../../modules/_core'); +var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); +module.exports = function stringify(it) { // eslint-disable-line no-unused-vars + return $JSON.stringify.apply($JSON, arguments); +}; + +},{"../../modules/_core":67}],52:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.create'); +var $Object = _dereq_('../../modules/_core').Object; +module.exports = function create(P, D) { + return $Object.create(P, D); +}; + +},{"../../modules/_core":67,"../../modules/es6.object.create":138}],53:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.define-property'); +var $Object = _dereq_('../../modules/_core').Object; +module.exports = function defineProperty(it, key, desc) { + return $Object.defineProperty(it, key, desc); +}; + +},{"../../modules/_core":67,"../../modules/es6.object.define-property":139}],54:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.freeze'); +module.exports = _dereq_('../../modules/_core').Object.freeze; + +},{"../../modules/_core":67,"../../modules/es6.object.freeze":140}],55:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.get-prototype-of'); +module.exports = _dereq_('../../modules/_core').Object.getPrototypeOf; + +},{"../../modules/_core":67,"../../modules/es6.object.get-prototype-of":141}],56:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.object.set-prototype-of'); +module.exports = _dereq_('../../modules/_core').Object.setPrototypeOf; + +},{"../../modules/_core":67,"../../modules/es6.object.set-prototype-of":142}],57:[function(_dereq_,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"../modules/_core":67,"../modules/es6.object.to-string":143,"../modules/es6.promise":144,"../modules/es6.string.iterator":145,"../modules/es7.promise.finally":147,"../modules/es7.promise.try":148,"../modules/web.dom.iterable":151,"dup":44}],58:[function(_dereq_,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../modules/_core":67,"../../modules/es6.object.to-string":143,"../../modules/es6.symbol":146,"../../modules/es7.symbol.async-iterator":149,"../../modules/es7.symbol.observable":150,"dup":46}],59:[function(_dereq_,module,exports){ +_dereq_('../../modules/es6.string.iterator'); +_dereq_('../../modules/web.dom.iterable'); +module.exports = _dereq_('../../modules/_wks-ext').f('iterator'); + +},{"../../modules/_wks-ext":131,"../../modules/es6.string.iterator":145,"../../modules/web.dom.iterable":151}],60:[function(_dereq_,module,exports){ +module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +},{}],61:[function(_dereq_,module,exports){ +module.exports = function () { /* empty */ }; + +},{}],62:[function(_dereq_,module,exports){ +module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; +}; + +},{}],63:[function(_dereq_,module,exports){ +var isObject = _dereq_('./_is-object'); +module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +},{"./_is-object":87}],64:[function(_dereq_,module,exports){ +// false -> Array#indexOf +// true -> Array#includes +var toIObject = _dereq_('./_to-iobject'); +var toLength = _dereq_('./_to-length'); +var toAbsoluteIndex = _dereq_('./_to-absolute-index'); +module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +},{"./_to-absolute-index":123,"./_to-iobject":125,"./_to-length":126}],65:[function(_dereq_,module,exports){ +// getting tag from 19.1.3.6 Object.prototype.toString() +var cof = _dereq_('./_cof'); +var TAG = _dereq_('./_wks')('toStringTag'); +// ES3 wrong here +var ARG = cof(function () { return arguments; }()) == 'Arguments'; + +// fallback for IE11 Script Access Denied error +var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } +}; + +module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; + +},{"./_cof":66,"./_wks":132}],66:[function(_dereq_,module,exports){ +var toString = {}.toString; + +module.exports = function (it) { + return toString.call(it).slice(8, -1); +}; + +},{}],67:[function(_dereq_,module,exports){ +var core = module.exports = { version: '2.5.3' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + +},{}],68:[function(_dereq_,module,exports){ +'use strict'; +var $defineProperty = _dereq_('./_object-dp'); +var createDesc = _dereq_('./_property-desc'); + +module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; +}; + +},{"./_object-dp":99,"./_property-desc":112}],69:[function(_dereq_,module,exports){ +// optional / simple context binding +var aFunction = _dereq_('./_a-function'); +module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +},{"./_a-function":60}],70:[function(_dereq_,module,exports){ +// 7.2.1 RequireObjectCoercible(argument) +module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +},{}],71:[function(_dereq_,module,exports){ +// Thank's IE8 for his funny defineProperty +module.exports = !_dereq_('./_fails')(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +},{"./_fails":76}],72:[function(_dereq_,module,exports){ +var isObject = _dereq_('./_is-object'); +var document = _dereq_('./_global').document; +// typeof document.createElement is 'object' in old IE +var is = isObject(document) && isObject(document.createElement); +module.exports = function (it) { + return is ? document.createElement(it) : {}; +}; + +},{"./_global":78,"./_is-object":87}],73:[function(_dereq_,module,exports){ +// IE 8- don't enum bug keys +module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +},{}],74:[function(_dereq_,module,exports){ +// all enumerable object keys, includes symbols +var getKeys = _dereq_('./_object-keys'); +var gOPS = _dereq_('./_object-gops'); +var pIE = _dereq_('./_object-pie'); +module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +},{"./_object-gops":104,"./_object-keys":107,"./_object-pie":108}],75:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var core = _dereq_('./_core'); +var ctx = _dereq_('./_ctx'); +var hide = _dereq_('./_hide'); +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; + +},{"./_core":67,"./_ctx":69,"./_global":78,"./_hide":80}],76:[function(_dereq_,module,exports){ +module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; } }; -/*global self*/ -function polyfill$1() { - var local = undefined; +},{}],77:[function(_dereq_,module,exports){ +var ctx = _dereq_('./_ctx'); +var call = _dereq_('./_iter-call'); +var isArrayIter = _dereq_('./_is-array-iter'); +var anObject = _dereq_('./_an-object'); +var toLength = _dereq_('./_to-length'); +var getIterFn = _dereq_('./core.get-iterator-method'); +var BREAK = {}; +var RETURN = {}; +var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); + var f = ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = call(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } +}; +exports.BREAK = BREAK; +exports.RETURN = RETURN; - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } +},{"./_an-object":63,"./_ctx":69,"./_is-array-iter":85,"./_iter-call":88,"./_to-length":126,"./core.get-iterator-method":133}],78:[function(_dereq_,module,exports){ +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + +},{}],79:[function(_dereq_,module,exports){ +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +},{}],80:[function(_dereq_,module,exports){ +var dP = _dereq_('./_object-dp'); +var createDesc = _dereq_('./_property-desc'); +module.exports = _dereq_('./_descriptors') ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +},{"./_descriptors":71,"./_object-dp":99,"./_property-desc":112}],81:[function(_dereq_,module,exports){ +var document = _dereq_('./_global').document; +module.exports = document && document.documentElement; + +},{"./_global":78}],82:[function(_dereq_,module,exports){ +module.exports = !_dereq_('./_descriptors') && !_dereq_('./_fails')(function () { + return Object.defineProperty(_dereq_('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +},{"./_descriptors":71,"./_dom-create":72,"./_fails":76}],83:[function(_dereq_,module,exports){ +// fast apply, http://jsperf.lnkit.com/fast-apply/5 +module.exports = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); +}; + +},{}],84:[function(_dereq_,module,exports){ +// fallback for non-array-like ES3 and non-enumerable old V8 strings +var cof = _dereq_('./_cof'); +// eslint-disable-next-line no-prototype-builtins +module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); +}; + +},{"./_cof":66}],85:[function(_dereq_,module,exports){ +// check on default Array iterator +var Iterators = _dereq_('./_iterators'); +var ITERATOR = _dereq_('./_wks')('iterator'); +var ArrayProto = Array.prototype; + +module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); +}; + +},{"./_iterators":93,"./_wks":132}],86:[function(_dereq_,module,exports){ +// 7.2.2 IsArray(argument) +var cof = _dereq_('./_cof'); +module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; +}; + +},{"./_cof":66}],87:[function(_dereq_,module,exports){ +module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +},{}],88:[function(_dereq_,module,exports){ +// call something on iterator step with safe closing on error +var anObject = _dereq_('./_an-object'); +module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } +}; + +},{"./_an-object":63}],89:[function(_dereq_,module,exports){ +'use strict'; +var create = _dereq_('./_object-create'); +var descriptor = _dereq_('./_property-desc'); +var setToStringTag = _dereq_('./_set-to-string-tag'); +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +_dereq_('./_hide')(IteratorPrototype, _dereq_('./_wks')('iterator'), function () { return this; }); + +module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); +}; + +},{"./_hide":80,"./_object-create":98,"./_property-desc":112,"./_set-to-string-tag":117,"./_wks":132}],90:[function(_dereq_,module,exports){ +'use strict'; +var LIBRARY = _dereq_('./_library'); +var $export = _dereq_('./_export'); +var redefine = _dereq_('./_redefine'); +var hide = _dereq_('./_hide'); +var has = _dereq_('./_has'); +var Iterators = _dereq_('./_iterators'); +var $iterCreate = _dereq_('./_iter-create'); +var setToStringTag = _dereq_('./_set-to-string-tag'); +var getPrototypeOf = _dereq_('./_object-gpo'); +var ITERATOR = _dereq_('./_wks')('iterator'); +var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = (!BUGGY && $native) || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis); } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; - var P = local.Promise; +},{"./_export":75,"./_has":79,"./_hide":80,"./_iter-create":89,"./_iterators":93,"./_library":94,"./_object-gpo":105,"./_redefine":114,"./_set-to-string-tag":117,"./_wks":132}],91:[function(_dereq_,module,exports){ +var ITERATOR = _dereq_('./_wks')('iterator'); +var SAFE_CLOSING = false; - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } +try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); +} catch (e) { /* empty */ } - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } - } +module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; +}; - local.Promise = Promise$2; +},{"./_wks":132}],92:[function(_dereq_,module,exports){ +module.exports = function (done, value) { + return { value: value, done: !!done }; +}; + +},{}],93:[function(_dereq_,module,exports){ +module.exports = {}; + +},{}],94:[function(_dereq_,module,exports){ +module.exports = true; + +},{}],95:[function(_dereq_,module,exports){ +var META = _dereq_('./_uid')('meta'); +var isObject = _dereq_('./_is-object'); +var has = _dereq_('./_has'); +var setDesc = _dereq_('./_object-dp').f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !_dereq_('./_fails')(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; + +},{"./_fails":76,"./_has":79,"./_is-object":87,"./_object-dp":99,"./_uid":129}],96:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var macrotask = _dereq_('./_task').set; +var Observer = global.MutationObserver || global.WebKitMutationObserver; +var process = global.process; +var Promise = global.Promise; +var isNode = _dereq_('./_cof')(process) == 'process'; + +module.exports = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(global.navigator && global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + var promise = Promise.resolve(); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; +}; + +},{"./_cof":66,"./_global":78,"./_task":122}],97:[function(_dereq_,module,exports){ +'use strict'; +// 25.4.1.5 NewPromiseCapability(C) +var aFunction = _dereq_('./_a-function'); + +function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); } -// Strange compat.. -Promise$2.polyfill = polyfill$1; -Promise$2.Promise = Promise$2; +module.exports.f = function (C) { + return new PromiseCapability(C); +}; -return Promise$2; +},{"./_a-function":60}],98:[function(_dereq_,module,exports){ +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +var anObject = _dereq_('./_an-object'); +var dPs = _dereq_('./_object-dps'); +var enumBugKeys = _dereq_('./_enum-bug-keys'); +var IE_PROTO = _dereq_('./_shared-key')('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE = 'prototype'; -}))); +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = _dereq_('./_dom-create')('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + _dereq_('./_html').appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); +}; + +module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); +}; + +},{"./_an-object":63,"./_dom-create":72,"./_enum-bug-keys":73,"./_html":81,"./_object-dps":100,"./_shared-key":118}],99:[function(_dereq_,module,exports){ +var anObject = _dereq_('./_an-object'); +var IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define'); +var toPrimitive = _dereq_('./_to-primitive'); +var dP = Object.defineProperty; + +exports.f = _dereq_('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +},{"./_an-object":63,"./_descriptors":71,"./_ie8-dom-define":82,"./_to-primitive":128}],100:[function(_dereq_,module,exports){ +var dP = _dereq_('./_object-dp'); +var anObject = _dereq_('./_an-object'); +var getKeys = _dereq_('./_object-keys'); + +module.exports = _dereq_('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; +}; + +},{"./_an-object":63,"./_descriptors":71,"./_object-dp":99,"./_object-keys":107}],101:[function(_dereq_,module,exports){ +var pIE = _dereq_('./_object-pie'); +var createDesc = _dereq_('./_property-desc'); +var toIObject = _dereq_('./_to-iobject'); +var toPrimitive = _dereq_('./_to-primitive'); +var has = _dereq_('./_has'); +var IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define'); +var gOPD = Object.getOwnPropertyDescriptor; + +exports.f = _dereq_('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); +}; + +},{"./_descriptors":71,"./_has":79,"./_ie8-dom-define":82,"./_object-pie":108,"./_property-desc":112,"./_to-iobject":125,"./_to-primitive":128}],102:[function(_dereq_,module,exports){ +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +var toIObject = _dereq_('./_to-iobject'); +var gOPN = _dereq_('./_object-gopn').f; +var toString = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } +}; + +module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); +}; + +},{"./_object-gopn":103,"./_to-iobject":125}],103:[function(_dereq_,module,exports){ +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) +var $keys = _dereq_('./_object-keys-internal'); +var hiddenKeys = _dereq_('./_enum-bug-keys').concat('length', 'prototype'); + +exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); +}; + +},{"./_enum-bug-keys":73,"./_object-keys-internal":106}],104:[function(_dereq_,module,exports){ +exports.f = Object.getOwnPropertySymbols; + +},{}],105:[function(_dereq_,module,exports){ +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) +var has = _dereq_('./_has'); +var toObject = _dereq_('./_to-object'); +var IE_PROTO = _dereq_('./_shared-key')('IE_PROTO'); +var ObjectProto = Object.prototype; + +module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; +}; + +},{"./_has":79,"./_shared-key":118,"./_to-object":127}],106:[function(_dereq_,module,exports){ +var has = _dereq_('./_has'); +var toIObject = _dereq_('./_to-iobject'); +var arrayIndexOf = _dereq_('./_array-includes')(false); +var IE_PROTO = _dereq_('./_shared-key')('IE_PROTO'); + +module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; +}; + +},{"./_array-includes":64,"./_has":79,"./_shared-key":118,"./_to-iobject":125}],107:[function(_dereq_,module,exports){ +// 19.1.2.14 / 15.2.3.14 Object.keys(O) +var $keys = _dereq_('./_object-keys-internal'); +var enumBugKeys = _dereq_('./_enum-bug-keys'); + +module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); +}; + +},{"./_enum-bug-keys":73,"./_object-keys-internal":106}],108:[function(_dereq_,module,exports){ +exports.f = {}.propertyIsEnumerable; + +},{}],109:[function(_dereq_,module,exports){ +// most Object methods by ES6 should accept primitives +var $export = _dereq_('./_export'); +var core = _dereq_('./_core'); +var fails = _dereq_('./_fails'); +module.exports = function (KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); +}; + +},{"./_core":67,"./_export":75,"./_fails":76}],110:[function(_dereq_,module,exports){ +module.exports = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } +}; + +},{}],111:[function(_dereq_,module,exports){ +var anObject = _dereq_('./_an-object'); +var isObject = _dereq_('./_is-object'); +var newPromiseCapability = _dereq_('./_new-promise-capability'); + +module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; +}; + +},{"./_an-object":63,"./_is-object":87,"./_new-promise-capability":97}],112:[function(_dereq_,module,exports){ +module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +},{}],113:[function(_dereq_,module,exports){ +var hide = _dereq_('./_hide'); +module.exports = function (target, src, safe) { + for (var key in src) { + if (safe && target[key]) target[key] = src[key]; + else hide(target, key, src[key]); + } return target; +}; + +},{"./_hide":80}],114:[function(_dereq_,module,exports){ +module.exports = _dereq_('./_hide'); + +},{"./_hide":80}],115:[function(_dereq_,module,exports){ +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ +var isObject = _dereq_('./_is-object'); +var anObject = _dereq_('./_an-object'); +var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); +}; +module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = _dereq_('./_ctx')(Function.call, _dereq_('./_object-gopd').f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check +}; + +},{"./_an-object":63,"./_ctx":69,"./_is-object":87,"./_object-gopd":101}],116:[function(_dereq_,module,exports){ +'use strict'; +var global = _dereq_('./_global'); +var core = _dereq_('./_core'); +var dP = _dereq_('./_object-dp'); +var DESCRIPTORS = _dereq_('./_descriptors'); +var SPECIES = _dereq_('./_wks')('species'); + +module.exports = function (KEY) { + var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); +}; + +},{"./_core":67,"./_descriptors":71,"./_global":78,"./_object-dp":99,"./_wks":132}],117:[function(_dereq_,module,exports){ +var def = _dereq_('./_object-dp').f; +var has = _dereq_('./_has'); +var TAG = _dereq_('./_wks')('toStringTag'); + +module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + +},{"./_has":79,"./_object-dp":99,"./_wks":132}],118:[function(_dereq_,module,exports){ +var shared = _dereq_('./_shared')('keys'); +var uid = _dereq_('./_uid'); +module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); +}; + +},{"./_shared":119,"./_uid":129}],119:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var SHARED = '__core-js_shared__'; +var store = global[SHARED] || (global[SHARED] = {}); +module.exports = function (key) { + return store[key] || (store[key] = {}); +}; + +},{"./_global":78}],120:[function(_dereq_,module,exports){ +// 7.3.20 SpeciesConstructor(O, defaultConstructor) +var anObject = _dereq_('./_an-object'); +var aFunction = _dereq_('./_a-function'); +var SPECIES = _dereq_('./_wks')('species'); +module.exports = function (O, D) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); +}; + +},{"./_a-function":60,"./_an-object":63,"./_wks":132}],121:[function(_dereq_,module,exports){ +var toInteger = _dereq_('./_to-integer'); +var defined = _dereq_('./_defined'); +// true -> String#at +// false -> String#codePointAt +module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +},{"./_defined":70,"./_to-integer":124}],122:[function(_dereq_,module,exports){ +var ctx = _dereq_('./_ctx'); +var invoke = _dereq_('./_invoke'); +var html = _dereq_('./_html'); +var cel = _dereq_('./_dom-create'); +var global = _dereq_('./_global'); +var process = global.process; +var setTask = global.setImmediate; +var clearTask = global.clearImmediate; +var MessageChannel = global.MessageChannel; +var Dispatch = global.Dispatch; +var counter = 0; +var queue = {}; +var ONREADYSTATECHANGE = 'onreadystatechange'; +var defer, channel, port; +var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; +var listener = function (event) { + run.call(event.data); +}; +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (_dereq_('./_cof')(process) == 'process') { + defer = function (id) { + process.nextTick(ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { + defer = function (id) { + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in cel('script')) { + defer = function (id) { + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(ctx(run, id, 1), 0); + }; + } +} +module.exports = { + set: setTask, + clear: clearTask +}; + +},{"./_cof":66,"./_ctx":69,"./_dom-create":72,"./_global":78,"./_html":81,"./_invoke":83}],123:[function(_dereq_,module,exports){ +var toInteger = _dereq_('./_to-integer'); +var max = Math.max; +var min = Math.min; +module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); +}; + +},{"./_to-integer":124}],124:[function(_dereq_,module,exports){ +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +},{}],125:[function(_dereq_,module,exports){ +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = _dereq_('./_iobject'); +var defined = _dereq_('./_defined'); +module.exports = function (it) { + return IObject(defined(it)); +}; + +},{"./_defined":70,"./_iobject":84}],126:[function(_dereq_,module,exports){ +// 7.1.15 ToLength +var toInteger = _dereq_('./_to-integer'); +var min = Math.min; +module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +},{"./_to-integer":124}],127:[function(_dereq_,module,exports){ +// 7.1.13 ToObject(argument) +var defined = _dereq_('./_defined'); +module.exports = function (it) { + return Object(defined(it)); +}; + +},{"./_defined":70}],128:[function(_dereq_,module,exports){ +// 7.1.1 ToPrimitive(input [, PreferredType]) +var isObject = _dereq_('./_is-object'); +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +},{"./_is-object":87}],129:[function(_dereq_,module,exports){ +var id = 0; +var px = Math.random(); +module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; + +},{}],130:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var core = _dereq_('./_core'); +var LIBRARY = _dereq_('./_library'); +var wksExt = _dereq_('./_wks-ext'); +var defineProperty = _dereq_('./_object-dp').f; +module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); +}; + +},{"./_core":67,"./_global":78,"./_library":94,"./_object-dp":99,"./_wks-ext":131}],131:[function(_dereq_,module,exports){ +exports.f = _dereq_('./_wks'); + +},{"./_wks":132}],132:[function(_dereq_,module,exports){ +var store = _dereq_('./_shared')('wks'); +var uid = _dereq_('./_uid'); +var Symbol = _dereq_('./_global').Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +$exports.store = store; + +},{"./_global":78,"./_shared":119,"./_uid":129}],133:[function(_dereq_,module,exports){ +var classof = _dereq_('./_classof'); +var ITERATOR = _dereq_('./_wks')('iterator'); +var Iterators = _dereq_('./_iterators'); +module.exports = _dereq_('./_core').getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; +}; + +},{"./_classof":65,"./_core":67,"./_iterators":93,"./_wks":132}],134:[function(_dereq_,module,exports){ +var anObject = _dereq_('./_an-object'); +var get = _dereq_('./core.get-iterator-method'); +module.exports = _dereq_('./_core').getIterator = function (it) { + var iterFn = get(it); + if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); + return anObject(iterFn.call(it)); +}; + +},{"./_an-object":63,"./_core":67,"./core.get-iterator-method":133}],135:[function(_dereq_,module,exports){ +var classof = _dereq_('./_classof'); +var ITERATOR = _dereq_('./_wks')('iterator'); +var Iterators = _dereq_('./_iterators'); +module.exports = _dereq_('./_core').isIterable = function (it) { + var O = Object(it); + return O[ITERATOR] !== undefined + || '@@iterator' in O + // eslint-disable-next-line no-prototype-builtins + || Iterators.hasOwnProperty(classof(O)); +}; + +},{"./_classof":65,"./_core":67,"./_iterators":93,"./_wks":132}],136:[function(_dereq_,module,exports){ +'use strict'; +var ctx = _dereq_('./_ctx'); +var $export = _dereq_('./_export'); +var toObject = _dereq_('./_to-object'); +var call = _dereq_('./_iter-call'); +var isArrayIter = _dereq_('./_is-array-iter'); +var toLength = _dereq_('./_to-length'); +var createProperty = _dereq_('./_create-property'); +var getIterFn = _dereq_('./core.get-iterator-method'); + +$export($export.S + $export.F * !_dereq_('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } +}); + +},{"./_create-property":68,"./_ctx":69,"./_export":75,"./_is-array-iter":85,"./_iter-call":88,"./_iter-detect":91,"./_to-length":126,"./_to-object":127,"./core.get-iterator-method":133}],137:[function(_dereq_,module,exports){ +'use strict'; +var addToUnscopables = _dereq_('./_add-to-unscopables'); +var step = _dereq_('./_iter-step'); +var Iterators = _dereq_('./_iterators'); +var toIObject = _dereq_('./_to-iobject'); + +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +module.exports = _dereq_('./_iter-define')(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); +}, 'values'); + +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +Iterators.Arguments = Iterators.Array; + +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); + +},{"./_add-to-unscopables":61,"./_iter-define":90,"./_iter-step":92,"./_iterators":93,"./_to-iobject":125}],138:[function(_dereq_,module,exports){ +var $export = _dereq_('./_export'); +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +$export($export.S, 'Object', { create: _dereq_('./_object-create') }); + +},{"./_export":75,"./_object-create":98}],139:[function(_dereq_,module,exports){ +var $export = _dereq_('./_export'); +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +$export($export.S + $export.F * !_dereq_('./_descriptors'), 'Object', { defineProperty: _dereq_('./_object-dp').f }); + +},{"./_descriptors":71,"./_export":75,"./_object-dp":99}],140:[function(_dereq_,module,exports){ +// 19.1.2.5 Object.freeze(O) +var isObject = _dereq_('./_is-object'); +var meta = _dereq_('./_meta').onFreeze; + +_dereq_('./_object-sap')('freeze', function ($freeze) { + return function freeze(it) { + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; +}); + +},{"./_is-object":87,"./_meta":95,"./_object-sap":109}],141:[function(_dereq_,module,exports){ +// 19.1.2.9 Object.getPrototypeOf(O) +var toObject = _dereq_('./_to-object'); +var $getPrototypeOf = _dereq_('./_object-gpo'); + +_dereq_('./_object-sap')('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return $getPrototypeOf(toObject(it)); + }; +}); + +},{"./_object-gpo":105,"./_object-sap":109,"./_to-object":127}],142:[function(_dereq_,module,exports){ +// 19.1.3.19 Object.setPrototypeOf(O, proto) +var $export = _dereq_('./_export'); +$export($export.S, 'Object', { setPrototypeOf: _dereq_('./_set-proto').set }); + +},{"./_export":75,"./_set-proto":115}],143:[function(_dereq_,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"dup":39}],144:[function(_dereq_,module,exports){ +'use strict'; +var LIBRARY = _dereq_('./_library'); +var global = _dereq_('./_global'); +var ctx = _dereq_('./_ctx'); +var classof = _dereq_('./_classof'); +var $export = _dereq_('./_export'); +var isObject = _dereq_('./_is-object'); +var aFunction = _dereq_('./_a-function'); +var anInstance = _dereq_('./_an-instance'); +var forOf = _dereq_('./_for-of'); +var speciesConstructor = _dereq_('./_species-constructor'); +var task = _dereq_('./_task').set; +var microtask = _dereq_('./_microtask')(); +var newPromiseCapabilityModule = _dereq_('./_new-promise-capability'); +var perform = _dereq_('./_perform'); +var promiseResolve = _dereq_('./_promise-resolve'); +var PROMISE = 'Promise'; +var TypeError = global.TypeError; +var process = global.process; +var $Promise = global[PROMISE]; +var isNode = classof(process) == 'process'; +var empty = function () { /* empty */ }; +var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; +var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; + +var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[_dereq_('./_wks')('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; + } catch (e) { /* empty */ } +}(); + +// helpers +var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); + if (domain) domain.exit(); + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); +}; +var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); +}; +var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; +}; +var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); +}; +var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); +}; +var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } +}; + +// constructor polyfill +if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = _dereq_('./_redefine-all')($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; +} + +$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); +_dereq_('./_set-to-string-tag')($Promise, PROMISE); +_dereq_('./_set-species')(PROMISE); +Wrapper = _dereq_('./_core')[PROMISE]; + +// statics +$export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } +}); +$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); + } +}); +$export($export.S + $export.F * !(USE_NATIVE && _dereq_('./_iter-detect')(function (iter) { + $Promise.all(iter)['catch'](empty); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } +}); + +},{"./_a-function":60,"./_an-instance":62,"./_classof":65,"./_core":67,"./_ctx":69,"./_export":75,"./_for-of":77,"./_global":78,"./_is-object":87,"./_iter-detect":91,"./_library":94,"./_microtask":96,"./_new-promise-capability":97,"./_perform":110,"./_promise-resolve":111,"./_redefine-all":113,"./_set-species":116,"./_set-to-string-tag":117,"./_species-constructor":120,"./_task":122,"./_wks":132}],145:[function(_dereq_,module,exports){ +'use strict'; +var $at = _dereq_('./_string-at')(true); + +// 21.1.3.27 String.prototype[@@iterator]() +_dereq_('./_iter-define')(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +},{"./_iter-define":90,"./_string-at":121}],146:[function(_dereq_,module,exports){ +'use strict'; +// ECMAScript 6 symbols shim +var global = _dereq_('./_global'); +var has = _dereq_('./_has'); +var DESCRIPTORS = _dereq_('./_descriptors'); +var $export = _dereq_('./_export'); +var redefine = _dereq_('./_redefine'); +var META = _dereq_('./_meta').KEY; +var $fails = _dereq_('./_fails'); +var shared = _dereq_('./_shared'); +var setToStringTag = _dereq_('./_set-to-string-tag'); +var uid = _dereq_('./_uid'); +var wks = _dereq_('./_wks'); +var wksExt = _dereq_('./_wks-ext'); +var wksDefine = _dereq_('./_wks-define'); +var enumKeys = _dereq_('./_enum-keys'); +var isArray = _dereq_('./_is-array'); +var anObject = _dereq_('./_an-object'); +var isObject = _dereq_('./_is-object'); +var toIObject = _dereq_('./_to-iobject'); +var toPrimitive = _dereq_('./_to-primitive'); +var createDesc = _dereq_('./_property-desc'); +var _create = _dereq_('./_object-create'); +var gOPNExt = _dereq_('./_object-gopn-ext'); +var $GOPD = _dereq_('./_object-gopd'); +var $DP = _dereq_('./_object-dp'); +var $keys = _dereq_('./_object-keys'); +var gOPD = $GOPD.f; +var dP = $DP.f; +var gOPN = gOPNExt.f; +var $Symbol = global.Symbol; +var $JSON = global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE = 'prototype'; +var HIDDEN = wks('_hidden'); +var TO_PRIMITIVE = wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = shared('symbol-registry'); +var AllSymbols = shared('symbols'); +var OPSymbols = shared('op-symbols'); +var ObjectProto = Object[PROTOTYPE]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); +} : dP; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + _dereq_('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames; + _dereq_('./_object-pie').f = $propertyIsEnumerable; + _dereq_('./_object-gops').f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !_dereq_('./_library')) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; +} + +$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + +for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + +$export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +$export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +setToStringTag(global.JSON, 'JSON', true); + +},{"./_an-object":63,"./_descriptors":71,"./_enum-keys":74,"./_export":75,"./_fails":76,"./_global":78,"./_has":79,"./_hide":80,"./_is-array":86,"./_is-object":87,"./_library":94,"./_meta":95,"./_object-create":98,"./_object-dp":99,"./_object-gopd":101,"./_object-gopn":103,"./_object-gopn-ext":102,"./_object-gops":104,"./_object-keys":107,"./_object-pie":108,"./_property-desc":112,"./_redefine":114,"./_set-to-string-tag":117,"./_shared":119,"./_to-iobject":125,"./_to-primitive":128,"./_uid":129,"./_wks":132,"./_wks-define":130,"./_wks-ext":131}],147:[function(_dereq_,module,exports){ +// https://github.com/tc39/proposal-promise-finally +'use strict'; +var $export = _dereq_('./_export'); +var core = _dereq_('./_core'); +var global = _dereq_('./_global'); +var speciesConstructor = _dereq_('./_species-constructor'); +var promiseResolve = _dereq_('./_promise-resolve'); + +$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { + var C = speciesConstructor(this, core.Promise || global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); +} }); + +},{"./_core":67,"./_export":75,"./_global":78,"./_promise-resolve":111,"./_species-constructor":120}],148:[function(_dereq_,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-promise-try +var $export = _dereq_('./_export'); +var newPromiseCapability = _dereq_('./_new-promise-capability'); +var perform = _dereq_('./_perform'); + +$export($export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = newPromiseCapability.f(this); + var result = perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; +} }); + +},{"./_export":75,"./_new-promise-capability":97,"./_perform":110}],149:[function(_dereq_,module,exports){ +_dereq_('./_wks-define')('asyncIterator'); + +},{"./_wks-define":130}],150:[function(_dereq_,module,exports){ +_dereq_('./_wks-define')('observable'); + +},{"./_wks-define":130}],151:[function(_dereq_,module,exports){ +_dereq_('./es6.array.iterator'); +var global = _dereq_('./_global'); +var hide = _dereq_('./_hide'); +var Iterators = _dereq_('./_iterators'); +var TO_STRING_TAG = _dereq_('./_wks')('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = Iterators.Array; +} + +},{"./_global":78,"./_hide":80,"./_iterators":93,"./_wks":132,"./es6.array.iterator":137}],152:[function(_dereq_,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],153:[function(_dereq_,module,exports){ +// 22.1.3.31 Array.prototype[@@unscopables] +var UNSCOPABLES = _dereq_('./_wks')('unscopables'); +var ArrayProto = Array.prototype; +if (ArrayProto[UNSCOPABLES] == undefined) _dereq_('./_hide')(ArrayProto, UNSCOPABLES, {}); +module.exports = function (key) { + ArrayProto[UNSCOPABLES][key] = true; +}; + +},{"./_hide":177,"./_wks":232}],154:[function(_dereq_,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"dup":62}],155:[function(_dereq_,module,exports){ +arguments[4][63][0].apply(exports,arguments) +},{"./_is-object":184,"dup":63}],156:[function(_dereq_,module,exports){ +// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) +'use strict'; +var toObject = _dereq_('./_to-object'); +var toAbsoluteIndex = _dereq_('./_to-absolute-index'); +var toLength = _dereq_('./_to-length'); + +module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; +}; + +},{"./_to-absolute-index":219,"./_to-length":223,"./_to-object":224}],157:[function(_dereq_,module,exports){ +// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) +'use strict'; +var toObject = _dereq_('./_to-object'); +var toAbsoluteIndex = _dereq_('./_to-absolute-index'); +var toLength = _dereq_('./_to-length'); +module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var aLen = arguments.length; + var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); + var end = aLen > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; +}; + +},{"./_to-absolute-index":219,"./_to-length":223,"./_to-object":224}],158:[function(_dereq_,module,exports){ +arguments[4][64][0].apply(exports,arguments) +},{"./_to-absolute-index":219,"./_to-iobject":222,"./_to-length":223,"dup":64}],159:[function(_dereq_,module,exports){ +// 0 -> Array#forEach +// 1 -> Array#map +// 2 -> Array#filter +// 3 -> Array#some +// 4 -> Array#every +// 5 -> Array#find +// 6 -> Array#findIndex +var ctx = _dereq_('./_ctx'); +var IObject = _dereq_('./_iobject'); +var toObject = _dereq_('./_to-object'); +var toLength = _dereq_('./_to-length'); +var asc = _dereq_('./_array-species-create'); +module.exports = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || asc; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IObject(O); + var f = ctx(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; +}; + +},{"./_array-species-create":161,"./_ctx":166,"./_iobject":181,"./_to-length":223,"./_to-object":224}],160:[function(_dereq_,module,exports){ +var isObject = _dereq_('./_is-object'); +var isArray = _dereq_('./_is-array'); +var SPECIES = _dereq_('./_wks')('species'); + +module.exports = function (original) { + var C; + if (isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; +}; + +},{"./_is-array":183,"./_is-object":184,"./_wks":232}],161:[function(_dereq_,module,exports){ +// 9.4.2.3 ArraySpeciesCreate(originalArray, length) +var speciesConstructor = _dereq_('./_array-species-constructor'); + +module.exports = function (original, length) { + return new (speciesConstructor(original))(length); +}; + +},{"./_array-species-constructor":160}],162:[function(_dereq_,module,exports){ +arguments[4][65][0].apply(exports,arguments) +},{"./_cof":163,"./_wks":232,"dup":65}],163:[function(_dereq_,module,exports){ +arguments[4][66][0].apply(exports,arguments) +},{"dup":66}],164:[function(_dereq_,module,exports){ +arguments[4][67][0].apply(exports,arguments) +},{"dup":67}],165:[function(_dereq_,module,exports){ +arguments[4][68][0].apply(exports,arguments) +},{"./_object-dp":196,"./_property-desc":208,"dup":68}],166:[function(_dereq_,module,exports){ +arguments[4][69][0].apply(exports,arguments) +},{"./_a-function":152,"dup":69}],167:[function(_dereq_,module,exports){ +arguments[4][70][0].apply(exports,arguments) +},{"dup":70}],168:[function(_dereq_,module,exports){ +arguments[4][71][0].apply(exports,arguments) +},{"./_fails":173,"dup":71}],169:[function(_dereq_,module,exports){ +arguments[4][72][0].apply(exports,arguments) +},{"./_global":175,"./_is-object":184,"dup":72}],170:[function(_dereq_,module,exports){ +arguments[4][73][0].apply(exports,arguments) +},{"dup":73}],171:[function(_dereq_,module,exports){ +arguments[4][74][0].apply(exports,arguments) +},{"./_object-gops":201,"./_object-keys":204,"./_object-pie":205,"dup":74}],172:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var core = _dereq_('./_core'); +var hide = _dereq_('./_hide'); +var redefine = _dereq_('./_redefine'); +var ctx = _dereq_('./_ctx'); +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if (target) redefine(target, key, out, type & $export.U); + // export + if (exports[key] != out) hide(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } +}; +global.core = core; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; + +},{"./_core":164,"./_ctx":166,"./_global":175,"./_hide":177,"./_redefine":210}],173:[function(_dereq_,module,exports){ +arguments[4][76][0].apply(exports,arguments) +},{"dup":76}],174:[function(_dereq_,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"./_an-object":155,"./_ctx":166,"./_is-array-iter":182,"./_iter-call":185,"./_to-length":223,"./core.get-iterator-method":233,"dup":77}],175:[function(_dereq_,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],176:[function(_dereq_,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"dup":79}],177:[function(_dereq_,module,exports){ +arguments[4][80][0].apply(exports,arguments) +},{"./_descriptors":168,"./_object-dp":196,"./_property-desc":208,"dup":80}],178:[function(_dereq_,module,exports){ +arguments[4][81][0].apply(exports,arguments) +},{"./_global":175,"dup":81}],179:[function(_dereq_,module,exports){ +arguments[4][82][0].apply(exports,arguments) +},{"./_descriptors":168,"./_dom-create":169,"./_fails":173,"dup":82}],180:[function(_dereq_,module,exports){ +arguments[4][83][0].apply(exports,arguments) +},{"dup":83}],181:[function(_dereq_,module,exports){ +arguments[4][84][0].apply(exports,arguments) +},{"./_cof":163,"dup":84}],182:[function(_dereq_,module,exports){ +arguments[4][85][0].apply(exports,arguments) +},{"./_iterators":190,"./_wks":232,"dup":85}],183:[function(_dereq_,module,exports){ +arguments[4][86][0].apply(exports,arguments) +},{"./_cof":163,"dup":86}],184:[function(_dereq_,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],185:[function(_dereq_,module,exports){ +arguments[4][88][0].apply(exports,arguments) +},{"./_an-object":155,"dup":88}],186:[function(_dereq_,module,exports){ +arguments[4][89][0].apply(exports,arguments) +},{"./_hide":177,"./_object-create":195,"./_property-desc":208,"./_set-to-string-tag":212,"./_wks":232,"dup":89}],187:[function(_dereq_,module,exports){ +arguments[4][90][0].apply(exports,arguments) +},{"./_export":172,"./_has":176,"./_hide":177,"./_iter-create":186,"./_iterators":190,"./_library":191,"./_object-gpo":202,"./_redefine":210,"./_set-to-string-tag":212,"./_wks":232,"dup":90}],188:[function(_dereq_,module,exports){ +arguments[4][91][0].apply(exports,arguments) +},{"./_wks":232,"dup":91}],189:[function(_dereq_,module,exports){ +arguments[4][92][0].apply(exports,arguments) +},{"dup":92}],190:[function(_dereq_,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93}],191:[function(_dereq_,module,exports){ +module.exports = false; + +},{}],192:[function(_dereq_,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"./_fails":173,"./_has":176,"./_is-object":184,"./_object-dp":196,"./_uid":229,"dup":95}],193:[function(_dereq_,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./_cof":163,"./_global":175,"./_task":218,"dup":96}],194:[function(_dereq_,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./_a-function":152,"dup":97}],195:[function(_dereq_,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"./_an-object":155,"./_dom-create":169,"./_enum-bug-keys":170,"./_html":178,"./_object-dps":197,"./_shared-key":213,"dup":98}],196:[function(_dereq_,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"./_an-object":155,"./_descriptors":168,"./_ie8-dom-define":179,"./_to-primitive":225,"dup":99}],197:[function(_dereq_,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./_an-object":155,"./_descriptors":168,"./_object-dp":196,"./_object-keys":204,"dup":100}],198:[function(_dereq_,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"./_descriptors":168,"./_has":176,"./_ie8-dom-define":179,"./_object-pie":205,"./_property-desc":208,"./_to-iobject":222,"./_to-primitive":225,"dup":101}],199:[function(_dereq_,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"./_object-gopn":200,"./_to-iobject":222,"dup":102}],200:[function(_dereq_,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"./_enum-bug-keys":170,"./_object-keys-internal":203,"dup":103}],201:[function(_dereq_,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],202:[function(_dereq_,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"./_has":176,"./_shared-key":213,"./_to-object":224,"dup":105}],203:[function(_dereq_,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./_array-includes":158,"./_has":176,"./_shared-key":213,"./_to-iobject":222,"dup":106}],204:[function(_dereq_,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"./_enum-bug-keys":170,"./_object-keys-internal":203,"dup":107}],205:[function(_dereq_,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],206:[function(_dereq_,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"dup":110}],207:[function(_dereq_,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"./_an-object":155,"./_is-object":184,"./_new-promise-capability":194,"dup":111}],208:[function(_dereq_,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"dup":112}],209:[function(_dereq_,module,exports){ +var redefine = _dereq_('./_redefine'); +module.exports = function (target, src, safe) { + for (var key in src) redefine(target, key, src[key], safe); + return target; +}; + +},{"./_redefine":210}],210:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var hide = _dereq_('./_hide'); +var has = _dereq_('./_has'); +var SRC = _dereq_('./_uid')('src'); +var TO_STRING = 'toString'; +var $toString = Function[TO_STRING]; +var TPL = ('' + $toString).split(TO_STRING); + +_dereq_('./_core').inspectSource = function (it) { + return $toString.call(it); +}; + +(module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) has(val, 'name') || hide(val, 'name', key); + if (O[key] === val) return; + if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + hide(O, key, val); + } +// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative +})(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); +}); + +},{"./_core":164,"./_global":175,"./_has":176,"./_hide":177,"./_uid":229}],211:[function(_dereq_,module,exports){ +'use strict'; +var global = _dereq_('./_global'); +var dP = _dereq_('./_object-dp'); +var DESCRIPTORS = _dereq_('./_descriptors'); +var SPECIES = _dereq_('./_wks')('species'); + +module.exports = function (KEY) { + var C = global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); +}; + +},{"./_descriptors":168,"./_global":175,"./_object-dp":196,"./_wks":232}],212:[function(_dereq_,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./_has":176,"./_object-dp":196,"./_wks":232,"dup":117}],213:[function(_dereq_,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"./_shared":214,"./_uid":229,"dup":118}],214:[function(_dereq_,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./_global":175,"dup":119}],215:[function(_dereq_,module,exports){ +arguments[4][120][0].apply(exports,arguments) +},{"./_a-function":152,"./_an-object":155,"./_wks":232,"dup":120}],216:[function(_dereq_,module,exports){ +arguments[4][121][0].apply(exports,arguments) +},{"./_defined":167,"./_to-integer":221,"dup":121}],217:[function(_dereq_,module,exports){ +'use strict'; +var toInteger = _dereq_('./_to-integer'); +var defined = _dereq_('./_defined'); + +module.exports = function repeat(count) { + var str = String(defined(this)); + var res = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; + return res; +}; + +},{"./_defined":167,"./_to-integer":221}],218:[function(_dereq_,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"./_cof":163,"./_ctx":166,"./_dom-create":169,"./_global":175,"./_html":178,"./_invoke":180,"dup":122}],219:[function(_dereq_,module,exports){ +arguments[4][123][0].apply(exports,arguments) +},{"./_to-integer":221,"dup":123}],220:[function(_dereq_,module,exports){ +// https://tc39.github.io/ecma262/#sec-toindex +var toInteger = _dereq_('./_to-integer'); +var toLength = _dereq_('./_to-length'); +module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length!'); + return length; +}; + +},{"./_to-integer":221,"./_to-length":223}],221:[function(_dereq_,module,exports){ +arguments[4][124][0].apply(exports,arguments) +},{"dup":124}],222:[function(_dereq_,module,exports){ +arguments[4][125][0].apply(exports,arguments) +},{"./_defined":167,"./_iobject":181,"dup":125}],223:[function(_dereq_,module,exports){ +arguments[4][126][0].apply(exports,arguments) +},{"./_to-integer":221,"dup":126}],224:[function(_dereq_,module,exports){ +arguments[4][127][0].apply(exports,arguments) +},{"./_defined":167,"dup":127}],225:[function(_dereq_,module,exports){ +arguments[4][128][0].apply(exports,arguments) +},{"./_is-object":184,"dup":128}],226:[function(_dereq_,module,exports){ +'use strict'; +if (_dereq_('./_descriptors')) { + var LIBRARY = _dereq_('./_library'); + var global = _dereq_('./_global'); + var fails = _dereq_('./_fails'); + var $export = _dereq_('./_export'); + var $typed = _dereq_('./_typed'); + var $buffer = _dereq_('./_typed-buffer'); + var ctx = _dereq_('./_ctx'); + var anInstance = _dereq_('./_an-instance'); + var propertyDesc = _dereq_('./_property-desc'); + var hide = _dereq_('./_hide'); + var redefineAll = _dereq_('./_redefine-all'); + var toInteger = _dereq_('./_to-integer'); + var toLength = _dereq_('./_to-length'); + var toIndex = _dereq_('./_to-index'); + var toAbsoluteIndex = _dereq_('./_to-absolute-index'); + var toPrimitive = _dereq_('./_to-primitive'); + var has = _dereq_('./_has'); + var classof = _dereq_('./_classof'); + var isObject = _dereq_('./_is-object'); + var toObject = _dereq_('./_to-object'); + var isArrayIter = _dereq_('./_is-array-iter'); + var create = _dereq_('./_object-create'); + var getPrototypeOf = _dereq_('./_object-gpo'); + var gOPN = _dereq_('./_object-gopn').f; + var getIterFn = _dereq_('./core.get-iterator-method'); + var uid = _dereq_('./_uid'); + var wks = _dereq_('./_wks'); + var createArrayMethod = _dereq_('./_array-methods'); + var createArrayIncludes = _dereq_('./_array-includes'); + var speciesConstructor = _dereq_('./_species-constructor'); + var ArrayIterators = _dereq_('./es6.array.iterator'); + var Iterators = _dereq_('./_iterators'); + var $iterDetect = _dereq_('./_iter-detect'); + var setSpecies = _dereq_('./_set-species'); + var arrayFill = _dereq_('./_array-fill'); + var arrayCopyWithin = _dereq_('./_array-copy-within'); + var $DP = _dereq_('./_object-dp'); + var $GOPD = _dereq_('./_object-gopd'); + var dP = $DP.f; + var gOPD = $GOPD.f; + var RangeError = global.RangeError; + var TypeError = global.TypeError; + var Uint8Array = global.Uint8Array; + var ARRAY_BUFFER = 'ArrayBuffer'; + var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var PROTOTYPE = 'prototype'; + var ArrayProto = Array[PROTOTYPE]; + var $ArrayBuffer = $buffer.ArrayBuffer; + var $DataView = $buffer.DataView; + var arrayForEach = createArrayMethod(0); + var arrayFilter = createArrayMethod(2); + var arraySome = createArrayMethod(3); + var arrayEvery = createArrayMethod(4); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var arrayIncludes = createArrayIncludes(true); + var arrayIndexOf = createArrayIncludes(false); + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var arrayLastIndexOf = ArrayProto.lastIndexOf; + var arrayReduce = ArrayProto.reduce; + var arrayReduceRight = ArrayProto.reduceRight; + var arrayJoin = ArrayProto.join; + var arraySort = ArrayProto.sort; + var arraySlice = ArrayProto.slice; + var arrayToString = ArrayProto.toString; + var arrayToLocaleString = ArrayProto.toLocaleString; + var ITERATOR = wks('iterator'); + var TAG = wks('toStringTag'); + var TYPED_CONSTRUCTOR = uid('typed_constructor'); + var DEF_CONSTRUCTOR = uid('def_constructor'); + var ALL_CONSTRUCTORS = $typed.CONSTR; + var TYPED_ARRAY = $typed.TYPED; + var VIEW = $typed.VIEW; + var WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function (O, length) { + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function () { + // eslint-disable-next-line no-undef + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { + new Uint8Array(1).set({}); + }); + + var toOffset = function (it, BYTES) { + var offset = toInteger(it); + if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function (it) { + if (isObject(it) && TYPED_ARRAY in it) return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function (C, length) { + if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function (O, list) { + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = allocate(C, length); + while (length > index) result[index] = list[index++]; + return result; + }; + + var addGetter = function (it, key, internal) { + dP(it, key, { get: function () { return this._d[internal]; } }); + }; + + var $from = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iterFn = getIterFn(O); + var i, length, values, result, step, iterator; + if (iterFn != undefined && !isArrayIter(iterFn)) { + for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { + values.push(step.value); + } O = values; + } + if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); + for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = allocate(this, length); + while (length > index) result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString() { + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /* , end */) { + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /* , thisArg */) { + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /* , thisArg */) { + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /* , thisArg */) { + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /* , thisArg */) { + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /* , thisArg */) { + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /* , fromIndex */) { + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /* , fromIndex */) { + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator) { // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /* , thisArg */) { + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse() { + var that = this; + var length = validate(that).length; + var middle = Math.floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /* , thisArg */) { + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn) { + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end) { + var O = validate(this); + var length = O.length; + var $begin = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end) { + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /* , offset */) { + validate(this); + var offset = toOffset(arguments[1], 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError(WRONG_LENGTH); + while (index < len) this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries() { + return arrayEntries.call(validate(this)); + }, + keys: function keys() { + return arrayKeys.call(validate(this)); + }, + values: function values() { + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function (target, key) { + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key) { + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc) { + if (isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ) { + target[key] = desc.value; + return target; + } return dP(target, key, desc); + }; + + if (!ALL_CONSTRUCTORS) { + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if (fails(function () { arrayToString.call({}); })) { + arrayToString = arrayToLocaleString = function toString() { + return arrayJoin.call(this); + }; + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function () { /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function () { return this[TYPED_ARRAY]; } + }); + + // eslint-disable-next-line max-statements + module.exports = function (KEY, BYTES, wrapper, CLAMPED) { + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + KEY; + var SETTER = 'set' + KEY; + var TypedArray = global[NAME]; + var Base = TypedArray || {}; + var TAC = TypedArray && getPrototypeOf(TypedArray); + var FORCED = !TypedArray || !$typed.ABV; + var O = {}; + var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function (that, index) { + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function (that, index, value) { + var data = that._d; + if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function (that, index) { + dP(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (FORCED) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME, '_d'); + var index = 0; + var offset = 0; + var buffer, byteLength, length, klass; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (TYPED_ARRAY in data) { + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if (!fails(function () { + TypedArray(1); + }) || !fails(function () { + new TypedArray(-1); // eslint-disable-line no-new + }) || !$iterDetect(function (iter) { + new TypedArray(); // eslint-disable-line no-new + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(1.5); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if (!isObject(data)) return new Base(toIndex(data)); + if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if (TYPED_ARRAY in data) return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { + if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR]; + var CORRECT_ITER_NAME = !!$nativeIterator + && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); + var $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { + dP(TypedArrayPrototype, TAG, { + get: function () { return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES + }); + + $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { + from: $from, + of: $of + }); + + if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; + + $export($export.P + $export.F * fails(function () { + new TypedArray(1).slice(); + }), NAME, { slice: $slice }); + + $export($export.P + $export.F * (fails(function () { + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); + }) || !fails(function () { + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, { toLocaleString: $toLocaleString }); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); + }; +} else module.exports = function () { /* empty */ }; + +},{"./_an-instance":154,"./_array-copy-within":156,"./_array-fill":157,"./_array-includes":158,"./_array-methods":159,"./_classof":162,"./_ctx":166,"./_descriptors":168,"./_export":172,"./_fails":173,"./_global":175,"./_has":176,"./_hide":177,"./_is-array-iter":182,"./_is-object":184,"./_iter-detect":188,"./_iterators":190,"./_library":191,"./_object-create":195,"./_object-dp":196,"./_object-gopd":198,"./_object-gopn":200,"./_object-gpo":202,"./_property-desc":208,"./_redefine-all":209,"./_set-species":211,"./_species-constructor":215,"./_to-absolute-index":219,"./_to-index":220,"./_to-integer":221,"./_to-length":223,"./_to-object":224,"./_to-primitive":225,"./_typed":228,"./_typed-buffer":227,"./_uid":229,"./_wks":232,"./core.get-iterator-method":233,"./es6.array.iterator":237}],227:[function(_dereq_,module,exports){ +'use strict'; +var global = _dereq_('./_global'); +var DESCRIPTORS = _dereq_('./_descriptors'); +var LIBRARY = _dereq_('./_library'); +var $typed = _dereq_('./_typed'); +var hide = _dereq_('./_hide'); +var redefineAll = _dereq_('./_redefine-all'); +var fails = _dereq_('./_fails'); +var anInstance = _dereq_('./_an-instance'); +var toInteger = _dereq_('./_to-integer'); +var toLength = _dereq_('./_to-length'); +var toIndex = _dereq_('./_to-index'); +var gOPN = _dereq_('./_object-gopn').f; +var dP = _dereq_('./_object-dp').f; +var arrayFill = _dereq_('./_array-fill'); +var setToStringTag = _dereq_('./_set-to-string-tag'); +var ARRAY_BUFFER = 'ArrayBuffer'; +var DATA_VIEW = 'DataView'; +var PROTOTYPE = 'prototype'; +var WRONG_LENGTH = 'Wrong length!'; +var WRONG_INDEX = 'Wrong index!'; +var $ArrayBuffer = global[ARRAY_BUFFER]; +var $DataView = global[DATA_VIEW]; +var Math = global.Math; +var RangeError = global.RangeError; +// eslint-disable-next-line no-shadow-restricted-names +var Infinity = global.Infinity; +var BaseBuffer = $ArrayBuffer; +var abs = Math.abs; +var pow = Math.pow; +var floor = Math.floor; +var log = Math.log; +var LN2 = Math.LN2; +var BUFFER = 'buffer'; +var BYTE_LENGTH = 'byteLength'; +var BYTE_OFFSET = 'byteOffset'; +var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; +var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; +var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + +// IEEE754 conversions based on https://github.com/feross/ieee754 +function packIEEE754(value, mLen, nBytes) { + var buffer = new Array(nBytes); + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; + var i = 0; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + var e, m, c; + value = abs(value); + // eslint-disable-next-line no-self-compare + if (value != value || value === Infinity) { + // eslint-disable-next-line no-self-compare + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if (value * (c = pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; +} +function unpackIEEE754(buffer, mLen, nBytes) { + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = eLen - 7; + var i = nBytes - 1; + var s = buffer[i--]; + var e = s & 127; + var m; + s >>= 7; + for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); +} + +function unpackI32(bytes) { + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; +} +function packI8(it) { + return [it & 0xff]; +} +function packI16(it) { + return [it & 0xff, it >> 8 & 0xff]; +} +function packI32(it) { + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; +} +function packF64(it) { + return packIEEE754(it, 52, 8); +} +function packF32(it) { + return packIEEE754(it, 23, 4); +} + +function addGetter(C, key, internal) { + dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); +} + +function get(view, bytes, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); +} +function set(view, bytes, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = conversion(+value); + for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; +} + +if (!$typed.ABV) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + this._b = arrayFill.call(new Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH]; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); +} else { + if (!fails(function () { + $ArrayBuffer(1); + }) || !fails(function () { + new $ArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new $ArrayBuffer(); // eslint-disable-line no-new + new $ArrayBuffer(1.5); // eslint-disable-line no-new + new $ArrayBuffer(NaN); // eslint-disable-line no-new + return $ArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new BaseBuffer(toIndex(length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); + } + if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); +} +setToStringTag($ArrayBuffer, ARRAY_BUFFER); +setToStringTag($DataView, DATA_VIEW); +hide($DataView[PROTOTYPE], $typed.VIEW, true); +exports[ARRAY_BUFFER] = $ArrayBuffer; +exports[DATA_VIEW] = $DataView; + +},{"./_an-instance":154,"./_array-fill":157,"./_descriptors":168,"./_fails":173,"./_global":175,"./_hide":177,"./_library":191,"./_object-dp":196,"./_object-gopn":200,"./_redefine-all":209,"./_set-to-string-tag":212,"./_to-index":220,"./_to-integer":221,"./_to-length":223,"./_typed":228}],228:[function(_dereq_,module,exports){ +var global = _dereq_('./_global'); +var hide = _dereq_('./_hide'); +var uid = _dereq_('./_uid'); +var TYPED = uid('typed_array'); +var VIEW = uid('view'); +var ABV = !!(global.ArrayBuffer && global.DataView); +var CONSTR = ABV; +var i = 0; +var l = 9; +var Typed; + +var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' +).split(','); + +while (i < l) { + if (Typed = global[TypedArrayConstructors[i++]]) { + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; +} + +module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW +}; + +},{"./_global":175,"./_hide":177,"./_uid":229}],229:[function(_dereq_,module,exports){ +arguments[4][129][0].apply(exports,arguments) +},{"dup":129}],230:[function(_dereq_,module,exports){ +arguments[4][130][0].apply(exports,arguments) +},{"./_core":164,"./_global":175,"./_library":191,"./_object-dp":196,"./_wks-ext":231,"dup":130}],231:[function(_dereq_,module,exports){ +arguments[4][131][0].apply(exports,arguments) +},{"./_wks":232,"dup":131}],232:[function(_dereq_,module,exports){ +arguments[4][132][0].apply(exports,arguments) +},{"./_global":175,"./_shared":214,"./_uid":229,"dup":132}],233:[function(_dereq_,module,exports){ +arguments[4][133][0].apply(exports,arguments) +},{"./_classof":162,"./_core":164,"./_iterators":190,"./_wks":232,"dup":133}],234:[function(_dereq_,module,exports){ +// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) +var $export = _dereq_('./_export'); + +$export($export.P, 'Array', { fill: _dereq_('./_array-fill') }); + +_dereq_('./_add-to-unscopables')('fill'); + +},{"./_add-to-unscopables":153,"./_array-fill":157,"./_export":172}],235:[function(_dereq_,module,exports){ +'use strict'; +// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) +var $export = _dereq_('./_export'); +var $find = _dereq_('./_array-methods')(5); +var KEY = 'find'; +var forced = true; +// Shouldn't skip holes +if (KEY in []) Array(1)[KEY](function () { forced = false; }); +$export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); +_dereq_('./_add-to-unscopables')(KEY); + +},{"./_add-to-unscopables":153,"./_array-methods":159,"./_export":172}],236:[function(_dereq_,module,exports){ +arguments[4][136][0].apply(exports,arguments) +},{"./_create-property":165,"./_ctx":166,"./_export":172,"./_is-array-iter":182,"./_iter-call":185,"./_iter-detect":188,"./_to-length":223,"./_to-object":224,"./core.get-iterator-method":233,"dup":136}],237:[function(_dereq_,module,exports){ +arguments[4][137][0].apply(exports,arguments) +},{"./_add-to-unscopables":153,"./_iter-define":187,"./_iter-step":189,"./_iterators":190,"./_to-iobject":222,"dup":137}],238:[function(_dereq_,module,exports){ +'use strict'; +// 19.1.3.6 Object.prototype.toString() +var classof = _dereq_('./_classof'); +var test = {}; +test[_dereq_('./_wks')('toStringTag')] = 'z'; +if (test + '' != '[object z]') { + _dereq_('./_redefine')(Object.prototype, 'toString', function toString() { + return '[object ' + classof(this) + ']'; + }, true); +} + +},{"./_classof":162,"./_redefine":210,"./_wks":232}],239:[function(_dereq_,module,exports){ +arguments[4][144][0].apply(exports,arguments) +},{"./_a-function":152,"./_an-instance":154,"./_classof":162,"./_core":164,"./_ctx":166,"./_export":172,"./_for-of":174,"./_global":175,"./_is-object":184,"./_iter-detect":188,"./_library":191,"./_microtask":193,"./_new-promise-capability":194,"./_perform":206,"./_promise-resolve":207,"./_redefine-all":209,"./_set-species":211,"./_set-to-string-tag":212,"./_species-constructor":215,"./_task":218,"./_wks":232,"dup":144}],240:[function(_dereq_,module,exports){ +arguments[4][145][0].apply(exports,arguments) +},{"./_iter-define":187,"./_string-at":216,"dup":145}],241:[function(_dereq_,module,exports){ +var $export = _dereq_('./_export'); + +$export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: _dereq_('./_string-repeat') +}); + +},{"./_export":172,"./_string-repeat":217}],242:[function(_dereq_,module,exports){ +arguments[4][146][0].apply(exports,arguments) +},{"./_an-object":155,"./_descriptors":168,"./_enum-keys":171,"./_export":172,"./_fails":173,"./_global":175,"./_has":176,"./_hide":177,"./_is-array":183,"./_is-object":184,"./_library":191,"./_meta":192,"./_object-create":195,"./_object-dp":196,"./_object-gopd":198,"./_object-gopn":200,"./_object-gopn-ext":199,"./_object-gops":201,"./_object-keys":204,"./_object-pie":205,"./_property-desc":208,"./_redefine":210,"./_set-to-string-tag":212,"./_shared":214,"./_to-iobject":222,"./_to-primitive":225,"./_uid":229,"./_wks":232,"./_wks-define":230,"./_wks-ext":231,"dup":146}],243:[function(_dereq_,module,exports){ +_dereq_('./_typed-array')('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"./_typed-array":226}],244:[function(_dereq_,module,exports){ +arguments[4][147][0].apply(exports,arguments) +},{"./_core":164,"./_export":172,"./_global":175,"./_promise-resolve":207,"./_species-constructor":215,"dup":147}],245:[function(_dereq_,module,exports){ +arguments[4][148][0].apply(exports,arguments) +},{"./_export":172,"./_new-promise-capability":194,"./_perform":206,"dup":148}],246:[function(_dereq_,module,exports){ +arguments[4][149][0].apply(exports,arguments) +},{"./_wks-define":230,"dup":149}],247:[function(_dereq_,module,exports){ +arguments[4][150][0].apply(exports,arguments) +},{"./_wks-define":230,"dup":150}],248:[function(_dereq_,module,exports){ +var $iterators = _dereq_('./es6.array.iterator'); +var getKeys = _dereq_('./_object-keys'); +var redefine = _dereq_('./_redefine'); +var global = _dereq_('./_global'); +var hide = _dereq_('./_hide'); +var Iterators = _dereq_('./_iterators'); +var wks = _dereq_('./_wks'); +var ITERATOR = wks('iterator'); +var TO_STRING_TAG = wks('toStringTag'); +var ArrayValues = Iterators.Array; + +var DOMIterables = { + CSSRuleList: true, // TODO: Not spec compliant, should be false. + CSSStyleDeclaration: false, + CSSValueList: false, + ClientRectList: false, + DOMRectList: false, + DOMStringList: false, + DOMTokenList: true, + DataTransferItemList: false, + FileList: false, + HTMLAllCollection: false, + HTMLCollection: false, + HTMLFormElement: false, + HTMLSelectElement: false, + MediaList: true, // TODO: Not spec compliant, should be false. + MimeTypeArray: false, + NamedNodeMap: false, + NodeList: true, + PaintRequestList: false, + Plugin: false, + PluginArray: false, + SVGLengthList: false, + SVGNumberList: false, + SVGPathSegList: false, + SVGPointList: false, + SVGStringList: false, + SVGTransformList: false, + SourceBufferList: false, + StyleSheetList: true, // TODO: Not spec compliant, should be false. + TextTrackCueList: false, + TextTrackList: false, + TouchList: false +}; + +for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { + var NAME = collections[i]; + var explicit = DOMIterables[NAME]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + var key; + if (proto) { + if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); + if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); + } +} + +},{"./_global":175,"./_hide":177,"./_iterators":190,"./_object-keys":204,"./_redefine":210,"./_wks":232,"./es6.array.iterator":237}],249:[function(_dereq_,module,exports){ +'use strict'; + +var elliptic = exports; + +elliptic.version = _dereq_('../package.json').version; +elliptic.utils = _dereq_('./elliptic/utils'); +elliptic.rand = _dereq_('brorand'); +elliptic.curve = _dereq_('./elliptic/curve'); +elliptic.curves = _dereq_('./elliptic/curves'); + +// Protocols +elliptic.ec = _dereq_('./elliptic/ec'); +elliptic.eddsa = _dereq_('./elliptic/eddsa'); + +},{"../package.json":264,"./elliptic/curve":252,"./elliptic/curves":255,"./elliptic/ec":256,"./elliptic/eddsa":259,"./elliptic/utils":263,"brorand":38}],250:[function(_dereq_,module,exports){ +'use strict'; + +var BN = _dereq_('bn.js'); +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + + // Generalized Greg Maxwell's trick + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + +},{"../../elliptic":249,"bn.js":37}],251:[function(_dereq_,module,exports){ +'use strict'; + +var curve = _dereq_('../curve'); +var elliptic = _dereq_('../../elliptic'); +var BN = _dereq_('bn.js'); +var inherits = _dereq_('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.z).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + +},{"../../elliptic":249,"../curve":252,"bn.js":37,"inherits":279}],252:[function(_dereq_,module,exports){ +'use strict'; + +var curve = exports; + +curve.base = _dereq_('./base'); +curve.short = _dereq_('./short'); +curve.mont = _dereq_('./mont'); +curve.edwards = _dereq_('./edwards'); + +},{"./base":250,"./edwards":251,"./mont":253,"./short":254}],253:[function(_dereq_,module,exports){ +'use strict'; + +var curve = _dereq_('../curve'); +var BN = _dereq_('bn.js'); +var inherits = _dereq_('inherits'); +var Base = curve.base; + +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + // Note: this implementation is according to the original paper + // by P. Montgomery, NOT the one by D. J. Bernstein. + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + var bytes = utils.toArray(bytes, enc); + + // TODO Curve448 + // Montgomery curve points must be represented in the compressed format + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + if (bytes.length === 33 && bytes[0] === 0x40) + bytes = bytes.slice(1, 33).reverse(); // point must be little-endian + if (bytes.length !== 32) + throw new Error('Unknown point compression format'); + return this.point(bytes, 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + + // Note: the output should always be little-endian + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + if (compact) { + return [ 0x40 ].concat(this.getX().toArray('le', len)); + } else { + return this.getX().toArray('be', len); + } +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + +},{"../../elliptic":249,"../curve":252,"bn.js":37,"inherits":279}],254:[function(_dereq_,module,exports){ +'use strict'; + +var curve = _dereq_('../curve'); +var elliptic = _dereq_('../../elliptic'); +var BN = _dereq_('bn.js'); +var inherits = _dereq_('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +},{"../../elliptic":249,"../curve":252,"bn.js":37,"inherits":279}],255:[function(_dereq_,module,exports){ +'use strict'; + +var curves = exports; + +var hash = _dereq_('hash.js'); +var elliptic = _dereq_('../elliptic'); + +var assert = elliptic.utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new elliptic.curve.short(options); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else if (options.type === 'mont') + this.curve = new elliptic.curve.mont(options); + else throw new Error('Unknown curve type.'); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] +}); + +// https://tools.ietf.org/html/rfc7748#section-4.1 +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + cofactor: '8', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + cofactor: '8', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +var pre; +try { + pre = _dereq_('./precomputed/secp256k1'); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] +}); + +},{"../elliptic":249,"./precomputed/secp256k1":262,"hash.js":265}],256:[function(_dereq_,module,exports){ +'use strict'; + +var BN = _dereq_('bn.js'); +var HmacDRBG = _dereq_('hmac-drbg'); +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +var KeyPair = _dereq_('./key'); +var Signature = _dereq_('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = elliptic.curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray() + }); + + // Key generation for curve25519 is simpler + if (this.curve.type === 'mont') { + var priv = new BN(drbg.generate(32)); + return this.keyFromPrivate(priv); + } + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8' + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + if (!this.curve._maxwellTrick) { + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + var p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; + +},{"../../elliptic":249,"./key":257,"./signature":258,"bn.js":37,"hmac-drbg":277}],257:[function(_dereq_,module,exports){ +'use strict'; + +var BN = _dereq_('bn.js'); +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); +}; + +// TODO: should not validate for X25519 +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(enc, compact) { + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // For Curve25519/Curve448 we have a specific procedure. + // TODO Curve448 + if (this.ec.curve.type === 'mont') { + var one = this.ec.curve.one; + var mask = one.ushln(255 - 3).sub(one).ushln(3); + this.priv = this.priv.or(one.ushln(255 - 1)); + this.priv = this.priv.and(mask); + } else + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + var x = pub.mul(this.priv).getX(); + var len = x.byteLength(); + + // Note: this is not ideal, but the RFC's are unclear + // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B + if (this.ec.curve.type === 'mont') { + return x.toArray('le', len); + } else { + return x.toArray('be', len); + } +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + +},{"../../elliptic":249,"bn.js":37}],258:[function(_dereq_,module,exports){ +'use strict'; + +var BN = _dereq_('bn.js'); + +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; + +},{"../../elliptic":249,"bn.js":37}],259:[function(_dereq_,module,exports){ +'use strict'; + +var hash = _dereq_('hash.js'); +var HmacDRBG = _dereq_('hmac-drbg'); +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = _dereq_('./key'); +var Signature = _dereq_('./signature'); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.curve.n.toArray() + }); + + return this.keyFromSecret(drbg.generate(32)); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; + +},{"../../elliptic":249,"./key":260,"./signature":261,"hash.js":265,"hmac-drbg":277}],260:[function(_dereq_,module,exports){ +'use strict'; + +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + if (params.hasOwnProperty('secret')) + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else { + this._pubBytes = parseBytes(params.pub); + if (this._pubBytes && this._pubBytes.length === 33 && + this._pubBytes[0] === 0x40) + this._pubBytes = this._pubBytes.slice(1, 33); + if (this._pubBytes && this._pubBytes.length !== 32) + throw new Error('Unknown point compression format'); + } +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + // https://tools.ietf.org/html/rfc8032#section-5.1.5 + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc, compact) { + return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc); +}; + +module.exports = KeyPair; + +},{"../../elliptic":249}],261:[function(_dereq_,module,exports){ +'use strict'; + +var BN = _dereq_('bn.js'); +var elliptic = _dereq_('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; + +},{"../../elliptic":249,"bn.js":37}],262:[function(_dereq_,module,exports){ +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } +}; + +},{}],263:[function(_dereq_,module,exports){ +'use strict'; + +var utils = exports; +var BN = _dereq_('bn.js'); +var minAssert = _dereq_('minimalistic-assert'); +var minUtils = _dereq_('minimalistic-crypto-utils'); + +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; + +// Represent num in a w-NAF form +function getNAF(num, w) { + var naf = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + + +},{"bn.js":37,"minimalistic-assert":280,"minimalistic-crypto-utils":281}],264:[function(_dereq_,module,exports){ +module.exports={ + "_from": "github:openpgpjs/elliptic", + "_id": "elliptic@6.4.0", + "_inBundle": false, + "_location": "/elliptic", + "_phantomChildren": {}, + "_requested": { + "type": "git", + "raw": "elliptic@github:openpgpjs/elliptic", + "name": "elliptic", + "escapedName": "elliptic", + "rawSpec": "github:openpgpjs/elliptic", + "saveSpec": "github:openpgpjs/elliptic", + "fetchSpec": null, + "gitCommittish": null + }, + "_requiredBy": [ + "/" + ], + "_resolved": "github:openpgpjs/elliptic#8b8ee8475b86402b125d4ad3a863a4ccd762e48c", + "_spec": "elliptic@github:openpgpjs/elliptic", + "_where": "/Users/sunny/Desktop/Protonmail/openpgpjs", + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + }, + "deprecated": false, + "description": "EC cryptography", + "devDependencies": { + "brfs": "^1.4.3", + "coveralls": "^2.11.3", + "grunt": "^0.4.5", + "grunt-browserify": "^5.0.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-connect": "^1.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^1.0.1", + "grunt-mocha-istanbul": "^3.0.1", + "grunt-saucelabs": "^8.6.2", + "istanbul": "^0.4.2", + "jscs": "^2.9.0", + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/indutny/elliptic", + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "license": "MIT", + "main": "lib/elliptic.js", + "name": "elliptic", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/elliptic.git" + }, + "scripts": { + "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "lint": "npm run jscs && npm run jshint", + "test": "npm run lint && npm run unit", + "unit": "istanbul test _mocha --reporter=spec test/index.js", + "version": "grunt dist && git add dist/" + }, + "version": "6.4.0" +} + +},{}],265:[function(_dereq_,module,exports){ +var hash = exports; + +hash.utils = _dereq_('./hash/utils'); +hash.common = _dereq_('./hash/common'); +hash.sha = _dereq_('./hash/sha'); +hash.ripemd = _dereq_('./hash/ripemd'); +hash.hmac = _dereq_('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; + +},{"./hash/common":266,"./hash/hmac":267,"./hash/ripemd":268,"./hash/sha":269,"./hash/utils":276}],266:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('./utils'); +var assert = _dereq_('minimalistic-assert'); + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; + +},{"./utils":276,"minimalistic-assert":280}],267:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('./utils'); +var assert = _dereq_('minimalistic-assert'); + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + +},{"./utils":276,"minimalistic-assert":280}],268:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('./utils'); +var common = _dereq_('./common'); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + +},{"./common":266,"./utils":276}],269:[function(_dereq_,module,exports){ +'use strict'; + +exports.sha1 = _dereq_('./sha/1'); +exports.sha224 = _dereq_('./sha/224'); +exports.sha256 = _dereq_('./sha/256'); +exports.sha384 = _dereq_('./sha/384'); +exports.sha512 = _dereq_('./sha/512'); + +},{"./sha/1":270,"./sha/224":271,"./sha/256":272,"./sha/384":273,"./sha/512":274}],270:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); +var common = _dereq_('../common'); +var shaCommon = _dereq_('./common'); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +},{"../common":266,"../utils":276,"./common":275}],271:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); +var SHA256 = _dereq_('./256'); + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + + +},{"../utils":276,"./256":272}],272:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); +var common = _dereq_('../common'); +var shaCommon = _dereq_('./common'); +var assert = _dereq_('minimalistic-assert'); + +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; + +var BlockHash = common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +},{"../common":266,"../utils":276,"./common":275,"minimalistic-assert":280}],273:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); + +var SHA512 = _dereq_('./512'); + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + +},{"../utils":276,"./512":274}],274:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); +var common = _dereq_('../common'); +var assert = _dereq_('minimalistic-assert'); + +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; + +var BlockHash = common.BlockHash; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +},{"../common":266,"../utils":276,"minimalistic-assert":280}],275:[function(_dereq_,module,exports){ +'use strict'; + +var utils = _dereq_('../utils'); +var rotr32 = utils.rotr32; + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +exports.ft_1 = ft_1; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +exports.ch32 = ch32; + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +exports.maj32 = maj32; + +function p32(x, y, z) { + return x ^ y ^ z; +} +exports.p32 = p32; + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} +exports.s0_256 = s0_256; + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} +exports.s1_256 = s1_256; + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} +exports.g0_256 = g0_256; + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} +exports.g1_256 = g1_256; + +},{"../utils":276}],276:[function(_dereq_,module,exports){ +'use strict'; + +var assert = _dereq_('minimalistic-assert'); +var inherits = _dereq_('inherits'); + +exports.inherits = inherits; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +exports.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +exports.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +exports.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +exports.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +exports.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +exports.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +exports.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +exports.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +exports.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +exports.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +exports.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +exports.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +exports.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +exports.sum32_5 = sum32_5; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +} +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +} +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.shr64_lo = shr64_lo; + +},{"inherits":279,"minimalistic-assert":280}],277:[function(_dereq_,module,exports){ +'use strict'; + +var hash = _dereq_('hash.js'); +var utils = _dereq_('minimalistic-crypto-utils'); +var assert = _dereq_('minimalistic-assert'); + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils.toArray(options.pers, options.persEnc || 'hex'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); +}; + +},{"hash.js":265,"minimalistic-assert":280,"minimalistic-crypto-utils":281}],278:[function(_dereq_,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],279:[function(_dereq_,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],280:[function(_dereq_,module,exports){ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + +},{}],281:[function(_dereq_,module,exports){ +'use strict'; + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + +},{}],282:[function(_dereq_,module,exports){ +// Top level file is just a mixin of submodules & constants +'use strict'; + +var assign = _dereq_('./lib/utils/common').assign; + +var deflate = _dereq_('./lib/deflate'); +var inflate = _dereq_('./lib/inflate'); +var constants = _dereq_('./lib/zlib/constants'); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; + +},{"./lib/deflate":283,"./lib/inflate":284,"./lib/utils/common":285,"./lib/zlib/constants":288}],283:[function(_dereq_,module,exports){ +'use strict'; + + +var zlib_deflate = _dereq_('./zlib/deflate'); +var utils = _dereq_('./utils/common'); +var strings = _dereq_('./utils/strings'); +var msg = _dereq_('./zlib/messages'); +var ZStream = _dereq_('./zlib/zstream'); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + +},{"./utils/common":285,"./utils/strings":286,"./zlib/deflate":290,"./zlib/messages":295,"./zlib/zstream":297}],284:[function(_dereq_,module,exports){ +'use strict'; + + +var zlib_inflate = _dereq_('./zlib/inflate'); +var utils = _dereq_('./utils/common'); +var strings = _dereq_('./utils/strings'); +var c = _dereq_('./zlib/constants'); +var msg = _dereq_('./zlib/messages'); +var ZStream = _dereq_('./zlib/zstream'); +var GZheader = _dereq_('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var dict; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + // Convert data if needed + if (typeof dictionary === 'string') { + dict = strings.string2buf(dictionary); + } else if (toString.call(dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(dictionary); + } else { + dict = dictionary; + } + + status = zlib_inflate.inflateSetDictionary(this.strm, dict); + + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + +},{"./utils/common":285,"./utils/strings":286,"./zlib/constants":288,"./zlib/gzheader":291,"./zlib/inflate":293,"./zlib/messages":295,"./zlib/zstream":297}],285:[function(_dereq_,module,exports){ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + +},{}],286:[function(_dereq_,module,exports){ +// String encode/decode helpers +'use strict'; + + +var utils = _dereq_('./common'); + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK = true; +var STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new utils.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // use fallback for big arrays to avoid stack overflow + if (len < 65537) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":285}],287:[function(_dereq_,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],288:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],289:[function(_dereq_,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],290:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = _dereq_('../utils/common'); +var trees = _dereq_('./trees'); +var adler32 = _dereq_('./adler32'); +var crc32 = _dereq_('./crc32'); +var msg = _dereq_('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":285,"./adler32":287,"./crc32":289,"./messages":295,"./trees":296}],291:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + +},{}],292:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],293:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = _dereq_('../utils/common'); +var adler32 = _dereq_('./adler32'); +var crc32 = _dereq_('./crc32'); +var inflate_fast = _dereq_('./inffast'); +var inflate_table = _dereq_('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ -}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":3}],3:[function(_dereq_,module,exports){ +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":285,"./adler32":287,"./crc32":289,"./inffast":292,"./inftrees":294}],294:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = _dereq_('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":285}],295:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],296:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = _dereq_('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [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]; + +var extra_dbits = /* extra bits for each distance code */ + [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]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":285}],297:[function(_dereq_,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],298:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -4141,7 +24499,7 @@ function defaultClearTimeout () { } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { - //normal environments in sane situations + //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined @@ -4166,7 +24524,7 @@ function runTimeout(fun) { } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { - //normal environments in sane situations + //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined @@ -4287,514 +24645,2007 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],4:[function(_dereq_,module,exports){ -(function (global){ -(function () { - function Rusha(chunkSize) { - 'use strict'; - var util = { - getDataType: function (data) { - if (typeof data === 'string') { - return 'string'; - } - if (data instanceof Array) { - return 'array'; - } - if (typeof global !== 'undefined' && global.Buffer && global.Buffer.isBuffer(data)) { - return 'buffer'; - } - if (data instanceof ArrayBuffer) { - return 'arraybuffer'; - } - if (data.buffer instanceof ArrayBuffer) { - return 'view'; - } - if (data instanceof Blob) { - return 'blob'; - } - throw new Error('Unsupported data type.'); - } - }; - var // Private object structure. - self$2 = { fill: 0 }; - var // Calculate the length of buffer that the sha1 routine uses - // including the padding. - padlen = function (len) { - for (len += 9; len % 64 > 0; len += 1); - return len; - }; - var padZeroes = function (bin, len) { - var h8 = new Uint8Array(bin.buffer); - var om = len % 4, align = len - om; - switch (om) { - case 0: - h8[align + 3] = 0; - case 1: - h8[align + 2] = 0; - case 2: - h8[align + 1] = 0; - case 3: - h8[align + 0] = 0; - } - for (var i$2 = (len >> 2) + 1; i$2 < bin.length; i$2++) - bin[i$2] = 0; - }; - var padData = function (bin, chunkLen, msgLen) { - bin[chunkLen >> 2] |= 128 << 24 - (chunkLen % 4 << 3); - // To support msgLen >= 2 GiB, use a float division when computing the - // high 32-bits of the big-endian message length in bits. - bin[((chunkLen >> 2) + 2 & ~15) + 14] = msgLen / (1 << 29) | 0; - bin[((chunkLen >> 2) + 2 & ~15) + 15] = msgLen << 3; - }; - var // Convert a binary string and write it to the heap. - // A binary string is expected to only contain char codes < 256. - convStr = function (H8, H32, start, len, off) { - var str = this, i$2, om = off % 4, lm = (len + om) % 4, j = len - lm; - switch (om) { - case 0: - H8[off] = str.charCodeAt(start + 3); - case 1: - H8[off + 1 - (om << 1) | 0] = str.charCodeAt(start + 2); - case 2: - H8[off + 2 - (om << 1) | 0] = str.charCodeAt(start + 1); - case 3: - H8[off + 3 - (om << 1) | 0] = str.charCodeAt(start); - } - if (len < lm + om) { - return; - } - for (i$2 = 4 - om; i$2 < j; i$2 = i$2 + 4 | 0) { - H32[off + i$2 >> 2] = str.charCodeAt(start + i$2) << 24 | str.charCodeAt(start + i$2 + 1) << 16 | str.charCodeAt(start + i$2 + 2) << 8 | str.charCodeAt(start + i$2 + 3); - } - switch (lm) { - case 3: - H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2); - case 2: - H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1); - case 1: - H8[off + j + 3 | 0] = str.charCodeAt(start + j); - } - }; - var // Convert a buffer or array and write it to the heap. - // The buffer or array is expected to only contain elements < 256. - convBuf = function (H8, H32, start, len, off) { - var buf = this, i$2, om = off % 4, lm = (len + om) % 4, j = len - lm; - switch (om) { - case 0: - H8[off] = buf[start + 3]; - case 1: - H8[off + 1 - (om << 1) | 0] = buf[start + 2]; - case 2: - H8[off + 2 - (om << 1) | 0] = buf[start + 1]; - case 3: - H8[off + 3 - (om << 1) | 0] = buf[start]; - } - if (len < lm + om) { - return; - } - for (i$2 = 4 - om; i$2 < j; i$2 = i$2 + 4 | 0) { - H32[off + i$2 >> 2 | 0] = buf[start + i$2] << 24 | buf[start + i$2 + 1] << 16 | buf[start + i$2 + 2] << 8 | buf[start + i$2 + 3]; - } - switch (lm) { - case 3: - H8[off + j + 1 | 0] = buf[start + j + 2]; - case 2: - H8[off + j + 2 | 0] = buf[start + j + 1]; - case 1: - H8[off + j + 3 | 0] = buf[start + j]; - } - }; - var convBlob = function (H8, H32, start, len, off) { - var blob = this, i$2, om = off % 4, lm = (len + om) % 4, j = len - lm; - var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len))); - switch (om) { - case 0: - H8[off] = buf[3]; - case 1: - H8[off + 1 - (om << 1) | 0] = buf[2]; - case 2: - H8[off + 2 - (om << 1) | 0] = buf[1]; - case 3: - H8[off + 3 - (om << 1) | 0] = buf[0]; - } - if (len < lm + om) { - return; - } - for (i$2 = 4 - om; i$2 < j; i$2 = i$2 + 4 | 0) { - H32[off + i$2 >> 2 | 0] = buf[i$2] << 24 | buf[i$2 + 1] << 16 | buf[i$2 + 2] << 8 | buf[i$2 + 3]; - } - switch (lm) { - case 3: - H8[off + j + 1 | 0] = buf[j + 2]; - case 2: - H8[off + j + 2 | 0] = buf[j + 1]; - case 1: - H8[off + j + 3 | 0] = buf[j]; - } - }; - var convFn = function (data) { - switch (util.getDataType(data)) { - case 'string': - return convStr.bind(data); - case 'array': - return convBuf.bind(data); - case 'buffer': - return convBuf.bind(data); - case 'arraybuffer': - return convBuf.bind(new Uint8Array(data)); - case 'view': - return convBuf.bind(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); - case 'blob': - return convBlob.bind(data); - } - }; - var slice = function (data, offset) { - switch (util.getDataType(data)) { - case 'string': - return data.slice(offset); - case 'array': - return data.slice(offset); - case 'buffer': - return data.slice(offset); - case 'arraybuffer': - return data.slice(offset); - case 'view': - return data.buffer.slice(offset); - } - }; - var // Precompute 00 - ff strings - precomputedHex = new Array(256); - for (var i = 0; i < 256; i++) { - precomputedHex[i] = (i < 16 ? '0' : '') + i.toString(16); - } - var // Convert an ArrayBuffer into its hexadecimal string representation. - hex = function (arrayBuffer) { - var binarray = new Uint8Array(arrayBuffer); - var res = new Array(arrayBuffer.byteLength); - for (var i$2 = 0; i$2 < res.length; i$2++) { - res[i$2] = precomputedHex[binarray[i$2]]; - } - return res.join(''); - }; - var ceilHeapSize = function (v) { - // The asm.js spec says: - // The heap object's byteLength must be either - // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1. - // Also, byteLengths smaller than 2^16 are deprecated. - var p; - if (// If v is smaller than 2^16, the smallest possible solution - // is 2^16. - v <= 65536) - return 65536; - if (// If v < 2^24, we round up to 2^n, - // otherwise we round up to 2^24 * n. - v < 16777216) { - for (p = 1; p < v; p = p << 1); - } else { - for (p = 16777216; p < v; p += 16777216); - } - return p; - }; - var // Initialize the internal data structures to a new capacity. - init = function (size) { - if (size % 64 > 0) { - throw new Error('Chunk size must be a multiple of 128 bit'); - } - self$2.offset = 0; - self$2.maxChunkLen = size; - self$2.padMaxChunkLen = padlen(size); - // The size of the heap is the sum of: - // 1. The padded input message size - // 2. The extended space the algorithm needs (320 byte) - // 3. The 160 bit state the algorithm uses - self$2.heap = new ArrayBuffer(ceilHeapSize(self$2.padMaxChunkLen + 320 + 20)); - self$2.h32 = new Int32Array(self$2.heap); - self$2.h8 = new Int8Array(self$2.heap); - self$2.core = new Rusha._core({ - Int32Array: Int32Array, - DataView: DataView - }, {}, self$2.heap); - self$2.buffer = null; - }; - // Iinitializethe datastructures according - // to a chunk siyze. - init(chunkSize || 64 * 1024); - var initState = function (heap, padMsgLen) { - self$2.offset = 0; - var io = new Int32Array(heap, padMsgLen + 320, 5); - io[0] = 1732584193; - io[1] = -271733879; - io[2] = -1732584194; - io[3] = 271733878; - io[4] = -1009589776; - }; - var padChunk = function (chunkLen, msgLen) { - var padChunkLen = padlen(chunkLen); - var view = new Int32Array(self$2.heap, 0, padChunkLen >> 2); - padZeroes(view, chunkLen); - padData(view, chunkLen, msgLen); - return padChunkLen; - }; - var // Write data to the heap. - write = function (data, chunkOffset, chunkLen, off) { - convFn(data)(self$2.h8, self$2.h32, chunkOffset, chunkLen, off || 0); - }; - var // Initialize and call the RushaCore, - // assuming an input buffer of length len * 4. - coreCall = function (data, chunkOffset, chunkLen, msgLen, finalize) { - var padChunkLen = chunkLen; - write(data, chunkOffset, chunkLen); - if (finalize) { - padChunkLen = padChunk(chunkLen, msgLen); - } - self$2.core.hash(padChunkLen, self$2.padMaxChunkLen); - }; - var getRawDigest = function (heap, padMaxChunkLen) { - var io = new Int32Array(heap, padMaxChunkLen + 320, 5); - var out = new Int32Array(5); - var arr = new DataView(out.buffer); - arr.setInt32(0, io[0], false); - arr.setInt32(4, io[1], false); - arr.setInt32(8, io[2], false); - arr.setInt32(12, io[3], false); - arr.setInt32(16, io[4], false); - return out; - }; - var // Calculate the hash digest as an array of 5 32bit integers. - rawDigest = this.rawDigest = function (str) { - var msgLen = str.byteLength || str.length || str.size || 0; - initState(self$2.heap, self$2.padMaxChunkLen); - var chunkOffset = 0, chunkLen = self$2.maxChunkLen; - for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) { - coreCall(str, chunkOffset, chunkLen, msgLen, false); - } - coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true); - return getRawDigest(self$2.heap, self$2.padMaxChunkLen); - }; - // The digest and digestFrom* interface returns the hash digest - // as a hex string. - this.digest = this.digestFromString = this.digestFromBuffer = this.digestFromArrayBuffer = function (str) { - return hex(rawDigest(str).buffer); - }; - this.resetState = function () { - initState(self$2.heap, self$2.padMaxChunkLen); - return this; - }; - this.append = function (chunk) { - var chunkOffset = 0; - var chunkLen = chunk.byteLength || chunk.length || chunk.size || 0; - var turnOffset = self$2.offset % self$2.maxChunkLen; - var inputLen; - self$2.offset += chunkLen; - while (chunkOffset < chunkLen) { - inputLen = Math.min(chunkLen - chunkOffset, self$2.maxChunkLen - turnOffset); - write(chunk, chunkOffset, inputLen, turnOffset); - turnOffset += inputLen; - chunkOffset += inputLen; - if (turnOffset === self$2.maxChunkLen) { - self$2.core.hash(self$2.maxChunkLen, self$2.padMaxChunkLen); - turnOffset = 0; - } - } - return this; - }; - this.getState = function () { - var turnOffset = self$2.offset % self$2.maxChunkLen; - var heap; - if (!turnOffset) { - var io = new Int32Array(self$2.heap, self$2.padMaxChunkLen + 320, 5); - heap = io.buffer.slice(io.byteOffset, io.byteOffset + io.byteLength); - } else { - heap = self$2.heap.slice(0); - } - return { - offset: self$2.offset, - heap: heap - }; - }; - this.setState = function (state) { - self$2.offset = state.offset; - if (state.heap.byteLength === 20) { - var io = new Int32Array(self$2.heap, self$2.padMaxChunkLen + 320, 5); - io.set(new Int32Array(state.heap)); - } else { - self$2.h32.set(new Int32Array(state.heap)); - } - return this; - }; - var rawEnd = this.rawEnd = function () { - var msgLen = self$2.offset; - var chunkLen = msgLen % self$2.maxChunkLen; - var padChunkLen = padChunk(chunkLen, msgLen); - self$2.core.hash(padChunkLen, self$2.padMaxChunkLen); - var result = getRawDigest(self$2.heap, self$2.padMaxChunkLen); - initState(self$2.heap, self$2.padMaxChunkLen); - return result; - }; - this.end = function () { - return hex(rawEnd().buffer); - }; +},{}],299:[function(_dereq_,module,exports){ +// This method of obtaining a reference to the global object needs to be +// kept identical to the way it is obtained in runtime.js +var g = (function() { return this })() || Function("return this")(); + +// Use `getOwnPropertyNames` because not all browsers support calling +// `hasOwnProperty` on the global `self` object in a worker. See #183. +var hadRuntime = g.regeneratorRuntime && + Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; + +// Save the old regeneratorRuntime in case it needs to be restored later. +var oldRuntime = hadRuntime && g.regeneratorRuntime; + +// Force reevalutation of runtime.js. +g.regeneratorRuntime = undefined; + +module.exports = _dereq_("./runtime"); + +if (hadRuntime) { + // Restore the original runtime. + g.regeneratorRuntime = oldRuntime; +} else { + // Remove the global property added by runtime.js. + try { + delete g.regeneratorRuntime; + } catch(e) { + g.regeneratorRuntime = undefined; + } +} + +},{"./runtime":300}],300:[function(_dereq_,module,exports){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + +!(function(global) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; } - ; - // The low-level RushCore module provides the heart of Rusha, - // a high-speed sha1 implementation working on an Int32Array heap. - // At first glance, the implementation seems complicated, however - // with the SHA1 spec at hand, it is obvious this almost a textbook - // implementation that has a few functions hand-inlined and a few loops - // hand-unrolled. - Rusha._core = function RushaCore(stdlib, foreign, heap) { - 'use asm'; - var H = new stdlib.Int32Array(heap); - function hash(k, x) { - // k in bytes - k = k | 0; - x = x | 0; - var i = 0, j = 0, y0 = 0, z0 = 0, y1 = 0, z1 = 0, y2 = 0, z2 = 0, y3 = 0, z3 = 0, y4 = 0, z4 = 0, t0 = 0, t1 = 0; - y0 = H[x + 320 >> 2] | 0; - y1 = H[x + 324 >> 2] | 0; - y2 = H[x + 328 >> 2] | 0; - y3 = H[x + 332 >> 2] | 0; - y4 = H[x + 336 >> 2] | 0; - for (i = 0; (i | 0) < (k | 0); i = i + 64 | 0) { - z0 = y0; - z1 = y1; - z2 = y2; - z3 = y3; - z4 = y4; - for (j = 0; (j | 0) < 64; j = j + 4 | 0) { - t1 = H[i + j >> 2] | 0; - t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0; - y4 = y3; - y3 = y2; - y2 = y1 << 30 | y1 >>> 2; - y1 = y0; - y0 = t0; - H[k + j >> 2] = t1; - } - for (j = k + 64 | 0; (j | 0) < (k + 80 | 0); j = j + 4 | 0) { - t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; - t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | ~y1 & y3) | 0) + ((t1 + y4 | 0) + 1518500249 | 0) | 0; - y4 = y3; - y3 = y2; - y2 = y1 << 30 | y1 >>> 2; - y1 = y0; - y0 = t0; - H[j >> 2] = t1; - } - for (j = k + 80 | 0; (j | 0) < (k + 160 | 0); j = j + 4 | 0) { - t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; - t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) + 1859775393 | 0) | 0; - y4 = y3; - y3 = y2; - y2 = y1 << 30 | y1 >>> 2; - y1 = y0; - y0 = t0; - H[j >> 2] = t1; - } - for (j = k + 160 | 0; (j | 0) < (k + 240 | 0); j = j + 4 | 0) { - t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; - t0 = ((y0 << 5 | y0 >>> 27) + (y1 & y2 | y1 & y3 | y2 & y3) | 0) + ((t1 + y4 | 0) - 1894007588 | 0) | 0; - y4 = y3; - y3 = y2; - y2 = y1 << 30 | y1 >>> 2; - y1 = y0; - y0 = t0; - H[j >> 2] = t1; - } - for (j = k + 240 | 0; (j | 0) < (k + 320 | 0); j = j + 4 | 0) { - t1 = (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) << 1 | (H[j - 12 >> 2] ^ H[j - 32 >> 2] ^ H[j - 56 >> 2] ^ H[j - 64 >> 2]) >>> 31; - t0 = ((y0 << 5 | y0 >>> 27) + (y1 ^ y2 ^ y3) | 0) + ((t1 + y4 | 0) - 899497514 | 0) | 0; - y4 = y3; - y3 = y2; - y2 = y1 << 30 | y1 >>> 2; - y1 = y0; - y0 = t0; - H[j >> 2] = t1; - } - y0 = y0 + z0 | 0; - y1 = y1 + z1 | 0; - y2 = y2 + z2 | 0; - y3 = y3 + z3 | 0; - y4 = y4 + z4 | 0; - } - H[x + 320 >> 2] = y0; - H[x + 324 >> 2] = y1; - H[x + 328 >> 2] = y2; - H[x + 332 >> 2] = y3; - H[x + 336 >> 2] = y4; + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + runtime.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); } - return { hash: hash }; + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + runtime.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } }; - if (// If we'e running in Node.JS, export a module. - typeof module !== 'undefined') { - module.exports = Rusha; - } else if (// If we're running in a DOM context, export - // the Rusha object to toplevel. - typeof window !== 'undefined') { - window.Rusha = Rusha; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; } - if (// If we're running in a webworker, accept - // messages containing a jobid and a buffer - // or blob object, and return the hash result. - typeof FileReaderSync !== 'undefined') { - var reader = new FileReaderSync(); - var hashData = function hash(hasher, data, cb) { - try { - return cb(null, hasher.digest(data)); - } catch (e) { - return cb(e); + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; } + } + + next.value = undefined; + next.done = true; + + return next; }; - var hashFile = function hashArrayBuffer(hasher, readTotal, blockSize, file, cb) { - var reader$2 = new self.FileReader(); - reader$2.onloadend = function onloadend() { - var buffer = reader$2.result; - readTotal += reader$2.result.byteLength; - try { - hasher.append(buffer); - } catch (e) { - cb(e); - return; - } - if (readTotal < file.size) { - hashFile(hasher, readTotal, blockSize, file, cb); - } else { - cb(null, hasher.end()); - } - }; - reader$2.readAsArrayBuffer(file.slice(readTotal, readTotal + blockSize)); - }; - self.onmessage = function onMessage(event) { - var data = event.data.data, file = event.data.file, id = event.data.id; - if (typeof id === 'undefined') - return; - if (!file && !data) - return; - var blockSize = event.data.blockSize || 4 * 1024 * 1024; - var hasher = new Rusha(blockSize); - hasher.resetState(); - var done = function done$2(err, hash) { - if (!err) { - self.postMessage({ - id: id, - hash: hash - }); - } else { - self.postMessage({ - id: id, - error: err.name - }); - } - }; - if (data) - hashData(hasher, data, done); - if (file) - hashFile(hasher, 0, blockSize, file, done); - }; + + return next.next = next; + } } -}()); + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; +})( + // In sloppy mode, unbound `this` refers to the global object, fallback to + // Function constructor if we're in global strict mode. That is sadly a form + // of indirect eval which violates Content Security Policy. + (function() { return this })() || Function("return this")() +); + +},{}],301:[function(_dereq_,module,exports){ +(function (global){ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Rusha = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o> 2] = str.charCodeAt(start + i) << 24 | str.charCodeAt(start + i + 1) << 16 | str.charCodeAt(start + i + 2) << 8 | str.charCodeAt(start + i + 3); + } + switch (lm) { + case 3: + H8[off + j + 1 | 0] = str.charCodeAt(start + j + 2); + case 2: + H8[off + j + 2 | 0] = str.charCodeAt(start + j + 1); + case 1: + H8[off + j + 3 | 0] = str.charCodeAt(start + j); + } +}; + +// Convert a buffer or array and write it to the heap. +// The buffer or array is expected to only contain elements < 256. +var convBuf = function (buf, H8, H32, start, len, off) { + var i = void 0, + om = off % 4, + lm = (len + om) % 4, + j = len - lm; + switch (om) { + case 0: + H8[off] = buf[start + 3]; + case 1: + H8[off + 1 - (om << 1) | 0] = buf[start + 2]; + case 2: + H8[off + 2 - (om << 1) | 0] = buf[start + 1]; + case 3: + H8[off + 3 - (om << 1) | 0] = buf[start]; + } + if (len < lm + (4 - om)) { + return; + } + for (i = 4 - om; i < j; i = i + 4 | 0) { + H32[off + i >> 2 | 0] = buf[start + i] << 24 | buf[start + i + 1] << 16 | buf[start + i + 2] << 8 | buf[start + i + 3]; + } + switch (lm) { + case 3: + H8[off + j + 1 | 0] = buf[start + j + 2]; + case 2: + H8[off + j + 2 | 0] = buf[start + j + 1]; + case 1: + H8[off + j + 3 | 0] = buf[start + j]; + } +}; + +var convBlob = function (blob, H8, H32, start, len, off) { + var i = void 0, + om = off % 4, + lm = (len + om) % 4, + j = len - lm; + var buf = new Uint8Array(reader.readAsArrayBuffer(blob.slice(start, start + len))); + switch (om) { + case 0: + H8[off] = buf[3]; + case 1: + H8[off + 1 - (om << 1) | 0] = buf[2]; + case 2: + H8[off + 2 - (om << 1) | 0] = buf[1]; + case 3: + H8[off + 3 - (om << 1) | 0] = buf[0]; + } + if (len < lm + (4 - om)) { + return; + } + for (i = 4 - om; i < j; i = i + 4 | 0) { + H32[off + i >> 2 | 0] = buf[i] << 24 | buf[i + 1] << 16 | buf[i + 2] << 8 | buf[i + 3]; + } + switch (lm) { + case 3: + H8[off + j + 1 | 0] = buf[j + 2]; + case 2: + H8[off + j + 2 | 0] = buf[j + 1]; + case 1: + H8[off + j + 3 | 0] = buf[j]; + } +}; + +module.exports = function (data, H8, H32, start, len, off) { + if (typeof data === 'string') { + return convStr(data, H8, H32, start, len, off); + } + if (data instanceof Array) { + return convBuf(data, H8, H32, start, len, off); + } + if (global.Buffer && global.Buffer.isBuffer(data)) { + return convBuf(data, H8, H32, start, len, off); + } + if (data instanceof ArrayBuffer) { + return convBuf(new Uint8Array(data), H8, H32, start, len, off); + } + if (data.buffer instanceof ArrayBuffer) { + return convBuf(new Uint8Array(data.buffer, data.byteOffset, data.byteLength), H8, H32, start, len, off); + } + if (data instanceof Blob) { + return convBlob(data, H8, H32, start, len, off); + } + throw new Error('Unsupported data type.'); +}; + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],5:[function(_dereq_,module,exports){ +},{}],3:[function(_dereq_,module,exports){ +'use strict'; +// The low-level RushCore module provides the heart of Rusha, +// a high-speed sha1 implementation working on an Int32Array heap. +// At first glance, the implementation seems complicated, however +// with the SHA1 spec at hand, it is obvious this almost a textbook +// implementation that has a few functions hand-inlined and a few loops +// hand-unrolled. +module.exports = function RushaCore(stdlib$1186, foreign$1187, heap$1188) { + 'use asm'; + var H$1189 = new stdlib$1186.Int32Array(heap$1188); + function hash$1190(k$1191, x$1192) { + // k in bytes + k$1191 = k$1191 | 0; + x$1192 = x$1192 | 0; + var i$1193 = 0, j$1194 = 0, y0$1195 = 0, z0$1196 = 0, y1$1197 = 0, z1$1198 = 0, y2$1199 = 0, z2$1200 = 0, y3$1201 = 0, z3$1202 = 0, y4$1203 = 0, z4$1204 = 0, t0$1205 = 0, t1$1206 = 0; + y0$1195 = H$1189[x$1192 + 320 >> 2] | 0; + y1$1197 = H$1189[x$1192 + 324 >> 2] | 0; + y2$1199 = H$1189[x$1192 + 328 >> 2] | 0; + y3$1201 = H$1189[x$1192 + 332 >> 2] | 0; + y4$1203 = H$1189[x$1192 + 336 >> 2] | 0; + for (i$1193 = 0; (i$1193 | 0) < (k$1191 | 0); i$1193 = i$1193 + 64 | 0) { + z0$1196 = y0$1195; + z1$1198 = y1$1197; + z2$1200 = y2$1199; + z3$1202 = y3$1201; + z4$1204 = y4$1203; + for (j$1194 = 0; (j$1194 | 0) < 64; j$1194 = j$1194 + 4 | 0) { + t1$1206 = H$1189[i$1193 + j$1194 >> 2] | 0; + t0$1205 = ((y0$1195 << 5 | y0$1195 >>> 27) + (y1$1197 & y2$1199 | ~y1$1197 & y3$1201) | 0) + ((t1$1206 + y4$1203 | 0) + 1518500249 | 0) | 0; + y4$1203 = y3$1201; + y3$1201 = y2$1199; + y2$1199 = y1$1197 << 30 | y1$1197 >>> 2; + y1$1197 = y0$1195; + y0$1195 = t0$1205; + H$1189[k$1191 + j$1194 >> 2] = t1$1206; + } + for (j$1194 = k$1191 + 64 | 0; (j$1194 | 0) < (k$1191 + 80 | 0); j$1194 = j$1194 + 4 | 0) { + t1$1206 = (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) << 1 | (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) >>> 31; + t0$1205 = ((y0$1195 << 5 | y0$1195 >>> 27) + (y1$1197 & y2$1199 | ~y1$1197 & y3$1201) | 0) + ((t1$1206 + y4$1203 | 0) + 1518500249 | 0) | 0; + y4$1203 = y3$1201; + y3$1201 = y2$1199; + y2$1199 = y1$1197 << 30 | y1$1197 >>> 2; + y1$1197 = y0$1195; + y0$1195 = t0$1205; + H$1189[j$1194 >> 2] = t1$1206; + } + for (j$1194 = k$1191 + 80 | 0; (j$1194 | 0) < (k$1191 + 160 | 0); j$1194 = j$1194 + 4 | 0) { + t1$1206 = (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) << 1 | (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) >>> 31; + t0$1205 = ((y0$1195 << 5 | y0$1195 >>> 27) + (y1$1197 ^ y2$1199 ^ y3$1201) | 0) + ((t1$1206 + y4$1203 | 0) + 1859775393 | 0) | 0; + y4$1203 = y3$1201; + y3$1201 = y2$1199; + y2$1199 = y1$1197 << 30 | y1$1197 >>> 2; + y1$1197 = y0$1195; + y0$1195 = t0$1205; + H$1189[j$1194 >> 2] = t1$1206; + } + for (j$1194 = k$1191 + 160 | 0; (j$1194 | 0) < (k$1191 + 240 | 0); j$1194 = j$1194 + 4 | 0) { + t1$1206 = (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) << 1 | (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) >>> 31; + t0$1205 = ((y0$1195 << 5 | y0$1195 >>> 27) + (y1$1197 & y2$1199 | y1$1197 & y3$1201 | y2$1199 & y3$1201) | 0) + ((t1$1206 + y4$1203 | 0) - 1894007588 | 0) | 0; + y4$1203 = y3$1201; + y3$1201 = y2$1199; + y2$1199 = y1$1197 << 30 | y1$1197 >>> 2; + y1$1197 = y0$1195; + y0$1195 = t0$1205; + H$1189[j$1194 >> 2] = t1$1206; + } + for (j$1194 = k$1191 + 240 | 0; (j$1194 | 0) < (k$1191 + 320 | 0); j$1194 = j$1194 + 4 | 0) { + t1$1206 = (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) << 1 | (H$1189[j$1194 - 12 >> 2] ^ H$1189[j$1194 - 32 >> 2] ^ H$1189[j$1194 - 56 >> 2] ^ H$1189[j$1194 - 64 >> 2]) >>> 31; + t0$1205 = ((y0$1195 << 5 | y0$1195 >>> 27) + (y1$1197 ^ y2$1199 ^ y3$1201) | 0) + ((t1$1206 + y4$1203 | 0) - 899497514 | 0) | 0; + y4$1203 = y3$1201; + y3$1201 = y2$1199; + y2$1199 = y1$1197 << 30 | y1$1197 >>> 2; + y1$1197 = y0$1195; + y0$1195 = t0$1205; + H$1189[j$1194 >> 2] = t1$1206; + } + y0$1195 = y0$1195 + z0$1196 | 0; + y1$1197 = y1$1197 + z1$1198 | 0; + y2$1199 = y2$1199 + z2$1200 | 0; + y3$1201 = y3$1201 + z3$1202 | 0; + y4$1203 = y4$1203 + z4$1204 | 0; + } + H$1189[x$1192 + 320 >> 2] = y0$1195; + H$1189[x$1192 + 324 >> 2] = y1$1197; + H$1189[x$1192 + 328 >> 2] = y2$1199; + H$1189[x$1192 + 332 >> 2] = y3$1201; + H$1189[x$1192 + 336 >> 2] = y4$1203; + } + return { hash: hash$1190 }; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +/* eslint-env commonjs, browser */ + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Rusha = _dereq_('./rusha'); + +var _require = _dereq_('./utils'), + toHex = _require.toHex; + +var Hash = function () { + function Hash() { + _classCallCheck(this, Hash); + + this._rusha = new Rusha(); + this._rusha.resetState(); + } + + Hash.prototype.update = function update(data) { + this._rusha.append(data); + return this; + }; + + Hash.prototype.digest = function digest(encoding) { + var digest = this._rusha.rawEnd().buffer; + if (!encoding) { + return digest; + } + if (encoding === 'hex') { + return toHex(digest); + } + throw new Error('unsupported digest encoding'); + }; + + return Hash; +}(); + +module.exports = function () { + return new Hash(); +}; + +},{"./rusha":6,"./utils":7}],5:[function(_dereq_,module,exports){ +"use strict"; +/* eslint-env commonjs, browser */ + +var webworkify = _dereq_('webworkify'); + +var Rusha = _dereq_('./rusha'); +var createHash = _dereq_('./hash'); +var runWorker = _dereq_('./worker'); + +var _require = _dereq_('./utils'), + isDedicatedWorkerScope = _require.isDedicatedWorkerScope; + +var isRunningInDedicatedWorker = typeof self !== 'undefined' && isDedicatedWorkerScope(self); + +Rusha.disableWorkerBehaviour = isRunningInDedicatedWorker ? runWorker() : function () {}; + +Rusha.createWorker = function () { + var worker = webworkify(_dereq_('./worker')); + var terminate = worker.terminate; + worker.terminate = function () { + URL.revokeObjectURL(worker.objectURL); + terminate.call(worker); + }; + return worker; +}; + +Rusha.createHash = createHash; + +module.exports = Rusha; + +},{"./hash":4,"./rusha":6,"./utils":7,"./worker":8,"webworkify":1}],6:[function(_dereq_,module,exports){ +"use strict"; +/* eslint-env commonjs, browser */ + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var RushaCore = _dereq_('./core.sjs'); + +var _require = _dereq_('./utils'), + toHex = _require.toHex, + ceilHeapSize = _require.ceilHeapSize; + +var conv = _dereq_('./conv'); + +// Calculate the length of buffer that the sha1 routine uses +// including the padding. +var padlen = function (len) { + for (len += 9; len % 64 > 0; len += 1) {} + return len; +}; + +var padZeroes = function (bin, len) { + var h8 = new Uint8Array(bin.buffer); + var om = len % 4, + align = len - om; + switch (om) { + case 0: + h8[align + 3] = 0; + case 1: + h8[align + 2] = 0; + case 2: + h8[align + 1] = 0; + case 3: + h8[align + 0] = 0; + } + for (var i = (len >> 2) + 1; i < bin.length; i++) { + bin[i] = 0; + } +}; + +var padData = function (bin, chunkLen, msgLen) { + bin[chunkLen >> 2] |= 0x80 << 24 - (chunkLen % 4 << 3); + // To support msgLen >= 2 GiB, use a float division when computing the + // high 32-bits of the big-endian message length in bits. + bin[((chunkLen >> 2) + 2 & ~0x0f) + 14] = msgLen / (1 << 29) | 0; + bin[((chunkLen >> 2) + 2 & ~0x0f) + 15] = msgLen << 3; +}; + +var getRawDigest = function (heap, padMaxChunkLen) { + var io = new Int32Array(heap, padMaxChunkLen + 320, 5); + var out = new Int32Array(5); + var arr = new DataView(out.buffer); + arr.setInt32(0, io[0], false); + arr.setInt32(4, io[1], false); + arr.setInt32(8, io[2], false); + arr.setInt32(12, io[3], false); + arr.setInt32(16, io[4], false); + return out; +}; + +var Rusha = function () { + function Rusha(chunkSize) { + _classCallCheck(this, Rusha); + + chunkSize = chunkSize || 64 * 1024; + if (chunkSize % 64 > 0) { + throw new Error('Chunk size must be a multiple of 128 bit'); + } + this._offset = 0; + this._maxChunkLen = chunkSize; + this._padMaxChunkLen = padlen(chunkSize); + // The size of the heap is the sum of: + // 1. The padded input message size + // 2. The extended space the algorithm needs (320 byte) + // 3. The 160 bit state the algoritm uses + this._heap = new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen + 320 + 20)); + this._h32 = new Int32Array(this._heap); + this._h8 = new Int8Array(this._heap); + this._core = new RushaCore({ Int32Array: Int32Array }, {}, this._heap); + } + + Rusha.prototype._initState = function _initState(heap, padMsgLen) { + this._offset = 0; + var io = new Int32Array(heap, padMsgLen + 320, 5); + io[0] = 1732584193; + io[1] = -271733879; + io[2] = -1732584194; + io[3] = 271733878; + io[4] = -1009589776; + }; + + Rusha.prototype._padChunk = function _padChunk(chunkLen, msgLen) { + var padChunkLen = padlen(chunkLen); + var view = new Int32Array(this._heap, 0, padChunkLen >> 2); + padZeroes(view, chunkLen); + padData(view, chunkLen, msgLen); + return padChunkLen; + }; + + Rusha.prototype._write = function _write(data, chunkOffset, chunkLen, off) { + conv(data, this._h8, this._h32, chunkOffset, chunkLen, off || 0); + }; + + Rusha.prototype._coreCall = function _coreCall(data, chunkOffset, chunkLen, msgLen, finalize) { + var padChunkLen = chunkLen; + this._write(data, chunkOffset, chunkLen); + if (finalize) { + padChunkLen = this._padChunk(chunkLen, msgLen); + } + this._core.hash(padChunkLen, this._padMaxChunkLen); + }; + + Rusha.prototype.rawDigest = function rawDigest(str) { + var msgLen = str.byteLength || str.length || str.size || 0; + this._initState(this._heap, this._padMaxChunkLen); + var chunkOffset = 0, + chunkLen = this._maxChunkLen; + for (chunkOffset = 0; msgLen > chunkOffset + chunkLen; chunkOffset += chunkLen) { + this._coreCall(str, chunkOffset, chunkLen, msgLen, false); + } + this._coreCall(str, chunkOffset, msgLen - chunkOffset, msgLen, true); + return getRawDigest(this._heap, this._padMaxChunkLen); + }; + + Rusha.prototype.digest = function digest(str) { + return toHex(this.rawDigest(str).buffer); + }; + + Rusha.prototype.digestFromString = function digestFromString(str) { + return this.digest(str); + }; + + Rusha.prototype.digestFromBuffer = function digestFromBuffer(str) { + return this.digest(str); + }; + + Rusha.prototype.digestFromArrayBuffer = function digestFromArrayBuffer(str) { + return this.digest(str); + }; + + Rusha.prototype.resetState = function resetState() { + this._initState(this._heap, this._padMaxChunkLen); + return this; + }; + + Rusha.prototype.append = function append(chunk) { + var chunkOffset = 0; + var chunkLen = chunk.byteLength || chunk.length || chunk.size || 0; + var turnOffset = this._offset % this._maxChunkLen; + var inputLen = void 0; + + this._offset += chunkLen; + while (chunkOffset < chunkLen) { + inputLen = Math.min(chunkLen - chunkOffset, this._maxChunkLen - turnOffset); + this._write(chunk, chunkOffset, inputLen, turnOffset); + turnOffset += inputLen; + chunkOffset += inputLen; + if (turnOffset === this._maxChunkLen) { + this._core.hash(this._maxChunkLen, this._padMaxChunkLen); + turnOffset = 0; + } + } + return this; + }; + + Rusha.prototype.getState = function getState() { + var turnOffset = this._offset % this._maxChunkLen; + var heap = void 0; + if (!turnOffset) { + var io = new Int32Array(this._heap, this._padMaxChunkLen + 320, 5); + heap = io.buffer.slice(io.byteOffset, io.byteOffset + io.byteLength); + } else { + heap = this._heap.slice(0); + } + return { + offset: this._offset, + heap: heap + }; + }; + + Rusha.prototype.setState = function setState(state) { + this._offset = state.offset; + if (state.heap.byteLength === 20) { + var io = new Int32Array(this._heap, this._padMaxChunkLen + 320, 5); + io.set(new Int32Array(state.heap)); + } else { + this._h32.set(new Int32Array(state.heap)); + } + return this; + }; + + Rusha.prototype.rawEnd = function rawEnd() { + var msgLen = this._offset; + var chunkLen = msgLen % this._maxChunkLen; + var padChunkLen = this._padChunk(chunkLen, msgLen); + this._core.hash(padChunkLen, this._padMaxChunkLen); + var result = getRawDigest(this._heap, this._padMaxChunkLen); + this._initState(this._heap, this._padMaxChunkLen); + return result; + }; + + Rusha.prototype.end = function end() { + return toHex(this.rawEnd().buffer); + }; + + return Rusha; +}(); + +module.exports = Rusha; +module.exports._core = RushaCore; + +},{"./conv":2,"./core.sjs":3,"./utils":7}],7:[function(_dereq_,module,exports){ +"use strict"; +/* eslint-env commonjs, browser */ + +// +// toHex +// + +var precomputedHex = new Array(256); +for (var i = 0; i < 256; i++) { + precomputedHex[i] = (i < 0x10 ? '0' : '') + i.toString(16); +} + +module.exports.toHex = function (arrayBuffer) { + var binarray = new Uint8Array(arrayBuffer); + var res = new Array(arrayBuffer.byteLength); + for (var _i = 0; _i < res.length; _i++) { + res[_i] = precomputedHex[binarray[_i]]; + } + return res.join(''); +}; + +// +// ceilHeapSize +// + +module.exports.ceilHeapSize = function (v) { + // The asm.js spec says: + // The heap object's byteLength must be either + // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1. + // Also, byteLengths smaller than 2^16 are deprecated. + var p = 0; + // If v is smaller than 2^16, the smallest possible solution + // is 2^16. + if (v <= 65536) return 65536; + // If v < 2^24, we round up to 2^n, + // otherwise we round up to 2^24 * n. + if (v < 16777216) { + for (p = 1; p < v; p = p << 1) {} + } else { + for (p = 16777216; p < v; p += 16777216) {} + } + return p; +}; + +// +// isDedicatedWorkerScope +// + +module.exports.isDedicatedWorkerScope = function (self) { + var isRunningInWorker = 'WorkerGlobalScope' in self && self instanceof self.WorkerGlobalScope; + var isRunningInSharedWorker = 'SharedWorkerGlobalScope' in self && self instanceof self.SharedWorkerGlobalScope; + var isRunningInServiceWorker = 'ServiceWorkerGlobalScope' in self && self instanceof self.ServiceWorkerGlobalScope; + + // Detects whether we run inside a dedicated worker or not. + // + // We can't just check for `DedicatedWorkerGlobalScope`, since IE11 + // has a bug where it only supports `WorkerGlobalScope`. + // + // Therefore, we consider us as running inside a dedicated worker + // when we are running inside a worker, but not in a shared or service worker. + // + // When new types of workers are introduced, we will need to adjust this code. + return isRunningInWorker && !isRunningInSharedWorker && !isRunningInServiceWorker; +}; + +},{}],8:[function(_dereq_,module,exports){ +"use strict"; +/* eslint-env commonjs, worker */ + +module.exports = function () { + var Rusha = _dereq_('./rusha'); + + var hashData = function (hasher, data, cb) { + try { + return cb(null, hasher.digest(data)); + } catch (e) { + return cb(e); + } + }; + + var hashFile = function (hasher, readTotal, blockSize, file, cb) { + var reader = new self.FileReader(); + reader.onloadend = function onloadend() { + if (reader.error) { + return cb(reader.error); + } + var buffer = reader.result; + readTotal += reader.result.byteLength; + try { + hasher.append(buffer); + } catch (e) { + cb(e); + return; + } + if (readTotal < file.size) { + hashFile(hasher, readTotal, blockSize, file, cb); + } else { + cb(null, hasher.end()); + } + }; + reader.readAsArrayBuffer(file.slice(readTotal, readTotal + blockSize)); + }; + + var workerBehaviourEnabled = true; + + self.onmessage = function (event) { + if (!workerBehaviourEnabled) { + return; + } + + var data = event.data.data, + file = event.data.file, + id = event.data.id; + if (typeof id === 'undefined') return; + if (!file && !data) return; + var blockSize = event.data.blockSize || 4 * 1024 * 1024; + var hasher = new Rusha(blockSize); + hasher.resetState(); + var done = function (err, hash) { + if (!err) { + self.postMessage({ id: id, hash: hash }); + } else { + self.postMessage({ id: id, error: err.name }); + } + }; + if (data) hashData(hasher, data, done); + if (file) hashFile(hasher, 0, blockSize, file, done); + }; + + return function () { + workerBehaviourEnabled = false; + }; +}; + +},{"./rusha":6}]},{},[5])(5) +}); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],302:[function(_dereq_,module,exports){ +(function(self) { + 'use strict'; + + if (self.fetch) { + return + } + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: 'FileReader' in self && 'Blob' in self && (function() { + try { + new Blob() + return true + } catch(e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ] + + var isDataView = function(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + var isArrayBufferView = ArrayBuffer.isView || function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + } + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name) + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value) + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift() + return {done: value === undefined, value: value} + } + } + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + } + } + + return iterator + } + + function Headers(headers) { + this.map = {} + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value) + }, this) + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]) + }, this) + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]) + }, this) + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name) + value = normalizeValue(value) + var oldValue = this.map[name] + this.map[name] = oldValue ? oldValue+','+value : value + } + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)] + } + + Headers.prototype.get = function(name) { + name = normalizeName(name) + return this.has(name) ? this.map[name] : null + } + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + } + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value) + } + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this) + } + } + } + + Headers.prototype.keys = function() { + var items = [] + this.forEach(function(value, name) { items.push(name) }) + return iteratorFor(items) + } + + Headers.prototype.values = function() { + var items = [] + this.forEach(function(value) { items.push(value) }) + return iteratorFor(items) + } + + Headers.prototype.entries = function() { + var items = [] + this.forEach(function(value, name) { items.push([name, value]) }) + return iteratorFor(items) + } + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result) + } + reader.onerror = function() { + reject(reader.error) + } + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader() + var promise = fileReaderReady(reader) + reader.readAsArrayBuffer(blob) + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader() + var promise = fileReaderReady(reader) + reader.readAsText(blob) + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf) + var chars = new Array(view.length) + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]) + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength) + view.set(new Uint8Array(buf)) + return view.buffer + } + } + + function Body() { + this.bodyUsed = false + + this._initBody = function(body) { + this._bodyInit = body + if (!body) { + this._bodyText = '' + } else if (typeof body === 'string') { + this._bodyText = body + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString() + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer) + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]) + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body) + } else { + throw new Error('unsupported BodyInit type') + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8') + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type) + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') + } + } + } + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + } + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + } + } + + this.text = function() { + var rejected = consumed(this) + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + } + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + } + } + + this.json = function() { + return this.text().then(JSON.parse) + } + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] + + function normalizeMethod(method) { + var upcased = method.toUpperCase() + return (methods.indexOf(upcased) > -1) ? upcased : method + } + + function Request(input, options) { + options = options || {} + var body = options.body + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url + this.credentials = input.credentials + if (!options.headers) { + this.headers = new Headers(input.headers) + } + this.method = input.method + this.mode = input.mode + if (!body && input._bodyInit != null) { + body = input._bodyInit + input.bodyUsed = true + } + } else { + this.url = String(input) + } + + this.credentials = options.credentials || this.credentials || 'omit' + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers) + } + this.method = normalizeMethod(options.method || this.method || 'GET') + this.mode = options.mode || this.mode || null + this.referrer = null + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body) + } + + Request.prototype.clone = function() { + return new Request(this, { body: this._bodyInit }) + } + + function decode(body) { + var form = new FormData() + body.trim().split('&').forEach(function(bytes) { + if (bytes) { + var split = bytes.split('=') + var name = split.shift().replace(/\+/g, ' ') + var value = split.join('=').replace(/\+/g, ' ') + form.append(decodeURIComponent(name), decodeURIComponent(value)) + } + }) + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers() + rawHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':') + var key = parts.shift().trim() + if (key) { + var value = parts.join(':').trim() + headers.append(key, value) + } + }) + return headers + } + + Body.call(Request.prototype) + + function Response(bodyInit, options) { + if (!options) { + options = {} + } + + this.type = 'default' + this.status = 'status' in options ? options.status : 200 + this.ok = this.status >= 200 && this.status < 300 + this.statusText = 'statusText' in options ? options.statusText : 'OK' + this.headers = new Headers(options.headers) + this.url = options.url || '' + this._initBody(bodyInit) + } + + Body.call(Response.prototype) + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + } + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}) + response.type = 'error' + return response + } + + var redirectStatuses = [301, 302, 303, 307, 308] + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + } + + self.Headers = Headers + self.Request = Request + self.Response = Response + + self.fetch = function(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init) + var xhr = new XMLHttpRequest() + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + } + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') + var body = 'response' in xhr ? xhr.response : xhr.responseText + resolve(new Response(body, options)) + } + + xhr.onerror = function() { + reject(new TypeError('Network request failed')) + } + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')) + } + + xhr.open(request.method, request.url, true) + + if (request.credentials === 'include') { + xhr.withCredentials = true + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob' + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value) + }) + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) + }) + } + self.fetch.polyfill = true +})(typeof self !== 'undefined' ? self : this); + +},{}],303:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +exports.CleartextMessage = CleartextMessage; +exports.readArmored = readArmored; + +var _config = _dereq_('./config'); + +var _config2 = _interopRequireDefault(_config); + +var _armor = _dereq_('./encoding/armor'); + +var _armor2 = _interopRequireDefault(_armor); + +var _enums = _dereq_('./enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _packet = _dereq_('./packet'); + +var _packet2 = _interopRequireDefault(_packet); + +var _signature = _dereq_('./signature'); + +var _message = _dereq_('./message'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @class + * @classdesc Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + * @param {String} text The cleartext of the signed message + * @param {module:signature} signature The detached signature or an empty signature if message not yet signed + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -4817,64 +26668,25 @@ process.umask = function() { return 0; }; * @requires encoding/armor * @requires enums * @requires packet + * @requires signature * @module cleartext */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.CleartextMessage = CleartextMessage; -exports.readArmored = readArmored; - -var _config = _dereq_('./config'); - -var _config2 = _interopRequireDefault(_config); - -var _packet = _dereq_('./packet'); - -var _packet2 = _interopRequireDefault(_packet); - -var _enums = _dereq_('./enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -var _armor = _dereq_('./encoding/armor.js'); - -var _armor2 = _interopRequireDefault(_armor); - -var _signature = _dereq_('./signature.js'); - -var sigModule = _interopRequireWildcard(_signature); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @class - * @classdesc Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} - * @param {String} text The cleartext of the signed message - * @param {module:signature} signature The detached signature or an empty signature if message not yet signed - */ - function CleartextMessage(text, signature) { if (!(this instanceof CleartextMessage)) { return new CleartextMessage(text, signature); } // normalize EOL to canonical form this.text = text.replace(/\r/g, '').replace(/[\t ]+\n/g, "\n").replace(/\n/g, "\r\n"); - if (signature && !(signature instanceof sigModule.Signature)) { + if (signature && !(signature instanceof _signature.Signature)) { throw new Error('Invalid signature input'); } - this.signature = signature || new sigModule.Signature(new _packet2.default.List()); + this.signature = signature || new _signature.Signature(new _packet2.default.List()); } /** * Returns the key IDs of the keys that signed the cleartext message - * @return {Array} array of keyid objects + * @returns {Array} array of keyid objects */ CleartextMessage.prototype.getSigningKeyIds = function () { var keyIds = []; @@ -4888,89 +26700,116 @@ CleartextMessage.prototype.getSigningKeyIds = function () { /** * Sign the cleartext message * @param {Array} privateKeys private keys with decrypted secret key data for signing - * @return {module:message~CleartextMessage} new cleartext message with signed content + * @param {Signature} signature (optional) any existing detached signature + * @param {Date} date (optional) The creation time of the signature that should be created + * @returns {Promise} new cleartext message with signed content + * @async */ -CleartextMessage.prototype.sign = function (privateKeys) { - return new CleartextMessage(this.text, this.signDetached(privateKeys)); -}; +CleartextMessage.prototype.sign = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(privateKeys) { + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = CleartextMessage; + _context.t1 = this.text; + _context.next = 4; + return this.signDetached(privateKeys, signature, date); + + case 4: + _context.t2 = _context.sent; + return _context.abrupt('return', new _context.t0(_context.t1, _context.t2)); + + case 6: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); /** * Sign the cleartext message * @param {Array} privateKeys private keys with decrypted secret key data for signing - * @return {module:signature~Signature} new detached signature of message content + * @param {Signature} signature (optional) any existing detached signature + * @param {Date} date (optional) The creation time of the signature that should be created + * @returns {Promise} new detached signature of message content + * @async */ -CleartextMessage.prototype.signDetached = function (privateKeys) { - var packetlist = new _packet2.default.List(); - var literalDataPacket = new _packet2.default.Literal(); - literalDataPacket.setText(this.text); - for (var i = 0; i < privateKeys.length; i++) { - if (privateKeys[i].isPublic()) { - throw new Error('Need private key for signing'); - } - var signaturePacket = new _packet2.default.Signature(); - signaturePacket.signatureType = _enums2.default.signature.text; - signaturePacket.hashAlgorithm = _config2.default.prefer_hash_algorithm; - var signingKeyPacket = privateKeys[i].getSigningKeyPacket(); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - if (!signingKeyPacket.isDecrypted) { - throw new Error('Private key is not decrypted.'); - } - signaturePacket.sign(signingKeyPacket, literalDataPacket); - packetlist.push(signaturePacket); - } - return new sigModule.Signature(packetlist); -}; +CleartextMessage.prototype.signDetached = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(privateKeys) { + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var literalDataPacket; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + literalDataPacket = new _packet2.default.Literal(); + + literalDataPacket.setText(this.text); + + _context2.t0 = _signature.Signature; + _context2.next = 5; + return (0, _message.createSignaturePackets)(literalDataPacket, privateKeys, signature, date); + + case 5: + _context2.t1 = _context2.sent; + return _context2.abrupt('return', new _context2.t0(_context2.t1)); + + case 7: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x4) { + return _ref2.apply(this, arguments); + }; +}(); /** * Verify signatures of cleartext signed message * @param {Array} keys array of keys to verify signatures - * @return {Array<{keyid: module:type/keyid, valid: Boolean}>} list of signer's keyid and validity of signature + * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns {Promise>} list of signer's keyid and validity of signature + * @async */ CleartextMessage.prototype.verify = function (keys) { - return this.verifyDetached(this.signature, keys); + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); + + return this.verifyDetached(this.signature, keys, date); }; /** * Verify signatures of cleartext signed message * @param {Array} keys array of keys to verify signatures - * @return {Array<{keyid: module:type/keyid, valid: Boolean}>} list of signer's keyid and validity of signature + * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns {Promise>} list of signer's keyid and validity of signature + * @async */ CleartextMessage.prototype.verifyDetached = function (signature, keys) { - var result = []; + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var signatureList = signature.packets; var literalDataPacket = new _packet2.default.Literal(); // we assume that cleartext signature is generated based on UTF8 cleartext literalDataPacket.setText(this.text); - for (var i = 0; i < signatureList.length; i++) { - var keyPacket = null; - for (var j = 0; j < keys.length; j++) { - keyPacket = keys[j].getSigningKeyPacket(signatureList[i].issuerKeyId); - if (keyPacket) { - break; - } - } - - var verifiedSig = {}; - if (keyPacket) { - verifiedSig.keyid = signatureList[i].issuerKeyId; - verifiedSig.valid = signatureList[i].verify(keyPacket, literalDataPacket); - } else { - verifiedSig.keyid = signatureList[i].issuerKeyId; - verifiedSig.valid = null; - } - - var packetlist = new _packet2.default.List(); - packetlist.push(signatureList[i]); - verifiedSig.signature = new sigModule.Signature(packetlist); - - result.push(verifiedSig); - } - return result; + return (0, _message.createVerificationObjects)(signatureList, [literalDataPacket], keys, date); }; /** * Get cleartext - * @return {String} cleartext of message + * @returns {String} cleartext of message */ CleartextMessage.prototype.getText = function () { // normalize end of line to \n @@ -4979,11 +26818,17 @@ CleartextMessage.prototype.getText = function () { /** * Returns ASCII armored text of cleartext signed message - * @return {String} ASCII armor + * @returns {String} ASCII armor */ CleartextMessage.prototype.armor = function () { + var hashes = this.signature.packets.map(function (packet) { + return _enums2.default.read(_enums2.default.hash, packet.hashAlgorithm).toUpperCase(); + }); + hashes = hashes.filter(function (item, i, ar) { + return ar.indexOf(item) === i; + }); var body = { - hash: _enums2.default.read(_enums2.default.hash, _config2.default.prefer_hash_algorithm).toUpperCase(), + hash: hashes.join(), text: this.text, data: this.signature.packets.write() }; @@ -4993,7 +26838,7 @@ CleartextMessage.prototype.armor = function () { /** * reads an OpenPGP cleartext signed message and returns a CleartextMessage object * @param {String} armoredText text to be parsed - * @return {module:cleartext~CleartextMessage} new cleartext message object + * @returns {module:cleartext~CleartextMessage} new cleartext message object * @static */ function readArmored(armoredText) { @@ -5004,9 +26849,8 @@ function readArmored(armoredText) { var packetlist = new _packet2.default.List(); packetlist.read(input.data); verifyHeaders(input.headers, packetlist); - var signature = new sigModule.Signature(packetlist); - var newMessage = new CleartextMessage(input.text, signature); - return newMessage; + var signature = new _signature.Signature(packetlist); + return new CleartextMessage(input.text, signature); } /** @@ -5017,16 +26861,20 @@ function readArmored(armoredText) { */ function verifyHeaders(headers, packetlist) { var checkHashAlgos = function checkHashAlgos(hashAlgos) { - function check(algo) { - return packetlist[i].hashAlgorithm === algo; - } + var check = function check(packet) { + return function (algo) { + return packet.hashAlgorithm === algo; + }; + }; + for (var i = 0; i < packetlist.length; i++) { - if (packetlist[i].tag === _enums2.default.packet.signature && !hashAlgos.some(check)) { + if (packetlist[i].tag === _enums2.default.packet.signature && !hashAlgos.some(check(packetlist[i]))) { return false; } } return true; }; + var oneHeader = null; var hashAlgos = []; headers.forEach(function (header) { @@ -5047,97 +26895,756 @@ function verifyHeaders(headers, packetlist) { throw new Error('Only "Hash" header allowed in cleartext signed message'); } }); + if (!hashAlgos.length && !checkHashAlgos([_enums2.default.hash.md5])) { throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); - } else if (!checkHashAlgos(hashAlgos)) { + } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { throw new Error('Hash algorithm mismatch in armor header and signature'); } } -},{"./config":10,"./encoding/armor.js":33,"./enums.js":35,"./packet":47,"./signature.js":66}],6:[function(_dereq_,module,exports){ -/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';var n=void 0,u=!0,aa=this;function ba(e,d){var c=e.split("."),f=aa;!(c[0]in f)&&f.execScript&&f.execScript("var "+c[0]);for(var a;c.length&&(a=c.shift());)!c.length&&d!==n?f[a]=d:f=f[a]?f[a]:f[a]={}};var C="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function K(e,d){this.index="number"===typeof d?d:0;this.d=0;this.buffer=e instanceof(C?Uint8Array:Array)?e:new (C?Uint8Array:Array)(32768);if(2*this.buffer.length<=this.index)throw Error("invalid index");this.buffer.length<=this.index&&ca(this)}function ca(e){var d=e.buffer,c,f=d.length,a=new (C?Uint8Array:Array)(f<<1);if(C)a.set(d);else for(c=0;c>>8&255]<<16|L[e>>>16&255]<<8|L[e>>>24&255])>>32-d:L[e]>>8-d);if(8>d+b)k=k<>d-m-1&1,8===++b&&(b=0,f[a++]=L[k],k=0,a===f.length&&(f=ca(this)));f[a]=k;this.buffer=f;this.d=b;this.index=a};K.prototype.finish=function(){var e=this.buffer,d=this.index,c;0M;++M){for(var R=M,S=R,ha=7,R=R>>>1;R;R>>>=1)S<<=1,S|=R&1,--ha;ga[M]=(S<>>0}var L=ga;function ja(e){this.buffer=new (C?Uint16Array:Array)(2*e);this.length=0}ja.prototype.getParent=function(e){return 2*((e-2)/4|0)};ja.prototype.push=function(e,d){var c,f,a=this.buffer,b;c=this.length;a[this.length++]=d;for(a[this.length++]=e;0a[f])b=a[c],a[c]=a[f],a[f]=b,b=a[c+1],a[c+1]=a[f+1],a[f+1]=b,c=f;else break;return this.length}; -ja.prototype.pop=function(){var e,d,c=this.buffer,f,a,b;d=c[0];e=c[1];this.length-=2;c[0]=c[this.length];c[1]=c[this.length+1];for(b=0;;){a=2*b+2;if(a>=this.length)break;a+2c[a]&&(a+=2);if(c[a]>c[b])f=c[b],c[b]=c[a],c[a]=f,f=c[b+1],c[b+1]=c[a+1],c[a+1]=f;else break;b=a}return{index:e,value:d,length:this.length}};function ka(e,d){this.e=ma;this.f=0;this.input=C&&e instanceof Array?new Uint8Array(e):e;this.c=0;d&&(d.lazy&&(this.f=d.lazy),"number"===typeof d.compressionType&&(this.e=d.compressionType),d.outputBuffer&&(this.b=C&&d.outputBuffer instanceof Array?new Uint8Array(d.outputBuffer):d.outputBuffer),"number"===typeof d.outputIndex&&(this.c=d.outputIndex));this.b||(this.b=new (C?Uint8Array:Array)(32768))}var ma=2,T=[],U; -for(U=0;288>U;U++)switch(u){case 143>=U:T.push([U+48,8]);break;case 255>=U:T.push([U-144+400,9]);break;case 279>=U:T.push([U-256+0,7]);break;case 287>=U:T.push([U-280+192,8]);break;default:throw"invalid literal: "+U;} -ka.prototype.h=function(){var e,d,c,f,a=this.input;switch(this.e){case 0:c=0;for(f=a.length;c>>8&255;l[h++]=p&255;l[h++]=p>>>8&255;if(C)l.set(b,h),h+=b.length,l=l.subarray(0,h);else{v=0;for(x=b.length;vs)for(;0s?s:138,A>s-3&&A=A?(E[D++]=17,E[D++]=A-3,H[17]++):(E[D++]=18,E[D++]=A-11,H[18]++),s-=A;else if(E[D++]=F[r],H[F[r]]++,s--,3>s)for(;0s?s:6,A>s-3&&Ay;y++)ia[y]=ea[Ia[y]];for(P=19;4=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272, -a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:throw"invalid length: "+a;}}var d=[],c,f;for(c=3;258>=c;c++)f=e(c),d[c]=f[2]<<24| -f[1]<<16|f[0];return d}(),Ga=C?new Uint32Array(Fa):Fa; -function na(e,d){function c(a,c){var b=a.g,d=[],f=0,e;e=Ga[a.length];d[f++]=e&65535;d[f++]=e>>16&255;d[f++]=e>>24;var g;switch(u){case 1===b:g=[0,b-1,0];break;case 2===b:g=[1,b-2,0];break;case 3===b:g=[2,b-3,0];break;case 4===b:g=[3,b-4,0];break;case 6>=b:g=[4,b-5,1];break;case 8>=b:g=[5,b-7,1];break;case 12>=b:g=[6,b-9,2];break;case 16>=b:g=[7,b-13,2];break;case 24>=b:g=[8,b-17,3];break;case 32>=b:g=[9,b-25,3];break;case 48>=b:g=[10,b-33,4];break;case 64>=b:g=[11,b-49,4];break;case 96>=b:g=[12,b- -65,5];break;case 128>=b:g=[13,b-97,5];break;case 192>=b:g=[14,b-129,6];break;case 256>=b:g=[15,b-193,6];break;case 384>=b:g=[16,b-257,7];break;case 512>=b:g=[17,b-385,7];break;case 768>=b:g=[18,b-513,8];break;case 1024>=b:g=[19,b-769,8];break;case 1536>=b:g=[20,b-1025,9];break;case 2048>=b:g=[21,b-1537,9];break;case 3072>=b:g=[22,b-2049,10];break;case 4096>=b:g=[23,b-3073,10];break;case 6144>=b:g=[24,b-4097,11];break;case 8192>=b:g=[25,b-6145,11];break;case 12288>=b:g=[26,b-8193,12];break;case 16384>= -b:g=[27,b-12289,12];break;case 24576>=b:g=[28,b-16385,13];break;case 32768>=b:g=[29,b-24577,13];break;default:throw"invalid distance";}e=g;d[f++]=e[0];d[f++]=e[1];d[f++]=e[2];var k,m;k=0;for(m=d.length;k=b;)t[b++]=0;for(b=0;29>=b;)w[b++]=0}t[256]=1;f=0;for(a=d.length;f=a){x&&c(x,-1);b=0;for(k=a-f;bk&&d+kb&&(a=f,b=k);if(258===k)break}return new qa(b,d-a)} -function oa(e,d){var c=e.length,f=new ja(572),a=new (C?Uint8Array:Array)(c),b,k,m,g,p;if(!C)for(g=0;g2*a[h-1]+b[h]&&(a[h]=2*a[h-1]+b[h]),m[h]=Array(a[h]),g[h]=Array(a[h]);for(l=0;le[l]?(m[h][q]=t,g[h][q]=d,w+=2):(m[h][q]=e[l],g[h][q]=l,++l);p[h]=0;1===b[h]&&f(h)}return k} -function pa(e){var d=new (C?Uint16Array:Array)(e.length),c=[],f=[],a=0,b,k,m,g;b=0;for(k=e.length;b>>=1}return d};ba("Zlib.RawDeflate",ka);ba("Zlib.RawDeflate.prototype.compress",ka.prototype.h);var Ka={NONE:0,FIXED:1,DYNAMIC:ma},V,La,$,Ma;if(Object.keys)V=Object.keys(Ka);else for(La in V=[],$=0,Ka)V[$++]=La;$=0;for(Ma=V.length;$a&&(a=c[p]),c[p]>=1;x=g<<16|p;for(s=n;s>>=1;switch(c){case 0:var d=this.input,a=this.d,b=this.b,e=this.a,f=d.length,g=k,h=k,l=b.length,n=k;this.c=this.f=0;if(a+1>=f)throw Error("invalid uncompressed block header: LEN");g=d[a++]|d[a++]<<8;if(a+1>=f)throw Error("invalid uncompressed block header: NLEN");h=d[a++]|d[a++]<<8;if(g===~h)throw Error("invalid uncompressed block header: length verify");if(a+g>d.length)throw Error("input buffer is broken");switch(this.i){case A:for(;e+g> -b.length;){n=l-e;g-=n;if(t)b.set(d.subarray(a,a+n),e),e+=n,a+=n;else for(;n--;)b[e++]=d[a++];this.a=e;b=this.e();e=this.a}break;case y:for(;e+g>b.length;)b=this.e({o:2});break;default:throw Error("invalid inflate mode");}if(t)b.set(d.subarray(a,a+g),e),e+=g,a+=g;else for(;g--;)b[e++]=d[a++];this.d=a;this.a=e;this.b=b;break;case 1:this.j(ba,ca);break;case 2:for(var m=B(this,5)+257,p=B(this,5)+1,s=B(this,4)+4,x=new (t?Uint8Array:Array)(C.length),Q=k,R=k,S=k,v=k,M=k,F=k,z=k,q=k,T=k,q=0;q=U?8:255>=U?9:279>=U?7:8;var ba=u(P),V=new (t?Uint8Array:Array)(30),W,ea;W=0;for(ea=V.length;W=g)throw Error("input buffer is broken");a|=e[f++]<>>d;c.c=b-d;c.d=f;return h} -function D(c,d){for(var a=c.f,b=c.c,e=c.input,f=c.d,g=e.length,h=d[0],l=d[1],n,m;b=g);)a|=e[f++]<>>16;if(m>b)throw Error("invalid code length: "+m);c.f=a>>m;c.c=b-m;c.d=f;return n&65535} -w.prototype.j=function(c,d){var a=this.b,b=this.a;this.n=c;for(var e=a.length-258,f,g,h,l;256!==(f=D(this,c));)if(256>f)b>=e&&(this.a=b,a=this.e(),b=this.a),a[b++]=f;else{g=f-257;l=H[g];0=e&&(this.a=b,a=this.e(),b=this.a);for(;l--;)a[b]=a[b++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=b}; -w.prototype.s=function(c,d){var a=this.b,b=this.a;this.n=c;for(var e=a.length,f,g,h,l;256!==(f=D(this,c));)if(256>f)b>=e&&(a=this.e(),e=a.length),a[b++]=f;else{g=f-257;l=H[g];0e&&(a=this.e(),e=a.length);for(;l--;)a[b]=a[b++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=b}; -w.prototype.e=function(){var c=new (t?Uint8Array:Array)(this.a-32768),d=this.a-32768,a,b,e=this.b;if(t)c.set(e.subarray(32768,c.length));else{a=0;for(b=c.length;aa;++a)e[a]=e[d+a];this.a=32768;return e}; -w.prototype.u=function(c){var d,a=this.input.length/this.d+1|0,b,e,f,g=this.input,h=this.b;c&&("number"===typeof c.o&&(a=c.o),"number"===typeof c.q&&(a+=c.q));2>a?(b=(g.length-this.d)/this.n[2],f=258*(b/2)|0,e=fd&&(this.b.length=d),c=this.b);return this.buffer=c};r("Zlib.RawInflate",w);r("Zlib.RawInflate.prototype.decompress",w.prototype.t);var X={ADAPTIVE:y,BLOCK:A},Y,Z,$,fa;if(Object.keys)Y=Object.keys(X);else for(Z in Y=[],$=0,X)Y[$++]=Z;$=0;for(fa=Y.length;$>>8&255]<<16|Q[d>>>16&255]<<8|Q[d>>>24&255])>>32-a:Q[d]>>8-a);if(8>a+f)g=g<>a-h-1&1,8===++f&&(f=0,e[b++]=Q[g],g=0,b===e.length&&(e=this.f()));e[b]=g;this.buffer=e;this.i=f;this.index=b};I.prototype.finish=function(){var d=this.buffer,a=this.index,c;0ca;++ca){for(var R=ca,ha=R,ia=7,R=R>>>1;R;R>>>=1)ha<<=1,ha|=R&1,--ia;ba[ca]=(ha<>>0}var Q=ba;function ja(d){this.buffer=new (G?Uint16Array:Array)(2*d);this.length=0}ja.prototype.getParent=function(d){return 2*((d-2)/4|0)};ja.prototype.push=function(d,a){var c,e,b=this.buffer,f;c=this.length;b[this.length++]=a;for(b[this.length++]=d;0b[e])f=b[c],b[c]=b[e],b[e]=f,f=b[c+1],b[c+1]=b[e+1],b[e+1]=f,c=e;else break;return this.length}; -ja.prototype.pop=function(){var d,a,c=this.buffer,e,b,f;a=c[0];d=c[1];this.length-=2;c[0]=c[this.length];c[1]=c[this.length+1];for(f=0;;){b=2*f+2;if(b>=this.length)break;b+2c[b]&&(b+=2);if(c[b]>c[f])e=c[f],c[f]=c[b],c[b]=e,e=c[f+1],c[f+1]=c[b+1],c[b+1]=e;else break;f=b}return{index:d,value:a,length:this.length}};function S(d){var a=d.length,c=0,e=Number.POSITIVE_INFINITY,b,f,g,h,k,p,q,r,n,l;for(r=0;rc&&(c=d[r]),d[r]>=1;l=g<<16|r;for(n=p;nT;T++)switch(z){case 143>=T:pa.push([T+48,8]);break;case 255>=T:pa.push([T-144+400,9]);break;case 279>=T:pa.push([T-256+0,7]);break;case 287>=T:pa.push([T-280+192,8]);break;default:m("invalid literal: "+T)} -ka.prototype.j=function(){var d,a,c,e,b=this.input;switch(this.h){case 0:c=0;for(e=b.length;c>>8&255;n[l++]=p&255;n[l++]=p>>>8&255;if(G)n.set(f,l),l+=f.length,n=n.subarray(0,l);else{q=0;for(r=f.length;qy)for(;0y?y:138,F>y-3&&F=F?(J[H++]=17,J[H++]=F-3,O[17]++):(J[H++]=18,J[H++]=F-11,O[18]++),y-=F;else if(J[H++]=K[u],O[K[u]]++,y--,3>y)for(;0y?y:6,F>y-3&&FD;D++)sa[D]=la[gb[D]];for(Z=19;4=b:return[265,b-11,1];case 14>=b:return[266,b-13,1];case 16>=b:return[267,b-15,1];case 18>=b:return[268,b-17,1];case 22>=b:return[269,b-19,2];case 26>=b:return[270,b-23,2];case 30>=b:return[271,b-27,2];case 34>=b:return[272, -b-31,2];case 42>=b:return[273,b-35,3];case 50>=b:return[274,b-43,3];case 58>=b:return[275,b-51,3];case 66>=b:return[276,b-59,3];case 82>=b:return[277,b-67,4];case 98>=b:return[278,b-83,4];case 114>=b:return[279,b-99,4];case 130>=b:return[280,b-115,4];case 162>=b:return[281,b-131,5];case 194>=b:return[282,b-163,5];case 226>=b:return[283,b-195,5];case 257>=b:return[284,b-227,5];case 258===b:return[285,b-258,0];default:m("invalid length: "+b)}}var a=[],c,e;for(c=3;258>=c;c++)e=d(c),a[c]=e[2]<<24|e[1]<< -16|e[0];return a}(),xa=G?new Uint32Array(wa):wa; -function qa(d,a){function c(b,c){var a=b.G,d=[],e=0,f;f=xa[b.length];d[e++]=f&65535;d[e++]=f>>16&255;d[e++]=f>>24;var g;switch(z){case 1===a:g=[0,a-1,0];break;case 2===a:g=[1,a-2,0];break;case 3===a:g=[2,a-3,0];break;case 4===a:g=[3,a-4,0];break;case 6>=a:g=[4,a-5,1];break;case 8>=a:g=[5,a-7,1];break;case 12>=a:g=[6,a-9,2];break;case 16>=a:g=[7,a-13,2];break;case 24>=a:g=[8,a-17,3];break;case 32>=a:g=[9,a-25,3];break;case 48>=a:g=[10,a-33,4];break;case 64>=a:g=[11,a-49,4];break;case 96>=a:g=[12,a- -65,5];break;case 128>=a:g=[13,a-97,5];break;case 192>=a:g=[14,a-129,6];break;case 256>=a:g=[15,a-193,6];break;case 384>=a:g=[16,a-257,7];break;case 512>=a:g=[17,a-385,7];break;case 768>=a:g=[18,a-513,8];break;case 1024>=a:g=[19,a-769,8];break;case 1536>=a:g=[20,a-1025,9];break;case 2048>=a:g=[21,a-1537,9];break;case 3072>=a:g=[22,a-2049,10];break;case 4096>=a:g=[23,a-3073,10];break;case 6144>=a:g=[24,a-4097,11];break;case 8192>=a:g=[25,a-6145,11];break;case 12288>=a:g=[26,a-8193,12];break;case 16384>= -a:g=[27,a-12289,12];break;case 24576>=a:g=[28,a-16385,13];break;case 32768>=a:g=[29,a-24577,13];break;default:m("invalid distance")}f=g;d[e++]=f[0];d[e++]=f[1];d[e++]=f[2];var h,k;h=0;for(k=d.length;h=f;)t[f++]=0;for(f=0;29>=f;)x[f++]=0}t[256]=1;e=0;for(b=a.length;e=b){r&&c(r,-1);f=0;for(g=b-e;fg&&a+gf&&(b=e,f=g);if(258===g)break}return new ua(f,a-b)} -function ra(d,a){var c=d.length,e=new ja(572),b=new (G?Uint8Array:Array)(c),f,g,h,k,p;if(!G)for(k=0;k2*b[l-1]+f[l]&&(b[l]=2*b[l-1]+f[l]),h[l]=Array(b[l]),k[l]=Array(b[l]);for(n=0;nd[n]?(h[l][s]=t,k[l][s]=a,x+=2):(h[l][s]=d[n],k[l][s]=n,++n);p[l]=0;1===f[l]&&e(l)}return g} -function ta(d){var a=new (G?Uint16Array:Array)(d.length),c=[],e=[],b=0,f,g,h,k;f=0;for(g=d.length;f>>=1}return a};function U(d,a){this.l=[];this.m=32768;this.e=this.g=this.c=this.q=0;this.input=G?new Uint8Array(d):d;this.s=!1;this.n=Aa;this.B=!1;if(a||!(a={}))a.index&&(this.c=a.index),a.bufferSize&&(this.m=a.bufferSize),a.bufferType&&(this.n=a.bufferType),a.resize&&(this.B=a.resize);switch(this.n){case Ba:this.b=32768;this.a=new (G?Uint8Array:Array)(32768+this.m+258);break;case Aa:this.b=0;this.a=new (G?Uint8Array:Array)(this.m);this.f=this.J;this.t=this.H;this.o=this.I;break;default:m(Error("invalid inflate mode"))}} -var Ba=0,Aa=1,Ca={D:Ba,C:Aa}; -U.prototype.p=function(){for(;!this.s;){var d=V(this,3);d&1&&(this.s=z);d>>>=1;switch(d){case 0:var a=this.input,c=this.c,e=this.a,b=this.b,f=a.length,g=w,h=w,k=e.length,p=w;this.e=this.g=0;c+1>=f&&m(Error("invalid uncompressed block header: LEN"));g=a[c++]|a[c++]<<8;c+1>=f&&m(Error("invalid uncompressed block header: NLEN"));h=a[c++]|a[c++]<<8;g===~h&&m(Error("invalid uncompressed block header: length verify"));c+g>a.length&&m(Error("input buffer is broken"));switch(this.n){case Ba:for(;b+g>e.length;){p= -k-b;g-=p;if(G)e.set(a.subarray(c,c+p),b),b+=p,c+=p;else for(;p--;)e[b++]=a[c++];this.b=b;e=this.f();b=this.b}break;case Aa:for(;b+g>e.length;)e=this.f({v:2});break;default:m(Error("invalid inflate mode"))}if(G)e.set(a.subarray(c,c+g),b),b+=g,c+=g;else for(;g--;)e[b++]=a[c++];this.c=c;this.b=b;this.a=e;break;case 1:this.o(Da,Ea);break;case 2:for(var q=V(this,5)+257,r=V(this,5)+1,n=V(this,4)+4,l=new (G?Uint8Array:Array)(Sa.length),s=w,t=w,x=w,E=w,B=w,C=w,L=w,v=w,M=w,v=0;v=W?8:255>=W?9:279>=W?7:8;var Da=S(cb),eb=new (G?Uint8Array:Array)(30),fb,hb;fb=0;for(hb=eb.length;fb=g&&m(Error("input buffer is broken")),c|=b[f++]<>>a;d.e=e-a;d.c=f;return h} -function Ta(d,a){for(var c=d.g,e=d.e,b=d.input,f=d.c,g=b.length,h=a[0],k=a[1],p,q;e=g);)c|=b[f++]<>>16;q>e&&m(Error("invalid code length: "+q));d.g=c>>q;d.e=e-q;d.c=f;return p&65535} -U.prototype.o=function(d,a){var c=this.a,e=this.b;this.u=d;for(var b=c.length-258,f,g,h,k;256!==(f=Ta(this,d));)if(256>f)e>=b&&(this.b=e,c=this.f(),e=this.b),c[e++]=f;else{g=f-257;k=Wa[g];0=b&&(this.b=e,c=this.f(),e=this.b);for(;k--;)c[e]=c[e++-h]}for(;8<=this.e;)this.e-=8,this.c--;this.b=e}; -U.prototype.I=function(d,a){var c=this.a,e=this.b;this.u=d;for(var b=c.length,f,g,h,k;256!==(f=Ta(this,d));)if(256>f)e>=b&&(c=this.f(),b=c.length),c[e++]=f;else{g=f-257;k=Wa[g];0b&&(c=this.f(),b=c.length);for(;k--;)c[e]=c[e++-h]}for(;8<=this.e;)this.e-=8,this.c--;this.b=e}; -U.prototype.f=function(){var d=new (G?Uint8Array:Array)(this.b-32768),a=this.b-32768,c,e,b=this.a;if(G)d.set(b.subarray(32768,d.length));else{c=0;for(e=d.length;cc;++c)b[c]=b[a+c];this.b=32768;return b}; -U.prototype.J=function(d){var a,c=this.input.length/this.c+1|0,e,b,f,g=this.input,h=this.a;d&&("number"===typeof d.v&&(c=d.v),"number"===typeof d.F&&(c+=d.F));2>c?(e=(g.length-this.c)/this.u[2],f=258*(e/2)|0,b=fa&&(this.a.length=a),d=this.a);return this.buffer=d};function ib(d){if("string"===typeof d){var a=d.split(""),c,e;c=0;for(e=a.length;c>>0;d=a}for(var b=1,f=0,g=d.length,h,k=0;0>>0};function jb(d,a){var c,e;this.input=d;this.c=0;if(a||!(a={}))a.index&&(this.c=a.index),a.verify&&(this.M=a.verify);c=d[this.c++];e=d[this.c++];switch(c&15){case kb:this.method=kb;break;default:m(Error("unsupported compression method"))}0!==((c<<8)+e)%31&&m(Error("invalid fcheck flag:"+((c<<8)+e)%31));e&32&&m(Error("fdict flag is not supported"));this.A=new U(d,{index:this.c,bufferSize:a.bufferSize,bufferType:a.bufferType,resize:a.resize})} -jb.prototype.p=function(){var d=this.input,a,c;a=this.A.p();this.c=this.A.c;this.M&&(c=(d[this.c++]<<24|d[this.c++]<<16|d[this.c++]<<8|d[this.c++])>>>0,c!==ib(a)&&m(Error("invalid adler-32 checksum")));return a};var kb=8;function lb(d,a){this.input=d;this.a=new (G?Uint8Array:Array)(32768);this.h=X.k;var c={},e;if((a||!(a={}))&&"number"===typeof a.compressionType)this.h=a.compressionType;for(e in a)c[e]=a[e];c.outputBuffer=this.a;this.z=new ka(this.input,c)}var X=oa; -lb.prototype.j=function(){var d,a,c,e,b,f,g,h=0;g=this.a;d=kb;switch(d){case kb:a=Math.LOG2E*Math.log(32768)-8;break;default:m(Error("invalid compression method"))}c=a<<4|d;g[h++]=c;switch(d){case kb:switch(this.h){case X.NONE:b=0;break;case X.r:b=1;break;case X.k:b=2;break;default:m(Error("unsupported compression type"))}break;default:m(Error("invalid compression method"))}e=b<<6|0;g[h++]=e|31-(256*c+e)%31;f=ib(this.input);this.z.b=h;g=this.z.j();h=g.length;G&&(g=new Uint8Array(g.buffer),g.length<= -h+4&&(this.a=new Uint8Array(g.length+4),this.a.set(g),g=this.a),g=g.subarray(0,h+4));g[h++]=f>>24&255;g[h++]=f>>16&255;g[h++]=f>>8&255;g[h++]=f&255;return g};function mb(d,a){var c,e,b,f;if(Object.keys)c=Object.keys(a);else for(e in c=[],b=0,a)c[b++]=e;b=0;for(f=c.length;b>> 3, + r = e - 8 * t;this.seek(t), this._eof = !1, this.readBits(r); + }, this.tellBit = function () { + for (var e = 8 * _t.tell(), n = r; 0 != (255 & n);) { + e--, n <<= 1; + }return e; + }, this.readByte = function () { + return 0 == (255 & r) ? _t.readByte() : this.readBits(8); + }, this.seek = function (e) { + _t.seek(e), r = 256; + }; + }).call(this), function () { + var e = 1;this.writeBit = function (r) { + e <<= 1, r && (e |= 1), 256 & e && (_t.writeByte(255 & e), e = 1); + }, this.writeByte = function (r) { + 1 === e ? _t.writeByte(r) : _t.writeBits(8, r); + }, this.flush = function () { + for (; 1 !== e;) { + this.writeBit(0); + }_t.flush && _t.flush(); + }; + }.call(this); + };return t.EOF = e.EOF, t.prototype = (0, _create2.default)(e.prototype), t.prototype.readBits = function (e) { + var t, + r = 0;if (e > 31) return (r = 65536 * this.readBits(e - 16)) + this.readBits(16);for (t = 0; t < e; t++) { + r <<= 1, this.readBit() > 0 && r++; + }return r; + }, t.prototype.writeBits = function (e, t) { + if (e > 32) { + var r = 65535 & t, + n = (t - r) / 65536;return this.writeBits(e - 16, n), void this.writeBits(16, r); + }var i;for (i = e - 1; i >= 0; i--) { + this.writeBit(t >>> i & 1); + } + }, t; +}(Stream), Util = function (e, t) { + var r = (0, _create2.default)(null), + n = t.EOF;r.coerceInputStream = function (e, r) { + if ("readByte" in e) { + if (r && !("read" in e)) { + var i = e;e = new t(), e.readByte = function () { + var e = i.readByte();return e === n && (this._eof = !0), e; + }, "size" in i && (e.size = i.size), "seek" in i && (e.seek = function (e) { + i.seek(e), this._eof = !1; + }), "tell" in i && (e.tell = i.tell.bind(i)); + } + } else { + var o = e;e = new t(), e.size = o.length, e.pos = 0, e.readByte = function () { + return this.pos >= this.size ? n : o[this.pos++]; + }, e.read = function (e, t, r) { + for (var n = 0; n < r && this.pos < o.length;) { + e[t++] = o[this.pos++], n++; + }return n; + }, e.seek = function (e) { + this.pos = e; + }, e.tell = function () { + return this.pos; + }, e.eof = function () { + return this.pos >= o.length; + }; + }return e; + };var i = function i(e, t) { + this.buffer = e, this.resizeOk = t, this.pos = 0; + };i.prototype = (0, _create2.default)(t.prototype), i.prototype.writeByte = function (e) { + if (this.resizeOk && this.pos >= this.buffer.length) { + var t = r.makeU8Buffer(2 * this.buffer.length);t.set(this.buffer), this.buffer = t; + }this.buffer[this.pos++] = e; + }, i.prototype.getBuffer = function () { + if (this.pos !== this.buffer.length) { + if (!this.resizeOk) throw new TypeError("outputsize does not match decoded input");var e = r.makeU8Buffer(this.pos);e.set(this.buffer.subarray(0, this.pos)), this.buffer = e; + }return this.buffer; + }, r.coerceOutputStream = function (e, t) { + var n = { stream: e, retval: e };if (e) { + if ("object" == (typeof e === "undefined" ? "undefined" : (0, _typeof3.default)(e)) && "writeByte" in e) return n;"number" == typeof t ? (console.assert(t >= 0), n.stream = new i(r.makeU8Buffer(t), !1)) : n.stream = new i(e, !1); + } else n.stream = new i(r.makeU8Buffer(16384), !0);return Object.defineProperty(n, "retval", { get: n.stream.getBuffer.bind(n.stream) }), n; + }, r.compressFileHelper = function (e, t, n) { + return function (i, o, f) { + i = r.coerceInputStream(i);var a = r.coerceOutputStream(o, o);o = a.stream;var u;for (u = 0; u < e.length; u++) { + o.writeByte(e.charCodeAt(u)); + }var s;if (s = "size" in i && i.size >= 0 ? i.size : -1, n) { + var c = r.coerceOutputStream([]);for (r.writeUnsignedNumber(c.stream, s + 1), c = c.retval, u = 0; u < c.length - 1; u++) { + o.writeByte(c[u]); + }n = c[c.length - 1]; + } else r.writeUnsignedNumber(o, s + 1);return t(i, o, s, f, n), a.retval; + }; + }, r.decompressFileHelper = function (e, t) { + return function (n, i) { + n = r.coerceInputStream(n);var o;for (o = 0; o < e.length; o++) { + if (e.charCodeAt(o) !== n.readByte()) throw new Error("Bad magic"); + }var f = r.readUnsignedNumber(n) - 1, + a = r.coerceOutputStream(i, f);return i = a.stream, t(n, i, f), a.retval; + }; + }, r.compressWithModel = function (e, t, r) { + for (var i = 0; i !== t;) { + var o = e.readByte();if (o === n) { + r.encode(256);break; + }r.encode(o), i++; + } + }, r.decompressWithModel = function (e, t, r) { + for (var n = 0; n !== t;) { + var i = r.decode();if (256 === i) break;e.writeByte(i), n++; + } + }, r.writeUnsignedNumber = function (e, t) { + console.assert(t >= 0);var r, + n = [];do { + n.push(127 & t), t = Math.floor(t / 128); + } while (0 !== t);for (n[0] |= 128, r = n.length - 1; r >= 0; r--) { + e.writeByte(n[r]); + }return e; + }, r.readUnsignedNumber = function (e) { + for (var t, r = 0;;) { + if (128 & (t = e.readByte())) { + r += 127 & t;break; + }r = 128 * (r + t); + }return r; + };var o = function o(e) { + for (var t = 0, r = e.length; t < r; t++) { + e[t] = 0; + }return e; + }, + f = function f(e) { + return o(new Array(e)); + }, + a = function a(e) { + return e; + };"undefined" != typeof process && Array.prototype.some.call(new Uint32Array(128), function (e) { + return 0 !== e; + }) && (a = o), r.makeU8Buffer = "undefined" != typeof Uint8Array ? function (e) { + return a(new Uint8Array(e)); + } : "undefined" != typeof Buffer ? function (e) { + var t = new Buffer(e);return t.fill(0), t; + } : f, r.makeU16Buffer = "undefined" != typeof Uint16Array ? function (e) { + return a(new Uint16Array(e)); + } : f, r.makeU32Buffer = "undefined" != typeof Uint32Array ? function (e) { + return a(new Uint32Array(e)); + } : f, r.makeS32Buffer = "undefined" != typeof Int32Array ? function (e) { + return a(new Int32Array(e)); + } : f, r.arraycopy = function (e, t) { + console.assert(e.length >= t.length);for (var r = 0, n = t.length; r < n; r++) { + e[r] = t[r]; + }return e; + };var u = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8];console.assert(256 === u.length);var s = r.fls = function (e) { + return console.assert(e >= 0), e > 4294967295 ? 32 + s(Math.floor(e / 4294967296)) : 0 != (4294901760 & e) ? 0 != (4278190080 & e) ? 24 + u[e >>> 24 & 255] : 16 + u[e >>> 16] : 0 != (65280 & e) ? 8 + u[e >>> 8] : u[e]; + };return r.log2c = function (e) { + return 0 === e ? -1 : s(e - 1); + }, e(r); +}(freeze, Stream), BWT = function (e, t) { + var r = console.assert.bind(console), + n = function n(e, t, r, _n) { + var i;for (i = 0; i < _n; i++) { + t[i] = 0; + }for (i = 0; i < r; i++) { + t[e[i]]++; + } + }, + i = function i(e, t, r, n) { + var i, + o = 0;if (n) for (i = 0; i < r; i++) { + o += e[i], t[i] = o; + } else for (i = 0; i < r; i++) { + o += e[i], t[i] = o - e[i]; + } + }, + o = function o(e, t, _o, f, a, u) { + var s, c, h, l, d;for (_o === f && n(e, _o, a, u), i(_o, f, u, !1), h = a - 1, s = f[d = e[h]], h--, t[s++] = e[h] < d ? ~h : h, c = 0; c < a; c++) { + (h = t[c]) > 0 ? (r(e[h] >= e[h + 1]), (l = e[h]) !== d && (f[d] = s, s = f[d = l]), r(c < s), h--, t[s++] = e[h] < d ? ~h : h, t[c] = 0) : h < 0 && (t[c] = ~h); + }for (_o === f && n(e, _o, a, u), i(_o, f, u, 1), c = a - 1, s = f[d = 0]; c >= 0; c--) { + (h = t[c]) > 0 && (r(e[h] <= e[h + 1]), (l = e[h]) !== d && (f[d] = s, s = f[d = l]), r(s <= c), h--, t[--s] = e[h] > d ? ~(h + 1) : h, t[c] = 0); + } + }, + f = function f(e, t, n, i) { + var o, f, a, u, s, c, h, l, d, B;for (r(n > 0), o = 0; (a = t[o]) < 0; o++) { + t[o] = ~a, r(o + 1 < n); + }if (o < i) for (f = o, o++; r(o < n), !((a = t[o]) < 0 && (t[f++] = ~a, t[o] = 0, f === i)); o++) {}l = e[o = f = n - 1];do { + d = l; + } while (--o >= 0 && (l = e[o]) >= d);for (; o >= 0;) { + do { + d = l; + } while (--o >= 0 && (l = e[o]) <= d);if (o >= 0) { + t[i + (o + 1 >>> 1)] = f - o, f = o + 1;do { + d = l; + } while (--o >= 0 && (l = e[o]) >= d); + } + }for (o = 0, h = 0, u = n, c = 0; o < i; o++) { + if (a = t[o], s = t[i + (a >>> 1)], B = !0, s === c && u + s < n) { + for (f = 0; f < s && e[a + f] === e[u + f];) { + f++; + }f === s && (B = !1); + }B && (h++, u = a, c = s), t[i + (a >>> 1)] = h; + }return h; + }, + a = function a(e, t, o, f, _a, u) { + var s, c, h, l, d;for (o === f && n(e, o, _a, u), i(o, f, u, !1), h = _a - 1, s = f[d = e[h]], t[s++] = h > 0 && e[h - 1] < d ? ~h : h, c = 0; c < _a; c++) { + h = t[c], t[c] = ~h, h > 0 && (h--, r(e[h] >= e[h + 1]), (l = e[h]) !== d && (f[d] = s, s = f[d = l]), r(c < s), t[s++] = h > 0 && e[h - 1] < d ? ~h : h); + }for (o === f && n(e, o, _a, u), i(o, f, u, !0), c = _a - 1, s = f[d = 0]; c >= 0; c--) { + (h = t[c]) > 0 ? (h--, r(e[h] <= e[h + 1]), (l = e[h]) !== d && (f[d] = s, s = f[d = l]), r(s <= c), t[--s] = 0 === h || e[h - 1] > d ? ~h : h) : t[c] = ~h; + } + }, + u = function u(e, t, o, f, a, _u) { + var s, + c, + h, + l, + d, + B = -1;for (o === f && n(e, o, a, _u), i(o, f, _u, !1), h = a - 1, s = f[d = e[h]], t[s++] = h > 0 && e[h - 1] < d ? ~h : h, c = 0; c < a; c++) { + (h = t[c]) > 0 ? (h--, r(e[h] >= e[h + 1]), t[c] = ~(l = e[h]), l !== d && (f[d] = s, s = f[d = l]), r(c < s), t[s++] = h > 0 && e[h - 1] < d ? ~h : h) : 0 !== h && (t[c] = ~h); + }for (o === f && n(e, o, a, _u), i(o, f, _u, !0), c = a - 1, s = f[d = 0]; c >= 0; c--) { + (h = t[c]) > 0 ? (h--, r(e[h] <= e[h + 1]), t[c] = l = e[h], l !== d && (f[d] = s, s = f[d = l]), r(s <= c), t[--s] = h > 0 && e[h - 1] > d ? ~e[h - 1] : h) : 0 !== h ? t[c] = ~h : B = c; + }return B; + }, + s = function s(e, c, h, l, d, B) { + var p, + v, + m, + w, + E, + g, + _, + b, + y, + R, + C, + k, + T, + O = 0, + S = 0;for (d <= 256 ? (p = t.makeS32Buffer(d), d <= h ? (v = c.subarray(l + h - d), S = 1) : (v = t.makeS32Buffer(d), S = 3)) : d <= h ? (p = c.subarray(l + h - d), d <= h - d ? (v = c.subarray(l + h - 2 * d), S = 0) : d <= 1024 ? (v = t.makeS32Buffer(d), S = 2) : (v = p, S = 8)) : (p = v = t.makeS32Buffer(d), S = 12), n(e, p, l, d), i(p, v, d, !0), w = 0; w < l; w++) { + c[w] = 0; + }g = -1, w = l - 1, E = l, _ = 0, k = e[l - 1];do { + T = k; + } while (--w >= 0 && (k = e[w]) >= T);for (; w >= 0;) { + do { + T = k; + } while (--w >= 0 && (k = e[w]) <= T);if (w >= 0) { + g >= 0 && (c[g] = E), g = --v[T], E = w, ++_;do { + T = k; + } while (--w >= 0 && (k = e[w]) >= T); + } + }if (_ > 1 ? (o(e, c, p, v, l, d), R = f(e, c, l, _)) : 1 === _ ? (c[g] = E + 1, R = 1) : R = 0, R < _) { + for (0 != (4 & S) && (p = null, v = null), 0 != (2 & S) && (v = null), C = l + h - 2 * _, 0 == (13 & S) && (d + R <= C ? C -= d : S |= 8), r(l >>> 1 <= C + _), w = _ + (l >>> 1) - 1, E = 2 * _ + C - 1; _ <= w; w--) { + 0 !== c[w] && (c[E--] = c[w] - 1); + }m = c.subarray(_ + C), s(m, c, C, _, R, !1), m = null, w = l - 1, E = 2 * _ - 1, k = e[l - 1];do { + T = k; + } while (--w >= 0 && (k = e[w]) >= T);for (; w >= 0;) { + do { + T = k; + } while (--w >= 0 && (k = e[w]) <= T);if (w >= 0) { + c[E--] = w + 1;do { + T = k; + } while (--w >= 0 && (k = e[w]) >= T); + } + }for (w = 0; w < _; w++) { + c[w] = c[_ + c[w]]; + }0 != (4 & S) && (p = v = t.makeS32Buffer(d)), 0 != (2 & S) && (v = t.makeS32Buffer(d)); + }if (0 != (8 & S) && n(e, p, l, d), _ > 1) { + i(p, v, d, !0), w = _ - 1, E = l, b = c[_ - 1], T = e[b];do { + for (y = v[k = T]; y < E;) { + c[--E] = 0; + }do { + if (c[--E] = b, --w < 0) break;b = c[w]; + } while ((T = e[b]) === k); + } while (w >= 0);for (; E > 0;) { + c[--E] = 0; + } + }return B ? O = u(e, c, p, v, l, d) : a(e, c, p, v, l, d), p = null, v = null, O; + }, + c = (0, _create2.default)(null);return c.suffixsort = function (e, t, n, i) { + if (r(e && t && e.length >= n && t.length >= n), n <= 1) return 1 === n && (t[0] = 0), 0;if (!i) if (1 === e.BYTES_PER_ELEMENT) i = 256;else { + if (2 !== e.BYTES_PER_ELEMENT) throw new Error("Need to specify alphabetSize");i = 65536; + }return r(i > 0), e.BYTES_PER_ELEMENT && r(i <= 1 << 8 * e.BYTES_PER_ELEMENT), s(e, t, 0, n, i, !1); + }, c.bwtransform = function (e, t, n, i, o) { + var f, a;if (r(e && t && n), r(e.length >= i && t.length >= i && n.length >= i), i <= 1) return 1 === i && (t[0] = e[0]), i;if (!o) if (1 === e.BYTES_PER_ELEMENT) o = 256;else { + if (2 !== e.BYTES_PER_ELEMENT) throw new Error("Need to specify alphabetSize");o = 65536; + }for (r(o > 0), e.BYTES_PER_ELEMENT && r(o <= 1 << 8 * e.BYTES_PER_ELEMENT), a = s(e, n, 0, i, o, !0), t[0] = e[i - 1], f = 0; f < a; f++) { + t[f + 1] = n[f]; + }for (f += 1; f < i; f++) { + t[f] = n[f]; + }return a + 1; + }, c.unbwtransform = function (e, r, n, i, o) { + var f, + a, + u = t.makeU32Buffer(256);for (f = 0; f < 256; f++) { + u[f] = 0; + }for (f = 0; f < i; f++) { + n[f] = u[e[f]]++; + }for (f = 0, a = 0; f < 256; f++) { + a += u[f], u[f] = a - u[f]; + }for (f = i - 1, a = 0; f >= 0; f--) { + a = n[a] + u[r[f] = e[a]], a += a < o ? 1 : 0; + }u = null; + }, c.bwtransform2 = function (e, n, i, o) { + var f, + a, + u = 0;if (r(e && n), r(e.length >= i && n.length >= i), i <= 1) return 1 === i && (n[0] = e[0]), 0;if (!o) if (1 === e.BYTES_PER_ELEMENT) o = 256;else { + if (2 !== e.BYTES_PER_ELEMENT) throw new Error("Need to specify alphabetSize");o = 65536; + }r(o > 0), e.BYTES_PER_ELEMENT && r(o <= 1 << 8 * e.BYTES_PER_ELEMENT);var c;if ((c = e.length >= 2 * i ? e : o <= 256 ? t.makeU8Buffer(2 * i) : o <= 65536 ? t.makeU16Buffer(2 * i) : t.makeU32Buffer(2 * i)) !== e) for (f = 0; f < i; f++) { + c[f] = e[f]; + }for (f = 0; f < i; f++) { + c[i + f] = c[f]; + }var h = t.makeS32Buffer(2 * i);for (s(c, h, 0, 2 * i, o, !1), f = 0, a = 0; f < 2 * i; f++) { + var l = h[f];l < i && (0 === l && (u = a), --l < 0 && (l = i - 1), n[a++] = e[l]); + }return r(a === i), u; + }, e(c); +}(freeze, Util), CRC32 = function (e) { + var t = e.arraycopy(e.makeU32Buffer(256), [0, 79764919, 159529838, 222504665, 319059676, 398814059, 445009330, 507990021, 638119352, 583659535, 797628118, 726387553, 890018660, 835552979, 1015980042, 944750013, 1276238704, 1221641927, 1167319070, 1095957929, 1595256236, 1540665371, 1452775106, 1381403509, 1780037320, 1859660671, 1671105958, 1733955601, 2031960084, 2111593891, 1889500026, 1952343757, 2552477408, 2632100695, 2443283854, 2506133561, 2334638140, 2414271883, 2191915858, 2254759653, 3190512472, 3135915759, 3081330742, 3009969537, 2905550212, 2850959411, 2762807018, 2691435357, 3560074640, 3505614887, 3719321342, 3648080713, 3342211916, 3287746299, 3467911202, 3396681109, 4063920168, 4143685023, 4223187782, 4286162673, 3779000052, 3858754371, 3904687514, 3967668269, 881225847, 809987520, 1023691545, 969234094, 662832811, 591600412, 771767749, 717299826, 311336399, 374308984, 453813921, 533576470, 25881363, 88864420, 134795389, 214552010, 2023205639, 2086057648, 1897238633, 1976864222, 1804852699, 1867694188, 1645340341, 1724971778, 1587496639, 1516133128, 1461550545, 1406951526, 1302016099, 1230646740, 1142491917, 1087903418, 2896545431, 2825181984, 2770861561, 2716262478, 3215044683, 3143675388, 3055782693, 3001194130, 2326604591, 2389456536, 2200899649, 2280525302, 2578013683, 2640855108, 2418763421, 2498394922, 3769900519, 3832873040, 3912640137, 3992402750, 4088425275, 4151408268, 4197601365, 4277358050, 3334271071, 3263032808, 3476998961, 3422541446, 3585640067, 3514407732, 3694837229, 3640369242, 1762451694, 1842216281, 1619975040, 1682949687, 2047383090, 2127137669, 1938468188, 2001449195, 1325665622, 1271206113, 1183200824, 1111960463, 1543535498, 1489069629, 1434599652, 1363369299, 622672798, 568075817, 748617968, 677256519, 907627842, 853037301, 1067152940, 995781531, 51762726, 131386257, 177728840, 240578815, 269590778, 349224269, 429104020, 491947555, 4046411278, 4126034873, 4172115296, 4234965207, 3794477266, 3874110821, 3953728444, 4016571915, 3609705398, 3555108353, 3735388376, 3664026991, 3290680682, 3236090077, 3449943556, 3378572211, 3174993278, 3120533705, 3032266256, 2961025959, 2923101090, 2868635157, 2813903052, 2742672763, 2604032198, 2683796849, 2461293480, 2524268063, 2284983834, 2364738477, 2175806836, 2238787779, 1569362073, 1498123566, 1409854455, 1355396672, 1317987909, 1246755826, 1192025387, 1137557660, 2072149281, 2135122070, 1912620623, 1992383480, 1753615357, 1816598090, 1627664531, 1707420964, 295390185, 358241886, 404320391, 483945776, 43990325, 106832002, 186451547, 266083308, 932423249, 861060070, 1041341759, 986742920, 613929101, 542559546, 756411363, 701822548, 3316196985, 3244833742, 3425377559, 3370778784, 3601682597, 3530312978, 3744426955, 3689838204, 3819031489, 3881883254, 3928223919, 4007849240, 4037393693, 4100235434, 4180117107, 4259748804, 2310601993, 2373574846, 2151335527, 2231098320, 2596047829, 2659030626, 2470359227, 2550115596, 2947551409, 2876312838, 2788305887, 2733848168, 3165939309, 3094707162, 3040238851, 2985771188]);return function () { + var e = 4294967295;this.getCRC = function () { + return ~e >>> 0; + }, this.updateCRC = function (r) { + e = e << 8 ^ t[255 & (e >>> 24 ^ r)]; + }, this.updateCRCRun = function (r, n) { + for (; n-- > 0;) { + e = e << 8 ^ t[255 & (e >>> 24 ^ r)]; + } + }; + }; +}(Util), HuffmanAllocator = function (e, t) { + var r = function r(e, t, _r) { + for (var n = e.length, i = t, o = e.length - 2; t >= _r && e[t] % n > i;) { + o = t, t -= i - t + 1; + }for (t = Math.max(_r - 1, t); o > t + 1;) { + var f = t + o >> 1;e[f] % n > i ? o = f : t = f; + }return o; + }, + n = function n(e) { + var t = e.length;e[0] += e[1];var r, n, i, o;for (r = 0, n = 1, i = 2; n < t - 1; n++) { + i >= t || e[r] < e[i] ? (o = e[r], e[r++] = n) : o = e[i++], i >= t || r < n && e[r] < e[i] ? (o += e[r], e[r++] = n + t) : o += e[i++], e[n] = o; + } + }, + i = function i(e, t) { + var n, + i = e.length - 2;for (n = 1; n < t - 1 && i > 1; n++) { + i = r(e, i - 1, 0); + }return i; + }, + o = function o(e) { + var t, + n, + i, + o, + f = e.length - 2, + a = e.length - 1;for (t = 1, n = 2; n > 0; t++) { + for (i = f, f = r(e, i - 1, 0), o = n - (i - f); o > 0; o--) { + e[a--] = t; + }n = i - f << 1; + } + }, + f = function f(e, t, n) { + var i, + o, + f, + a, + u = e.length - 2, + s = e.length - 1, + c = 1 == n ? 2 : 1, + h = 1 == n ? t - 2 : t;for (i = c << 1; i > 0; c++) { + for (o = u, u = u <= t ? u : r(e, o - 1, t), f = 0, c >= n ? f = Math.min(h, 1 << c - n) : c == n - 1 && (f = 1, e[u] == o && u++), a = i - (o - u + f); a > 0; a--) { + e[s--] = c; + }h -= f, i = o - u + f << 1; + } + };return e({ allocateHuffmanCodeLengths: function allocateHuffmanCodeLengths(e, r) { + switch (e.length) {case 2: + e[1] = 1;case 1: + return void (e[0] = 1);}n(e);var a = i(e, r);if (e[0] % e.length >= a) o(e);else { + var u = r - t.fls(a - 1);f(e, a, u); + } + } }); +}(freeze, Util), Bzip2 = function (e, t, r, n, i, o, f) { + var a = o.EOF, + u = function u(e, t) { + var r, + n = e[t];for (r = t; r > 0; r--) { + e[r] = e[r - 1]; + }return e[0] = n, n; + }, + s = { OK: 0, LAST_BLOCK: -1, NOT_BZIP_DATA: -2, UNEXPECTED_INPUT_EOF: -3, UNEXPECTED_OUTPUT_EOF: -4, DATA_ERROR: -5, OUT_OF_MEMORY: -6, OBSOLETE_INPUT: -7, END_OF_BLOCK: -8 }, + c = {};c[s.LAST_BLOCK] = "Bad file checksum", c[s.NOT_BZIP_DATA] = "Not bzip data", c[s.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF", c[s.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF", c[s.DATA_ERROR] = "Data error", c[s.OUT_OF_MEMORY] = "Out of memory", c[s.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";var h = function h(e, t) { + var r = c[e] || "unknown error";t && (r += ": " + t);var n = new TypeError(r);throw n.errorCode = e, n; + }, + l = function l(e, t) { + this.writePos = this.writeCurrent = this.writeCount = 0, this._start_bunzip(e, t); + };l.prototype._init_block = function () { + return this._get_next_block() ? (this.blockCRC = new n(), !0) : (this.writeCount = -1, !1); + }, l.prototype._start_bunzip = function (e, r) { + var n = f.makeU8Buffer(4);4 === e.read(n, 0, 4) && "BZh" === String.fromCharCode(n[0], n[1], n[2]) || h(s.NOT_BZIP_DATA, "bad magic");var i = n[3] - 48;(i < 1 || i > 9) && h(s.NOT_BZIP_DATA, "level out of range"), this.reader = new t(e), this.dbufSize = 1e5 * i, this.nextoutput = 0, this.outputStream = r, this.streamCRC = 0; + }, l.prototype._get_next_block = function () { + var e, + t, + r, + n = this.reader, + i = n.readBits(48);if (25779555029136 === i) return !1;54156738319193 !== i && h(s.NOT_BZIP_DATA), this.targetBlockCRC = n.readBits(32), this.streamCRC = (this.targetBlockCRC ^ (this.streamCRC << 1 | this.streamCRC >>> 31)) >>> 0, n.readBits(1) && h(s.OBSOLETE_INPUT);var o = n.readBits(24);o > this.dbufSize && h(s.DATA_ERROR, "initial position out of bounds");var a = n.readBits(16), + c = f.makeU8Buffer(256), + l = 0;for (e = 0; e < 16; e++) { + if (a & 1 << 15 - e) { + var d = 16 * e;for (r = n.readBits(16), t = 0; t < 16; t++) { + r & 1 << 15 - t && (c[l++] = d + t); + } + } + }var B = n.readBits(3);(B < 2 || B > 6) && h(s.DATA_ERROR);var p = n.readBits(15);0 === p && h(s.DATA_ERROR);var v = f.makeU8Buffer(256);for (e = 0; e < B; e++) { + v[e] = e; + }var m = f.makeU8Buffer(p);for (e = 0; e < p; e++) { + for (t = 0; n.readBits(1); t++) { + t >= B && h(s.DATA_ERROR); + }m[e] = u(v, t); + }var w, + E = l + 2, + g = [];for (t = 0; t < B; t++) { + var _ = f.makeU8Buffer(E), + b = f.makeU16Buffer(21);for (a = n.readBits(5), e = 0; e < E; e++) { + for (; (a < 1 || a > 20) && h(s.DATA_ERROR), n.readBits(1);) { + n.readBits(1) ? a-- : a++; + }_[e] = a; + }var y, R;for (y = R = _[0], e = 1; e < E; e++) { + _[e] > R ? R = _[e] : _[e] < y && (y = _[e]); + }w = {}, g.push(w), w.permute = f.makeU16Buffer(258), w.limit = f.makeU32Buffer(22), w.base = f.makeU32Buffer(21), w.minLen = y, w.maxLen = R;var C = 0;for (e = y; e <= R; e++) { + for (b[e] = w.limit[e] = 0, a = 0; a < E; a++) { + _[a] === e && (w.permute[C++] = a); + } + }for (e = 0; e < E; e++) { + b[_[e]]++; + }for (C = a = 0, e = y; e < R; e++) { + C += b[e], w.limit[e] = C - 1, C <<= 1, a += b[e], w.base[e + 1] = C - a; + }w.limit[R + 1] = Number.MAX_VALUE, w.limit[R] = C + b[R] - 1, w.base[y] = 0; + }var k = f.makeU32Buffer(256);for (e = 0; e < 256; e++) { + v[e] = e; + }var T, + O = 0, + S = 0, + U = 0, + A = this.dbuf = f.makeU32Buffer(this.dbufSize);for (E = 0;;) { + for (E-- || (E = 49, U >= p && h(s.DATA_ERROR), w = g[m[U++]]), e = w.minLen, t = n.readBits(e); e > w.maxLen && h(s.DATA_ERROR), !(t <= w.limit[e]); e++) { + t = t << 1 | n.readBits(1); + }t -= w.base[e], (t < 0 || t >= 258) && h(s.DATA_ERROR);var z = w.permute[t];if (0 !== z && 1 !== z) { + if (O) for (O = 0, S + a > this.dbufSize && h(s.DATA_ERROR), T = c[v[0]], k[T] += a; a--;) { + A[S++] = T; + }if (z > l) break;S >= this.dbufSize && h(s.DATA_ERROR), e = z - 1, T = u(v, e), T = c[T], k[T]++, A[S++] = T; + } else O || (O = 1, a = 0), a += 0 === z ? O : 2 * O, O <<= 1; + }for ((o < 0 || o >= S) && h(s.DATA_ERROR), t = 0, e = 0; e < 256; e++) { + r = t + k[e], k[e] = t, t = r; + }for (e = 0; e < S; e++) { + T = 255 & A[e], A[k[T]] |= e << 8, k[T]++; + }var N = 0, + L = 0, + P = 0;return S && (N = A[o], L = 255 & N, N >>= 8, P = -1), this.writePos = N, this.writeCurrent = L, this.writeCount = S, this.writeRun = P, !0; + }, l.prototype._read_bunzip = function (e, t) { + var r, n, i;if (this.writeCount < 0) return 0;for (var o = this.dbuf, f = this.writePos, a = this.writeCurrent, u = this.writeCount, c = (this.outputsize, this.writeRun); u;) { + for (u--, n = a, f = o[f], a = 255 & f, f >>= 8, 3 == c++ ? (r = a, i = n, a = -1) : (r = 1, i = a), this.blockCRC.updateCRCRun(i, r); r--;) { + this.outputStream.writeByte(i), this.nextoutput++; + }a != n && (c = 0); + }return this.writeCount = u, this.blockCRC.getCRC() !== this.targetBlockCRC && h(s.DATA_ERROR, "Bad block CRC (got " + this.blockCRC.getCRC().toString(16) + " expected " + this.targetBlockCRC.toString(16) + ")"), this.nextoutput; + }, l.Err = s, l.decode = function (e, t, r) { + for (var n = f.coerceInputStream(e), i = f.coerceOutputStream(t, t), o = i.stream, a = new l(n, o);;) { + if ("eof" in n && n.eof()) break;if (a._init_block()) a._read_bunzip();else { + var u = a.reader.readBits(32);if (u !== a.streamCRC && h(s.DATA_ERROR, "Bad stream CRC (got " + a.streamCRC.toString(16) + " expected " + u.toString(16) + ")"), !(r && "eof" in n) || n.eof()) break;a._start_bunzip(n, o); + } + }return i.retval; + }, l.decodeBlock = function (e, t, r) { + var i = f.coerceInputStream(e), + o = f.coerceOutputStream(r, r), + a = o.stream, + u = new l(i, a);return u.reader.seekBit(t), u._get_next_block() && (u.blockCRC = new n(), u.writeCopies = 0, u._read_bunzip()), o.retval; + }, l.table = function (e, t, r) { + var n = new o();n.delegate = f.coerceInputStream(e), n.pos = 0, n.readByte = function () { + return this.pos++, this.delegate.readByte(); + }, n.tell = function () { + return this.pos; + }, n.delegate.eof && (n.eof = n.delegate.eof.bind(n.delegate));var i = new o();i.pos = 0, i.writeByte = function () { + this.pos++; + };for (var a = new l(n, i), u = a.dbufSize;;) { + if ("eof" in n && n.eof()) break;var s = a.reader.tellBit();if (a._init_block()) { + var c = i.pos;a._read_bunzip(), t(s, i.pos - c); + } else { + a.reader.readBits(32);if (!(r && "eof" in n) || n.eof()) break;a._start_bunzip(n, i), console.assert(a.dbufSize === u, "shouldn't change block size within multistream file"); + } + } + };var d = function d(e, t) { + var r, + n = [];for (r = 0; r < t; r++) { + n[r] = e[r] << 9 | r; + }n.sort(function (e, t) { + return e - t; + });var o = n.map(function (e) { + return e >>> 9; + });for (i.allocateHuffmanCodeLengths(o, 20), this.codeLengths = f.makeU8Buffer(t), r = 0; r < t; r++) { + var a = 511 & n[r];this.codeLengths[a] = o[r]; + } + };d.prototype.computeCanonical = function () { + var e, + t = this.codeLengths.length, + r = [];for (e = 0; e < t; e++) { + r[e] = this.codeLengths[e] << 9 | e; + }r.sort(function (e, t) { + return e - t; + }), this.code = f.makeU32Buffer(t);var n = 0, + i = 0;for (e = 0; e < t; e++) { + var o = r[e] >>> 9, + a = 511 & r[e];console.assert(i <= o), n <<= o - i, this.code[a] = n++, i = o; + } + }, d.prototype.cost = function (e, t, r) { + var n, + i = 0;for (n = 0; n < r; n++) { + i += this.codeLengths[e[t + n]]; + }return i; + }, d.prototype.emit = function (e) { + var t, + r = this.codeLengths[0];for (e.writeBits(5, r), t = 0; t < this.codeLengths.length; t++) { + var n, + i, + o = this.codeLengths[t];for (console.assert(o > 0 && o <= 20), r < o ? (n = 2, i = o - r) : (n = 3, i = r - o); i-- > 0;) { + e.writeBits(2, n); + }e.writeBit(0), r = o; + } + }, d.prototype.encode = function (e, t) { + e.writeBits(this.codeLengths[t], this.code[t]); + };var B = function B(e, t, r, n) { + for (var i = 0, o = -1, f = 0; i < r && !(4 === f && (t[i++] = 0, i >= r));) { + var u = e.readByte();if (u === a) break;if (n.updateCRC(u), u !== o) o = u, f = 1;else if (++f > 4) { + if (f < 256) { + t[i - 1]++;continue; + }f = 1; + }t[i++] = u; + }return i; + }, + p = function p(e, t, r) { + var n, i, o;for (n = 0, o = 0; n < r.length; n += 50) { + var f = Math.min(50, r.length - n), + a = 0, + u = t[0].cost(r, n, f);for (i = 1; i < t.length; i++) { + var s = t[i].cost(r, n, f);s < u && (a = i, u = s); + }e[o++] = a; + } + }, + v = function v(e, t, r, n, i) { + for (var o, f, a, u = []; e.length < t;) { + for (p(n, e, r), o = 0; o < e.length; o++) { + u[o] = 0; + }for (o = 0; o < n.length; o++) { + u[n[o]]++; + }var s = u.indexOf(Math.max.apply(Math, u)), + c = [];for (o = 0, f = 0; o < n.length; o++) { + if (n[o] === s) { + var h = 50 * o, + l = Math.min(h + 50, r.length);c.push({ index: o, cost: e[s].cost(r, h, l - h) }); + } + }for (c.sort(function (e, t) { + return e.cost - t.cost; + }), o = c.length >>> 1; o < c.length; o++) { + n[c[o].index] = e.length; + }e.push(null);var B, + v = [];for (o = 0; o < e.length; o++) { + for (B = v[o] = [], f = 0; f < i; f++) { + B[f] = 0; + } + }for (o = 0, f = 0; o < r.length;) { + for (B = v[n[f++]], a = 0; a < 50 && o < r.length; a++) { + B[r[o++]]++; + } + }for (o = 0; o < e.length; o++) { + e[o] = new d(v[o], i); + } + } + }, + m = function m(e, t, n) { + var i, + o, + a, + s, + c = f.makeU8Buffer(t), + h = r.bwtransform2(e, c, t, 256);n.writeBit(0), n.writeBits(24, h);var l = [], + B = [];for (o = 0; o < t; o++) { + i = e[o], l[i] = !0, B[i >>> 4] = !0; + }for (o = 0; o < 16; o++) { + n.writeBit(!!B[o]); + }for (o = 0; o < 16; o++) { + if (B[o]) for (a = 0; a < 16; a++) { + n.writeBit(!!l[o << 4 | a]); + } + }var m = 0;for (o = 0; o < 256; o++) { + l[o] && m++; + }var w = f.makeU16Buffer(t + 1), + E = m + 1, + g = [];for (o = 0; o <= E; o++) { + g[o] = 0; + }var _ = f.makeU8Buffer(m);for (o = 0, a = 0; o < 256; o++) { + l[o] && (_[a++] = o); + }l = null, B = null;var b = 0, + y = 0, + R = function R(e) { + w[b++] = e, g[e]++; + }, + C = function C() { + for (; 0 !== y;) { + 1 & y ? (R(0), y -= 1) : (R(1), y -= 2), y >>>= 1; + } + };for (o = 0; o < c.length; o++) { + for (i = c[o], a = 0; a < m && _[a] !== i; a++) {}console.assert(a !== m), u(_, a), 0 === a ? y++ : (C(), R(a + 1), y = 0); + }C(), R(E), w = w.subarray(0, b);var k, + T = [];for (k = b >= 2400 ? 6 : b >= 1200 ? 5 : b >= 600 ? 4 : b >= 200 ? 3 : 2, T.push(new d(g, E + 1)), o = 0; o <= E; o++) { + g[o] = 1; + }T.push(new d(g, E + 1)), g = null;var O = f.makeU8Buffer(Math.ceil(b / 50));for (v(T, k, w, O, E + 1), p(O, T, w), console.assert(T.length >= 2 && T.length <= 6), n.writeBits(3, T.length), n.writeBits(15, O.length), o = 0; o < T.length; o++) { + _[o] = o; + }for (o = 0; o < O.length; o++) { + var S = O[o];for (a = 0; a < T.length && _[a] !== S; a++) {}for (console.assert(a < T.length), u(_, a); a > 0; a--) { + n.writeBit(1); + }n.writeBit(0); + }for (o = 0; o < T.length; o++) { + T[o].emit(n), T[o].computeCanonical(); + }for (o = 0, s = 0; o < b;) { + var U = T[O[s++]];for (a = 0; a < 50 && o < b; a++) { + U.encode(n, w[o++]); + } + } + }, + w = (0, _create2.default)(null);return w.compressFile = function (e, r, i) { + e = f.coerceInputStream(e);var o = f.coerceOutputStream(r, r);r = new t(o.stream);var a = 9;if ("number" == typeof i && (a = i), a < 1 || a > 9) throw new Error("Invalid block size multiplier");var u = 1e5 * a;u -= 19, r.writeByte("B".charCodeAt(0)), r.writeByte("Z".charCodeAt(0)), r.writeByte("h".charCodeAt(0)), r.writeByte("0".charCodeAt(0) + a);var s, + c = f.makeU8Buffer(u), + h = 0;do { + var l = new n();s = B(e, c, u, l), s > 0 && (h = ((h << 1 | h >>> 31) ^ l.getCRC()) >>> 0, r.writeBits(48, 54156738319193), r.writeBits(32, l.getCRC()), m(c, s, r)); + } while (s === u);return r.writeBits(48, 25779555029136), r.writeBits(32, h), r.flush(), o.retval; + }, w.decompressFile = l.decode, w.decompressBlock = l.decodeBlock, w.table = l.table, w; +}(0, BitStream, BWT, CRC32, HuffmanAllocator, Stream, Util), module.exports = Bzip2; + +}).call(this,_dereq_('_process'),_dereq_("buffer").Buffer) +},{"_process":298,"babel-runtime/core-js/object/create":20,"babel-runtime/core-js/object/freeze":22,"babel-runtime/helpers/typeof":34,"buffer":40}],305:[function(_dereq_,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _enums = _dereq_("../enums"); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + /** @property {Integer} prefer_hash_algorithm Default hash algorithm {@link module:enums.hash} */ + prefer_hash_algorithm: _enums2.default.hash.sha256, + /** @property {Integer} encryption_cipher Default encryption cipher {@link module:enums.symmetric} */ + encryption_cipher: _enums2.default.symmetric.aes256, + /** @property {Integer} compression Default compression algorithm {@link module:enums.compression} */ + compression: _enums2.default.compression.uncompressed, + /** @property {Integer} deflate_level Default zip/zlib compression level, between 1 and 9 */ + deflate_level: 6, + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** + * @property {Boolean} aead_protect + */ + aead_protect: false, + /** Use integrity protection for symmetric encryption + * @property {Boolean} integrity_protect */ + integrity_protect: true, + /** @property {Boolean} ignore_mdc_error Fail on decrypt if message is not integrity protected */ + ignore_mdc_error: false, + /** @property {Boolean} checksum_required Do not throw error when armor is missing a checksum */ + checksum_required: false, + /** @property {Boolean} rsa_blinding */ + rsa_blinding: true, + /** Work-around for rare GPG decryption bug when encrypting with multiple passwords + * Slower and slightly less secure + * @property {Boolean} password_collision_check + */ + password_collision_check: false, + /** @property {Boolean} revocations_expire If true, expired revocation signatures are ignored */ + revocations_expire: false, + + /** @property {Boolean} use_native Use native Node.js crypto/zlib and WebCrypto APIs when available */ + use_native: true, + /** @property {Boolean} Use transferable objects between the Web Worker and main thread */ + zero_copy: false, + /** @property {Boolean} debug If enabled, debug messages will be printed */ + debug: false, + /** @property {Boolean} tolerant Ignore unsupported/unrecognizable packets instead of throwing an error */ + tolerant: true, + + /** @property {Boolean} show_version Whether to include {@link module:config/config.versionstring} in armored messages */ + show_version: true, + /** @property {Boolean} show_comment Whether to include {@link module:config/config.commentstring} in armored messages */ + show_comment: true, + /** @property {String} versionstring A version string to be included in armored messages */ + versionstring: "OpenPGP.js v3.0.0", + /** @property {String} commentstring A comment string to be included in armored messages */ + commentstring: "https://openpgpjs.org", + + /** @property {String} keyserver */ + keyserver: "https://keyserver.ubuntu.com", + /** @property {String} node_store */ + node_store: "./openpgp.store" +}; // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -5155,59 +27662,12 @@ h+4&&(this.a=new Uint8Array(g.length+4),this.a.set(g),g=this.a),g=g.subarray(0,h // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * This object contains configuration values. + * This object contains global configuration values. * @requires enums - * @property {Integer} prefer_hash_algorithm - * @property {Integer} encryption_cipher - * @property {Integer} compression - * @property {Boolean} show_version - * @property {Boolean} show_comment - * @property {Boolean} integrity_protect - * @property {String} keyserver - * @property {Boolean} debug If enabled, debug messages will be printed * @module config/config */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = { - prefer_hash_algorithm: _enums2.default.hash.sha256, - encryption_cipher: _enums2.default.symmetric.aes256, - compression: _enums2.default.compression.zip, - aead_protect: false, // use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption - integrity_protect: true, // use integrity protection for symmetric encryption - ignore_mdc_error: false, // fail on decrypt if message is not integrity protected - checksum_required: false, // do not throw error when armor is missing a checksum - verify_expired_keys: true, // allow signature verification with expired keys - rsa_blinding: true, - use_native: true, // use native node.js crypto and Web Crypto apis (if available) - zero_copy: false, // use transferable objects between the Web Worker and main thread - debug: false, - tolerant: true, // ignore unsupported/unrecognizable packets instead of throwing an error - show_version: true, - show_comment: true, - versionstring: "OpenPGP.js v2.6.2", - commentstring: "https://openpgpjs.org", - keyserver: "https://keyserver.ubuntu.com", - node_store: './openpgp.store' -}; - -},{"../enums.js":35}],10:[function(_dereq_,module,exports){ -/** - * @see module:config/config - * @module config - */ - +},{"../enums":337}],306:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -5225,31 +27685,156 @@ Object.defineProperty(exports, 'default', { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -},{"./config.js":9}],11:[function(_dereq_,module,exports){ -// Modified by ProtonTech AG +},{"./config.js":305}],307:[function(_dereq_,module,exports){ +'use strict'; -// Modified by Recurity Labs GmbH +Object.defineProperty(exports, "__esModule", { + value: true +}); -// modified version of https://www.hanewin.net/encrypt/PGdecode.js: +var _cipher = _dereq_('./cipher'); -/* OpenPGP encryption using RSA/AES - * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de - * version 2.0, check www.haneWIN.de for the latest version +var _cipher2 = _interopRequireDefault(_cipher); - * This software is provided as-is, without express or implied warranty. - * Permission to use, copy, modify, distribute or sell this software, with or - * without fee, for any purpose and by any individual or organization, is hereby - * granted, provided that the above copyright notice and this paragraph appear - * in all copies. Distribution as a part of an application or binary must - * include the above copyright notice in the documentation and/or other - * materials provided with the application or distribution. - */ +var _util = _dereq_('../util'); -/** - * @requires crypto/cipher - * @module crypto/cfb - */ +var _util2 = _interopRequireDefault(_util); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +// Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions + +function wrap(key, data) { + var aes = new _cipher2.default["aes" + key.length * 8](key); + var IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); + var P = unpack(data); + var A = IV; + var R = P; + var n = P.length / 2; + var t = new Uint32Array([0, 0]); + var B = new Uint32Array(4); + for (var j = 0; j <= 5; ++j) { + for (var i = 0; i < n; ++i) { + t[1] = n * j + (1 + i); + // B = A + B[0] = A[0]; + B[1] = A[1]; + // B = A || R[i] + B[2] = R[2 * i]; + B[3] = R[2 * i + 1]; + // B = AES(K, B) + B = unpack(aes.encrypt(pack(B))); + // A = MSB(64, B) ^ t + A = B.subarray(0, 2); + A[0] ^= t[0]; + A[1] ^= t[1]; + // R[i] = LSB(64, B) + R[2 * i] = B[2]; + R[2 * i + 1] = B[3]; + } + } + return pack(A, R); +} + +function unwrap(key, data) { + var aes = new _cipher2.default["aes" + key.length * 8](key); + var IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]); + var C = unpack(data); + var A = C.subarray(0, 2); + var R = C.subarray(2); + var n = C.length / 2 - 1; + var t = new Uint32Array([0, 0]); + var B = new Uint32Array(4); + for (var j = 5; j >= 0; --j) { + for (var i = n - 1; i >= 0; --i) { + t[1] = n * j + (i + 1); + // B = A ^ t + B[0] = A[0] ^ t[0]; + B[1] = A[1] ^ t[1]; + // B = (A ^ t) || R[i] + B[2] = R[2 * i]; + B[3] = R[2 * i + 1]; + // B = AES-1(B) + B = unpack(aes.decrypt(pack(B))); + // A = MSB(64, B) + A = B.subarray(0, 2); + // R[i] = LSB(64, B) + R[2 * i] = B[2]; + R[2 * i + 1] = B[3]; + } + } + if (A[0] === IV[0] && A[1] === IV[1]) { + return pack(R); + } + throw new Error("Key Data Integrity failed"); +} + +function createArrayBuffer(data) { + if (_util2.default.isString(data)) { + var length = data.length; + + var buffer = new ArrayBuffer(length); + var view = new Uint8Array(buffer); + for (var j = 0; j < length; ++j) { + view[j] = data.charCodeAt(j); + } + return buffer; + } + return new Uint8Array(data).buffer; +} + +function unpack(data) { + var length = data.length; + + var buffer = createArrayBuffer(data); + var view = new DataView(buffer); + var arr = new Uint32Array(length / 4); + for (var i = 0; i < length / 4; ++i) { + arr[i] = view.getUint32(4 * i); + } + return arr; +} + +function pack() { + var length = 0; + for (var k = 0; k < arguments.length; ++k) { + length += 4 * arguments[k].length; + } + var buffer = new ArrayBuffer(length); + var view = new DataView(buffer); + var offset = 0; + for (var i = 0; i < arguments.length; ++i) { + for (var j = 0; j < arguments[i].length; ++j) { + view.setUint32(offset + 4 * j, arguments[i][j]); + } + offset += 4 * arguments[i].length; + } + return new Uint8Array(buffer); +} + +exports.default = { + wrap: wrap, + unwrap: unwrap +}; + +},{"../util":376,"./cipher":313}],308:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -5278,7 +27863,7 @@ exports.default = { * IV should be used or not. The encrypteddatapacket uses the * "old" style with a resync. Encryption within an * encryptedintegrityprotecteddata packet is not resyncing the IV. - * @return {Uint8Array} encrypted data + * @returns {Uint8Array} encrypted data */ encrypt: function encrypt(prefixrandom, cipherfn, plaintext, key, resync) { cipherfn = new _cipher2.default[cipherfn](key); @@ -5294,7 +27879,9 @@ exports.default = { prefixrandom = new_prefix; var ciphertext = new Uint8Array(plaintext.length + 2 + block_size * 2); - var i, n, begin; + var i = void 0; + var n = void 0; + var begin = void 0; var offset = resync ? 0 : 2; // 1. The feedback register (FR) is set to the IV, which is all zeros. @@ -5369,7 +27956,7 @@ exports.default = { * @param {Uint8Array} key Uint8Array representation of key to be used to check the mdc * This will be passed to the cipherfn * @param {Uint8Array} ciphertext The encrypted data - * @return {Uint8Array} plaintext Data of D(ciphertext) with blocksize length +2 + * @returns {Uint8Array} plaintext Data of D(ciphertext) with blocksize length +2 */ mdc: function mdc(cipherfn, key, ciphertext) { cipherfn = new _cipher2.default[cipherfn](key); @@ -5377,7 +27964,7 @@ exports.default = { var iblock = new Uint8Array(block_size); var ablock = new Uint8Array(block_size); - var i; + var i = void 0; // initialisation vector for (i = 0; i < block_size; i++) { @@ -5410,7 +27997,7 @@ exports.default = { * IV should be used or not. The encrypteddatapacket uses the * "old" style with a resync. Decryption within an * encryptedintegrityprotecteddata packet is not resyncing the IV. - * @return {Uint8Array} the plaintext data + * @returns {Uint8Array} the plaintext data */ decrypt: function decrypt(cipherfn, key, ciphertext, resync) { @@ -5420,7 +28007,9 @@ exports.default = { var iblock = new Uint8Array(block_size); var ablock = new Uint8Array(block_size); - var i, j, n; + var i = void 0; + var j = void 0; + var n = void 0; var text = new Uint8Array(ciphertext.length - block_size); // initialisation vector @@ -5494,8 +28083,8 @@ exports.default = { var blockc = new Uint8Array(block_size); var pos = 0; var cyphertext = new Uint8Array(plaintext.length); - var i, - j = 0; + var i = void 0; + var j = 0; if (iv === null) { for (i = 0; i < block_size; i++) { @@ -5522,12 +28111,12 @@ exports.default = { cipherfn = new _cipher2.default[cipherfn](key); var block_size = cipherfn.blockSize; - var blockp; + var blockp = void 0; var pos = 0; var plaintext = new Uint8Array(ciphertext.length); var offset = 0; - var i, - j = 0; + var i = void 0; + var j = 0; if (iv === null) { blockp = new Uint8Array(block_size); @@ -5548,12 +28137,15 @@ exports.default = { return plaintext; } -}; +}; // Modified by ProtonTech AG -},{"./cipher":16}],12:[function(_dereq_,module,exports){ -/* Rijndael (AES) Encryption - * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de - * version 1.1, check www.haneWIN.de for the latest version +// Modified by Recurity Labs GmbH + +// modified version of https://www.hanewin.net/encrypt/PGdecode.js: + +/* OpenPGP encryption using RSA/AES + * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de + * version 2.0, check www.haneWIN.de for the latest version * This software is provided as-is, without express or implied warranty. * Permission to use, copy, modify, distribute or sell this software, with or @@ -5565,213 +28157,38 @@ exports.default = { */ /** - * @module crypto/cipher/aes + * @requires crypto/cipher + * @module crypto/cfb */ +},{"./cipher":313}],309:[function(_dereq_,module,exports){ 'use strict'; -// The round constants used in subkey expansion - Object.defineProperty(exports, "__esModule", { value: true }); -var Rcon = new Uint8Array([0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]); -// Precomputed lookup table for the SBox -var S = new Uint8Array([99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]); +var _from = _dereq_('babel-runtime/core-js/array/from'); -var T1 = new Uint32Array([0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c]); +var _from2 = _interopRequireDefault(_from); -var T2 = new Uint32Array([0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a]); +var _exports = _dereq_('asmcrypto.js/src/aes/ecb/exports'); -var T3 = new Uint32Array([0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16]); - -var T4 = new Uint32Array([0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616]); - -function B0(x) { - return x & 255; -} - -function B1(x) { - return x >> 8 & 255; -} - -function B2(x) { - return x >> 16 & 255; -} - -function B3(x) { - return x >> 24 & 255; -} - -function F1(x0, x1, x2, x3) { - return B1(T1[x0 & 255]) | B1(T1[x1 >> 8 & 255]) << 8 | B1(T1[x2 >> 16 & 255]) << 16 | B1(T1[x3 >>> 24]) << 24; -} - -function packBytes(octets) { - var i, j; - var len = octets.length; - var b = new Array(len / 4); - - if (!octets || len % 4) { - return; - } - - for (i = 0, j = 0; j < len; j += 4) { - b[i++] = octets[j] | octets[j + 1] << 8 | octets[j + 2] << 16 | octets[j + 3] << 24; - } - - return b; -} - -function unpackBytes(packed) { - var j; - var i = 0, - l = packed.length; - var r = new Array(l * 4); - - for (j = 0; j < l; j++) { - r[i++] = B0(packed[j]); - r[i++] = B1(packed[j]); - r[i++] = B2(packed[j]); - r[i++] = B3(packed[j]); - } - return r; -} - -// ------------------------------------------------ - -var maxkc = 8; -var maxrk = 14; - -function keyExpansion(key) { - var kc, i, j, r, t; - var rounds; - var keySched = new Array(maxrk + 1); - var keylen = key.length; - var k = new Array(maxkc); - var tk = new Array(maxkc); - var rconpointer = 0; - - if (keylen === 16) { - rounds = 10; - kc = 4; - } else if (keylen === 24) { - rounds = 12; - kc = 6; - } else if (keylen === 32) { - rounds = 14; - kc = 8; - } else { - throw new Error('Invalid key-length for AES key:' + keylen); - } - - for (i = 0; i < maxrk + 1; i++) { - keySched[i] = new Uint32Array(4); - } - - for (i = 0, j = 0; j < keylen; j++, i += 4) { - k[j] = key[i] | key[i + 1] << 8 | key[i + 2] << 16 | key[i + 3] << 24; - } - - for (j = kc - 1; j >= 0; j--) { - tk[j] = k[j]; - } - - r = 0; - t = 0; - for (j = 0; j < kc && r < rounds + 1;) { - for (; j < kc && t < 4; j++, t++) { - keySched[r][t] = tk[j]; - } - if (t === 4) { - r++; - t = 0; - } - } - - while (r < rounds + 1) { - var temp = tk[kc - 1]; - - tk[0] ^= S[B1(temp)] | S[B2(temp)] << 8 | S[B3(temp)] << 16 | S[B0(temp)] << 24; - tk[0] ^= Rcon[rconpointer++]; - - if (kc !== 8) { - for (j = 1; j < kc; j++) { - tk[j] ^= tk[j - 1]; - } - } else { - for (j = 1; j < kc / 2; j++) { - tk[j] ^= tk[j - 1]; - } - - temp = tk[kc / 2 - 1]; - tk[kc / 2] ^= S[B0(temp)] | S[B1(temp)] << 8 | S[B2(temp)] << 16 | S[B3(temp)] << 24; - - for (j = kc / 2 + 1; j < kc; j++) { - tk[j] ^= tk[j - 1]; - } - } - - for (j = 0; j < kc && r < rounds + 1;) { - for (; j < kc && t < 4; j++, t++) { - keySched[r][t] = tk[j]; - } - if (t === 4) { - r++; - t = 0; - } - } - } - - return { - rounds: rounds, - rk: keySched - }; -} - -function AESencrypt(block, ctx, t) { - var r, rounds, b; - - b = packBytes(block); - rounds = ctx.rounds; - - for (r = 0; r < rounds - 1; r++) { - t[0] = b[0] ^ ctx.rk[r][0]; - t[1] = b[1] ^ ctx.rk[r][1]; - t[2] = b[2] ^ ctx.rk[r][2]; - t[3] = b[3] ^ ctx.rk[r][3]; - - b[0] = T1[t[0] & 255] ^ T2[t[1] >> 8 & 255] ^ T3[t[2] >> 16 & 255] ^ T4[t[3] >>> 24]; - b[1] = T1[t[1] & 255] ^ T2[t[2] >> 8 & 255] ^ T3[t[3] >> 16 & 255] ^ T4[t[0] >>> 24]; - b[2] = T1[t[2] & 255] ^ T2[t[3] >> 8 & 255] ^ T3[t[0] >> 16 & 255] ^ T4[t[1] >>> 24]; - b[3] = T1[t[3] & 255] ^ T2[t[0] >> 8 & 255] ^ T3[t[1] >> 16 & 255] ^ T4[t[2] >>> 24]; - } - - // last round is special - r = rounds - 1; - - t[0] = b[0] ^ ctx.rk[r][0]; - t[1] = b[1] ^ ctx.rk[r][1]; - t[2] = b[2] ^ ctx.rk[r][2]; - t[3] = b[3] ^ ctx.rk[r][3]; - - b[0] = F1(t[0], t[1], t[2], t[3]) ^ ctx.rk[rounds][0]; - b[1] = F1(t[1], t[2], t[3], t[0]) ^ ctx.rk[rounds][1]; - b[2] = F1(t[2], t[3], t[0], t[1]) ^ ctx.rk[rounds][2]; - b[3] = F1(t[3], t[0], t[1], t[2]) ^ ctx.rk[rounds][3]; - - return unpackBytes(b); -} - -function makeClass(length) { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// TODO use webCrypto or nodeCrypto when possible. +function aes(length) { var c = function c(key) { - this.key = keyExpansion(key); - this._temp = new Uint32Array(this.blockSize / 4); + this.key = Uint8Array.from(key); this.encrypt = function (block) { - return AESencrypt(block, this.key, this._temp); + block = Uint8Array.from(block); + return (0, _from2.default)(_exports.AES_ECB.encrypt(block, this.key, false)); + }; + + this.decrypt = function (block) { + block = Uint8Array.from(block); + return (0, _from2.default)(_exports.AES_ECB.decrypt(block, this.key, false)); }; }; @@ -5779,15 +28196,19 @@ function makeClass(length) { c.keySize = c.prototype.keySize = length / 8; return c; -} +} /** + * @requires asmcrypto.js + * @module crypto/cipher/aes + */ -exports.default = { - 128: makeClass(128), - 192: makeClass(192), - 256: makeClass(256) -}; +exports.default = aes; -},{}],13:[function(_dereq_,module,exports){ +},{"asmcrypto.js/src/aes/ecb/exports":6,"babel-runtime/core-js/array/from":16}],310:[function(_dereq_,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); /* Modified by Recurity Labs GmbH * * Originally written by nklein software (nklein.com) @@ -5797,8 +28218,6 @@ exports.default = { * @module crypto/cipher/blowfish */ -'use strict'; - /* * Javascript implementation based on Bruce Schneier's reference implementation. * @@ -5806,11 +28225,6 @@ exports.default = { * The constructor doesn't do much of anything. It's just here * so we can start defining properties and methods and such. */ - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = BF; function Blowfish() {} /* @@ -5853,23 +28267,19 @@ Blowfish.prototype._clean = function (xx) { //* This is the mixing function that uses the sboxes //* Blowfish.prototype._F = function (xx) { - var aa; - var bb; - var cc; - var dd; - var yy; + var yy = void 0; - dd = xx & 0x00FF; + var dd = xx & 0x00FF; xx >>>= 8; - cc = xx & 0x00FF; + var cc = xx & 0x00FF; xx >>>= 8; - bb = xx & 0x00FF; + var bb = xx & 0x00FF; xx >>>= 8; - aa = xx & 0x00FF; + var aa = xx & 0x00FF; yy = this.sboxes[0][aa] + this.sboxes[1][bb]; - yy = yy ^ this.sboxes[2][cc]; - yy = yy + this.sboxes[3][dd]; + yy ^= this.sboxes[2][cc]; + yy += this.sboxes[3][dd]; return yy; }; @@ -5882,10 +28292,10 @@ Blowfish.prototype._encrypt_block = function (vals) { var dataL = vals[0]; var dataR = vals[1]; - var ii; + var ii = void 0; for (ii = 0; ii < this.NN; ++ii) { - dataL = dataL ^ this.parray[ii]; + dataL ^= this.parray[ii]; dataR = this._F(dataL) ^ dataR; var tmp = dataL; @@ -5893,8 +28303,8 @@ Blowfish.prototype._encrypt_block = function (vals) { dataR = tmp; } - dataL = dataL ^ this.parray[this.NN + 0]; - dataR = dataR ^ this.parray[this.NN + 1]; + dataL ^= this.parray[this.NN + 0]; + dataR ^= this.parray[this.NN + 1]; vals[0] = this._clean(dataR); vals[1] = this._clean(dataL); @@ -5910,7 +28320,7 @@ Blowfish.prototype._encrypt_block = function (vals) { //* the F() method to deconstruct the vector. //* Blowfish.prototype.encrypt_block = function (vector) { - var ii; + var ii = void 0; var vals = [0, 0]; var off = this.BLOCKSIZE / 2; for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) { @@ -5939,10 +28349,10 @@ Blowfish.prototype._decrypt_block = function (vals) { var dataL = vals[0]; var dataR = vals[1]; - var ii; + var ii = void 0; for (ii = this.NN + 1; ii > 1; --ii) { - dataL = dataL ^ this.parray[ii]; + dataL ^= this.parray[ii]; dataR = this._F(dataL) ^ dataR; var tmp = dataL; @@ -5950,8 +28360,8 @@ Blowfish.prototype._decrypt_block = function (vals) { dataR = tmp; } - dataL = dataL ^ this.parray[1]; - dataR = dataR ^ this.parray[0]; + dataL ^= this.parray[1]; + dataR ^= this.parray[0]; vals[0] = this._clean(dataR); vals[1] = this._clean(dataL); @@ -5962,14 +28372,13 @@ Blowfish.prototype._decrypt_block = function (vals) { //* sboxes and parray for this encryption. //* Blowfish.prototype.init = function (key) { - var ii; + var ii = void 0; var jj = 0; this.parray = []; for (ii = 0; ii < this.NN + 2; ++ii) { var data = 0x00000000; - var kk; - for (kk = 0; kk < 4; ++kk) { + for (var kk = 0; kk < 4; ++kk) { data = data << 8 | key[jj] & 0x00FF; if (++jj >= key.length) { jj = 0; @@ -6013,10 +28422,18 @@ function BF(key) { return this.bf.encrypt_block(block); }; } + BF.keySize = BF.prototype.keySize = 16; BF.blockSize = BF.prototype.blockSize = 16; -},{}],14:[function(_dereq_,module,exports){ +exports.default = BF; + +},{}],311:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -6035,12 +28452,6 @@ BF.blockSize = BF.prototype.blockSize = 16; /** @module crypto/cipher/cast5 */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = Cast5; function OpenpgpSymencCast5() { this.BlockSize = 8; this.KeySize = 16; @@ -6076,7 +28487,7 @@ function OpenpgpSymencCast5() { for (var i = 0; i < src.length; i += 8) { var l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3]; var r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7]; - var t; + var t = void 0; t = r; r = l ^ f1(r, this.masking[0], this.rotate[0]); @@ -6149,7 +28560,7 @@ function OpenpgpSymencCast5() { for (var i = 0; i < src.length; i += 8) { var l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3]; var r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7]; - var t; + var t = void 0; t = r; r = l ^ f1(r, this.masking[15], this.rotate[15]); @@ -6272,16 +28683,16 @@ function OpenpgpSymencCast5() { var t = new Array(8); var k = new Array(32); - var i, j; + var j = void 0; - for (i = 0; i < 4; i++) { + for (var i = 0; i < 4; i++) { j = i * 4; t[i] = inn[j] << 24 | inn[j + 1] << 16 | inn[j + 2] << 8 | inn[j + 3]; } var x = [6, 7, 4, 5]; var ki = 0; - var w; + var w = void 0; for (var half = 0; half < 2; half++) { for (var round = 0; round < 4; round++) { @@ -6311,9 +28722,9 @@ function OpenpgpSymencCast5() { } } - for (i = 0; i < 16; i++) { - this.masking[i] = k[i]; - this.rotate[i] = k[16 + i] & 0x1f; + for (var _i = 0; _i < 16; _i++) { + this.masking[_i] = k[_i]; + this.rotate[_i] = k[16 + _i] & 0x1f; } }; @@ -6367,7 +28778,14 @@ function Cast5(key) { Cast5.blockSize = Cast5.prototype.blockSize = 8; Cast5.keySize = Cast5.prototype.keySize = 16; -},{}],15:[function(_dereq_,module,exports){ +exports.default = Cast5; + +},{}],312:[function(_dereq_,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); //Paul Tero, July 2001 //http://www.tero.co.uk/des/ // @@ -6395,11 +28813,6 @@ Cast5.keySize = Cast5.prototype.keySize = 16; * @module crypto/cipher/des */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); function des(keys, message, encrypt, mode, iv, padding) { //declaring this locally speeds things up a bit var spfunction1 = new Array(0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004); @@ -6412,17 +28825,21 @@ function des(keys, message, encrypt, mode, iv, padding) { var spfunction8 = new Array(0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000); //create the 16 or 48 subkeys we will need - var m = 0, - i, - j, - temp, - right1, - right2, - left, - right, - looping; - var cbcleft, cbcleft2, cbcright, cbcright2; - var endloop, loopinc; + var m = 0; + var i = void 0; + var j = void 0; + var temp = void 0; + var right1 = void 0; + var right2 = void 0; + var left = void 0; + var right = void 0; + var looping = void 0; + var cbcleft = void 0; + var cbcleft2 = void 0; + var cbcright = void 0; + var cbcright2 = void 0; + var endloop = void 0; + var loopinc = void 0; var len = message.length; //set up the loops for single and triple des @@ -6587,11 +29004,11 @@ function des_createKeys(key) { //now define the left shifts which need to be done var shifts = new Array(0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0); //other variables - var lefttemp, - righttemp, - m = 0, - n = 0, - temp; + var lefttemp = void 0; + var righttemp = void 0; + var m = 0; + var n = 0; + var temp = void 0; for (var j = 0; j < iterations; j++) { //either 1 or 3 iterations @@ -6658,7 +29075,7 @@ function des_createKeys(key) { function des_addPadding(message, padding) { var padLength = 8 - message.length % 8; - var pad; + var pad = void 0; if (padding === 2 && padLength < 8) { //pad the message with spaces pad = " ".charCodeAt(0); @@ -6687,7 +29104,7 @@ function des_addPadding(message, padding) { function des_removePadding(message, padding) { var padLength = null; - var pad; + var pad = void 0; if (padding === 2) { // space padded pad = " ".charCodeAt(0); @@ -6714,7 +29131,7 @@ function des_removePadding(message, padding) { // added by Recurity Labs -function Des(key) { +function TripleDES(key) { this.key = []; for (var i = 0; i < 3; i++) { @@ -6726,13 +29143,12 @@ function Des(key) { }; } -Des.keySize = Des.prototype.keySize = 24; -Des.blockSize = Des.prototype.blockSize = 8; +TripleDES.keySize = TripleDES.prototype.keySize = 24; +TripleDES.blockSize = TripleDES.prototype.blockSize = 8; -// This is "original" DES - Des is actually Triple DES. -// This is only exported so we can unit test. +// This is "original" DES -function OriginalDes(key) { +function DES(key) { this.key = key; this.encrypt = function (block, padding) { @@ -6746,29 +29162,16 @@ function OriginalDes(key) { }; } -exports.default = { - /** @static */ - des: Des, - /** @static */ - originalDes: OriginalDes -}; - -},{}],16:[function(_dereq_,module,exports){ -/** - * @requires crypto/cipher/aes - * @requires crypto/cipher/blowfish - * @requires crypto/cipher/cast5 - * @requires crypto/cipher/twofish - * @module crypto/cipher - */ +exports.default = { DES: DES, TripleDES: TripleDES }; +},{}],313:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -var _aes = _dereq_('./aes.js'); +var _aes = _dereq_('./aes'); var _aes2 = _interopRequireDefault(_aes); @@ -6776,15 +29179,15 @@ var _des = _dereq_('./des.js'); var _des2 = _interopRequireDefault(_des); -var _cast = _dereq_('./cast5.js'); +var _cast = _dereq_('./cast5'); var _cast2 = _interopRequireDefault(_cast); -var _twofish = _dereq_('./twofish.js'); +var _twofish = _dereq_('./twofish'); var _twofish2 = _interopRequireDefault(_twofish); -var _blowfish = _dereq_('./blowfish.js'); +var _blowfish = _dereq_('./blowfish'); var _blowfish2 = _interopRequireDefault(_blowfish); @@ -6792,13 +29195,13 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de exports.default = { /** @see module:crypto/cipher/aes */ - aes128: _aes2.default[128], - aes192: _aes2.default[192], - aes256: _aes2.default[256], - /** @see module:crypto/cipher/des.originalDes */ - des: _des2.default.originalDes, - /** @see module:crypto/cipher/des.des */ - tripledes: _des2.default.des, + aes128: (0, _aes2.default)(128), + aes192: (0, _aes2.default)(192), + aes256: (0, _aes2.default)(256), + /** @see module:crypto/cipher/des~DES */ + des: _des2.default.DES, + /** @see module:crypto/cipher/des~TripleDES */ + tripledes: _des2.default.TripleDES, /** @see module:crypto/cipher/cast5 */ cast5: _cast2.default, /** @see module:crypto/cipher/twofish */ @@ -6809,15 +29212,22 @@ exports.default = { idea: function idea() { throw new Error('IDEA symmetric-key algorithm not implemented'); } -}; +}; /** + * @fileoverview Symmetric cryptography functions + * @requires crypto/cipher/aes + * @requires crypto/cipher/des + * @requires crypto/cipher/cast5 + * @requires crypto/cipher/twofish + * @requires crypto/cipher/blowfish + * @module crypto/cipher + */ -},{"./aes.js":12,"./blowfish.js":13,"./cast5.js":14,"./des.js":15,"./twofish.js":17}],17:[function(_dereq_,module,exports){ +},{"./aes":309,"./blowfish":310,"./cast5":311,"./des.js":312,"./twofish":314}],314:[function(_dereq_,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = TF; /* Modified by Recurity Labs GmbH * * Cipher.js @@ -6842,6 +29252,8 @@ exports.default = TF; * @module crypto/cipher/twofish */ +/* eslint-disable no-mixed-operators */ + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Math //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -6885,17 +29297,19 @@ function createTwofish() { function tfsInit(key) { keyBytes = key; - var i, - a, - b, - c, - d, - meKey = [], - moKey = [], - inKey = []; - var kLen; + var i = void 0; + var a = void 0; + var b = void 0; + var c = void 0; + var d = void 0; + var meKey = []; + var moKey = []; + var inKey = []; + var kLen = void 0; var sKey = []; - var f01, f5b, fef; + var f01 = void 0; + var f5b = void 0; + var fef = void 0; var q0 = [[8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]]; var q1 = [[14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]]; @@ -6915,7 +29329,9 @@ function createTwofish() { } function mdsRem(p, q) { - var i, t, u; + var i = void 0; + var t = void 0; + var u = void 0; for (i = 0; i < 8; i++) { t = q >>> 24; q = q << 8 & MAXINT | p >>> 24; @@ -6935,19 +29351,18 @@ function createTwofish() { } function qp(n, x) { - var a, b, c, d; - a = x >> 4; - b = x & 15; - c = q0[n][a ^ b]; - d = q1[n][ror4[b] ^ ashx[a]]; + var a = x >> 4; + var b = x & 15; + var c = q0[n][a ^ b]; + var d = q1[n][ror4[b] ^ ashx[a]]; return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d]; } function hFun(x, key) { - var a = getB(x, 0), - b = getB(x, 1), - c = getB(x, 2), - d = getB(x, 3); + var a = getB(x, 0); + var b = getB(x, 1); + var c = getB(x, 2); + var d = getB(x, 3); switch (kLen) { case 4: a = q[1][a] ^ getB(key[3], 0); @@ -7137,8 +29552,69 @@ function toArray(typedArray) { TF.keySize = TF.prototype.keySize = 32; TF.blockSize = TF.prototype.blockSize = 16; -},{}],18:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +exports.default = TF; + +},{}],315:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _public_key = _dereq_('./public_key'); + +var _public_key2 = _interopRequireDefault(_public_key); + +var _cipher = _dereq_('./cipher'); + +var _cipher2 = _interopRequireDefault(_cipher); + +var _random = _dereq_('./random'); + +var _random2 = _interopRequireDefault(_random); + +var _ecdh_symkey = _dereq_('../type/ecdh_symkey'); + +var _ecdh_symkey2 = _interopRequireDefault(_ecdh_symkey); + +var _kdf_params = _dereq_('../type/kdf_params'); + +var _kdf_params2 = _interopRequireDefault(_kdf_params); + +var _mpi = _dereq_('../type/mpi'); + +var _mpi2 = _interopRequireDefault(_mpi); + +var _oid = _dereq_('../type/oid'); + +var _oid2 = _interopRequireDefault(_oid); + +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function constructParams(types, data) { + return types.map(function (type, i) { + if (data && data[i]) { + return new type(data[i]); + } + return new type(); + }); +} // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -7158,220 +29634,347 @@ TF.blockSize = TF.prototype.blockSize = 16; // The GPG4Browsers crypto interface /** - * @requires crypto/cipher * @requires crypto/public_key + * @requires crypto/cipher * @requires crypto/random + * @requires type/ecdh_symkey + * @requires type/kdf_params * @requires type/mpi + * @requires type/oid + * @requires enums + * @requires util * @module crypto/crypto */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _random = _dereq_('./random.js'); - -var _random2 = _interopRequireDefault(_random); - -var _cipher = _dereq_('./cipher'); - -var _cipher2 = _interopRequireDefault(_cipher); - -var _public_key = _dereq_('./public_key'); - -var _public_key2 = _interopRequireDefault(_public_key); - -var _mpi = _dereq_('../type/mpi.js'); - -var _mpi2 = _interopRequireDefault(_mpi); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - exports.default = { /** - * Encrypts data using the specified public key multiprecision integers - * and the specified algorithm. - * @param {module:enums.publicKey} algo Algorithm to be used (See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}) - * @param {Array} publicMPIs Algorithm dependent multiprecision integers - * @param {module:type/mpi} data Data to be encrypted as MPI - * @return {Array} if RSA an module:type/mpi; - * if elgamal encryption an array of two module:type/mpi is returned; otherwise null + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} algo Public key algorithm + * @param {Array} pub_params Algorithm-specific public key parameters + * @param {module:type/mpi} data Data to be encrypted as MPI + * @param {String} fingerprint Recipient fingerprint + * @returns {Array} encrypted session key parameters + * @async */ - publicKeyEncrypt: function publicKeyEncrypt(algo, publicMPIs, data) { - var result = function () { - var m; - switch (algo) { - case 'rsa_encrypt': - case 'rsa_encrypt_sign': - var rsa = new _public_key2.default.rsa(); - var n = publicMPIs[0].toBigInteger(); - var e = publicMPIs[1].toBigInteger(); - m = data.toBigInteger(); - return [rsa.encrypt(m, e, n)]; + publicKeyEncrypt: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(algo, pub_params, data, fingerprint) { + var types; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + types = this.getEncSessionKeyParamTypes(algo); + return _context2.abrupt('return', (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() { + var m, n, e, res, _m, p, g, y, _res, oid, Q, kdf_params, _res2; - case 'elgamal': - var elgamal = new _public_key2.default.elgamal(); - var p = publicMPIs[0].toBigInteger(); - var g = publicMPIs[1].toBigInteger(); - var y = publicMPIs[2].toBigInteger(); - m = data.toBigInteger(); - return elgamal.encrypt(m, g, p, y); + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = algo; + _context.next = _context.t0 === _enums2.default.publicKey.rsa_encrypt ? 3 : _context.t0 === _enums2.default.publicKey.rsa_encrypt_sign ? 3 : _context.t0 === _enums2.default.publicKey.elgamal ? 10 : _context.t0 === _enums2.default.publicKey.ecdh ? 18 : 25; + break; - default: - return []; - } - }(); + case 3: + m = data.toBN(); + n = pub_params[0].toBN(); + e = pub_params[1].toBN(); + _context.next = 8; + return _public_key2.default.rsa.encrypt(m, n, e); - return result.map(function (bn) { - var mpi = new _mpi2.default(); - mpi.fromBigInteger(bn); - return mpi; - }); - }, + case 8: + res = _context.sent; + return _context.abrupt('return', constructParams(types, [res])); + + case 10: + _m = data.toBN(); + p = pub_params[0].toBN(); + g = pub_params[1].toBN(); + y = pub_params[2].toBN(); + _context.next = 16; + return _public_key2.default.elgamal.encrypt(_m, p, g, y); + + case 16: + _res = _context.sent; + return _context.abrupt('return', constructParams(types, [_res.c1, _res.c2])); + + case 18: + oid = pub_params[0]; + Q = pub_params[1].toUint8Array(); + kdf_params = pub_params[2]; + _context.next = 23; + return _public_key2.default.elliptic.ecdh.encrypt(oid, kdf_params.cipher, kdf_params.hash, data, Q, fingerprint); + + case 23: + _res2 = _context.sent; + return _context.abrupt('return', constructParams(types, [_res2.V, _res2.C])); + + case 25: + return _context.abrupt('return', []); + + case 26: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + }))()); + + case 2: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function publicKeyEncrypt(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + } + + return publicKeyEncrypt; + }(), /** - * Decrypts data using the specified public key multiprecision integers of the private key, - * the specified secretMPIs of the private key and the specified algorithm. - * @param {module:enums.publicKey} algo Algorithm to be used (See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}) - * @param {Array} publicMPIs Algorithm dependent multiprecision integers - * of the public key part of the private key - * @param {Array} secretMPIs Algorithm dependent multiprecision integers - * of the private key used - * @param {module:type/mpi} data Data to be encrypted as MPI - * @return {module:type/mpi} returns a big integer containing the decrypted data; otherwise null + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param {module:enums.publicKey} algo Public key algorithm + * @param {Array} key_params Algorithm-specific public, private key parameters + * @param {Array} + data_params encrypted session key parameters + * @param {String} fingerprint Recipient fingerprint + * @returns {module:type/mpi} An MPI containing the decrypted data + * @async */ + publicKeyDecrypt: function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(algo, key_params, data_params, fingerprint) { + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.t0 = _mpi2.default; + _context4.next = 3; + return (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() { + var c, n, e, d, p, q, u, c1, c2, _p, x, oid, kdf_params, V, C, _d; - publicKeyDecrypt: function publicKeyDecrypt(algo, keyIntegers, dataIntegers) { - var p; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.t0 = algo; + _context3.next = _context3.t0 === _enums2.default.publicKey.rsa_encrypt_sign ? 3 : _context3.t0 === _enums2.default.publicKey.rsa_encrypt ? 3 : _context3.t0 === _enums2.default.publicKey.elgamal ? 11 : _context3.t0 === _enums2.default.publicKey.ecdh ? 16 : 22; + break; - var bn = function () { - switch (algo) { - case 'rsa_encrypt_sign': - case 'rsa_encrypt': - var rsa = new _public_key2.default.rsa(); - // 0 and 1 are the public key. - var n = keyIntegers[0].toBigInteger(); - var e = keyIntegers[1].toBigInteger(); - // 2 to 5 are the private key. - var d = keyIntegers[2].toBigInteger(); - p = keyIntegers[3].toBigInteger(); - var q = keyIntegers[4].toBigInteger(); - var u = keyIntegers[5].toBigInteger(); - var m = dataIntegers[0].toBigInteger(); - return rsa.decrypt(m, n, e, d, p, q, u); - case 'elgamal': - var elgamal = new _public_key2.default.elgamal(); - var x = keyIntegers[3].toBigInteger(); - var c1 = dataIntegers[0].toBigInteger(); - var c2 = dataIntegers[1].toBigInteger(); - p = keyIntegers[0].toBigInteger(); - return elgamal.decrypt(c1, c2, p, x); - default: - return null; - } - }(); + case 3: + c = data_params[0].toBN(); + n = key_params[0].toBN(); // n = pq - var result = new _mpi2.default(); - result.fromBigInteger(bn); - return result; - }, + e = key_params[1].toBN(); + d = key_params[2].toBN(); // de = 1 mod (p-1)(q-1) - /** Returns the number of integers comprising the private key of an algorithm + p = key_params[3].toBN(); + q = key_params[4].toBN(); + u = key_params[5].toBN(); // q^-1 mod p + + return _context3.abrupt('return', _public_key2.default.rsa.decrypt(c, n, e, d, p, q, u)); + + case 11: + c1 = data_params[0].toBN(); + c2 = data_params[1].toBN(); + _p = key_params[0].toBN(); + x = key_params[3].toBN(); + return _context3.abrupt('return', _public_key2.default.elgamal.decrypt(c1, c2, _p, x)); + + case 16: + oid = key_params[0]; + kdf_params = key_params[2]; + V = data_params[0].toUint8Array(); + C = data_params[1].data; + _d = key_params[3].toUint8Array(); + return _context3.abrupt('return', _public_key2.default.elliptic.ecdh.decrypt(oid, kdf_params.cipher, kdf_params.hash, V, C, _d, fingerprint)); + + case 22: + throw new Error('Invalid public key encryption algorithm.'); + + case 23: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + }))(); + + case 3: + _context4.t1 = _context4.sent; + return _context4.abrupt('return', new _context4.t0(_context4.t1)); + + case 5: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + function publicKeyDecrypt(_x5, _x6, _x7, _x8) { + return _ref3.apply(this, arguments); + } + + return publicKeyDecrypt; + }(), + + /** Returns the types comprising the private key of an algorithm * @param {String} algo The public key algorithm - * @return {Integer} The number of integers. + * @returns {Array} The array of types */ - getPrivateMpiCount: function getPrivateMpiCount(algo) { + getPrivKeyParamTypes: function getPrivKeyParamTypes(algo) { switch (algo) { - case 'rsa_encrypt': - case 'rsa_encrypt_sign': - case 'rsa_sign': - // Algorithm-Specific Fields for RSA secret keys: - // - multiprecision integer (MPI) of RSA secret exponent d. - // - MPI of RSA secret prime value p. - // - MPI of RSA secret prime value q (p < q). - // - MPI of u, the multiplicative inverse of p, mod q. - return 4; - case 'elgamal': - // Algorithm-Specific Fields for Elgamal secret keys: - // - MPI of Elgamal secret exponent x. - return 1; - case 'dsa': - // Algorithm-Specific Fields for DSA secret keys: - // - MPI of DSA secret exponent x. - return 1; + // Algorithm-Specific Fields for RSA secret keys: + // - multiprecision integer (MPI) of RSA secret exponent d. + // - MPI of RSA secret prime value p. + // - MPI of RSA secret prime value q (p < q). + // - MPI of u, the multiplicative inverse of p, mod q. + case _enums2.default.publicKey.rsa_encrypt: + case _enums2.default.publicKey.rsa_encrypt_sign: + case _enums2.default.publicKey.rsa_sign: + return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default]; + // Algorithm-Specific Fields for Elgamal secret keys: + // - MPI of Elgamal secret exponent x. + case _enums2.default.publicKey.elgamal: + return [_mpi2.default]; + // Algorithm-Specific Fields for DSA secret keys: + // - MPI of DSA secret exponent x. + case _enums2.default.publicKey.dsa: + return [_mpi2.default]; + // Algorithm-Specific Fields for ECDSA or ECDH secret keys: + // - MPI of an integer representing the secret key. + case _enums2.default.publicKey.ecdh: + case _enums2.default.publicKey.ecdsa: + case _enums2.default.publicKey.eddsa: + return [_mpi2.default]; default: - throw new Error('Unknown algorithm'); + throw new Error('Invalid public key encryption algorithm.'); } }, - getPublicMpiCount: function getPublicMpiCount(algo) { - // - A series of multiprecision integers comprising the key material: - // Algorithm-Specific Fields for RSA public keys: - // - a multiprecision integer (MPI) of RSA public modulus n; - // - an MPI of RSA public encryption exponent e. + /** Returns the types comprising the public key of an algorithm + * @param {String} algo The public key algorithm + * @returns {Array} The array of types + */ + getPubKeyParamTypes: function getPubKeyParamTypes(algo) { switch (algo) { - case 'rsa_encrypt': - case 'rsa_encrypt_sign': - case 'rsa_sign': - return 2; - + // Algorithm-Specific Fields for RSA public keys: + // - a multiprecision integer (MPI) of RSA public modulus n; + // - an MPI of RSA public encryption exponent e. + case _enums2.default.publicKey.rsa_encrypt: + case _enums2.default.publicKey.rsa_encrypt_sign: + case _enums2.default.publicKey.rsa_sign: + return [_mpi2.default, _mpi2.default]; // Algorithm-Specific Fields for Elgamal public keys: - // - MPI of Elgamal prime p; - // - MPI of Elgamal group generator g; - // - MPI of Elgamal public key value y (= g**x mod p where x is secret). - case 'elgamal': - return 3; - + // - MPI of Elgamal prime p; + // - MPI of Elgamal group generator g; + // - MPI of Elgamal public key value y (= g**x mod p where x is secret). + case _enums2.default.publicKey.elgamal: + return [_mpi2.default, _mpi2.default, _mpi2.default]; // Algorithm-Specific Fields for DSA public keys: // - MPI of DSA prime p; // - MPI of DSA group order q (q is a prime divisor of p-1); // - MPI of DSA group generator g; // - MPI of DSA public-key value y (= g**x mod p where x is secret). - case 'dsa': - return 4; - + case _enums2.default.publicKey.dsa: + return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default]; + // Algorithm-Specific Fields for ECDSA/EdDSA public keys: + // - OID of curve; + // - MPI of EC point representing public key. + case _enums2.default.publicKey.ecdsa: + case _enums2.default.publicKey.eddsa: + return [_oid2.default, _mpi2.default]; + // Algorithm-Specific Fields for ECDH public keys: + // - OID of curve; + // - MPI of EC point representing public key. + // - KDF: variable-length field containing KDF parameters. + case _enums2.default.publicKey.ecdh: + return [_oid2.default, _mpi2.default, _kdf_params2.default]; default: - throw new Error('Unknown algorithm.'); + throw new Error('Invalid public key encryption algorithm.'); } }, - generateMpi: function generateMpi(algo, bits) { + /** Returns the types comprising the encrypted session key of an algorithm + * @param {String} algo The public key algorithm + * @returns {Array} The array of types + */ + getEncSessionKeyParamTypes: function getEncSessionKeyParamTypes(algo) { switch (algo) { - case 'rsa_encrypt': - case 'rsa_encrypt_sign': - case 'rsa_sign': - //remember "publicKey" refers to the crypto/public_key dir - var rsa = new _public_key2.default.rsa(); - return rsa.generate(bits, "10001").then(function (keyObject) { - var output = []; - output.push(keyObject.n); - output.push(keyObject.ee); - output.push(keyObject.d); - output.push(keyObject.p); - output.push(keyObject.q); - output.push(keyObject.u); - return mapResult(output); + // Algorithm-Specific Fields for RSA encrypted session keys: + // - MPI of RSA encrypted value m**e mod n. + case _enums2.default.publicKey.rsa_encrypt: + case _enums2.default.publicKey.rsa_encrypt_sign: + return [_mpi2.default]; + + // Algorithm-Specific Fields for Elgamal encrypted session keys: + // - MPI of Elgamal value g**k mod p + // - MPI of Elgamal value m * y**k mod p + case _enums2.default.publicKey.elgamal: + return [_mpi2.default, _mpi2.default]; + // Algorithm-Specific Fields for ECDH encrypted session keys: + // - MPI containing the ephemeral key used to establish the shared secret + // - ECDH Symmetric Key + case _enums2.default.publicKey.ecdh: + return [_mpi2.default, _ecdh_symkey2.default]; + default: + throw new Error('Invalid public key encryption algorithm.'); + } + }, + + /** Generate algorithm-specific key parameters + * @param {String} algo The public key algorithm + * @param {Integer} bits Bit length for RSA keys + * @param {module:type/oid} oid Object identifier for ECC keys + * @returns {Array} The array of parameters + * @async + */ + generateParams: function generateParams(algo, bits, oid) { + var types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo)); + switch (algo) { + case _enums2.default.publicKey.rsa_encrypt: + case _enums2.default.publicKey.rsa_encrypt_sign: + case _enums2.default.publicKey.rsa_sign: + { + return _public_key2.default.rsa.generate(bits, "10001").then(function (keyObject) { + return constructParams(types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u]); + }); + } + case _enums2.default.publicKey.dsa: + case _enums2.default.publicKey.elgamal: + throw new Error('Unsupported algorithm for key generation.'); + case _enums2.default.publicKey.ecdsa: + case _enums2.default.publicKey.eddsa: + return _public_key2.default.elliptic.generate(oid).then(function (keyObject) { + return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]); + }); + case _enums2.default.publicKey.ecdh: + return _public_key2.default.elliptic.generate(oid).then(function (keyObject) { + return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]); }); default: - throw new Error('Unsupported algorithm for key generation.'); - } - - function mapResult(result) { - return result.map(function (bn) { - var mpi = new _mpi2.default(); - mpi.fromBigInteger(bn); - return mpi; - }); + throw new Error('Invalid public key algorithm.'); } }, /** - * generate random byte prefix as string for the specified algorithm - * @param {module:enums.symmetric} algo Algorithm to use (see {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2}) - * @return {Uint8Array} Random bytes with length equal to the block - * size of the cipher + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes with length equal to the block size of the cipher + * @async */ getPrefixRandom: function getPrefixRandom(algo) { return _random2.default.getRandomBytes(_cipher2.default[algo].blockSize); @@ -7379,15 +29982,42 @@ exports.default = { /** * Generating a session key for the specified symmetric algorithm - * @param {module:enums.symmetric} algo Algorithm to use (see {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2}) - * @return {Uint8Array} Random bytes as a string to be used as a key + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param {module:enums.symmetric} algo Symmetric encryption algorithm + * @returns {Uint8Array} Random bytes as a string to be used as a key + * @async */ generateSessionKey: function generateSessionKey(algo) { return _random2.default.getRandomBytes(_cipher2.default[algo].keySize); - } + }, + + constructParams: constructParams }; -},{"../type/mpi.js":68,"./cipher":16,"./public_key":28,"./random.js":31}],19:[function(_dereq_,module,exports){ +},{"../enums":337,"../type/ecdh_symkey":370,"../type/kdf_params":371,"../type/mpi":373,"../type/oid":374,"../util":376,"./cipher":313,"./public_key":330,"./random":333,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],316:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _exports = _dereq_('asmcrypto.js/src/aes/gcm/exports'); + +var _config = _dereq_('../config'); + +var _config2 = _interopRequireDefault(_config); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var webCrypto = _util2.default.getWebCrypto(); // no GCM support in IE11, Safari 9 // OpenPGP.js - An OpenPGP implementation in javascript // Copyright (C) 2016 Tankred Hase // @@ -7408,36 +30038,16 @@ exports.default = { /** * @fileoverview This module wraps native AES-GCM en/decryption for both * the WebCrypto api as well as node.js' crypto api. + * @requires asmcrypto.js + * @requires config + * @requires util + * @module crypto/gcm */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.ivLength = undefined; -exports.encrypt = encrypt; -exports.decrypt = decrypt; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _config = _dereq_('../config'); - -var _config2 = _interopRequireDefault(_config); - -var _asmcryptoLite = _dereq_('asmcrypto-lite'); - -var _asmcryptoLite2 = _interopRequireDefault(_asmcryptoLite); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var webCrypto = _util2.default.getWebCrypto(); // no GCM support in IE11, Safari 9 var nodeCrypto = _util2.default.getNodeCrypto(); var Buffer = _util2.default.getNodeBuffer(); -var ivLength = exports.ivLength = 12; // size of the IV in bytes +var ivLength = 12; // size of the IV in bytes var TAG_LEN = 16; // size of the tag in bytes var ALGO = 'AES-GCM'; @@ -7447,23 +30057,21 @@ var ALGO = 'AES-GCM'; * @param {Uint8Array} plaintext The cleartext input to be encrypted * @param {Uint8Array} key The encryption key * @param {Uint8Array} iv The initialization vector (12 bytes) - * @return {Promise} The ciphertext output + * @returns {Promise} The ciphertext output */ function encrypt(cipher, plaintext, key, iv) { if (cipher.substr(0, 3) !== 'aes') { - return Promise.reject(new Error('GCM mode supports only AES cipher')); + return _promise2.default.reject(new Error('GCM mode supports only AES cipher')); } - if (webCrypto && _config2.default.use_native && key.length !== 24) { + if (webCrypto && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support return webEncrypt(plaintext, key, iv); - } else if (nodeCrypto && _config2.default.use_native) { + } else if (nodeCrypto) { // Node crypto library return nodeEncrypt(plaintext, key, iv); - } else { - // asm.js fallback - return Promise.resolve(_asmcryptoLite2.default.AES_GCM.encrypt(plaintext, key, iv)); - } + } // asm.js fallback + return _promise2.default.resolve(_exports.AES_GCM.encrypt(plaintext, key, iv)); } /** @@ -7472,25 +30080,29 @@ function encrypt(cipher, plaintext, key, iv) { * @param {Uint8Array} ciphertext The ciphertext input to be decrypted * @param {Uint8Array} key The encryption key * @param {Uint8Array} iv The initialization vector (12 bytes) - * @return {Promise} The plaintext output + * @returns {Promise} The plaintext output */ function decrypt(cipher, ciphertext, key, iv) { if (cipher.substr(0, 3) !== 'aes') { - return Promise.reject(new Error('GCM mode supports only AES cipher')); + return _promise2.default.reject(new Error('GCM mode supports only AES cipher')); } - if (webCrypto && _config2.default.use_native && key.length !== 24) { + if (webCrypto && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support return webDecrypt(ciphertext, key, iv); - } else if (nodeCrypto && _config2.default.use_native) { + } else if (nodeCrypto) { // Node crypto library return nodeDecrypt(ciphertext, key, iv); - } else { - // asm.js fallback - return Promise.resolve(_asmcryptoLite2.default.AES_GCM.decrypt(ciphertext, key, iv)); - } + } // asm.js fallback + return _promise2.default.resolve(_exports.AES_GCM.decrypt(ciphertext, key, iv)); } +exports.default = { + ivLength: ivLength, + encrypt: encrypt, + decrypt: decrypt +}; + ////////////////////////// // // // Helper functions // @@ -7520,7 +30132,7 @@ function nodeEncrypt(pt, key, iv) { iv = new Buffer(iv); var en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-gcm', key, iv); var ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext - return Promise.resolve(new Uint8Array(ct)); + return _promise2.default.resolve(new Uint8Array(ct)); } function nodeDecrypt(ct, key, iv) { @@ -7530,53 +30142,59 @@ function nodeDecrypt(ct, key, iv) { var de = new nodeCrypto.createDecipheriv('aes-' + key.length * 8 + '-gcm', key, iv); de.setAuthTag(ct.slice(ct.length - TAG_LEN, ct.length)); // read auth tag at end of ciphertext var pt = Buffer.concat([de.update(ct.slice(0, ct.length - TAG_LEN)), de.final()]); - return Promise.resolve(new Uint8Array(pt)); + return _promise2.default.resolve(new Uint8Array(pt)); } -},{"../config":10,"../util.js":70,"asmcrypto-lite":1}],20:[function(_dereq_,module,exports){ -/** - * @requires crypto/hash/sha - * @requires crypto/hash/md5 - * @requires crypto/hash/ripe-md - * @requires util - * @module crypto/hash - */ - +},{"../config":306,"../util":376,"asmcrypto.js/src/aes/gcm/exports":8,"babel-runtime/core-js/promise":25}],317:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -var _sha = _dereq_('./sha.js'); - -var _sha2 = _interopRequireDefault(_sha); - -var _asmcryptoLite = _dereq_('asmcrypto-lite'); - -var _asmcryptoLite2 = _interopRequireDefault(_asmcryptoLite); - var _rusha = _dereq_('rusha'); var _rusha2 = _interopRequireDefault(_rusha); -var _md = _dereq_('./md5.js'); +var _exports = _dereq_('asmcrypto.js/src/hash/sha256/exports'); + +var _ = _dereq_('hash.js/lib/hash/sha/224'); + +var _2 = _interopRequireDefault(_); + +var _3 = _dereq_('hash.js/lib/hash/sha/384'); + +var _4 = _interopRequireDefault(_3); + +var _5 = _dereq_('hash.js/lib/hash/sha/512'); + +var _6 = _interopRequireDefault(_5); + +var _ripemd = _dereq_('hash.js/lib/hash/ripemd'); + +var _md = _dereq_('./md5'); var _md2 = _interopRequireDefault(_md); -var _ripeMd = _dereq_('./ripe-md.js'); - -var _ripeMd2 = _interopRequireDefault(_ripeMd); - -var _util = _dereq_('../../util.js'); +var _util = _dereq_('../../util'); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var rusha = new _rusha2.default(), - nodeCrypto = _util2.default.getNodeCrypto(), - Buffer = _util2.default.getNodeBuffer(); +/** + * @fileoverview Hashing functions + * @requires rusha + * @requires asmcrypto.js + * @requires hash.js + * @requires crypto/hash/md5 + * @requires util + * @module crypto/hash + */ + +var rusha = new _rusha2.default(); +var nodeCrypto = _util2.default.getNodeCrypto(); +var Buffer = _util2.default.getNodeBuffer(); function node_hash(type) { return function (data) { @@ -7586,10 +30204,15 @@ function node_hash(type) { }; } -var hash_fns; +function hashjs_hash(hash) { + return function (data) { + return _util2.default.str_to_Uint8Array(_util2.default.hex_to_str(hash().update(data).digest('hex'))); + }; +} + +var hash_fns = void 0; if (nodeCrypto) { // Use Node native crypto for all hash functions - hash_fns = { md5: node_hash('md5'), sha1: node_hash('sha1'), @@ -7601,24 +30224,24 @@ if (nodeCrypto) { }; } else { // Use JS fallbacks - hash_fns = { - /** @see module:crypto/hash/md5 */ + /** @see module:./md5 */ md5: _md2.default, /** @see module:rusha */ sha1: function sha1(data) { - return _util2.default.str2Uint8Array(_util2.default.hex2bin(rusha.digest(data))); + return _util2.default.str_to_Uint8Array(_util2.default.hex_to_str(rusha.digest(data))); }, - /** @see module:crypto/hash/sha.sha224 */ - sha224: _sha2.default.sha224, + /** @see module:hash.js */ + sha224: hashjs_hash(_2.default), /** @see module:asmcrypto */ - sha256: _asmcryptoLite2.default.SHA256.bytes, - /** @see module:crypto/hash/sha.sha384 */ - sha384: _sha2.default.sha384, - /** @see module:crypto/hash/sha.sha512 */ - sha512: _sha2.default.sha512, - /** @see module:crypto/hash/ripe-md */ - ripemd: _ripeMd2.default + sha256: _exports.SHA256.bytes, + /** @see module:hash.js */ + sha384: hashjs_hash(_4.default), + // TODO, benchmark this vs asmCrypto's SHA512 + /** @see module:hash.js */ + sha512: hashjs_hash(_6.default), + /** @see module:hash.js */ + ripemd: hashjs_hash(_ripemd.ripemd160) }; } @@ -7636,7 +30259,7 @@ exports.default = { * Create a hash on the specified data using the specified algorithm * @param {module:enums.hash} algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) * @param {Uint8Array} data Data to be hashed - * @return {Uint8Array} hash value + * @returns {Uint8Array} hash value */ digest: function digest(algo, data) { switch (algo) { @@ -7669,7 +30292,7 @@ exports.default = { /** * Returns the hash size in bytes of the specified hash algorithm type * @param {module:enums.hash} algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @return {Integer} Size in bytes of the resulting hash + * @returns {Integer} Size in bytes of the resulting hash */ getHashByteLength: function getHashByteLength(algo) { switch (algo) { @@ -7699,49 +30322,50 @@ exports.default = { } }; -},{"../../util.js":70,"./md5.js":21,"./ripe-md.js":22,"./sha.js":23,"asmcrypto-lite":1,"rusha":4}],21:[function(_dereq_,module,exports){ -/** - * A fast MD5 JavaScript implementation - * Copyright (c) 2012 Joseph Myers - * http://www.myersdaily.org/joseph/javascript/md5-text.html - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for any purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * Of course, this soft is provided "as is" without express or implied - * warranty of any kind. - */ - -/** - * @requires util - * @module crypto/hash/md5 - */ - +},{"../../util":376,"./md5":318,"asmcrypto.js/src/hash/sha256/exports":12,"hash.js/lib/hash/ripemd":268,"hash.js/lib/hash/sha/224":271,"hash.js/lib/hash/sha/384":273,"hash.js/lib/hash/sha/512":274,"rusha":301}],318:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = function (entree) { - var hex = md5(_util2.default.Uint8Array2str(entree)); - var bin = _util2.default.str2Uint8Array(_util2.default.hex2bin(hex)); - return bin; -}; - -var _util = _dereq_('../../util.js'); +var _util = _dereq_('../../util'); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * MD5 hash + * @param {String} entree string to hash + */ +function md5(entree) { + var digest = md51(_util2.default.Uint8Array_to_str(entree)); + return _util2.default.hex_to_Uint8Array(hex(digest)); +} /** + * A fast MD5 JavaScript implementation + * Copyright (c) 2012 Joseph Myers + * http://www.myersdaily.org/joseph/javascript/md5-text.html + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. + * + * Of course, this soft is provided "as is" without express or implied + * warranty of any kind. + */ + +/** + * @requires util + * @module crypto/hash/md5 + */ + function md5cycle(x, k) { - var a = x[0], - b = x[1], - c = x[2], - d = x[3]; + var a = x[0]; + var b = x[1]; + var c = x[2]; + var d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); @@ -7817,12 +30441,6 @@ function md5cycle(x, k) { x[3] = add32(d, x[3]); } -/** - * MD5 hash - * @param {String} entree string to hash - */ - - function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32(a << s | a >>> 32 - s, b); @@ -7845,9 +30463,9 @@ function ii(a, b, c, d, x, s, t) { } function md51(s) { - var n = s.length, - state = [1732584193, -271733879, -1732584194, 271733878], - i; + var n = s.length; + var state = [1732584193, -271733879, -1732584194, 271733878]; + var i = void 0; for (i = 64; i <= s.length; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); } @@ -7885,8 +30503,8 @@ function md51(s) { */ function md5blk(s) { /* I figured global was faster. */ - var md5blks = [], - i; /* Andy King said do it this way. */ + var md5blks = []; + var i = void 0; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); } @@ -7896,8 +30514,8 @@ function md5blk(s) { var hex_chr = '0123456789abcdef'.split(''); function rhex(n) { - var s = '', - j = 0; + var s = ''; + var j = 0; for (; j < 4; j++) { s += hex_chr[n >> j * 8 + 4 & 0x0F] + hex_chr[n >> j * 8 & 0x0F]; } @@ -7911,10 +30529,6 @@ function hex(x) { return x.join(''); } -function md5(s) { - return hex(md51(s)); -} - /* this function is much faster, so if possible we use it. Some IEs are the only ones I know of that @@ -7925,1621 +30539,9 @@ function add32(a, b) { return a + b & 0xFFFFFFFF; } -},{"../../util.js":70}],22:[function(_dereq_,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = RMDstring; - -var _util = _dereq_("../../util.js"); - -var _util2 = _interopRequireDefault(_util); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var RMDsize = 160; /* - * CryptoMX Tools - * Copyright (C) 2004 - 2006 Derek Buitenhuis - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - -/* Modified by Recurity Labs GmbH - */ - -/* Modified by ProtonTech AG - */ - -/** - * @requires util - * @module crypto/hash/ripe-md - */ - -var X = []; - -function ROL(x, n) { - return new Number(x << n | x >>> 32 - n); -} - -function F(x, y, z) { - return new Number(x ^ y ^ z); -} - -function G(x, y, z) { - return new Number(x & y | ~x & z); -} - -function H(x, y, z) { - return new Number((x | ~y) ^ z); -} - -function I(x, y, z) { - return new Number(x & z | y & ~z); -} - -function J(x, y, z) { - return new Number(x ^ (y | ~z)); -} - -function mixOneRound(a, b, c, d, e, x, s, roundNumber) { - switch (roundNumber) { - case 0: - a += F(b, c, d) + x + 0x00000000; - break; - case 1: - a += G(b, c, d) + x + 0x5a827999; - break; - case 2: - a += H(b, c, d) + x + 0x6ed9eba1; - break; - case 3: - a += I(b, c, d) + x + 0x8f1bbcdc; - break; - case 4: - a += J(b, c, d) + x + 0xa953fd4e; - break; - case 5: - a += J(b, c, d) + x + 0x50a28be6; - break; - case 6: - a += I(b, c, d) + x + 0x5c4dd124; - break; - case 7: - a += H(b, c, d) + x + 0x6d703ef3; - break; - case 8: - a += G(b, c, d) + x + 0x7a6d76e9; - break; - case 9: - a += F(b, c, d) + x + 0x00000000; - break; - - default: - throw new Error("Bogus round number"); - break; - } - - a = ROL(a, s) + e; - c = ROL(c, 10); - - a &= 0xffffffff; - b &= 0xffffffff; - c &= 0xffffffff; - d &= 0xffffffff; - e &= 0xffffffff; - - var retBlock = []; - retBlock[0] = a; - retBlock[1] = b; - retBlock[2] = c; - retBlock[3] = d; - retBlock[4] = e; - retBlock[5] = x; - retBlock[6] = s; - - return retBlock; -} - -function MDinit(MDbuf) { - MDbuf[0] = 0x67452301; - MDbuf[1] = 0xefcdab89; - MDbuf[2] = 0x98badcfe; - MDbuf[3] = 0x10325476; - MDbuf[4] = 0xc3d2e1f0; -} - -var ROLs = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], [7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12], [11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5], [11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12], [9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6], [9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11], [9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5], [15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8], [8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]]; - -var indexes = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8], [3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12], [1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2], [4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12], [6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2], [15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13], [8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14], [12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]]; - -function compress(MDbuf, X) { - var blockA = []; - var blockB = []; - - var retBlock; - - var i, j; - - for (i = 0; i < 5; i++) { - blockA[i] = new Number(MDbuf[i]); - blockB[i] = new Number(MDbuf[i]); - } - - var step = 0; - for (j = 0; j < 5; j++) { - for (i = 0; i < 16; i++) { - retBlock = mixOneRound(blockA[(step + 0) % 5], blockA[(step + 1) % 5], blockA[(step + 2) % 5], blockA[(step + 3) % 5], blockA[(step + 4) % 5], X[indexes[j][i]], ROLs[j][i], j); - - blockA[(step + 0) % 5] = retBlock[0]; - blockA[(step + 1) % 5] = retBlock[1]; - blockA[(step + 2) % 5] = retBlock[2]; - blockA[(step + 3) % 5] = retBlock[3]; - blockA[(step + 4) % 5] = retBlock[4]; - - step += 4; - } - } - - step = 0; - for (j = 5; j < 10; j++) { - for (i = 0; i < 16; i++) { - retBlock = mixOneRound(blockB[(step + 0) % 5], blockB[(step + 1) % 5], blockB[(step + 2) % 5], blockB[(step + 3) % 5], blockB[(step + 4) % 5], X[indexes[j][i]], ROLs[j][i], j); - - blockB[(step + 0) % 5] = retBlock[0]; - blockB[(step + 1) % 5] = retBlock[1]; - blockB[(step + 2) % 5] = retBlock[2]; - blockB[(step + 3) % 5] = retBlock[3]; - blockB[(step + 4) % 5] = retBlock[4]; - - step += 4; - } - } - - blockB[3] += blockA[2] + MDbuf[1]; - MDbuf[1] = MDbuf[2] + blockA[3] + blockB[4]; - MDbuf[2] = MDbuf[3] + blockA[4] + blockB[0]; - MDbuf[3] = MDbuf[4] + blockA[0] + blockB[1]; - MDbuf[4] = MDbuf[0] + blockA[1] + blockB[2]; - MDbuf[0] = blockB[3]; -} - -function zeroX(X) { - for (var i = 0; i < 16; i++) { - X[i] = 0; - } -} - -function MDfinish(MDbuf, strptr, lswlen, mswlen) { - var X = new Array(16); - zeroX(X); - - var j = 0; - for (var i = 0; i < (lswlen & 63); i++) { - X[i >>> 2] ^= (strptr.charCodeAt(j++) & 255) << 8 * (i & 3); - } - - X[lswlen >>> 2 & 15] ^= 1 << 8 * (lswlen & 3) + 7; - - if ((lswlen & 63) > 55) { - compress(MDbuf, X); - X = new Array(16); - zeroX(X); - } - - X[14] = lswlen << 3; - X[15] = lswlen >>> 29 | mswlen << 3; - - compress(MDbuf, X); -} - -function BYTES_TO_DWORD(fourChars) { - var tmp = (fourChars.charCodeAt(3) & 255) << 24; - tmp |= (fourChars.charCodeAt(2) & 255) << 16; - tmp |= (fourChars.charCodeAt(1) & 255) << 8; - tmp |= fourChars.charCodeAt(0) & 255; - - return tmp; -} - -function RMD(message) { - var MDbuf = new Array(RMDsize / 32); - var hashcode = new Array(RMDsize / 8); - var length; - var nbytes; - - MDinit(MDbuf); - length = message.length; - - var X = new Array(16); - zeroX(X); - - var i, - j = 0; - for (nbytes = length; nbytes > 63; nbytes -= 64) { - for (i = 0; i < 16; i++) { - X[i] = BYTES_TO_DWORD(message.substr(j, 4)); - j += 4; - } - compress(MDbuf, X); - } - - MDfinish(MDbuf, message.substr(j), length, 0); - - for (i = 0; i < RMDsize / 8; i += 4) { - hashcode[i] = MDbuf[i >>> 2] & 255; - hashcode[i + 1] = MDbuf[i >>> 2] >>> 8 & 255; - hashcode[i + 2] = MDbuf[i >>> 2] >>> 16 & 255; - hashcode[i + 3] = MDbuf[i >>> 2] >>> 24 & 255; - } - - return hashcode; -} - -function RMDstring(message) { - var hashcode = RMD(_util2.default.Uint8Array2str(message)); - var retString = ""; - - for (var i = 0; i < RMDsize / 8; i++) { - retString += String.fromCharCode(hashcode[i]); - } - - return _util2.default.str2Uint8Array(retString); -} - -},{"../../util.js":70}],23:[function(_dereq_,module,exports){ -/** - * @preserve A JavaScript implementation of the SHA family of hashes, as - * defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation - * as defined in FIPS PUB 198a - * - * Copyright Brian Turek 2008-2015 - * Distributed under the BSD License - * See https://caligatio.github.io/jsSHA/ for more information - * - * Several functions taken from Paul Johnston - */ - -/** - * SUPPORTED_ALGS is the stub for a compile flag that will cause pruning of - * functions that are not needed when a limited number of SHA families are - * selected - * - * @define {number} ORed value of SHA variants to be supported - * 1 = SHA-1, 2 = SHA-224/SHA-256, 4 = SHA-384/SHA-512 - */ - -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var SUPPORTED_ALGS = 4 | 2 | 1; - -/** - * Int_64 is a object for 2 32-bit numbers emulating a 64-bit number - * - * @private - * @constructor - * @this {Int_64} - * @param {number} msint_32 The most significant 32-bits of a 64-bit number - * @param {number} lsint_32 The least significant 32-bits of a 64-bit number - */ -function Int_64(msint_32, lsint_32) { - this.highOrder = msint_32; - this.lowOrder = lsint_32; -} - -/** - * Convert a string to an array of big-endian words - * - * @private - * @param {string} str String to be converted to binary representation - * @param {string} utfType The Unicode type, UTF8 or UTF16BE, UTF16LE, to - * use to encode the source string - * @return {{value : Array., binLen : number}} Hash list where - * "value" contains the output number array and "binLen" is the binary - * length of "value" - */ -function str2binb(str, utfType) { - var bin = [], - codePnt, - binArr = [], - byteCnt = 0, - i, - j, - offset; - - if ("UTF8" === utfType) { - for (i = 0; i < str.length; i += 1) { - codePnt = str.charCodeAt(i); - binArr = []; - - if (0x80 > codePnt) { - binArr.push(codePnt); - } else if (0x800 > codePnt) { - binArr.push(0xC0 | codePnt >>> 6); - binArr.push(0x80 | codePnt & 0x3F); - } else if (0xd800 > codePnt || 0xe000 <= codePnt) { - binArr.push(0xe0 | codePnt >>> 12, 0x80 | codePnt >>> 6 & 0x3f, 0x80 | codePnt & 0x3f); - } else { - i += 1; - codePnt = 0x10000 + ((codePnt & 0x3ff) << 10 | str.charCodeAt(i) & 0x3ff); - binArr.push(0xf0 | codePnt >>> 18, 0x80 | codePnt >>> 12 & 0x3f, 0x80 | codePnt >>> 6 & 0x3f, 0x80 | codePnt & 0x3f); - } - - for (j = 0; j < binArr.length; j += 1) { - offset = byteCnt >>> 2; - while (bin.length <= offset) { - bin.push(0); - } - bin[offset] |= binArr[j] << 24 - 8 * (byteCnt % 4); - byteCnt += 1; - } - } - } else if ("UTF16BE" === utfType || "UTF16LE" === utfType) { - for (i = 0; i < str.length; i += 1) { - codePnt = str.charCodeAt(i); - /* Internally strings are UTF-16BE so only change if UTF-16LE */ - if ("UTF16LE" === utfType) { - j = codePnt & 0xFF; - codePnt = j << 8 | codePnt >> 8; - } - - offset = byteCnt >>> 2; - while (bin.length <= offset) { - bin.push(0); - } - bin[offset] |= codePnt << 16 - 8 * (byteCnt % 4); - byteCnt += 2; - } - } - return { "value": bin, "binLen": byteCnt * 8 }; -} - -/** - * Convert a hex string to an array of big-endian words - * - * @private - * @param {string} str String to be converted to binary representation - * @return {{value : Array., binLen : number}} Hash list where - * "value" contains the output number array and "binLen" is the binary - * length of "value" - */ -function hex2binb(str) { - var bin = [], - length = str.length, - i, - num, - offset; - - if (0 !== length % 2) { - throw "String of HEX type must be in byte increments"; - } - - for (i = 0; i < length; i += 2) { - num = parseInt(str.substr(i, 2), 16); - if (!isNaN(num)) { - offset = i >>> 3; - while (bin.length <= offset) { - bin.push(0); - } - bin[i >>> 3] |= num << 24 - 4 * (i % 8); - } else { - throw "String of HEX type contains invalid characters"; - } - } - - return { "value": bin, "binLen": length * 4 }; -} - -/** - * Convert a string of raw bytes to an array of big-endian words - * - * @private - * @param {string} str String of raw bytes to be converted to binary representation - * @return {{value : Array., binLen : number}} Hash list where - * "value" contains the output number array and "binLen" is the binary - * length of "value" - */ -function bytes2binb(str) { - var bin = [], - codePnt, - i, - offset; - - for (i = 0; i < str.length; i += 1) { - codePnt = str.charCodeAt(i); - - offset = i >>> 2; - if (bin.length <= offset) { - bin.push(0); - } - bin[offset] |= codePnt << 24 - 8 * (i % 4); - } - - return { "value": bin, "binLen": str.length * 8 }; -} - -/** - * Convert a Uint8Array of raw bytes to an array of big-endian 32-bit words - * - * @private - * @param {Uint8Array} str String of raw bytes to be converted to binary representation - * @return {{value : Array., binLen : number}} Hash list where - * "value" contains the output array and "binLen" is the binary - * length of "value" - */ -function typed2binb(array) { - - var bin = [], - octet, - i, - offset; - - for (i = 0; i < array.length; i += 1) { - octet = array[i]; - - offset = i >>> 2; - if (bin.length <= offset) { - bin.push(0); - } - bin[offset] |= octet << 24 - 8 * (i % 4); - } - - return { "value": bin, "binLen": array.length * 8 }; -} - -/** - * Convert a base-64 string to an array of big-endian words - * - * @private - * @param {string} str String to be converted to binary representation - * @return {{value : Array., binLen : number}} Hash list where - * "value" contains the output number array and "binLen" is the binary - * length of "value" - */ -function b642binb(str) { - var retVal = [], - byteCnt = 0, - index, - i, - j, - tmpInt, - strPart, - firstEqual, - offset, - b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - if (-1 === str.search(/^[a-zA-Z0-9=+\/]+$/)) { - throw "Invalid character in base-64 string"; - } - firstEqual = str.indexOf('='); - str = str.replace(/\=/g, ''); - if (-1 !== firstEqual && firstEqual < str.length) { - throw "Invalid '=' found in base-64 string"; - } - - for (i = 0; i < str.length; i += 4) { - strPart = str.substr(i, 4); - tmpInt = 0; - - for (j = 0; j < strPart.length; j += 1) { - index = b64Tab.indexOf(strPart[j]); - tmpInt |= index << 18 - 6 * j; - } - - for (j = 0; j < strPart.length - 1; j += 1) { - offset = byteCnt >>> 2; - while (retVal.length <= offset) { - retVal.push(0); - } - retVal[offset] |= (tmpInt >>> 16 - j * 8 & 0xFF) << 24 - 8 * (byteCnt % 4); - byteCnt += 1; - } - } - - return { "value": retVal, "binLen": byteCnt * 8 }; -} - -/** - * Convert an array of big-endian words to a hex string. - * - * @private - * @param {Array.} binarray Array of integers to be converted to - * hexidecimal representation - * @param {{outputUpper : boolean, b64Pad : string}} formatOpts Hash list - * containing validated output formatting options - * @return {string} Hexidecimal representation of the parameter in string - * form - */ -function binb2hex(binarray, formatOpts) { - var hex_tab = "0123456789abcdef", - str = "", - length = binarray.length * 4, - i, - srcByte; - - for (i = 0; i < length; i += 1) { - /* The below is more than a byte but it gets taken care of later */ - srcByte = binarray[i >>> 2] >>> (3 - i % 4) * 8; - str += hex_tab.charAt(srcByte >>> 4 & 0xF) + hex_tab.charAt(srcByte & 0xF); - } - - return formatOpts["outputUpper"] ? str.toUpperCase() : str; -} - -/** - * Convert an array of big-endian words to a base-64 string - * - * @private - * @param {Array.} binarray Array of integers to be converted to - * base-64 representation - * @param {{outputUpper : boolean, b64Pad : string}} formatOpts Hash list - * containing validated output formatting options - * @return {string} Base-64 encoded representation of the parameter in - * string form - */ -function binb2b64(binarray, formatOpts) { - var str = "", - length = binarray.length * 4, - i, - j, - triplet, - offset, - int1, - int2, - b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - for (i = 0; i < length; i += 3) { - offset = i + 1 >>> 2; - int1 = binarray.length <= offset ? 0 : binarray[offset]; - offset = i + 2 >>> 2; - int2 = binarray.length <= offset ? 0 : binarray[offset]; - triplet = (binarray[i >>> 2] >>> 8 * (3 - i % 4) & 0xFF) << 16 | (int1 >>> 8 * (3 - (i + 1) % 4) & 0xFF) << 8 | int2 >>> 8 * (3 - (i + 2) % 4) & 0xFF; - for (j = 0; j < 4; j += 1) { - if (i * 8 + j * 6 <= binarray.length * 32) { - str += b64Tab.charAt(triplet >>> 6 * (3 - j) & 0x3F); - } else { - str += formatOpts["b64Pad"]; - } - } - } - return str; -} - -/** - * Convert an array of big-endian words to raw bytes string - * - * @private - * @param {Array.} binarray Array of integers to be converted to - * a raw bytes string representation - * @param {!Object} formatOpts Unused Hash list - * @return {string} Raw bytes representation of the parameter in string - * form - */ -function binb2bytes(binarray, formatOpts) { - var str = "", - length = binarray.length * 4, - i, - srcByte; - - for (i = 0; i < length; i += 1) { - srcByte = binarray[i >>> 2] >>> (3 - i % 4) * 8 & 0xFF; - str += String.fromCharCode(srcByte); - } - - return str; -} - -/** - * Convert an array of big-endian words to raw bytes Uint8Array - * - * @private - * @param {Array.} binarray Array of integers to be converted to - * a raw bytes string representation - * @param {!Object} formatOpts Unused Hash list - * @return {Uint8Array} Raw bytes representation of the parameter - */ -function binb2typed(binarray, formatOpts) { - var length = binarray.length * 4; - var arr = new Uint8Array(length), - i; - - for (i = 0; i < length; i += 1) { - arr[i] = binarray[i >>> 2] >>> (3 - i % 4) * 8 & 0xFF; - } - - return arr; -} - -/** - * Validate hash list containing output formatting options, ensuring - * presence of every option or adding the default value - * - * @private - * @param {{outputUpper : boolean, b64Pad : string}|undefined} outputOpts - * Hash list of output formatting options - * @return {{outputUpper : boolean, b64Pad : string}} Validated hash list - * containing output formatting options - */ -function getOutputOpts(outputOpts) { - var retVal = { "outputUpper": false, "b64Pad": "=" }; - - try { - if (outputOpts.hasOwnProperty("outputUpper")) { - retVal["outputUpper"] = outputOpts["outputUpper"]; - } - - if (outputOpts.hasOwnProperty("b64Pad")) { - retVal["b64Pad"] = outputOpts["b64Pad"]; - } - } catch (ignore) {} - - if ("boolean" !== typeof retVal["outputUpper"]) { - throw "Invalid outputUpper formatting option"; - } - - if ("string" !== typeof retVal["b64Pad"]) { - throw "Invalid b64Pad formatting option"; - } - - return retVal; -} - -/** - * The 32-bit implementation of circular rotate left - * - * @private - * @param {number} x The 32-bit integer argument - * @param {number} n The number of bits to shift - * @return {number} The x shifted circularly by n bits - */ -function rotl_32(x, n) { - return x << n | x >>> 32 - n; -} - -/** - * The 32-bit implementation of circular rotate right - * - * @private - * @param {number} x The 32-bit integer argument - * @param {number} n The number of bits to shift - * @return {number} The x shifted circularly by n bits - */ -function rotr_32(x, n) { - return x >>> n | x << 32 - n; -} - -/** - * The 64-bit implementation of circular rotate right - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @param {number} n The number of bits to shift - * @return {Int_64} The x shifted circularly by n bits - */ -function rotr_64(x, n) { - var retVal = null, - tmp = new Int_64(x.highOrder, x.lowOrder); - - if (32 >= n) { - retVal = new Int_64(tmp.highOrder >>> n | tmp.lowOrder << 32 - n & 0xFFFFFFFF, tmp.lowOrder >>> n | tmp.highOrder << 32 - n & 0xFFFFFFFF); - } else { - retVal = new Int_64(tmp.lowOrder >>> n - 32 | tmp.highOrder << 64 - n & 0xFFFFFFFF, tmp.highOrder >>> n - 32 | tmp.lowOrder << 64 - n & 0xFFFFFFFF); - } - - return retVal; -} - -/** - * The 32-bit implementation of shift right - * - * @private - * @param {number} x The 32-bit integer argument - * @param {number} n The number of bits to shift - * @return {number} The x shifted by n bits - */ -function shr_32(x, n) { - return x >>> n; -} - -/** - * The 64-bit implementation of shift right - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @param {number} n The number of bits to shift - * @return {Int_64} The x shifted by n bits - */ -function shr_64(x, n) { - var retVal = null; - - if (32 >= n) { - retVal = new Int_64(x.highOrder >>> n, x.lowOrder >>> n | x.highOrder << 32 - n & 0xFFFFFFFF); - } else { - retVal = new Int_64(0, x.highOrder >>> n - 32); - } - - return retVal; -} - -/** - * The 32-bit implementation of the NIST specified Parity function - * - * @private - * @param {number} x The first 32-bit integer argument - * @param {number} y The second 32-bit integer argument - * @param {number} z The third 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function parity_32(x, y, z) { - return x ^ y ^ z; -} - -/** - * The 32-bit implementation of the NIST specified Ch function - * - * @private - * @param {number} x The first 32-bit integer argument - * @param {number} y The second 32-bit integer argument - * @param {number} z The third 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function ch_32(x, y, z) { - return x & y ^ ~x & z; -} - -/** - * The 64-bit implementation of the NIST specified Ch function - * - * @private - * @param {Int_64} x The first 64-bit integer argument - * @param {Int_64} y The second 64-bit integer argument - * @param {Int_64} z The third 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function ch_64(x, y, z) { - return new Int_64(x.highOrder & y.highOrder ^ ~x.highOrder & z.highOrder, x.lowOrder & y.lowOrder ^ ~x.lowOrder & z.lowOrder); -} - -/** - * The 32-bit implementation of the NIST specified Maj function - * - * @private - * @param {number} x The first 32-bit integer argument - * @param {number} y The second 32-bit integer argument - * @param {number} z The third 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function maj_32(x, y, z) { - return x & y ^ x & z ^ y & z; -} - -/** - * The 64-bit implementation of the NIST specified Maj function - * - * @private - * @param {Int_64} x The first 64-bit integer argument - * @param {Int_64} y The second 64-bit integer argument - * @param {Int_64} z The third 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function maj_64(x, y, z) { - return new Int_64(x.highOrder & y.highOrder ^ x.highOrder & z.highOrder ^ y.highOrder & z.highOrder, x.lowOrder & y.lowOrder ^ x.lowOrder & z.lowOrder ^ y.lowOrder & z.lowOrder); -} - -/** - * The 32-bit implementation of the NIST specified Sigma0 function - * - * @private - * @param {number} x The 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function sigma0_32(x) { - return rotr_32(x, 2) ^ rotr_32(x, 13) ^ rotr_32(x, 22); -} - -/** - * The 64-bit implementation of the NIST specified Sigma0 function - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function sigma0_64(x) { - var rotr28 = rotr_64(x, 28), - rotr34 = rotr_64(x, 34), - rotr39 = rotr_64(x, 39); - - return new Int_64(rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder, rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder); -} - -/** - * The 32-bit implementation of the NIST specified Sigma1 function - * - * @private - * @param {number} x The 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function sigma1_32(x) { - return rotr_32(x, 6) ^ rotr_32(x, 11) ^ rotr_32(x, 25); -} - -/** - * The 64-bit implementation of the NIST specified Sigma1 function - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function sigma1_64(x) { - var rotr14 = rotr_64(x, 14), - rotr18 = rotr_64(x, 18), - rotr41 = rotr_64(x, 41); - - return new Int_64(rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder, rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder); -} - -/** - * The 32-bit implementation of the NIST specified Gamma0 function - * - * @private - * @param {number} x The 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function gamma0_32(x) { - return rotr_32(x, 7) ^ rotr_32(x, 18) ^ shr_32(x, 3); -} - -/** - * The 64-bit implementation of the NIST specified Gamma0 function - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function gamma0_64(x) { - var rotr1 = rotr_64(x, 1), - rotr8 = rotr_64(x, 8), - shr7 = shr_64(x, 7); - - return new Int_64(rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder, rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder); -} - -/** - * The 32-bit implementation of the NIST specified Gamma1 function - * - * @private - * @param {number} x The 32-bit integer argument - * @return {number} The NIST specified output of the function - */ -function gamma1_32(x) { - return rotr_32(x, 17) ^ rotr_32(x, 19) ^ shr_32(x, 10); -} - -/** - * The 64-bit implementation of the NIST specified Gamma1 function - * - * @private - * @param {Int_64} x The 64-bit integer argument - * @return {Int_64} The NIST specified output of the function - */ -function gamma1_64(x) { - var rotr19 = rotr_64(x, 19), - rotr61 = rotr_64(x, 61), - shr6 = shr_64(x, 6); - - return new Int_64(rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder, rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder); -} - -/** - * Add two 32-bit integers, wrapping at 2^32. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {number} a The first 32-bit integer argument to be added - * @param {number} b The second 32-bit integer argument to be added - * @return {number} The sum of a + b - */ -function safeAdd_32_2(a, b) { - var lsw = (a & 0xFFFF) + (b & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16); - - return (msw & 0xFFFF) << 16 | lsw & 0xFFFF; -} - -/** - * Add four 32-bit integers, wrapping at 2^32. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {number} a The first 32-bit integer argument to be added - * @param {number} b The second 32-bit integer argument to be added - * @param {number} c The third 32-bit integer argument to be added - * @param {number} d The fourth 32-bit integer argument to be added - * @return {number} The sum of a + b + c + d - */ -function safeAdd_32_4(a, b, c, d) { - var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (lsw >>> 16); - - return (msw & 0xFFFF) << 16 | lsw & 0xFFFF; -} - -/** - * Add five 32-bit integers, wrapping at 2^32. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {number} a The first 32-bit integer argument to be added - * @param {number} b The second 32-bit integer argument to be added - * @param {number} c The third 32-bit integer argument to be added - * @param {number} d The fourth 32-bit integer argument to be added - * @param {number} e The fifth 32-bit integer argument to be added - * @return {number} The sum of a + b + c + d + e - */ -function safeAdd_32_5(a, b, c, d, e) { - var lsw = (a & 0xFFFF) + (b & 0xFFFF) + (c & 0xFFFF) + (d & 0xFFFF) + (e & 0xFFFF), - msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (e >>> 16) + (lsw >>> 16); - - return (msw & 0xFFFF) << 16 | lsw & 0xFFFF; -} - -/** - * Add two 64-bit integers, wrapping at 2^64. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {Int_64} x The first 64-bit integer argument to be added - * @param {Int_64} y The second 64-bit integer argument to be added - * @return {Int_64} The sum of x + y - */ -function safeAdd_64_2(x, y) { - var lsw, msw, lowOrder, highOrder; - - lsw = (x.lowOrder & 0xFFFF) + (y.lowOrder & 0xFFFF); - msw = (x.lowOrder >>> 16) + (y.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - lsw = (x.highOrder & 0xFFFF) + (y.highOrder & 0xFFFF) + (msw >>> 16); - msw = (x.highOrder >>> 16) + (y.highOrder >>> 16) + (lsw >>> 16); - highOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - return new Int_64(highOrder, lowOrder); -} - -/** - * Add four 64-bit integers, wrapping at 2^64. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {Int_64} a The first 64-bit integer argument to be added - * @param {Int_64} b The second 64-bit integer argument to be added - * @param {Int_64} c The third 64-bit integer argument to be added - * @param {Int_64} d The fourth 64-bit integer argument to be added - * @return {Int_64} The sum of a + b + c + d - */ -function safeAdd_64_4(a, b, c, d) { - var lsw, msw, lowOrder, highOrder; - - lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) + (c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF); - msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) + (c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) + (msw >>> 16); - msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (lsw >>> 16); - highOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - return new Int_64(highOrder, lowOrder); -} - -/** - * Add five 64-bit integers, wrapping at 2^64. This uses 16-bit operations - * internally to work around bugs in some JS interpreters. - * - * @private - * @param {Int_64} a The first 64-bit integer argument to be added - * @param {Int_64} b The second 64-bit integer argument to be added - * @param {Int_64} c The third 64-bit integer argument to be added - * @param {Int_64} d The fourth 64-bit integer argument to be added - * @param {Int_64} e The fourth 64-bit integer argument to be added - * @return {Int_64} The sum of a + b + c + d + e - */ -function safeAdd_64_5(a, b, c, d, e) { - var lsw, msw, lowOrder, highOrder; - - lsw = (a.lowOrder & 0xFFFF) + (b.lowOrder & 0xFFFF) + (c.lowOrder & 0xFFFF) + (d.lowOrder & 0xFFFF) + (e.lowOrder & 0xFFFF); - msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (e.lowOrder >>> 16) + (lsw >>> 16); - lowOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - lsw = (a.highOrder & 0xFFFF) + (b.highOrder & 0xFFFF) + (c.highOrder & 0xFFFF) + (d.highOrder & 0xFFFF) + (e.highOrder & 0xFFFF) + (msw >>> 16); - msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (e.highOrder >>> 16) + (lsw >>> 16); - highOrder = (msw & 0xFFFF) << 16 | lsw & 0xFFFF; - - return new Int_64(highOrder, lowOrder); -} - -/** - * Calculates the SHA-1 hash of the string set at instantiation - * - * @private - * @param {Array.} message The binary array representation of the - * string to hash - * @param {number} messageLen The number of bits in the message - * @return {Array.} The array of integers representing the SHA-1 - * hash of message - */ -function coreSHA1(message, messageLen) { - var W = [], - a, - b, - c, - d, - e, - T, - ch = ch_32, - parity = parity_32, - maj = maj_32, - rotl = rotl_32, - safeAdd_2 = safeAdd_32_2, - i, - t, - safeAdd_5 = safeAdd_32_5, - appendedMessageLength, - offset, - H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - offset = (messageLen + 65 >>> 9 << 4) + 15; - while (message.length <= offset) { - message.push(0); - } - /* Append '1' at the end of the binary string */ - message[messageLen >>> 5] |= 0x80 << 24 - messageLen % 32; - /* Append length of binary string in the position such that the new - length is a multiple of 512. Logic does not work for even multiples - of 512 but there can never be even multiples of 512 */ - message[offset] = messageLen; - - appendedMessageLength = message.length; - - for (i = 0; i < appendedMessageLength; i += 16) { - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; - - for (t = 0; t < 80; t += 1) { - if (t < 16) { - W[t] = message[t + i]; - } else { - W[t] = rotl(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); - } - - if (t < 20) { - T = safeAdd_5(rotl(a, 5), ch(b, c, d), e, 0x5a827999, W[t]); - } else if (t < 40) { - T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0x6ed9eba1, W[t]); - } else if (t < 60) { - T = safeAdd_5(rotl(a, 5), maj(b, c, d), e, 0x8f1bbcdc, W[t]); - } else { - T = safeAdd_5(rotl(a, 5), parity(b, c, d), e, 0xca62c1d6, W[t]); - } - - e = d; - d = c; - c = rotl(b, 30); - b = a; - a = T; - } - - H[0] = safeAdd_2(a, H[0]); - H[1] = safeAdd_2(b, H[1]); - H[2] = safeAdd_2(c, H[2]); - H[3] = safeAdd_2(d, H[3]); - H[4] = safeAdd_2(e, H[4]); - } - - return H; -} - -/** - * Calculates the desired SHA-2 hash of the string set at instantiation - * - * @private - * @param {Array.} message The binary array representation of the - * string to hash - * @param {number} messageLen The number of bits in message - * @param {string} variant The desired SHA-2 variant - * @return {Array.} The array of integers representing the SHA-2 - * hash of message - */ -function coreSHA2(message, messageLen, variant) { - var a, - b, - c, - d, - e, - f, - g, - h, - T1, - T2, - H, - numRounds, - lengthPosition, - i, - t, - binaryStringInc, - binaryStringMult, - safeAdd_2, - safeAdd_4, - safeAdd_5, - gamma0, - gamma1, - sigma0, - sigma1, - ch, - maj, - Int, - W = [], - int1, - int2, - offset, - appendedMessageLength, - retVal, - K = [0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2], - H_trunc = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4], - H_full = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19]; - - /* Set up the various function handles and variable for the specific - * variant */ - if ((variant === "SHA-224" || variant === "SHA-256") && 2 & SUPPORTED_ALGS) { - /* 32-bit variant */ - numRounds = 64; - lengthPosition = (messageLen + 65 >>> 9 << 4) + 15; - binaryStringInc = 16; - binaryStringMult = 1; - Int = Number; - safeAdd_2 = safeAdd_32_2; - safeAdd_4 = safeAdd_32_4; - safeAdd_5 = safeAdd_32_5; - gamma0 = gamma0_32; - gamma1 = gamma1_32; - sigma0 = sigma0_32; - sigma1 = sigma1_32; - maj = maj_32; - ch = ch_32; - - if ("SHA-224" === variant) { - H = H_trunc; - } else /* "SHA-256" === variant */ - { - H = H_full; - } - } else if ((variant === "SHA-384" || variant === "SHA-512") && 4 & SUPPORTED_ALGS) { - /* 64-bit variant */ - numRounds = 80; - lengthPosition = (messageLen + 128 >>> 10 << 5) + 31; - binaryStringInc = 32; - binaryStringMult = 2; - Int = Int_64; - safeAdd_2 = safeAdd_64_2; - safeAdd_4 = safeAdd_64_4; - safeAdd_5 = safeAdd_64_5; - gamma0 = gamma0_64; - gamma1 = gamma1_64; - sigma0 = sigma0_64; - sigma1 = sigma1_64; - maj = maj_64; - ch = ch_64; - - K = [new Int(K[0], 0xd728ae22), new Int(K[1], 0x23ef65cd), new Int(K[2], 0xec4d3b2f), new Int(K[3], 0x8189dbbc), new Int(K[4], 0xf348b538), new Int(K[5], 0xb605d019), new Int(K[6], 0xaf194f9b), new Int(K[7], 0xda6d8118), new Int(K[8], 0xa3030242), new Int(K[9], 0x45706fbe), new Int(K[10], 0x4ee4b28c), new Int(K[11], 0xd5ffb4e2), new Int(K[12], 0xf27b896f), new Int(K[13], 0x3b1696b1), new Int(K[14], 0x25c71235), new Int(K[15], 0xcf692694), new Int(K[16], 0x9ef14ad2), new Int(K[17], 0x384f25e3), new Int(K[18], 0x8b8cd5b5), new Int(K[19], 0x77ac9c65), new Int(K[20], 0x592b0275), new Int(K[21], 0x6ea6e483), new Int(K[22], 0xbd41fbd4), new Int(K[23], 0x831153b5), new Int(K[24], 0xee66dfab), new Int(K[25], 0x2db43210), new Int(K[26], 0x98fb213f), new Int(K[27], 0xbeef0ee4), new Int(K[28], 0x3da88fc2), new Int(K[29], 0x930aa725), new Int(K[30], 0xe003826f), new Int(K[31], 0x0a0e6e70), new Int(K[32], 0x46d22ffc), new Int(K[33], 0x5c26c926), new Int(K[34], 0x5ac42aed), new Int(K[35], 0x9d95b3df), new Int(K[36], 0x8baf63de), new Int(K[37], 0x3c77b2a8), new Int(K[38], 0x47edaee6), new Int(K[39], 0x1482353b), new Int(K[40], 0x4cf10364), new Int(K[41], 0xbc423001), new Int(K[42], 0xd0f89791), new Int(K[43], 0x0654be30), new Int(K[44], 0xd6ef5218), new Int(K[45], 0x5565a910), new Int(K[46], 0x5771202a), new Int(K[47], 0x32bbd1b8), new Int(K[48], 0xb8d2d0c8), new Int(K[49], 0x5141ab53), new Int(K[50], 0xdf8eeb99), new Int(K[51], 0xe19b48a8), new Int(K[52], 0xc5c95a63), new Int(K[53], 0xe3418acb), new Int(K[54], 0x7763e373), new Int(K[55], 0xd6b2b8a3), new Int(K[56], 0x5defb2fc), new Int(K[57], 0x43172f60), new Int(K[58], 0xa1f0ab72), new Int(K[59], 0x1a6439ec), new Int(K[60], 0x23631e28), new Int(K[61], 0xde82bde9), new Int(K[62], 0xb2c67915), new Int(K[63], 0xe372532b), new Int(0xca273ece, 0xea26619c), new Int(0xd186b8c7, 0x21c0c207), new Int(0xeada7dd6, 0xcde0eb1e), new Int(0xf57d4f7f, 0xee6ed178), new Int(0x06f067aa, 0x72176fba), new Int(0x0a637dc5, 0xa2c898a6), new Int(0x113f9804, 0xbef90dae), new Int(0x1b710b35, 0x131c471b), new Int(0x28db77f5, 0x23047d84), new Int(0x32caab7b, 0x40c72493), new Int(0x3c9ebe0a, 0x15c9bebc), new Int(0x431d67c4, 0x9c100d4c), new Int(0x4cc5d4be, 0xcb3e42b6), new Int(0x597f299c, 0xfc657e2a), new Int(0x5fcb6fab, 0x3ad6faec), new Int(0x6c44198c, 0x4a475817)]; - - if ("SHA-384" === variant) { - H = [new Int(0xcbbb9d5d, H_trunc[0]), new Int(0x0629a292a, H_trunc[1]), new Int(0x9159015a, H_trunc[2]), new Int(0x0152fecd8, H_trunc[3]), new Int(0x67332667, H_trunc[4]), new Int(0x98eb44a87, H_trunc[5]), new Int(0xdb0c2e0d, H_trunc[6]), new Int(0x047b5481d, H_trunc[7])]; - } else /* "SHA-512" === variant */ - { - H = [new Int(H_full[0], 0xf3bcc908), new Int(H_full[1], 0x84caa73b), new Int(H_full[2], 0xfe94f82b), new Int(H_full[3], 0x5f1d36f1), new Int(H_full[4], 0xade682d1), new Int(H_full[5], 0x2b3e6c1f), new Int(H_full[6], 0xfb41bd6b), new Int(H_full[7], 0x137e2179)]; - } - } else { - throw "Unexpected error in SHA-2 implementation"; - } - - while (message.length <= lengthPosition) { - message.push(0); - } - /* Append '1' at the end of the binary string */ - message[messageLen >>> 5] |= 0x80 << 24 - messageLen % 32; - /* Append length of binary string in the position such that the new - * length is correct */ - message[lengthPosition] = messageLen; - - appendedMessageLength = message.length; - - for (i = 0; i < appendedMessageLength; i += binaryStringInc) { - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; - f = H[5]; - g = H[6]; - h = H[7]; - - for (t = 0; t < numRounds; t += 1) { - if (t < 16) { - offset = t * binaryStringMult + i; - int1 = message.length <= offset ? 0 : message[offset]; - int2 = message.length <= offset + 1 ? 0 : message[offset + 1]; - /* Bit of a hack - for 32-bit, the second term is ignored */ - W[t] = new Int(int1, int2); - } else { - W[t] = safeAdd_4(gamma1(W[t - 2]), W[t - 7], gamma0(W[t - 15]), W[t - 16]); - } - - T1 = safeAdd_5(h, sigma1(e), ch(e, f, g), K[t], W[t]); - T2 = safeAdd_2(sigma0(a), maj(a, b, c)); - h = g; - g = f; - f = e; - e = safeAdd_2(d, T1); - d = c; - c = b; - b = a; - a = safeAdd_2(T1, T2); - } - - H[0] = safeAdd_2(a, H[0]); - H[1] = safeAdd_2(b, H[1]); - H[2] = safeAdd_2(c, H[2]); - H[3] = safeAdd_2(d, H[3]); - H[4] = safeAdd_2(e, H[4]); - H[5] = safeAdd_2(f, H[5]); - H[6] = safeAdd_2(g, H[6]); - H[7] = safeAdd_2(h, H[7]); - } - - if ("SHA-224" === variant && 2 & SUPPORTED_ALGS) { - retVal = [H[0], H[1], H[2], H[3], H[4], H[5], H[6]]; - } else if ("SHA-256" === variant && 2 & SUPPORTED_ALGS) { - retVal = H; - } else if ("SHA-384" === variant && 4 & SUPPORTED_ALGS) { - retVal = [H[0].highOrder, H[0].lowOrder, H[1].highOrder, H[1].lowOrder, H[2].highOrder, H[2].lowOrder, H[3].highOrder, H[3].lowOrder, H[4].highOrder, H[4].lowOrder, H[5].highOrder, H[5].lowOrder]; - } else if ("SHA-512" === variant && 4 & SUPPORTED_ALGS) { - retVal = [H[0].highOrder, H[0].lowOrder, H[1].highOrder, H[1].lowOrder, H[2].highOrder, H[2].lowOrder, H[3].highOrder, H[3].lowOrder, H[4].highOrder, H[4].lowOrder, H[5].highOrder, H[5].lowOrder, H[6].highOrder, H[6].lowOrder, H[7].highOrder, H[7].lowOrder]; - } else /* This should never be reached */ - { - throw "Unexpected error in SHA-2 implementation"; - } - - return retVal; -} - -/** - * jsSHA is the workhorse of the library. Instantiate it with the string to - * be hashed as the parameter - * - * @constructor - * @this {jsSHA} - * @param {string} srcString The string to be hashed - * @param {string} inputFormat The format of srcString, HEX, ASCII, TEXT, - * B64, or BYTES - * @param {string=} encoding The text encoding to use to encode the source - * string - */ -var jsSHA = function jsSHA(srcString, inputFormat, encoding) { - var strBinLen = 0, - strToHash = [0], - utfType = '', - srcConvertRet = null; - - utfType = encoding || "UTF8"; - - if (!("UTF8" === utfType || "UTF16BE" === utfType || "UTF16LE" === utfType)) { - throw "encoding must be UTF8, UTF16BE, or UTF16LE"; - } - - /* Convert the input string into the correct type */ - if ("HEX" === inputFormat) { - if (0 !== srcString.length % 2) { - throw "srcString of HEX type must be in byte increments"; - } - srcConvertRet = hex2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } else if ("TEXT" === inputFormat || "ASCII" === inputFormat) { - srcConvertRet = str2binb(srcString, utfType); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } else if ("B64" === inputFormat) { - srcConvertRet = b642binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } else if ("BYTES" === inputFormat) { - srcConvertRet = bytes2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } else if ("TYPED" === inputFormat) { - srcConvertRet = typed2binb(srcString); - strBinLen = srcConvertRet["binLen"]; - strToHash = srcConvertRet["value"]; - } else { - throw "inputFormat must be HEX, TEXT, ASCII, B64, BYTES, or TYPED"; - } - - /** - * Returns the desired SHA hash of the string specified at instantiation - * using the specified parameters - * - * @expose - * @param {string} variant The desired SHA variant (SHA-1, SHA-224, - * SHA-256, SHA-384, or SHA-512) - * @param {string} format The desired output formatting (B64, HEX, or BYTES) - * @param {number=} numRounds The number of rounds of hashing to be - * executed - * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts - * Hash list of output formatting options - * @return {string} The string representation of the hash in the format - * specified - */ - this.getHash = function (variant, format, numRounds, outputFormatOpts) { - var formatFunc = null, - message = strToHash.slice(), - messageBinLen = strBinLen, - i; - - /* Need to do argument patching since both numRounds and - outputFormatOpts are optional */ - if (3 === arguments.length) { - if ("number" !== typeof numRounds) { - outputFormatOpts = numRounds; - numRounds = 1; - } - } else if (2 === arguments.length) { - numRounds = 1; - } - - /* Validate the numRounds argument */ - if (numRounds !== parseInt(numRounds, 10) || 1 > numRounds) { - throw "numRounds must a integer >= 1"; - } - - /* Validate the output format selection */ - switch (format) { - case "HEX": - formatFunc = binb2hex; - break; - case "B64": - formatFunc = binb2b64; - break; - case "BYTES": - formatFunc = binb2bytes; - break; - case "TYPED": - formatFunc = binb2typed; - break; - default: - throw "format must be HEX, B64, or BYTES"; - } - - if ("SHA-1" === variant && 1 & SUPPORTED_ALGS) { - for (i = 0; i < numRounds; i += 1) { - message = coreSHA1(message, messageBinLen); - messageBinLen = 160; - } - } else if ("SHA-224" === variant && 2 & SUPPORTED_ALGS) { - for (i = 0; i < numRounds; i += 1) { - message = coreSHA2(message, messageBinLen, variant); - messageBinLen = 224; - } - } else if ("SHA-256" === variant && 2 & SUPPORTED_ALGS) { - for (i = 0; i < numRounds; i += 1) { - message = coreSHA2(message, messageBinLen, variant); - messageBinLen = 256; - } - } else if ("SHA-384" === variant && 4 & SUPPORTED_ALGS) { - for (i = 0; i < numRounds; i += 1) { - message = coreSHA2(message, messageBinLen, variant); - messageBinLen = 384; - } - } else if ("SHA-512" === variant && 4 & SUPPORTED_ALGS) { - for (i = 0; i < numRounds; i += 1) { - message = coreSHA2(message, messageBinLen, variant); - messageBinLen = 512; - } - } else { - throw "Chosen SHA variant is not supported"; - } - - return formatFunc(message, getOutputOpts(outputFormatOpts)); - }; - - /** - * Returns the desired HMAC of the string specified at instantiation - * using the key and variant parameter - * - * @expose - * @param {string} key The key used to calculate the HMAC - * @param {string} inputFormat The format of key, HEX, TEXT, ASCII, - * B64, or BYTES - * @param {string} variant The desired SHA variant (SHA-1, SHA-224, - * SHA-256, SHA-384, or SHA-512) - * @param {string} outputFormat The desired output formatting - * (B64, HEX, or BYTES) - * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts - * associative array of output formatting options - * @return {string} The string representation of the hash in the format - * specified - */ - this.getHMAC = function (key, inputFormat, variant, outputFormat, outputFormatOpts) { - var formatFunc, - keyToUse, - blockByteSize, - blockBitSize, - i, - retVal, - lastArrayIndex, - keyBinLen, - hashBitSize, - keyWithIPad = [], - keyWithOPad = [], - keyConvertRet = null; - - /* Validate the output format selection */ - switch (outputFormat) { - case "HEX": - formatFunc = binb2hex; - break; - case "B64": - formatFunc = binb2b64; - break; - case "BYTES": - formatFunc = binb2bytes; - break; - default: - throw "outputFormat must be HEX, B64, or BYTES"; - } - - /* Validate the hash variant selection and set needed variables */ - if ("SHA-1" === variant && 1 & SUPPORTED_ALGS) { - blockByteSize = 64; - hashBitSize = 160; - } else if ("SHA-224" === variant && 2 & SUPPORTED_ALGS) { - blockByteSize = 64; - hashBitSize = 224; - } else if ("SHA-256" === variant && 2 & SUPPORTED_ALGS) { - blockByteSize = 64; - hashBitSize = 256; - } else if ("SHA-384" === variant && 4 & SUPPORTED_ALGS) { - blockByteSize = 128; - hashBitSize = 384; - } else if ("SHA-512" === variant && 4 & SUPPORTED_ALGS) { - blockByteSize = 128; - hashBitSize = 512; - } else { - throw "Chosen SHA variant is not supported"; - } - - /* Validate input format selection */ - if ("HEX" === inputFormat) { - keyConvertRet = hex2binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } else if ("TEXT" === inputFormat || "ASCII" === inputFormat) { - keyConvertRet = str2binb(key, utfType); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } else if ("B64" === inputFormat) { - keyConvertRet = b642binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } else if ("BYTES" === inputFormat) { - keyConvertRet = bytes2binb(key); - keyBinLen = keyConvertRet["binLen"]; - keyToUse = keyConvertRet["value"]; - } else { - throw "inputFormat must be HEX, TEXT, ASCII, B64, or BYTES"; - } - - /* These are used multiple times, calculate and store them */ - blockBitSize = blockByteSize * 8; - lastArrayIndex = blockByteSize / 4 - 1; - - /* Figure out what to do with the key based on its size relative to - * the hash's block size */ - if (blockByteSize < keyBinLen / 8) { - if ("SHA-1" === variant && 1 & SUPPORTED_ALGS) { - keyToUse = coreSHA1(keyToUse, keyBinLen); - } else if (6 & SUPPORTED_ALGS) { - keyToUse = coreSHA2(keyToUse, keyBinLen, variant); - } else { - throw "Unexpected error in HMAC implementation"; - } - /* For all variants, the block size is bigger than the output - * size so there will never be a useful byte at the end of the - * string */ - while (keyToUse.length <= lastArrayIndex) { - keyToUse.push(0); - } - keyToUse[lastArrayIndex] &= 0xFFFFFF00; - } else if (blockByteSize > keyBinLen / 8) { - /* If the blockByteSize is greater than the key length, there - * will always be at LEAST one "useless" byte at the end of the - * string */ - while (keyToUse.length <= lastArrayIndex) { - keyToUse.push(0); - } - keyToUse[lastArrayIndex] &= 0xFFFFFF00; - } - - /* Create ipad and opad */ - for (i = 0; i <= lastArrayIndex; i += 1) { - keyWithIPad[i] = keyToUse[i] ^ 0x36363636; - keyWithOPad[i] = keyToUse[i] ^ 0x5C5C5C5C; - } - - /* Calculate the HMAC */ - if ("SHA-1" === variant && 1 & SUPPORTED_ALGS) { - retVal = coreSHA1(keyWithOPad.concat(coreSHA1(keyWithIPad.concat(strToHash), blockBitSize + strBinLen)), blockBitSize + hashBitSize); - } else if (6 & SUPPORTED_ALGS) { - retVal = coreSHA2(keyWithOPad.concat(coreSHA2(keyWithIPad.concat(strToHash), blockBitSize + strBinLen, variant)), blockBitSize + hashBitSize, variant); - } else { - throw "Unexpected error in HMAC implementation"; - } - - return formatFunc(retVal, getOutputOpts(outputFormatOpts)); - }; -}; - -exports.default = { - /** SHA1 hash */ - sha1: function sha1(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); - return shaObj.getHash("SHA-1", "TYPED"); - }, - /** SHA224 hash */ - sha224: function sha224(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); - return shaObj.getHash("SHA-224", "TYPED"); - }, - /** SHA256 hash */ - sha256: function sha256(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); - return shaObj.getHash("SHA-256", "TYPED"); - }, - /** SHA384 hash */ - sha384: function sha384(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); - return shaObj.getHash("SHA-384", "TYPED"); - }, - /** SHA512 hash */ - sha512: function sha512(str) { - var shaObj = new jsSHA(str, "TYPED", "UTF8"); - return shaObj.getHash("SHA-512", "TYPED"); - } -}; - -},{}],24:[function(_dereq_,module,exports){ -/** - * @see module:crypto/crypto - * @module crypto - */ +exports.default = md5; +},{"../../util":376}],319:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -9560,7 +30562,7 @@ var _cfb2 = _interopRequireDefault(_cfb); var _gcm = _dereq_('./gcm'); -var gcm = _interopRequireWildcard(_gcm); +var _gcm2 = _interopRequireDefault(_gcm); var _public_key = _dereq_('./public_key'); @@ -9578,14 +30580,21 @@ var _pkcs = _dereq_('./pkcs1'); var _pkcs2 = _interopRequireDefault(_pkcs); -var _crypto = _dereq_('./crypto.js'); +var _pkcs3 = _dereq_('./pkcs5'); + +var _pkcs4 = _interopRequireDefault(_pkcs3); + +var _crypto = _dereq_('./crypto'); var _crypto2 = _interopRequireDefault(_crypto); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _aes_kw = _dereq_('./aes_kw'); + +var _aes_kw2 = _interopRequireDefault(_aes_kw); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// TODO move cfb and gcm to cipher var mod = { /** @see module:crypto/cipher */ cipher: _cipher2.default, @@ -9594,7 +30603,7 @@ var mod = { /** @see module:crypto/cfb */ cfb: _cfb2.default, /** @see module:crypto/gcm */ - gcm: gcm, + gcm: _gcm2.default, /** @see module:crypto/public_key */ publicKey: _public_key2.default, /** @see module:crypto/signature */ @@ -9602,8 +30611,21 @@ var mod = { /** @see module:crypto/random */ random: _random2.default, /** @see module:crypto/pkcs1 */ - pkcs1: _pkcs2.default -}; + pkcs1: _pkcs2.default, + /** @see module:crypto/pkcs5 */ + pkcs5: _pkcs4.default, + /** @see module:crypto/aes_kw */ + aes_kw: _aes_kw2.default +}; /** + * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + * @module crypto + */ for (var i in _crypto2.default) { mod[i] = _crypto2.default[i]; @@ -9611,8 +30633,91 @@ for (var i in _crypto2.default) { exports.default = mod; -},{"./cfb":11,"./cipher":16,"./crypto.js":18,"./gcm":19,"./hash":20,"./pkcs1":25,"./public_key":28,"./random":31,"./signature":32}],25:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +},{"./aes_kw":307,"./cfb":308,"./cipher":313,"./crypto":315,"./gcm":316,"./hash":317,"./pkcs1":320,"./pkcs5":321,"./public_key":330,"./random":333,"./signature":334}],320:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Create padding with secure random data + * @private + * @param {Integer} length Length of the padding in bytes + * @returns {String} Padding as string + * @async + */ +var getPkcs1Padding = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(length) { + var result, randomBytes, i; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + result = ''; + + case 1: + if (!(result.length < length)) { + _context.next = 8; + break; + } + + _context.next = 4; + return _random2.default.getRandomBytes(length - result.length); + + case 4: + randomBytes = _context.sent; + + for (i = 0; i < randomBytes.length; i++) { + if (randomBytes[i] !== 0) { + result += String.fromCharCode(randomBytes[i]); + } + } + _context.next = 1; + break; + + case 8: + return _context.abrupt('return', result); + + case 9: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function getPkcs1Padding(_x) { + return _ref.apply(this, arguments); + }; +}(); + +var _random = _dereq_('./random'); + +var _random2 = _interopRequireDefault(_random); + +var _hash = _dereq_('./hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * ASN1 object identifiers for hashes (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}) + */ +var hash_headers = []; // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -9631,97 +30736,73 @@ exports.default = mod; /** * PKCS1 encoding - * @requires crypto/crypto - * @requires crypto/hash - * @requires crypto/public_key/jsbn * @requires crypto/random + * @requires crypto/hash * @requires util * @module crypto/pkcs1 */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _random = _dereq_('./random.js'); - -var _random2 = _interopRequireDefault(_random); - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _jsbn = _dereq_('./public_key/jsbn.js'); - -var _jsbn2 = _interopRequireDefault(_jsbn); - -var _hash = _dereq_('./hash'); - -var _hash2 = _interopRequireDefault(_hash); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * ASN1 object identifiers for hashes (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}) - */ -var hash_headers = []; hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10]; hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14]; hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20]; hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30]; hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40]; -hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C]; - -/** - * Create padding with secure random data - * @private - * @param {Integer} length Length of the padding in bytes - * @return {String} Padding as string - */ -function getPkcs1Padding(length) { - var result = ''; - var randomByte; - while (result.length < length) { - randomByte = _random2.default.getSecureRandomOctet(); - if (randomByte !== 0) { - result += String.fromCharCode(randomByte); - } - } - return result; -} - -exports.default = { +hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C];exports.default = { eme: { /** * create a EME-PKCS1-v1_5 padding (See {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}) * @param {String} M message to be encoded * @param {Integer} k the length in octets of the key modulus - * @return {String} EME-PKCS1 padded message + * @returns {Promise} EME-PKCS1 padded message + * @async */ - encode: function encode(M, k) { - var mLen = M.length; - // length checking - if (mLen > k - 11) { - throw new Error('Message too long'); + encode: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(M, k) { + var mLen, PS; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + mLen = M.length; + // length checking + + if (!(mLen > k - 11)) { + _context2.next = 3; + break; + } + + throw new Error('Message too long'); + + case 3: + _context2.next = 5; + return getPkcs1Padding(k - mLen - 3); + + case 5: + PS = _context2.sent; + return _context2.abrupt('return', String.fromCharCode(0) + String.fromCharCode(2) + PS + String.fromCharCode(0) + M); + + case 7: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function encode(_x2, _x3) { + return _ref2.apply(this, arguments); } - // Generate an octet string PS of length k - mLen - 3 consisting of - // pseudo-randomly generated nonzero octets - var PS = getPkcs1Padding(k - mLen - 3); - // Concatenate PS, the message M, and other padding to form an - // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M. - var EM = String.fromCharCode(0) + String.fromCharCode(2) + PS + String.fromCharCode(0) + M; - return EM; - }, + + return encode; + }(), /** * decodes a EME-PKCS1-v1_5 padding (See {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}) * @param {String} EM encoded message, an octet string - * @return {String} message, an octet string + * @returns {String} message, an octet string */ decode: function decode(EM) { - // leading zeros truncated by jsbn + // leading zeros truncated by bn.js if (EM.charCodeAt(0) !== 0) { EM = String.fromCharCode(0) + EM; } @@ -9735,9 +30816,8 @@ exports.default = { var separator = EM.charCodeAt(i++); if (firstOct === 0 && secondOct === 2 && psLen >= 8 && separator === 0) { return EM.substr(i); - } else { - throw new Error('Decryption error'); } + throw new Error('Decryption error'); } }, @@ -9750,9 +30830,9 @@ exports.default = { * @returns {String} encoded message */ encode: function encode(algo, M, emLen) { - var i; + var i = void 0; // Apply the hash function to the message M to produce a hash value H - var H = _util2.default.Uint8Array2str(_hash2.default.digest(algo, _util2.default.str2Uint8Array(M))); + var H = _util2.default.Uint8Array_to_str(_hash2.default.digest(algo, _util2.default.str_to_Uint8Array(M))); if (H.length !== _hash2.default.getHashByteLength(algo)) { throw new Error('Invalid hash length'); } @@ -9778,13 +30858,107 @@ exports.default = { // Concatenate PS, the hash prefix T, and other padding to form the // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || T. var EM = String.fromCharCode(0x00) + String.fromCharCode(0x01) + PS + String.fromCharCode(0x00) + T; - return new _jsbn2.default(_util2.default.hexstrdump(EM), 16); + return _util2.default.str_to_hex(EM); } } }; -},{"../util.js":70,"./hash":20,"./public_key/jsbn.js":29,"./random.js":31}],26:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +},{"../util":376,"./hash":317,"./random":333,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],321:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +// Functions to add and remove PKCS5 padding + +/** + * Add pkcs5 padding to a text. + * @param {String} msg Text to add padding + * @returns {String} Text with padding added + */ +function encode(msg) { + var c = 8 - msg.length % 8; + var padding = String.fromCharCode(c).repeat(c); + return msg + padding; +} + +/** + * Remove pkcs5 padding from a string. + * @param {String} msg Text to remove padding from + * @returns {String} Text with padding removed + */ +function decode(msg) { + var len = msg.length; + if (len > 0) { + var c = msg.charCodeAt(len - 1); + if (c >= 1 && c <= 8) { + var provided = msg.substr(len - c); + var computed = String.fromCharCode(c).repeat(c); + if (provided === computed) { + return msg.substr(0, len - c); + } + } + } + throw new Error('Invalid padding'); +} + +exports.default = { encode: encode, decode: decode }; + +},{}],322:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _hash = _dereq_('../hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _random = _dereq_('../random'); + +var _random2 = _interopRequireDefault(_random); + +var _config = _dereq_('../../config'); + +var _config2 = _interopRequireDefault(_config); + +var _util = _dereq_('../../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var one = new _bn2.default(1); // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -9804,129 +30978,212 @@ exports.default = { // A Digital signature algorithm implementation /** + * @requires bn.js * @requires crypto/hash - * @requires crypto/public_key/jsbn * @requires crypto/random + * @requires config * @requires util * @module crypto/public_key/dsa */ +var zero = new _bn2.default(0); + +/* + TODO regarding the hash function, read: + https://tools.ietf.org/html/rfc4880#section-13.6 + https://tools.ietf.org/html/rfc4880#section-14 +*/ + +exports.default = { + /** + * DSA Sign function + * @param {Integer} hash_algo + * @param {String} m + * @param {BN} g + * @param {BN} p + * @param {BN} q + * @param {BN} x + * @returns {{ r: BN, s: BN }} + * @async + */ + sign: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(hash_algo, m, g, p, q, x) { + var k, r, s, t, redp, redq, gred, xred, h; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + k = void 0; + r = void 0; + s = void 0; + t = void 0; + redp = new _bn2.default.red(p); + redq = new _bn2.default.red(q); + gred = g.toRed(redp); + xred = x.toRed(redq); + // If the output size of the chosen hash is larger than the number of + // bits of q, the hash result is truncated to fit by taking the number + // of leftmost bits equal to the number of bits of q. This (possibly + // truncated) hash function result is treated as a number and used + // directly in the DSA signature algorithm. + + h = new _bn2.default(_util2.default.str_to_Uint8Array(_util2.default.getLeftNBits(_util2.default.Uint8Array_to_str(_hash2.default.digest(hash_algo, m)), q.bitLength()))); + // FIPS-186-4, section 4.6: + // The values of r and s shall be checked to determine if r = 0 or s = 0. + // If either r = 0 or s = 0, a new value of k shall be generated, and the + // signature shall be recalculated. It is extremely unlikely that r = 0 + // or s = 0 if signatures are generated properly. + + case 9: + if (!true) { + _context.next = 23; + break; + } + + _context.next = 12; + return _random2.default.getRandomBN(one, q); + + case 12: + k = _context.sent; + // returns in [1, q-1] + r = gred.redPow(k).fromRed().toRed(redq); // (g**k mod p) mod q + + if (!(zero.cmp(r) === 0)) { + _context.next = 16; + break; + } + + return _context.abrupt('continue', 9); + + case 16: + t = h.add(x.mul(r)).toRed(redq); // H(m) + x*r mod q + s = k.toRed(redq).redInvm().redMul(t); // k**-1 * (H(m) + x*r) mod q + + if (!(zero.cmp(s) === 0)) { + _context.next = 20; + break; + } + + return _context.abrupt('continue', 9); + + case 20: + return _context.abrupt('break', 23); + + case 23: + return _context.abrupt('return', { r: r.toArrayLike(Uint8Array), + s: s.toArrayLike(Uint8Array) }); + + case 24: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + function sign(_x, _x2, _x3, _x4, _x5, _x6) { + return _ref.apply(this, arguments); + } + + return sign; + }(), + + /** + * DSA Verify function + * @param {Integer} hash_algo + * @param {BN} r + * @param {BN} s + * @param {String} m + * @param {BN} g + * @param {BN} p + * @param {BN} q + * @param {BN} y + * @returns BN + * @async + */ + verify: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(hash_algo, r, s, m, g, p, q, y) { + var redp, redq, h, w, u1, u2, t1, t2, v; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(zero.ucmp(r) >= 0 || r.ucmp(q) >= 0 || zero.ucmp(s) >= 0 || s.ucmp(q) >= 0)) { + _context2.next = 3; + break; + } + + _util2.default.print_debug("invalid DSA Signature"); + return _context2.abrupt('return', null); + + case 3: + redp = new _bn2.default.red(p); + redq = new _bn2.default.red(q); + h = new _bn2.default(_util2.default.str_to_Uint8Array(_util2.default.getLeftNBits(_util2.default.Uint8Array_to_str(_hash2.default.digest(hash_algo, m)), q.bitLength()))); + w = s.toRed(redq).redInvm(); // s**-1 mod q + + if (!(zero.cmp(w) === 0)) { + _context2.next = 10; + break; + } + + _util2.default.print_debug("invalid DSA Signature"); + return _context2.abrupt('return', null); + + case 10: + u1 = h.toRed(redq).redMul(w); // H(m) * w mod q + + u2 = r.toRed(redq).redMul(w); // r * w mod q + + t1 = g.toRed(redp).redPow(u1.fromRed()); // g**u1 mod p + + t2 = y.toRed(redp).redPow(u2.fromRed()); // y**u2 mod p + + v = t1.redMul(t2).fromRed().mod(q); // (g**u1 * y**u2 mod p) mod q + + return _context2.abrupt('return', v.cmp(r) === 0); + + case 16: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function verify(_x7, _x8, _x9, _x10, _x11, _x12, _x13, _x14) { + return _ref2.apply(this, arguments); + } + + return verify; + }() +}; + +},{"../../config":306,"../../util":376,"../hash":317,"../random":333,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],323:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = DSA; -var _jsbn = _dereq_('./jsbn.js'); +var _regenerator = _dereq_('babel-runtime/regenerator'); -var _jsbn2 = _interopRequireDefault(_jsbn); +var _regenerator2 = _interopRequireDefault(_regenerator); -var _random = _dereq_('../random.js'); +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _random = _dereq_('../random'); var _random2 = _interopRequireDefault(_random); -var _hash = _dereq_('../hash'); - -var _hash2 = _interopRequireDefault(_hash); - -var _util = _dereq_('../../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _config = _dereq_('../../config'); - -var _config2 = _interopRequireDefault(_config); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function DSA() { - // s1 = ((g**s) mod p) mod q - // s1 = ((s**-1)*(sha-1(m)+(s1*x) mod q) - function sign(hashalgo, m, g, p, q, x) { - // If the output size of the chosen hash is larger than the number of - // bits of q, the hash result is truncated to fit by taking the number - // of leftmost bits equal to the number of bits of q. This (possibly - // truncated) hash function result is treated as a number and used - // directly in the DSA signature algorithm. - var hashed_data = _util2.default.getLeftNBits(_util2.default.Uint8Array2str(_hash2.default.digest(hashalgo, _util2.default.str2Uint8Array(m))), q.bitLength()); - var hash = new _jsbn2.default(_util2.default.hexstrdump(hashed_data), 16); - // FIPS-186-4, section 4.6: - // The values of r and s shall be checked to determine if r = 0 or s = 0. - // If either r = 0 or s = 0, a new value of k shall be generated, and the - // signature shall be recalculated. It is extremely unlikely that r = 0 - // or s = 0 if signatures are generated properly. - var k, s1, s2; - while (true) { - k = _random2.default.getRandomBigIntegerInRange(_jsbn2.default.ONE, q.subtract(_jsbn2.default.ONE)); - s1 = g.modPow(k, p).mod(q); - s2 = k.modInverse(q).multiply(hash.add(x.multiply(s1))).mod(q); - if (s1 !== 0 && s2 !== 0) { - break; - } - } - var result = []; - result[0] = s1.toMPI(); - result[1] = s2.toMPI(); - return result; - } - - function select_hash_algorithm(q) { - var usersetting = _config2.default.prefer_hash_algorithm; - /* - * 1024-bit key, 160-bit q, SHA-1, SHA-224, SHA-256, SHA-384, or SHA-512 hash - * 2048-bit key, 224-bit q, SHA-224, SHA-256, SHA-384, or SHA-512 hash - * 2048-bit key, 256-bit q, SHA-256, SHA-384, or SHA-512 hash - * 3072-bit key, 256-bit q, SHA-256, SHA-384, or SHA-512 hash - */ - switch (Math.round(q.bitLength() / 8)) { - case 20: - // 1024 bit - if (usersetting !== 2 && usersetting > 11 && usersetting !== 10 && usersetting < 8) { - return 2; // prefer sha1 - } - return usersetting; - case 28: - // 2048 bit - if (usersetting > 11 && usersetting < 8) { - return 11; - } - return usersetting; - case 32: - // 4096 bit // prefer sha224 - if (usersetting > 10 && usersetting < 8) { - return 8; // prefer sha256 - } - return usersetting; - default: - _util2.default.print_debug("DSA select hash algorithm: returning null for an unknown length of q"); - return null; - } - } - this.select_hash_algorithm = select_hash_algorithm; - - function verify(hashalgo, s1, s2, m, p, q, g, y) { - var hashed_data = _util2.default.getLeftNBits(_util2.default.Uint8Array2str(_hash2.default.digest(hashalgo, _util2.default.str2Uint8Array(m))), q.bitLength()); - var hash = new _jsbn2.default(_util2.default.hexstrdump(hashed_data), 16); - if (_jsbn2.default.ZERO.compareTo(s1) >= 0 || s1.compareTo(q) >= 0 || _jsbn2.default.ZERO.compareTo(s2) >= 0 || s2.compareTo(q) >= 0) { - _util2.default.print_debug("invalid DSA Signature"); - return null; - } - var w = s2.modInverse(q); - if (_jsbn2.default.ZERO.compareTo(w) === 0) { - _util2.default.print_debug("invalid DSA Signature"); - return null; - } - var u1 = hash.multiply(w).mod(q); - var u2 = s1.multiply(w).mod(q); - return g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q); - } - - this.sign = sign; - this.verify = verify; -} - -},{"../../config":10,"../../util.js":70,"../hash":20,"../random.js":31,"./jsbn.js":29}],27:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -9947,1784 +31204,1903 @@ function DSA() { // ElGamal implementation /** - * @requires crypto/public_key/jsbn + * @requires bn.js * @requires crypto/random - * @requires util * @module crypto/public_key/elgamal */ +var zero = new _bn2.default(0); + +exports.default = { + /** + * ElGamal Encryption function + * @param {BN} m + * @param {BN} p + * @param {BN} g + * @param {BN} y + * @returns {{ c1: BN, c2: BN }} + * @async + */ + encrypt: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(m, p, g, y) { + var redp, mred, gred, yred, k; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + redp = new _bn2.default.red(p); + mred = m.toRed(redp); + gred = g.toRed(redp); + yred = y.toRed(redp); + // See Section 11.5 here: https://crypto.stanford.edu/~dabo/cryptobook/BonehShoup_0_4.pdf + + _context.next = 6; + return _random2.default.getRandomBN(zero, p); + + case 6: + k = _context.sent; + return _context.abrupt('return', { + c1: gred.redPow(k).fromRed(), + c2: yred.redPow(k).redMul(mred).fromRed() + }); + + case 8: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + function encrypt(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + } + + return encrypt; + }(), + + /** + * ElGamal Encryption function + * @param {BN} c1 + * @param {BN} c2 + * @param {BN} p + * @param {BN} x + * @returns BN + * @async + */ + decrypt: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(c1, c2, p, x) { + var redp, c1red, c2red; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + redp = new _bn2.default.red(p); + c1red = c1.toRed(redp); + c2red = c2.toRed(redp); + return _context2.abrupt('return', c1red.redPow(x).redInvm().redMul(c2red).fromRed()); + + case 4: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function decrypt(_x5, _x6, _x7, _x8) { + return _ref2.apply(this, arguments); + } + + return decrypt; + }() +}; + +},{"../random":333,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],324:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Elgamal; +exports.getPreferredHashAlgo = exports.generate = exports.nodeCurves = exports.webCurves = exports.curves = undefined; -var _jsbn = _dereq_('./jsbn.js'); +var _regenerator = _dereq_('babel-runtime/regenerator'); -var _jsbn2 = _interopRequireDefault(_jsbn); +var _regenerator2 = _interopRequireDefault(_regenerator); -var _random = _dereq_('../random.js'); +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var generate = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(curve) { + var keyPair; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + curve = new Curve(curve); + _context2.next = 3; + return curve.genKeyPair(); + + case 3: + keyPair = _context2.sent; + return _context2.abrupt('return', { + oid: curve.oid, + Q: new _bn2.default(keyPair.getPublic()), + d: new _bn2.default(keyPair.getPrivate()), + hash: curve.hash, + cipher: curve.cipher + }); + + case 5: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function generate(_x) { + return _ref2.apply(this, arguments); + }; +}(); + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + + +var webGenKeyPair = function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(name) { + var webCryptoKey, privateKey, publicKey; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return webCrypto.generateKey({ name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"]); + + case 2: + webCryptoKey = _context3.sent; + _context3.next = 5; + return webCrypto.exportKey("jwk", webCryptoKey.privateKey); + + case 5: + privateKey = _context3.sent; + _context3.next = 8; + return webCrypto.exportKey("jwk", webCryptoKey.publicKey); + + case 8: + publicKey = _context3.sent; + return _context3.abrupt('return', { + pub: { + x: _util2.default.b64_to_Uint8Array(publicKey.x, true), + y: _util2.default.b64_to_Uint8Array(publicKey.y, true) + }, + priv: _util2.default.b64_to_Uint8Array(privateKey.d, true) + }); + + case 10: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function webGenKeyPair(_x2) { + return _ref3.apply(this, arguments); + }; +}(); + +var nodeGenKeyPair = function () { + var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(name) { + var ecdh; + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + // Note: ECDSA and ECDH key generation is structurally equivalent + ecdh = nodeCrypto.createECDH(nodeCurves[name]); + _context4.next = 3; + return ecdh.generateKeys(); + + case 3: + return _context4.abrupt('return', { + pub: ecdh.getPublicKey().toJSON().data, + priv: ecdh.getPrivateKey().toJSON().data + }); + + case 4: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function nodeGenKeyPair(_x3) { + return _ref4.apply(this, arguments); + }; +}(); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _elliptic = _dereq_('elliptic'); + +var _key = _dereq_('./key'); + +var _key2 = _interopRequireDefault(_key); + +var _random = _dereq_('../../random'); var _random2 = _interopRequireDefault(_random); -var _util = _dereq_('../../util.js'); +var _enums = _dereq_('../../../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../../../util'); + +var _util2 = _interopRequireDefault(_util); + +var _oid = _dereq_('../../../type/oid'); + +var _oid2 = _interopRequireDefault(_oid); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Wrapper of an instance of an Elliptic Curve + * @requires bn.js + * @requires elliptic + * @requires crypto/public_key/elliptic/key + * @requires crypto/random + * @requires enums + * @requires util + * @requires type/oid + * @module crypto/public_key/elliptic/curve + */ + +var nodeCrypto = _util2.default.getNodeCrypto(); + +var nodeCurves = {}; +var webCurves = { + 'p256': 'P-256', + 'p384': 'P-384', + 'p521': 'P-521' +}; +if (nodeCrypto) { + var knownCurves = nodeCrypto.getCurves(); + nodeCurves.secp256k1 = knownCurves.includes('secp256k1') ? 'secp256k1' : undefined; + nodeCurves.p256 = knownCurves.includes('prime256v1') ? 'prime256v1' : undefined; + nodeCurves.p384 = knownCurves.includes('secp384r1') ? 'secp384r1' : undefined; + nodeCurves.p521 = knownCurves.includes('secp521r1') ? 'secp521r1' : undefined; + // TODO add more here +} + +var curves = { + p256: { + oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], + keyType: _enums2.default.publicKey.ecdsa, + hash: _enums2.default.hash.sha256, + cipher: _enums2.default.symmetric.aes128, + node: nodeCurves.p256, + web: webCurves.p256, + payloadSize: 32 + }, + p384: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], + keyType: _enums2.default.publicKey.ecdsa, + hash: _enums2.default.hash.sha384, + cipher: _enums2.default.symmetric.aes192, + node: nodeCurves.p384, + web: webCurves.p384, + payloadSize: 48 + }, + p521: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], + keyType: _enums2.default.publicKey.ecdsa, + hash: _enums2.default.hash.sha512, + cipher: _enums2.default.symmetric.aes256, + node: nodeCurves.p521, + web: webCurves.p521, + payloadSize: 66 + }, + secp256k1: { + oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], + keyType: _enums2.default.publicKey.ecdsa, + hash: _enums2.default.hash.sha256, + cipher: _enums2.default.symmetric.aes128, + node: nodeCurves.secp256k1 + }, + ed25519: { + oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], + keyType: _enums2.default.publicKey.eddsa, + hash: _enums2.default.hash.sha512, + payloadSize: 32 + }, + curve25519: { + oid: [0x06, 0x08, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], + keyType: _enums2.default.publicKey.ecdsa, + hash: _enums2.default.hash.sha256, + cipher: _enums2.default.symmetric.aes128 + }, + brainpoolP256r1: { // TODO 1.3.36.3.3.2.8.1.1.7 + oid: [0x06, 0x07, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07] + }, + brainpoolP384r1: { // TODO 1.3.36.3.3.2.8.1.1.11 + oid: [0x06, 0x07, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B] + }, + brainpoolP512r1: { // TODO 1.3.36.3.3.2.8.1.1.13 + oid: [0x06, 0x07, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D] + } +}; + +/** + * @constructor + */ +function Curve(oid_or_name, params) { + try { + if (_util2.default.isArray(oid_or_name) || _util2.default.isUint8Array(oid_or_name)) { + // by oid byte array + oid_or_name = new _oid2.default(oid_or_name); + } + if (oid_or_name instanceof _oid2.default) { + // by curve OID + oid_or_name = oid_or_name.getName(); + } + // by curve name or oid string + this.name = _enums2.default.write(_enums2.default.curve, oid_or_name); + } catch (err) { + throw new Error('Not valid curve'); + } + params = params || curves[this.name]; + + this.keyType = params.keyType; + switch (this.keyType) { + case _enums2.default.publicKey.ecdsa: + this.curve = new _elliptic.ec(this.name); + break; + case _enums2.default.publicKey.eddsa: + this.curve = new _elliptic.eddsa(this.name); + break; + default: + throw new Error('Unknown elliptic key type;'); + } + + this.oid = params.oid; + this.hash = params.hash; + this.cipher = params.cipher; + this.node = params.node && curves[this.name]; + this.web = params.web && curves[this.name]; + this.payloadSize = params.payloadSize; +} + +Curve.prototype.keyFromPrivate = function (priv) { + // Not for ed25519 + return new _key2.default(this, { priv: priv }); +}; + +Curve.prototype.keyFromSecret = function (secret) { + // Only for ed25519 + return new _key2.default(this, { secret: secret }); +}; + +Curve.prototype.keyFromPublic = function (pub) { + return new _key2.default(this, { pub: pub }); +}; + +Curve.prototype.genKeyPair = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() { + var keyPair, r, compact; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + keyPair = void 0; + + if (!(webCrypto && this.web)) { + _context.next = 13; + break; + } + + _context.prev = 2; + _context.next = 5; + return webGenKeyPair(this.name); + + case 5: + keyPair = _context.sent; + _context.next = 11; + break; + + case 8: + _context.prev = 8; + _context.t0 = _context['catch'](2); + + _util2.default.print_debug("Browser did not support signing: " + _context.t0.message); + + case 11: + _context.next = 17; + break; + + case 13: + if (!(nodeCrypto && this.node)) { + _context.next = 17; + break; + } + + _context.next = 16; + return nodeGenKeyPair(this.name); + + case 16: + keyPair = _context.sent; + + case 17: + if (!(!keyPair || !keyPair.priv)) { + _context.next = 30; + break; + } + + _context.t1 = this.curve; + _context.t2 = _util2.default; + _context.next = 22; + return _random2.default.getRandomBytes(32); + + case 22: + _context.t3 = _context.sent; + _context.t4 = _context.t2.Uint8Array_to_str.call(_context.t2, _context.t3); + _context.t5 = { + entropy: _context.t4 + }; + _context.next = 27; + return _context.t1.genKeyPair.call(_context.t1, _context.t5); + + case 27: + r = _context.sent; + compact = this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont'; + + if (this.keyType === _enums2.default.publicKey.eddsa) { + keyPair = { secret: r.getSecret() }; + } else { + keyPair = { pub: r.getPublic('array', compact), priv: r.getPrivate().toArray() }; + } + + case 30: + return _context.abrupt('return', new _key2.default(this, keyPair)); + + case 31: + case 'end': + return _context.stop(); + } + } + }, _callee, this, [[2, 8]]); +})); + +function getPreferredHashAlgo(oid) { + return curves[_enums2.default.write(_enums2.default.curve, oid.toHex())].hash; +} + +exports.default = Curve; +exports.curves = curves; +exports.webCurves = webCurves; +exports.nodeCurves = nodeCurves; +exports.generate = generate; +exports.getPreferredHashAlgo = getPreferredHashAlgo; + +},{"../../../enums":337,"../../../type/oid":374,"../../../util":376,"../../random":333,"./key":329,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37,"elliptic":249}],325:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Encrypt and wrap a session key + * + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {Enums} cipher_algo Symmetric cipher to use + * @param {Enums} hash_algo Hash algorithm to use + * @param {module:type/mpi} m Value derived from session key (RFC 6637) + * @param {Uint8Array} Q Recipient public key + * @param {String} fingerprint Recipient fingerprint + * @returns {{V: BN, C: BN}} Returns ephemeral key and encoded session key + * @async + */ +var encrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(oid, cipher_algo, hash_algo, m, Q, fingerprint) { + var curve, param, v, S, Z, C; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + fingerprint = _util2.default.hex_to_Uint8Array(fingerprint); + curve = new _curves2.default(oid); + param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); + + cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo); + _context.next = 6; + return curve.genKeyPair(); + + case 6: + v = _context.sent; + + Q = curve.keyFromPublic(Q); + S = v.derive(Q); + Z = kdf(hash_algo, S, _cipher2.default[cipher_algo].keySize, param); + C = _aes_kw2.default.wrap(Z, m.toString()); + return _context.abrupt('return', { + V: new _bn2.default(v.getPublic()), + C: C + }); + + case 12: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function encrypt(_x, _x2, _x3, _x4, _x5, _x6) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Decrypt and unwrap the value derived from session key + * + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {Enums} cipher_algo Symmetric cipher to use + * @param {Enums} hash_algo Hash algorithm to use + * @param {BN} V Public part of ephemeral key + * @param {Uint8Array} C Encrypted and wrapped value derived from session key + * @param {Uint8Array} d Recipient private key + * @param {String} fingerprint Recipient fingerprint + * @returns {Uint8Array} Value derived from session + * @async + */ + + +var decrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(oid, cipher_algo, hash_algo, V, C, d, fingerprint) { + var curve, param, S, Z; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + fingerprint = _util2.default.hex_to_Uint8Array(fingerprint); + curve = new _curves2.default(oid); + param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); + + cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo); + V = curve.keyFromPublic(V); + d = curve.keyFromPrivate(d); + S = d.derive(V); + Z = kdf(hash_algo, S, _cipher2.default[cipher_algo].keySize, param); + return _context2.abrupt('return', new _bn2.default(_aes_kw2.default.unwrap(Z, C))); + + case 9: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function decrypt(_x7, _x8, _x9, _x10, _x11, _x12, _x13) { + return _ref2.apply(this, arguments); + }; +}(); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _curves = _dereq_('./curves'); + +var _curves2 = _interopRequireDefault(_curves); + +var _aes_kw = _dereq_('../../aes_kw'); + +var _aes_kw2 = _interopRequireDefault(_aes_kw); + +var _cipher = _dereq_('../../cipher'); + +var _cipher2 = _interopRequireDefault(_cipher); + +var _hash = _dereq_('../../hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _kdf_params = _dereq_('../../../type/kdf_params'); + +var _kdf_params2 = _interopRequireDefault(_kdf_params); + +var _oid = _dereq_('../../../type/oid'); + +var _oid2 = _interopRequireDefault(_oid); + +var _enums = _dereq_('../../../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../../../util'); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function Elgamal() { - - function encrypt(m, g, p, y) { - // choose k in {2,...,p-2} - var pMinus2 = p.subtract(_jsbn2.default.TWO); - var k = _random2.default.getRandomBigIntegerInRange(_jsbn2.default.ONE, pMinus2); - k = k.mod(pMinus2).add(_jsbn2.default.ONE); - var c = []; - c[0] = g.modPow(k, p); - c[1] = y.modPow(k, p).multiply(m).mod(p); - return c; - } - - function decrypt(c1, c2, p, x) { - _util2.default.print_debug("Elgamal Decrypt:\nc1:" + _util2.default.hexstrdump(c1.toMPI()) + "\n" + "c2:" + _util2.default.hexstrdump(c2.toMPI()) + "\n" + "p:" + _util2.default.hexstrdump(p.toMPI()) + "\n" + "x:" + _util2.default.hexstrdump(x.toMPI())); - return c1.modPow(x, p).modInverse(p).multiply(c2).mod(p); - //var c = c1.pow(x).modInverse(p); // c0^-a mod p - //return c.multiply(c2).mod(p); - } - - // signing and signature verification using Elgamal is not required by OpenPGP. - this.encrypt = encrypt; - this.decrypt = decrypt; +// Build Param for ECDH algorithm (RFC 6637) +function buildEcdhParam(public_algo, oid, cipher_algo, hash_algo, fingerprint) { + var kdf_params = new _kdf_params2.default([hash_algo, cipher_algo]); + return _util2.default.concatUint8Array([oid.write(), new Uint8Array([public_algo]), kdf_params.write(), _util2.default.str_to_Uint8Array("Anonymous Sender "), fingerprint]); } -},{"../../util.js":70,"../random.js":31,"./jsbn.js":29}],28:[function(_dereq_,module,exports){ +// Key Derivation Function (RFC 6637) +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + /** - * @requires crypto/public_key/dsa - * @requires crypto/public_key/elgamal - * @requires crypto/public_key/rsa - * @module crypto/public_key + * @fileoverview Key encryption and decryption for RFC 6637 ECDH + * @requires crypto/public_key/elliptic/curves + * @requires crypto/aes_kw + * @requires crypto/cipher + * @requires crypto/hash + * @requires type/oid + * @requires type/kdf_params + * @requires enums + * @requires util + * @module crypto/public_key/elliptic/ecdh */ -'use strict'; +function kdf(hash_algo, X, length, param) { + return _hash2.default.digest(hash_algo, _util2.default.concatUint8Array([new Uint8Array([0, 0, 0, 1]), new Uint8Array(X), param])).subarray(0, length); +}exports.default = { encrypt: encrypt, decrypt: decrypt }; -/** @see module:crypto/public_key/rsa */ +},{"../../../enums":337,"../../../type/kdf_params":371,"../../../type/oid":374,"../../../util":376,"../../aes_kw":307,"../../cipher":313,"../../hash":317,"./curves":324,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],326:[function(_dereq_,module,exports){ +'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -var _rsa = _dereq_('./rsa.js'); +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Sign a message using the provided key + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {enums.hash} hash_algo Hash algorithm used to sign + * @param {Uint8Array} m Message to sign + * @param {Uint8Array} d Private key used to sign the message + * @returns {{r: Uint8Array, + * s: Uint8Array}} Signature of the message + * @async + */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs + * @requires crypto/hash + * @requires crypto/public_key/elliptic/curves + * @module crypto/public_key/elliptic/ecdsa + */ + +var sign = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(oid, hash_algo, m, d) { + var curve, key, signature; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + curve = new _curves2.default(oid); + key = curve.keyFromPrivate(d); + _context.next = 4; + return key.sign(m, hash_algo); + + case 4: + signature = _context.sent; + return _context.abrupt('return', { r: signature.r.toArrayLike(Uint8Array), + s: signature.s.toArrayLike(Uint8Array) }); + + case 6: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function sign(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {enums.hash} hash_algo Hash algorithm used in the signature + * @param {{r: Uint8Array, + s: Uint8Array}} signature Signature to verify + * @param {Uint8Array} m Message to verify + * @param {Uint8Array} Q Public key used to verify the message + * @returns {Boolean} + * @async + */ + + +var verify = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(oid, hash_algo, signature, m, Q) { + var curve, key; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + curve = new _curves2.default(oid); + key = curve.keyFromPublic(Q); + return _context2.abrupt('return', key.verify(m, signature, hash_algo)); + + case 3: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function verify(_x5, _x6, _x7, _x8, _x9) { + return _ref2.apply(this, arguments); + }; +}(); + +var _hash = _dereq_('../../hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _curves = _dereq_('./curves'); + +var _curves2 = _interopRequireDefault(_curves); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { sign: sign, verify: verify }; + +},{"../../hash":317,"./curves":324,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],327:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Sign a message using the provided key + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {enums.hash} hash_algo Hash algorithm used to sign + * @param {Uint8Array} m Message to sign + * @param {Uint8Array} d Private key used to sign + * @returns {{R: Uint8Array, + * S: Uint8Array}} Signature of the message + * @async + */ +var sign = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(oid, hash_algo, m, d) { + var curve, key, signature; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + curve = new _curves2.default(oid); + key = curve.keyFromSecret(d); + _context.next = 4; + return key.sign(m, hash_algo); + + case 4: + signature = _context.sent; + return _context.abrupt('return', { R: new Uint8Array(signature.Rencoded()), + S: new Uint8Array(signature.Sencoded()) }); + + case 6: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function sign(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Verifies if a signature is valid for a message + * @param {module:type/oid} oid Elliptic curve object identifier + * @param {enums.hash} hash_algo Hash algorithm used in the signature + * @param {{R: Uint8Array, + S: Uint8Array}} signature Signature to verify the message + * @param {Uint8Array} m Message to verify + * @param {Uint8Array} Q Public key used to verify the message + * @returns {Boolean} + * @async + */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP + * @requires bn.js + * @requires crypto/hash + * @requires crypto/public_key/elliptic/curves + * @module crypto/public_key/elliptic/eddsa + */ + +var verify = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(oid, hash_algo, signature, m, Q) { + var curve, key; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + curve = new _curves2.default(oid); + key = curve.keyFromPublic(Q); + return _context2.abrupt('return', key.verify(m, signature, hash_algo)); + + case 3: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function verify(_x5, _x6, _x7, _x8, _x9) { + return _ref2.apply(this, arguments); + }; +}(); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _hash = _dereq_('../../hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _curves = _dereq_('./curves'); + +var _curves2 = _interopRequireDefault(_curves); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { sign: sign, verify: verify }; + +},{"../../hash":317,"./curves":324,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],328:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _curves = _dereq_('./curves'); + +var _curves2 = _interopRequireDefault(_curves); + +var _ecdsa = _dereq_('./ecdsa'); + +var _ecdsa2 = _interopRequireDefault(_ecdsa); + +var _eddsa = _dereq_('./eddsa'); + +var _eddsa2 = _interopRequireDefault(_eddsa); + +var _ecdh = _dereq_('./ecdh'); + +var _ecdh2 = _interopRequireDefault(_ecdh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Functions to access Elliptic Curve Cryptography + * @see module:crypto/public_key/elliptic/curve + * @see module:crypto/public_key/elliptic/ecdh + * @see module:crypto/public_key/elliptic/ecdsa + * @see module:crypto/public_key/elliptic/eddsa + * @module crypto/public_key/elliptic + */ + +exports.default = { + Curve: _curves2.default, ecdh: _ecdh2.default, ecdsa: _ecdsa2.default, eddsa: _eddsa2.default, generate: _curves.generate, getPreferredHashAlgo: _curves.getPreferredHashAlgo +}; + +},{"./curves":324,"./ecdh":325,"./ecdsa":326,"./eddsa":327}],329:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +////////////////////////// +// // +// Helper functions // +// // +////////////////////////// + + +var webSign = function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(curve, hash_algo, message, keyPair) { + var len, key, signature; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + len = curve.payloadSize; + _context3.next = 3; + return webCrypto.importKey("jwk", { + "kty": "EC", + "crv": _curves.webCurves[curve.name], + "x": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray('be', len)), true), + "y": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray('be', len)), true), + "d": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray('be', len)), true), + "use": "sig", + "kid": "ECDSA Private Key" + }, { + "name": "ECDSA", + "namedCurve": _curves.webCurves[curve.name], + "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) } + }, false, ["sign"]); + + case 3: + key = _context3.sent; + _context3.t0 = Uint8Array; + _context3.next = 7; + return webCrypto.sign({ + "name": 'ECDSA', + "namedCurve": _curves.webCurves[curve.name], + "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) } + }, key, message); + + case 7: + _context3.t1 = _context3.sent; + signature = new _context3.t0(_context3.t1); + return _context3.abrupt('return', { + r: new _bn2.default(signature.slice(0, len)), + s: new _bn2.default(signature.slice(len, len << 1)) + }); + + case 10: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function webSign(_x6, _x7, _x8, _x9) { + return _ref3.apply(this, arguments); + }; +}(); + +var webVerify = function () { + var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(curve, hash_algo, _ref5, message, publicKey) { + var r = _ref5.r, + s = _ref5.s; + var len, key, signature; + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + len = curve.payloadSize; + _context4.next = 3; + return webCrypto.importKey("jwk", { + "kty": "EC", + "crv": _curves.webCurves[curve.name], + "x": _util2.default.Uint8Array_to_b64(new Uint8Array(publicKey.getX().toArray('be', len)), true), + "y": _util2.default.Uint8Array_to_b64(new Uint8Array(publicKey.getY().toArray('be', len)), true), + "use": "sig", + "kid": "ECDSA Public Key" + }, { + "name": "ECDSA", + "namedCurve": _curves.webCurves[curve.name], + "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) } + }, false, ["verify"]); + + case 3: + key = _context4.sent; + signature = _util2.default.concatUint8Array([new Uint8Array(len - r.length), r, new Uint8Array(len - s.length), s]).buffer; + return _context4.abrupt('return', webCrypto.verify({ + "name": 'ECDSA', + "namedCurve": _curves.webCurves[curve.name], + "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) } + }, key, signature, message)); + + case 6: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function webVerify(_x10, _x11, _x12, _x13, _x14) { + return _ref4.apply(this, arguments); + }; +}(); + +var nodeSign = function () { + var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(curve, hash_algo, message, keyPair) { + var sign, key; + return _regenerator2.default.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + sign = nodeCrypto.createSign(_enums2.default.read(_enums2.default.hash, hash_algo)); + + sign.write(message); + sign.end(); + + key = ECPrivateKey.encode({ + version: 1, + parameters: curve.oid, + privateKey: keyPair.getPrivate().toArray(), + publicKey: { unused: 0, data: keyPair.getPublic().encode() } + }, 'pem', { + label: 'EC PRIVATE KEY' + }); + return _context5.abrupt('return', ECDSASignature.decode(sign.sign(key), 'der')); + + case 5: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this); + })); + + return function nodeSign(_x15, _x16, _x17, _x18) { + return _ref6.apply(this, arguments); + }; +}(); + +var nodeVerify = function () { + var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(curve, hash_algo, _ref8, message, publicKey) { + var r = _ref8.r, + s = _ref8.s; + var verify, key, signature; + return _regenerator2.default.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + verify = nodeCrypto.createVerify(_enums2.default.read(_enums2.default.hash, hash_algo)); + + verify.write(message); + verify.end(); + + key = SubjectPublicKeyInfo.encode({ + algorithm: { + algorithm: [1, 2, 840, 10045, 2, 1], + parameters: curve.oid + }, + subjectPublicKey: { unused: 0, data: publicKey.encode() } + }, 'pem', { + label: 'PUBLIC KEY' + }); + signature = ECDSASignature.encode({ + r: new _bn2.default(r), s: new _bn2.default(s) + }, 'der'); + _context6.prev = 5; + return _context6.abrupt('return', verify.verify(key, signature)); + + case 9: + _context6.prev = 9; + _context6.t0 = _context6['catch'](5); + return _context6.abrupt('return', false); + + case 12: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this, [[5, 9]]); + })); + + return function nodeVerify(_x19, _x20, _x21, _x22, _x23) { + return _ref7.apply(this, arguments); + }; +}(); + +// Originally written by Owen Smith https://github.com/omsmith +// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/ + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _curves = _dereq_('./curves'); + +var _hash = _dereq_('../../hash'); + +var _hash2 = _interopRequireDefault(_hash); + +var _util = _dereq_('../../../util'); + +var _util2 = _interopRequireDefault(_util); + +var _enums = _dereq_('../../../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Wrapper for a KeyPair of an Elliptic Curve + * @requires bn.js + * @requires crypto/public_key/elliptic/curves + * @requires crypto/hash + * @requires util + * @requires enums + * @requires asn1.js + * @module crypto/public_key/elliptic/key + */ + +var nodeCrypto = _util2.default.getNodeCrypto(); + +/** + * @constructor + */ +function KeyPair(curve, options) { + this.curve = curve; + this.keyType = curve.curve.type === 'edwards' ? _enums2.default.publicKey.eddsa : _enums2.default.publicKey.ecdsa; + this.keyPair = this.curve.curve.keyPair(options); +} + +KeyPair.prototype.sign = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(message, hash_algo) { + var signature, digest; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(webCrypto && this.curve.web)) { + _context.next = 13; + break; + } + + _context.prev = 1; + _context.next = 4; + return webSign(this.curve, hash_algo, message, this.keyPair); + + case 4: + signature = _context.sent; + return _context.abrupt('return', signature); + + case 8: + _context.prev = 8; + _context.t0 = _context['catch'](1); + + _util2.default.print_debug("Browser did not support signing: " + _context.t0.message); + + case 11: + _context.next = 15; + break; + + case 13: + if (!(nodeCrypto && this.curve.node)) { + _context.next = 15; + break; + } + + return _context.abrupt('return', nodeSign(this.curve, hash_algo, message, this.keyPair)); + + case 15: + digest = typeof hash_algo === 'undefined' ? message : _hash2.default.digest(hash_algo, message); + return _context.abrupt('return', this.keyPair.sign(digest)); + + case 17: + case 'end': + return _context.stop(); + } + } + }, _callee, this, [[1, 8]]); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; +}(); + +KeyPair.prototype.verify = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(message, signature, hash_algo) { + var result, digest; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(webCrypto && this.curve.web)) { + _context2.next = 13; + break; + } + + _context2.prev = 1; + _context2.next = 4; + return webVerify(this.curve, hash_algo, signature, message, this.keyPair.getPublic()); + + case 4: + result = _context2.sent; + return _context2.abrupt('return', result); + + case 8: + _context2.prev = 8; + _context2.t0 = _context2['catch'](1); + + _util2.default.print_debug("Browser did not support signing: " + _context2.t0.message); + + case 11: + _context2.next = 15; + break; + + case 13: + if (!(nodeCrypto && this.curve.node)) { + _context2.next = 15; + break; + } + + return _context2.abrupt('return', nodeVerify(this.curve, hash_algo, signature, message, this.keyPair.getPublic())); + + case 15: + digest = typeof hash_algo === 'undefined' ? message : _hash2.default.digest(hash_algo, message); + return _context2.abrupt('return', this.keyPair.verify(digest, signature)); + + case 17: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[1, 8]]); + })); + + return function (_x3, _x4, _x5) { + return _ref2.apply(this, arguments); + }; +}(); + +KeyPair.prototype.derive = function (pub) { + if (this.keyType === _enums2.default.publicKey.eddsa) { + throw new Error('Key can only be used for EdDSA'); + } + return this.keyPair.derive(pub.keyPair.getPublic()); +}; + +KeyPair.prototype.getPublic = function () { + var compact = this.curve.curve.curve.type === 'edwards' || this.curve.curve.curve.type === 'mont'; + return this.keyPair.getPublic('array', compact); +}; + +KeyPair.prototype.getPrivate = function () { + if (this.curve.keyType === _enums2.default.publicKey.eddsa) { + return this.keyPair.getSecret(); + } + return this.keyPair.getPrivate().toArray(); +}; + +exports.default = KeyPair; +var asn1 = nodeCrypto ? _dereq_('asn1.js') : undefined; + +var ECDSASignature = nodeCrypto ? asn1.define('ECDSASignature', function () { + this.seq().obj(this.key('r').int(), this.key('s').int()); +}) : undefined; + +var ECPrivateKey = nodeCrypto ? asn1.define('ECPrivateKey', function () { + this.seq().obj(this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').explicit(0).optional().any(), this.key('publicKey').explicit(1).optional().bitstr()); +}) : undefined; + +var AlgorithmIdentifier = nodeCrypto ? asn1.define('AlgorithmIdentifier', function () { + this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional().any()); +}) : undefined; + +var SubjectPublicKeyInfo = nodeCrypto ? asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr()); +}) : undefined; + +},{"../../../enums":337,"../../../util":376,"../../hash":317,"./curves":324,"asn1.js":"asn1.js","babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],330:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _rsa = _dereq_('./rsa'); var _rsa2 = _interopRequireDefault(_rsa); -var _elgamal = _dereq_('./elgamal.js'); +var _elgamal = _dereq_('./elgamal'); var _elgamal2 = _interopRequireDefault(_elgamal); -var _dsa = _dereq_('./dsa.js'); +var _elliptic = _dereq_('./elliptic'); + +var _elliptic2 = _interopRequireDefault(_elliptic); + +var _dsa = _dereq_('./dsa'); var _dsa2 = _interopRequireDefault(_dsa); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** @see module:crypto/public_key/elgamal */ +/** @see module:crypto/public_key/elliptic */ +/** + * @fileoverview Asymmetric cryptography functions + * @see module:crypto/public_key/dsa + * @see module:crypto/public_key/elgamal + * @see module:crypto/public_key/elliptic + * @see module:crypto/public_key/rsa + * @module crypto/public_key + */ + +/** @see module:crypto/public_key/rsa */ exports.default = { rsa: _rsa2.default, elgamal: _elgamal2.default, + elliptic: _elliptic2.default, dsa: _dsa2.default }; /** @see module:crypto/public_key/dsa */ -},{"./dsa.js":26,"./elgamal.js":27,"./rsa.js":30}],29:[function(_dereq_,module,exports){ -"use strict"; +/** @see module:crypto/public_key/elgamal */ + +},{"./dsa":322,"./elgamal":323,"./elliptic":328,"./rsa":332}],331:[function(_dereq_,module,exports){ +'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = BigInteger; -var _util = _dereq_("../../util.js"); +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Probabilistic random number generator + * @param {Integer} bits Bit length of the prime + * @param {BN} e Optional RSA exponent to check against the prime + * @param {Integer} k Optional number of iterations of Miller-Rabin test + * @returns BN + * @async + */ +var randomProbablePrime = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(bits, e, k) { + var min, thirty, adds, n, i; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + min = new _bn2.default(1).shln(bits - 1); + thirty = new _bn2.default(30); + /* + * We can avoid any multiples of 3 and 5 by looking at n mod 30 + * 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 + * the next possible prime is mod 30: + * 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 + */ + + 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]; + _context.next = 5; + return _random2.default.getRandomBN(min, min.shln(1)); + + case 5: + n = _context.sent; + i = n.mod(thirty).toNumber(); + + case 7: + n.iaddn(adds[i]); + i = (i + adds[i]) % adds.length; + // If reached the maximum, go back to the minimum. + if (n.bitLength() > bits) { + n = n.mod(min.shln(1)).iadd(min); + i = n.mod(thirty).toNumber(); + } + // eslint-disable-next-line no-await-in-loop + + case 10: + _context.next = 12; + return isProbablePrime(n, e, k); + + case 12: + if (!_context.sent) { + _context.next = 7; + break; + } + + case 13: + return _context.abrupt('return', n); + + case 14: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function randomProbablePrime(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Probabilistic primality testing + * @param {BN} n Number to test + * @param {BN} e Optional RSA exponent to check against the prime + * @param {Integer} k Optional number of iterations of Miller-Rabin test + * @returns {boolean} + * @async + */ + + +var isProbablePrime = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(n, e, k) { + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(e && !n.subn(1).gcd(e).eqn(1))) { + _context2.next = 2; + break; + } + + return _context2.abrupt('return', false); + + case 2: + if (divisionTest(n)) { + _context2.next = 4; + break; + } + + return _context2.abrupt('return', false); + + case 4: + if (fermat(n)) { + _context2.next = 6; + break; + } + + return _context2.abrupt('return', false); + + case 6: + _context2.next = 8; + return millerRabin(n, k); + + case 8: + if (_context2.sent) { + _context2.next = 10; + break; + } + + return _context2.abrupt('return', false); + + case 10: + return _context2.abrupt('return', true); + + case 11: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function isProbablePrime(_x4, _x5, _x6) { + return _ref2.apply(this, arguments); + }; +}(); + +/** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n === 1. + * @param {BN} n Number to test + * @param {Integer} b Optional Fermat test base + * @returns {boolean} + */ + + +// Miller-Rabin - Miller Rabin algorithm for primality test +// Copyright Fedor Indutny, 2014. +// +// This software is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin + +// Sample syntax for Fixed-Base Miller-Rabin: +// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0])) + +/** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param {BN} n Number to test + * @param {Integer} k Optional number of iterations of Miller-Rabin test + * @param {Function} rand Optional function to generate potential witnesses + * @returns {boolean} + * @async + */ +var millerRabin = function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(n, k, rand) { + var len, red, rone, n1, rn1, s, d, a, x, i; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + len = n.bitLength(); + red = _bn2.default.mont(n); + rone = new _bn2.default(1).toRed(red); + + + if (!k) { + k = Math.max(1, len / 48 | 0); + } + + n1 = n.subn(1); + rn1 = n1.toRed(red); + + // Find d and s, (n - 1) = (2 ^ s) * d; + + s = 0; + + while (!n1.testn(s)) { + s++; + } + d = n.shrn(s); + + case 9: + if (!(k > 0)) { + _context3.next = 37; + break; + } + + if (!rand) { + _context3.next = 14; + break; + } + + _context3.t0 = rand(); + _context3.next = 17; + break; + + case 14: + _context3.next = 16; + return _random2.default.getRandomBN(new _bn2.default(2), n1); + + case 16: + _context3.t0 = _context3.sent; + + case 17: + a = _context3.t0; + x = a.toRed(red).redPow(d); + + if (!(x.eq(rone) || x.eq(rn1))) { + _context3.next = 21; + break; + } + + return _context3.abrupt('continue', 34); + + case 21: + i = void 0; + i = 1; + + case 23: + if (!(i < s)) { + _context3.next = 32; + break; + } + + x = x.redSqr(); + + if (!x.eq(rone)) { + _context3.next = 27; + break; + } + + return _context3.abrupt('return', false); + + case 27: + if (!x.eq(rn1)) { + _context3.next = 29; + break; + } + + return _context3.abrupt('break', 32); + + case 29: + i++; + _context3.next = 23; + break; + + case 32: + if (!(i === s)) { + _context3.next = 34; + break; + } + + return _context3.abrupt('return', false); + + case 34: + k--; + _context3.next = 9; + break; + + case 37: + return _context3.abrupt('return', true); + + case 38: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function millerRabin(_x7, _x8, _x9) { + return _ref3.apply(this, arguments); + }; +}(); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _random = _dereq_('../random'); + +var _random2 = _interopRequireDefault(_random); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2018 Proton Technologies AG +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview Algorithms for probabilistic random prime generation + * @requires bn.js + * @requires crypto/random + * @module crypto/public_key/prime + */ + +exports.default = { + randomProbablePrime: randomProbablePrime, isProbablePrime: isProbablePrime, fermat: fermat, millerRabin: millerRabin, divisionTest: divisionTest +}; +function fermat(n, b) { + b = b || new _bn2.default(2); + return b.toRed(_bn2.default.mont(n)).redPow(n.subn(1)).fromRed().cmpn(1) === 0; +} + +function divisionTest(n) { + return small_primes.every(function (m) { + return n.modn(m) !== 0; + }); +} + +// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c +var small_primes = [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999]; + +},{"../random":333,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],332:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _prime = _dereq_('./prime'); + +var _prime2 = _interopRequireDefault(_prime); + +var _random = _dereq_('../random'); + +var _random2 = _interopRequireDefault(_random); + +var _config = _dereq_('../../config'); + +var _config2 = _interopRequireDefault(_config); + +var _util = _dereq_('../../util'); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// Basic JavaScript BN library - subset useful for RSA encryption. - -// Bits per digit -var dbits; - -// JavaScript engine analysis -/* - * Copyright (c) 2003-2005 Tom Wu (tjw@cs.Stanford.EDU) - * All Rights Reserved. - * - * Modified by Recurity Labs GmbH - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, - * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY - * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, - * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF - * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT - * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * In addition, the following condition applies: - * - * All redistributions must retain an intact copy of this copyright notice - * and disclaimer. - */ - -/** - * @requires util - * @module crypto/public_key/jsbn - */ - -var canary = 0xdeadbeefcafe; -var j_lm = (canary & 0xffffff) == 0xefcafe; - -// (public) Constructor - -function BigInteger(a, b, c) { - if (a != null) if ("number" == typeof a) this.fromNumber(a, b, c);else if (b == null && "string" != typeof a) this.fromString(a, 256);else this.fromString(a, b); -} - -// return new, unset BigInteger - -function nbi() { - return new BigInteger(null); -} - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) - -function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c; - c = Math.floor(v / 0x4000000); - w[j++] = v & 0x3ffffff; +// Helper for IE11 KeyOperation objects +function promisifyIE11Op(keyObj, err) { + if (typeof keyObj.then !== 'function') { + // IE11 KeyOperation + return new _promise2.default(function (resolve, reject) { + keyObj.onerror = function () { + reject(new Error(err)); + }; + keyObj.oncomplete = function (e) { + resolve(e.target.result); + }; + }); } - return c; -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - -function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15; - while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w[j++] = l & 0x3fffffff; - } - return c; -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. - -function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14; - while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w[j++] = l & 0xfffffff; - } - return c; -} -/*if(j_lm && (navigator != undefined && - navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; -} -else if(j_lm && (navigator != undefined && navigator.appName != "Netscape")) {*/ -BigInteger.prototype.am = am1; -dbits = 26; -/*} -else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; -}*/ - -BigInteger.prototype.DB = dbits; -BigInteger.prototype.DM = (1 << dbits) - 1; -BigInteger.prototype.DV = 1 << dbits; - -var BI_FP = 52; -BigInteger.prototype.FV = Math.pow(2, BI_FP); -BigInteger.prototype.F1 = BI_FP - dbits; -BigInteger.prototype.F2 = 2 * dbits - BI_FP; - -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; -var BI_RC = new Array(); -var rr, vv; -rr = "0".charCodeAt(0); -for (vv = 0; vv <= 9; ++vv) { - BI_RC[rr++] = vv; -}rr = "a".charCodeAt(0); -for (vv = 10; vv < 36; ++vv) { - BI_RC[rr++] = vv; -}rr = "A".charCodeAt(0); -for (vv = 10; vv < 36; ++vv) { - BI_RC[rr++] = vv; -}function int2char(n) { - return BI_RM.charAt(n); -} - -function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; -} - -// (protected) copy this to r - -function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) { - r[i] = this[i]; - }r.t = this.t; - r.s = this.s; -} - -// (protected) set from integer value x, -DV <= x < DV - -function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0; -} - -// return bigint initialized to value - -function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; -} - -// (protected) set from string and radix - -function bnpFromString(s, b) { - var k; - if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, - mi = false, - sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 0xff : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) { - this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; - this[this.t++] = x >> this.DB - sh; - } else this[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 0x80) != 0) { - this.s = -1; - if (sh > 0) this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); -} - -// (protected) clamp off excess high words - -function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this[this.t - 1] == c) { - --this.t; - } -} - -// (public) return string representation in given radix - -function bnToString(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else return this.toRadix(b); - var km = (1 << k) - 1, - d, - m = false, - r = "", - i = this.t; - var p = this.DB - i * this.DB % k; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this[i] & (1 << p) - 1) << k - p; - d |= this[--i] >> (p += this.DB - k); - } else { - d = this[i] >> (p -= k) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : "0"; -} - -// (public) -this - -function bnNegate() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; -} - -// (public) |this| - -function bnAbs() { - return this.s < 0 ? this.negate() : this; -} - -// (public) return + if this > a, - if this < a, 0 if equal - -function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) { - if ((r = this[i] - a[i]) != 0) return r; - }return 0; -} - -// returns bit length of the integer x - -function nbits(x) { - var r = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; -} - -// (public) return the number of bits in "this" - -function bnBitLength() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); -} - -// (protected) r = this << n*DB - -function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) { - r[i + n] = this[i]; - }for (i = n - 1; i >= 0; --i) { - r[i] = 0; - }r.t = this.t + n; - r.s = this.s; -} - -// (protected) r = this >> n*DB - -function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) { - r[i - n] = this[i]; - }r.t = Math.max(this.t - n, 0); - r.s = this.s; -} - -// (protected) r = this << n - -function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), - c = this.s << bs & this.DM, - i; - for (i = this.t - 1; i >= 0; --i) { - r[i + ds + 1] = this[i] >> cbs | c; - c = (this[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) { - r[i] = 0; - }r[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); -} - -// (protected) r = this >> n - -function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r[i - ds - 1] |= (this[i] & bm) << cbs; - r[i - ds] = this[i] >> bs; - } - if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); -} - -// (protected) r = this - a - -function bnpSubTo(a, r) { - var i = 0, - c = 0, - m = Math.min(a.t, this.t); - while (i < m) { - c += this[i] - a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c; - r.t = i; - r.clamp(); -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. - -function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) { - r[i] = 0; - }for (i = 0; i < y.t; ++i) { - r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); - }r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); -} - -// (protected) r = this^2, r != this (HAC 14.16) - -function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) { - r[i] = 0; - }for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV; - r[i + x.t + 1] = 1; - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. - -function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - var i = r.t, - j = i - ys, - t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r[r.t++] = 1; - r.subTo(t, r); - } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) { - y[y.t++] = 0; - }while (--j >= 0) { - // Estimate quotient digit - var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - // Try it out - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r[i] < --qd) { - r.subTo(t, r); - } - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r); -} - -// (public) this mod a - -function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; -} - -// Modular reduction using "classic" algorithm - -function Classic(m) { - this.m = m; -} - -function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);else return x; -} - -function cRevert(x) { - return x; -} - -function cReduce(x) { - x.divRemTo(this.m, null, x); -} - -function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); -} - -function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); -} - -Classic.prototype.convert = cConvert; -Classic.prototype.revert = cRevert; -Classic.prototype.reduce = cReduce; -Classic.prototype.mulTo = cMulTo; -Classic.prototype.sqrTo = cSqrTo; - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. - -function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 - y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4 - y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8 - y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return y > 0 ? this.DV - y : -y; -} - -// Montgomery reduction - -function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 0x7fff; - this.mph = this.mp >> 15; - this.um = (1 << m.DB - 15) - 1; - this.mt2 = 2 * m.t; -} - -// xR mod m - -function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; -} - -// x/R mod m - -function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; -} - -// x = x/R mod m (HAC 14.32) - -function montReduce(x) { - while (x.t <= this.mt2) { - // pad x so am has enough room later - x[x.t++] = 0; - }for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; - // use am to combine the multiply-shift-add into one call - j = i + this.m.t; - x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV; - x[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); -} - -// r = "x^2/R mod m"; x != r - -function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); -} - -// r = "xy/R mod m"; x,y != r - -function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); -} - -Montgomery.prototype.convert = montConvert; -Montgomery.prototype.revert = montRevert; -Montgomery.prototype.reduce = montReduce; -Montgomery.prototype.mulTo = montMulTo; -Montgomery.prototype.sqrTo = montSqrTo; - -// (protected) true iff this is even - -function bnpIsEven() { - return (this.t > 0 ? this[0] & 1 : this.s) == 0; -} - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - -function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & 1 << i) > 0) z.mulTo(r2, g, r);else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); -} - -// (public) this^e % m, 0 <= e < 2^32 - -function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m);else z = new Montgomery(m); - return this.exp(e, z); -} - -// protected -BigInteger.prototype.copyTo = bnpCopyTo; -BigInteger.prototype.fromInt = bnpFromInt; -BigInteger.prototype.fromString = bnpFromString; -BigInteger.prototype.clamp = bnpClamp; -BigInteger.prototype.dlShiftTo = bnpDLShiftTo; -BigInteger.prototype.drShiftTo = bnpDRShiftTo; -BigInteger.prototype.lShiftTo = bnpLShiftTo; -BigInteger.prototype.rShiftTo = bnpRShiftTo; -BigInteger.prototype.subTo = bnpSubTo; -BigInteger.prototype.multiplyTo = bnpMultiplyTo; -BigInteger.prototype.squareTo = bnpSquareTo; -BigInteger.prototype.divRemTo = bnpDivRemTo; -BigInteger.prototype.invDigit = bnpInvDigit; -BigInteger.prototype.isEven = bnpIsEven; -BigInteger.prototype.exp = bnpExp; - -// public -BigInteger.prototype.toString = bnToString; -BigInteger.prototype.negate = bnNegate; -BigInteger.prototype.abs = bnAbs; -BigInteger.prototype.compareTo = bnCompareTo; -BigInteger.prototype.bitLength = bnBitLength; -BigInteger.prototype.mod = bnMod; -BigInteger.prototype.modPowInt = bnModPowInt; - -// "constants" -BigInteger.ZERO = nbv(0); -BigInteger.ONE = nbv(1); -BigInteger.TWO = nbv(2); - -/* - * Copyright (c) 2003-2005 Tom Wu (tjw@cs.Stanford.EDU) - * All Rights Reserved. - * - * Modified by Recurity Labs GmbH - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, - * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY - * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, - * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF - * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT - * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * In addition, the following condition applies: - * - * All redistributions must retain an intact copy of this copyright notice - * and disclaimer. - */ - -// Extended JavaScript BN functions, required for RSA private ops. - -// Version 1.1: new BigInteger("0", 10) returns "proper" zero -// Version 1.2: square() API, isProbablePrime fix - -// (public) -function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; -} - -// (public) return value as integer - -function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV;else if (this.t == 0) return -1; - } else if (this.t == 1) return this[0];else if (this.t == 0) return 0; - // assumes 16 < DB < 32 - return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0]; -} - -// (public) return value as byte - -function bnByteValue() { - return this.t == 0 ? this.s : this[0] << 24 >> 24; -} - -// (public) return value as short (assumes DB>=16) - -function bnShortValue() { - return this.t == 0 ? this.s : this[0] << 16 >> 16; -} - -// (protected) return x s.t. r^x < DV - -function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); -} - -// (public) 0 if this == 0, 1 if this > 0 - -function bnSigNum() { - if (this.s < 0) return -1;else if (this.t <= 0 || this.t == 1 && this[0] <= 0) return 0;else return 1; -} - -// (protected) convert to radix string - -function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), - y = nbi(), - z = nbi(), - r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; -} - -// (protected) convert from radix string - -function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); -} - -// (protected) alternate constructor - -function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) this.fromInt(1);else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); // force odd - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1;else x[0] = 0; - this.fromString(x, 256); - } -} - -// (public) convert to bigendian byte array - -function bnToByteArray() { - var i = this.t, - r = new Array(); - r[0] = this.s; - var p = this.DB - i * this.DB % 8, - d, - k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | this.s << this.DB - p; - while (i >= 0) { - if (p < 8) { - d = (this[i] & (1 << p) - 1) << 8 - p; - d |= this[--i] >> (p += this.DB - 8); - } else { - d = this[i] >> (p -= 8) & 0xff; - if (p <= 0) { - p += this.DB; - --i; - } - } - //if((d&0x80) != 0) d |= -256; - //if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; -} - -function bnEquals(a) { - return this.compareTo(a) == 0; -} - -function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; -} - -function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; -} - -// (protected) r = this op a (bitwise) - -function bnpBitwiseTo(a, op, r) { - var i, - f, - m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) { - r[i] = op(this[i], a[i]); - }if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) { - r[i] = op(this[i], f); - }r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) { - r[i] = op(f, a[i]); - }r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); -} - -// (public) this & a - -function op_and(x, y) { - return x & y; -} - -function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; -} - -// (public) this | a - -function op_or(x, y) { - return x | y; -} - -function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; -} - -// (public) this ^ a - -function op_xor(x, y) { - return x ^ y; -} - -function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; -} - -// (public) this & ~a - -function op_andnot(x, y) { - return x & ~y; -} - -function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; -} - -// (public) ~this - -function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) { - r[i] = this.DM & ~this[i]; - }r.t = this.t; - r.s = ~this.s; - return r; -} - -// (public) this << n - -function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r);else this.lShiftTo(n, r); - return r; -} - -// (public) this >> n - -function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r);else this.rShiftTo(n, r); - return r; -} - -// return index of lowest 1-bit in x, x < 2^31 - -function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 0xffff) == 0) { - x >>= 16; - r += 16; - } - if ((x & 0xff) == 0) { - x >>= 8; - r += 8; - } - if ((x & 0xf) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; -} - -// (public) returns index of lowest 1-bit (or -1 if none) - -function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) { - if (this[i] != 0) return i * this.DB + lbit(this[i]); - }if (this.s < 0) return this.t * this.DB; - return -1; -} - -// return number of 1 bits in x - -function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; -} - -// (public) return number of set bits - -function bnBitCount() { - var r = 0, - x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) { - r += cbit(this[i] ^ x); - }return r; -} - -// (public) true iff nth bit is set - -function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this[j] & 1 << n % this.DB) != 0; -} - -// (protected) this op (1<>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c; - r.t = i; - r.clamp(); -} - -// (public) this + a - -function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; -} - -// (public) this - a - -function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; -} - -// (public) this * a - -function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; -} - -// (public) this^2 - -function bnSquare() { - var r = nbi(); - this.squareTo(r); - return r; -} - -// (public) this / a - -function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; -} - -// (public) this % a - -function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; -} - -// (public) [this/a,this%a] - -function bnDivideAndRemainder(a) { - var q = nbi(), - r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); -} - -// (protected) this *= n, this >= 0, 1 < n < DV - -function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); -} - -// (protected) this += n << w words, this >= 0 - -function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) { - this[this.t++] = 0; - }this[w] += n; - while (this[w] >= this.DV) { - this[w] -= this.DV; - if (++w >= this.t) this[this.t++] = 0; - ++this[w]; - } -} - -// A "null" reducer - -function NullExp() {} - -function nNop(x) { - return x; -} - -function nMulTo(x, y, r) { - x.multiplyTo(y, r); -} - -function nSqrTo(x, r) { - x.squareTo(r); -} - -NullExp.prototype.convert = nNop; -NullExp.prototype.revert = nNop; -NullExp.prototype.mulTo = nMulTo; -NullExp.prototype.sqrTo = nSqrTo; - -// (public) this^e - -function bnPow(e) { - return this.exp(e, new NullExp()); -} - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. - -function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while (i > 0) { - r[--i] = 0; - }var j; - for (j = r.t - this.t; i < j; ++i) { - r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); - }for (j = Math.min(a.t, n); i < j; ++i) { - this.am(0, a[i], r, i, 0, n - i); - }r.clamp(); -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. - -function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) { - r[i] = 0; - }for (i = Math.max(n - this.t, 0); i < a.t; ++i) { - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); - }r.clamp(); - r.drShiftTo(1, r); -} - -// Barrett modular reduction - -function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; -} - -function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m);else if (x.compareTo(this.m) < 0) return x;else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } -} - -function barrettRevert(x) { - return x; -} - -// x = x mod m (HAC 14.42) - -function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) { - x.dAddOffset(1, this.m.t + 1); - }x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) { - x.subTo(this.m, x); - } -} - -// r = x^2 mod m; x != r - -function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); -} - -// r = x*y mod m; x,y != r - -function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); -} - -Barrett.prototype.convert = barrettConvert; -Barrett.prototype.revert = barrettRevert; -Barrett.prototype.reduce = barrettReduce; -Barrett.prototype.mulTo = barrettMulTo; -Barrett.prototype.sqrTo = barrettSqrTo; - -// (public) this^e % m (HAC 14.85) - -function bnModPow(e, m) { - var i = e.bitLength(), - k, - r = nbv(1), - z; - if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6; - if (i < 8) z = new Classic(m);else if (m.isEven()) z = new Barrett(m);else z = new Montgomery(m); - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - - var j = e.t - 1, - w, - is1 = true, - r2 = nbi(), - t; - i = nbits(e[j]) - 1; - while (j >= 0) { - if (i >= k1) w = e[j] >> i - k1 & km;else { - w = (e[j] & (1 << i + 1) - 1) << k1 - i; - if (j > 0) w |= e[j - 1] >> this.DB + i - k1; - } - - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2);else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - - while (j >= 0 && (e[j] & 1 << i) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); -} - -// (public) gcd(this,a) (HAC 14.54) - -function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; -} - -// (protected) this % n, n < 2^26 - -function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, - r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) if (d == 0) r = this[0] % n;else for (var i = this.t - 1; i >= 0; --i) { - r = (d * r + this[i]) % n; - }return r; -} - -// (public) 1/this % m (HAC 14.61) - -function bnModInverse(m) { - var ac = m.isEven(); - if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), - v = this.clone(); - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d);else return d; - if (d.signum() < 0) return d.add(m);else return d; -} - -var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - -// (public) test primality with certainty >= 1-.5^t - -function bnIsProbablePrime(t) { - var i, - x = this.abs(); - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) { - if (x[0] == lowprimes[i]) return true; - }return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1; - while (j < lowprimes.length && m < lplim) { - m *= lowprimes[j++]; - }m = x.modInt(m); - while (i < j) { - if (m % lowprimes[i++] == 0) return false; - } - } - return x.millerRabin(t); -} - -/* added by Recurity Labs */ - -function nbits(x) { - var n = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - n += 16; - } - if ((t = x >> 8) != 0) { - x = t; - n += 8; - } - if ((t = x >> 4) != 0) { - x = t; - n += 4; - } - if ((t = x >> 2) != 0) { - x = t; - n += 2; - } - if ((t = x >> 1) != 0) { - x = t; - n += 1; - } - return n; -} - -function bnToMPI() { - var ba = this.toByteArray(); - var size = (ba.length - 1) * 8 + nbits(ba[0]); - var result = ""; - result += String.fromCharCode((size & 0xFF00) >> 8); - result += String.fromCharCode(size & 0xFF); - result += _util2.default.bin2str(ba); - return result; -} -/* END of addition */ - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - t = t + 1 >> 1; - if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - var j, - bases = []; - for (var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - for (;;) { - j = lowprimes[Math.floor(Math.random() * lowprimes.length)]; - if (bases.indexOf(j) == -1) break; - } - bases.push(j); - a.fromInt(j); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; -} - -// protected -BigInteger.prototype.chunkSize = bnpChunkSize; -BigInteger.prototype.toRadix = bnpToRadix; -BigInteger.prototype.fromRadix = bnpFromRadix; -BigInteger.prototype.fromNumber = bnpFromNumber; -BigInteger.prototype.bitwiseTo = bnpBitwiseTo; -BigInteger.prototype.changeBit = bnpChangeBit; -BigInteger.prototype.addTo = bnpAddTo; -BigInteger.prototype.dMultiply = bnpDMultiply; -BigInteger.prototype.dAddOffset = bnpDAddOffset; -BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; -BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; -BigInteger.prototype.modInt = bnpModInt; -BigInteger.prototype.millerRabin = bnpMillerRabin; - -// public -BigInteger.prototype.clone = bnClone; -BigInteger.prototype.intValue = bnIntValue; -BigInteger.prototype.byteValue = bnByteValue; -BigInteger.prototype.shortValue = bnShortValue; -BigInteger.prototype.signum = bnSigNum; -BigInteger.prototype.toByteArray = bnToByteArray; -BigInteger.prototype.equals = bnEquals; -BigInteger.prototype.min = bnMin; -BigInteger.prototype.max = bnMax; -BigInteger.prototype.and = bnAnd; -BigInteger.prototype.or = bnOr; -BigInteger.prototype.xor = bnXor; -BigInteger.prototype.andNot = bnAndNot; -BigInteger.prototype.not = bnNot; -BigInteger.prototype.shiftLeft = bnShiftLeft; -BigInteger.prototype.shiftRight = bnShiftRight; -BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; -BigInteger.prototype.bitCount = bnBitCount; -BigInteger.prototype.testBit = bnTestBit; -BigInteger.prototype.setBit = bnSetBit; -BigInteger.prototype.clearBit = bnClearBit; -BigInteger.prototype.flipBit = bnFlipBit; -BigInteger.prototype.add = bnAdd; -BigInteger.prototype.subtract = bnSubtract; -BigInteger.prototype.multiply = bnMultiply; -BigInteger.prototype.divide = bnDivide; -BigInteger.prototype.remainder = bnRemainder; -BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; -BigInteger.prototype.modPow = bnModPow; -BigInteger.prototype.modInverse = bnModInverse; -BigInteger.prototype.pow = bnPow; -BigInteger.prototype.gcd = bnGCD; -BigInteger.prototype.isProbablePrime = bnIsProbablePrime; -BigInteger.prototype.toMPI = bnToMPI; - -// JSBN-specific extension -BigInteger.prototype.square = bnSquare; - -},{"../../util.js":70}],30:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript + return keyObj; +} // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -11744,278 +33120,411 @@ BigInteger.prototype.square = bnSquare; // RSA implementation /** - * @requires crypto/public_key/jsbn + * @requires bn.js + * @requires crypto/public_key/prime * @requires crypto/random + * @requires config * @requires util * @module crypto/public_key/rsa */ +exports.default = { + /** Create signature + * @param m message as BN + * @param n public MPI part as BN + * @param e public MPI part as BN + * @param d private MPI part as BN + * @returns BN + * @async + */ + sign: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(m, n, e, d) { + var nred; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(n.cmp(m) <= 0)) { + _context.next = 2; + break; + } + + throw new Error('Data too large.'); + + case 2: + nred = new _bn2.default.red(n); + return _context.abrupt('return', m.toRed(nred).redPow(d).toArrayLike(Uint8Array, 'be', n.byteLength())); + + case 4: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + function sign(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + } + + return sign; + }(), + + /** + * Verify signature + * @param s signature as BN + * @param n public MPI part as BN + * @param e public MPI part as BN + * @returns BN + * @async + */ + verify: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(s, n, e) { + var nred; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(n.cmp(s) <= 0)) { + _context2.next = 2; + break; + } + + throw new Error('Data too large.'); + + case 2: + nred = new _bn2.default.red(n); + return _context2.abrupt('return', s.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength())); + + case 4: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function verify(_x5, _x6, _x7) { + return _ref2.apply(this, arguments); + } + + return verify; + }(), + + /** + * Encrypt message + * @param m message as BN + * @param n public MPI part as BN + * @param e public MPI part as BN + * @returns BN + * @async + */ + encrypt: function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(m, n, e) { + var nred; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + if (!(n.cmp(m) <= 0)) { + _context3.next = 2; + break; + } + + throw new Error('Data too large.'); + + case 2: + nred = new _bn2.default.red(n); + return _context3.abrupt('return', m.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength())); + + case 4: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function encrypt(_x8, _x9, _x10) { + return _ref3.apply(this, arguments); + } + + return encrypt; + }(), + + /** + * Decrypt RSA message + * @param m message as BN + * @param n RSA public modulus n as BN + * @param e RSA public exponent as BN + * @param d RSA d as BN + * @param p RSA p as BN + * @param q RSA q as BN + * @param u RSA u as BN + * @returns {BN} The decrypted value of the message + * @async + */ + decrypt: function () { + var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(m, n, e, d, p, q, u) { + var dq, dp, pred, qred, nred, blinder, unblinder, mp, mq, t, h, result; + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (!(n.cmp(m) <= 0)) { + _context4.next = 2; + break; + } + + throw new Error('Data too large.'); + + case 2: + dq = d.mod(q.subn(1)); // d mod (q-1) + + dp = d.mod(p.subn(1)); // d mod (p-1) + + pred = new _bn2.default.red(p); + qred = new _bn2.default.red(q); + nred = new _bn2.default.red(n); + blinder = void 0; + unblinder = void 0; + + if (!_config2.default.rsa_blinding) { + _context4.next = 16; + break; + } + + _context4.next = 12; + return _random2.default.getRandomBN(new _bn2.default(2), n); + + case 12: + _context4.t0 = nred; + unblinder = _context4.sent.toRed(_context4.t0); + + blinder = unblinder.redInvm().redPow(e); + m = m.toRed(nred).redMul(blinder).fromRed(); + + case 16: + mp = m.toRed(pred).redPow(dp); + mq = m.toRed(qred).redPow(dq); + t = mq.redSub(mp.fromRed().toRed(qred)); + h = u.toRed(qred).redMul(t).fromRed(); + result = h.mul(p).add(mp).toRed(nred); + + + if (_config2.default.rsa_blinding) { + result = result.redMul(unblinder); + } + + return _context4.abrupt('return', result.toArrayLike(Uint8Array, 'be', n.byteLength())); + + case 23: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + function decrypt(_x11, _x12, _x13, _x14, _x15, _x16, _x17) { + return _ref4.apply(this, arguments); + } + + return decrypt; + }(), + + /** + * Generate a new random private key B bits long with public exponent E + * @param {Integer} B RSA bit length + * @param {String} E RSA public exponent in hex string + * @returns {{n: BN, e: BN, d: BN, + * p: BN, q: BN, u: BN}} RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = q ** -1 mod p + * @async + */ + generate: function () { + var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(B, E) { + var key, webCrypto, keyPair, keyGenOpt, jwk, p, q, _ref6, phi; + + return _regenerator2.default.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + key = void 0; + + E = new _bn2.default(E, 16); + webCrypto = _util2.default.getWebCryptoAll(); + + // Native RSA keygen using Web Crypto + + if (!webCrypto) { + _context5.next = 35; + break; + } + + keyPair = void 0; + keyGenOpt = void 0; + + if (!(window.crypto && window.crypto.subtle || window.msCrypto)) { + _context5.next = 14; + break; + } + + // current standard spec + keyGenOpt = { + name: 'RSASSA-PKCS1-v1_5', + modulusLength: B, // the specified keysize in bits + publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']); + _context5.next = 11; + return promisifyIE11Op(keyPair, 'Error generating RSA key pair.'); + + case 11: + keyPair = _context5.sent; + _context5.next = 22; + break; + + case 14: + if (!(window.crypto && window.crypto.webkitSubtle)) { + _context5.next = 21; + break; + } + + // outdated spec implemented by old Webkit + keyGenOpt = { + name: 'RSA-OAEP', + modulusLength: B, // the specified keysize in bits + publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent + hash: { + name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' + } + }; + _context5.next = 18; + return webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']); + + case 18: + keyPair = _context5.sent; + _context5.next = 22; + break; + + case 21: + throw new Error('Unknown WebCrypto implementation'); + + case 22: + + // export the generated keys as JsonWebKey (JWK) + // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 + jwk = webCrypto.exportKey('jwk', keyPair.privateKey); + _context5.next = 25; + return promisifyIE11Op(jwk, 'Error exporting RSA key pair.'); + + case 25: + jwk = _context5.sent; + + + // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk) + if (jwk instanceof ArrayBuffer) { + jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk))); + } + + // map JWK parameters to BN + key = {}; + key.n = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.n)); + key.e = E; + key.d = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.d)); + key.p = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.p)); + key.q = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.q)); + key.u = key.p.invm(key.q); + return _context5.abrupt('return', key); + + case 35: + _context5.next = 37; + return _prime2.default.randomProbablePrime(B - (B >> 1), E, 40); + + case 37: + p = _context5.sent; + _context5.next = 40; + return _prime2.default.randomProbablePrime(B >> 1, E, 40); + + case 40: + q = _context5.sent; + + + if (p.cmp(q) < 0) { + _ref6 = [q, p]; + p = _ref6[0]; + q = _ref6[1]; + } + + phi = p.subn(1).mul(q.subn(1)); + return _context5.abrupt('return', { + n: p.mul(q), + e: E, + d: E.invm(phi), + p: p, + q: q, + // dp: d.mod(p.subn(1)), + // dq: d.mod(q.subn(1)), + u: p.invm(q) + }); + + case 44: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this); + })); + + function generate(_x18, _x19) { + return _ref5.apply(this, arguments); + } + + return generate; + }(), + + prime: _prime2.default +}; + +},{"../../config":306,"../../util":376,"../random":333,"./prime":331,"babel-runtime/core-js/promise":25,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],333:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = RSA; -var _jsbn = _dereq_('./jsbn.js'); +var _regenerator = _dereq_('babel-runtime/regenerator'); -var _jsbn2 = _interopRequireDefault(_jsbn); +var _regenerator2 = _interopRequireDefault(_regenerator); -var _util = _dereq_('../../util.js'); +var _typeof2 = _dereq_('babel-runtime/helpers/typeof'); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _mpi = _dereq_('../type/mpi'); + +var _mpi2 = _interopRequireDefault(_mpi); + +var _util = _dereq_('../util'); var _util2 = _interopRequireDefault(_util); -var _random = _dereq_('../random.js'); - -var _random2 = _interopRequireDefault(_random); - -var _config = _dereq_('../../config'); - -var _config2 = _interopRequireDefault(_config); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function SecureRandom() { - function nextBytes(byteArray) { - for (var n = 0; n < byteArray.length; n++) { - byteArray[n] = _random2.default.getSecureRandomOctet(); - } - } - this.nextBytes = nextBytes; -} - -var blinder = _jsbn2.default.ZERO; -var unblinder = _jsbn2.default.ZERO; - -function blind(m, n, e) { - if (unblinder.bitLength() === n.bitLength()) { - unblinder = unblinder.square().mod(n); - } else { - unblinder = _random2.default.getRandomBigIntegerInRange(_jsbn2.default.TWO, n); - } - blinder = unblinder.modInverse(n).modPow(e, n); - return m.multiply(blinder).mod(n); -} - -function unblind(t, n) { - return t.multiply(unblinder).mod(n); -} - -function RSA() { - /** - * This function uses jsbn Big Num library to decrypt RSA - * @param m - * message - * @param n - * RSA public modulus n as BigInteger - * @param e - * RSA public exponent as BigInteger - * @param d - * RSA d as BigInteger - * @param p - * RSA p as BigInteger - * @param q - * RSA q as BigInteger - * @param u - * RSA u as BigInteger - * @return {BigInteger} The decrypted value of the message - */ - function decrypt(m, n, e, d, p, q, u) { - if (_config2.default.rsa_blinding) { - m = blind(m, n, e); - } - var xp = m.mod(p).modPow(d.mod(p.subtract(_jsbn2.default.ONE)), p); - var xq = m.mod(q).modPow(d.mod(q.subtract(_jsbn2.default.ONE)), q); - _util2.default.print_debug("rsa.js decrypt\nxpn:" + _util2.default.hexstrdump(xp.toMPI()) + "\nxqn:" + _util2.default.hexstrdump(xq.toMPI())); - - var t = xq.subtract(xp); - if (t[0] === 0) { - t = xp.subtract(xq); - t = t.multiply(u).mod(q); - t = q.subtract(t); - } else { - t = t.multiply(u).mod(q); - } - t = t.multiply(p).add(xp); - if (_config2.default.rsa_blinding) { - t = unblind(t, n); - } - return t; - } - - /** - * encrypt message - * @param m message as BigInteger - * @param e public MPI part as BigInteger - * @param n public MPI part as BigInteger - * @return BigInteger - */ - function encrypt(m, e, n) { - return m.modPowInt(e, n); - } - - /* Sign and Verify */ - function sign(m, d, n) { - return m.modPow(d, n); - } - - function verify(x, e, n) { - return x.modPowInt(e, n); - } - - // "empty" RSA key constructor - - function KeyObject() { - this.n = null; - this.e = 0; - this.ee = null; - this.d = null; - this.p = null; - this.q = null; - this.dmp1 = null; - this.dmq1 = null; - this.u = null; - } - - // Generate a new random private key B bits long, using public expt E - - function generate(B, E) { - var webCrypto = _util2.default.getWebCryptoAll(); - - // - // Native RSA keygen using Web Crypto - // - - if (webCrypto) { - var Euint32 = new Uint32Array([parseInt(E, 16)]); // get integer of exponent - var Euint8 = new Uint8Array(Euint32.buffer); // get bytes of exponent - var keyGenOpt; - - var keys; - if (window.crypto && window.crypto.webkitSubtle) { - // outdated spec implemented by Webkit - keyGenOpt = { - name: 'RSA-OAEP', - modulusLength: B, // the specified keysize in bits - publicExponent: Euint8.subarray(0, 3), // take three bytes (max 65537) - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - keys = webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']); - } else { - // current standard spec - keyGenOpt = { - name: 'RSASSA-PKCS1-v1_5', - modulusLength: B, // the specified keysize in bits - publicExponent: Euint8.subarray(0, 3), // take three bytes (max 65537) - hash: { - name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' - } - }; - - keys = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']); - if (typeof keys.then !== 'function') { - // IE11 KeyOperation - keys = _util2.default.promisifyIE11Op(keys, 'Error generating RSA key pair.'); - } - } - - return keys.then(exportKey).then(function (key) { - if (key instanceof ArrayBuffer) { - // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk) - return decodeKey(JSON.parse(String.fromCharCode.apply(null, new Uint8Array(key)))); - } - return decodeKey(key); - }); - } - - function exportKey(keypair) { - // export the generated keys as JsonWebKey (JWK) - // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 - var key = webCrypto.exportKey('jwk', keypair.privateKey); - if (typeof key.then !== 'function') { - // IE11 KeyOperation - key = _util2.default.promisifyIE11Op(key, 'Error exporting RSA key pair.'); - } - return key; - } - - function decodeKey(jwk) { - // map JWK parameters to local BigInteger type system - var key = new KeyObject(); - key.n = toBigInteger(jwk.n); - key.ee = new _jsbn2.default(E, 16); - key.d = toBigInteger(jwk.d); - key.p = toBigInteger(jwk.p); - key.q = toBigInteger(jwk.q); - key.u = key.p.modInverse(key.q); - - function toBigInteger(base64url) { - var base64 = base64url.replace(/\-/g, '+').replace(/_/g, '/'); - var hex = _util2.default.hexstrdump(atob(base64)); - return new _jsbn2.default(hex, 16); - } - - return key; - } - - // - // JS code - // - - return new Promise(function (resolve) { - var key = new KeyObject(); - var rng = new SecureRandom(); - var qs = B >> 1; - key.e = parseInt(E, 16); - key.ee = new _jsbn2.default(E, 16); - - for (;;) { - for (;;) { - key.p = new _jsbn2.default(B - qs, 1, rng); - if (key.p.subtract(_jsbn2.default.ONE).gcd(key.ee).compareTo(_jsbn2.default.ONE) === 0 && key.p.isProbablePrime(10)) { - break; - } - } - for (;;) { - key.q = new _jsbn2.default(qs, 1, rng); - if (key.q.subtract(_jsbn2.default.ONE).gcd(key.ee).compareTo(_jsbn2.default.ONE) === 0 && key.q.isProbablePrime(10)) { - break; - } - } - if (key.p.compareTo(key.q) <= 0) { - var t = key.p; - key.p = key.q; - key.q = t; - } - var p1 = key.p.subtract(_jsbn2.default.ONE); - var q1 = key.q.subtract(_jsbn2.default.ONE); - var phi = p1.multiply(q1); - if (phi.gcd(key.ee).compareTo(_jsbn2.default.ONE) === 0) { - key.n = key.p.multiply(key.q); - key.d = key.ee.modInverse(phi); - key.dmp1 = key.d.mod(p1); - key.dmq1 = key.d.mod(q1); - key.u = key.p.modInverse(key.q); - break; - } - } - - resolve(key); - }); - } - - this.encrypt = encrypt; - this.decrypt = decrypt; - this.verify = verify; - this.sign = sign; - this.generate = generate; - this.keyObject = KeyObject; -} - -},{"../../config":10,"../../util.js":70,"../random.js":31,"./jsbn.js":29}],31:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +// Do not use util.getNodeCrypto because we need this regardless of use_native setting +var nodeCrypto = _util2.default.detectNode() && _dereq_('crypto'); // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -12035,132 +33544,147 @@ function RSA() { // The GPG4Browsers crypto interface /** + * @requires bn.js * @requires type/mpi * @requires util * @module crypto/random */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var _mpi = _dereq_('../type/mpi.js'); - -var _mpi2 = _interopRequireDefault(_mpi); - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var nodeCrypto = _util2.default.detectNode() && _dereq_('crypto'); - exports.default = { /** * Retrieve secure random byte array of the specified length * @param {Integer} length Length in bytes to generate - * @return {Uint8Array} Random byte array + * @returns {Uint8Array} Random byte array + * @async */ - getRandomBytes: function getRandomBytes(length) { - var result = new Uint8Array(length); - for (var i = 0; i < length; i++) { - result[i] = this.getSecureRandomOctet(); + getRandomBytes: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(length) { + var buf, bytes; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + buf = new Uint8Array(length); + + if (!(typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues)) { + _context.next = 5; + break; + } + + window.crypto.getRandomValues(buf); + _context.next = 20; + break; + + case 5: + if (!(typeof window !== 'undefined' && (0, _typeof3.default)(window.msCrypto) === 'object' && typeof window.msCrypto.getRandomValues === 'function')) { + _context.next = 9; + break; + } + + window.msCrypto.getRandomValues(buf); + _context.next = 20; + break; + + case 9: + if (!nodeCrypto) { + _context.next = 14; + break; + } + + bytes = nodeCrypto.randomBytes(buf.length); + + buf.set(bytes); + _context.next = 20; + break; + + case 14: + if (!this.randomBuffer.buffer) { + _context.next = 19; + break; + } + + _context.next = 17; + return this.randomBuffer.get(buf); + + case 17: + _context.next = 20; + break; + + case 19: + throw new Error('No secure random number generator available.'); + + case 20: + return _context.abrupt('return', buf); + + case 21: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + function getRandomBytes(_x) { + return _ref.apply(this, arguments); } - return result; - }, + + return getRandomBytes; + }(), /** - * Return a secure random number in the specified range - * @param {Integer} from Min of the random number - * @param {Integer} to Max of the random number (max 32bit) - * @return {Integer} A secure random number + * Create a secure random MPI that is greater than or equal to min and less than max. + * @param {module:type/mpi} min Lower bound, included + * @param {module:type/mpi} max Upper bound, excluded + * @returns {module:BN} Random MPI + * @async */ - getSecureRandom: function getSecureRandom(from, to) { - var randUint = this.getSecureRandomUint(); - var bits = (to - from).toString(2).length; - while ((randUint & Math.pow(2, bits) - 1) > to - from) { - randUint = this.getSecureRandomUint(); - } - return from + Math.abs(randUint & Math.pow(2, bits) - 1); - }, + getRandomBN: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(min, max) { + var modulus, bytes, r; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(max.cmp(min) <= 0)) { + _context2.next = 2; + break; + } - getSecureRandomOctet: function getSecureRandomOctet() { - var buf = new Uint8Array(1); - this.getRandomValues(buf); - return buf[0]; - }, + throw new Error('Illegal parameter value: max <= min'); - getSecureRandomUint: function getSecureRandomUint() { - var buf = new Uint8Array(4); - var dv = new DataView(buf.buffer); - this.getRandomValues(buf); - return dv.getUint32(0); - }, + case 2: + modulus = max.sub(min); + bytes = modulus.byteLength(); - /** - * Helper routine which calls platform specific crypto random generator - * @param {Uint8Array} buf - */ - getRandomValues: function getRandomValues(buf) { - if (!(buf instanceof Uint8Array)) { - throw new Error('Invalid type: buf not an Uint8Array'); - } - if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) { - window.crypto.getRandomValues(buf); - } else if (typeof window !== 'undefined' && _typeof(window.msCrypto) === 'object' && typeof window.msCrypto.getRandomValues === 'function') { - window.msCrypto.getRandomValues(buf); - } else if (nodeCrypto) { - var bytes = nodeCrypto.randomBytes(buf.length); - buf.set(bytes); - } else if (this.randomBuffer.buffer) { - this.randomBuffer.get(buf); - } else { - throw new Error('No secure random number generator available.'); - } - return buf; - }, + // Using a while loop is necessary to avoid bias introduced by the mod operation. + // However, we request 64 extra random bits so that the bias is negligible. + // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf - /** - * Create a secure random big integer of bits length - * @param {Integer} bits Bit length of the MPI to create - * @return {BigInteger} Resulting big integer - */ - getRandomBigInteger: function getRandomBigInteger(bits) { - if (bits < 1) { - throw new Error('Illegal parameter value: bits < 1'); - } - var numBytes = Math.floor((bits + 7) / 8); + _context2.t0 = _bn2.default; + _context2.next = 7; + return this.getRandomBytes(bytes + 8); - var randomBits = _util2.default.Uint8Array2str(this.getRandomBytes(numBytes)); - if (bits % 8 > 0) { + case 7: + _context2.t1 = _context2.sent; + r = new _context2.t0(_context2.t1); + return _context2.abrupt('return', r.mod(modulus).add(min)); - randomBits = String.fromCharCode(Math.pow(2, bits % 8) - 1 & randomBits.charCodeAt(0)) + randomBits.substring(1); - } - var mpi = new _mpi2.default(); - mpi.fromBytes(randomBits); - return mpi.toBigInteger(); - }, + case 10: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); - getRandomBigIntegerInRange: function getRandomBigIntegerInRange(min, max) { - if (max.compareTo(min) <= 0) { - throw new Error('Illegal parameter value: max <= min'); + function getRandomBN(_x2, _x3) { + return _ref2.apply(this, arguments); } - var range = max.subtract(min); - var r = this.getRandomBigInteger(range.bitLength()); - while (r.compareTo(range) > 0) { - r = this.getRandomBigInteger(range.bitLength()); - } - return min.add(r); - }, + return getRandomBN; + }(), randomBuffer: new RandomBuffer() - }; /** @@ -12170,15 +33694,17 @@ exports.default = { function RandomBuffer() { this.buffer = null; this.size = null; + this.callback = null; } /** * Initialize buffer * @param {Integer} size size of buffer */ -RandomBuffer.prototype.init = function (size) { +RandomBuffer.prototype.init = function (size, callback) { this.buffer = new Uint8Array(size); this.size = 0; + this.callback = callback; }; /** @@ -12205,177 +33731,290 @@ RandomBuffer.prototype.set = function (buf) { * Take numbers out of buffer and copy to array * @param {Uint8Array} buf the destination array */ -RandomBuffer.prototype.get = function (buf) { - if (!this.buffer) { - throw new Error('RandomBuffer is not initialized'); - } - if (!(buf instanceof Uint8Array)) { - throw new Error('Invalid type: buf not an Uint8Array'); - } - if (this.size < buf.length) { - throw new Error('Random number buffer depleted'); - } - for (var i = 0; i < buf.length; i++) { - buf[i] = this.buffer[--this.size]; - // clear buffer value - this.buffer[this.size] = 0; - } -}; +RandomBuffer.prototype.get = function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(buf) { + var i; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + if (this.buffer) { + _context3.next = 2; + break; + } -},{"../type/mpi.js":68,"../util.js":70,"crypto":"crypto"}],32:[function(_dereq_,module,exports){ -/** - * @requires util - * @requires crypto/hash - * @requires crypto/pkcs1 - * @requires crypto/public_key - * @module crypto/signature */ + throw new Error('RandomBuffer is not initialized'); + case 2: + if (buf instanceof Uint8Array) { + _context3.next = 4; + break; + } + + throw new Error('Invalid type: buf not an Uint8Array'); + + case 4: + if (!(this.size < buf.length)) { + _context3.next = 10; + break; + } + + if (this.callback) { + _context3.next = 7; + break; + } + + throw new Error('Random number buffer depleted'); + + case 7: + _context3.next = 9; + return this.callback(); + + case 9: + return _context3.abrupt('return', this.get(buf)); + + case 10: + for (i = 0; i < buf.length; i++) { + buf[i] = this.buffer[--this.size]; + // clear buffer value + this.buffer[this.size] = 0; + } + + case 11: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x4) { + return _ref3.apply(this, arguments); + }; +}(); + +},{"../type/mpi":373,"../util":376,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/helpers/typeof":34,"babel-runtime/regenerator":35,"bn.js":37,"crypto":"crypto"}],334:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -var _util = _dereq_('../util'); +var _regenerator = _dereq_('babel-runtime/regenerator'); -var _util2 = _interopRequireDefault(_util); +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _from = _dereq_('babel-runtime/core-js/array/from'); + +var _from2 = _interopRequireDefault(_from); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); var _public_key = _dereq_('./public_key'); var _public_key2 = _interopRequireDefault(_public_key); -var _pkcs = _dereq_('./pkcs1.js'); +var _pkcs = _dereq_('./pkcs1'); var _pkcs2 = _interopRequireDefault(_pkcs); +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { /** - * - * @param {module:enums.publicKey} algo public Key algorithm - * @param {module:enums.hash} hash_algo Hash algorithm - * @param {Array} msg_MPIs Signature multiprecision integers - * @param {Array} publickey_MPIs Public key multiprecision integers - * @param {Uint8Array} data Data on where the signature was computed on. - * @return {Boolean} true if signature (sig_data was equal to data over hash) + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo Public key algorithm + * @param {module:enums.hash} hash_algo Hash algorithm + * @param {Array} msg_MPIs Algorithm-specific signature parameters + * @param {Array} pub_MPIs Algorithm-specific public key parameters + * @param {Uint8Array} data Data for which the signature was created + * @returns {Boolean} True if signature is valid + * @async */ - verify: function verify(algo, hash_algo, msg_MPIs, publickey_MPIs, data) { - var m; + verify: function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(algo, hash_algo, msg_MPIs, pub_MPIs, data) { + var m, n, e, EM, EM2, r, s, p, q, g, y, oid, signature, Q, _oid, _signature, _Q; - data = _util2.default.Uint8Array2str(data); + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = algo; + _context.next = _context.t0 === _enums2.default.publicKey.rsa_encrypt_sign ? 3 : _context.t0 === _enums2.default.publicKey.rsa_encrypt ? 3 : _context.t0 === _enums2.default.publicKey.rsa_sign ? 3 : _context.t0 === _enums2.default.publicKey.dsa ? 11 : _context.t0 === _enums2.default.publicKey.ecdsa ? 18 : _context.t0 === _enums2.default.publicKey.eddsa ? 22 : 26; + break; - switch (algo) { - case 1: - // RSA (Encrypt or Sign) [HAC] - case 2: - // RSA Encrypt-Only [HAC] - case 3: - // RSA Sign-Only [HAC] - var rsa = new _public_key2.default.rsa(); - var n = publickey_MPIs[0].toBigInteger(); - var k = publickey_MPIs[0].byteLength(); - var e = publickey_MPIs[1].toBigInteger(); - m = msg_MPIs[0].toBigInteger(); - var EM = rsa.verify(m, e, n); - var EM2 = _pkcs2.default.emsa.encode(hash_algo, data, k); - return EM.compareTo(EM2) === 0; - case 16: - // Elgamal (Encrypt-Only) [ELGAMAL] [HAC] - throw new Error("signing with Elgamal is not defined in the OpenPGP standard."); - case 17: - // DSA (Digital Signature Algorithm) [FIPS186] [HAC] - var dsa = new _public_key2.default.dsa(); - var s1 = msg_MPIs[0].toBigInteger(); - var s2 = msg_MPIs[1].toBigInteger(); - var p = publickey_MPIs[0].toBigInteger(); - var q = publickey_MPIs[1].toBigInteger(); - var g = publickey_MPIs[2].toBigInteger(); - var y = publickey_MPIs[3].toBigInteger(); - m = data; - var dopublic = dsa.verify(hash_algo, s1, s2, m, p, q, g, y); - return dopublic.compareTo(s1) === 0; - default: - throw new Error('Invalid signature algorithm.'); + case 3: + m = msg_MPIs[0].toBN(); + n = pub_MPIs[0].toBN(); + e = pub_MPIs[1].toBN(); + _context.next = 8; + return _public_key2.default.rsa.verify(m, n, e); + + case 8: + EM = _context.sent; + EM2 = _pkcs2.default.emsa.encode(hash_algo, _util2.default.Uint8Array_to_str(data), n.byteLength()); + return _context.abrupt('return', _util2.default.Uint8Array_to_hex(EM) === EM2); + + case 11: + r = msg_MPIs[0].toBN(); + s = msg_MPIs[1].toBN(); + p = pub_MPIs[0].toBN(); + q = pub_MPIs[1].toBN(); + g = pub_MPIs[2].toBN(); + y = pub_MPIs[3].toBN(); + return _context.abrupt('return', _public_key2.default.dsa.verify(hash_algo, r, s, data, g, p, q, y)); + + case 18: + oid = pub_MPIs[0]; + signature = { r: msg_MPIs[0].toUint8Array(), s: msg_MPIs[1].toUint8Array() }; + Q = pub_MPIs[1].toUint8Array(); + return _context.abrupt('return', _public_key2.default.elliptic.ecdsa.verify(oid, hash_algo, signature, data, Q)); + + case 22: + _oid = pub_MPIs[0]; + // TODO refactor elliptic to accept Uint8Array + // EdDSA signature params are expected in little-endian format + + _signature = { R: (0, _from2.default)(msg_MPIs[0].toUint8Array('le', 32)), + S: (0, _from2.default)(msg_MPIs[1].toUint8Array('le', 32)) }; + _Q = (0, _from2.default)(pub_MPIs[1].toUint8Array('be', 33)); + return _context.abrupt('return', _public_key2.default.elliptic.eddsa.verify(_oid, hash_algo, _signature, data, _Q)); + + case 26: + throw new Error('Invalid signature algorithm.'); + + case 27: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + function verify(_x, _x2, _x3, _x4, _x5) { + return _ref.apply(this, arguments); } - }, + + return verify; + }(), /** - * Create a signature on data using the specified algorithm - * @param {module:enums.hash} hash_algo hash Algorithm to use (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param {module:enums.publicKey} algo Asymmetric cipher algorithm to use (See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}) - * @param {Array} publicMPIs Public key multiprecision integers - * of the private key - * @param {Array} secretMPIs Private key multiprecision - * integers which is used to sign the data - * @param {Uint8Array} data Data to be signed - * @return {Array} + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param {module:enums.publicKey} algo Public key algorithm + * @param {module:enums.hash} hash_algo Hash algorithm + * @param {Array} key_params Algorithm-specific public and private key parameters + * @param {Uint8Array} data Data to be signed + * @returns {Uint8Array} Signature + * @async */ - sign: function sign(hash_algo, algo, keyIntegers, data) { + sign: function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(algo, hash_algo, key_params, data) { + var n, e, d, m, signature, p, q, g, x, _signature2, oid, _d, _signature3, _oid2, _d2, _signature4; - data = _util2.default.Uint8Array2str(data); + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.t0 = algo; + _context2.next = _context2.t0 === _enums2.default.publicKey.rsa_encrypt_sign ? 3 : _context2.t0 === _enums2.default.publicKey.rsa_encrypt ? 3 : _context2.t0 === _enums2.default.publicKey.rsa_sign ? 3 : _context2.t0 === _enums2.default.publicKey.dsa ? 12 : _context2.t0 === _enums2.default.publicKey.elgamal ? 20 : _context2.t0 === _enums2.default.publicKey.ecdsa ? 21 : _context2.t0 === _enums2.default.publicKey.eddsa ? 27 : 33; + break; - var m; + case 3: + n = key_params[0].toBN(); + e = key_params[1].toBN(); + d = key_params[2].toBN(); - switch (algo) { - case 1: - // RSA (Encrypt or Sign) [HAC] - case 2: - // RSA Encrypt-Only [HAC] - case 3: - // RSA Sign-Only [HAC] - var rsa = new _public_key2.default.rsa(); - var d = keyIntegers[2].toBigInteger(); - var n = keyIntegers[0].toBigInteger(); - m = _pkcs2.default.emsa.encode(hash_algo, data, keyIntegers[0].byteLength()); - return _util2.default.str2Uint8Array(rsa.sign(m, d, n).toMPI()); + data = _util2.default.Uint8Array_to_str(data); + m = new _bn2.default(_pkcs2.default.emsa.encode(hash_algo, data, n.byteLength()), 16); + _context2.next = 10; + return _public_key2.default.rsa.sign(m, n, e, d); - case 17: - // DSA (Digital Signature Algorithm) [FIPS186] [HAC] - var dsa = new _public_key2.default.dsa(); + case 10: + signature = _context2.sent; + return _context2.abrupt('return', _util2.default.Uint8Array_to_MPI(signature)); - var p = keyIntegers[0].toBigInteger(); - var q = keyIntegers[1].toBigInteger(); - var g = keyIntegers[2].toBigInteger(); - var x = keyIntegers[4].toBigInteger(); - m = data; - var result = dsa.sign(hash_algo, m, g, p, q, x); + case 12: + p = key_params[0].toBN(); + q = key_params[1].toBN(); + g = key_params[2].toBN(); + x = key_params[4].toBN(); + _context2.next = 18; + return _public_key2.default.dsa.sign(hash_algo, data, g, p, q, x); - return _util2.default.str2Uint8Array(result[0].toString() + result[1].toString()); - case 16: - // Elgamal (Encrypt-Only) [ELGAMAL] [HAC] - throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); - default: - throw new Error('Invalid signature algorithm.'); + case 18: + _signature2 = _context2.sent; + return _context2.abrupt('return', _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(_signature2.r), _util2.default.Uint8Array_to_MPI(_signature2.s)])); + + case 20: + throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.'); + + case 21: + oid = key_params[0]; + _d = key_params[2].toUint8Array(); + _context2.next = 25; + return _public_key2.default.elliptic.ecdsa.sign(oid, hash_algo, data, _d); + + case 25: + _signature3 = _context2.sent; + return _context2.abrupt('return', _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(_signature3.r), _util2.default.Uint8Array_to_MPI(_signature3.s)])); + + case 27: + _oid2 = key_params[0]; + _d2 = (0, _from2.default)(key_params[2].toUint8Array('be', 32)); + _context2.next = 31; + return _public_key2.default.elliptic.eddsa.sign(_oid2, hash_algo, data, _d2); + + case 31: + _signature4 = _context2.sent; + return _context2.abrupt('return', _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(_signature4.R), _util2.default.Uint8Array_to_MPI(_signature4.S)])); + + case 33: + throw new Error('Invalid signature algorithm.'); + + case 34: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function sign(_x6, _x7, _x8, _x9) { + return _ref2.apply(this, arguments); } - } -}; -},{"../util":70,"./pkcs1.js":25,"./public_key":28}],33:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * @requires encoding/base64 - * @requires enums - * @requires config - * @module encoding/armor - */ + return sign; + }() +}; /** + * @requires bn.js + * @requires crypto/public_key + * @requires crypto/pkcs1 + * @requires enums + * @requires util + * @module crypto/signature + */ +},{"../enums":337,"../util":376,"./pkcs1":320,"./public_key":330,"babel-runtime/core-js/array/from":16,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35,"bn.js":37}],335:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -12465,6 +34104,30 @@ function getType(text) { * @version 2011-12-16 * @returns {String} The header information */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @requires encoding/base64 + * @requires enums + * @requires config + * @module encoding/armor + */ + function addheader() { var result = ""; if (_config2.default.show_version) { @@ -12480,7 +34143,7 @@ function addheader() { /** * Calculates a checksum over the given data and returns it base64 encoded * @param {String} data Data to create a CRC-24 checksum for - * @return {String} Base64 encoded checksum + * @returns {String} Base64 encoded checksum */ function getCheckSum(data) { var c = createcrc24(data); @@ -12493,7 +34156,7 @@ function getCheckSum(data) { * given base64 encoded checksum * @param {String} data Data to create a CRC-24 checksum for * @param {String} checksum Base64 encoded checksum - * @return {Boolean} True if the given checksum is correct; otherwise false + * @returns {Boolean} True if the given checksum is correct; otherwise false */ function verifyCheckSum(data, checksum) { var c = getCheckSum(data); @@ -12503,7 +34166,7 @@ function verifyCheckSum(data, checksum) { /** * Internal function to calculate a CRC-24 checksum over a given string (data) * @param {String} data Data to create a CRC-24 checksum for - * @return {Integer} The CRC-24 checksum as number + * @returns {Integer} The CRC-24 checksum as number */ var crc_table = [0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23, 0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, 0x09685646, 0x0bf72951, 0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926, 0x1b3eb631, 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54, 0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, 0x39b822eb, 0x393e6e10, 0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, 0x315aa1a0, 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62, 0x36fb2099, 0x37f7b96f, 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c, 0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, 0x2cc90f5e, 0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe, 0x7e2a7448, 0x7eac38b3, 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc, 0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, 0x62330fbb, 0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9, 0x6df64132, 0x6f693e25, 0x6fef72de, 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, 0x69c426ea, 0x422ae476, 0x42aca88d, 0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff, 0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1, 0x5d26359f, 0x5da07964, 0x5cace092, 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, 0x59145247, 0x59921ebc, 0x589e874a, 0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, 0x51f6d10c, 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035, 0x575bc9c3, 0x57dd8538]; @@ -12607,7 +34270,9 @@ function dearmor(text) { // so we know the index of the data we are interested in. var indexBase = 1; - var result, checksum, msg; + var result = void 0; + var checksum = void 0; + var msg = void 0; if (text.search(reSplit) !== splittext[0].length) { indexBase = 0; @@ -12725,7 +34390,12 @@ exports.default = { decode: dearmor }; -},{"../config":10,"../enums.js":35,"./base64.js":34}],34:[function(_dereq_,module,exports){ +},{"../config":306,"../enums.js":337,"./base64.js":336}],336:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); /* OpenPGP radix-64/base64 string encoding/decoding * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de * version 1.0, check www.haneWIN.de for the latest version @@ -12743,45 +34413,47 @@ exports.default = { * @module encoding/base64 */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +var b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64 +var b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64 /** * Convert binary array to radix-64 * @param {Uint8Array} t Uint8Array to convert + * @param {bool} u if true, output is URL-safe * @returns {string} radix-64 version of input string * @static */ -function s2r(t, o) { +function s2r(t) { + var u = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + // TODO check btoa alternative - var a, c, n; - var r = o ? o : [], - l = 0, - s = 0; + var b64 = u ? b64u : b64s; + var a = void 0; + var c = void 0; + var n = void 0; + var r = []; + var l = 0; + var s = 0; var tl = t.length; for (n = 0; n < tl; n++) { c = t[n]; if (s === 0) { - r.push(b64s.charAt(c >> 2 & 63)); + r.push(b64.charAt(c >> 2 & 63)); a = (c & 3) << 4; } else if (s === 1) { - r.push(b64s.charAt(a | c >> 4 & 15)); + r.push(b64.charAt(a | c >> 4 & 15)); a = (c & 15) << 2; } else if (s === 2) { - r.push(b64s.charAt(a | c >> 6 & 3)); + r.push(b64.charAt(a | c >> 6 & 3)); l += 1; - if (l % 60 === 0) { + if (l % 60 === 0 && !u) { r.push("\n"); } - r.push(b64s.charAt(c & 63)); + r.push(b64.charAt(c & 63)); } l += 1; - if (l % 60 === 0) { + if (l % 60 === 0 && !u) { r.push("\n"); } @@ -12791,22 +34463,21 @@ function s2r(t, o) { } } if (s > 0) { - r.push(b64s.charAt(a)); + r.push(b64.charAt(a)); l += 1; - if (l % 60 === 0) { + if (l % 60 === 0 && !u) { + r.push("\n"); + } + if (!u) { + r.push('='); + l += 1; + } + } + if (s === 1 && !u) { + if (l % 60 === 0 && !u) { r.push("\n"); } r.push('='); - l += 1; - } - if (s === 1) { - if (l % 60 === 0) { - r.push("\n"); - } - r.push('='); - } - if (o) { - return; } return r.join(''); } @@ -12814,19 +34485,22 @@ function s2r(t, o) { /** * Convert radix-64 to binary array * @param {String} t radix-64 string to convert + * @param {bool} u if true, input is interpreted as URL-safe * @returns {Uint8Array} binary array version of input string * @static */ -function r2s(t) { +function r2s(t, u) { // TODO check atob alternative - var c, n; - var r = [], - s = 0, - a = 0; + var b64 = u ? b64u : b64s; + var c = void 0; + var n = void 0; + var r = []; + var s = 0; + var a = 0; var tl = t.length; for (n = 0; n < tl; n++) { - c = b64s.indexOf(t.charAt(n)); + c = b64.indexOf(t.charAt(n)); if (c >= 0) { if (s) { r.push(a | c >> 6 - s & 255); @@ -12843,18 +34517,70 @@ exports.default = { decode: r2s }; -},{}],35:[function(_dereq_,module,exports){ -'use strict'; - -/** - * @module enums - */ +},{}],337:[function(_dereq_,module,exports){ +"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +/** + * @module enums + */ + exports.default = { + /** Maps curve names under various standards to one + * @enum {String} + * @readonly + */ + curve: { + /** NIST P-256 Curve */ + "p256": "p256", + "P-256": "p256", + "secp256r1": "p256", + "prime256v1": "p256", + "1.2.840.10045.3.1.7": "p256", + "2a8648ce3d030107": "p256", + "2A8648CE3D030107": "p256", + + /** NIST P-384 Curve */ + "p384": "p384", + "P-384": "p384", + "secp384r1": "p384", + "1.3.132.0.34": "p384", + "2b81040022": "p384", + "2B81040022": "p384", + + /** NIST P-521 Curve */ + "p521": "p521", + "P-521": "p521", + "secp521r1": "p521", + "1.3.132.0.35": "p521", + "2b81040023": "p521", + "2B81040023": "p521", + + /** SECP256k1 Curve */ + "secp256k1": "secp256k1", + "1.3.132.0.10": "secp256k1", + "2b8104000a": "secp256k1", + "2B8104000A": "secp256k1", + + /** Ed25519 Curve */ + "ed25519": "ed25519", + "Ed25519": "ed25519", + "1.3.6.1.4.1.11591.15.1": "ed25519", + "2b06010401da470f01": "ed25519", + "2B06010401DA470F01": "ed25519", + + /** Curve25519 */ + "cv25519": "curve25519", + "curve25519": "curve25519", + "Curve25519": "curve25519", + "1.3.6.1.4.1.3029.1.5.1": "curve25519", + "2b060104019755010501": "curve25519", + "2B060104019755010501": "curve25519" + }, + /** A string to key specifier type * @enum {Integer} * @readonly @@ -12871,11 +34597,23 @@ exports.default = { * @readonly */ publicKey: { + /** RSA (Encrypt or Sign) [HAC] */ rsa_encrypt_sign: 1, + /** RSA (Encrypt only) [HAC] */ rsa_encrypt: 2, + /** RSA (Sign only) [HAC] */ rsa_sign: 3, + /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */ elgamal: 16, - dsa: 17 + /** DSA (Sign only) [FIPS186] [HAC] */ + dsa: 17, + /** ECDH (Encrypt only) [RFC6637] */ + ecdh: 18, + /** ECDSA (Sign only) [RFC6637] */ + ecdsa: 19, + /** EdDSA (Sign only) + * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */ + eddsa: 22 }, /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} @@ -12922,6 +34660,17 @@ exports.default = { sha224: 11 }, + /** A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + * @enum {String} + */ + webHash: { + 'SHA-1': 2, + 'SHA-256': 8, + 'SHA-384': 9, + 'SHA-512': 10 + }, + /** A list of packet types and numeric tags associated with them. * @enum {Integer} * @readonly @@ -12967,37 +34716,44 @@ exports.default = { signature: { /** 0x00: Signature of a binary document. */ binary: 0, - /** 0x01: Signature of a canonical text document.
+ /** 0x01: Signature of a canonical text document. + * * Canonicalyzing the document by converting line endings. */ text: 1, - /** 0x02: Standalone signature.
+ /** 0x02: Standalone signature. + * * This signature is a signature of only its own subpacket contents. * It is calculated identically to a signature over a zero-lengh * binary document. Note that it doesn't make sense to have a V3 * standalone signature. */ standalone: 2, - /** 0x10: Generic certification of a User ID and Public-Key packet.
+ /** 0x10: Generic certification of a User ID and Public-Key packet. + * * The issuer of this certification does not make any particular * assertion as to how well the certifier has checked that the owner * of the key is in fact the person described by the User ID. */ cert_generic: 16, - /** 0x11: Persona certification of a User ID and Public-Key packet.
+ /** 0x11: Persona certification of a User ID and Public-Key packet. + * * The issuer of this certification has not done any verification of * the claim that the owner of this key is the User ID specified. */ cert_persona: 17, - /** 0x12: Casual certification of a User ID and Public-Key packet.
+ /** 0x12: Casual certification of a User ID and Public-Key packet. + * * The issuer of this certification has done some casual * verification of the claim of identity. */ cert_casual: 18, - /** 0x13: Positive certification of a User ID and Public-Key packet.
+ /** 0x13: Positive certification of a User ID and Public-Key packet. + * * The issuer of this certification has done substantial - * verification of the claim of identity.
- *
+ * verification of the claim of identity. + * * Most OpenPGP implementations make their "key signatures" as 0x10 * certifications. Some implementations can issue 0x11-0x13 * certifications, but few differentiate between the types. */ cert_positive: 19, - /** 0x30: Certification revocation signature
+ /** 0x30: Certification revocation signature + * * This signature revokes an earlier User ID certification signature * (signature class 0x10 through 0x13) or direct-key signature * (0x1F). It should be issued by the same key that issued the @@ -13006,7 +34762,8 @@ exports.default = { * revokes, and should have a later creation date than that * certificate. */ cert_revocation: 48, - /** 0x18: Subkey Binding Signature
+ /** 0x18: Subkey Binding Signature + * * This signature is a statement by the top-level signing key that * indicates that it owns the subkey. This signature is calculated * directly on the primary key and subkey, and not on any User ID or @@ -13015,12 +34772,13 @@ exports.default = { * contains a 0x19 signature made by the signing subkey on the * primary key and subkey. */ subkey_binding: 24, - /** 0x19: Primary Key Binding Signature
+ /** 0x19: Primary Key Binding Signature + * * This signature is a statement by a signing subkey, indicating * that it is owned by the primary key and subkey. This signature * is calculated the same way as a 0x18 signature: directly on the - * primary key and subkey, and not on any User ID or other packets.
- *
+ * primary key and subkey, and not on any User ID or other packets. + * * When a signature is made over a key, the hash data starts with the * octet 0x99, followed by a two-octet length of the key, and then body * of the key packet. (Note that this is an old-style packet header for @@ -13029,7 +34787,8 @@ exports.default = { * the subkey using the same format as the main key (also using 0x99 as * the first octet). */ key_binding: 25, - /** 0x1F: Signature directly on a key
+ /** 0x1F: Signature directly on a key + * * This signature is calculated directly on a key. It binds the * information in the Signature subpackets to the key, and is * appropriate to be used for subpackets that provide information @@ -13038,27 +34797,30 @@ exports.default = { * about the key itself, rather than the binding between a key and a * name. */ key: 31, - /** 0x20: Key revocation signature
+ /** 0x20: Key revocation signature + * * The signature is calculated directly on the key being revoked. A * revoked key is not to be used. Only revocation signatures by the * key being revoked, or by an authorized revocation key, should be * considered valid revocation signatures.a */ key_revocation: 32, - /** 0x28: Subkey revocation signature
+ /** 0x28: Subkey revocation signature + * * The signature is calculated directly on the subkey being revoked. * A revoked subkey is not to be used. Only revocation signatures * by the top-level signature key that is bound to this subkey, or * by an authorized revocation key, should be considered valid - * revocation signatures.
- *
+ * revocation signatures. + * * Key revocation signatures (types 0x20 and 0x28) * hash only the key being revoked. */ subkey_revocation: 40, - /** 0x40: Timestamp signature.
+ /** 0x40: Timestamp signature. * This signature is only meaningful for the timestamp contained in * it. */ timestamp: 64, - /** 0x50: Third-Party Confirmation signature.
+ /** 0x50: Third-Party Confirmation signature. + * * This signature is a signature over some other OpenPGP Signature * packet(s). It is analogous to a notary seal on the signed data. * A third-party signature SHOULD include Signature Target @@ -13157,15 +34919,15 @@ exports.default = { if (type[e] !== undefined) { return type[e]; - } else { - throw new Error('Invalid enum value.'); } + + throw new Error('Invalid enum value.'); }, /** Converts from an integer to string. */ read: function read(type, e) { for (var i in type) { - if (type[i] === parseInt(e)) { + if (type[i] === parseInt(e, 10)) { return i; } } @@ -13175,7 +34937,38 @@ exports.default = { }; -},{}],36:[function(_dereq_,module,exports){ +},{}],338:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _config = _dereq_('./config'); + +var _config2 = _interopRequireDefault(_config); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @constructor + * @param {String} keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use e.g. https://pgp.mit.edu + */ +function HKP(keyServerBaseUrl) { + this._baseUrl = keyServerBaseUrl || _config2.default.keyserver; + this._fetch = typeof window !== 'undefined' ? window.fetch : _dereq_('node-fetch'); +} + +/** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param {String} options.keyID The long public key ID. + * @param {String} options.query This can be any part of the key user ID such as name + * or email address. + * @returns {Promise} The ascii armored public key. + * @async + */ // OpenPGP.js - An OpenPGP implementation in javascript // Copyright (C) 2015 Tankred Hase // @@ -13196,42 +34989,12 @@ exports.default = { /** * @fileoverview This class implements a client for the OpenPGP HTTP Keyserver Protocol (HKP) * in order to lookup and upload keys on standard public key servers. + * @module hkp */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = HKP; - -var _config = _dereq_('./config'); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Initialize the HKP client and configure it with the key server url and fetch function. - * @constructor - * @param {String} keyServerBaseUrl (optional) The HKP key server base url including - * the protocol to use e.g. https://pgp.mit.edu - */ -function HKP(keyServerBaseUrl) { - this._baseUrl = keyServerBaseUrl ? keyServerBaseUrl : _config2.default.keyserver; - this._fetch = typeof window !== 'undefined' ? window.fetch : _dereq_('node-fetch'); -} - -/** - * Search for a public key on the key server either by key ID or part of the user ID. - * @param {String} options.keyID The long public key ID. - * @param {String} options.query This can be any part of the key user ID such as name - * or email address. - * @return {Promise} The ascii armored public key. - */ HKP.prototype.lookup = function (options) { - var uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search=', - fetch = this._fetch; + var uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search='; + var fetch = this._fetch; if (options.keyId) { uri += '0x' + encodeURIComponent(options.keyId); @@ -13256,11 +35019,12 @@ HKP.prototype.lookup = function (options) { /** * Upload a public key to the server. * @param {String} publicKeyArmored An ascii armored public key to be uploaded. - * @return {Promise} + * @returns {Promise} + * @async */ HKP.prototype.upload = function (publicKeyArmored) { - var uri = this._baseUrl + '/pks/add', - fetch = this._fetch; + var uri = this._baseUrl + '/pks/add'; + var fetch = this._fetch; return fetch(uri, { method: 'post', @@ -13271,32 +35035,89 @@ HKP.prototype.upload = function (publicKeyArmored) { }); }; -},{"./config":10,"node-fetch":"node-fetch"}],37:[function(_dereq_,module,exports){ -'use strict'; +exports.default = HKP; -/** - * Export high level api as default. - * Usage: - * - * import openpgp from 'openpgp.js' - * openpgp.encryptMessage(keys, text) - */ +},{"./config":306,"node-fetch":"node-fetch"}],339:[function(_dereq_,module,exports){ +'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.HKP = exports.AsyncProxy = exports.Keyring = exports.crypto = exports.config = exports.enums = exports.armor = exports.Keyid = exports.S2K = exports.MPI = exports.packet = exports.util = exports.cleartext = exports.message = exports.signature = exports.key = undefined; +exports.HKP = exports.AsyncProxy = exports.Keyring = exports.crypto = exports.config = exports.enums = exports.armor = exports.OID = exports.KDFParams = exports.ECDHSymmetricKey = exports.Keyid = exports.S2K = exports.MPI = exports.packet = exports.util = exports.cleartext = exports.message = exports.signature = exports.key = exports.destroyWorker = exports.getWorker = exports.initWorker = exports.decryptSessionKeys = exports.encryptSessionKey = exports.decryptKey = exports.reformatKey = exports.generateKey = exports.verify = exports.sign = exports.decrypt = exports.encrypt = undefined; var _openpgp = _dereq_('./openpgp'); -Object.keys(_openpgp).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _openpgp[key]; - } - }); +Object.defineProperty(exports, 'encrypt', { + enumerable: true, + get: function get() { + return _openpgp.encrypt; + } +}); +Object.defineProperty(exports, 'decrypt', { + enumerable: true, + get: function get() { + return _openpgp.decrypt; + } +}); +Object.defineProperty(exports, 'sign', { + enumerable: true, + get: function get() { + return _openpgp.sign; + } +}); +Object.defineProperty(exports, 'verify', { + enumerable: true, + get: function get() { + return _openpgp.verify; + } +}); +Object.defineProperty(exports, 'generateKey', { + enumerable: true, + get: function get() { + return _openpgp.generateKey; + } +}); +Object.defineProperty(exports, 'reformatKey', { + enumerable: true, + get: function get() { + return _openpgp.reformatKey; + } +}); +Object.defineProperty(exports, 'decryptKey', { + enumerable: true, + get: function get() { + return _openpgp.decryptKey; + } +}); +Object.defineProperty(exports, 'encryptSessionKey', { + enumerable: true, + get: function get() { + return _openpgp.encryptSessionKey; + } +}); +Object.defineProperty(exports, 'decryptSessionKeys', { + enumerable: true, + get: function get() { + return _openpgp.decryptSessionKeys; + } +}); +Object.defineProperty(exports, 'initWorker', { + enumerable: true, + get: function get() { + return _openpgp.initWorker; + } +}); +Object.defineProperty(exports, 'getWorker', { + enumerable: true, + get: function get() { + return _openpgp.getWorker; + } +}); +Object.defineProperty(exports, 'destroyWorker', { + enumerable: true, + get: function get() { + return _openpgp.destroyWorker; + } }); var _util = _dereq_('./util'); @@ -13344,6 +35165,33 @@ Object.defineProperty(exports, 'Keyid', { } }); +var _ecdh_symkey = _dereq_('./type/ecdh_symkey'); + +Object.defineProperty(exports, 'ECDHSymmetricKey', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ecdh_symkey).default; + } +}); + +var _kdf_params = _dereq_('./type/kdf_params'); + +Object.defineProperty(exports, 'KDFParams', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_kdf_params).default; + } +}); + +var _oid = _dereq_('./type/oid'); + +Object.defineProperty(exports, 'OID', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_oid).default; + } +}); + var _armor = _dereq_('./encoding/armor'); Object.defineProperty(exports, 'armor', { @@ -13438,6 +35286,15 @@ exports.default = openpgp; * import { encryptMessage } from 'openpgp.js' * encryptMessage(keys, text) */ +/* eslint-disable import/newline-after-import, import/first */ + +/** + * Export high level api as default. + * Usage: + * + * import openpgp from 'openpgp.js' + * openpgp.encryptMessage(keys, text) + */ /** @@ -13470,7 +35327,710 @@ var cleartext = exports.cleartext = cleartextMod; * @name module:openpgp.util */ -},{"./cleartext":5,"./config/config":9,"./crypto":24,"./encoding/armor":33,"./enums":35,"./hkp":36,"./key":38,"./keyring":39,"./message":42,"./openpgp":43,"./packet":47,"./signature":66,"./type/keyid":67,"./type/mpi":68,"./type/s2k":69,"./util":70,"./worker/async_proxy":71}],38:[function(_dereq_,module,exports){ +},{"./cleartext":303,"./config/config":305,"./crypto":319,"./encoding/armor":335,"./enums":337,"./hkp":338,"./key":340,"./keyring":341,"./message":344,"./openpgp":345,"./packet":349,"./signature":369,"./type/ecdh_symkey":370,"./type/kdf_params":371,"./type/keyid":372,"./type/mpi":373,"./type/oid":374,"./type/s2k":375,"./util":376,"./worker/async_proxy":377}],340:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPreferredSymAlgo = exports.getPreferredHashAlgo = exports.reformat = undefined; + +var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of'); + +var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); + +var _slicedToArray2 = _dereq_('babel-runtime/helpers/slicedToArray'); + +var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Merges signatures from source[attr] to dest[attr] + * @private + * @param {Object} source + * @param {Object} dest + * @param {String} attr + * @param {Function} checkFn optional, signature only merged if true + */ +var mergeSignatures = function () { + var _ref19 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee19(source, dest, attr, checkFn) { + return _regenerator2.default.wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + source = source[attr]; + + if (!source) { + _context19.next = 8; + break; + } + + if (dest[attr].length) { + _context19.next = 6; + break; + } + + dest[attr] = source; + _context19.next = 8; + break; + + case 6: + _context19.next = 8; + return _promise2.default.all(source.map(function () { + var _ref20 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee18(sourceSig) { + return _regenerator2.default.wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + _context18.t1 = !sourceSig.isExpired(); + + if (!_context18.t1) { + _context18.next = 8; + break; + } + + _context18.t2 = !checkFn; + + if (_context18.t2) { + _context18.next = 7; + break; + } + + _context18.next = 6; + return checkFn(sourceSig); + + case 6: + _context18.t2 = _context18.sent; + + case 7: + _context18.t1 = _context18.t2; + + case 8: + _context18.t0 = _context18.t1; + + if (!_context18.t0) { + _context18.next = 11; + break; + } + + _context18.t0 = !dest[attr].some(function (destSig) { + return _util2.default.equalsUint8Array(destSig.signature, sourceSig.signature); + }); + + case 11: + if (!_context18.t0) { + _context18.next = 13; + break; + } + + dest[attr].push(sourceSig); + + case 13: + case 'end': + return _context18.stop(); + } + } + }, _callee18, this); + })); + + return function (_x32) { + return _ref20.apply(this, arguments); + }; + }())); + + case 8: + case 'end': + return _context19.stop(); + } + } + }, _callee19, this); + })); + + return function mergeSignatures(_x28, _x29, _x30, _x31) { + return _ref19.apply(this, arguments); + }; +}(); + +// TODO + + +/** + * Reformats and signs an OpenPGP with a given User ID. Currently only supports RSA keys. + * @param {module:key~Key} options.privateKey The private key to reformat + * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign] + * @param {String|Array} options.userIds assumes already in form of "User Name " + If array is used, the first userId is set as primary user Id + * @param {String} options.passphrase The passphrase used to encrypt the resulting private key + * @param {Boolean} [options.unlocked=false] The secret part of the generated key is unlocked + * @param {Number} [options.keyExpirationTime=0] The number of seconds after the key creation time that the key expires + * @returns {Promise} + * @async + * @static + */ +var reformat = exports.reformat = function () { + var _ref44 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee41(options) { + var secretKeyPacket, secretSubkeyPacket, isDecrypted, packetlist, i; + return _regenerator2.default.wrap(function _callee41$(_context41) { + while (1) { + switch (_context41.prev = _context41.next) { + case 0: + secretKeyPacket = void 0; + secretSubkeyPacket = void 0; + + options.keyType = options.keyType || _enums2.default.publicKey.rsa_encrypt_sign; + // RSA Encrypt-Only and RSA Sign-Only are deprecated and SHOULD NOT be generated + + if (!(options.keyType !== _enums2.default.publicKey.rsa_encrypt_sign)) { + _context41.next = 5; + break; + } + + throw new Error('Only RSA Encrypt or Sign supported'); + + case 5: + _context41.prev = 5; + isDecrypted = options.privateKey.getKeyPackets().every(function (keyPacket) { + return keyPacket.isDecrypted; + }); + + if (isDecrypted) { + _context41.next = 10; + break; + } + + _context41.next = 10; + return options.privateKey.decrypt(); + + case 10: + _context41.next = 15; + break; + + case 12: + _context41.prev = 12; + _context41.t0 = _context41['catch'](5); + throw new Error('Key not decrypted'); + + case 15: + + if (!options.passphrase) { + // Key without passphrase is unlocked by definition + options.unlocked = true; + } + if (_util2.default.isString(options.userIds)) { + options.userIds = [options.userIds]; + } + packetlist = options.privateKey.toPacketlist(); + + for (i = 0; i < packetlist.length; i++) { + if (packetlist[i].tag === _enums2.default.packet.secretKey) { + secretKeyPacket = packetlist[i]; + options.keyType = secretKeyPacket.algorithm; + } else if (packetlist[i].tag === _enums2.default.packet.secretSubkey) { + secretSubkeyPacket = packetlist[i]; + options.subkeyType = secretSubkeyPacket.algorithm; + } + } + + if (secretKeyPacket) { + _context41.next = 21; + break; + } + + throw new Error('Key does not contain a secret key packet'); + + case 21: + return _context41.abrupt('return', wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options)); + + case 22: + case 'end': + return _context41.stop(); + } + } + }, _callee41, this, [[5, 12]]); + })); + + return function reformat(_x68) { + return _ref44.apply(this, arguments); + }; +}(); + +var wrapKeyObject = function () { + var _ref45 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee43(secretKeyPacket, secretSubkeyPacket, options) { + var packetlist, dataToSign, subkeySignaturePacket; + return _regenerator2.default.wrap(function _callee43$(_context43) { + while (1) { + switch (_context43.prev = _context43.next) { + case 0: + if (!options.passphrase) { + _context43.next = 6; + break; + } + + _context43.next = 3; + return secretKeyPacket.encrypt(options.passphrase); + + case 3: + if (!secretSubkeyPacket) { + _context43.next = 6; + break; + } + + _context43.next = 6; + return secretSubkeyPacket.encrypt(options.passphrase); + + case 6: + packetlist = new _packet2.default.List(); + + + packetlist.push(secretKeyPacket); + + _context43.next = 10; + return _promise2.default.all(options.userIds.map(function () { + var _ref46 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee42(userId, index) { + var userIdPacket, dataToSign, signaturePacket; + return _regenerator2.default.wrap(function _callee42$(_context42) { + while (1) { + switch (_context42.prev = _context42.next) { + case 0: + userIdPacket = new _packet2.default.Userid(); + + userIdPacket.read(_util2.default.str_to_Uint8Array(userId)); + + dataToSign = {}; + + dataToSign.userid = userIdPacket; + dataToSign.key = secretKeyPacket; + signaturePacket = new _packet2.default.Signature(); + + signaturePacket.signatureType = _enums2.default.signature.cert_generic; + signaturePacket.publicKeyAlgorithm = options.keyType; + _context42.next = 10; + return getPreferredHashAlgo(secretKeyPacket); + + case 10: + signaturePacket.hashAlgorithm = _context42.sent; + + signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]; + signaturePacket.preferredSymmetricAlgorithms = []; + // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) + signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes256); + signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes128); + signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes192); + signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.cast5); + signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.tripledes); + signaturePacket.preferredHashAlgorithms = []; + // prefer fast asm.js implementations (SHA-256). SHA-1 will not be secure much longer...move to bottom of list + signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha256); + signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha512); + signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha1); + signaturePacket.preferredCompressionAlgorithms = []; + signaturePacket.preferredCompressionAlgorithms.push(_enums2.default.compression.zlib); + signaturePacket.preferredCompressionAlgorithms.push(_enums2.default.compression.zip); + if (index === 0) { + signaturePacket.isPrimaryUserID = true; + } + if (_config2.default.integrity_protect) { + signaturePacket.features = []; + signaturePacket.features.push(1); // Modification Detection + } + if (options.keyExpirationTime > 0) { + signaturePacket.keyExpirationTime = options.keyExpirationTime; + signaturePacket.keyNeverExpires = false; + } + _context42.next = 30; + return signaturePacket.sign(secretKeyPacket, dataToSign); + + case 30: + return _context42.abrupt('return', { userIdPacket: userIdPacket, signaturePacket: signaturePacket }); + + case 31: + case 'end': + return _context42.stop(); + } + } + }, _callee42, this); + })); + + return function (_x72, _x73) { + return _ref46.apply(this, arguments); + }; + }())).then(function (list) { + list.forEach(function (_ref47) { + var userIdPacket = _ref47.userIdPacket, + signaturePacket = _ref47.signaturePacket; + + packetlist.push(userIdPacket); + packetlist.push(signaturePacket); + }); + }); + + case 10: + if (!secretSubkeyPacket) { + _context43.next = 26; + break; + } + + dataToSign = {}; + + dataToSign.key = secretKeyPacket; + dataToSign.bind = secretSubkeyPacket; + subkeySignaturePacket = new _packet2.default.Signature(); + + subkeySignaturePacket.signatureType = _enums2.default.signature.subkey_binding; + subkeySignaturePacket.publicKeyAlgorithm = options.keyType; + _context43.next = 19; + return getPreferredHashAlgo(secretSubkeyPacket); + + case 19: + subkeySignaturePacket.hashAlgorithm = _context43.sent; + + subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.encrypt_communication | _enums2.default.keyFlags.encrypt_storage]; + if (options.keyExpirationTime > 0) { + subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime; + subkeySignaturePacket.keyNeverExpires = false; + } + _context43.next = 24; + return subkeySignaturePacket.sign(secretKeyPacket, dataToSign); + + case 24: + + packetlist.push(secretSubkeyPacket); + packetlist.push(subkeySignaturePacket); + + case 26: + + if (!options.unlocked) { + secretKeyPacket.clearPrivateParams(); + if (secretSubkeyPacket) { + secretSubkeyPacket.clearPrivateParams(); + } + } + + return _context43.abrupt('return', new Key(packetlist)); + + case 28: + case 'end': + return _context43.stop(); + } + } + }, _callee43, this); + })); + + return function wrapKeyObject(_x69, _x70, _x71) { + return _ref45.apply(this, arguments); + }; +}(); + +/** + * Checks if a given certificate or binding signature is revoked + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {Object} dataToVerify The data to check + * @param {Array} revocations The revocation signatures to check + * @param {module:packet/signature} signature The certificate or signature to check + * @param {module:packet/public_subkey| + * module:packet/secret_subkey| + * module:packet/public_key| + * module:packet/secret_key} key, optional The key packet to check the signature + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} True if the signature revokes the data + * @async + */ + + +var isDataRevoked = function () { + var _ref48 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee45(primaryKey, dataToVerify, revocations, signature, key) { + var date = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : new Date(); + var normDate, revocationKeyIds; + return _regenerator2.default.wrap(function _callee45$(_context45) { + while (1) { + switch (_context45.prev = _context45.next) { + case 0: + key = key || primaryKey; + normDate = _util2.default.normalizeDate(date); + revocationKeyIds = []; + _context45.next = 5; + return _promise2.default.all(revocations.map(function () { + var _ref49 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee44(revocationSignature) { + return _regenerator2.default.wrap(function _callee44$(_context44) { + while (1) { + switch (_context44.prev = _context44.next) { + case 0: + _context44.t0 = !(_config2.default.revocations_expire && revocationSignature.isExpired(normDate)); + + if (!_context44.t0) { + _context44.next = 8; + break; + } + + _context44.t1 = revocationSignature.verified; + + if (_context44.t1) { + _context44.next = 7; + break; + } + + _context44.next = 6; + return revocationSignature.verify(key, dataToVerify); + + case 6: + _context44.t1 = _context44.sent; + + case 7: + _context44.t0 = _context44.t1; + + case 8: + if (!_context44.t0) { + _context44.next = 11; + break; + } + + // TODO get an identifier of the revoked object instead + revocationKeyIds.push(revocationSignature.issuerKeyId); + return _context44.abrupt('return', true); + + case 11: + return _context44.abrupt('return', false); + + case 12: + case 'end': + return _context44.stop(); + } + } + }, _callee44, this); + })); + + return function (_x80) { + return _ref49.apply(this, arguments); + }; + }())); + + case 5: + if (!signature) { + _context45.next = 8; + break; + } + + signature.revoked = revocationKeyIds.some(function (keyId) { + return keyId.equals(signature.issuerKeyId); + }) ? true : signature.revoked; + return _context45.abrupt('return', signature.revoked); + + case 8: + return _context45.abrupt('return', revocationKeyIds.length > 0); + + case 9: + case 'end': + return _context45.stop(); + } + } + }, _callee45, this); + })); + + return function isDataRevoked(_x74, _x75, _x76, _x77, _x78) { + return _ref48.apply(this, arguments); + }; +}(); + +/** + * Returns the preferred signature hash algorithm of a key + * @param {object} key + * @returns {Promise} + * @async + */ +var getPreferredHashAlgo = exports.getPreferredHashAlgo = function () { + var _ref50 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee46(key) { + var hash_algo, pref_algo, primaryUser, _primaryUser$selfCert; + + return _regenerator2.default.wrap(function _callee46$(_context46) { + while (1) { + switch (_context46.prev = _context46.next) { + case 0: + hash_algo = _config2.default.prefer_hash_algorithm; + pref_algo = hash_algo; + + if (!(key instanceof Key)) { + _context46.next = 8; + break; + } + + _context46.next = 5; + return key.getPrimaryUser(); + + case 5: + primaryUser = _context46.sent; + + if (primaryUser && primaryUser.selfCertification.preferredHashAlgorithms) { + _primaryUser$selfCert = (0, _slicedToArray3.default)(primaryUser.selfCertification.preferredHashAlgorithms, 1); + pref_algo = _primaryUser$selfCert[0]; + + hash_algo = _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo; + } + // disable expiration checks + key = key.getSigningKeyPacket(undefined, null); + + case 8: + switch ((0, _getPrototypeOf2.default)(key)) { + case _packet2.default.SecretKey.prototype: + case _packet2.default.PublicKey.prototype: + case _packet2.default.SecretSubkey.prototype: + case _packet2.default.PublicSubkey.prototype: + switch (key.algorithm) { + case 'ecdh': + case 'ecdsa': + case 'eddsa': + pref_algo = _crypto2.default.publicKey.elliptic.getPreferredHashAlgo(key.params[0]); + } + } + return _context46.abrupt('return', _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo); + + case 10: + case 'end': + return _context46.stop(); + } + } + }, _callee46, this); + })); + + return function getPreferredHashAlgo(_x82) { + return _ref50.apply(this, arguments); + }; +}(); + +/** + * Returns the preferred symmetric algorithm for a set of keys + * @param {Array} keys Set of keys + * @returns {Promise} Preferred symmetric algorithm + * @async + */ + + +var getPreferredSymAlgo = exports.getPreferredSymAlgo = function () { + var _ref51 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee48(keys) { + var prioMap, prefAlgo, algo; + return _regenerator2.default.wrap(function _callee48$(_context48) { + while (1) { + switch (_context48.prev = _context48.next) { + case 0: + prioMap = {}; + _context48.next = 3; + return _promise2.default.all(keys.map(function () { + var _ref52 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee47(key) { + var primaryUser; + return _regenerator2.default.wrap(function _callee47$(_context47) { + while (1) { + switch (_context47.prev = _context47.next) { + case 0: + _context47.next = 2; + return key.getPrimaryUser(); + + case 2: + primaryUser = _context47.sent; + + if (!(!primaryUser || !primaryUser.selfCertification.preferredSymmetricAlgorithms)) { + _context47.next = 5; + break; + } + + return _context47.abrupt('return', _config2.default.encryption_cipher); + + case 5: + primaryUser.selfCertification.preferredSymmetricAlgorithms.forEach(function (algo, index) { + var entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo }); + entry.prio += 64 >> index; + entry.count++; + }); + + case 6: + case 'end': + return _context47.stop(); + } + } + }, _callee47, this); + })); + + return function (_x84) { + return _ref52.apply(this, arguments); + }; + }())); + + case 3: + prefAlgo = { prio: 0, algo: _config2.default.encryption_cipher }; + + for (algo in prioMap) { + try { + if (algo !== _enums2.default.symmetric.plaintext && algo !== _enums2.default.symmetric.idea && // not implemented + _enums2.default.read(_enums2.default.symmetric, algo) && // known algorithm + prioMap[algo].count === keys.length && // available for all keys + prioMap[algo].prio > prefAlgo.prio) { + prefAlgo = prioMap[algo]; + } + } catch (e) {} + } + return _context48.abrupt('return', prefAlgo.algo); + + case 6: + case 'end': + return _context48.stop(); + } + } + }, _callee48, this); + })); + + return function getPreferredSymAlgo(_x83) { + return _ref51.apply(this, arguments); + }; +}(); + +exports.Key = Key; +exports.read = read; +exports.readArmored = readArmored; +exports.generate = generate; + +var _armor = _dereq_('./encoding/armor'); + +var _armor2 = _interopRequireDefault(_armor); + +var _crypto = _dereq_('./crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _packet = _dereq_('./packet'); + +var _packet2 = _interopRequireDefault(_packet); + +var _config = _dereq_('./config'); + +var _config2 = _interopRequireDefault(_config); + +var _enums = _dereq_('./enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('./util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @class + * @classdesc Class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + * @param {module:packet/packetlist} packetlist The packets that form this key + */ + // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -13489,66 +36049,27 @@ var cleartext = exports.cleartext = cleartextMod; // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * @requires config * @requires encoding/armor - * @requires enums + * @requires crypto * @requires packet + * @requires config + * @requires enums + * @requires util * @module key */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Key = Key; -exports.read = read; -exports.readArmored = readArmored; -exports.generate = generate; -exports.reformat = reformat; -exports.getPreferredSymAlgo = getPreferredSymAlgo; - -var _packet = _dereq_('./packet'); - -var _packet2 = _interopRequireDefault(_packet); - -var _enums = _dereq_('./enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -var _armor = _dereq_('./encoding/armor.js'); - -var _armor2 = _interopRequireDefault(_armor); - -var _config = _dereq_('./config'); - -var _config2 = _interopRequireDefault(_config); - -var _util = _dereq_('./util'); - -var _util2 = _interopRequireDefault(_util); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @class - * @classdesc Class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. - * @param {module:packet/packetlist} packetlist The packets that form this key - */ - function Key(packetlist) { if (!(this instanceof Key)) { return new Key(packetlist); } // same data as in packetlist but in structured form this.primaryKey = null; - this.revocationSignature = null; - this.directSignatures = null; - this.users = null; - this.subKeys = null; + this.revocationSignatures = []; + this.directSignatures = []; + this.users = []; + this.subKeys = []; this.packetlist2structure(packetlist); - if (!this.primaryKey || !this.users) { + if (!this.primaryKey || !this.users.length) { throw new Error('Invalid key: need at least key and user ID packet'); } } @@ -13558,7 +36079,9 @@ function Key(packetlist) { * @param {module:packet/packetlist} packetlist The packets that form a key */ Key.prototype.packetlist2structure = function (packetlist) { - var user, primaryKeyId, subKey; + var user = void 0; + var primaryKeyId = void 0; + var subKey = void 0; for (var i = 0; i < packetlist.length; i++) { switch (packetlist[i].tag) { case _enums2.default.packet.publicKey: @@ -13569,17 +36092,11 @@ Key.prototype.packetlist2structure = function (packetlist) { case _enums2.default.packet.userid: case _enums2.default.packet.userAttribute: user = new User(packetlist[i]); - if (!this.users) { - this.users = []; - } this.users.push(user); break; case _enums2.default.packet.publicSubkey: case _enums2.default.packet.secretSubkey: user = null; - if (!this.subKeys) { - this.subKeys = []; - } subKey = new SubKey(packetlist[i]); this.subKeys.push(subKey); break; @@ -13594,34 +36111,19 @@ Key.prototype.packetlist2structure = function (packetlist) { continue; } if (packetlist[i].issuerKeyId.equals(primaryKeyId)) { - if (!user.selfCertifications) { - user.selfCertifications = []; - } user.selfCertifications.push(packetlist[i]); } else { - if (!user.otherCertifications) { - user.otherCertifications = []; - } user.otherCertifications.push(packetlist[i]); } break; case _enums2.default.signature.cert_revocation: if (user) { - if (!user.revocationCertifications) { - user.revocationCertifications = []; - } - user.revocationCertifications.push(packetlist[i]); + user.revocationSignatures.push(packetlist[i]); } else { - if (!this.directSignatures) { - this.directSignatures = []; - } this.directSignatures.push(packetlist[i]); } break; case _enums2.default.signature.key: - if (!this.directSignatures) { - this.directSignatures = []; - } this.directSignatures.push(packetlist[i]); break; case _enums2.default.signature.subkey_binding: @@ -13632,14 +36134,14 @@ Key.prototype.packetlist2structure = function (packetlist) { subKey.bindingSignatures.push(packetlist[i]); break; case _enums2.default.signature.key_revocation: - this.revocationSignature = packetlist[i]; + this.revocationSignatures.push(packetlist[i]); break; case _enums2.default.signature.subkey_revocation: if (!subKey) { _util2.default.print_debug('Dropping subkey revocation signature without preceding subkey packet'); continue; } - subKey.revocationSignature = packetlist[i]; + subKey.revocationSignatures.push(packetlist[i]); break; } break; @@ -13649,45 +36151,55 @@ Key.prototype.packetlist2structure = function (packetlist) { /** * Transforms structured key data to packetlist - * @return {module:packet/packetlist} The packets that form a key + * @returns {module:packet/packetlist} The packets that form a key */ Key.prototype.toPacketlist = function () { var packetlist = new _packet2.default.List(); packetlist.push(this.primaryKey); - packetlist.push(this.revocationSignature); + packetlist.concat(this.revocationSignatures); packetlist.concat(this.directSignatures); - var i; - for (i = 0; i < this.users.length; i++) { - packetlist.concat(this.users[i].toPacketlist()); - } - if (this.subKeys) { - for (i = 0; i < this.subKeys.length; i++) { - packetlist.concat(this.subKeys[i].toPacketlist()); - } - } + this.users.map(function (user) { + return packetlist.concat(user.toPacketlist()); + }); + this.subKeys.map(function (subKey) { + return packetlist.concat(subKey.toPacketlist()); + }); return packetlist; }; /** - * Returns all the private and public subkey packets - * @returns {Array<(module:packet/public_subkey|module:packet/secret_subkey)>} + * Returns packetlist containing all public or private subkey packets matching keyId; + * If keyId is not present, returns all subkey packets. + * @param {type/keyid} keyId + * @returns {module:packet/packetlist} */ Key.prototype.getSubkeyPackets = function () { - var subKeys = []; - if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { - subKeys.push(this.subKeys[i].subKey); + var keyId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + + var packets = new _packet2.default.List(); + this.subKeys.forEach(function (subKey) { + if (!keyId || subKey.subKey.getKeyId().equals(keyId, true)) { + packets.push(subKey.subKey); } - } - return subKeys; + }); + return packets; }; /** - * Returns all the private and public key and subkey packets - * @returns {Array<(module:packet/public_subkey|module:packet/secret_subkey|module:packet/secret_key|module:packet/public_key)>} + * Returns a packetlist containing all public or private key packets matching keyId. + * If keyId is not present, returns all key packets starting with the primary key. + * @param {type/keyid} keyId + * @returns {module:packet/packetlist} */ -Key.prototype.getAllKeyPackets = function () { - return [this.primaryKey].concat(this.getSubkeyPackets()); +Key.prototype.getKeyPackets = function () { + var keyId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + + var packets = new _packet2.default.List(); + if (!keyId || this.primaryKey.getKeyId().equals(keyId, true)) { + packets.push(this.primaryKey); + } + packets.concat(this.getSubkeyPackets(keyId)); + return packets; }; /** @@ -13695,50 +36207,26 @@ Key.prototype.getAllKeyPackets = function () { * @returns {Array} */ Key.prototype.getKeyIds = function () { - var keyIds = []; - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - keyIds.push(keys[i].getKeyId()); - } - return keyIds; -}; - -/** - * Returns first key packet for given array of key IDs - * @param {Array} keyIds - * @return {(module:packet/public_subkey|module:packet/public_key| - * module:packet/secret_subkey|module:packet/secret_key|null)} - */ -Key.prototype.getKeyPacket = function (keyIds) { - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - var keyId = keys[i].getKeyId(); - for (var j = 0; j < keyIds.length; j++) { - if (keyId.equals(keyIds[j])) { - return keys[i]; - } - } - } - return null; + return this.getKeyPackets().map(function (keyPacket) { + return keyPacket.getKeyId(); + }); }; /** * Returns userids - * @return {Array} array of userids + * @returns {Array} array of userids */ Key.prototype.getUserIds = function () { - var userids = []; - for (var i = 0; i < this.users.length; i++) { - if (this.users[i].userId) { - userids.push(_util2.default.Uint8Array2str(this.users[i].userId.write())); - } - } - return userids; + return this.users.map(function (user) { + return user.userId ? _util2.default.encode_utf8(user.userId.userid) : null; + }).filter(function (userid) { + return userid !== null; + }); }; /** * Returns true if this is a public key - * @return {Boolean} + * @returns {Boolean} */ Key.prototype.isPublic = function () { return this.primaryKey.tag === _enums2.default.packet.publicKey; @@ -13746,7 +36234,7 @@ Key.prototype.isPublic = function () { /** * Returns true if this is a private key - * @return {Boolean} + * @returns {Boolean} */ Key.prototype.isPrivate = function () { return this.primaryKey.tag === _enums2.default.packet.secretKey; @@ -13754,23 +36242,25 @@ Key.prototype.isPrivate = function () { /** * Returns key as public key (shallow copy) - * @return {module:key~Key} new public Key + * @returns {module:key~Key} new public Key */ Key.prototype.toPublic = function () { var packetlist = new _packet2.default.List(); var keyPackets = this.toPacketlist(); - var bytes; + var bytes = void 0; + var pubKeyPacket = void 0; + var pubSubkeyPacket = void 0; for (var i = 0; i < keyPackets.length; i++) { switch (keyPackets[i].tag) { case _enums2.default.packet.secretKey: bytes = keyPackets[i].writePublicKey(); - var pubKeyPacket = new _packet2.default.PublicKey(); + pubKeyPacket = new _packet2.default.PublicKey(); pubKeyPacket.read(bytes); packetlist.push(pubKeyPacket); break; case _enums2.default.packet.secretSubkey: bytes = keyPackets[i].writePublicKey(); - var pubSubkeyPacket = new _packet2.default.PublicSubkey(); + pubSubkeyPacket = new _packet2.default.PublicSubkey(); pubSubkeyPacket.read(bytes); packetlist.push(pubSubkeyPacket); break; @@ -13783,413 +36273,1262 @@ Key.prototype.toPublic = function () { /** * Returns ASCII armored text of key - * @return {String} ASCII armor + * @returns {String} ASCII armor */ Key.prototype.armor = function () { var type = this.isPublic() ? _enums2.default.armor.public_key : _enums2.default.armor.private_key; return _armor2.default.encode(type, this.toPacketlist().write()); }; -/** - * Returns first key packet or key packet by given keyId that is available for signing or signature verification - * @param {module:type/keyid} keyId, optional - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {(module:packet/secret_subkey|module:packet/secret_key|null)} key packet or null if no signing key has been found - */ -Key.prototype.getSigningKeyPacket = function (keyId) { - var allowExpired = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - var primaryUser = this.getPrimaryUser(allowExpired); - if (primaryUser && isValidSigningKeyPacket(this.primaryKey, primaryUser.selfCertificate) && (!keyId || this.primaryKey.getKeyId().equals(keyId)) && this.verifyPrimaryKey(allowExpired) === _enums2.default.keyStatus.valid) { - return this.primaryKey; - } - if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { - if (this.subKeys[i].isValidSigningKey(this.primaryKey, allowExpired) && (!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId))) { - return this.subKeys[i].subKey; - } - } - } - return null; -}; - -/** - * Returns preferred signature hash algorithm of this key - * @return {String} - */ -Key.prototype.getPreferredHashAlgorithm = function () { - var primaryUser = this.getPrimaryUser(); - if (primaryUser && primaryUser.selfCertificate.preferredHashAlgorithms) { - return primaryUser.selfCertificate.preferredHashAlgorithms[0]; - } - return _config2.default.prefer_hash_algorithm; -}; - -function isValidEncryptionKeyPacket(keyPacket, signature) { - return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.dsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_sign) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_communication) !== 0 || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_storage) !== 0); -} - function isValidSigningKeyPacket(keyPacket, signature) { - return (keyPacket.algorithm === _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.dsa) || keyPacket.algorithm === _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_sign) || keyPacket.algorithm === _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_encrypt_sign)) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.sign_data) !== 0); + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + + return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_encrypt) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.elgamal) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdh) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.sign_data) !== 0) && signature.verified && !signature.revoked && !signature.isExpired(date) && !isDataExpired(keyPacket, signature, date); } /** - * Returns the first valid encryption key packet for this key - * @returns {(module:packet/public_subkey|module:packet/secret_subkey|module:packet/secret_key|module:packet/public_key|null)} key packet or null if no encryption key has been found + * Returns first key packet or key packet by given keyId that is available for signing and verification + * @param {module:type/keyid} keyId, optional + * @param {Date} date use the given date for verification instead of the current time + * @returns {Promise} key packet or null if no signing key has been found + * @async */ -Key.prototype.getEncryptionKeyPacket = function () { - // V4: by convention subkeys are preferred for encryption service - // V3: keys MUST NOT have subkeys - if (this.subKeys) { - for (var i = 0; i < this.subKeys.length; i++) { - if (this.subKeys[i].isValidEncryptionKey(this.primaryKey)) { - return this.subKeys[i].subKey; - } - } - } - // if no valid subkey for encryption, evaluate primary key - var primaryUser = this.getPrimaryUser(); - if (primaryUser && primaryUser.selfCertificate && !primaryUser.selfCertificate.isExpired() && isValidEncryptionKeyPacket(this.primaryKey, primaryUser.selfCertificate)) { - return this.primaryKey; - } - return null; -}; +Key.prototype.getSigningKeyPacket = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() { + var keyId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); + var primaryKey, primaryUser, i, j; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + primaryKey = this.primaryKey; + _context.next = 3; + return this.getPrimaryUser(date); -/** - * Encrypts all secret key and subkey packets - * @param {String} passphrase - */ -Key.prototype.encrypt = function (passphrase) { - if (!this.isPrivate()) { - throw new Error("Nothing to encrypt in a public key"); - } + case 3: + primaryUser = _context.sent; + _context.t0 = primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, date); - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - keys[i].encrypt(passphrase); - keys[i].clearPrivateMPIs(); - } -}; + if (!_context.t0) { + _context.next = 9; + break; + } -/** - * Decrypts all secret key and subkey packets - * @param {String} passphrase - * @return {Boolean} true if all key and subkey packets decrypted successfully - */ -Key.prototype.decrypt = function (passphrase) { - if (this.isPrivate()) { - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - var success = keys[i].decrypt(passphrase); - if (!success) { - return false; - } - } - } else { - throw new Error("Nothing to decrypt in a public key"); - } - return true; -}; + _context.next = 8; + return this.verifyPrimaryKey(date); -/** - * Decrypts specific key packets by key ID - * @param {Array} keyIds - * @param {String} passphrase - * @return {Boolean} true if all key packets decrypted successfully - */ -Key.prototype.decryptKeyPacket = function (keyIds, passphrase) { - if (this.isPrivate()) { - var keys = this.getAllKeyPackets(); - for (var i = 0; i < keys.length; i++) { - var keyId = keys[i].getKeyId(); - for (var j = 0; j < keyIds.length; j++) { - if (keyId.equals(keyIds[j])) { - var success = keys[i].decrypt(passphrase); - if (!success) { - return false; - } + case 8: + _context.t0 = _context.sent; + + case 9: + if (!_context.t0) { + _context.next = 11; + break; + } + + return _context.abrupt('return', primaryKey); + + case 11: + i = 0; + + case 12: + if (!(i < this.subKeys.length)) { + _context.next = 26; + break; + } + + if (!(!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId))) { + _context.next = 23; + break; + } + + _context.next = 16; + return this.subKeys[i].verify(primaryKey, date); + + case 16: + j = 0; + + case 17: + if (!(j < this.subKeys[i].bindingSignatures.length)) { + _context.next = 23; + break; + } + + if (!isValidSigningKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], date)) { + _context.next = 20; + break; + } + + return _context.abrupt('return', this.subKeys[i].subKey); + + case 20: + j++; + _context.next = 17; + break; + + case 23: + i++; + _context.next = 12; + break; + + case 26: + return _context.abrupt('return', null); + + case 27: + case 'end': + return _context.stop(); } } - } - } else { - throw new Error("Nothing to decrypt in a public key"); - } - return true; -}; + }, _callee, this); + })); + + return function () { + return _ref.apply(this, arguments); + }; +}(); + +function isValidEncryptionKeyPacket(keyPacket, signature) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + + var normDate = _util2.default.normalizeDate(date); + return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.dsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_sign) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.eddsa) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_communication) !== 0 || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_storage) !== 0) && signature.verified && !signature.revoked && !signature.isExpired(date) && !isDataExpired(keyPacket, signature, date); +} + +/** + * Returns first key packet or key packet by given keyId that is available for encryption or decryption + * @param {module:type/keyid} keyId, optional + * @param {Date} date, optional + * @returns {Promise} key packet or null if no encryption key has been found + * @async + */ +Key.prototype.getEncryptionKeyPacket = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(keyId) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); + var primaryKey, i, j, primaryUser; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + primaryKey = this.primaryKey; + // V4: by convention subkeys are preferred for encryption service + // V3: keys MUST NOT have subkeys + + i = 0; + + case 2: + if (!(i < this.subKeys.length)) { + _context2.next = 16; + break; + } + + if (!(!keyId || this.subKeys[i].subKey.getKeyId().equals(keyId))) { + _context2.next = 13; + break; + } + + _context2.next = 6; + return this.subKeys[i].verify(primaryKey, date); + + case 6: + j = 0; + + case 7: + if (!(j < this.subKeys[i].bindingSignatures.length)) { + _context2.next = 13; + break; + } + + if (!isValidEncryptionKeyPacket(this.subKeys[i].subKey, this.subKeys[i].bindingSignatures[j], date)) { + _context2.next = 10; + break; + } + + return _context2.abrupt('return', this.subKeys[i].subKey); + + case 10: + j++; + _context2.next = 7; + break; + + case 13: + i++; + _context2.next = 2; + break; + + case 16: + _context2.next = 18; + return this.getPrimaryUser(date); + + case 18: + primaryUser = _context2.sent; + _context2.t0 = primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification, date); + + if (!_context2.t0) { + _context2.next = 24; + break; + } + + _context2.next = 23; + return this.verifyPrimaryKey(date); + + case 23: + _context2.t0 = _context2.sent; + + case 24: + if (!_context2.t0) { + _context2.next = 26; + break; + } + + return _context2.abrupt('return', primaryKey); + + case 26: + return _context2.abrupt('return', null); + + case 27: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x7) { + return _ref2.apply(this, arguments); + }; +}(); + +/** + * Encrypts all secret key and subkey packets matching keyId + * @param {module:type/keyid} keyId + * @param {String} passphrase + * @returns {Promise>} + * @async + */ +Key.prototype.encrypt = function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(passphrase) { + var keyId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (this.isPrivate()) { + _context4.next = 2; + break; + } + + throw new Error("Nothing to encrypt in a public key"); + + case 2: + return _context4.abrupt('return', _promise2.default.all(this.getKeyPackets(keyId).map(function () { + var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(keyPacket) { + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return keyPacket.encrypt(passphrase); + + case 2: + _context3.next = 4; + return keyPacket.clearPrivateParams(); + + case 4: + return _context3.abrupt('return', keyPacket); + + case 5: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x11) { + return _ref4.apply(this, arguments); + }; + }()))); + + case 3: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function (_x9) { + return _ref3.apply(this, arguments); + }; +}(); + +/** + * Decrypts all secret key and subkey packets matching keyId + * @param {String} passphrase + * @param {module:type/keyid} keyId + * @returns {Promise} true if all matching key and subkey packets decrypted successfully + * @async + */ +Key.prototype.decrypt = function () { + var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(passphrase) { + var keyId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var results; + return _regenerator2.default.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + if (this.isPrivate()) { + _context6.next = 2; + break; + } + + throw new Error("Nothing to decrypt in a public key"); + + case 2: + _context6.next = 4; + return _promise2.default.all(this.getKeyPackets(keyId).map(function () { + var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(keyPacket) { + return _regenerator2.default.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + return _context5.abrupt('return', keyPacket.decrypt(passphrase)); + + case 1: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this); + })); + + return function (_x14) { + return _ref6.apply(this, arguments); + }; + }())); + + case 4: + results = _context6.sent; + return _context6.abrupt('return', results.every(function (result) { + return result === true; + })); + + case 6: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this); + })); + + return function (_x12) { + return _ref5.apply(this, arguments); + }; +}(); + +/** + * Checks if a signature on a key is revoked + * @param {module:packet/secret_key| + * @param {module:packet/signature} signature The signature to verify + * @param {module:packet/public_subkey| + * module:packet/secret_subkey| + * module:packet/public_key| + * module:packet/secret_key} key, optional The key to verify the signature + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} True if the certificate is revoked + * @async + */ +Key.prototype.isRevoked = function () { + var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(signature, key) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + return _regenerator2.default.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + return _context7.abrupt('return', isDataRevoked(this.primaryKey, { key: this.primaryKey }, this.revocationSignatures, signature, key, date)); + + case 1: + case 'end': + return _context7.stop(); + } + } + }, _callee7, this); + })); + + return function (_x15, _x16) { + return _ref7.apply(this, arguments); + }; +}(); + +/** + * Returns a packetlist containing all verified public or private key packets matching keyId. + * If keyId is not present, returns all verified key packets starting with the primary key. + * Verification is in the context of given date. + * @param {type/keyid} keyId + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} + * @async + */ +Key.prototype.verifyKeyPackets = function () { + var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee9() { + var _this = this; + + var keyId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); + var packets, primaryKey; + return _regenerator2.default.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + packets = new _packet2.default.List(); + primaryKey = this.primaryKey; + _context9.next = 4; + return this.verifyPrimaryKey(date); + + case 4: + if (!_context9.sent) { + _context9.next = 6; + break; + } + + if (!keyId || primaryKey.getKeyId().equals(keyId)) { + packets.push(primaryKey); + } + + case 6: + _context9.next = 8; + return _promise2.default.all(this.subKeys.map(function () { + var _ref9 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8(subKey) { + return _regenerator2.default.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + if (!(!keyId || subKey.subKey.getKeyId().equals(keyId))) { + _context8.next = 5; + break; + } + + _context8.next = 3; + return subKey.verify(primaryKey, date); + + case 3: + if (!_context8.sent) { + _context8.next = 5; + break; + } + + packets.push(subKey.subKey); + + case 5: + case 'end': + return _context8.stop(); + } + } + }, _callee8, _this); + })); + + return function (_x20) { + return _ref9.apply(this, arguments); + }; + }())); + + case 8: + return _context9.abrupt('return', packets); + + case 9: + case 'end': + return _context9.stop(); + } + } + }, _callee9, this); + })); + + return function () { + return _ref8.apply(this, arguments); + }; +}(); /** * Verify primary key. Checks for revocation signatures, expiration time * and valid self signature - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {module:enums.keyStatus} The status of the primary key + * @param {Date} date (optional) use the given date for verification instead of the current time + * @returns {Promise} The status of the primary key + * @async */ Key.prototype.verifyPrimaryKey = function () { - var allowExpired = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var _ref10 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee10() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); - // check revocation signature - if (this.revocationSignature && !this.revocationSignature.isExpired() && (this.revocationSignature.verified || this.revocationSignature.verify(this.primaryKey, { key: this.primaryKey }))) { - return _enums2.default.keyStatus.revoked; - } - // check V3 expiration time - if (!allowExpired && this.primaryKey.version === 3 && this.primaryKey.expirationTimeV3 !== 0 && Date.now() > this.primaryKey.created.getTime() + this.primaryKey.expirationTimeV3 * 24 * 3600 * 1000) { - return _enums2.default.keyStatus.expired; - } - // check for at least one self signature. Self signature of user ID not mandatory - // See {@link https://tools.ietf.org/html/rfc4880#section-11.1} - var selfSigned = false; - for (var i = 0; i < this.users.length; i++) { - if (this.users[i].userId && this.users[i].selfCertifications) { - selfSigned = true; - } - } - if (!selfSigned) { - return _enums2.default.keyStatus.no_self_cert; - } - // check for valid self signature - var primaryUser = this.getPrimaryUser(); - if (!primaryUser) { - return _enums2.default.keyStatus.invalid; - } - // check V4 expiration time - if (!allowExpired && this.primaryKey.version === 4 && primaryUser.selfCertificate.keyNeverExpires === false && Date.now() > this.primaryKey.created.getTime() + primaryUser.selfCertificate.keyExpirationTime * 1000) { - return _enums2.default.keyStatus.expired; - } - return _enums2.default.keyStatus.valid; -}; + var primaryKey, _ref11, user, selfCertification, currentTime; + + return _regenerator2.default.wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + primaryKey = this.primaryKey; + // check for key revocation signatures + + _context10.next = 3; + return this.isRevoked(null, null, date); + + case 3: + if (!_context10.sent) { + _context10.next = 5; + break; + } + + return _context10.abrupt('return', _enums2.default.keyStatus.revoked); + + case 5: + if (this.users.some(function (user) { + return user.userId && user.selfCertifications.length; + })) { + _context10.next = 7; + break; + } + + return _context10.abrupt('return', _enums2.default.keyStatus.no_self_cert); + + case 7: + _context10.next = 9; + return this.getPrimaryUser(date); + + case 9: + _context10.t0 = _context10.sent; + + if (_context10.t0) { + _context10.next = 12; + break; + } + + _context10.t0 = {}; + + case 12: + _ref11 = _context10.t0; + user = _ref11.user; + selfCertification = _ref11.selfCertification; + + if (user) { + _context10.next = 17; + break; + } + + return _context10.abrupt('return', _enums2.default.keyStatus.invalid); + + case 17: + // check for expiration time + currentTime = _util2.default.normalizeDate(date); + + if (!(primaryKey.version === 3 && isDataExpired(primaryKey, null, date) || primaryKey.version === 4 && isDataExpired(primaryKey, selfCertification, date))) { + _context10.next = 20; + break; + } + + return _context10.abrupt('return', _enums2.default.keyStatus.expired); + + case 20: + return _context10.abrupt('return', _enums2.default.keyStatus.valid); + + case 21: + case 'end': + return _context10.stop(); + } + } + }, _callee10, this); + })); + + return function () { + return _ref10.apply(this, arguments); + }; +}(); /** - * Returns the expiration time of the primary key or null if key does not expire - * @return {Date|null} + * Returns the expiration time of the primary key or Infinity if key does not expire + * @returns {Promise} + * @async */ -Key.prototype.getExpirationTime = function () { - if (this.primaryKey.version === 3) { - return getExpirationTime(this.primaryKey); - } - if (this.primaryKey.version === 4) { - var primaryUser = this.getPrimaryUser(); - if (!primaryUser) { - return null; - } - return getExpirationTime(this.primaryKey, primaryUser.selfCertificate); - } -}; +Key.prototype.getExpirationTime = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee11() { + var primaryUser; + return _regenerator2.default.wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + if (!(this.primaryKey.version === 3)) { + _context11.next = 2; + break; + } -function getExpirationTime(keyPacket, selfCertificate) { - // check V3 expiration time - if (keyPacket.version === 3 && keyPacket.expirationTimeV3 !== 0) { - return new Date(keyPacket.created.getTime() + keyPacket.expirationTimeV3 * 24 * 3600 * 1000); - } - // check V4 expiration time - if (keyPacket.version === 4 && selfCertificate.keyNeverExpires === false) { - return new Date(keyPacket.created.getTime() + selfCertificate.keyExpirationTime * 1000); - } - return null; -} + return _context11.abrupt('return', getExpirationTime(this.primaryKey)); + + case 2: + if (!(this.primaryKey.version === 4)) { + _context11.next = 9; + break; + } + + _context11.next = 5; + return this.getPrimaryUser(); + + case 5: + primaryUser = _context11.sent; + + if (primaryUser) { + _context11.next = 8; + break; + } + + return _context11.abrupt('return', null); + + case 8: + return _context11.abrupt('return', getExpirationTime(this.primaryKey, primaryUser.selfCertification)); + + case 9: + case 'end': + return _context11.stop(); + } + } + }, _callee11, this); +})); /** * Returns primary user and most significant (latest valid) self signature - * - if multiple users are marked as primary users returns the one with the latest self signature - * - if no primary user is found returns the user with the latest self signature - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {{user: Array, selfCertificate: Array}|null} The primary user and the self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param {Date} date use the given date for verification instead of the current time + * @returns {Promise<{user: Array, + * selfCertification: Array}|undefined>} The primary user and the self signature + * @async */ Key.prototype.getPrimaryUser = function () { - var allowExpired = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var _ref13 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee12() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + var primaryKey, primaryUsers, lastCreated, lastPrimaryUserID, i, user, dataToVerify, j, cert; + return _regenerator2.default.wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + primaryKey = this.primaryKey; + primaryUsers = []; + lastCreated = null; + lastPrimaryUserID = null; + // TODO replace when Promise.forEach is implemented - var primUser = []; - for (var i = 0; i < this.users.length; i++) { - if (!this.users[i].userId || !this.users[i].selfCertifications) { - continue; - } - for (var j = 0; j < this.users[i].selfCertifications.length; j++) { - primUser.push({ index: i, user: this.users[i], selfCertificate: this.users[i].selfCertifications[j] }); - } - } - // sort by primary user flag and signature creation time - primUser = primUser.sort(function (a, b) { - if (a.selfCertificate.isPrimaryUserID > b.selfCertificate.isPrimaryUserID) { - return -1; - } else if (a.selfCertificate.isPrimaryUserID < b.selfCertificate.isPrimaryUserID) { - return 1; - } else if (a.selfCertificate.created > b.selfCertificate.created) { - return -1; - } else if (a.selfCertificate.created < b.selfCertificate.created) { - return 1; - } else { - return 0; - } - }); - // return first valid - for (var k = 0; k < primUser.length; k++) { - if (primUser[k].user.isValidSelfCertificate(this.primaryKey, primUser[k].selfCertificate, allowExpired)) { - return primUser[k]; - } - } - return null; -}; + i = 0; + + case 5: + if (!(i < this.users.length)) { + _context12.next = 40; + break; + } + + user = this.users[i]; + + if (user.userId) { + _context12.next = 9; + break; + } + + return _context12.abrupt('return'); + + case 9: + dataToVerify = { userid: user.userId, key: primaryKey }; + j = 0; + + case 11: + if (!(j < user.selfCertifications.length)) { + _context12.next = 37; + break; + } + + cert = user.selfCertifications[j]; + // skip if certificate is not the most recent + + if (!(cert.isPrimaryUserID && cert.isPrimaryUserID < lastPrimaryUserID || !lastPrimaryUserID && cert.created < lastCreated)) { + _context12.next = 15; + break; + } + + return _context12.abrupt('continue', 34); + + case 15: + _context12.t0 = cert.verified; + + if (_context12.t0) { + _context12.next = 20; + break; + } + + _context12.next = 19; + return cert.verify(primaryKey, dataToVerify); + + case 19: + _context12.t0 = _context12.sent; + + case 20: + if (_context12.t0) { + _context12.next = 22; + break; + } + + return _context12.abrupt('continue', 34); + + case 22: + _context12.t1 = cert.revoked; + + if (_context12.t1) { + _context12.next = 27; + break; + } + + _context12.next = 26; + return user.isRevoked(primaryKey, cert, null, date); + + case 26: + _context12.t1 = _context12.sent; + + case 27: + if (!_context12.t1) { + _context12.next = 29; + break; + } + + return _context12.abrupt('continue', 34); + + case 29: + if (!cert.isExpired(date)) { + _context12.next = 31; + break; + } + + return _context12.abrupt('continue', 34); + + case 31: + lastPrimaryUserID = cert.isPrimaryUserID; + lastCreated = cert.created; + primaryUsers.push({ index: i, user: user, selfCertification: cert }); + + case 34: + j++; + _context12.next = 11; + break; + + case 37: + i++; + _context12.next = 5; + break; + + case 40: + // sort by primary user flag and signature creation time + primaryUsers = primaryUsers.sort(function (a, b) { + var A = a.selfCertification; + var B = b.selfCertification; + return B.isPrimaryUserID - A.isPrimaryUserID || B.created - A.created; + }); + return _context12.abrupt('return', primaryUsers.pop()); + + case 42: + case 'end': + return _context12.stop(); + } + } + }, _callee12, this); + })); + + return function () { + return _ref13.apply(this, arguments); + }; +}(); /** * Update key with new components from specified key with same key ID: * users, subkeys, certificates are merged into the destination key, - * duplicates are ignored. + * duplicates and expired signatures are ignored. + * * If the specified key is a private key and the destination key is public, * the destination key is transformed to a private key. - * @param {module:key~Key} key source key to merge + * @param {module:key~Key} key Source key to merge */ -Key.prototype.update = function (key) { - var that = this; - if (key.verifyPrimaryKey() === _enums2.default.keyStatus.invalid) { - return; - } - if (this.primaryKey.getFingerprint() !== key.primaryKey.getFingerprint()) { - throw new Error('Key update method: fingerprints of keys not equal'); - } - if (this.isPublic() && key.isPrivate()) { - // check for equal subkey packets - var equal = (this.subKeys && this.subKeys.length) === (key.subKeys && key.subKeys.length) && (!this.subKeys || this.subKeys.every(function (destSubKey) { - return key.subKeys.some(function (srcSubKey) { - return destSubKey.subKey.getFingerprint() === srcSubKey.subKey.getFingerprint(); - }); - })); - if (!equal) { - throw new Error('Cannot update public key with private key if subkey mismatch'); - } - this.primaryKey = key.primaryKey; - } - // revocation signature - if (!this.revocationSignature && key.revocationSignature && !key.revocationSignature.isExpired() && (key.revocationSignature.verified || key.revocationSignature.verify(key.primaryKey, { key: key.primaryKey }))) { - this.revocationSignature = key.revocationSignature; - } - // direct signatures - mergeSignatures(key, this, 'directSignatures'); - // users - key.users.forEach(function (srcUser) { - var found = false; - for (var i = 0; i < that.users.length; i++) { - if (srcUser.userId && srcUser.userId.userid === that.users[i].userId.userid || srcUser.userAttribute && srcUser.userAttribute.equals(that.users[i].userAttribute)) { - that.users[i].update(srcUser, that.primaryKey); - found = true; - break; - } - } - if (!found) { - that.users.push(srcUser); - } - }); - // subkeys - if (key.subKeys) { - key.subKeys.forEach(function (srcSubKey) { - var found = false; - for (var i = 0; i < that.subKeys.length; i++) { - if (srcSubKey.subKey.getFingerprint() === that.subKeys[i].subKey.getFingerprint()) { - that.subKeys[i].update(srcSubKey, that.primaryKey); - found = true; - break; +Key.prototype.update = function () { + var _ref14 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee17(key) { + var that, equal; + return _regenerator2.default.wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + that = this; + _context17.next = 3; + return key.verifyPrimaryKey(); + + case 3: + _context17.t0 = _context17.sent; + _context17.t1 = _enums2.default.keyStatus.invalid; + + if (!(_context17.t0 === _context17.t1)) { + _context17.next = 7; + break; + } + + return _context17.abrupt('return'); + + case 7: + if (!(this.primaryKey.getFingerprint() !== key.primaryKey.getFingerprint())) { + _context17.next = 9; + break; + } + + throw new Error('Key update method: fingerprints of keys not equal'); + + case 9: + if (!(this.isPublic() && key.isPrivate())) { + _context17.next = 14; + break; + } + + // check for equal subkey packets + equal = this.subKeys.length === key.subKeys.length && this.subKeys.every(function (destSubKey) { + return key.subKeys.some(function (srcSubKey) { + return destSubKey.subKey.getFingerprint() === srcSubKey.subKey.getFingerprint(); + }); + }); + + if (equal) { + _context17.next = 13; + break; + } + + throw new Error('Cannot update public key with private key if subkey mismatch'); + + case 13: + this.primaryKey = key.primaryKey; + + case 14: + _context17.next = 16; + return mergeSignatures(key, this, 'revocationSignatures', function (srcRevSig) { + return isDataRevoked(that.primaryKey, that, [srcRevSig], null, key.primaryKey); + }); + + case 16: + _context17.next = 18; + return mergeSignatures(key, this, 'directSignatures'); + + case 18: + _context17.next = 20; + return _promise2.default.all(key.users.map(function () { + var _ref15 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee14(srcUser) { + var found; + return _regenerator2.default.wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + found = false; + _context14.next = 3; + return _promise2.default.all(that.users.map(function () { + var _ref16 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee13(dstUser) { + return _regenerator2.default.wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + if (!(srcUser.userId && srcUser.userId.userid === dstUser.userId.userid || srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))) { + _context13.next = 4; + break; + } + + _context13.next = 3; + return dstUser.update(srcUser, that.primaryKey); + + case 3: + found = true; + + case 4: + case 'end': + return _context13.stop(); + } + } + }, _callee13, this); + })); + + return function (_x25) { + return _ref16.apply(this, arguments); + }; + }())); + + case 3: + if (!found) { + that.users.push(srcUser); + } + + case 4: + case 'end': + return _context14.stop(); + } + } + }, _callee14, this); + })); + + return function (_x24) { + return _ref15.apply(this, arguments); + }; + }())); + + case 20: + _context17.next = 22; + return _promise2.default.all(key.subKeys.map(function () { + var _ref17 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee16(srcSubKey) { + var found; + return _regenerator2.default.wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + found = false; + _context16.next = 3; + return _promise2.default.all(that.subKeys.map(function () { + var _ref18 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee15(dstSubKey) { + return _regenerator2.default.wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + if (!(srcSubKey.subKey.getFingerprint() === dstSubKey.subKey.getFingerprint())) { + _context15.next = 4; + break; + } + + _context15.next = 3; + return dstSubKey.update(srcSubKey, that.primaryKey); + + case 3: + found = true; + + case 4: + case 'end': + return _context15.stop(); + } + } + }, _callee15, this); + })); + + return function (_x27) { + return _ref18.apply(this, arguments); + }; + }())); + + case 3: + if (!found) { + that.subKeys.push(srcSubKey); + } + + case 4: + case 'end': + return _context16.stop(); + } + } + }, _callee16, this); + })); + + return function (_x26) { + return _ref17.apply(this, arguments); + }; + }())); + + case 22: + case 'end': + return _context17.stop(); } } - if (!found) { - that.subKeys.push(srcSubKey); - } - }); - } -}; + }, _callee17, this); + })); -/** - * Merges signatures from source[attr] to dest[attr] - * @private - * @param {Object} source - * @param {Object} dest - * @param {String} attr - * @param {Function} checkFn optional, signature only merged if true - */ -function mergeSignatures(source, dest, attr, checkFn) { - source = source[attr]; - if (source) { - if (!dest[attr]) { - dest[attr] = source; - } else { - source.forEach(function (sourceSig) { - if (!sourceSig.isExpired() && (!checkFn || checkFn(sourceSig)) && !dest[attr].some(function (destSig) { - return _util2.default.equalsUint8Array(destSig.signature, sourceSig.signature); - })) { - dest[attr].push(sourceSig); - } - }); - } - } -} - -// TODO -Key.prototype.revoke = function () {}; + return function (_x23) { + return _ref14.apply(this, arguments); + }; +}();Key.prototype.revoke = function () {}; /** * Signs primary user of key * @param {Array} privateKey decrypted private keys for signing - * @return {module:key~Key} new public key with new certificate signature + * @returns {Promise} new public key with new certificate signature + * @async */ -Key.prototype.signPrimaryUser = function (privateKeys) { - var _ref = this.getPrimaryUser() || {}, - index = _ref.index, - user = _ref.user; +Key.prototype.signPrimaryUser = function () { + var _ref21 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee20(privateKeys) { + var _ref22, index, user, userSign, key; - if (!user) { - throw new Error('Could not find primary user'); - } - user = user.sign(this.primaryKey, privateKeys); - var key = new Key(this.toPacketlist()); - key.users[index] = user; - return key; -}; + return _regenerator2.default.wrap(function _callee20$(_context20) { + while (1) { + switch (_context20.prev = _context20.next) { + case 0: + _context20.next = 2; + return this.getPrimaryUser(); + + case 2: + _context20.t0 = _context20.sent; + + if (_context20.t0) { + _context20.next = 5; + break; + } + + _context20.t0 = {}; + + case 5: + _ref22 = _context20.t0; + index = _ref22.index; + user = _ref22.user; + + if (user) { + _context20.next = 10; + break; + } + + throw new Error('Could not find primary user'); + + case 10: + _context20.next = 12; + return user.sign(this.primaryKey, privateKeys); + + case 12: + userSign = _context20.sent; + key = new Key(this.toPacketlist()); + + key.users[index] = userSign; + return _context20.abrupt('return', key); + + case 16: + case 'end': + return _context20.stop(); + } + } + }, _callee20, this); + })); + + return function (_x33) { + return _ref21.apply(this, arguments); + }; +}(); /** * Signs all users of key * @param {Array} privateKeys decrypted private keys for signing - * @return {module:key~Key} new public key with new certificate signature + * @returns {Promise} new public key with new certificate signature + * @async */ -Key.prototype.signAllUsers = function (privateKeys) { - var _this = this; +Key.prototype.signAllUsers = function () { + var _ref23 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee21(privateKeys) { + var that, key; + return _regenerator2.default.wrap(function _callee21$(_context21) { + while (1) { + switch (_context21.prev = _context21.next) { + case 0: + that = this; + key = new Key(this.toPacketlist()); + _context21.next = 4; + return _promise2.default.all(this.users.map(function (user) { + return user.sign(that.primaryKey, privateKeys); + })); - var users = this.users.map(function (user) { - return user.sign(_this.primaryKey, privateKeys); - }); - var key = new Key(this.toPacketlist()); - key.users = users; - return key; -}; + case 4: + key.users = _context21.sent; + return _context21.abrupt('return', key); + + case 6: + case 'end': + return _context21.stop(); + } + } + }, _callee21, this); + })); + + return function (_x34) { + return _ref23.apply(this, arguments); + }; +}(); /** * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. * @param {Array} keys array of keys to verify certificate signatures - * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature + * @returns {Promise>} List of signer's keyid and validity of signature + * @async */ -Key.prototype.verifyPrimaryUser = function (keys) { - var _ref2 = this.getPrimaryUser() || {}, - user = _ref2.user; +Key.prototype.verifyPrimaryUser = function () { + var _ref24 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee22(keys) { + var primaryKey, _ref25, user, results; - if (!user) { - throw new Error('Could not find primary user'); - } - return user.verifyAllSignatures(this.primaryKey, keys); -}; + return _regenerator2.default.wrap(function _callee22$(_context22) { + while (1) { + switch (_context22.prev = _context22.next) { + case 0: + primaryKey = this.primaryKey; + _context22.next = 3; + return this.getPrimaryUser(); + + case 3: + _context22.t0 = _context22.sent; + + if (_context22.t0) { + _context22.next = 6; + break; + } + + _context22.t0 = {}; + + case 6: + _ref25 = _context22.t0; + user = _ref25.user; + + if (user) { + _context22.next = 10; + break; + } + + throw new Error('Could not find primary user'); + + case 10: + if (!keys) { + _context22.next = 16; + break; + } + + _context22.next = 13; + return user.verifyAllCertifications(primaryKey, keys); + + case 13: + _context22.t1 = _context22.sent; + _context22.next = 24; + break; + + case 16: + _context22.t2 = primaryKey.keyid; + _context22.next = 19; + return user.verify(primaryKey); + + case 19: + _context22.t3 = _context22.sent; + _context22.t4 = _enums2.default.keyStatus.valid; + _context22.t5 = _context22.t3 === _context22.t4; + _context22.t6 = { + keyid: _context22.t2, + valid: _context22.t5 + }; + _context22.t1 = [_context22.t6]; + + case 24: + results = _context22.t1; + return _context22.abrupt('return', results); + + case 26: + case 'end': + return _context22.stop(); + } + } + }, _callee22, this); + })); + + return function (_x35) { + return _ref24.apply(this, arguments); + }; +}(); /** * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. * @param {Array} keys array of keys to verify certificate signatures - * @return {Array<({userid: String, keyid: module:type/keyid, valid: Boolean})>} list of userid, signer's keyid and validity of signature + * @returns {Promise>} list of userid, signer's keyid and validity of signature + * @async */ -Key.prototype.verifyAllUsers = function (keys) { - var _this2 = this; +Key.prototype.verifyAllUsers = function () { + var _ref26 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee24(keys) { + var results, primaryKey; + return _regenerator2.default.wrap(function _callee24$(_context24) { + while (1) { + switch (_context24.prev = _context24.next) { + case 0: + results = []; + primaryKey = this.primaryKey; + _context24.next = 4; + return _promise2.default.all(this.users.map(function () { + var _ref27 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee23(user) { + var signatures; + return _regenerator2.default.wrap(function _callee23$(_context23) { + while (1) { + switch (_context23.prev = _context23.next) { + case 0: + if (!keys) { + _context23.next = 6; + break; + } - return this.users.reduce(function (signatures, user) { - return signatures.concat(user.verifyAllSignatures(_this2.primaryKey, keys).map(function (signature) { - return { - userid: user.userId.userid, - keyid: signature.keyid, - valid: signature.valid - }; - })); - }, []); -}; + _context23.next = 3; + return user.verifyAllCertifications(primaryKey, keys); + + case 3: + _context23.t0 = _context23.sent; + _context23.next = 14; + break; + + case 6: + _context23.t1 = primaryKey.keyid; + _context23.next = 9; + return user.verify(primaryKey); + + case 9: + _context23.t2 = _context23.sent; + _context23.t3 = _enums2.default.keyStatus.valid; + _context23.t4 = _context23.t2 === _context23.t3; + _context23.t5 = { + keyid: _context23.t1, + valid: _context23.t4 + }; + _context23.t0 = [_context23.t5]; + + case 14: + signatures = _context23.t0; + + signatures.forEach(function (signature) { + results.push({ + userid: user.userId.userid, + keyid: signature.keyid, + valid: signature.valid + }); + }); + + case 16: + case 'end': + return _context23.stop(); + } + } + }, _callee23, this); + })); + + return function (_x37) { + return _ref27.apply(this, arguments); + }; + }())); + + case 4: + return _context24.abrupt('return', results); + + case 5: + case 'end': + return _context24.stop(); + } + } + }, _callee24, this); + })); + + return function (_x36) { + return _ref26.apply(this, arguments); + }; +}(); /** * @class @@ -14201,170 +37540,548 @@ function User(userPacket) { } this.userId = userPacket.tag === _enums2.default.packet.userid ? userPacket : null; this.userAttribute = userPacket.tag === _enums2.default.packet.userAttribute ? userPacket : null; - this.selfCertifications = null; - this.otherCertifications = null; - this.revocationCertifications = null; + this.selfCertifications = []; + this.otherCertifications = []; + this.revocationSignatures = []; } /** * Transforms structured user data to packetlist - * @return {module:packet/packetlist} + * @returns {module:packet/packetlist} */ User.prototype.toPacketlist = function () { var packetlist = new _packet2.default.List(); packetlist.push(this.userId || this.userAttribute); - packetlist.concat(this.revocationCertifications); + packetlist.concat(this.revocationSignatures); packetlist.concat(this.selfCertifications); packetlist.concat(this.otherCertifications); return packetlist; }; -/** - * Checks if a self signature of the user is revoked - * @param {module:packet/signature} certificate - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @return {Boolean} True if the certificate is revoked - */ -User.prototype.isRevoked = function (certificate, primaryKey) { - if (this.revocationCertifications) { - var that = this; - return this.revocationCertifications.some(function (revCert) { - return revCert.issuerKeyId.equals(certificate.issuerKeyId) && !revCert.isExpired() && (revCert.verified || revCert.verify(primaryKey, { userid: that.userId || that.userAttribute, key: primaryKey })); - }); - } else { - return false; - } -}; - -/** - * Returns true if the self certificate is valid - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @param {module:packet/signature} selfCertificate A self certificate of this user - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {Boolean} - */ -User.prototype.isValidSelfCertificate = function (primaryKey, selfCertificate) { - var allowExpired = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - if (this.isRevoked(selfCertificate, primaryKey)) { - return false; - } - if ((!selfCertificate.isExpired() || allowExpired) && (selfCertificate.verified || selfCertificate.verify(primaryKey, { userid: this.userId || this.userAttribute, key: primaryKey }))) { - return true; - } - return false; -}; - /** * Signs user - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @param {Array} privateKeys decrypted private keys for signing - * @return {module:key~Key} new user with new certificate signatures + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {Array} privateKeys Decrypted private keys for signing + * @returns {Promise} New user with new certificate signatures + * @async */ -User.prototype.sign = function (primaryKey, privateKeys) { - var user, dataToSign, signingKeyPacket, signaturePacket; - dataToSign = {}; - dataToSign.key = primaryKey; - dataToSign.userid = this.userId || this.userAttribute; - user = new User(this.userId || this.userAttribute); - user.otherCertifications = []; - privateKeys.forEach(function (privateKey) { - if (privateKey.isPublic()) { - throw new Error('Need private key for signing'); - } - if (privateKey.primaryKey.getFingerprint() === primaryKey.getFingerprint()) { - throw new Error('Not implemented for self signing'); - } - signingKeyPacket = privateKey.getSigningKeyPacket(); - if (!signingKeyPacket) { - throw new Error('Could not find valid signing key packet'); - } - if (!signingKeyPacket.isDecrypted) { - throw new Error('Private key is not decrypted.'); - } - signaturePacket = new _packet2.default.Signature(); - // Most OpenPGP implementations use generic certification (0x10) - signaturePacket.signatureType = _enums2.default.write(_enums2.default.signature, _enums2.default.signature.cert_generic); - signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]; - signaturePacket.hashAlgorithm = privateKey.getPreferredHashAlgorithm(); - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - signaturePacket.signingKeyId = signingKeyPacket.getKeyId(); - signaturePacket.sign(signingKeyPacket, dataToSign); - user.otherCertifications.push(signaturePacket); - }); - user.update(this, primaryKey); - return user; -}; +User.prototype.sign = function () { + var _ref28 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee26(primaryKey, privateKeys) { + var dataToSign, user; + return _regenerator2.default.wrap(function _callee26$(_context26) { + while (1) { + switch (_context26.prev = _context26.next) { + case 0: + dataToSign = { userid: this.userId || this.userAttribute, key: primaryKey }; + user = new User(dataToSign.userid); + _context26.next = 4; + return _promise2.default.all(privateKeys.map(function () { + var _ref29 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee25(privateKey) { + var signingKeyPacket, signaturePacket; + return _regenerator2.default.wrap(function _callee25$(_context25) { + while (1) { + switch (_context25.prev = _context25.next) { + case 0: + if (!privateKey.isPublic()) { + _context25.next = 2; + break; + } + + throw new Error('Need private key for signing'); + + case 2: + if (!(privateKey.primaryKey.getFingerprint() === primaryKey.getFingerprint())) { + _context25.next = 4; + break; + } + + throw new Error('Not implemented for self signing'); + + case 4: + _context25.next = 6; + return privateKey.getSigningKeyPacket(); + + case 6: + signingKeyPacket = _context25.sent; + + if (signingKeyPacket) { + _context25.next = 9; + break; + } + + throw new Error('Could not find valid signing key packet in key ' + privateKey.primaryKey.getKeyId().toHex()); + + case 9: + if (signingKeyPacket.isDecrypted) { + _context25.next = 11; + break; + } + + throw new Error('Private key is not decrypted.'); + + case 11: + signaturePacket = new _packet2.default.Signature(); + // Most OpenPGP implementations use generic certification (0x10) + + signaturePacket.signatureType = _enums2.default.write(_enums2.default.signature, _enums2.default.signature.cert_generic); + signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]; + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + _context25.next = 17; + return getPreferredHashAlgo(privateKey); + + case 17: + signaturePacket.hashAlgorithm = _context25.sent; + + signaturePacket.signingKeyId = signingKeyPacket.getKeyId(); + signaturePacket.sign(signingKeyPacket, dataToSign); + return _context25.abrupt('return', signaturePacket); + + case 21: + case 'end': + return _context25.stop(); + } + } + }, _callee25, this); + })); + + return function (_x40) { + return _ref29.apply(this, arguments); + }; + }())); + + case 4: + user.otherCertifications = _context26.sent; + _context26.next = 7; + return user.update(this, primaryKey); + + case 7: + return _context26.abrupt('return', user); + + case 8: + case 'end': + return _context26.stop(); + } + } + }, _callee26, this); + })); + + return function (_x38, _x39) { + return _ref28.apply(this, arguments); + }; +}(); /** - * Verifies all user signatures - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @param {Array} keys array of keys to verify certificate signatures - * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature + * Checks if a given certificate of the user is revoked + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {module:packet/signature} certificate The certificate to verify + * @param {module:packet/public_subkey| + * module:packet/secret_subkey| + * module:packet/public_key| + * module:packet/secret_key} key, optional The key to verify the signature + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} True if the certificate is revoked + * @async */ -User.prototype.verifyAllSignatures = function (primaryKey, keys) { - var dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; - var certificates = this.selfCertifications.concat(this.otherCertifications || []); - return certificates.map(function (signaturePacket) { - var keyPackets = keys.filter(function (key) { - return key.getSigningKeyPacket(signaturePacket.issuerKeyId); - }); - var valid = null; - if (keyPackets.length > 0) { - valid = keyPackets.some(function (keyPacket) { - return signaturePacket.verify(keyPacket.primaryKey, dataToVerify); - }); - } - return { keyid: signaturePacket.issuerKeyId, valid: valid }; - }); -}; +User.prototype.isRevoked = function () { + var _ref30 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee27(primaryKey, certificate, key) { + var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Date(); + return _regenerator2.default.wrap(function _callee27$(_context27) { + while (1) { + switch (_context27.prev = _context27.next) { + case 0: + return _context27.abrupt('return', isDataRevoked(primaryKey, { + key: primaryKey, + userid: this.userId || this.userAttribute + }, this.revocationSignatures, certificate, key, date)); + + case 1: + case 'end': + return _context27.stop(); + } + } + }, _callee27, this); + })); + + return function (_x41, _x42, _x43) { + return _ref30.apply(this, arguments); + }; +}(); + +/** + * Verifies the user certificate + * @param {module:packet/secret_key| + module:packet/public_key} primaryKey The primary key packet + * @param {module:packet/signature} certificate A certificate of this user + * @param {Array} keys Array of keys to verify certificate signatures + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} status of the certificate + * @async + */ +User.prototype.verifyCertificate = function () { + var _ref31 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee29(primaryKey, certificate, keys) { + var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Date(); + var that, keyid, dataToVerify, results; + return _regenerator2.default.wrap(function _callee29$(_context29) { + while (1) { + switch (_context29.prev = _context29.next) { + case 0: + that = this; + keyid = certificate.issuerKeyId; + dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + _context29.next = 5; + return _promise2.default.all(keys.map(function () { + var _ref32 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee28(key) { + var keyPacket; + return _regenerator2.default.wrap(function _callee28$(_context28) { + while (1) { + switch (_context28.prev = _context28.next) { + case 0: + if (key.getKeyIds().some(function (id) { + return id.equals(keyid); + })) { + _context28.next = 2; + break; + } + + return _context28.abrupt('return'); + + case 2: + _context28.next = 4; + return key.getSigningKeyPacket(keyid, date); + + case 4: + keyPacket = _context28.sent; + _context28.t0 = certificate.revoked; + + if (_context28.t0) { + _context28.next = 10; + break; + } + + _context28.next = 9; + return that.isRevoked(primaryKey, certificate, keyPacket); + + case 9: + _context28.t0 = _context28.sent; + + case 10: + if (!_context28.t0) { + _context28.next = 12; + break; + } + + return _context28.abrupt('return', _enums2.default.keyStatus.revoked); + + case 12: + _context28.t1 = certificate.verified; + + if (_context28.t1) { + _context28.next = 17; + break; + } + + _context28.next = 16; + return certificate.verify(keyPacket, dataToVerify); + + case 16: + _context28.t1 = _context28.sent; + + case 17: + if (_context28.t1) { + _context28.next = 19; + break; + } + + return _context28.abrupt('return', _enums2.default.keyStatus.invalid); + + case 19: + if (!certificate.isExpired()) { + _context28.next = 21; + break; + } + + return _context28.abrupt('return', _enums2.default.keyStatus.expired); + + case 21: + return _context28.abrupt('return', _enums2.default.keyStatus.valid); + + case 22: + case 'end': + return _context28.stop(); + } + } + }, _callee28, this); + })); + + return function (_x49) { + return _ref32.apply(this, arguments); + }; + }())); + + case 5: + results = _context29.sent; + return _context29.abrupt('return', results.find(function (result) { + return result !== undefined; + })); + + case 7: + case 'end': + return _context29.stop(); + } + } + }, _callee29, this); + })); + + return function (_x45, _x46, _x47) { + return _ref31.apply(this, arguments); + }; +}(); + +/** + * Verifies all user certificates + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {Array} keys Array of keys to verify certificate signatures + * @returns {Promise>} List of signer's keyid and validity of signature + * @async + */ +User.prototype.verifyAllCertifications = function () { + var _ref33 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee31(primaryKey, keys) { + var that, certifications; + return _regenerator2.default.wrap(function _callee31$(_context31) { + while (1) { + switch (_context31.prev = _context31.next) { + case 0: + that = this; + certifications = this.selfCertifications.concat(this.otherCertifications); + return _context31.abrupt('return', _promise2.default.all(certifications.map(function () { + var _ref34 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee30(certification) { + var status; + return _regenerator2.default.wrap(function _callee30$(_context30) { + while (1) { + switch (_context30.prev = _context30.next) { + case 0: + _context30.next = 2; + return that.verifyCertificate(primaryKey, certification, keys); + + case 2: + status = _context30.sent; + return _context30.abrupt('return', { + keyid: certification.issuerKeyId, + valid: status === undefined ? null : status === _enums2.default.keyStatus.valid + }); + + case 4: + case 'end': + return _context30.stop(); + } + } + }, _callee30, this); + })); + + return function (_x52) { + return _ref34.apply(this, arguments); + }; + }()))); + + case 3: + case 'end': + return _context31.stop(); + } + } + }, _callee31, this); + })); + + return function (_x50, _x51) { + return _ref33.apply(this, arguments); + }; +}(); /** * Verify User. Checks for existence of self signatures, revocation signatures * and validity of self signature - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @return {module:enums.keyStatus} status of user + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @returns {Promise} Status of user + * @async */ -User.prototype.verify = function (primaryKey) { - if (!this.selfCertifications) { - return _enums2.default.keyStatus.no_self_cert; - } - var status; - for (var i = 0; i < this.selfCertifications.length; i++) { - if (this.isRevoked(this.selfCertifications[i], primaryKey)) { - status = _enums2.default.keyStatus.revoked; - continue; - } - if (!(this.selfCertifications[i].verified || this.selfCertifications[i].verify(primaryKey, { userid: this.userId || this.userAttribute, key: primaryKey }))) { - status = _enums2.default.keyStatus.invalid; - continue; - } - if (this.selfCertifications[i].isExpired()) { - status = _enums2.default.keyStatus.expired; - continue; - } - status = _enums2.default.keyStatus.valid; - break; - } - return status; -}; +User.prototype.verify = function () { + var _ref35 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee33(primaryKey) { + var that, dataToVerify, results; + return _regenerator2.default.wrap(function _callee33$(_context33) { + while (1) { + switch (_context33.prev = _context33.next) { + case 0: + if (this.selfCertifications.length) { + _context33.next = 2; + break; + } + + return _context33.abrupt('return', _enums2.default.keyStatus.no_self_cert); + + case 2: + that = this; + dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + // TODO replace when Promise.some or Promise.any are implemented + + _context33.t0 = [_enums2.default.keyStatus.invalid]; + _context33.next = 7; + return _promise2.default.all(this.selfCertifications.map(function () { + var _ref36 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee32(selfCertification) { + return _regenerator2.default.wrap(function _callee32$(_context32) { + while (1) { + switch (_context32.prev = _context32.next) { + case 0: + _context32.t0 = selfCertification.revoked; + + if (_context32.t0) { + _context32.next = 5; + break; + } + + _context32.next = 4; + return that.isRevoked(primaryKey, selfCertification); + + case 4: + _context32.t0 = _context32.sent; + + case 5: + if (!_context32.t0) { + _context32.next = 7; + break; + } + + return _context32.abrupt('return', _enums2.default.keyStatus.revoked); + + case 7: + _context32.t1 = selfCertification.verified; + + if (_context32.t1) { + _context32.next = 12; + break; + } + + _context32.next = 11; + return selfCertification.verify(primaryKey, dataToVerify); + + case 11: + _context32.t1 = _context32.sent; + + case 12: + if (_context32.t1) { + _context32.next = 14; + break; + } + + return _context32.abrupt('return', _enums2.default.keyStatus.invalid); + + case 14: + if (!selfCertification.isExpired()) { + _context32.next = 16; + break; + } + + return _context32.abrupt('return', _enums2.default.keyStatus.expired); + + case 16: + return _context32.abrupt('return', _enums2.default.keyStatus.valid); + + case 17: + case 'end': + return _context32.stop(); + } + } + }, _callee32, this); + })); + + return function (_x54) { + return _ref36.apply(this, arguments); + }; + }())); + + case 7: + _context33.t1 = _context33.sent; + results = _context33.t0.concat.call(_context33.t0, _context33.t1); + return _context33.abrupt('return', results.some(function (status) { + return status === _enums2.default.keyStatus.valid; + }) ? _enums2.default.keyStatus.valid : results.pop()); + + case 10: + case 'end': + return _context33.stop(); + } + } + }, _callee33, this); + })); + + return function (_x53) { + return _ref35.apply(this, arguments); + }; +}(); /** * Update user with new components from specified user - * @param {module:key~User} user source user to merge - * @param {module:packet/signature} primaryKey primary key used for validation + * @param {module:key~User} user Source user to merge + * @param {module:packet/secret_key| + module:packet/secret_subkey} primaryKey primary key used for validation */ -User.prototype.update = function (user, primaryKey) { - var that = this; - // self signatures - mergeSignatures(user, this, 'selfCertifications', function (srcSelfSig) { - return srcSelfSig.verified || srcSelfSig.verify(primaryKey, { userid: that.userId || that.userAttribute, key: primaryKey }); - }); - // other signatures - mergeSignatures(user, this, 'otherCertifications'); - // revocation signatures - mergeSignatures(user, this, 'revocationCertifications'); -}; +User.prototype.update = function () { + var _ref37 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee35(user, primaryKey) { + var dataToVerify; + return _regenerator2.default.wrap(function _callee35$(_context35) { + while (1) { + switch (_context35.prev = _context35.next) { + case 0: + dataToVerify = { userid: this.userId || this.userAttribute, key: primaryKey }; + // self signatures + + _context35.next = 3; + return mergeSignatures(user, this, 'selfCertifications', function () { + var _ref38 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee34(srcSelfSig) { + return _regenerator2.default.wrap(function _callee34$(_context34) { + while (1) { + switch (_context34.prev = _context34.next) { + case 0: + return _context34.abrupt('return', srcSelfSig.verified || srcSelfSig.verify(primaryKey, dataToVerify)); + + case 1: + case 'end': + return _context34.stop(); + } + } + }, _callee34, this); + })); + + return function (_x57) { + return _ref38.apply(this, arguments); + }; + }()); + + case 3: + _context35.next = 5; + return mergeSignatures(user, this, 'otherCertifications'); + + case 5: + _context35.next = 7; + return mergeSignatures(user, this, 'revocationSignatures', function (srcRevSig) { + return isDataRevoked(primaryKey, dataToVerify, [srcRevSig]); + }); + + case 7: + case 'end': + return _context35.stop(); + } + } + }, _callee35, this); + })); + + return function (_x55, _x56) { + return _ref37.apply(this, arguments); + }; +}(); /** * @class @@ -14376,119 +38093,190 @@ function SubKey(subKeyPacket) { } this.subKey = subKeyPacket; this.bindingSignatures = []; - this.revocationSignature = null; + this.revocationSignatures = []; } /** * Transforms structured subkey data to packetlist - * @return {module:packet/packetlist} + * @returns {module:packet/packetlist} */ SubKey.prototype.toPacketlist = function () { var packetlist = new _packet2.default.List(); packetlist.push(this.subKey); - packetlist.push(this.revocationSignature); - for (var i = 0; i < this.bindingSignatures.length; i++) { - packetlist.push(this.bindingSignatures[i]); - } + packetlist.concat(this.revocationSignatures); + packetlist.concat(this.bindingSignatures); return packetlist; }; /** - * Returns true if the subkey can be used for encryption - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @return {Boolean} + * Checks if a binding signature of a subkey is revoked + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {module:packet/signature} signature The binding signature to verify + * @param {module:packet/public_subkey| + * module:packet/secret_subkey| + * module:packet/public_key| + * module:packet/secret_key} key, optional The key to verify the signature + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} True if the binding signature is revoked + * @async */ -SubKey.prototype.isValidEncryptionKey = function (primaryKey) { - if (this.verify(primaryKey) !== _enums2.default.keyStatus.valid) { - return false; - } - for (var i = 0; i < this.bindingSignatures.length; i++) { - if (isValidEncryptionKeyPacket(this.subKey, this.bindingSignatures[i])) { - return true; - } - } - return false; -}; +SubKey.prototype.isRevoked = function () { + var _ref39 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee36(primaryKey, signature, key) { + var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Date(); + return _regenerator2.default.wrap(function _callee36$(_context36) { + while (1) { + switch (_context36.prev = _context36.next) { + case 0: + return _context36.abrupt('return', isDataRevoked(primaryKey, { + key: primaryKey, + bind: this.subKey + }, this.revocationSignatures, signature, key, date)); -/** - * Returns true if the subkey can be used for signing of data - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {Boolean} - */ -SubKey.prototype.isValidSigningKey = function (primaryKey) { - var allowExpired = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + case 1: + case 'end': + return _context36.stop(); + } + } + }, _callee36, this); + })); - if (this.verify(primaryKey, allowExpired) !== _enums2.default.keyStatus.valid) { - return false; - } - for (var i = 0; i < this.bindingSignatures.length; i++) { - if (isValidSigningKeyPacket(this.subKey, this.bindingSignatures[i])) { - return true; - } - } - return false; -}; + return function (_x58, _x59, _x60) { + return _ref39.apply(this, arguments); + }; +}(); /** * Verify subkey. Checks for revocation signatures, expiration time * and valid binding signature - * @param {module:packet/secret_key|module:packet/public_key} primaryKey The primary key packet - * @param {Boolean} allowExpired allows signature verification with expired keys - * @return {module:enums.keyStatus} The status of the subkey + * @param {module:packet/secret_key| + * module:packet/public_key} primaryKey The primary key packet + * @param {Date} date Use the given date instead of the current time + * @returns {Promise} The status of the subkey + * @async */ -SubKey.prototype.verify = function (primaryKey) { - var allowExpired = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; +SubKey.prototype.verify = function () { + var _ref40 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee38(primaryKey) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); + var that, dataToVerify, results; + return _regenerator2.default.wrap(function _callee38$(_context38) { + while (1) { + switch (_context38.prev = _context38.next) { + case 0: + that = this; + dataToVerify = { key: primaryKey, bind: this.subKey }; + // check for V3 expiration time - // check subkey revocation signature - if (this.revocationSignature && !this.revocationSignature.isExpired() && (this.revocationSignature.verified || this.revocationSignature.verify(primaryKey, { key: primaryKey, bind: this.subKey }))) { - return _enums2.default.keyStatus.revoked; - } - // check V3 expiration time - if (!allowExpired && this.subKey.version === 3 && this.subKey.expirationTimeV3 !== 0 && Date.now() > this.subKey.created.getTime() + this.subKey.expirationTimeV3 * 24 * 3600 * 1000) { - return _enums2.default.keyStatus.expired; - } - // check subkey binding signatures (at least one valid binding sig needed) - for (var i = 0; i < this.bindingSignatures.length; i++) { - var isLast = i === this.bindingSignatures.length - 1; - var sig = this.bindingSignatures[i]; - // check binding signature is not expired - if (!allowExpired && sig.isExpired()) { - if (isLast) { - return _enums2.default.keyStatus.expired; // last expired binding signature - } else { - continue; - } - } - // check binding signature can verify - if (!(sig.verified || sig.verify(primaryKey, { key: primaryKey, bind: this.subKey }))) { - if (isLast) { - return _enums2.default.keyStatus.invalid; // last invalid binding signature - } else { - continue; - } - } - // check V4 expiration time - if (this.subKey.version === 4) { - if (!allowExpired && sig.keyNeverExpires === false && Date.now() > this.subKey.created.getTime() + sig.keyExpirationTime * 1000) { - if (isLast) { - return _enums2.default.keyStatus.expired; // last V4 expired binding signature - } else { - continue; + if (!(this.subKey.version === 3 && isDataExpired(this.subKey, null, date))) { + _context38.next = 4; + break; + } + + return _context38.abrupt('return', _enums2.default.keyStatus.expired); + + case 4: + _context38.t0 = [_enums2.default.keyStatus.invalid]; + _context38.next = 7; + return _promise2.default.all(this.bindingSignatures.map(function () { + var _ref41 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee37(bindingSignature) { + return _regenerator2.default.wrap(function _callee37$(_context37) { + while (1) { + switch (_context37.prev = _context37.next) { + case 0: + _context37.t0 = bindingSignature.verified; + + if (_context37.t0) { + _context37.next = 5; + break; + } + + _context37.next = 4; + return bindingSignature.verify(primaryKey, dataToVerify); + + case 4: + _context37.t0 = _context37.sent; + + case 5: + if (_context37.t0) { + _context37.next = 7; + break; + } + + return _context37.abrupt('return', _enums2.default.keyStatus.invalid); + + case 7: + _context37.t1 = bindingSignature.revoked; + + if (_context37.t1) { + _context37.next = 12; + break; + } + + _context37.next = 11; + return that.isRevoked(primaryKey, bindingSignature, null, date); + + case 11: + _context37.t1 = _context37.sent; + + case 12: + if (!_context37.t1) { + _context37.next = 14; + break; + } + + return _context37.abrupt('return', _enums2.default.keyStatus.revoked); + + case 14: + if (!bindingSignature.isExpired(date)) { + _context37.next = 16; + break; + } + + return _context37.abrupt('return', _enums2.default.keyStatus.expired); + + case 16: + return _context37.abrupt('return', _enums2.default.keyStatus.valid); + + case 17: + case 'end': + return _context37.stop(); + } + } + }, _callee37, this); + })); + + return function (_x64) { + return _ref41.apply(this, arguments); + }; + }() // found a binding signature that passed all checks + )); + + case 7: + _context38.t1 = _context38.sent; + results = _context38.t0.concat.call(_context38.t0, _context38.t1); + return _context38.abrupt('return', results.some(function (status) { + return status === _enums2.default.keyStatus.valid; + }) ? _enums2.default.keyStatus.valid : results.pop()); + + case 10: + case 'end': + return _context38.stop(); } } - } - return _enums2.default.keyStatus.valid; // found a binding signature that passed all checks - } - return _enums2.default.keyStatus.invalid; // no binding signatures to check -}; + }, _callee38, this); + })); + + return function (_x62) { + return _ref40.apply(this, arguments); + }; +}(); /** - * Returns the expiration time of the subkey or null if key does not expire - * @return {Date|null} + * Returns the expiration time of the subkey or Infinity if key does not expire + * @returns {Date} */ SubKey.prototype.getExpirationTime = function () { - var highest; + var highest = void 0; for (var i = 0; i < this.bindingSignatures.length; i++) { var current = getExpirationTime(this.subKey, this.bindingSignatures[i]); if (current === null) { @@ -14503,39 +38291,143 @@ SubKey.prototype.getExpirationTime = function () { /** * Update subkey with new components from specified subkey - * @param {module:key~SubKey} subKey source subkey to merge - * @param {module:packet/signature} primaryKey primary key used for validation + * @param {module:key~SubKey} subKey Source subkey to merge + * @param {module:packet/secret_key| + module:packet/secret_subkey} primaryKey primary key used for validation */ -SubKey.prototype.update = function (subKey, primaryKey) { - if (subKey.verify(primaryKey) === _enums2.default.keyStatus.invalid) { - return; - } - if (this.subKey.getFingerprint() !== subKey.subKey.getFingerprint()) { - throw new Error('SubKey update method: fingerprints of subkeys not equal'); - } - // key packet - if (this.subKey.tag === _enums2.default.packet.publicSubkey && subKey.subKey.tag === _enums2.default.packet.secretSubkey) { - this.subKey = subKey.subKey; - } - // update missing binding signatures - if (this.bindingSignatures.length < subKey.bindingSignatures.length) { - for (var i = this.bindingSignatures.length; i < subKey.bindingSignatures.length; i++) { - var newSig = subKey.bindingSignatures[i]; - if (newSig.verified || newSig.verify(primaryKey, { key: primaryKey, bind: this.subKey })) { - this.bindingSignatures.push(newSig); +SubKey.prototype.update = function () { + var _ref42 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee40(subKey, primaryKey) { + var that, dataToVerify; + return _regenerator2.default.wrap(function _callee40$(_context40) { + while (1) { + switch (_context40.prev = _context40.next) { + case 0: + _context40.next = 2; + return subKey.verify(primaryKey); + + case 2: + _context40.t0 = _context40.sent; + _context40.t1 = _enums2.default.keyStatus.invalid; + + if (!(_context40.t0 === _context40.t1)) { + _context40.next = 6; + break; + } + + return _context40.abrupt('return'); + + case 6: + if (!(this.subKey.getFingerprint() !== subKey.subKey.getFingerprint())) { + _context40.next = 8; + break; + } + + throw new Error('SubKey update method: fingerprints of subkeys not equal'); + + case 8: + // key packet + if (this.subKey.tag === _enums2.default.packet.publicSubkey && subKey.subKey.tag === _enums2.default.packet.secretSubkey) { + this.subKey = subKey.subKey; + } + // update missing binding signatures + that = this; + dataToVerify = { key: primaryKey, bind: that.subKey }; + _context40.next = 13; + return mergeSignatures(subKey, this, 'bindingSignatures', function () { + var _ref43 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee39(srcBindSig) { + var i; + return _regenerator2.default.wrap(function _callee39$(_context39) { + while (1) { + switch (_context39.prev = _context39.next) { + case 0: + _context39.t0 = srcBindSig.verified; + + if (_context39.t0) { + _context39.next = 5; + break; + } + + _context39.next = 4; + return srcBindSig.verify(primaryKey, dataToVerify); + + case 4: + _context39.t0 = _context39.sent; + + case 5: + if (_context39.t0) { + _context39.next = 7; + break; + } + + return _context39.abrupt('return', false); + + case 7: + i = 0; + + case 8: + if (!(i < that.bindingSignatures.length)) { + _context39.next = 16; + break; + } + + if (!that.bindingSignatures[i].issuerKeyId.equals(srcBindSig.issuerKeyId)) { + _context39.next = 13; + break; + } + + if (!(srcBindSig.created < that.bindingSignatures[i].created)) { + _context39.next = 13; + break; + } + + that.bindingSignatures[i] = srcBindSig; + return _context39.abrupt('return', false); + + case 13: + i++; + _context39.next = 8; + break; + + case 16: + return _context39.abrupt('return', true); + + case 17: + case 'end': + return _context39.stop(); + } + } + }, _callee39, this); + })); + + return function (_x67) { + return _ref43.apply(this, arguments); + }; + }()); + + case 13: + _context40.next = 15; + return mergeSignatures(subKey, this, 'revocationSignatures', function (srcRevSig) { + return isDataRevoked(primaryKey, dataToVerify, [srcRevSig]); + }); + + case 15: + case 'end': + return _context40.stop(); + } } - } - } - // revocation signature - if (!this.revocationSignature && subKey.revocationSignature && !subKey.revocationSignature.isExpired() && (subKey.revocationSignature.verified || subKey.revocationSignature.verify(primaryKey, { key: primaryKey, bind: this.subKey }))) { - this.revocationSignature = subKey.revocationSignature; - } -}; + }, _callee40, this); + })); + + return function (_x65, _x66) { + return _ref42.apply(this, arguments); + }; +}(); /** * Reads an unarmored OpenPGP key list and returns one or multiple key objects * @param {Uint8Array} data to be parsed - * @return {{keys: Array, err: (Array|null)}} result object with key and error arrays + * @returns {{keys: Array, + * err: (Array|null)}} result object with key and error arrays * @static */ function read(data) { @@ -14568,7 +38460,8 @@ function read(data) { /** * Reads an OpenPGP armored text and returns one or multiple key objects * @param {String} armoredText text to be parsed - * @return {{keys: Array, err: (Array|null)}} result object with key and error arrays + * @returns {{keys: Array, + * err: (Array|null)}} result object with key and error arrays * @static */ function readArmored(armoredText) { @@ -14586,7 +38479,7 @@ function readArmored(armoredText) { } /** - * Generates a new OpenPGP key. Currently only supports RSA keys. + * Generates a new OpenPGP key. Supports RSA and ECC keys. * Primary and subkey will be of same type. * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign] to indicate what type of key to make. * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} @@ -14596,210 +38489,100 @@ function readArmored(armoredText) { * @param {String} options.passphrase The passphrase used to encrypt the resulting private key * @param {Boolean} [options.unlocked=false] The secret part of the generated key is unlocked * @param {Number} [options.keyExpirationTime=0] The number of seconds after the key creation time that the key expires - * @return {module:key~Key} + * @returns {Promise} + * @async * @static */ function generate(options) { - var secretKeyPacket, secretSubkeyPacket; - return Promise.resolve().then(function () { - options.keyType = options.keyType || _enums2.default.publicKey.rsa_encrypt_sign; - if (options.keyType !== _enums2.default.publicKey.rsa_encrypt_sign) { + var secretKeyPacket = void 0; + var secretSubkeyPacket = void 0; + return _promise2.default.resolve().then(function () { + if (options.curve) { + try { + options.curve = _enums2.default.write(_enums2.default.curve, options.curve); + } catch (e) { + throw new Error('Not valid curve.'); + } + if (options.curve === _enums2.default.curve.ed25519 || options.curve === _enums2.default.curve.curve25519) { + options.keyType = options.keyType || _enums2.default.publicKey.eddsa; + } else { + options.keyType = options.keyType || _enums2.default.publicKey.ecdsa; + } + options.subkeyType = options.subkeyType || _enums2.default.publicKey.ecdh; + } else if (options.numBits) { + options.keyType = options.keyType || _enums2.default.publicKey.rsa_encrypt_sign; + options.subkeyType = options.subkeyType || _enums2.default.publicKey.rsa_encrypt_sign; + } else { + throw new Error('Key type not specified.'); + } + + if (options.keyType !== _enums2.default.publicKey.rsa_encrypt_sign && options.keyType !== _enums2.default.publicKey.ecdsa && options.keyType !== _enums2.default.publicKey.eddsa) { // RSA Encrypt-Only and RSA Sign-Only are deprecated and SHOULD NOT be generated - throw new Error('Only RSA Encrypt or Sign supported'); + throw new Error('Unsupported key type'); + } + + if (options.subkeyType !== _enums2.default.publicKey.rsa_encrypt_sign && options.subkeyType !== _enums2.default.publicKey.ecdh) { + // RSA Encrypt-Only and RSA Sign-Only are deprecated and SHOULD NOT be generated + throw new Error('Unsupported subkey type'); } if (!options.passphrase) { // Key without passphrase is unlocked by definition options.unlocked = true; } - if (String.prototype.isPrototypeOf(options.userIds) || typeof options.userIds === 'string') { + if (_util2.default.isString(options.userIds)) { options.userIds = [options.userIds]; } - return Promise.all([generateSecretKey(), generateSecretSubkey()]).then(function () { + return _promise2.default.all([generateSecretKey(), generateSecretSubkey()]).then(function () { return wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options); }); }); function generateSecretKey() { secretKeyPacket = new _packet2.default.SecretKey(); + secretKeyPacket.packets = null; secretKeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.keyType); - return secretKeyPacket.generate(options.numBits); + options.curve = options.curve === _enums2.default.curve.curve25519 ? _enums2.default.curve.ed25519 : options.curve; + return secretKeyPacket.generate(options.numBits, options.curve); } function generateSecretSubkey() { secretSubkeyPacket = new _packet2.default.SecretSubkey(); - secretSubkeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.keyType); - return secretSubkeyPacket.generate(options.numBits); + secretKeyPacket.packets = null; + secretSubkeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.subkeyType); + options.curve = options.curve === _enums2.default.curve.ed25519 ? _enums2.default.curve.curve25519 : options.curve; + return secretSubkeyPacket.generate(options.numBits, options.curve); } } -/** - * Reformats and signs an OpenPGP with a given User ID. Currently only supports RSA keys. - * @param {module:key~Key} options.privateKey The private key to reformat - * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign] - * @param {String|Array} options.userIds assumes already in form of "User Name " - If array is used, the first userId is set as primary user Id - * @param {String} options.passphrase The passphrase used to encrypt the resulting private key - * @param {Boolean} [options.unlocked=false] The secret part of the generated key is unlocked - * @param {Number} [options.keyExpirationTime=0] The number of seconds after the key creation time that the key expires - * @return {module:key~Key} - * @static - */ -function reformat(options) { - var secretKeyPacket, secretSubkeyPacket; - return Promise.resolve().then(function () { +function isDataExpired(keyPacket, signature) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); - options.keyType = options.keyType || _enums2.default.publicKey.rsa_encrypt_sign; - if (options.keyType !== _enums2.default.publicKey.rsa_encrypt_sign) { - // RSA Encrypt-Only and RSA Sign-Only are deprecated and SHOULD NOT be generated - throw new Error('Only RSA Encrypt or Sign supported'); - } - - if (!options.privateKey.decrypt()) { - throw new Error('Key not decrypted'); - } - - if (!options.passphrase) { - // Key without passphrase is unlocked by definition - options.unlocked = true; - } - if (String.prototype.isPrototypeOf(options.userIds) || typeof options.userIds === 'string') { - options.userIds = [options.userIds]; - } - var packetlist = options.privateKey.toPacketlist(); - for (var i = 0; i < packetlist.length; i++) { - if (packetlist[i].tag === _enums2.default.packet.secretKey) { - secretKeyPacket = packetlist[i]; - } else if (packetlist[i].tag === _enums2.default.packet.secretSubkey) { - secretSubkeyPacket = packetlist[i]; - } - } - return wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options); - }); + var normDate = _util2.default.normalizeDate(date); + if (normDate !== null) { + var expirationTime = getExpirationTime(keyPacket, signature); + return !(keyPacket.created <= normDate && normDate < expirationTime) || signature && signature.isExpired(date); + } + return false; } -function wrapKeyObject(secretKeyPacket, secretSubkeyPacket, options) { - // set passphrase protection - if (options.passphrase) { - secretKeyPacket.encrypt(options.passphrase); - secretSubkeyPacket.encrypt(options.passphrase); +function getExpirationTime(keyPacket, signature) { + var expirationTime = void 0; + // check V3 expiration time + if (keyPacket.version === 3 && keyPacket.expirationTimeV3 !== 0) { + expirationTime = keyPacket.created.getTime() + keyPacket.expirationTimeV3 * 24 * 3600 * 1000; } - - var packetlist = new _packet2.default.List(); - - packetlist.push(secretKeyPacket); - - options.userIds.forEach(function (userId, index) { - - var userIdPacket = new _packet2.default.Userid(); - userIdPacket.read(_util2.default.str2Uint8Array(userId)); - - var dataToSign = {}; - dataToSign.userid = userIdPacket; - dataToSign.key = secretKeyPacket; - var signaturePacket = new _packet2.default.Signature(); - signaturePacket.signatureType = _enums2.default.signature.cert_generic; - signaturePacket.publicKeyAlgorithm = options.keyType; - signaturePacket.hashAlgorithm = _config2.default.prefer_hash_algorithm; - signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]; - signaturePacket.preferredSymmetricAlgorithms = []; - // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support) - signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes256); - signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes128); - signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.aes192); - signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.cast5); - signaturePacket.preferredSymmetricAlgorithms.push(_enums2.default.symmetric.tripledes); - signaturePacket.preferredHashAlgorithms = []; - // prefer fast asm.js implementations (SHA-256). SHA-1 will not be secure much longer...move to bottom of list - signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha256); - signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha512); - signaturePacket.preferredHashAlgorithms.push(_enums2.default.hash.sha1); - signaturePacket.preferredCompressionAlgorithms = []; - signaturePacket.preferredCompressionAlgorithms.push(_enums2.default.compression.zlib); - signaturePacket.preferredCompressionAlgorithms.push(_enums2.default.compression.zip); - if (index === 0) { - signaturePacket.isPrimaryUserID = true; - } - if (_config2.default.integrity_protect) { - signaturePacket.features = []; - signaturePacket.features.push(1); // Modification Detection - } - if (options.keyExpirationTime > 0) { - signaturePacket.keyExpirationTime = options.keyExpirationTime; - signaturePacket.keyNeverExpires = false; - } - signaturePacket.sign(secretKeyPacket, dataToSign); - - packetlist.push(userIdPacket); - packetlist.push(signaturePacket); - }); - - var dataToSign = {}; - dataToSign.key = secretKeyPacket; - dataToSign.bind = secretSubkeyPacket; - var subkeySignaturePacket = new _packet2.default.Signature(); - subkeySignaturePacket.signatureType = _enums2.default.signature.subkey_binding; - subkeySignaturePacket.publicKeyAlgorithm = options.keyType; - subkeySignaturePacket.hashAlgorithm = _config2.default.prefer_hash_algorithm; - subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.encrypt_communication | _enums2.default.keyFlags.encrypt_storage]; - if (options.keyExpirationTime > 0) { - subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime; - subkeySignaturePacket.keyNeverExpires = false; + // check V4 expiration time + if (keyPacket.version === 4 && signature.keyNeverExpires === false) { + expirationTime = signature.created.getTime() + signature.keyExpirationTime * 1000; } - subkeySignaturePacket.sign(secretKeyPacket, dataToSign); - - packetlist.push(secretSubkeyPacket); - packetlist.push(subkeySignaturePacket); - - if (!options.unlocked) { - secretKeyPacket.clearPrivateMPIs(); - secretSubkeyPacket.clearPrivateMPIs(); - } - - return new Key(packetlist); + return expirationTime ? new Date(expirationTime) : Infinity; } -/** - * Returns the preferred symmetric algorithm for a set of keys - * @param {Array} keys Set of keys - * @return {enums.symmetric} Preferred symmetric algorithm - */ -function getPreferredSymAlgo(keys) { - var prioMap = {}; - keys.forEach(function (key) { - var primaryUser = key.getPrimaryUser(); - if (!primaryUser || !primaryUser.selfCertificate.preferredSymmetricAlgorithms) { - return _config2.default.encryption_cipher; - } - primaryUser.selfCertificate.preferredSymmetricAlgorithms.forEach(function (algo, index) { - var entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo }); - entry.prio += 64 >> index; - entry.count++; - }); - }); - var prefAlgo = { prio: 0, algo: _config2.default.encryption_cipher }; - for (var algo in prioMap) { - try { - if (algo !== _enums2.default.symmetric.plaintext && algo !== _enums2.default.symmetric.idea && // not implemented - _enums2.default.read(_enums2.default.symmetric, algo) && // known algorithm - prioMap[algo].count === keys.length && // available for all keys - prioMap[algo].prio > prefAlgo.prio) { - prefAlgo = prioMap[algo]; - } - } catch (e) {} - } - return prefAlgo.algo; -} - -},{"./config":10,"./encoding/armor.js":33,"./enums.js":35,"./packet":47,"./util":70}],39:[function(_dereq_,module,exports){ +},{"./config":306,"./crypto":319,"./encoding/armor":335,"./enums":337,"./packet":349,"./util":376,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/core-js/promise":25,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/helpers/slicedToArray":33,"babel-runtime/regenerator":35}],341:[function(_dereq_,module,exports){ 'use strict'; -/** - * @see module:keyring/keyring - * @module keyring - */ - Object.defineProperty(exports, "__esModule", { value: true }); @@ -14814,11 +38597,45 @@ var _localstore2 = _interopRequireDefault(_localstore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * @fileoverview Functions dealing with storage of the keyring. + * @see module:keyring/keyring + * @see module:keyring/localstore + * @module keyring + */ _keyring2.default.localstore = _localstore2.default; exports.default = _keyring2.default; -},{"./keyring.js":40,"./localstore.js":41}],40:[function(_dereq_,module,exports){ +},{"./keyring.js":342,"./localstore.js":343}],342:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _key = _dereq_('../key'); + +var _localstore = _dereq_('./localstore'); + +var _localstore2 = _interopRequireDefault(_localstore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Initialization routine for the keyring. + * This method reads the keyring from HTML5 local storage and initializes this instance. + * @constructor + * @param {keyring/localstore} [storeHandler] class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -14837,38 +38654,11 @@ exports.default = _keyring2.default; // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * The class that deals with storage of the keyring. Currently the only option is to use HTML5 local storage. - * @requires enums * @requires key - * @requires util + * @requires keyring/localstore * @module keyring/keyring */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = Keyring; - -var _key = _dereq_('../key.js'); - -var keyModule = _interopRequireWildcard(_key); - -var _localstore = _dereq_('./localstore.js'); - -var _localstore2 = _interopRequireDefault(_localstore); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -/** - * Initialization routine for the keyring. This method reads the - * keyring from HTML5 local storage and initializes this instance. - * @constructor - * @param {class} [storeHandler] class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods - */ function Keyring(storeHandler) { this.storeHandler = storeHandler || new _localstore2.default(); this.publicKeys = new KeyArray(this.storeHandler.loadPublic()); @@ -14896,7 +38686,7 @@ Keyring.prototype.clear = function () { * @param {String} keyId provided as string of lowercase hex number * withouth 0x prefix (can be 16-character key ID or fingerprint) * @param {Boolean} deep if true search also in subkeys - * @return {Array|null} keys found or null + * @returns {Array|null} keys found or null */ Keyring.prototype.getKeysForId = function (keyId, deep) { var result = []; @@ -14909,7 +38699,7 @@ Keyring.prototype.getKeysForId = function (keyId, deep) { * Removes keys having the specified key id from the keyring * @param {String} keyId provided as string of lowercase hex number * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @return {Array|null} keys found or null + * @returns {Array|null} keys found or null */ Keyring.prototype.removeKeysForId = function (keyId) { var result = []; @@ -14920,7 +38710,7 @@ Keyring.prototype.removeKeysForId = function (keyId) { /** * Get all public and private keys - * @return {Array} all keys + * @returns {Array} all keys */ Keyring.prototype.getAllKeys = function () { return this.publicKeys.keys.concat(this.privateKeys.keys); @@ -14937,7 +38727,7 @@ function KeyArray(keys) { /** * Searches all keys in the KeyArray matching the address or address part of the user ids * @param {String} email email address to search for - * @return {Array} The public keys associated with provided email address. + * @returns {Array} The public keys associated with provided email address. */ KeyArray.prototype.getForAddress = function (email) { var results = []; @@ -14954,7 +38744,7 @@ KeyArray.prototype.getForAddress = function (email) { * @private * @param {String} email email address to search for * @param {module:key~Key} key The key to be checked. - * @return {Boolean} True if the email address is defined in the specified key + * @returns {Boolean} True if the email address is defined in the specified key */ function emailCheck(email, key) { email = email.toLowerCase(); @@ -14977,14 +38767,13 @@ function emailCheck(email, key) { * @param {String} keyId provided as string of lowercase hex number * withouth 0x prefix (can be 16-character key ID or fingerprint) * @param {module:packet/secret_key|public_key|public_subkey|secret_subkey} keypacket The keypacket to be checked - * @return {Boolean} True if keypacket has the specified keyid + * @returns {Boolean} True if keypacket has the specified keyid */ function keyIdCheck(keyId, keypacket) { if (keyId.length === 16) { return keyId === keypacket.getKeyId().toHex(); - } else { - return keyId === keypacket.getFingerprint(); } + return keyId === keypacket.getFingerprint(); } /** @@ -14992,14 +38781,14 @@ function keyIdCheck(keyId, keypacket) { * @param {String} keyId provided as string of lowercase hex number * withouth 0x prefix (can be 16-character key ID or fingerprint) * @param {Boolean} deep if true search also in subkeys - * @return {module:key~Key|null} key found or null + * @returns {module:key~Key|null} key found or null */ KeyArray.prototype.getForId = function (keyId, deep) { for (var i = 0; i < this.keys.length; i++) { if (keyIdCheck(keyId, this.keys[i].primaryKey)) { return this.keys[i]; } - if (deep && this.keys[i].subKeys) { + if (deep && this.keys[i].subKeys.length) { for (var j = 0; j < this.keys[i].subKeys.length; j++) { if (keyIdCheck(keyId, this.keys[i].subKeys[j].subKey)) { return this.keys[i]; @@ -15013,28 +38802,72 @@ KeyArray.prototype.getForId = function (keyId, deep) { /** * Imports a key from an ascii armored message * @param {String} armored message to read the keys/key from - * @return {Array|null} array of error objects or null + * @returns {Promise|null>} array of error objects or null + * @async */ -KeyArray.prototype.importKey = function (armored) { - var imported = keyModule.readArmored(armored); - var that = this; - imported.keys.forEach(function (key) { - // check if key already in key array - var keyidHex = key.primaryKey.getKeyId().toHex(); - var keyFound = that.getForId(keyidHex); - if (keyFound) { - keyFound.update(key); - } else { - that.push(key); - } - }); - return imported.err ? imported.err : null; -}; +KeyArray.prototype.importKey = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(armored) { + var imported, that, i, key, keyidHex, keyFound; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + imported = (0, _key.readArmored)(armored); + that = this; + i = 0; + + case 3: + if (!(i < imported.keys.length)) { + _context.next = 16; + break; + } + + key = imported.keys[i]; + // check if key already in key array + + keyidHex = key.primaryKey.getKeyId().toHex(); + keyFound = that.getForId(keyidHex); + + if (!keyFound) { + _context.next = 12; + break; + } + + _context.next = 10; + return keyFound.update(key); + + case 10: + _context.next = 13; + break; + + case 12: + that.push(key); + + case 13: + i++; + _context.next = 3; + break; + + case 16: + return _context.abrupt('return', imported.err ? imported.err : null); + + case 17: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); /** * Add key to KeyArray * @param {module:key~Key} key The key that will be added to the keyring - * @return {Number} The new length of the KeyArray + * @returns {Number} The new length of the KeyArray */ KeyArray.prototype.push = function (key) { return this.keys.push(key); @@ -15044,7 +38877,7 @@ KeyArray.prototype.push = function (key) { * Removes a key with the specified keyid from the keyring * @param {String} keyId provided as string of lowercase hex number * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @return {module:key~Key|null} The key object which has been removed or null + * @returns {module:key~Key|null} The key object which has been removed or null */ KeyArray.prototype.removeForId = function (keyId) { for (var i = 0; i < this.keys.length; i++) { @@ -15055,7 +38888,51 @@ KeyArray.prototype.removeForId = function (keyId) { return null; }; -},{"../key.js":38,"./localstore.js":41}],41:[function(_dereq_,module,exports){ +exports.default = Keyring; + +},{"../key":340,"./localstore":343,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],343:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _stringify = _dereq_('babel-runtime/core-js/json/stringify'); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _config = _dereq_('../config'); + +var _config2 = _interopRequireDefault(_config); + +var _key = _dereq_('../key'); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @constructor + * @param {String} prefix prefix for itemnames in localstore + */ +function LocalStore(prefix) { + prefix = prefix || 'openpgp-'; + this.publicKeysItem = prefix + this.publicKeysItem; + this.privateKeysItem = prefix + this.privateKeysItem; + if (typeof window !== 'undefined' && window.localStorage) { + this.storage = window.localStorage; + } else { + this.storage = new (_dereq_('node-localstorage').LocalStorage)(_config2.default.node_store); + } +} + +/* + * Declare the localstore itemnames + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -15074,55 +38951,18 @@ KeyArray.prototype.removeForId = function (keyId) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * The class that deals with storage of the keyring. Currently the only option is to use HTML5 local storage. * @requires config + * @requires key + * @requires util * @module keyring/localstore - * @param {String} prefix prefix for itemnames in localstore */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = LocalStore; - -var _config = _dereq_('../config'); - -var _config2 = _interopRequireDefault(_config); - -var _key = _dereq_('../key.js'); - -var keyModule = _interopRequireWildcard(_key); - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function LocalStore(prefix) { - prefix = prefix || 'openpgp-'; - this.publicKeysItem = prefix + this.publicKeysItem; - this.privateKeysItem = prefix + this.privateKeysItem; - if (typeof window !== 'undefined' && window.localStorage) { - this.storage = window.localStorage; - } else { - this.storage = new (_dereq_('node-localstorage').LocalStorage)(_config2.default.node_store); - } -} - -/* - * Declare the localstore itemnames - */ LocalStore.prototype.publicKeysItem = 'public-keys'; LocalStore.prototype.privateKeysItem = 'private-keys'; /** * Load the public keys from HTML5 local storage. - * @return {Array} array of keys retrieved from localstore + * @returns {Array} array of keys retrieved from localstore */ LocalStore.prototype.loadPublic = function () { return loadKeys(this.storage, this.publicKeysItem); @@ -15130,7 +38970,7 @@ LocalStore.prototype.loadPublic = function () { /** * Load the private keys from HTML5 local storage. - * @return {Array} array of keys retrieved from localstore + * @returns {Array} array of keys retrieved from localstore */ LocalStore.prototype.loadPrivate = function () { return loadKeys(this.storage, this.privateKeysItem); @@ -15140,9 +38980,9 @@ function loadKeys(storage, itemname) { var armoredKeys = JSON.parse(storage.getItem(itemname)); var keys = []; if (armoredKeys !== null && armoredKeys.length !== 0) { - var key; + var key = void 0; for (var i = 0; i < armoredKeys.length; i++) { - key = keyModule.readArmored(armoredKeys[i]); + key = (0, _key.readArmored)(armoredKeys[i]); if (!key.err) { keys.push(key.keys[0]); } else { @@ -15177,13 +39017,553 @@ function storeKeys(storage, itemname, keys) { for (var i = 0; i < keys.length; i++) { armoredKeys.push(keys[i].armor()); } - storage.setItem(itemname, JSON.stringify(armoredKeys)); + storage.setItem(itemname, (0, _stringify2.default)(armoredKeys)); } else { storage.removeItem(itemname); } } -},{"../config":10,"../key.js":38,"../util.js":70,"node-localstorage":"node-localstorage"}],42:[function(_dereq_,module,exports){ +exports.default = LocalStore; + +},{"../config":306,"../key":340,"../util":376,"babel-runtime/core-js/json/stringify":19,"node-localstorage":"node-localstorage"}],344:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createVerificationObjects = exports.createSignaturePackets = exports.encryptSessionKey = undefined; + +var _from = _dereq_('babel-runtime/core-js/array/from'); + +var _from2 = _interopRequireDefault(_from); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +/** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param {Uint8Array} sessionKey session key for encryption + * @param {String} symAlgo session key algorithm + * @param {Array} publicKeys (optional) public key(s) for message encryption + * @param {Array} passwords (optional) for message encryption + * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param {Date} date (optional) override the creation date signature + * @returns {Promise} new message with encrypted content + * @async + */ +var encryptSessionKey = exports.encryptSessionKey = function () { + var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee11(sessionKey, symAlgo, publicKeys, passwords) { + var wildcard = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var date = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : new Date(); + + var packetlist, results, testDecrypt, sum, encryptPassword, _results; + + return _regenerator2.default.wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + packetlist = new _packet2.default.List(); + + if (!publicKeys) { + _context11.next = 6; + break; + } + + _context11.next = 4; + return _promise2.default.all(publicKeys.map(function () { + var _ref9 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8(publicKey) { + var encryptionKeyPacket, pkESKeyPacket; + return _regenerator2.default.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return publicKey.getEncryptionKeyPacket(undefined, date); + + case 2: + encryptionKeyPacket = _context8.sent; + + if (encryptionKeyPacket) { + _context8.next = 5; + break; + } + + throw new Error('Could not find valid key packet for encryption in key ' + publicKey.primaryKey.getKeyId().toHex()); + + case 5: + pkESKeyPacket = new _packet2.default.PublicKeyEncryptedSessionKey(); + + pkESKeyPacket.publicKeyId = wildcard ? _keyid2.default.wildcard() : encryptionKeyPacket.getKeyId(); + pkESKeyPacket.publicKeyAlgorithm = encryptionKeyPacket.algorithm; + pkESKeyPacket.sessionKey = sessionKey; + pkESKeyPacket.sessionKeyAlgorithm = symAlgo; + _context8.next = 12; + return pkESKeyPacket.encrypt(encryptionKeyPacket); + + case 12: + delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption + return _context8.abrupt('return', pkESKeyPacket); + + case 14: + case 'end': + return _context8.stop(); + } + } + }, _callee8, this); + })); + + return function (_x21) { + return _ref9.apply(this, arguments); + }; + }())); + + case 4: + results = _context11.sent; + + packetlist.concat(results); + + case 6: + if (!passwords) { + _context11.next = 14; + break; + } + + testDecrypt = function () { + var _ref10 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee9(keyPacket, password) { + return _regenerator2.default.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.prev = 0; + _context9.next = 3; + return keyPacket.decrypt(password); + + case 3: + return _context9.abrupt('return', 1); + + case 6: + _context9.prev = 6; + _context9.t0 = _context9['catch'](0); + return _context9.abrupt('return', 0); + + case 9: + case 'end': + return _context9.stop(); + } + } + }, _callee9, this, [[0, 6]]); + })); + + return function testDecrypt(_x22, _x23) { + return _ref10.apply(this, arguments); + }; + }(); + + sum = function sum(accumulator, currentValue) { + return accumulator + currentValue; + }; + + encryptPassword = function () { + var _ref11 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee10(sessionKey, symAlgo, password) { + var symEncryptedSessionKeyPacket, _results2; + + return _regenerator2.default.wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + symEncryptedSessionKeyPacket = new _packet2.default.SymEncryptedSessionKey(); + + symEncryptedSessionKeyPacket.sessionKey = sessionKey; + symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo; + _context10.next = 5; + return symEncryptedSessionKeyPacket.encrypt(password); + + case 5: + if (!_config2.default.password_collision_check) { + _context10.next = 11; + break; + } + + _context10.next = 8; + return _promise2.default.all(passwords.map(function (pwd) { + return testDecrypt(symEncryptedSessionKeyPacket, pwd); + })); + + case 8: + _results2 = _context10.sent; + + if (!(_results2.reduce(sum) !== 1)) { + _context10.next = 11; + break; + } + + return _context10.abrupt('return', encryptPassword(sessionKey, symAlgo, password)); + + case 11: + + delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption + return _context10.abrupt('return', symEncryptedSessionKeyPacket); + + case 13: + case 'end': + return _context10.stop(); + } + } + }, _callee10, this); + })); + + return function encryptPassword(_x24, _x25, _x26) { + return _ref11.apply(this, arguments); + }; + }(); + + _context11.next = 12; + return _promise2.default.all(passwords.map(function (pwd) { + return encryptPassword(sessionKey, symAlgo, pwd); + })); + + case 12: + _results = _context11.sent; + + packetlist.concat(_results); + + case 14: + return _context11.abrupt('return', new Message(packetlist)); + + case 15: + case 'end': + return _context11.stop(); + } + } + }, _callee11, this); + })); + + return function encryptSessionKey(_x15, _x16, _x17, _x18) { + return _ref8.apply(this, arguments); + }; +}(); + +/** + * Sign the message (the literal data packet of the message) + * @param {Array} privateKeys private keys with decrypted secret key data for signing + * @param {Signature} signature (optional) any existing detached signature to add to the message + * @param {Date} date} (optional) override the creation time of the signature + * @returns {Promise} new message with signed content + * @async + */ + + +/** + * Create signature packets for the message + * @param {module:packet/literal} literalDataPacket the literal data packet to sign + * @param {Array} privateKeys private keys with decrypted secret key data for signing + * @param {Signature} signature (optional) any existing detached signature to append + * @param {Date} date (optional) override the creationtime of the signature + * @returns {Promise} list of signature packets + * @async + */ +var createSignaturePackets = exports.createSignaturePackets = function () { + var _ref15 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee16(literalDataPacket, privateKeys) { + var signature = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Date(); + var packetlist, literalFormat, signatureType, existingSigPacketlist; + return _regenerator2.default.wrap(function _callee16$(_context16) { + while (1) { + switch (_context16.prev = _context16.next) { + case 0: + packetlist = new _packet2.default.List(); + literalFormat = _enums2.default.write(_enums2.default.literal, literalDataPacket.format); + signatureType = literalFormat === _enums2.default.literal.binary ? _enums2.default.signature.binary : _enums2.default.signature.text; + _context16.next = 5; + return _promise2.default.all(privateKeys.map(function () { + var _ref16 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee15(privateKey) { + var signingKeyPacket, signaturePacket; + return _regenerator2.default.wrap(function _callee15$(_context15) { + while (1) { + switch (_context15.prev = _context15.next) { + case 0: + if (!privateKey.isPublic()) { + _context15.next = 2; + break; + } + + throw new Error('Need private key for signing'); + + case 2: + _context15.next = 4; + return privateKey.getSigningKeyPacket(undefined, date); + + case 4: + signingKeyPacket = _context15.sent; + + if (signingKeyPacket) { + _context15.next = 7; + break; + } + + throw new Error('Could not find valid key packet for signing in key ' + privateKey.primaryKey.getKeyId().toHex()); + + case 7: + if (signingKeyPacket.isDecrypted) { + _context15.next = 9; + break; + } + + throw new Error('Private key is not decrypted.'); + + case 9: + signaturePacket = new _packet2.default.Signature(date); + + signaturePacket.signatureType = signatureType; + signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; + _context15.next = 14; + return (0, _key.getPreferredHashAlgo)(privateKey); + + case 14: + signaturePacket.hashAlgorithm = _context15.sent; + _context15.next = 17; + return signaturePacket.sign(signingKeyPacket, literalDataPacket); + + case 17: + return _context15.abrupt('return', signaturePacket); + + case 18: + case 'end': + return _context15.stop(); + } + } + }, _callee15, this); + })); + + return function (_x39) { + return _ref16.apply(this, arguments); + }; + }())).then(function (signatureList) { + signatureList.forEach(function (signaturePacket) { + return packetlist.push(signaturePacket); + }); + }); + + case 5: + + if (signature) { + existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature); + + packetlist.concat(existingSigPacketlist); + } + return _context16.abrupt('return', packetlist); + + case 7: + case 'end': + return _context16.stop(); + } + } + }, _callee16, this); + })); + + return function createSignaturePackets(_x35, _x36) { + return _ref15.apply(this, arguments); + }; +}(); + +/** + * Verify message signatures + * @param {Array} keys array of keys to verify signatures + * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns {Promise>} list of signer's keyid and validity of signature + * @async + */ + + +/** + * Create list of objects containing signer's keyid and validity of signature + * @param {Array} signatureList array of signature packets + * @param {Array} literalDataList array of literal data packets + * @param {Array} keys array of keys to verify signatures + * @param {Date} date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns {Promise>} list of signer's keyid and validity of signature + * @async + */ +var createVerificationObjects = exports.createVerificationObjects = function () { + var _ref17 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee19(signatureList, literalDataList, keys) { + var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Date(); + return _regenerator2.default.wrap(function _callee19$(_context19) { + while (1) { + switch (_context19.prev = _context19.next) { + case 0: + return _context19.abrupt('return', _promise2.default.all(signatureList.map(function () { + var _ref18 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee18(signature) { + var keyPacket, verifiedSig, packetlist; + return _regenerator2.default.wrap(function _callee18$(_context18) { + while (1) { + switch (_context18.prev = _context18.next) { + case 0: + keyPacket = null; + _context18.next = 3; + return _promise2.default.all(keys.map(function () { + var _ref19 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee17(key) { + var result; + return _regenerator2.default.wrap(function _callee17$(_context17) { + while (1) { + switch (_context17.prev = _context17.next) { + case 0: + _context17.next = 2; + return key.getSigningKeyPacket(signature.issuerKeyId, date); + + case 2: + result = _context17.sent; + + if (result) { + keyPacket = result; + } + + case 4: + case 'end': + return _context17.stop(); + } + } + }, _callee17, this); + })); + + return function (_x47) { + return _ref19.apply(this, arguments); + }; + }())); + + case 3: + _context18.t0 = signature.issuerKeyId; + + if (!keyPacket) { + _context18.next = 10; + break; + } + + _context18.next = 7; + return signature.verify(keyPacket, literalDataList[0]); + + case 7: + _context18.t1 = _context18.sent; + _context18.next = 11; + break; + + case 10: + _context18.t1 = null; + + case 11: + _context18.t2 = _context18.t1; + verifiedSig = { + keyid: _context18.t0, + valid: _context18.t2 + }; + packetlist = new _packet2.default.List(); + + packetlist.push(signature); + verifiedSig.signature = new _signature.Signature(packetlist); + + return _context18.abrupt('return', verifiedSig); + + case 17: + case 'end': + return _context18.stop(); + } + } + }, _callee18, this); + })); + + return function (_x46) { + return _ref18.apply(this, arguments); + }; + }()))); + + case 1: + case 'end': + return _context19.stop(); + } + } + }, _callee19, this); + })); + + return function createVerificationObjects(_x42, _x43, _x44) { + return _ref17.apply(this, arguments); + }; +}(); + +/** + * Unwrap compressed message + * @returns {module:message~Message} message Content of compressed message + */ + + +exports.Message = Message; +exports.readArmored = readArmored; +exports.read = read; +exports.fromText = fromText; +exports.fromBinary = fromBinary; + +var _config = _dereq_('./config'); + +var _config2 = _interopRequireDefault(_config); + +var _crypto = _dereq_('./crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _armor = _dereq_('./encoding/armor'); + +var _armor2 = _interopRequireDefault(_armor); + +var _enums = _dereq_('./enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('./util'); + +var _util2 = _interopRequireDefault(_util); + +var _packet = _dereq_('./packet'); + +var _packet2 = _interopRequireDefault(_packet); + +var _keyid = _dereq_('./type/keyid'); + +var _keyid2 = _interopRequireDefault(_keyid); + +var _signature = _dereq_('./signature'); + +var _key = _dereq_('./key'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @class + * @classdesc Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + * @param {module:packet/packetlist} packetlist The packets that form this message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + +function Message(packetlist) { + if (!(this instanceof Message)) { + return new Message(packetlist); + } + this.packets = packetlist || new _packet2.default.List(); +} + +/** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns {Array} array of keyid objects + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -15206,78 +39586,13 @@ function storeKeys(storage, itemname, keys) { * @requires crypto * @requires encoding/armor * @requires enums + * @requires util * @requires packet + * @requires signature + * @requires key * @module message */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Message = Message; -exports.encryptSessionKey = encryptSessionKey; -exports.readArmored = readArmored; -exports.read = read; -exports.readSignedContent = readSignedContent; -exports.fromText = fromText; -exports.fromBinary = fromBinary; - -var _util = _dereq_('./util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _packet = _dereq_('./packet'); - -var _packet2 = _interopRequireDefault(_packet); - -var _enums = _dereq_('./enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -var _armor = _dereq_('./encoding/armor.js'); - -var _armor2 = _interopRequireDefault(_armor); - -var _config = _dereq_('./config'); - -var _config2 = _interopRequireDefault(_config); - -var _crypto = _dereq_('./crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -var _signature = _dereq_('./signature.js'); - -var sigModule = _interopRequireWildcard(_signature); - -var _key = _dereq_('./key.js'); - -var keyModule = _interopRequireWildcard(_key); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @class - * @classdesc Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - * @param {module:packet/packetlist} packetlist The packets that form this message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} - */ - -function Message(packetlist) { - if (!(this instanceof Message)) { - return new Message(packetlist); - } - this.packets = packetlist || new _packet2.default.List(); -} - -/** - * Returns the key IDs of the keys to which the session key is encrypted - * @return {Array} array of keyid objects - */ Message.prototype.getEncryptionKeyIds = function () { var keyIds = []; var pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey); @@ -15289,7 +39604,7 @@ Message.prototype.getEncryptionKeyIds = function () { /** * Returns the key IDs of the keys that signed the message - * @return {Array} array of keyid objects + * @returns {Array} array of keyid objects */ Message.prototype.getSigningKeyIds = function () { var keyIds = []; @@ -15311,95 +39626,337 @@ Message.prototype.getSigningKeyIds = function () { /** * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param {Key} privateKey (optional) private key with decrypted secret data - * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @param {String} password (optional) password used to decrypt - * @return {Message} new message with decrypted content + * @param {Array} privateKeys (optional) private keys with decrypted secret data + * @param {Array} passwords (optional) passwords used to decrypt + * @param {Array} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String } + * @returns {Promise} new message with decrypted content + * @async */ -Message.prototype.decrypt = function (privateKey, sessionKey, password) { - var _this = this; +Message.prototype.decrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(privateKeys, passwords, sessionKeys) { + var keyObjs, symEncryptedPacketlist, symEncryptedPacket, exception, i, resultMsg; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = sessionKeys; - return Promise.resolve().then(function () { - var keyObj = sessionKey || _this.decryptSessionKey(privateKey, password); - if (!keyObj || !_util2.default.isUint8Array(keyObj.data) || !_util2.default.isString(keyObj.algorithm)) { - throw new Error('Invalid session key for decryption.'); - } + if (_context.t0) { + _context.next = 5; + break; + } - var symEncryptedPacketlist = _this.packets.filterByTag(_enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected); + _context.next = 4; + return this.decryptSessionKeys(privateKeys, passwords); - if (symEncryptedPacketlist.length === 0) { - return; - } + case 4: + _context.t0 = _context.sent; - var symEncryptedPacket = symEncryptedPacketlist[0]; - return symEncryptedPacket.decrypt(keyObj.algorithm, keyObj.data).then(function () { - var resultMsg = new Message(symEncryptedPacket.packets); - symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after decryption - return resultMsg; - }); - }); -}; + case 5: + keyObjs = _context.t0; + symEncryptedPacketlist = this.packets.filterByTag(_enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected); -/** - * Decrypt an encrypted session key either with a private key or a password. - * @param {Key} privateKey (optional) private key with decrypted secret data - * @param {String} password (optional) password used to decrypt - * @return {Object} object with sessionKey, algorithm in the form: - * { data:Uint8Array, algorithm:String } - */ -Message.prototype.decryptSessionKey = function (privateKey, password) { - var keyPacket; + if (!(symEncryptedPacketlist.length === 0)) { + _context.next = 9; + break; + } - if (password) { - var symEncryptedSessionKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.symEncryptedSessionKey); - var symLength = symEncryptedSessionKeyPacketlist.length; - for (var i = 0; i < symLength; i++) { - keyPacket = symEncryptedSessionKeyPacketlist[i]; - try { - keyPacket.decrypt(password); - break; - } catch (err) { - if (i === symLength - 1) { - throw err; + return _context.abrupt('return', this); + + case 9: + symEncryptedPacket = symEncryptedPacketlist[0]; + exception = null; + i = 0; + + case 12: + if (!(i < keyObjs.length)) { + _context.next = 27; + break; + } + + if (!(!keyObjs[i] || !_util2.default.isUint8Array(keyObjs[i].data) || !_util2.default.isString(keyObjs[i].algorithm))) { + _context.next = 15; + break; + } + + throw new Error('Invalid session key for decryption.'); + + case 15: + _context.prev = 15; + _context.next = 18; + return symEncryptedPacket.decrypt(keyObjs[i].algorithm, keyObjs[i].data); + + case 18: + return _context.abrupt('break', 27); + + case 21: + _context.prev = 21; + _context.t1 = _context['catch'](15); + + exception = _context.t1; + + case 24: + i++; + _context.next = 12; + break; + + case 27: + if (!(!symEncryptedPacket.packets || !symEncryptedPacket.packets.length)) { + _context.next = 29; + break; + } + + throw exception || new Error('Decryption failed.'); + + case 29: + resultMsg = new Message(symEncryptedPacket.packets); + + symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after decryption + + return _context.abrupt('return', resultMsg); + + case 32: + case 'end': + return _context.stop(); } } - } - if (!keyPacket) { - throw new Error('No symmetrically encrypted session key packet found.'); - } - } else if (privateKey) { - var encryptionKeyIds = this.getEncryptionKeyIds(); - if (!encryptionKeyIds.length) { - // nothing to decrypt - return; - } - var privateKeyPacket = privateKey.getKeyPacket(encryptionKeyIds); - if (!privateKeyPacket.isDecrypted) { - throw new Error('Private key is not decrypted.'); - } - var pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey); - for (var j = 0; j < pkESKeyPacketlist.length; j++) { - if (pkESKeyPacketlist[j].publicKeyId.equals(privateKeyPacket.getKeyId())) { - keyPacket = pkESKeyPacketlist[j]; - keyPacket.decrypt(privateKeyPacket); - break; - } - } - } else { - throw new Error('No key or password specified.'); - } + }, _callee, this, [[15, 21]]); + })); - if (keyPacket) { - return { - data: keyPacket.sessionKey, - algorithm: keyPacket.sessionKeyAlgorithm - }; - } -}; + return function (_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Decrypt encrypted session keys either with private keys or passwords. + * @param {Array} privateKeys (optional) private keys with decrypted secret data + * @param {Array} passwords (optional) passwords used to decrypt + * @returns {Promise>} array of object with potential sessionKey, algorithm pairs + * @async + */ +Message.prototype.decryptSessionKeys = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(privateKeys, passwords) { + var keyPackets, symESKeyPacketlist, pkESKeyPacketlist, seen; + return _regenerator2.default.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + keyPackets = []; + + if (!passwords) { + _context6.next = 9; + break; + } + + symESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.symEncryptedSessionKey); + + if (symESKeyPacketlist) { + _context6.next = 5; + break; + } + + throw new Error('No symmetrically encrypted session key packet found.'); + + case 5: + _context6.next = 7; + return _promise2.default.all(symESKeyPacketlist.map(function () { + var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(keyPacket) { + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return _promise2.default.all(passwords.map(function () { + var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(password) { + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return keyPacket.decrypt(password); + + case 3: + keyPackets.push(keyPacket); + _context2.next = 8; + break; + + case 6: + _context2.prev = 6; + _context2.t0 = _context2['catch'](0); + + case 8: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this, [[0, 6]]); + })); + + return function (_x7) { + return _ref4.apply(this, arguments); + }; + }())); + + case 2: + case 'end': + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x6) { + return _ref3.apply(this, arguments); + }; + }())); + + case 7: + _context6.next = 18; + break; + + case 9: + if (!privateKeys) { + _context6.next = 17; + break; + } + + pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey); + + if (pkESKeyPacketlist) { + _context6.next = 13; + break; + } + + throw new Error('No public key encrypted session key packet found.'); + + case 13: + _context6.next = 15; + return _promise2.default.all(pkESKeyPacketlist.map(function () { + var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(keyPacket) { + var privateKeyPackets; + return _regenerator2.default.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + // TODO improve this + privateKeyPackets = privateKeys.reduce(function (acc, privateKey) { + return acc.concat(privateKey.getKeyPackets(keyPacket.publicKeyId)); + }, new _packet2.default.List()); + _context5.next = 3; + return _promise2.default.all(privateKeyPackets.map(function () { + var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(privateKeyPacket) { + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (privateKeyPacket) { + _context4.next = 2; + break; + } + + return _context4.abrupt('return'); + + case 2: + if (privateKeyPacket.isDecrypted) { + _context4.next = 4; + break; + } + + throw new Error('Private key is not decrypted.'); + + case 4: + _context4.prev = 4; + _context4.next = 7; + return keyPacket.decrypt(privateKeyPacket); + + case 7: + keyPackets.push(keyPacket); + _context4.next = 12; + break; + + case 10: + _context4.prev = 10; + _context4.t0 = _context4['catch'](4); + + case 12: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this, [[4, 10]]); + })); + + return function (_x9) { + return _ref6.apply(this, arguments); + }; + }())); + + case 3: + case 'end': + return _context5.stop(); + } + } + }, _callee5, this); + })); + + return function (_x8) { + return _ref5.apply(this, arguments); + }; + }())); + + case 15: + _context6.next = 18; + break; + + case 17: + throw new Error('No key or password specified.'); + + case 18: + if (!keyPackets.length) { + _context6.next = 21; + break; + } + + // Return only unique session keys + if (keyPackets.length > 1) { + seen = {}; + + keyPackets = keyPackets.filter(function (item) { + var k = item.sessionKeyAlgorithm + _util2.default.Uint8Array_to_str(item.sessionKey); + if (seen.hasOwnProperty(k)) { + return false; + } + seen[k] = true; + return true; + }); + } + + return _context6.abrupt('return', keyPackets.map(function (packet) { + return { data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }; + })); + + case 21: + throw new Error('Session key decryption failed.'); + + case 22: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this); + })); + + return function (_x4, _x5) { + return _ref2.apply(this, arguments); + }; +}(); /** * Get literal data that is the body of the message - * @return {(Uint8Array|null)} literal body of the message as Uint8Array + * @returns {(Uint8Array|null)} literal body of the message as Uint8Array */ Message.prototype.getLiteralData = function () { var literal = this.packets.findPacket(_enums2.default.packet.literal); @@ -15408,7 +39965,7 @@ Message.prototype.getLiteralData = function () { /** * Get filename from literal data packet - * @return {(String|null)} filename of literal data packet as string + * @returns {(String|null)} filename of literal data packet as string */ Message.prototype.getFilename = function () { var literal = this.packets.findPacket(_enums2.default.packet.literal); @@ -15417,15 +39974,14 @@ Message.prototype.getFilename = function () { /** * Get literal data as text - * @return {(String|null)} literal body of the message interpreted as text + * @returns {(String|null)} literal body of the message interpreted as text */ Message.prototype.getText = function () { var literal = this.packets.findPacket(_enums2.default.packet.literal); if (literal) { return literal.getText(); - } else { - return null; } + return null; }; /** @@ -15433,306 +39989,376 @@ Message.prototype.getText = function () { * @param {Array} keys (optional) public key(s) for message encryption * @param {Array} passwords (optional) password(s) for message encryption * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @return {Message} new message with encrypted content + * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param {Date} date (optional) override the creation date of the literal package + * @returns {Promise} new message with encrypted content + * @async */ -Message.prototype.encrypt = function (keys, passwords, sessionKey) { - var _this2 = this; +Message.prototype.encrypt = function () { + var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(keys, passwords, sessionKey) { + var wildcard = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var date = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Date(); + var symAlgo, symEncryptedPacket, msg; + return _regenerator2.default.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + symAlgo = void 0; + symEncryptedPacket = void 0; - var symAlgo = void 0, - msg = void 0, - symEncryptedPacket = void 0; - return Promise.resolve().then(function () { - if (sessionKey) { - if (!_util2.default.isUint8Array(sessionKey.data) || !_util2.default.isString(sessionKey.algorithm)) { - throw new Error('Invalid session key for encryption.'); - } - symAlgo = sessionKey.algorithm; - sessionKey = sessionKey.data; - } else if (keys && keys.length) { - symAlgo = _enums2.default.read(_enums2.default.symmetric, keyModule.getPreferredSymAlgo(keys)); - } else if (passwords && passwords.length) { - symAlgo = _enums2.default.read(_enums2.default.symmetric, _config2.default.encryption_cipher); - } else { - throw new Error('No keys, passwords, or session key provided.'); - } + if (!sessionKey) { + _context7.next = 9; + break; + } - if (!sessionKey) { - sessionKey = _crypto2.default.generateSessionKey(symAlgo); - } + if (!(!_util2.default.isUint8Array(sessionKey.data) || !_util2.default.isString(sessionKey.algorithm))) { + _context7.next = 5; + break; + } - msg = encryptSessionKey(sessionKey, symAlgo, keys, passwords); + throw new Error('Invalid session key for encryption.'); - if (_config2.default.aead_protect) { - symEncryptedPacket = new _packet2.default.SymEncryptedAEADProtected(); - } else if (_config2.default.integrity_protect) { - symEncryptedPacket = new _packet2.default.SymEncryptedIntegrityProtected(); - } else { - symEncryptedPacket = new _packet2.default.SymmetricallyEncrypted(); - } - symEncryptedPacket.packets = _this2.packets; + case 5: + symAlgo = sessionKey.algorithm; + sessionKey = sessionKey.data; + _context7.next = 23; + break; - return symEncryptedPacket.encrypt(symAlgo, sessionKey); - }).then(function () { - msg.packets.push(symEncryptedPacket); - symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after encryption - return { - message: msg, - sessionKey: { - data: sessionKey, - algorithm: symAlgo - } - }; - }); -}; + case 9: + if (!(keys && keys.length)) { + _context7.next = 18; + break; + } -/** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param {Uint8Array} sessionKey session key for encryption - * @param {String} symAlgo session key algorithm - * @param {Array} publicKeys (optional) public key(s) for message encryption - * @param {Array} passwords (optional) for message encryption - * @return {Message} new message with encrypted content - */ -function encryptSessionKey(sessionKey, symAlgo, publicKeys, passwords) { - var packetlist = new _packet2.default.List(); + _context7.t0 = _enums2.default; + _context7.t1 = _enums2.default.symmetric; + _context7.next = 14; + return (0, _key.getPreferredSymAlgo)(keys); - if (publicKeys) { - publicKeys.forEach(function (key) { - var encryptionKeyPacket = key.getEncryptionKeyPacket(); - if (encryptionKeyPacket) { - var pkESKeyPacket = new _packet2.default.PublicKeyEncryptedSessionKey(); - pkESKeyPacket.publicKeyId = encryptionKeyPacket.getKeyId(); - pkESKeyPacket.publicKeyAlgorithm = encryptionKeyPacket.algorithm; - pkESKeyPacket.sessionKey = sessionKey; - pkESKeyPacket.sessionKeyAlgorithm = symAlgo; - pkESKeyPacket.encrypt(encryptionKeyPacket); - delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption - packetlist.push(pkESKeyPacket); - } else { - throw new Error('Could not find valid key packet for encryption in key ' + key.primaryKey.getKeyId().toHex()); - } - }); - } + case 14: + _context7.t2 = _context7.sent; + symAlgo = _context7.t0.read.call(_context7.t0, _context7.t1, _context7.t2); + _context7.next = 23; + break; - if (passwords) { - passwords.forEach(function (password) { - var symEncryptedSessionKeyPacket = new _packet2.default.SymEncryptedSessionKey(); - symEncryptedSessionKeyPacket.sessionKey = sessionKey; - symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo; - symEncryptedSessionKeyPacket.encrypt(password); - delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption - packetlist.push(symEncryptedSessionKeyPacket); - }); - } + case 18: + if (!(passwords && passwords.length)) { + _context7.next = 22; + break; + } - return new Message(packetlist); -} + symAlgo = _enums2.default.read(_enums2.default.symmetric, _config2.default.encryption_cipher); + _context7.next = 23; + break; -/** - * Sign the message (the literal data packet of the message) - * @param {Array} privateKey private keys with decrypted secret key data for signing - * @param {Signature} signature (optional) any existing detached signature to add to the message - * @return {module:message~Message} new message with signed content - */ -Message.prototype.sign = function () { - var privateKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + case 22: + throw new Error('No keys, passwords, or session key provided.'); + + case 23: + if (sessionKey) { + _context7.next = 27; + break; + } + + _context7.next = 26; + return _crypto2.default.generateSessionKey(symAlgo); + + case 26: + sessionKey = _context7.sent; + + case 27: + _context7.next = 29; + return encryptSessionKey(sessionKey, symAlgo, keys, passwords, wildcard, date); + + case 29: + msg = _context7.sent; - var packetlist = new _packet2.default.List(); + if (_config2.default.aead_protect) { + symEncryptedPacket = new _packet2.default.SymEncryptedAEADProtected(); + } else if (_config2.default.integrity_protect) { + symEncryptedPacket = new _packet2.default.SymEncryptedIntegrityProtected(); + } else { + symEncryptedPacket = new _packet2.default.SymmetricallyEncrypted(); + } + symEncryptedPacket.packets = this.packets; - var literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } + _context7.next = 34; + return symEncryptedPacket.encrypt(symAlgo, sessionKey); - var literalFormat = _enums2.default.write(_enums2.default.literal, literalDataPacket.format); - var signatureType = literalFormat === _enums2.default.literal.binary ? _enums2.default.signature.binary : _enums2.default.signature.text; - var i, signingKeyPacket, existingSigPacketlist, onePassSig; + case 34: - if (signature) { - existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature); - if (existingSigPacketlist.length) { - for (i = existingSigPacketlist.length - 1; i >= 0; i--) { - var sigPacket = existingSigPacketlist[i]; - onePassSig = new _packet2.default.OnePassSignature(); - onePassSig.type = signatureType; - onePassSig.hashAlgorithm = _config2.default.prefer_hash_algorithm; - onePassSig.publicKeyAlgorithm = sigPacket.publicKeyAlgorithm; - onePassSig.signingKeyId = sigPacket.issuerKeyId; - if (!privateKeys.length && i === 0) { - onePassSig.flags = 1; + msg.packets.push(symEncryptedPacket); + symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after encryption + return _context7.abrupt('return', { + message: msg, + sessionKey: { + data: sessionKey, + algorithm: symAlgo + } + }); + + case 37: + case 'end': + return _context7.stop(); } - packetlist.push(onePassSig); } - } - } - for (i = 0; i < privateKeys.length; i++) { - if (privateKeys[i].isPublic()) { - throw new Error('Need private key for signing'); - } - onePassSig = new _packet2.default.OnePassSignature(); - onePassSig.type = signatureType; - //TODO get preferred hashg algo from key signature - onePassSig.hashAlgorithm = _config2.default.prefer_hash_algorithm; - signingKeyPacket = privateKeys[i].getSigningKeyPacket(); - if (!signingKeyPacket) { - throw new Error('Could not find valid key packet for signing in key ' + privateKeys[i].primaryKey.getKeyId().toHex()); - } - onePassSig.publicKeyAlgorithm = signingKeyPacket.algorithm; - onePassSig.signingKeyId = signingKeyPacket.getKeyId(); - if (i === privateKeys.length - 1) { - onePassSig.flags = 1; - } - packetlist.push(onePassSig); + }, _callee7, this); + })); + + return function (_x10, _x11, _x12) { + return _ref7.apply(this, arguments); + }; +}();Message.prototype.sign = function () { + var _ref12 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee13() { + var privateKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var packetlist, literalDataPacket, i, existingSigPacketlist, literalFormat, signatureType, signaturePacket, onePassSig; + return _regenerator2.default.wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + packetlist = new _packet2.default.List(); + literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal); + + if (literalDataPacket) { + _context13.next = 4; + break; + } + + throw new Error('No literal data packet to sign.'); + + case 4: + i = void 0; + existingSigPacketlist = void 0; + literalFormat = _enums2.default.write(_enums2.default.literal, literalDataPacket.format); + signatureType = literalFormat === _enums2.default.literal.binary ? _enums2.default.signature.binary : _enums2.default.signature.text; + + + if (signature) { + existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature); + for (i = existingSigPacketlist.length - 1; i >= 0; i--) { + signaturePacket = existingSigPacketlist[i]; + onePassSig = new _packet2.default.OnePassSignature(); + + onePassSig.type = signatureType; + onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm; + onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm; + onePassSig.signingKeyId = signaturePacket.issuerKeyId; + if (!privateKeys.length && i === 0) { + onePassSig.flags = 1; + } + packetlist.push(onePassSig); + } + } + + _context13.next = 11; + return _promise2.default.all((0, _from2.default)(privateKeys).reverse().map(function () { + var _ref13 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee12(privateKey, i) { + var signingKeyPacket, onePassSig; + return _regenerator2.default.wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + if (!privateKey.isPublic()) { + _context12.next = 2; + break; + } + + throw new Error('Need private key for signing'); + + case 2: + _context12.next = 4; + return privateKey.getSigningKeyPacket(undefined, date); + + case 4: + signingKeyPacket = _context12.sent; + + if (signingKeyPacket) { + _context12.next = 7; + break; + } + + throw new Error('Could not find valid key packet for signing in key ' + privateKey.primaryKey.getKeyId().toHex()); + + case 7: + onePassSig = new _packet2.default.OnePassSignature(); + + onePassSig.type = signatureType; + _context12.next = 11; + return (0, _key.getPreferredHashAlgo)(privateKey); + + case 11: + onePassSig.hashAlgorithm = _context12.sent; + + onePassSig.publicKeyAlgorithm = signingKeyPacket.algorithm; + onePassSig.signingKeyId = signingKeyPacket.getKeyId(); + if (i === privateKeys.length - 1) { + onePassSig.flags = 1; + } + return _context12.abrupt('return', onePassSig); + + case 16: + case 'end': + return _context12.stop(); + } + } + }, _callee12, this); + })); + + return function (_x30, _x31) { + return _ref13.apply(this, arguments); + }; + }())).then(function (onePassSignatureList) { + onePassSignatureList.forEach(function (onePassSig) { + return packetlist.push(onePassSig); + }); + }); + + case 11: + + packetlist.push(literalDataPacket); + _context13.t0 = packetlist; + _context13.next = 15; + return createSignaturePackets(literalDataPacket, privateKeys, signature, date); + + case 15: + _context13.t1 = _context13.sent; + + _context13.t0.concat.call(_context13.t0, _context13.t1); + + return _context13.abrupt('return', new Message(packetlist)); + + case 18: + case 'end': + return _context13.stop(); + } + } + }, _callee13, this); + })); + + return function () { + return _ref12.apply(this, arguments); + }; +}(); + +/** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param {module:enums.compression} compression compression algorithm to be used + * @returns {module:message~Message} new message with compressed content + */ +Message.prototype.compress = function (compression) { + if (compression === _enums2.default.compression.uncompressed) { + return this; } - packetlist.push(literalDataPacket); + var compressed = new _packet2.default.Compressed(); + compressed.packets = this.packets; + compressed.algorithm = _enums2.default.read(_enums2.default.compression, compression); - for (i = privateKeys.length - 1; i >= 0; i--) { - var signaturePacket = new _packet2.default.Signature(); - signaturePacket.signatureType = signatureType; - signaturePacket.hashAlgorithm = _config2.default.prefer_hash_algorithm; - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - if (!signingKeyPacket.isDecrypted) { - throw new Error('Private key is not decrypted.'); - } - signaturePacket.sign(signingKeyPacket, literalDataPacket); - packetlist.push(signaturePacket); - } + var packetList = new _packet2.default.List(); + packetList.push(compressed); - if (signature) { - packetlist.concat(existingSigPacketlist); - } - - return new Message(packetlist); + return new Message(packetList); }; /** * Create a detached signature for the message (the literal data packet of the message) - * @param {Array} privateKey private keys with decrypted secret key data for signing - * @param {Signature} signature (optional) any existing detached signature - * @return {module:signature~Signature} new detached signature of message content + * @param {Array} privateKeys private keys with decrypted secret key data for signing + * @param {Signature} signature (optional) any existing detached signature + * @param {Date} date (optional) override the creation time of the signature + * @returns {Promise} new detached signature of message content + * @async */ Message.prototype.signDetached = function () { - var privateKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _ref14 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee14() { + var privateKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var literalDataPacket; + return _regenerator2.default.wrap(function _callee14$(_context14) { + while (1) { + switch (_context14.prev = _context14.next) { + case 0: + literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal); + if (literalDataPacket) { + _context14.next = 3; + break; + } - var packetlist = new _packet2.default.List(); + throw new Error('No literal data packet to sign.'); - var literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal); - if (!literalDataPacket) { - throw new Error('No literal data packet to sign.'); - } + case 3: + _context14.t0 = _signature.Signature; + _context14.next = 6; + return createSignaturePackets(literalDataPacket, privateKeys, signature, date); - var literalFormat = _enums2.default.write(_enums2.default.literal, literalDataPacket.format); - var signatureType = literalFormat === _enums2.default.literal.binary ? _enums2.default.signature.binary : _enums2.default.signature.text; + case 6: + _context14.t1 = _context14.sent; + return _context14.abrupt('return', new _context14.t0(_context14.t1)); - for (var i = 0; i < privateKeys.length; i++) { - var signingKeyPacket = privateKeys[i].getSigningKeyPacket(); - var signaturePacket = new _packet2.default.Signature(); - signaturePacket.signatureType = signatureType; - signaturePacket.hashAlgorithm = _config2.default.prefer_hash_algorithm; - signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm; - if (!signingKeyPacket.isDecrypted) { - throw new Error('Private key is not decrypted.'); - } - signaturePacket.sign(signingKeyPacket, literalDataPacket); - packetlist.push(signaturePacket); - } - if (signature) { - var existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature); - packetlist.concat(existingSigPacketlist); - } + case 8: + case 'end': + return _context14.stop(); + } + } + }, _callee14, this); + })); - return new sigModule.Signature(packetlist); -}; + return function () { + return _ref14.apply(this, arguments); + }; +}();Message.prototype.verify = function (keys) { + var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); -/** - * Verify message signatures - * @param {Array} keys array of keys to verify signatures - * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature - */ -Message.prototype.verify = function (keys) { var msg = this.unwrapCompressed(); var literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } var signatureList = msg.packets.filterByTag(_enums2.default.packet.signature); - return createVerificationObjects(signatureList, literalDataList, keys); + return createVerificationObjects(signatureList, literalDataList, keys, date); }; /** * Verify detached message signature * @param {Array} keys array of keys to verify signatures - * @param {Signature} - * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature + * @param {Signature} signature + * @param {Date} date Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns {Promise>} list of signer's keyid and validity of signature + * @async */ Message.prototype.verifyDetached = function (signature, keys) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var msg = this.unwrapCompressed(); var literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal); if (literalDataList.length !== 1) { throw new Error('Can only verify message with one literal data packet.'); } var signatureList = signature.packets; - return createVerificationObjects(signatureList, literalDataList, keys); -}; - -/** - * Create list of objects containing signer's keyid and validity of signature - * @param {Array} signatureList array of signature packets - * @param {Array} literalDataList array of literal data packets - * @param {Array} keys array of keys to verify signatures - * @return {Array<({keyid: module:type/keyid, valid: Boolean})>} list of signer's keyid and validity of signature - */ -function createVerificationObjects(signatureList, literalDataList, keys) { - var result = []; - for (var i = 0; i < signatureList.length; i++) { - var keyPacket = null; - for (var j = 0; j < keys.length; j++) { - keyPacket = keys[j].getSigningKeyPacket(signatureList[i].issuerKeyId, _config2.default.verify_expired_keys); - if (keyPacket) { - break; - } - } - - var verifiedSig = {}; - if (keyPacket) { - //found a key packet that matches keyId of signature - verifiedSig.keyid = signatureList[i].issuerKeyId; - verifiedSig.valid = signatureList[i].verify(keyPacket, literalDataList[0]); - } else { - verifiedSig.keyid = signatureList[i].issuerKeyId; - verifiedSig.valid = null; - } - - var packetlist = new _packet2.default.List(); - packetlist.push(signatureList[i]); - verifiedSig.signature = new sigModule.Signature(packetlist); - - result.push(verifiedSig); - } - return result; -} - -/** - * Unwrap compressed message - * @return {module:message~Message} message Content of compressed message - */ -Message.prototype.unwrapCompressed = function () { + return createVerificationObjects(signatureList, literalDataList, keys, date); +};Message.prototype.unwrapCompressed = function () { var compressed = this.packets.filterByTag(_enums2.default.packet.compressed); if (compressed.length) { return new Message(compressed[0].packets); - } else { - return this; } + return this; +}; + +/** + * Append signature to unencrypted message object + * @param {String|Uint8Array} detachedSignature The detached ASCII-armored or Uint8Array PGP signature + */ +Message.prototype.appendSignature = function (detachedSignature) { + this.packets.read(_util2.default.isUint8Array(detachedSignature) ? detachedSignature : _armor2.default.decode(detachedSignature).data); }; /** * Returns ASCII armored text of message - * @return {String} ASCII armor + * @returns {String} ASCII armor */ Message.prototype.armor = function () { return _armor2.default.encode(_enums2.default.armor.message, this.packets.write()); @@ -15741,7 +40367,7 @@ Message.prototype.armor = function () { /** * reads an OpenPGP armored message and returns a message object * @param {String} armoredText text to be parsed - * @return {module:message~Message} new message object + * @returns {module:message~Message} new message object * @static */ function readArmored(armoredText) { @@ -15754,7 +40380,7 @@ function readArmored(armoredText) { /** * reads an OpenPGP message as byte array and returns a message object * @param {Uint8Array} input binary message - * @return {Message} new message object + * @returns {Message} new message object * @static */ function read(input) { @@ -15763,30 +40389,18 @@ function read(input) { return new Message(packetlist); } -/** - * Create a message object from signed content and a detached armored signature. - * @param {String} content An 8 bit ascii string containing e.g. a MIME subtree with text nodes or attachments - * @param {String} detachedSignature The detached ascii armored PGP signature - */ -function readSignedContent(content, detachedSignature) { - var literalDataPacket = new _packet2.default.Literal(); - literalDataPacket.setBytes(_util2.default.str2Uint8Array(content), _enums2.default.read(_enums2.default.literal, _enums2.default.literal.binary)); - var packetlist = new _packet2.default.List(); - packetlist.push(literalDataPacket); - var input = _armor2.default.decode(detachedSignature).data; - packetlist.read(input); - return new Message(packetlist); -} - /** * creates new message object from text * @param {String} text * @param {String} filename (optional) - * @return {module:message~Message} new message object + * @param {Date} date (optional) + * @returns {module:message~Message} new message object * @static */ function fromText(text, filename) { - var literalDataPacket = new _packet2.default.Literal(); + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + + var literalDataPacket = new _packet2.default.Literal(date); // text will be converted to UTF8 literalDataPacket.setText(text); if (filename !== undefined) { @@ -15801,15 +40415,18 @@ function fromText(text, filename) { * creates new message object from binary data * @param {Uint8Array} bytes * @param {String} filename (optional) - * @return {module:message~Message} new message object + * @param {Date} date (optional) + * @returns {module:message~Message} new message object * @static */ function fromBinary(bytes, filename) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + if (!_util2.default.isUint8Array(bytes)) { throw new Error('Data must be in the form of a Uint8Array'); } - var literalDataPacket = new _packet2.default.Literal(); + var literalDataPacket = new _packet2.default.Literal(date); if (filename) { literalDataPacket.setFilename(filename); } @@ -15822,7 +40439,64 @@ function fromBinary(bytes, filename) { return new Message(literalDataPacketlist); } -},{"./config":10,"./crypto":24,"./encoding/armor.js":33,"./enums.js":35,"./key.js":38,"./packet":47,"./signature.js":66,"./util.js":70}],43:[function(_dereq_,module,exports){ +},{"./config":306,"./crypto":319,"./encoding/armor":335,"./enums":337,"./key":340,"./packet":349,"./signature":369,"./type/keyid":372,"./util":376,"babel-runtime/core-js/array/from":16,"babel-runtime/core-js/promise":25,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],345:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +exports.initWorker = initWorker; +exports.getWorker = getWorker; +exports.destroyWorker = destroyWorker; +exports.generateKey = generateKey; +exports.reformatKey = reformatKey; +exports.decryptKey = decryptKey; +exports.encryptKey = encryptKey; +exports.encrypt = encrypt; +exports.decrypt = decrypt; +exports.sign = sign; +exports.verify = verify; +exports.encryptSessionKey = encryptSessionKey; +exports.decryptSessionKeys = decryptSessionKeys; + +var _message = _dereq_('./message'); + +var messageLib = _interopRequireWildcard(_message); + +var _cleartext = _dereq_('./cleartext'); + +var _key = _dereq_('./key'); + +var _config = _dereq_('./config/config'); + +var _config2 = _interopRequireDefault(_config); + +var _util = _dereq_('./util'); + +var _util2 = _interopRequireDefault(_util); + +var _async_proxy = _dereq_('./worker/async_proxy'); + +var _async_proxy2 = _interopRequireDefault(_async_proxy); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// Old browser polyfills // OpenPGP.js - An OpenPGP implementation in javascript // Copyright (C) 2016 Tankred Hase // @@ -15846,6 +40520,8 @@ function fromBinary(bytes, filename) { * @requires key * @requires config * @requires util + * @requires polyfills + * @requires worker/async_proxy * @module openpgp */ @@ -15855,58 +40531,9 @@ function fromBinary(bytes, filename) { * for extending and developing on top of the base library. */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.initWorker = initWorker; -exports.getWorker = getWorker; -exports.destroyWorker = destroyWorker; -exports.generateKey = generateKey; -exports.reformatKey = reformatKey; -exports.decryptKey = decryptKey; -exports.encrypt = encrypt; -exports.decrypt = decrypt; -exports.sign = sign; -exports.verify = verify; -exports.encryptSessionKey = encryptSessionKey; -exports.decryptSessionKey = decryptSessionKey; - -var _message = _dereq_('./message.js'); - -var messageLib = _interopRequireWildcard(_message); - -var _cleartext = _dereq_('./cleartext.js'); - -var cleartext = _interopRequireWildcard(_cleartext); - -var _key = _dereq_('./key.js'); - -var key = _interopRequireWildcard(_key); - -var _config = _dereq_('./config/config.js'); - -var _config2 = _interopRequireDefault(_config); - -var _util = _dereq_('./util'); - -var _util2 = _interopRequireDefault(_util); - -var _async_proxy = _dereq_('./worker/async_proxy.js'); - -var _async_proxy2 = _interopRequireDefault(_async_proxy); - -var _es6Promise = _dereq_('es6-promise'); - -var _es6Promise2 = _interopRequireDefault(_es6Promise); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -_es6Promise2.default.polyfill(); // load ES6 Promises polyfill - +if (typeof window !== 'undefined') { + _dereq_('./polyfills'); +} ////////////////////////// // // @@ -15919,24 +40546,28 @@ var asyncProxy = void 0; // instance of the asyncproxy /** * Set the path for the web worker script and create an instance of the async proxy - * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js' - * @param {Object} worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' + * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param {Number} n number of workers to initialize + * @param {Array} workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' */ function initWorker() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$path = _ref.path, path = _ref$path === undefined ? 'openpgp.worker.js' : _ref$path, - worker = _ref.worker; + _ref$n = _ref.n, + n = _ref$n === undefined ? 1 : _ref$n, + _ref$workers = _ref.workers, + workers = _ref$workers === undefined ? [] : _ref$workers; - if (worker || typeof window !== 'undefined' && window.Worker) { - asyncProxy = new _async_proxy2.default({ path: path, worker: worker, config: _config2.default }); + if (workers.length || typeof window !== 'undefined' && window.Worker) { + asyncProxy = new _async_proxy2.default({ path: path, n: n, workers: workers, config: _config2.default }); return true; } } /** * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() - * @return {module:worker/async_proxy~AsyncProxy|null} the async proxy or null if not initialized + * @returns {module:worker/async_proxy~AsyncProxy|null} the async proxy or null if not initialized */ function getWorker() { return asyncProxy; @@ -15957,16 +40588,19 @@ function destroyWorker() { /** - * Generates a new OpenPGP key pair. Currently only supports RSA keys. Primary and subkey will be of same type. + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key - * @param {Number} numBits (optional) number of bits for the key creation. (should be 2048 or 4096) + * @param {Number} numBits (optional) number of bits for RSA keys: 2048 or 4096. + * @param {String} curve (optional) elliptic curve for ECC keys: curve25519, p256, p384, p521, or secp256k1 * @param {Boolean} unlocked (optional) If the returned secret part of the generated key is unlocked * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @return {Promise} The generated key object in the form: + * @returns {Promise} The generated key object in the form: * { key:Key, privateKeyArmored:String, publicKeyArmored:String } + * @async * @static */ + function generateKey() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref2$userIds = _ref2.userIds, @@ -15977,21 +40611,30 @@ function generateKey() { _ref2$unlocked = _ref2.unlocked, unlocked = _ref2$unlocked === undefined ? false : _ref2$unlocked, _ref2$keyExpirationTi = _ref2.keyExpirationTime, - keyExpirationTime = _ref2$keyExpirationTi === undefined ? 0 : _ref2$keyExpirationTi; + keyExpirationTime = _ref2$keyExpirationTi === undefined ? 0 : _ref2$keyExpirationTi, + _ref2$curve = _ref2.curve, + curve = _ref2$curve === undefined ? "" : _ref2$curve; - var options = formatUserIds({ userIds: userIds, passphrase: passphrase, numBits: numBits, unlocked: unlocked, keyExpirationTime: keyExpirationTime }); + userIds = formatUserIds(userIds); + var options = { + userIds: userIds, passphrase: passphrase, numBits: numBits, unlocked: unlocked, keyExpirationTime: keyExpirationTime, curve: curve + }; + + if (_util2.default.getWebCryptoAll() && numBits < 2048) { + throw new Error('numBits should be 2048 or 4096, found: ' + numBits); + } if (!_util2.default.getWebCryptoAll() && asyncProxy) { // use web worker if web crypto apis are not supported return asyncProxy.delegate('generateKey', options); } - return key.generate(options).then(function (newKey) { + return (0, _key.generate)(options).then(function (key) { return { - key: newKey, - privateKeyArmored: newKey.armor(), - publicKeyArmored: newKey.toPublic().armor() + key: key, + privateKeyArmored: key.armor(), + publicKeyArmored: key.toPublic().armor() }; }).catch(onError.bind(null, 'Error generating keypair')); @@ -15999,12 +40642,14 @@ function generateKey() { /** * Reformats signature packets for a key and rewraps key object. + * @param {Key} privateKey private key to reformat * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key * @param {Boolean} unlocked (optional) If the returned secret part of the generated key is unlocked * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @return {Promise} The generated key object in the form: + * @returns {Promise} The generated key object in the form: * { key:Key, privateKeyArmored:String, publicKeyArmored:String } + * @async * @static */ function reformatKey() { @@ -16019,18 +40664,22 @@ function reformatKey() { _ref3$keyExpirationTi = _ref3.keyExpirationTime, keyExpirationTime = _ref3$keyExpirationTi === undefined ? 0 : _ref3$keyExpirationTi; - var options = formatUserIds({ privateKey: privateKey, userIds: userIds, passphrase: passphrase, unlocked: unlocked, keyExpirationTime: keyExpirationTime }); + userIds = formatUserIds(userIds); + + var options = { + privateKey: privateKey, userIds: userIds, passphrase: passphrase, unlocked: unlocked, keyExpirationTime: keyExpirationTime + }; if (asyncProxy) { return asyncProxy.delegate('reformatKey', options); } - return key.reformat(options).then(function (newKey) { + return (0, _key.reformat)(options).then(function (key) { return { - key: newKey, - privateKeyArmored: newKey.armor(), - publicKeyArmored: newKey.toPublic().armor() + key: key, + privateKeyArmored: key.armor(), + publicKeyArmored: key.toPublic().armor() }; }).catch(onError.bind(null, 'Error reformatting keypair')); @@ -16040,7 +40689,8 @@ function reformatKey() { * Unlock a private key with your passphrase. * @param {Key} privateKey the private key that is to be decrypted * @param {String} passphrase the user's passphrase chosen during key generation - * @return {Key} the unlocked private key + * @returns {Promise} the unlocked key object in the form: { key:Key } + * @async */ function decryptKey(_ref4) { var privateKey = _ref4.privateKey, @@ -16051,15 +40701,64 @@ function decryptKey(_ref4) { return asyncProxy.delegate('decryptKey', { privateKey: privateKey, passphrase: passphrase }); } - return execute(function () { + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() { + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return privateKey.decrypt(passphrase); - if (!privateKey.decrypt(passphrase)) { - throw new Error('Invalid passphrase'); - } - return { - key: privateKey - }; - }, 'Error decrypting private key'); + case 2: + return _context.abrupt('return', { + key: privateKey + }); + + case 3: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + }))).catch(onError.bind(null, 'Error decrypting private key')); +} + +/** + * Lock a private key with your passphrase. + * @param {Key} privateKey the private key that is to be decrypted + * @param {String} passphrase the user's passphrase chosen during key generation + * @returns {Promise} the locked key object in the form: { key:Key } + * @async + */ +function encryptKey(_ref6) { + var privateKey = _ref6.privateKey, + passphrase = _ref6.passphrase; + + if (asyncProxy) { + // use web worker if available + return asyncProxy.delegate('encryptKey', { privateKey: privateKey, passphrase: passphrase }); + } + + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() { + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return privateKey.encrypt(passphrase); + + case 2: + return _context2.abrupt('return', { + key: privateKey + }); + + case 3: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + }))).catch(onError.bind(null, 'Error decrypting private key')); } /////////////////////////////////////////// @@ -16072,65 +40771,104 @@ function decryptKey(_ref4) { /** * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords * must be specified. If private keys are specified, those will be used to sign the message. - * @param {String|Uint8Array} data text/data to be encrypted as JavaScript binary string or Uint8Array - * @param {Key|Array} publicKeys (optional) array of keys or single key, used to encrypt the message - * @param {Key|Array} privateKeys (optional) private keys for signing. If omitted message will not be signed - * @param {String|Array} passwords (optional) array of passwords or a single password to encrypt the message - * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @param {String} filename (optional) a filename for the literal data packet - * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects - * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object) - * @param {Signature} signature (optional) a detached signature to add to the encrypted message - * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object - * @return {Promise} encrypted (and optionally signed message) in the form: - * {data: ASCII armored message if 'armor' is true, - * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} + * @param {String|Uint8Array} data text/data to be encrypted as JavaScript binary string or Uint8Array + * @param {Key|Array} publicKeys (optional) array of keys or single key, used to encrypt the message + * @param {Key|Array} privateKeys (optional) private keys for signing. If omitted message will not be signed + * @param {String|Array} passwords (optional) array of passwords or a single password to encrypt the message + * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } + * @param {String} filename (optional) a filename for the literal data packet + * @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config + * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects + * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object) + * @param {Signature} signature (optional) a detached signature to add to the encrypted message + * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object + * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param {Date} date (optional) override the creation date of the message and the message signature + * @returns {Promise} encrypted (and optionally signed message) in the form: + * {data: ASCII armored message if 'armor' is true, + * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} + * @async * @static */ -function encrypt(_ref5) { - var data = _ref5.data, - publicKeys = _ref5.publicKeys, - privateKeys = _ref5.privateKeys, - passwords = _ref5.passwords, - sessionKey = _ref5.sessionKey, - filename = _ref5.filename, - _ref5$armor = _ref5.armor, - armor = _ref5$armor === undefined ? true : _ref5$armor, - _ref5$detached = _ref5.detached, - detached = _ref5$detached === undefined ? false : _ref5$detached, - _ref5$signature = _ref5.signature, - signature = _ref5$signature === undefined ? null : _ref5$signature, - _ref5$returnSessionKe = _ref5.returnSessionKey, - returnSessionKey = _ref5$returnSessionKe === undefined ? false : _ref5$returnSessionKe; +function encrypt(_ref8) { + var data = _ref8.data, + publicKeys = _ref8.publicKeys, + privateKeys = _ref8.privateKeys, + passwords = _ref8.passwords, + sessionKey = _ref8.sessionKey, + filename = _ref8.filename, + _ref8$compression = _ref8.compression, + compression = _ref8$compression === undefined ? _config2.default.compression : _ref8$compression, + _ref8$armor = _ref8.armor, + armor = _ref8$armor === undefined ? true : _ref8$armor, + _ref8$detached = _ref8.detached, + detached = _ref8$detached === undefined ? false : _ref8$detached, + _ref8$signature = _ref8.signature, + signature = _ref8$signature === undefined ? null : _ref8$signature, + _ref8$returnSessionKe = _ref8.returnSessionKey, + returnSessionKey = _ref8$returnSessionKe === undefined ? false : _ref8$returnSessionKe, + _ref8$wildcard = _ref8.wildcard, + wildcard = _ref8$wildcard === undefined ? false : _ref8$wildcard, + _ref8$date = _ref8.date, + date = _ref8$date === undefined ? new Date() : _ref8$date; checkData(data);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords); if (!nativeAEAD() && asyncProxy) { // use web worker if web crypto apis are not supported - return asyncProxy.delegate('encrypt', { data: data, publicKeys: publicKeys, privateKeys: privateKeys, passwords: passwords, sessionKey: sessionKey, filename: filename, armor: armor, detached: detached, signature: signature, returnSessionKey: returnSessionKey }); + return asyncProxy.delegate('encrypt', { data: data, publicKeys: publicKeys, privateKeys: privateKeys, passwords: passwords, sessionKey: sessionKey, filename: filename, armor: armor, detached: detached, signature: signature, returnSessionKey: returnSessionKey, wildcard: wildcard, date: date }); } var result = {}; - return Promise.resolve().then(function () { + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() { + var message, detachedSignature; + return _regenerator2.default.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + message = createMessage(data, filename, date); - var message = createMessage(data, filename); - if (!privateKeys) { - privateKeys = []; - } - if (privateKeys.length || signature) { - // sign the message only if private keys or signature is specified - if (detached) { - var detachedSignature = message.signDetached(privateKeys, signature); - if (armor) { - result.signature = detachedSignature.armor(); - } else { - result.signature = detachedSignature; + if (!privateKeys) { + privateKeys = []; + } + + if (!(privateKeys.length || signature)) { + _context3.next = 13; + break; + } + + if (!detached) { + _context3.next = 10; + break; + } + + _context3.next = 6; + return message.signDetached(privateKeys, signature, date); + + case 6: + detachedSignature = _context3.sent; + + result.signature = armor ? detachedSignature.armor() : detachedSignature; + _context3.next = 13; + break; + + case 10: + _context3.next = 12; + return message.sign(privateKeys, signature, date); + + case 12: + message = _context3.sent; + + case 13: + message = message.compress(compression); + return _context3.abrupt('return', message.encrypt(publicKeys, passwords, sessionKey, wildcard, date)); + + case 15: + case 'end': + return _context3.stop(); } - } else { - message = message.sign(privateKeys, signature); } - } - return message.encrypt(publicKeys, passwords, sessionKey); - }).then(function (encrypted) { + }, _callee3, this); + }))).then(function (encrypted) { if (armor) { result.data = encrypted.message.armor(); } else { @@ -16146,51 +40884,89 @@ function encrypt(_ref5) { /** * Decrypts a message with the user's private key, a session key or a password. Either a private key, * a session key or a password must be specified. - * @param {Message} message the message object with the encrypted data - * @param {Key} privateKey (optional) private key with decrypted secret key data or session key - * @param {Key|Array} publicKeys (optional) array of public keys or single key, to verify signatures - * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @param {String} password (optional) single password to decrypt the message - * @param {String} format (optional) return data format either as 'utf8' or 'binary' - * @param {Signature} signature (optional) detached signature for verification - * @return {Promise} decrypted and verified message in the form: + * @param {Message} message the message object with the encrypted data + * @param {Key|Array} privateKeys (optional) private keys with decrypted secret key data or session key + * @param {String|Array} passwords (optional) passwords to decrypt the message + * @param {Object|Array} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String } + * @param {Key|Array} publicKeys (optional) array of public keys or single key, to verify signatures + * @param {String} format (optional) return data format either as 'utf8' or 'binary' + * @param {Signature} signature (optional) detached signature for verification + * @param {Date} date (optional) use the given date for verification instead of the current time + * @returns {Promise} decrypted and verified message in the form: * { data:Uint8Array|String, filename:String, signatures:[{ keyid:String, valid:Boolean }] } + * @async * @static */ -function decrypt(_ref6) { - var message = _ref6.message, - privateKey = _ref6.privateKey, - publicKeys = _ref6.publicKeys, - sessionKey = _ref6.sessionKey, - password = _ref6.password, - _ref6$format = _ref6.format, - format = _ref6$format === undefined ? 'utf8' : _ref6$format, - _ref6$signature = _ref6.signature, - signature = _ref6$signature === undefined ? null : _ref6$signature; +function decrypt(_ref10) { + var message = _ref10.message, + privateKeys = _ref10.privateKeys, + passwords = _ref10.passwords, + sessionKeys = _ref10.sessionKeys, + publicKeys = _ref10.publicKeys, + _ref10$format = _ref10.format, + format = _ref10$format === undefined ? 'utf8' : _ref10$format, + _ref10$signature = _ref10.signature, + signature = _ref10$signature === undefined ? null : _ref10$signature, + _ref10$date = _ref10.date, + date = _ref10$date === undefined ? new Date() : _ref10$date; - checkMessage(message);publicKeys = toArray(publicKeys); + checkMessage(message);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords);sessionKeys = toArray(sessionKeys); if (!nativeAEAD() && asyncProxy) { // use web worker if web crypto apis are not supported - return asyncProxy.delegate('decrypt', { message: message, privateKey: privateKey, publicKeys: publicKeys, sessionKey: sessionKey, password: password, format: format, signature: signature }); + return asyncProxy.delegate('decrypt', { message: message, privateKeys: privateKeys, passwords: passwords, sessionKeys: sessionKeys, publicKeys: publicKeys, format: format, signature: signature, date: date }); } - return message.decrypt(privateKey, sessionKey, password).then(function (message) { + return message.decrypt(privateKeys, passwords, sessionKeys).then(function () { + var _ref11 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(message) { + var result; + return _regenerator2.default.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + result = parseMessage(message, format); - var result = parseMessage(message, format); - if (!publicKeys) { - publicKeys = []; - } - if (signature) { - //detached signature - result.signatures = message.verifyDetached(signature, publicKeys); - } else { - result.signatures = message.verify(publicKeys); - } + if (!publicKeys) { + publicKeys = []; + } - return result; - }).catch(onError.bind(null, 'Error decrypting message')); + if (!signature) { + _context4.next = 8; + break; + } + + _context4.next = 5; + return message.verifyDetached(signature, publicKeys, date); + + case 5: + _context4.t0 = _context4.sent; + _context4.next = 11; + break; + + case 8: + _context4.next = 10; + return message.verify(publicKeys, date); + + case 10: + _context4.t0 = _context4.sent; + + case 11: + result.signatures = _context4.t0; + return _context4.abrupt('return', result); + + case 13: + case 'end': + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function (_x4) { + return _ref11.apply(this, arguments); + }; + }()).catch(onError.bind(null, 'Error decrypting message')); } ////////////////////////////////////////// @@ -16206,55 +40982,80 @@ function decrypt(_ref6) { * @param {Key|Array} privateKeys array of keys or single key with decrypted secret key data to sign cleartext * @param {Boolean} armor (optional) if the return value should be ascii armored or the message object * @param {Boolean} detached (optional) if the return value should contain a detached signature - * @return {Promise} signed cleartext in the form: + * @param {Date} date (optional) override the creation date signature + * @returns {Promise} signed cleartext in the form: * {data: ASCII armored message if 'armor' is true, * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} + * @async * @static */ -function sign(_ref7) { - var data = _ref7.data, - privateKeys = _ref7.privateKeys, - _ref7$armor = _ref7.armor, - armor = _ref7$armor === undefined ? true : _ref7$armor, - _ref7$detached = _ref7.detached, - detached = _ref7$detached === undefined ? false : _ref7$detached; +function sign(_ref12) { + var data = _ref12.data, + privateKeys = _ref12.privateKeys, + _ref12$armor = _ref12.armor, + armor = _ref12$armor === undefined ? true : _ref12$armor, + _ref12$detached = _ref12.detached, + detached = _ref12$detached === undefined ? false : _ref12$detached, + _ref12$date = _ref12.date, + date = _ref12$date === undefined ? new Date() : _ref12$date; checkData(data); privateKeys = toArray(privateKeys); if (asyncProxy) { // use web worker if available - return asyncProxy.delegate('sign', { data: data, privateKeys: privateKeys, armor: armor, detached: detached }); + return asyncProxy.delegate('sign', { + data: data, privateKeys: privateKeys, armor: armor, detached: detached, date: date + }); } var result = {}; - return execute(function () { - var message; + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5() { + var message, signature; + return _regenerator2.default.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + message = _util2.default.isString(data) ? new _cleartext.CleartextMessage(data) : messageLib.fromBinary(data); - if (_util2.default.isString(data)) { - message = new cleartext.CleartextMessage(data); - } else { - message = messageLib.fromBinary(data); - } + if (!detached) { + _context5.next = 8; + break; + } - if (detached) { - var signature = message.signDetached(privateKeys); - if (armor) { - result.signature = signature.armor(); - } else { - result.signature = signature; + _context5.next = 4; + return message.signDetached(privateKeys, undefined, date); + + case 4: + signature = _context5.sent; + + result.signature = armor ? signature.armor() : signature; + _context5.next = 12; + break; + + case 8: + _context5.next = 10; + return message.sign(privateKeys, undefined, date); + + case 10: + message = _context5.sent; + + if (armor) { + result.data = message.armor(); + } else { + result.message = message; + } + + case 12: + return _context5.abrupt('return', result); + + case 13: + case 'end': + return _context5.stop(); + } } - } else { - message = message.sign(privateKeys); - if (armor) { - result.data = message.armor(); - } else { - result.message = message; - } - } - - return result; - }, 'Error signing cleartext message'); + }, _callee5, this); + }))).catch(onError.bind(null, 'Error signing cleartext message')); } /** @@ -16262,39 +41063,69 @@ function sign(_ref7) { * @param {Key|Array} publicKeys array of publicKeys or single key, to verify signatures * @param {CleartextMessage} message cleartext message object with signatures * @param {Signature} signature (optional) detached signature for verification - * @return {Promise} cleartext with status of verified signatures in the form of: - * { data:String, signatures: [{ keyid:String, valid:Boolean }] } + * @param {Date} date (optional) use the given date for verification instead of the current time + * @returns {Promise} cleartext with status of verified signatures in the form of: + * { data:String, signatures: [{ keyid:String, valid:Boolean }] } + * @async * @static */ -function verify(_ref8) { - var message = _ref8.message, - publicKeys = _ref8.publicKeys, - _ref8$signature = _ref8.signature, - signature = _ref8$signature === undefined ? null : _ref8$signature; +function verify(_ref14) { + var message = _ref14.message, + publicKeys = _ref14.publicKeys, + _ref14$signature = _ref14.signature, + signature = _ref14$signature === undefined ? null : _ref14$signature, + _ref14$date = _ref14.date, + date = _ref14$date === undefined ? new Date() : _ref14$date; checkCleartextOrMessage(message); publicKeys = toArray(publicKeys); if (asyncProxy) { // use web worker if available - return asyncProxy.delegate('verify', { message: message, publicKeys: publicKeys, signature: signature }); + return asyncProxy.delegate('verify', { message: message, publicKeys: publicKeys, signature: signature, date: date }); } - var result = {}; - return execute(function () { - if (cleartext.CleartextMessage.prototype.isPrototypeOf(message)) { - result.data = message.getText(); - } else { - result.data = message.getLiteralData(); - } - if (signature) { - //detached signature - result.signatures = message.verifyDetached(signature, publicKeys); - } else { - result.signatures = message.verify(publicKeys); - } - return result; - }, 'Error verifying cleartext signed message'); + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6() { + var result; + return _regenerator2.default.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + result = {}; + + result.data = message instanceof _cleartext.CleartextMessage ? message.getText() : message.getLiteralData(); + + if (!signature) { + _context6.next = 8; + break; + } + + _context6.next = 5; + return message.verifyDetached(signature, publicKeys, date); + + case 5: + _context6.t0 = _context6.sent; + _context6.next = 11; + break; + + case 8: + _context6.next = 10; + return message.verify(publicKeys, date); + + case 10: + _context6.t0 = _context6.sent; + + case 11: + result.signatures = _context6.t0; + return _context6.abrupt('return', result); + + case 13: + case 'end': + return _context6.stop(); + } + } + }, _callee6, this); + }))).catch(onError.bind(null, 'Error verifying cleartext signed message')); } /////////////////////////////////////////////// @@ -16311,57 +41142,87 @@ function verify(_ref8) { * @param {String} algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' * @param {Key|Array} publicKeys (optional) array of public keys or single key, used to encrypt the key * @param {String|Array} passwords (optional) passwords for the message - * @return {Promise} the encrypted session key packets contained in a message object + * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs + * @returns {Promise} the encrypted session key packets contained in a message object + * @async * @static */ -function encryptSessionKey(_ref9) { - var data = _ref9.data, - algorithm = _ref9.algorithm, - publicKeys = _ref9.publicKeys, - passwords = _ref9.passwords; +function encryptSessionKey(_ref16) { + var data = _ref16.data, + algorithm = _ref16.algorithm, + publicKeys = _ref16.publicKeys, + passwords = _ref16.passwords, + _ref16$wildcard = _ref16.wildcard, + wildcard = _ref16$wildcard === undefined ? false : _ref16$wildcard; checkBinary(data);checkString(algorithm, 'algorithm');publicKeys = toArray(publicKeys);passwords = toArray(passwords); if (asyncProxy) { // use web worker if available - return asyncProxy.delegate('encryptSessionKey', { data: data, algorithm: algorithm, publicKeys: publicKeys, passwords: passwords }); + return asyncProxy.delegate('encryptSessionKey', { data: data, algorithm: algorithm, publicKeys: publicKeys, passwords: passwords, wildcard: wildcard }); } - return execute(function () { - return { + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7() { + return _regenerator2.default.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return messageLib.encryptSessionKey(data, algorithm, publicKeys, passwords, wildcard); - message: messageLib.encryptSessionKey(data, algorithm, publicKeys, passwords) + case 2: + _context7.t0 = _context7.sent; + return _context7.abrupt('return', { + message: _context7.t0 + }); - }; - }, 'Error encrypting session key'); + case 4: + case 'end': + return _context7.stop(); + } + } + }, _callee7, this); + }))).catch(onError.bind(null, 'Error encrypting session key')); } /** - * Decrypt a symmetric session key with a private key or password. Either a private key or + * Decrypt symmetric session keys with a private key or password. Either a private key or * a password must be specified. - * @param {Message} message a message object containing the encrypted session key packets - * @param {Key} privateKey (optional) private key with decrypted secret key data - * @param {String} password (optional) a single password to decrypt the session key - * @return {Promise} decrypted session key and algorithm in object form: + * @param {Message} message a message object containing the encrypted session key packets + * @param {Key|Array} privateKeys (optional) private keys with decrypted secret key data + * @param {String|Array} passwords (optional) passwords to decrypt the session key + * @returns {Promise} Array of decrypted session key, algorithm pairs in form: * { data:Uint8Array, algorithm:String } * or 'undefined' if no key packets found + * @async * @static */ -function decryptSessionKey(_ref10) { - var message = _ref10.message, - privateKey = _ref10.privateKey, - password = _ref10.password; +function decryptSessionKeys(_ref18) { + var message = _ref18.message, + privateKeys = _ref18.privateKeys, + passwords = _ref18.passwords; - checkMessage(message); + checkMessage(message);privateKeys = toArray(privateKeys);passwords = toArray(passwords); if (asyncProxy) { // use web worker if available - return asyncProxy.delegate('decryptSessionKey', { message: message, privateKey: privateKey, password: password }); + return asyncProxy.delegate('decryptSessionKeys', { message: message, privateKeys: privateKeys, passwords: passwords }); } - return execute(function () { - return message.decryptSessionKey(privateKey, password); - }, 'Error decrypting session key'); + return _promise2.default.resolve().then((0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8() { + return _regenerator2.default.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + return _context8.abrupt('return', message.decryptSessionKeys(privateKeys, passwords)); + + case 1: + case 'end': + return _context8.stop(); + } + } + }, _callee8, this); + }))).catch(onError.bind(null, 'Error decrypting session keys')); } ////////////////////////// @@ -16390,12 +41251,12 @@ function checkData(data, name) { } } function checkMessage(message) { - if (!messageLib.Message.prototype.isPrototypeOf(message)) { + if (!(message instanceof messageLib.Message)) { throw new Error('Parameter [message] needs to be of type Message'); } } function checkCleartextOrMessage(message) { - if (!cleartext.CleartextMessage.prototype.isPrototypeOf(message) && !messageLib.Message.prototype.isPrototypeOf(message)) { + if (!(message instanceof _cleartext.CleartextMessage) && !(message instanceof messageLib.Message)) { throw new Error('Parameter [message] needs to be of type Message or CleartextMessage'); } } @@ -16403,12 +41264,12 @@ function checkCleartextOrMessage(message) { /** * Format user ids for internal use. */ -function formatUserIds(options) { - if (!options.userIds) { - return options; +function formatUserIds(userIds) { + if (!userIds) { + return userIds; } - options.userIds = toArray(options.userIds); // normalize to array - options.userIds = options.userIds.map(function (id) { + userIds = toArray(userIds); // normalize to array + userIds = userIds.map(function (id) { if (_util2.default.isString(id) && !_util2.default.isUserId(id)) { throw new Error('Invalid user id format'); } @@ -16427,13 +41288,13 @@ function formatUserIds(options) { } return id.name + '<' + id.email + '>'; }); - return options; + return userIds; } /** * Normalize parameter to an array if it is not undefined. * @param {Object} param the parameter to be normalized - * @return {Array|undefined} the resulting array or undefined + * @returns {Array|undefined} the resulting array or undefined */ function toArray(param) { if (param && !_util2.default.isArray(param)) { @@ -16446,14 +41307,17 @@ function toArray(param) { * Creates a message obejct either from a Uint8Array or a string. * @param {String|Uint8Array} data the payload for the message * @param {String} filename the literal data packet's filename - * @return {Message} a message object + * @param {Date} date the creation date of the package + * @returns {Message} a message object */ function createMessage(data, filename) { + var date = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Date(); + var msg = void 0; if (_util2.default.isUint8Array(data)) { - msg = messageLib.fromBinary(data, filename); + msg = messageLib.fromBinary(data, filename, date); } else if (_util2.default.isString(data)) { - msg = messageLib.fromText(data, filename); + msg = messageLib.fromText(data, filename, date); } else { throw new Error('Data must be of type String or Uint8Array'); } @@ -16464,7 +41328,7 @@ function createMessage(data, filename) { * Parse the message given a certain format. * @param {Message} message the message object to be parse * @param {String} format the output format e.g. 'utf8' or 'binary' - * @return {Object} the parse data in the respective format + * @returns {Object} the parse data in the respective format */ function parseMessage(message, format) { if (format === 'binary') { @@ -16477,25 +41341,8 @@ function parseMessage(message, format) { data: message.getText(), filename: message.getFilename() }; - } else { - throw new Error('Invalid format'); } -} - -/** - * Command pattern that wraps synchronous code into a promise. - * @param {function} cmd The synchronous function with a return value - * to be wrapped in a promise - * @param {String} message A human readable error Message - * @return {Promise} The promise wrapped around cmd - */ -function execute(cmd, message) { - // wrap the sync cmd in a promise - var promise = new Promise(function (resolve) { - return resolve(cmd()); - }); - // handler error globally - return promise.catch(onError.bind(null, message)); + throw new Error('Invalid format'); } /** @@ -16518,18 +41365,13 @@ function onError(message, error) { /** * Check for AES-GCM support and configuration by the user. Only browsers that * implement the current WebCrypto specification support native AES-GCM. - * @return {Boolean} If authenticated encryption should be used + * @returns {Boolean} If authenticated encryption should be used */ function nativeAEAD() { return _util2.default.getWebCrypto() && _config2.default.aead_protect; } -},{"./cleartext.js":5,"./config/config.js":9,"./key.js":38,"./message.js":42,"./util":70,"./worker/async_proxy.js":71,"es6-promise":2}],44:[function(_dereq_,module,exports){ -/** - * @requires enums - * @module packet - */ - +},{"./cleartext":303,"./config/config":305,"./key":340,"./message":344,"./polyfills":368,"./util":376,"./worker/async_proxy":377,"babel-runtime/core-js/promise":25,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],346:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16742,30 +41584,7 @@ function packetClassFromTagName(tag) { return tag.substr(0, 1).toUpperCase() + tag.substr(1); } -},{"../enums.js":35,"./all_packets.js":44,"./compressed.js":46,"./literal.js":48,"./marker.js":49,"./one_pass_signature.js":50,"./public_key.js":53,"./public_key_encrypted_session_key.js":54,"./public_subkey.js":55,"./secret_key.js":56,"./secret_subkey.js":57,"./signature.js":58,"./sym_encrypted_aead_protected.js":59,"./sym_encrypted_integrity_protected.js":60,"./sym_encrypted_session_key.js":61,"./symmetrically_encrypted.js":62,"./trust.js":63,"./user_attribute.js":64,"./userid.js":65}],45:[function(_dereq_,module,exports){ -// OpenPGP.js - An OpenPGP implementation in javascript -// Copyright (C) 2015 Tankred Hase -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * @fileoverview This module implements packet list cloning required to - * pass certain object types between the web worker and main thread using - * the structured cloning algorithm. - */ - +},{"../enums.js":337,"./all_packets.js":346,"./compressed.js":348,"./literal.js":350,"./marker.js":351,"./one_pass_signature.js":352,"./public_key.js":355,"./public_key_encrypted_session_key.js":356,"./public_subkey.js":357,"./secret_key.js":358,"./secret_subkey.js":359,"./signature.js":360,"./sym_encrypted_aead_protected.js":361,"./sym_encrypted_integrity_protected.js":362,"./sym_encrypted_session_key.js":363,"./symmetrically_encrypted.js":364,"./trust.js":365,"./user_attribute.js":366,"./userid.js":367}],347:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16774,33 +41593,27 @@ Object.defineProperty(exports, "__esModule", { exports.clonePackets = clonePackets; exports.parseClonedPackets = parseClonedPackets; -var _key = _dereq_('../key.js'); +var _key = _dereq_('../key'); -var key = _interopRequireWildcard(_key); +var _message = _dereq_('../message'); -var _message = _dereq_('../message.js'); +var _cleartext = _dereq_('../cleartext'); -var message = _interopRequireWildcard(_message); +var _signature = _dereq_('../signature'); -var _cleartext = _dereq_('../cleartext.js'); - -var cleartext = _interopRequireWildcard(_cleartext); - -var _signature = _dereq_('../signature.js'); - -var signature = _interopRequireWildcard(_signature); - -var _packetlist = _dereq_('./packetlist.js'); +var _packetlist = _dereq_('./packetlist'); var _packetlist2 = _interopRequireDefault(_packetlist); -var _keyid = _dereq_('../type/keyid.js'); +var _keyid = _dereq_('../type/keyid'); var _keyid2 = _interopRequireDefault(_keyid); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _util = _dereq_('../util'); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ////////////////////////////// // // @@ -16812,7 +41625,7 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; /** * Create a packetlist from the correspoding object types. * @param {Object} options the object passed to and from the web worker - * @return {Object} a mutated version of the options optject + * @returns {Object} a mutated version of the options optject */ function clonePackets(options) { if (options.publicKeys) { @@ -16833,13 +41646,13 @@ function clonePackets(options) { } if (options.message) { //could be either a Message or CleartextMessage object - if (options.message instanceof message.Message) { + if (options.message instanceof _message.Message) { options.message = options.message.packets; - } else if (options.message instanceof cleartext.CleartextMessage) { - options.message.signature = options.message.signature.packets; + } else if (options.message instanceof _cleartext.CleartextMessage) { + options.message = { text: options.message.text, signature: options.message.signature.packets }; } } - if (options.signature && options.signature instanceof signature.Signature) { + if (options.signature && options.signature instanceof _signature.Signature) { options.signature = options.signature.packets; } if (options.signatures) { @@ -16848,7 +41661,29 @@ function clonePackets(options) { }); } return options; -} +} // OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015 Tankred Hase +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * @fileoverview This module implements packet list cloning required to + * pass certain object types between the web worker and main thread using + * the structured cloning algorithm. + * @module packet/clone + */ function verificationObjectToClone(verObject) { verObject.signature = verObject.signature.packets; @@ -16866,9 +41701,9 @@ function verificationObjectToClone(verObject) { * Creates an object with the correct prototype from a corresponding packetlist. * @param {Object} options the object passed to and from the web worker * @param {String} method the public api function name to be delegated to the worker - * @return {Object} a mutated version of the options optject + * @returns {Object} a mutated version of the options optject */ -function parseClonedPackets(options, method) { +function parseClonedPackets(options) { if (options.publicKeys) { options.publicKeys = options.publicKeys.map(packetlistCloneToKey); } @@ -16897,37 +41732,65 @@ function parseClonedPackets(options, method) { function packetlistCloneToKey(clone) { var packetlist = _packetlist2.default.fromStructuredClone(clone); - return new key.Key(packetlist); + return new _key.Key(packetlist); } function packetlistCloneToMessage(clone) { var packetlist = _packetlist2.default.fromStructuredClone(clone); - return new message.Message(packetlist); + return new _message.Message(packetlist); } function packetlistCloneToCleartextMessage(clone) { var packetlist = _packetlist2.default.fromStructuredClone(clone.signature); - return new cleartext.CleartextMessage(clone.text, new signature.Signature(packetlist)); + return new _cleartext.CleartextMessage(clone.text, new _signature.Signature(packetlist)); } //verification objects function packetlistCloneToSignatures(clone) { clone.keyid = _keyid2.default.fromClone(clone.keyid); - clone.signature = new signature.Signature(clone.signature); + clone.signature = new _signature.Signature(clone.signature); return clone; } function packetlistCloneToSignature(clone) { - if (typeof clone === "string") { + if (_util2.default.isString(clone)) { //signature is armored return clone; } var packetlist = _packetlist2.default.fromStructuredClone(clone); - return new signature.Signature(packetlist); + return new _signature.Signature(packetlist); } -},{"../cleartext.js":5,"../key.js":38,"../message.js":42,"../signature.js":66,"../type/keyid.js":67,"./packetlist.js":52}],46:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +},{"../cleartext":303,"../key":340,"../message":344,"../signature":369,"../type/keyid":372,"../util":376,"./packetlist":354}],348:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _pako = _dereq_('pako'); + +var _pako2 = _interopRequireDefault(_pako); + +var _config = _dereq_('../config'); + +var _config2 = _interopRequireDefault(_config); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../util.js'); + +var _util2 = _interopRequireDefault(_util); + +var _bzip2Build = _dereq_('../compression/bzip2.build.js'); + +var _bzip2Build2 = _interopRequireDefault(_bzip2Build); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nodeZlib = _util2.default.getNodeZlib(); // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -16945,47 +41808,74 @@ function packetlistCloneToSignature(clone) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Compressed Data Packet (Tag 8)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: The Compressed Data packet contains compressed data. Typically, + * Implementation of the Compressed Data Packet (Tag 8) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, * this packet is found as the contents of an encrypted packet, or following * a Signature or One-Pass Signature packet, and contains a literal data packet. * @requires compression/zlib * @requires compression/rawinflate * @requires compression/rawdeflate + * @requires compression/bzip2 * @requires enums * @requires util * @module packet/compressed */ -'use strict'; +var Buffer = _util2.default.getNodeBuffer(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = Compressed; +function node_zlib(func) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -var _enums = _dereq_('../enums.js'); + return function (data) { + return func(data, options); + }; +} -var _enums2 = _interopRequireDefault(_enums); +function pako_zlib(constructor) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -var _util = _dereq_('../util.js'); + return function (data) { + var obj = new constructor(options); + obj.push(data, true); + return obj.result; + }; +} -var _util2 = _interopRequireDefault(_util); +var compress_fns = void 0; +var decompress_fns = void 0; +if (nodeZlib) { + // Use Node native zlib for DEFLATE compression/decompression + compress_fns = { + // eslint-disable-next-line no-sync + zip: node_zlib(nodeZlib.deflateRawSync, { level: _config2.default.deflate_level }), + // eslint-disable-next-line no-sync + zlib: node_zlib(nodeZlib.deflateSync, { level: _config2.default.deflate_level }), + bzip2: _bzip2Build2.default.compressFile + }; -var _zlibMin = _dereq_('../compression/zlib.min.js'); + decompress_fns = { + // eslint-disable-next-line no-sync + zip: node_zlib(nodeZlib.inflateRawSync), + // eslint-disable-next-line no-sync + zlib: node_zlib(nodeZlib.inflateSync), + bzip2: _bzip2Build2.default.decompressFile + }; +} else { + // Use JS fallbacks + compress_fns = { + zip: pako_zlib(_pako2.default.Deflate, { raw: true, level: _config2.default.deflate_level }), + zlib: pako_zlib(_pako2.default.Deflate, { level: _config2.default.deflate_level }), + bzip2: _bzip2Build2.default.compressFile + }; -var _zlibMin2 = _interopRequireDefault(_zlibMin); - -var _rawinflateMin = _dereq_('../compression/rawinflate.min.js'); - -var _rawinflateMin2 = _interopRequireDefault(_rawinflateMin); - -var _rawdeflateMin = _dereq_('../compression/rawdeflate.min.js'); - -var _rawdeflateMin2 = _interopRequireDefault(_rawdeflateMin); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + decompress_fns = { + zip: pako_zlib(_pako2.default.Inflate, { raw: true }), + zlib: pako_zlib(_pako2.default.Inflate), + bzip2: _bzip2Build2.default.decompressFile + }; +} /** * @constructor @@ -17030,14 +41920,14 @@ Compressed.prototype.read = function (bytes) { /** * Return the compressed packet. - * @return {String} binary compressed packet + * @returns {String} binary compressed packet */ Compressed.prototype.write = function () { if (this.compressed === null) { this.compress(); } - return _util2.default.concatUint8Array(new Uint8Array([_enums2.default.write(_enums2.default.compression, this.algorithm)]), this.compressed); + return _util2.default.concatUint8Array([new Uint8Array([_enums2.default.write(_enums2.default.compression, this.algorithm)]), this.compressed]); }; /** @@ -17045,71 +41935,29 @@ Compressed.prototype.write = function () { * read by read_packet */ Compressed.prototype.decompress = function () { - var decompressed, inflate; - switch (this.algorithm) { - case 'uncompressed': - decompressed = this.compressed; - break; - - case 'zip': - inflate = new _rawinflateMin2.default.Zlib.RawInflate(this.compressed); - decompressed = inflate.decompress(); - break; - - case 'zlib': - inflate = new _zlibMin2.default.Zlib.Inflate(this.compressed); - decompressed = inflate.decompress(); - break; - - case 'bzip2': - // TODO: need to implement this - throw new Error('Compression algorithm BZip2 [BZ2] is not implemented.'); - - default: - throw new Error("Compression algorithm unknown :" + this.algorithm); + if (!decompress_fns[this.algorithm]) { + throw new Error("Compression algorithm unknown :" + this.algorithm); } - this.packets.read(decompressed); + this.packets.read(decompress_fns[this.algorithm](this.compressed)); }; /** * Compress the packet data (member decompressedData) */ Compressed.prototype.compress = function () { - var uncompressed, deflate; - uncompressed = this.packets.write(); - switch (this.algorithm) { - - case 'uncompressed': - // - Uncompressed - this.compressed = uncompressed; - break; - - case 'zip': - // - ZIP [RFC1951] - deflate = new _rawdeflateMin2.default.Zlib.RawDeflate(uncompressed); - this.compressed = deflate.compress(); - break; - - case 'zlib': - // - ZLIB [RFC1950] - deflate = new _zlibMin2.default.Zlib.Deflate(uncompressed); - this.compressed = deflate.compress(); - break; - - case 'bzip2': - // - BZip2 [BZ2] - // TODO: need to implement this - throw new Error("Compression algorithm BZip2 [BZ2] is not implemented."); - - default: - throw new Error("Compression algorithm unknown :" + this.type); + if (!compress_fns[this.algorithm]) { + throw new Error("Compression algorithm unknown :" + this.algorithm); } + + this.compressed = compress_fns[this.algorithm](this.packets.write()); }; -},{"../compression/rawdeflate.min.js":6,"../compression/rawinflate.min.js":7,"../compression/zlib.min.js":8,"../enums.js":35,"../util.js":70}],47:[function(_dereq_,module,exports){ +exports.default = Compressed; + +},{"../compression/bzip2.build.js":304,"../config":306,"../enums.js":337,"../util.js":376,"pako":282}],349:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17137,7 +41985,13 @@ var mod = { List: _packetlist2.default, /** @see module:packet/clone */ clone: clone -}; +}; /** + * @fileoverview OpenPGP packet types + * @see module:packet/all_packets + * @see module:packet/packetlist + * @see module:packet/clone + * @module packet + */ for (var i in packets) { mod[i] = packets[i]; @@ -17145,7 +41999,27 @@ for (var i in packets) { exports.default = mod; -},{"./all_packets.js":44,"./clone.js":45,"./packetlist.js":52}],48:[function(_dereq_,module,exports){ +},{"./all_packets.js":346,"./clone.js":347,"./packetlist.js":354}],350:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _util = _dereq_('../util.js'); + +var _util2 = _interopRequireDefault(_util); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @param {Date} date the creation date of the literal package + * @constructor + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -17164,39 +42038,22 @@ exports.default = mod; // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Literal Data Packet (Tag 11)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: A Literal Data packet contains the body of a message; data that - * is not to be further interpreted. + * Implementation of the Literal Data Packet (Tag 11) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. * @requires enums * @requires util * @module packet/literal */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = Literal; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @constructor - */ function Literal() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + this.tag = _enums2.default.packet.literal; this.format = 'utf8'; // default format for literal data packets - this.date = new Date(); + this.date = _util2.default.normalizeDate(date); this.data = new Uint8Array(0); // literal data representation this.filename = 'msg.txt'; } @@ -17210,17 +42067,17 @@ Literal.prototype.setText = function (text) { // normalize EOL to \r\n text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n'); // encode UTF8 - this.data = this.format === 'utf8' ? _util2.default.str2Uint8Array(_util2.default.encode_utf8(text)) : _util2.default.str2Uint8Array(text); + this.data = this.format === 'utf8' ? _util2.default.str_to_Uint8Array(_util2.default.encode_utf8(text)) : _util2.default.str_to_Uint8Array(text); }; /** * Returns literal data packets as native JavaScript string * with normalized end of line to \n - * @return {String} literal data as text + * @returns {String} literal data as text */ Literal.prototype.getText = function () { // decode UTF8 - var text = _util2.default.decode_utf8(_util2.default.Uint8Array2str(this.data)); + var text = _util2.default.decode_utf8(_util2.default.Uint8Array_to_str(this.data)); // normalize EOL to \n return text.replace(/\r\n/g, '\n'); }; @@ -17263,14 +42120,14 @@ Literal.prototype.getFilename = function () { * Parsing function for a literal data packet (tag 11). * * @param {Uint8Array} input Payload of a tag 11 packet - * @return {module:packet/literal} object representation + * @returns {module:packet/literal} object representation */ Literal.prototype.read = function (bytes) { // - A one-octet field that describes how the data is formatted. var format = _enums2.default.read(_enums2.default.literal, bytes[0]); var filename_len = bytes[1]; - this.filename = _util2.default.decode_utf8(_util2.default.Uint8Array2str(bytes.subarray(2, 2 + filename_len))); + this.filename = _util2.default.decode_utf8(_util2.default.Uint8Array_to_str(bytes.subarray(2, 2 + filename_len))); this.date = _util2.default.readDate(bytes.subarray(2 + filename_len, 2 + filename_len + 4)); @@ -17282,10 +42139,10 @@ Literal.prototype.read = function (bytes) { /** * Creates a string representation of the packet * - * @return {Uint8Array} Uint8Array representation of the packet + * @returns {Uint8Array} Uint8Array representation of the packet */ Literal.prototype.write = function () { - var filename = _util2.default.str2Uint8Array(_util2.default.encode_utf8(this.filename)); + var filename = _util2.default.str_to_Uint8Array(_util2.default.encode_utf8(this.filename)); var filename_length = new Uint8Array([filename.length]); var format = new Uint8Array([_enums2.default.write(_enums2.default.literal, this.format)]); @@ -17295,44 +42152,14 @@ Literal.prototype.write = function () { return _util2.default.concatUint8Array([format, filename_length, filename, date, data]); }; -},{"../enums.js":35,"../util.js":70}],49:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - -/** - * Implementation of the strange "Marker packet" (Tag 10)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet.
- *
- * Such a packet MUST be ignored when received. - * @requires enums - * @module packet/marker - */ +exports.default = Literal; +},{"../enums.js":337,"../util.js":376}],351:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Marker; var _enums = _dereq_('../enums.js'); @@ -17356,20 +42183,8 @@ function Marker() { * @param {Integer} len * Length of the packet or the remaining length of * input at position - * @return {module:packet/marker} Object representation + * @returns {module:packet/marker} Object representation */ -Marker.prototype.read = function (bytes) { - if (bytes[0] === 0x50 && // P - bytes[1] === 0x47 && // G - bytes[2] === 0x50) { - // P - return true; - } - // marker packet does not contain "PGP" - return false; -}; - -},{"../enums.js":35}],50:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -17388,25 +42203,38 @@ Marker.prototype.read = function (bytes) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the One-Pass Signature Packets (Tag 4)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. -* @requires util + * Implementation of the strange "Marker packet" (Tag 10) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * + * Such a packet MUST be ignored when received. * @requires enums - * @requires type/keyid - * @module packet/one_pass_signature -*/ + * @module packet/marker + */ +Marker.prototype.read = function (bytes) { + if (bytes[0] === 0x50 && // P + bytes[1] === 0x47 && // G + bytes[2] === 0x50) { + // P + return true; + } + // marker packet does not contain "PGP" + return false; +}; + +exports.default = Marker; + +},{"../enums.js":337}],352:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = OnePassSignature; var _util = _dereq_('../util.js'); @@ -17438,8 +42266,40 @@ function OnePassSignature() { /** * parsing function for a one-pass signature packet (tag 4). * @param {Uint8Array} bytes payload of a tag 4 packet - * @return {module:packet/one_pass_signature} object representation + * @returns {module:packet/one_pass_signature} object representation */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Implementation of the One-Pass Signature Packets (Tag 4) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + * @requires util + * @requires enums + * @requires type/keyid + * @module packet/one_pass_signature +*/ + OnePassSignature.prototype.read = function (bytes) { var mypos = 0; // A one-octet version number. The current version is 3. @@ -17470,10 +42330,9 @@ OnePassSignature.prototype.read = function (bytes) { /** * creates a string representation of a one-pass signature packet - * @return {Uint8Array} a Uint8Array representation of a one-pass signature packet + * @returns {Uint8Array} a Uint8Array representation of a one-pass signature packet */ OnePassSignature.prototype.write = function () { - var start = new Uint8Array([3, _enums2.default.write(_enums2.default.signature, this.type), _enums2.default.write(_enums2.default.hash, this.hashAlgorithm), _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)]); var end = new Uint8Array([this.flags]); @@ -17488,37 +42347,20 @@ OnePassSignature.prototype.postCloneTypeFix = function () { this.signingKeyId = _keyid2.default.fromClone(this.signingKeyId); }; -},{"../enums.js":35,"../type/keyid.js":67,"../util.js":70}],51:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +exports.default = OnePassSignature; -/** - * @requires enums - * @requires util - * @module packet/packet - */ - -'use strict'; +},{"../enums.js":337,"../type/keyid.js":372,"../util.js":376}],353:[function(_dereq_,module,exports){ +"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var _util = _dereq_('../util.js'); +var _slicedToArray2 = _dereq_("babel-runtime/helpers/slicedToArray"); + +var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); + +var _util = _dereq_("../util.js"); var _util2 = _interopRequireDefault(_util); @@ -17526,12 +42368,15 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de exports.default = { readSimpleLength: function readSimpleLength(bytes) { - var len = 0, - offset, - type = bytes[0]; + var len = 0; + var offset = void 0; + var type = bytes[0]; if (type < 192) { - len = bytes[0]; + var _bytes = (0, _slicedToArray3.default)(bytes, 1); + + len = _bytes[0]; + offset = 1; } else if (type < 255) { len = (bytes[0] - 192 << 8) + bytes[1] + 192; @@ -17552,10 +42397,9 @@ exports.default = { * string * * @param {Integer} length The length to encode - * @return {Uint8Array} String with openpgp length representation + * @returns {Uint8Array} String with openpgp length representation */ writeSimpleLength: function writeSimpleLength(length) { - if (length < 192) { return new Uint8Array([length]); } else if (length > 191 && length < 8384) { @@ -17564,9 +42408,8 @@ exports.default = { * representation of a let d = b + 192 */ return new Uint8Array([(length - 192 >> 8) + 192, length - 192 & 0xFF]); - } else { - return _util2.default.concatUint8Array([new Uint8Array([255]), _util2.default.writeNumber(length, 4)]); } + return _util2.default.concatUint8Array([new Uint8Array([255]), _util2.default.writeNumber(length, 4)]); }, /** @@ -17575,7 +42418,7 @@ exports.default = { * * @param {Integer} tag_type Tag type * @param {Integer} length Length of the payload - * @return {String} String of the header + * @returns {String} String of the header */ writeHeader: function writeHeader(tag_type, length) { /* we're only generating v4 packet headers here */ @@ -17588,17 +42431,15 @@ exports.default = { * * @param {Integer} tag_type Tag type * @param {Integer} length Length of the payload - * @return {String} String of the header + * @returns {String} String of the header */ writeOldHeader: function writeOldHeader(tag_type, length) { - if (length < 256) { return new Uint8Array([0x80 | tag_type << 2, length]); } else if (length < 65536) { return _util2.default.concatUint8Array([new Uint8Array([0x80 | tag_type << 2 | 1]), _util2.default.writeNumber(length, 2)]); - } else { - return _util2.default.concatUint8Array([new Uint8Array([0x80 | tag_type << 2 | 2]), _util2.default.writeNumber(length, 4)]); } + return _util2.default.concatUint8Array([new Uint8Array([0x80 | tag_type << 2 | 2]), _util2.default.writeNumber(length, 4)]); }, /** @@ -17607,7 +42448,7 @@ exports.default = { * @param {String} input Input stream as string * @param {integer} position Position to start parsing * @param {integer} len Length of the input from position on - * @return {Object} Returns a parsed module:packet/packet + * @returns {Object} Returns a parsed module:packet/packet */ read: function read(input, position, len) { // some sanity checks @@ -17617,14 +42458,14 @@ exports.default = { var mypos = position; var tag = -1; var format = -1; - var packet_length; + var packet_length = void 0; format = 0; // 0 = old format; 1 = new format if ((input[mypos] & 0x40) !== 0) { format = 1; } - var packet_length_type; + var packet_length_type = void 0; if (format) { // new format header tag = input[mypos] & 0x3F; // bit 5-0 @@ -17674,59 +42515,58 @@ exports.default = { packet_length = len; break; } - } else // 4.2.2. New Format Packet Lengths - { - - // 4.2.2.1. One-Octet Lengths - if (input[mypos] < 192) { - packet_length = input[mypos++]; - _util2.default.print_debug("1 byte length:" + packet_length); - // 4.2.2.2. Two-Octet Lengths - } else if (input[mypos] >= 192 && input[mypos] < 224) { - packet_length = (input[mypos++] - 192 << 8) + input[mypos++] + 192; - _util2.default.print_debug("2 byte length:" + packet_length); - // 4.2.2.4. Partial Body Lengths - } else if (input[mypos] > 223 && input[mypos] < 255) { - packet_length = 1 << (input[mypos++] & 0x1F); - _util2.default.print_debug("4 byte length:" + packet_length); - // EEEK, we're reading the full data here... - var mypos2 = mypos + packet_length; - bodydata = [input.subarray(mypos, mypos + packet_length)]; - var tmplen; - while (true) { - if (input[mypos2] < 192) { - tmplen = input[mypos2++]; - packet_length += tmplen; - bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); - mypos2 += tmplen; - break; - } else if (input[mypos2] >= 192 && input[mypos2] < 224) { - tmplen = (input[mypos2++] - 192 << 8) + input[mypos2++] + 192; - packet_length += tmplen; - bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); - mypos2 += tmplen; - break; - } else if (input[mypos2] > 223 && input[mypos2] < 255) { - tmplen = 1 << (input[mypos2++] & 0x1F); - packet_length += tmplen; - bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); - mypos2 += tmplen; - } else { - mypos2++; - tmplen = input[mypos2++] << 24 | input[mypos2++] << 16 | input[mypos2++] << 8 | input[mypos2++]; - bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); - packet_length += tmplen; - mypos2 += tmplen; - break; - } + } else { + // 4.2.2. New Format Packet Lengths + // 4.2.2.1. One-Octet Lengths + if (input[mypos] < 192) { + packet_length = input[mypos++]; + _util2.default.print_debug("1 byte length:" + packet_length); + // 4.2.2.2. Two-Octet Lengths + } else if (input[mypos] >= 192 && input[mypos] < 224) { + packet_length = (input[mypos++] - 192 << 8) + input[mypos++] + 192; + _util2.default.print_debug("2 byte length:" + packet_length); + // 4.2.2.4. Partial Body Lengths + } else if (input[mypos] > 223 && input[mypos] < 255) { + packet_length = 1 << (input[mypos++] & 0x1F); + _util2.default.print_debug("4 byte length:" + packet_length); + // EEEK, we're reading the full data here... + var mypos2 = mypos + packet_length; + bodydata = [input.subarray(mypos, mypos + packet_length)]; + var tmplen = void 0; + while (true) { + if (input[mypos2] < 192) { + tmplen = input[mypos2++]; + packet_length += tmplen; + bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); + mypos2 += tmplen; + break; + } else if (input[mypos2] >= 192 && input[mypos2] < 224) { + tmplen = (input[mypos2++] - 192 << 8) + input[mypos2++] + 192; + packet_length += tmplen; + bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); + mypos2 += tmplen; + break; + } else if (input[mypos2] > 223 && input[mypos2] < 255) { + tmplen = 1 << (input[mypos2++] & 0x1F); + packet_length += tmplen; + bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); + mypos2 += tmplen; + } else { + mypos2++; + tmplen = input[mypos2++] << 24 | input[mypos2++] << 16 | input[mypos2++] << 8 | input[mypos2++]; + bodydata.push(input.subarray(mypos2, mypos2 + tmplen)); + packet_length += tmplen; + mypos2 += tmplen; + break; } - real_packet_length = mypos2 - mypos; - // 4.2.2.3. Five-Octet Lengths - } else { - mypos++; - packet_length = input[mypos++] << 24 | input[mypos++] << 16 | input[mypos++] << 8 | input[mypos++]; } + real_packet_length = mypos2 - mypos; + // 4.2.2.3. Five-Octet Lengths + } else { + mypos++; + packet_length = input[mypos++] << 24 | input[mypos++] << 16 | input[mypos++] << 8 | input[mypos++]; } + } // if there was'nt a partial body length: use the specified // packet_length @@ -17746,26 +42586,43 @@ exports.default = { offset: mypos + real_packet_length }; } -}; +}; // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -},{"../util.js":70}],52:[function(_dereq_,module,exports){ /** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - * @requires util * @requires enums - * @requires packet - * @requires packet/packet - * @module packet/packetlist + * @requires util + * @module packet/packet */ +},{"../util.js":376,"babel-runtime/helpers/slicedToArray":33}],354:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Packetlist; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _util = _dereq_('../util'); @@ -17792,18 +42649,32 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. * @constructor */ function Packetlist() { - /** The number of packets contained within the list. + /** + * The number of packets contained within the list. * @readonly * @type {Integer} */ this.length = 0; } + /** * Reads a stream of binary data and interprents it as a list of packets. * @param {Uint8Array} A Uint8Array of bytes. */ +/* eslint-disable callback-return */ +/** + * @requires util + * @requires enums + * @requires packet + * @requires packet/packet + * @module packet/packetlist + */ + Packetlist.prototype.read = function (bytes) { var i = 0; @@ -17819,7 +42690,7 @@ Packetlist.prototype.read = function (bytes) { pushed = true; packet.read(parsed.packet); } catch (e) { - if (!_config2.default.tolerant || parsed.tag == _enums2.default.packet.symmetricallyEncrypted || parsed.tag == _enums2.default.packet.literal || parsed.tag == _enums2.default.packet.compressed) { + if (!_config2.default.tolerant || parsed.tag === _enums2.default.packet.symmetricallyEncrypted || parsed.tag === _enums2.default.packet.literal || parsed.tag === _enums2.default.packet.compressed) { throw e; } if (pushed) { @@ -17863,7 +42734,7 @@ Packetlist.prototype.push = function (packet) { /** * Remove a packet from the list and return it. - * @return {Object} The packet that was removed + * @returns {Object} The packet that was removed */ Packetlist.prototype.pop = function () { if (this.length === 0) { @@ -17878,10 +42749,9 @@ Packetlist.prototype.pop = function () { }; /** -* Creates a new PacketList with all packets that pass the test implemented by the provided function. -*/ + * Creates a new PacketList with all packets that pass the test implemented by the provided function. + */ Packetlist.prototype.filter = function (callback) { - var filtered = new Packetlist(); for (var i = 0; i < this.length; i++) { @@ -17894,18 +42764,24 @@ Packetlist.prototype.filter = function (callback) { }; /** -* Creates a new PacketList with all packets from the given types -*/ + * Creates a new PacketList with all packets from the given types + */ Packetlist.prototype.filterByTag = function () { - var args = Array.prototype.slice.call(arguments); var filtered = new Packetlist(); var that = this; - function handle(packetType) { - return that[i].tag === packetType; + var handle = function handle(tag) { + return function (packetType) { + return tag === packetType; + }; + }; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } + for (var i = 0; i < this.length; i++) { - if (args.some(handle)) { + if (args.some(handle(that[i].tag))) { filtered.push(this[i]); } } @@ -17914,34 +42790,115 @@ Packetlist.prototype.filterByTag = function () { }; /** -* Executes the provided callback once for each element -*/ + * Executes the provided callback once for each element + */ Packetlist.prototype.forEach = function (callback) { for (var i = 0; i < this.length; i++) { - callback(this[i]); + callback(this[i], i, this); } }; +/** + * Returns an array containing return values of callback + * on each element + */ +Packetlist.prototype.map = function (callback) { + var packetArray = []; + + for (var i = 0; i < this.length; i++) { + packetArray.push(callback(this[i], i, this)); + } + + return packetArray; +}; + +/** + * Executes the callback function once for each element + * until it finds one where callback returns a truthy value + * @param {Function} callback + * @returns {Promise} + * @async + */ +Packetlist.prototype.some = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(callback) { + var i; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + i = 0; + + case 1: + if (!(i < this.length)) { + _context.next = 9; + break; + } + + _context.next = 4; + return callback(this[i], i, this); + + case 4: + if (!_context.sent) { + _context.next = 6; + break; + } + + return _context.abrupt('return', true); + + case 6: + i++; + _context.next = 1; + break; + + case 9: + return _context.abrupt('return', false); + + case 10: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Executes the callback function once for each element, + * returns true if all callbacks returns a truthy value + */ +Packetlist.prototype.every = function (callback) { + for (var i = 0; i < this.length; i++) { + if (!callback(this[i], i, this)) { + return false; + } + } + return true; +}; + /** * Traverses packet tree and returns first matching packet * @param {module:enums.packet} type The packet type - * @return {module:packet/packet|null} + * @returns {module:packet/packet|null} */ Packetlist.prototype.findPacket = function (type) { var packetlist = this.filterByTag(type); if (packetlist.length) { return packetlist[0]; - } else { - var found = null; - for (var i = 0; i < this.length; i++) { - if (this[i].packets.length) { - found = this[i].packets.findPacket(type); - if (found) { - return found; - } + } + var found = null; + for (var i = 0; i < this.length; i++) { + if (this[i].packets.length) { + found = this[i].packets.findPacket(type); + if (found) { + return found; } } } + return null; }; @@ -17949,15 +42906,21 @@ Packetlist.prototype.findPacket = function (type) { * Returns array of found indices by tag */ Packetlist.prototype.indexOfTag = function () { - var args = Array.prototype.slice.call(arguments); var tagIndex = []; var that = this; - function handle(packetType) { - return that[i].tag === packetType; + var handle = function handle(tag) { + return function (packetType) { + return tag === packetType; + }; + }; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; } + for (var i = 0; i < this.length; i++) { - if (args.some(handle)) { + if (args.some(handle(that[i].tag))) { tagIndex.push(i); } } @@ -17987,6 +42950,7 @@ Packetlist.prototype.concat = function (packetlist) { this.push(packetlist[i]); } } + return this; }; /** @@ -18008,66 +42972,35 @@ Packetlist.fromStructuredClone = function (packetlistClone) { return packetlist; }; -},{"../config":10,"../enums.js":35,"../util":70,"./all_packets.js":44,"./packet.js":51}],53:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * Implementation of the Key Material Packet (Tag 5,6,7,14)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. Consequently, this section is complex. - * @requires crypto - * @requires enums - * @requires type/keyid - * @requires type/mpi - * @requires util - * @module packet/public_key - */ +exports.default = Packetlist; +},{"../config":306,"../enums.js":337,"../util":376,"./all_packets.js":346,"./packet.js":353,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],355:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = PublicKey; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _mpi = _dereq_('../type/mpi.js'); - -var _mpi2 = _interopRequireDefault(_mpi); - -var _keyid = _dereq_('../type/keyid.js'); - -var _keyid2 = _interopRequireDefault(_keyid); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); var _crypto = _dereq_('../crypto'); var _crypto2 = _interopRequireDefault(_crypto); +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +var _keyid = _dereq_('../type/keyid'); + +var _keyid2 = _interopRequireDefault(_keyid); + +var _mpi = _dereq_('../type/mpi'); + +var _mpi2 = _interopRequireDefault(_mpi); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** @@ -18078,13 +43011,9 @@ function PublicKey() { this.version = 4; /** Key creation date. * @type {Date} */ - this.created = new Date(); - /** A list of multiprecision integers - * @type {module:type/mpi} */ - this.mpi = []; - /** Public key algorithm - * @type {module:enums.publicKey} */ - this.algorithm = 'rsa_sign'; + this.created = _util2.default.normalizeDate(); + /* Algorithm specific params */ + this.params = []; // time in days (V3 only) this.expirationTimeV3 = 0; /** @@ -18103,8 +43032,39 @@ function PublicKey() { * 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} * called by read_tag<num> * @param {Uint8Array} bytes Input array to read the packet from - * @return {Object} This object with attributes set by the parser + * @returns {Object} This object with attributes set by the parser */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. Consequently, this section is complex. + * @requires crypto + * @requires enums + * @requires util + * @requires type/keyid + * @module packet/public_key + */ + PublicKey.prototype.read = function (bytes) { var pos = 0; // A one-octet version number (3 or 4). @@ -18124,28 +43084,23 @@ PublicKey.prototype.read = function (bytes) { // - A one-octet number denoting the public-key algorithm of this key. this.algorithm = _enums2.default.read(_enums2.default.publicKey, bytes[pos++]); + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + var types = _crypto2.default.getPubKeyParamTypes(algo); + this.params = _crypto2.default.constructParams(types); - var mpicount = _crypto2.default.getPublicMpiCount(this.algorithm); - this.mpi = []; - - var bmpi = bytes.subarray(pos, bytes.length); + var b = bytes.subarray(pos, bytes.length); var p = 0; - for (var i = 0; i < mpicount && p < bmpi.length; i++) { - - this.mpi[i] = new _mpi2.default(); - - p += this.mpi[i].read(bmpi.subarray(p, bmpi.length)); - - if (p > bmpi.length) { + for (var i = 0; i < types.length && p < b.length; i++) { + p += this.params[i].read(b.subarray(p, b.length)); + if (p > b.length) { throw new Error('Error reading MPI @:' + p); } } return p + 6; - } else { - throw new Error('Version ' + this.version + ' of the key packet is unsupported.'); } + throw new Error('Version ' + this.version + ' of the key packet is unsupported.'); }; /** @@ -18157,10 +43112,9 @@ PublicKey.prototype.readPublicKey = PublicKey.prototype.read; /** * Same as write_private_key, but has less information because of * public key. - * @return {Uint8Array} OpenPGP packet body contents, + * @returns {Uint8Array} OpenPGP packet body contents, */ PublicKey.prototype.write = function () { - var arr = []; // Version arr.push(new Uint8Array([this.version])); @@ -18168,12 +43122,12 @@ PublicKey.prototype.write = function () { if (this.version === 3) { arr.push(_util2.default.writeNumber(this.expirationTimeV3, 2)); } - arr.push(new Uint8Array([_enums2.default.write(_enums2.default.publicKey, this.algorithm)])); - - var mpicount = _crypto2.default.getPublicMpiCount(this.algorithm); - - for (var i = 0; i < mpicount; i++) { - arr.push(this.mpi[i].write()); + // Algorithm-specific params + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + var paramCount = _crypto2.default.getPubKeyParamTypes(algo).length; + arr.push(new Uint8Array([algo])); + for (var i = 0; i < paramCount; i++) { + arr.push(this.params[i].write()); } return _util2.default.concatUint8Array(arr); @@ -18196,7 +43150,7 @@ PublicKey.prototype.writeOld = function () { /** * Calculates the key id of the key - * @return {String} A 8 byte key id + * @returns {String} A 8 byte key id */ PublicKey.prototype.getKeyId = function () { if (this.keyid) { @@ -18204,9 +43158,9 @@ PublicKey.prototype.getKeyId = function () { } this.keyid = new _keyid2.default(); if (this.version === 4) { - this.keyid.read(_util2.default.str2Uint8Array(_util2.default.hex2bin(this.getFingerprint()).substr(12, 8))); + this.keyid.read(_util2.default.str_to_Uint8Array(_util2.default.hex_to_str(this.getFingerprint()).substr(12, 8))); } else if (this.version === 3) { - var arr = this.mpi[0].write(); + var arr = this.params[0].write(); this.keyid.read(arr.subarray(arr.length - 8, arr.length)); } return this.keyid; @@ -18214,7 +43168,7 @@ PublicKey.prototype.getKeyId = function () { /** * Calculates the fingerprint of the key - * @return {String} A string containing the fingerprint in lowercase hex + * @returns {String} A string containing the fingerprint in lowercase hex */ PublicKey.prototype.getFingerprint = function () { if (this.fingerprint) { @@ -18223,84 +43177,65 @@ PublicKey.prototype.getFingerprint = function () { var toHash = ''; if (this.version === 4) { toHash = this.writeOld(); - this.fingerprint = _util2.default.Uint8Array2str(_crypto2.default.hash.sha1(toHash)); + this.fingerprint = _util2.default.Uint8Array_to_str(_crypto2.default.hash.sha1(toHash)); } else if (this.version === 3) { - var mpicount = _crypto2.default.getPublicMpiCount(this.algorithm); - for (var i = 0; i < mpicount; i++) { - toHash += this.mpi[i].toBytes(); + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + var paramCount = _crypto2.default.getPubKeyParamTypes(algo).length; + for (var i = 0; i < paramCount; i++) { + toHash += this.params[i].toString(); } - this.fingerprint = _util2.default.Uint8Array2str(_crypto2.default.hash.md5(_util2.default.str2Uint8Array(toHash))); + this.fingerprint = _util2.default.Uint8Array_to_str(_crypto2.default.hash.md5(_util2.default.str_to_Uint8Array(toHash))); } - this.fingerprint = _util2.default.hexstrdump(this.fingerprint); + this.fingerprint = _util2.default.str_to_hex(this.fingerprint); return this.fingerprint; }; /** - * Returns bit size of key - * @return {int} Number of bits + * Returns algorithm information + * @returns {Promise} An object of the form {algorithm: String, bits:int, curve:String} */ -PublicKey.prototype.getBitSize = function () { - return this.mpi[0].byteLength() * 8; +PublicKey.prototype.getAlgorithmInfo = function () { + var result = {}; + result.algorithm = this.algorithm; + if (this.params[0] instanceof _mpi2.default) { + result.bits = this.params[0].byteLength() * 8; + } else { + result.curve = this.params[0].getName(); + } + return result; }; /** * Fix custom types after cloning */ PublicKey.prototype.postCloneTypeFix = function () { - for (var i = 0; i < this.mpi.length; i++) { - this.mpi[i] = _mpi2.default.fromClone(this.mpi[i]); + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + var types = _crypto2.default.getPubKeyParamTypes(algo); + for (var i = 0; i < types.length; i++) { + var param = this.params[i]; + this.params[i] = types[i].fromClone(param); } if (this.keyid) { this.keyid = _keyid2.default.fromClone(this.keyid); } }; -},{"../crypto":24,"../enums.js":35,"../type/keyid.js":67,"../type/mpi.js":68,"../util.js":70}],54:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * Public-Key Encrypted Session Key Packets (Tag 1)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - * @requires crypto - * @requires enums - * @requires type/keyid - * @requires type/mpi - * @requires util - * @module packet/public_key_encrypted_session_key - */ +exports.default = PublicKey; +},{"../crypto":319,"../enums":337,"../type/keyid":372,"../type/mpi":373,"../util":376}],356:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = PublicKeyEncryptedSessionKey; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _keyid = _dereq_('../type/keyid.js'); @@ -18310,6 +43245,10 @@ var _util = _dereq_('../util.js'); var _util2 = _interopRequireDefault(_util); +var _ecdh_symkey = _dereq_('../type/ecdh_symkey.js'); + +var _ecdh_symkey2 = _interopRequireDefault(_ecdh_symkey); + var _mpi = _dereq_('../type/mpi.js'); var _mpi2 = _interopRequireDefault(_mpi); @@ -18327,15 +43266,53 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de /** * @constructor */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Public-Key Encrypted Session Key Packets (Tag 1) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + * @requires crypto + * @requires enums + * @requires type/ecdh_symkey + * @requires type/keyid + * @requires type/mpi + * @requires util + * @module packet/public_key_encrypted_session_key + */ + function PublicKeyEncryptedSessionKey() { this.tag = _enums2.default.packet.publicKeyEncryptedSessionKey; this.version = 3; this.publicKeyId = new _keyid2.default(); - this.publicKeyAlgorithm = 'rsa_encrypt'; - this.sessionKey = null; - this.sessionKeyAlgorithm = 'aes256'; /** @type {Array} */ this.encrypted = []; @@ -18348,46 +43325,30 @@ function PublicKeyEncryptedSessionKey() { * @param {Integer} position Position to start reading from the input string * @param {Integer} len Length of the packet or the remaining length of * input at position - * @return {module:packet/public_key_encrypted_session_key} Object representation + * @returns {module:packet/public_key_encrypted_session_key} Object representation */ PublicKeyEncryptedSessionKey.prototype.read = function (bytes) { - this.version = bytes[0]; this.publicKeyId.read(bytes.subarray(1, bytes.length)); this.publicKeyAlgorithm = _enums2.default.read(_enums2.default.publicKey, bytes[9]); var i = 10; - var integerCount = function (algo) { - switch (algo) { - case 'rsa_encrypt': - case 'rsa_encrypt_sign': - return 1; + var algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + var types = _crypto2.default.getEncSessionKeyParamTypes(algo); + this.encrypted = _crypto2.default.constructParams(types); - case 'elgamal': - return 2; - - default: - throw new Error("Invalid algorithm."); - } - }(this.publicKeyAlgorithm); - - this.encrypted = []; - - for (var j = 0; j < integerCount; j++) { - var mpi = new _mpi2.default(); - i += mpi.read(bytes.subarray(i, bytes.length)); - this.encrypted.push(mpi); + for (var j = 0; j < types.length; j++) { + i += this.encrypted[j].read(bytes.subarray(i, bytes.length)); } }; /** * Create a string representation of a tag 1 packet * - * @return {Uint8Array} The Uint8Array representation + * @returns {Uint8Array} The Uint8Array representation */ PublicKeyEncryptedSessionKey.prototype.write = function () { - var arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([_enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)])]; for (var i = 0; i < this.encrypted.length; i++) { @@ -18397,55 +43358,166 @@ PublicKeyEncryptedSessionKey.prototype.write = function () { return _util2.default.concatUint8Array(arr); }; -PublicKeyEncryptedSessionKey.prototype.encrypt = function (key) { - var data = String.fromCharCode(_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)); +/** + * Encrypt session key packet + * @param {module:packet/public_key} key Public key + * @returns {Promise} + * @async + */ +PublicKeyEncryptedSessionKey.prototype.encrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(key) { + var data, checksum, toEncrypt, algo; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + data = String.fromCharCode(_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)); - data += _util2.default.Uint8Array2str(this.sessionKey); - var checksum = _util2.default.calc_checksum(this.sessionKey); - data += _util2.default.Uint8Array2str(_util2.default.writeNumber(checksum, 2)); - var mpi = new _mpi2.default(); - mpi.fromBytes(_crypto2.default.pkcs1.eme.encode(data, key.mpi[0].byteLength())); + data += _util2.default.Uint8Array_to_str(this.sessionKey); + checksum = _util2.default.calc_checksum(this.sessionKey); - this.encrypted = _crypto2.default.publicKeyEncrypt(this.publicKeyAlgorithm, key.mpi, mpi); -}; + data += _util2.default.Uint8Array_to_str(_util2.default.writeNumber(checksum, 2)); + + toEncrypt = void 0; + algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + + if (!(algo === _enums2.default.publicKey.ecdh)) { + _context.next = 10; + break; + } + + toEncrypt = new _mpi2.default(_crypto2.default.pkcs5.encode(data)); + _context.next = 15; + break; + + case 10: + _context.t0 = _mpi2.default; + _context.next = 13; + return _crypto2.default.pkcs1.eme.encode(data, key.params[0].byteLength()); + + case 13: + _context.t1 = _context.sent; + toEncrypt = new _context.t0(_context.t1); + + case 15: + _context.next = 17; + return _crypto2.default.publicKeyEncrypt(algo, key.params, toEncrypt, key.fingerprint); + + case 17: + this.encrypted = _context.sent; + return _context.abrupt('return', true); + + case 19: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); /** * Decrypts the session key (only for public key encrypted session key * packets (tag 1) * * @param {module:packet/secret_key} key - * Private key with secMPIs unlocked - * @return {String} The unencrypted session key + * Private key with secret params unlocked + * @returns {Promise} + * @async */ -PublicKeyEncryptedSessionKey.prototype.decrypt = function (key) { - var result = _crypto2.default.publicKeyDecrypt(this.publicKeyAlgorithm, key.mpi, this.encrypted).toBytes(); +PublicKeyEncryptedSessionKey.prototype.decrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(key) { + var algo, result, checksum, decoded; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + _context2.next = 3; + return _crypto2.default.publicKeyDecrypt(algo, key.params, this.encrypted, key.fingerprint); - var checksum = _util2.default.readNumber(_util2.default.str2Uint8Array(result.substr(result.length - 2))); + case 3: + result = _context2.sent; + checksum = void 0; + decoded = void 0; - var decoded = _crypto2.default.pkcs1.eme.decode(result); + if (algo === _enums2.default.publicKey.ecdh) { + decoded = _crypto2.default.pkcs5.decode(result.toString()); + checksum = _util2.default.readNumber(_util2.default.str_to_Uint8Array(decoded.substr(decoded.length - 2))); + } else { + decoded = _crypto2.default.pkcs1.eme.decode(result.toString()); + checksum = _util2.default.readNumber(result.toUint8Array().slice(result.byteLength() - 2)); + } - key = _util2.default.str2Uint8Array(decoded.substring(1, decoded.length - 2)); + key = _util2.default.str_to_Uint8Array(decoded.substring(1, decoded.length - 2)); - if (checksum !== _util2.default.calc_checksum(key)) { - throw new Error('Checksum mismatch'); - } else { - this.sessionKey = key; - this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decoded.charCodeAt(0)); - } -}; + if (!(checksum !== _util2.default.calc_checksum(key))) { + _context2.next = 12; + break; + } + + throw new Error('Checksum mismatch'); + + case 12: + this.sessionKey = key; + this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decoded.charCodeAt(0)); + + case 14: + return _context2.abrupt('return', true); + + case 15: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x2) { + return _ref2.apply(this, arguments); + }; +}(); /** * Fix custom types after cloning */ PublicKeyEncryptedSessionKey.prototype.postCloneTypeFix = function () { this.publicKeyId = _keyid2.default.fromClone(this.publicKeyId); + var algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + var types = _crypto2.default.getEncSessionKeyParamTypes(algo); for (var i = 0; i < this.encrypted.length; i++) { - this.encrypted[i] = _mpi2.default.fromClone(this.encrypted[i]); + this.encrypted[i] = types[i].fromClone(this.encrypted[i]); } }; -},{"../crypto":24,"../enums.js":35,"../type/keyid.js":67,"../type/mpi.js":68,"../util.js":70}],55:[function(_dereq_,module,exports){ +exports.default = PublicKeyEncryptedSessionKey; + +},{"../crypto":319,"../enums.js":337,"../type/ecdh_symkey.js":370,"../type/keyid.js":372,"../type/mpi.js":373,"../util.js":376,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],357:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _public_key = _dereq_('./public_key.js'); + +var _public_key2 = _interopRequireDefault(_public_key); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + * @extends module:packet/public_key + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -18469,12 +43541,30 @@ PublicKeyEncryptedSessionKey.prototype.postCloneTypeFix = function () { * @module packet/public_subkey */ +function PublicSubkey() { + _public_key2.default.call(this); + this.tag = _enums2.default.packet.publicSubkey; +} + +PublicSubkey.prototype = new _public_key2.default(); +PublicSubkey.prototype.constructor = PublicSubkey; + +exports.default = PublicSubkey; + +},{"../enums.js":337,"./public_key.js":355}],358:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = PublicSubkey; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _public_key = _dereq_('./public_key.js'); @@ -18484,21 +43574,28 @@ var _enums = _dereq_('../enums.js'); var _enums2 = _interopRequireDefault(_enums); +var _util = _dereq_('../util.js'); + +var _util2 = _interopRequireDefault(_util); + +var _crypto = _dereq_('../crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _s2k = _dereq_('../type/s2k.js'); + +var _s2k2 = _interopRequireDefault(_s2k); + +var _keyid = _dereq_('../type/keyid.js'); + +var _keyid2 = _interopRequireDefault(_keyid); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @constructor * @extends module:packet/public_key */ -function PublicSubkey() { - _public_key2.default.call(this); - this.tag = _enums2.default.packet.publicSubkey; -} - -PublicSubkey.prototype = new _public_key2.default(); -PublicSubkey.prototype.constructor = PublicSubkey; - -},{"../enums.js":35,"./public_key.js":53}],56:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -18517,8 +43614,8 @@ PublicSubkey.prototype.constructor = PublicSubkey; // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Key Material Packet (Tag 5,6,7,14)
- *
+ * Implementation of the Key Material Packet (Tag 5,6,7,14) + * * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: * A key material packet contains all the information about a public or * private key. There are four variants of this packet type, and two @@ -18526,49 +43623,12 @@ PublicSubkey.prototype.constructor = PublicSubkey; * @requires crypto * @requires enums * @requires packet/public_key - * @requires type/mpi + * @requires type/keyid * @requires type/s2k * @requires util * @module packet/secret_key */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = SecretKey; - -var _public_key = _dereq_('./public_key.js'); - -var _public_key2 = _interopRequireDefault(_public_key); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _crypto = _dereq_('../crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -var _mpi = _dereq_('../type/mpi.js'); - -var _mpi2 = _interopRequireDefault(_mpi); - -var _s2k = _dereq_('../type/s2k.js'); - -var _s2k2 = _interopRequireDefault(_s2k); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @constructor - * @extends module:packet/public_key - */ function SecretKey() { _public_key2.default.call(this); this.tag = _enums2.default.packet.secretKey; @@ -18584,55 +43644,55 @@ SecretKey.prototype.constructor = SecretKey; function get_hash_len(hash) { if (hash === 'sha1') { return 20; - } else { - return 2; } + return 2; } function get_hash_fn(hash) { if (hash === 'sha1') { return _crypto2.default.hash.sha1; - } else { - return function (c) { - return _util2.default.writeNumber(_util2.default.calc_checksum(c), 2); - }; } + return function (c) { + return _util2.default.writeNumber(_util2.default.calc_checksum(c), 2); + }; } // Helper function -function parse_cleartext_mpi(hash_algorithm, cleartext, algorithm) { - var hashlen = get_hash_len(hash_algorithm), - hashfn = get_hash_fn(hash_algorithm); +function parse_cleartext_params(hash_algorithm, cleartext, algorithm) { + var hashlen = get_hash_len(hash_algorithm); + var hashfn = get_hash_fn(hash_algorithm); - var hashtext = _util2.default.Uint8Array2str(cleartext.subarray(cleartext.length - hashlen, cleartext.length)); + var hashtext = _util2.default.Uint8Array_to_str(cleartext.subarray(cleartext.length - hashlen, cleartext.length)); cleartext = cleartext.subarray(0, cleartext.length - hashlen); - - var hash = _util2.default.Uint8Array2str(hashfn(cleartext)); + var hash = _util2.default.Uint8Array_to_str(hashfn(cleartext)); if (hash !== hashtext) { - return new Error("Hash mismatch."); + return new Error("Incorrect key passphrase"); } - var mpis = _crypto2.default.getPrivateMpiCount(algorithm); + var algo = _enums2.default.write(_enums2.default.publicKey, algorithm); + var types = _crypto2.default.getPrivKeyParamTypes(algo); + var params = _crypto2.default.constructParams(types); + var p = 0; - var j = 0; - var mpi = []; - - for (var i = 0; i < mpis && j < cleartext.length; i++) { - mpi[i] = new _mpi2.default(); - j += mpi[i].read(cleartext.subarray(j, cleartext.length)); + for (var i = 0; i < types.length && p < cleartext.length; i++) { + p += params[i].read(cleartext.subarray(p, cleartext.length)); + if (p > cleartext.length) { + throw new Error('Error reading param @:' + p); + } } - return mpi; + return params; } -function write_cleartext_mpi(hash_algorithm, algorithm, mpi) { +function write_cleartext_params(hash_algorithm, algorithm, params) { var arr = []; - var discard = _crypto2.default.getPublicMpiCount(algorithm); + var algo = _enums2.default.write(_enums2.default.publicKey, algorithm); + var numPublicParams = _crypto2.default.getPubKeyParamTypes(algo).length; - for (var i = discard; i < mpi.length; i++) { - arr.push(mpi[i].write()); + for (var i = numPublicParams; i < params.length; i++) { + arr.push(params[i].write()); } var bytes = _util2.default.concatUint8Array(arr); @@ -18666,24 +43726,24 @@ SecretKey.prototype.read = function (bytes) { // - Plain or encrypted multiprecision integers comprising the secret // key data. These algorithm-specific fields are as described // below. - var parsedMPI = parse_cleartext_mpi('mod', bytes.subarray(1, bytes.length), this.algorithm); - if (parsedMPI instanceof Error) { - throw parsedMPI; + var privParams = parse_cleartext_params('mod', bytes.subarray(1, bytes.length), this.algorithm); + if (privParams instanceof Error) { + throw privParams; } - this.mpi = this.mpi.concat(parsedMPI); + this.params = this.params.concat(privParams); this.isDecrypted = true; } }; /** Creates an OpenPGP key packet for the given key. - * @return {String} A string of bytes containing the secret key OpenPGP packet + * @returns {String} A string of bytes containing the secret key OpenPGP packet */ SecretKey.prototype.write = function () { var arr = [this.writePublicKey()]; if (!this.encrypted) { arr.push(new Uint8Array([0])); - arr.push(write_cleartext_mpi('mod', this.algorithm, this.mpi)); + arr.push(write_cleartext_params('mod', this.algorithm, this.params)); } else { arr.push(this.encrypted); } @@ -18696,119 +43756,223 @@ SecretKey.prototype.write = function () { * and the passphrase is empty or undefined, the key will be set as not encrypted. * This can be used to remove passphrase protection after calling decrypt(). * @param {String} passphrase + * @returns {Promise} + * @async */ -SecretKey.prototype.encrypt = function (passphrase) { - if (this.isDecrypted && !passphrase) { - this.encrypted = null; - return; - } else if (!passphrase) { - throw new Error('The key must be decrypted before removing passphrase protection.'); - } +SecretKey.prototype.encrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(passphrase) { + var s2k, symmetric, cleartext, key, blockLen, iv, arr; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(this.isDecrypted && !passphrase)) { + _context.next = 5; + break; + } - var s2k = new _s2k2.default(), - symmetric = 'aes256', - cleartext = write_cleartext_mpi('sha1', this.algorithm, this.mpi), - key = produceEncryptionKey(s2k, passphrase, symmetric), - blockLen = _crypto2.default.cipher[symmetric].blockSize, - iv = _crypto2.default.random.getRandomBytes(blockLen); + this.encrypted = null; + return _context.abrupt('return', false); - var arr = [new Uint8Array([254, _enums2.default.write(_enums2.default.symmetric, symmetric)])]; - arr.push(s2k.write()); - arr.push(iv); - arr.push(_crypto2.default.cfb.normalEncrypt(symmetric, key, cleartext, iv)); + case 5: + if (passphrase) { + _context.next = 7; + break; + } - this.encrypted = _util2.default.concatUint8Array(arr); -}; + throw new Error('The key must be decrypted before removing passphrase protection.'); + + case 7: + s2k = new _s2k2.default(); + _context.next = 10; + return _crypto2.default.random.getRandomBytes(8); + + case 10: + s2k.salt = _context.sent; + symmetric = 'aes256'; + cleartext = write_cleartext_params('sha1', this.algorithm, this.params); + key = produceEncryptionKey(s2k, passphrase, symmetric); + blockLen = _crypto2.default.cipher[symmetric].blockSize; + _context.next = 17; + return _crypto2.default.random.getRandomBytes(blockLen); + + case 17: + iv = _context.sent; + arr = [new Uint8Array([254, _enums2.default.write(_enums2.default.symmetric, symmetric)])]; + + arr.push(s2k.write()); + arr.push(iv); + arr.push(_crypto2.default.cfb.normalEncrypt(symmetric, key, cleartext, iv)); + + this.encrypted = _util2.default.concatUint8Array(arr); + return _context.abrupt('return', true); + + case 24: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); function produceEncryptionKey(s2k, passphrase, algorithm) { return s2k.produce_key(passphrase, _crypto2.default.cipher[algorithm].keySize); } /** - * Decrypts the private key MPIs which are needed to use the key. + * Decrypts the private key params which are needed to use the key. * @link module:packet/secret_key.isDecrypted should be * false otherwise a call to this function is not needed * - * @param {String} str_passphrase The passphrase for this private key - * as string - * @return {Boolean} True if the passphrase was correct or MPI already - * decrypted; false if not + * @param {String} passphrase The passphrase for this private key as string + * @returns {Promise} + * @async */ -SecretKey.prototype.decrypt = function (passphrase) { - if (this.isDecrypted) { - return true; - } +SecretKey.prototype.decrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(passphrase) { + var i, symmetric, key, s2k_usage, s2k, iv, ciphertext, cleartext, hash, privParams; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!this.isDecrypted) { + _context2.next = 2; + break; + } - var i = 0, - symmetric, - key; + throw new Error('Key packet is already decrypted.'); - var s2k_usage = this.encrypted[i++]; + case 2: + i = 0; + symmetric = void 0; + key = void 0; + s2k_usage = this.encrypted[i++]; - // - [Optional] If string-to-key usage octet was 255 or 254, a one- - // octet symmetric encryption algorithm. - if (s2k_usage === 255 || s2k_usage === 254) { - symmetric = this.encrypted[i++]; - symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric); + // - [Optional] If string-to-key usage octet was 255 or 254, a one- + // octet symmetric encryption algorithm. - // - [Optional] If string-to-key usage octet was 255 or 254, a - // string-to-key specifier. The length of the string-to-key - // specifier is implied by its type, as described above. - var s2k = new _s2k2.default(); - i += s2k.read(this.encrypted.subarray(i, this.encrypted.length)); + if (s2k_usage === 255 || s2k_usage === 254) { + symmetric = this.encrypted[i++]; + symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric); - key = produceEncryptionKey(s2k, passphrase, symmetric); - } else { - symmetric = s2k_usage; - symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric); - key = _crypto2.default.hash.md5(passphrase); - } + // - [Optional] If string-to-key usage octet was 255 or 254, a + // string-to-key specifier. The length of the string-to-key + // specifier is implied by its type, as described above. + s2k = new _s2k2.default(); - // - [Optional] If secret data is encrypted (string-to-key usage octet - // not zero), an Initial Vector (IV) of the same length as the - // cipher's block size. - var iv = this.encrypted.subarray(i, i + _crypto2.default.cipher[symmetric].blockSize); + i += s2k.read(this.encrypted.subarray(i, this.encrypted.length)); - i += iv.length; + key = produceEncryptionKey(s2k, passphrase, symmetric); + } else { + symmetric = s2k_usage; + symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric); + key = _crypto2.default.hash.md5(passphrase); + } - var cleartext, - ciphertext = this.encrypted.subarray(i, this.encrypted.length); + // - [Optional] If secret data is encrypted (string-to-key usage octet + // not zero), an Initial Vector (IV) of the same length as the + // cipher's block size. + iv = this.encrypted.subarray(i, i + _crypto2.default.cipher[symmetric].blockSize); - cleartext = _crypto2.default.cfb.normalDecrypt(symmetric, key, ciphertext, iv); - var hash = s2k_usage === 254 ? 'sha1' : 'mod'; + i += iv.length; - var parsedMPI = parse_cleartext_mpi(hash, cleartext, this.algorithm); - if (parsedMPI instanceof Error) { - return false; - } - this.mpi = this.mpi.concat(parsedMPI); - this.isDecrypted = true; - this.encrypted = null; - return true; -}; + ciphertext = this.encrypted.subarray(i, this.encrypted.length); + cleartext = _crypto2.default.cfb.normalDecrypt(symmetric, key, ciphertext, iv); + hash = s2k_usage === 254 ? 'sha1' : 'mod'; + privParams = parse_cleartext_params(hash, cleartext, this.algorithm); -SecretKey.prototype.generate = function (bits) { - var self = this; + if (!(privParams instanceof Error)) { + _context2.next = 15; + break; + } - return _crypto2.default.generateMpi(self.algorithm, bits).then(function (mpi) { - self.mpi = mpi; - self.isDecrypted = true; + throw privParams; + + case 15: + this.params = this.params.concat(privParams); + this.isDecrypted = true; + this.encrypted = null; + + return _context2.abrupt('return', true); + + case 19: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x2) { + return _ref2.apply(this, arguments); + }; +}(); + +SecretKey.prototype.generate = function (bits, curve) { + var that = this; + var algo = _enums2.default.write(_enums2.default.publicKey, that.algorithm); + return _crypto2.default.generateParams(algo, bits, curve).then(function (params) { + that.params = params; + that.isDecrypted = true; }); }; /** - * Clear private MPIs, return to initial state + * Clear private params, return to initial state */ -SecretKey.prototype.clearPrivateMPIs = function () { +SecretKey.prototype.clearPrivateParams = function () { if (!this.encrypted) { - throw new Error('If secret key is not encrypted, clearing private MPIs is irreversible.'); + throw new Error('If secret key is not encrypted, clearing private params is irreversible.'); } - this.mpi = this.mpi.slice(0, _crypto2.default.getPublicMpiCount(this.algorithm)); + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + this.params = this.params.slice(0, _crypto2.default.getPubKeyParamTypes(algo).length); this.isDecrypted = false; }; -},{"../crypto":24,"../enums.js":35,"../type/mpi.js":68,"../type/s2k.js":69,"../util.js":70,"./public_key.js":53}],57:[function(_dereq_,module,exports){ +/** + * Fix custom types after cloning + */ +SecretKey.prototype.postCloneTypeFix = function () { + var algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm); + var types = [].concat(_crypto2.default.getPubKeyParamTypes(algo), _crypto2.default.getPrivKeyParamTypes(algo)); + for (var i = 0; i < this.params.length; i++) { + var param = this.params[i]; + this.params[i] = types[i].fromClone(param); + } + if (this.keyid) { + this.keyid = _keyid2.default.fromClone(this.keyid); + } +}; + +exports.default = SecretKey; + +},{"../crypto":319,"../enums.js":337,"../type/keyid.js":372,"../type/s2k.js":375,"../util.js":376,"./public_key.js":355,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],359:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _secret_key = _dereq_('./secret_key.js'); + +var _secret_key2 = _interopRequireDefault(_secret_key); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + * @extends module:packet/secret_key + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -18832,27 +43996,6 @@ SecretKey.prototype.clearPrivateMPIs = function () { * @module packet/secret_subkey */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = SecretSubkey; - -var _secret_key = _dereq_('./secret_key.js'); - -var _secret_key2 = _interopRequireDefault(_secret_key); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @constructor - * @extends module:packet/secret_key - */ function SecretSubkey() { _secret_key2.default.call(this); this.tag = _enums2.default.packet.secretSubkey; @@ -18861,21 +44004,30 @@ function SecretSubkey() { SecretSubkey.prototype = new _secret_key2.default(); SecretSubkey.prototype.constructor = SecretSubkey; -},{"../enums.js":35,"./secret_key.js":56}],58:[function(_dereq_,module,exports){ +exports.default = SecretSubkey; + +},{"../enums.js":337,"./secret_key.js":358}],360:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Signature; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _util = _dereq_('../util.js'); var _util2 = _interopRequireDefault(_util); -var _packet = _dereq_('./packet.js'); +var _packet2 = _dereq_('./packet.js'); -var _packet2 = _interopRequireDefault(_packet); +var _packet3 = _interopRequireDefault(_packet2); var _enums = _dereq_('../enums.js'); @@ -18897,6 +44049,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de /** * @constructor + * @param {Date} date the creation date of the signature */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH @@ -18916,8 +44069,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Signature Packet (Tag 2)
- *
+ * Implementation of the Signature Packet (Tag 2) + * * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: * A Signature packet describes a binding between some public key and * some data. The most common signatures are a signature of a file or a @@ -18932,6 +44085,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ function Signature() { + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + this.tag = _enums2.default.packet.signature; this.version = 4; this.signatureType = null; @@ -18942,7 +44097,7 @@ function Signature() { this.unhashedSubpackets = null; this.signedHashValue = null; - this.created = new Date(); + this.created = _util2.default.normalizeDate(date); this.signatureExpirationTime = null; this.signatureNeverExpires = true; this.exportable = null; @@ -18974,7 +44129,8 @@ function Signature() { this.signatureTargetHash = null; this.embeddedSignature = null; - this.verified = false; + this.verified = null; + this.revoked = null; } /** @@ -18982,84 +44138,86 @@ function Signature() { * @param {String} bytes payload of a tag 2 packet * @param {Integer} position position to start reading from the bytes string * @param {Integer} len length of the packet or the remaining length of bytes at position - * @return {module:packet/signature} object representation + * @returns {module:packet/signature} object representation */ Signature.prototype.read = function (bytes) { var i = 0; this.version = bytes[i++]; + + function subpackets(bytes) { + // Two-octet scalar octet count for following subpacket data. + var subpacket_length = _util2.default.readNumber(bytes.subarray(0, 2)); + + var i = 2; + + // subpacket data set (zero or more subpackets) + while (i < 2 + subpacket_length) { + var len = _packet3.default.readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.read_sub_packet(bytes.subarray(i, i + len.len)); + + i += len.len; + } + + return i; + } + // switch on version (3 and 4) switch (this.version) { case 3: - // One-octet length of following hashed material. MUST be 5. - if (bytes[i++] !== 5) { - _util2.default.print_debug("packet/signature.js\n" + 'invalid One-octet length of following hashed material.' + 'MUST be 5. @:' + (i - 1)); - } - - var sigpos = i; - // One-octet signature type. - this.signatureType = bytes[i++]; - - // Four-octet creation time. - this.created = _util2.default.readDate(bytes.subarray(i, i + 4)); - i += 4; - - // storing data appended to data which gets verified - this.signatureData = bytes.subarray(sigpos, i); - - // Eight-octet Key ID of signer. - this.issuerKeyId.read(bytes.subarray(i, i + 8)); - i += 8; - - // One-octet public-key algorithm. - this.publicKeyAlgorithm = bytes[i++]; - - // One-octet hash algorithm. - this.hashAlgorithm = bytes[i++]; - break; - case 4: - this.signatureType = bytes[i++]; - this.publicKeyAlgorithm = bytes[i++]; - this.hashAlgorithm = bytes[i++]; - - var subpackets = function subpackets(bytes) { - // Two-octet scalar octet count for following subpacket data. - var subpacket_length = _util2.default.readNumber(bytes.subarray(0, 2)); - - var i = 2; - - // subpacket data set (zero or more subpackets) - while (i < 2 + subpacket_length) { - - var len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.read_sub_packet(bytes.subarray(i, i + len.len)); - - i += len.len; + { + // One-octet length of following hashed material. MUST be 5. + if (bytes[i++] !== 5) { + _util2.default.print_debug("packet/signature.js\n" + 'invalid One-octet length of following hashed material.' + 'MUST be 5. @:' + (i - 1)); } - return i; - }; + var sigpos = i; + // One-octet signature type. + this.signatureType = bytes[i++]; - // hashed subpackets + // Four-octet creation time. + this.created = _util2.default.readDate(bytes.subarray(i, i + 4)); + i += 4; + // storing data appended to data which gets verified + this.signatureData = bytes.subarray(sigpos, i); - i += subpackets.call(this, bytes.subarray(i, bytes.length), true); + // Eight-octet Key ID of signer. + this.issuerKeyId.read(bytes.subarray(i, i + 8)); + i += 8; - // A V4 signature hashes the packet body - // starting from its first field, the version number, through the end - // of the hashed subpacket data. Thus, the fields hashed are the - // signature version, the signature type, the public-key algorithm, the - // hash algorithm, the hashed subpacket length, and the hashed - // subpacket body. - this.signatureData = bytes.subarray(0, i); - var sigDataLength = i; + // One-octet public-key algorithm. + this.publicKeyAlgorithm = bytes[i++]; - // unhashed subpackets - i += subpackets.call(this, bytes.subarray(i, bytes.length), false); - this.unhashedSubpackets = bytes.subarray(sigDataLength, i); + // One-octet hash algorithm. + this.hashAlgorithm = bytes[i++]; + break; + } + case 4: + { + this.signatureType = bytes[i++]; + this.publicKeyAlgorithm = bytes[i++]; + this.hashAlgorithm = bytes[i++]; - break; + // hashed subpackets + i += subpackets.call(this, bytes.subarray(i, bytes.length), true); + + // A V4 signature hashes the packet body + // starting from its first field, the version number, through the end + // of the hashed subpacket data. Thus, the fields hashed are the + // signature version, the signature type, the public-key algorithm, the + // hash algorithm, the hashed subpacket length, and the hashed + // subpacket body. + this.signatureData = bytes.subarray(0, i); + var sigDataLength = i; + + // unhashed subpackets + i += subpackets.call(this, bytes.subarray(i, bytes.length), false); + this.unhashedSubpackets = bytes.subarray(sigDataLength, i); + + break; + } default: throw new Error('Version ' + this.version + ' of the signature is unsupported.'); } @@ -19095,51 +44253,80 @@ Signature.prototype.write = function () { * Signs provided data. This needs to be done prior to serialization. * @param {module:packet/secret_key} key private key used to sign the message. * @param {Object} data Contains packets to be signed. + * @returns {Promise} + * @async */ -Signature.prototype.sign = function (key, data) { - var signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType), - publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm), - hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm); +Signature.prototype.sign = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(key, data) { + var signatureType, publicKeyAlgorithm, hashAlgorithm, arr, trailer, toHash, hash; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType); + publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm); + arr = [new Uint8Array([4, signatureType, publicKeyAlgorithm, hashAlgorithm])]; - var arr = [new Uint8Array([4, signatureType, publicKeyAlgorithm, hashAlgorithm])]; - this.issuerKeyId = key.getKeyId(); + this.issuerKeyId = key.getKeyId(); - // Add hashed subpackets - arr.push(this.write_all_sub_packets()); + // Add hashed subpackets + arr.push(this.write_all_sub_packets()); - this.signatureData = _util2.default.concatUint8Array(arr); + this.signatureData = _util2.default.concatUint8Array(arr); - var trailer = this.calculateTrailer(); + trailer = this.calculateTrailer(); + toHash = null; + _context.t0 = this.version; + _context.next = _context.t0 === 3 ? 12 : _context.t0 === 4 ? 14 : 16; + break; - var toHash = null; + case 12: + toHash = _util2.default.concatUint8Array([this.toSign(signatureType, data), new Uint8Array([signatureType]), _util2.default.writeDate(this.created)]); + return _context.abrupt('break', 17); - switch (this.version) { - case 3: - toHash = _util2.default.concatUint8Array([this.toSign(signatureType, data), new Uint8Array([signatureType]), _util2.default.writeDate(this.created)]); - break; - case 4: - toHash = _util2.default.concatUint8Array([this.toSign(signatureType, data), this.signatureData, trailer]); - break; - default: - throw new Error('Version ' + this.version + ' of the signature is unsupported.'); - } + case 14: + toHash = _util2.default.concatUint8Array([this.toSign(signatureType, data), this.signatureData, trailer]); + return _context.abrupt('break', 17); - var hash = _crypto2.default.hash.digest(hashAlgorithm, toHash); + case 16: + throw new Error('Version ' + this.version + ' of the signature is unsupported.'); - this.signedHashValue = hash.subarray(0, 2); + case 17: + hash = _crypto2.default.hash.digest(hashAlgorithm, toHash); - this.signature = _crypto2.default.signature.sign(hashAlgorithm, publicKeyAlgorithm, key.mpi, toHash); -}; + + this.signedHashValue = hash.subarray(0, 2); + + _context.next = 21; + return _crypto2.default.signature.sign(publicKeyAlgorithm, hashAlgorithm, key.params, toHash); + + case 21: + this.signature = _context.sent; + return _context.abrupt('return', true); + + case 23: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x2, _x3) { + return _ref.apply(this, arguments); + }; +}(); /** * Creates string of bytes with all subpacket data - * @return {String} a string-representation of a all subpacket data + * @returns {String} a string-representation of a all subpacket data */ Signature.prototype.write_all_sub_packets = function () { var sub = _enums2.default.signatureSubpacket; var arr = []; - var bytes; + var bytes = void 0; if (this.created !== null) { arr.push(write_sub_packet(sub.signature_creation_time, _util2.default.writeDate(this.created))); } @@ -19163,11 +44350,10 @@ Signature.prototype.write_all_sub_packets = function () { arr.push(write_sub_packet(sub.key_expiration_time, _util2.default.writeNumber(this.keyExpirationTime, 4))); } if (this.preferredSymmetricAlgorithms !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.preferredSymmetricAlgorithms)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredSymmetricAlgorithms)); arr.push(write_sub_packet(sub.preferred_symmetric_algorithms, bytes)); } if (this.revocationKeyClass !== null) { - bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]); bytes = _util2.default.concatUint8Array([bytes, this.revocationKeyFingerprint]); arr.push(write_sub_packet(sub.revocation_key, bytes)); @@ -19184,51 +44370,51 @@ Signature.prototype.write_all_sub_packets = function () { bytes.push(_util2.default.writeNumber(name.length, 2)); // 2 octets of value length bytes.push(_util2.default.writeNumber(value.length, 2)); - bytes.push(_util2.default.str2Uint8Array(name + value)); + bytes.push(_util2.default.str_to_Uint8Array(name + value)); bytes = _util2.default.concatUint8Array(bytes); arr.push(write_sub_packet(sub.notation_data, bytes)); } } } if (this.preferredHashAlgorithms !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.preferredHashAlgorithms)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredHashAlgorithms)); arr.push(write_sub_packet(sub.preferred_hash_algorithms, bytes)); } if (this.preferredCompressionAlgorithms !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.preferredCompressionAlgorithms)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredCompressionAlgorithms)); arr.push(write_sub_packet(sub.preferred_compression_algorithms, bytes)); } if (this.keyServerPreferences !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.keyServerPreferences)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyServerPreferences)); arr.push(write_sub_packet(sub.key_server_preferences, bytes)); } if (this.preferredKeyServer !== null) { - arr.push(write_sub_packet(sub.preferred_key_server, _util2.default.str2Uint8Array(this.preferredKeyServer))); + arr.push(write_sub_packet(sub.preferred_key_server, _util2.default.str_to_Uint8Array(this.preferredKeyServer))); } if (this.isPrimaryUserID !== null) { arr.push(write_sub_packet(sub.primary_user_id, new Uint8Array([this.isPrimaryUserID ? 1 : 0]))); } if (this.policyURI !== null) { - arr.push(write_sub_packet(sub.policy_uri, _util2.default.str2Uint8Array(this.policyURI))); + arr.push(write_sub_packet(sub.policy_uri, _util2.default.str_to_Uint8Array(this.policyURI))); } if (this.keyFlags !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.keyFlags)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyFlags)); arr.push(write_sub_packet(sub.key_flags, bytes)); } if (this.signersUserId !== null) { - arr.push(write_sub_packet(sub.signers_user_id, _util2.default.str2Uint8Array(this.signersUserId))); + arr.push(write_sub_packet(sub.signers_user_id, _util2.default.str_to_Uint8Array(this.signersUserId))); } if (this.reasonForRevocationFlag !== null) { - bytes = _util2.default.str2Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); + bytes = _util2.default.str_to_Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString); arr.push(write_sub_packet(sub.reason_for_revocation, bytes)); } if (this.features !== null) { - bytes = _util2.default.str2Uint8Array(_util2.default.bin2str(this.features)); + bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.features)); arr.push(write_sub_packet(sub.features, bytes)); } if (this.signatureTargetPublicKeyAlgorithm !== null) { bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])]; - bytes.push(_util2.default.str2Uint8Array(this.signatureTargetHash)); + bytes.push(_util2.default.str_to_Uint8Array(this.signatureTargetHash)); bytes = _util2.default.concatUint8Array(bytes); arr.push(write_sub_packet(sub.signature_target, bytes)); } @@ -19247,11 +44433,11 @@ Signature.prototype.write_all_sub_packets = function () { * @param {Integer} type subpacket signature type. Signature types as described * in {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 Section 5.2.3.2} * @param {String} data data to be included - * @return {String} a string-representation of a sub signature packet (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC 4880 5.2.3.1}) + * @returns {String} a string-representation of a sub signature packet (See {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC 4880 5.2.3.1}) */ function write_sub_packet(type, data) { var arr = []; - arr.push(_packet2.default.writeSimpleLength(data.length + 1)); + arr.push(_packet3.default.writeSimpleLength(data.length + 1)); arr.push(new Uint8Array([type])); arr.push(data); return _util2.default.concatUint8Array(arr); @@ -19272,7 +44458,7 @@ Signature.prototype.read_sub_packet = function (bytes) { // The leftwost bit denotes a "critical" packet, but we ignore it. var type = bytes[mypos++] & 0x7F; - var seconds; + var seconds = void 0; // subpacket type switch (type) { @@ -19336,7 +44522,6 @@ Signature.prototype.read_sub_packet = function (bytes) { // Notation Data // We don't know how to handle anything but a text flagged data. if (bytes[mypos] === 0x80) { - // We extract key/value tuple from the byte stream. mypos += 4; var m = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2)); @@ -19344,8 +44529,8 @@ Signature.prototype.read_sub_packet = function (bytes) { var n = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2)); mypos += 2; - var name = _util2.default.Uint8Array2str(bytes.subarray(mypos, mypos + m)), - value = _util2.default.Uint8Array2str(bytes.subarray(mypos + m, mypos + m + n)); + var name = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + m)); + var value = _util2.default.Uint8Array_to_str(bytes.subarray(mypos + m, mypos + m + n)); this.notation = this.notation || {}; this.notation[name] = value; @@ -19367,7 +44552,7 @@ Signature.prototype.read_sub_packet = function (bytes) { break; case 24: // Preferred Key Server - this.preferredKeyServer = _util2.default.Uint8Array2str(bytes.subarray(mypos, bytes.length)); + this.preferredKeyServer = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length)); break; case 25: // Primary User ID @@ -19375,7 +44560,7 @@ Signature.prototype.read_sub_packet = function (bytes) { break; case 26: // Policy URI - this.policyURI = _util2.default.Uint8Array2str(bytes.subarray(mypos, bytes.length)); + this.policyURI = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length)); break; case 27: // Key Flags @@ -19383,27 +44568,29 @@ Signature.prototype.read_sub_packet = function (bytes) { break; case 28: // Signer's User ID - this.signersUserId += _util2.default.Uint8Array2str(bytes.subarray(mypos, bytes.length)); + this.signersUserId += _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length)); break; case 29: // Reason for Revocation this.reasonForRevocationFlag = bytes[mypos++]; - this.reasonForRevocationString = _util2.default.Uint8Array2str(bytes.subarray(mypos, bytes.length)); + this.reasonForRevocationString = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length)); break; case 30: // Features read_array.call(this, 'features', bytes.subarray(mypos, bytes.length)); break; case 31: - // Signature Target - // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) - this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; - this.signatureTargetHashAlgorithm = bytes[mypos++]; + { + // Signature Target + // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + this.signatureTargetPublicKeyAlgorithm = bytes[mypos++]; + this.signatureTargetHashAlgorithm = bytes[mypos++]; - var len = _crypto2.default.getHashByteLength(this.signatureTargetHashAlgorithm); + var len = _crypto2.default.getHashByteLength(this.signatureTargetHashAlgorithm); - this.signatureTargetHash = _util2.default.Uint8Array2str(bytes.subarray(mypos, mypos + len)); - break; + this.signatureTargetHash = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + len)); + break; + } case 32: // Embedded Signature this.embeddedSignature = new Signature(); @@ -19431,27 +44618,29 @@ Signature.prototype.toSign = function (type, data) { case t.cert_casual: case t.cert_positive: case t.cert_revocation: - var packet, tag; + { + var _packet = void 0; + var tag = void 0; - if (data.userid !== undefined) { - tag = 0xB4; - packet = data.userid; - } else if (data.userattribute !== undefined) { - tag = 0xD1; - packet = data.userattribute; - } else { - throw new Error('Either a userid or userattribute packet needs to be ' + 'supplied for certification.'); + if (data.userid !== undefined) { + tag = 0xB4; + _packet = data.userid; + } else if (data.userattribute !== undefined) { + tag = 0xD1; + _packet = data.userattribute; + } else { + throw new Error('Either a userid or userattribute packet needs to be ' + 'supplied for certification.'); + } + + var bytes = _packet.write(); + + if (this.version === 4) { + return _util2.default.concatUint8Array([this.toSign(t.key, data), new Uint8Array([tag]), _util2.default.writeNumber(bytes.length, 4), bytes]); + } else if (this.version === 3) { + return _util2.default.concatUint8Array([this.toSign(t.key, data), bytes]); + } + break; } - - var bytes = packet.write(); - - if (this.version === 4) { - return _util2.default.concatUint8Array([this.toSign(t.key, data), new Uint8Array([tag]), _util2.default.writeNumber(bytes.length, 4), bytes]); - } else if (this.version === 3) { - return _util2.default.concatUint8Array([this.toSign(t.key, data), bytes]); - } - break; - case t.subkey_binding: case t.subkey_revocation: case t.key_binding: @@ -19491,48 +44680,78 @@ Signature.prototype.calculateTrailer = function () { * @param {String|Object} data data which on the signature applies * @param {module:packet/public_subkey|module:packet/public_key| * module:packet/secret_subkey|module:packet/secret_key} key the public key to verify the signature - * @return {boolean} True if message is verified, else false. + * @returns {Promise} True if message is verified, else false. + * @async */ -Signature.prototype.verify = function (key, data) { - var signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType), - publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm), - hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm); +Signature.prototype.verify = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(key, data) { + var signatureType, publicKeyAlgorithm, hashAlgorithm, bytes, trailer, mpicount, endian, mpi, i, j; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType); + publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm); + hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm); + bytes = this.toSign(signatureType, data); + trailer = this.calculateTrailer(); + mpicount = 0; + // Algorithm-Specific Fields for RSA signatures: + // - multiprecision number (MPI) of RSA signature value m**d mod n. - var bytes = this.toSign(signatureType, data), - trailer = this.calculateTrailer(); + if (publicKeyAlgorithm > 0 && publicKeyAlgorithm < 4) { + mpicount = 1; - var mpicount = 0; - // Algorithm-Specific Fields for RSA signatures: - // - multiprecision number (MPI) of RSA signature value m**d mod n. - if (publicKeyAlgorithm > 0 && publicKeyAlgorithm < 4) { - mpicount = 1; - } - // Algorithm-Specific Fields for DSA signatures: - // - MPI of DSA value r. - // - MPI of DSA value s. - else if (publicKeyAlgorithm === 17) { - mpicount = 2; - } + // Algorithm-Specific Fields for DSA, ECDSA, and EdDSA signatures: + // - MPI of DSA value r. + // - MPI of DSA value s. + } else if (publicKeyAlgorithm === _enums2.default.publicKey.dsa || publicKeyAlgorithm === _enums2.default.publicKey.ecdsa || publicKeyAlgorithm === _enums2.default.publicKey.eddsa) { + mpicount = 2; + } - var mpi = [], - i = 0; - for (var j = 0; j < mpicount; j++) { - mpi[j] = new _mpi2.default(); - i += mpi[j].read(this.signature.subarray(i, this.signature.length)); - } + // EdDSA signature parameters are encoded in little-endian format + // https://tools.ietf.org/html/rfc8032#section-5.1.2 + endian = publicKeyAlgorithm === _enums2.default.publicKey.eddsa ? 'le' : 'be'; + mpi = []; + i = 0; - this.verified = _crypto2.default.signature.verify(publicKeyAlgorithm, hashAlgorithm, mpi, key.mpi, _util2.default.concatUint8Array([bytes, this.signatureData, trailer])); + for (j = 0; j < mpicount; j++) { + mpi[j] = new _mpi2.default(); + i += mpi[j].read(this.signature.subarray(i, this.signature.length), endian); + } - return this.verified; -}; + _context2.next = 13; + return _crypto2.default.signature.verify(publicKeyAlgorithm, hashAlgorithm, mpi, key.params, _util2.default.concatUint8Array([bytes, this.signatureData, trailer])); + + case 13: + this.verified = _context2.sent; + return _context2.abrupt('return', this.verified); + + case 15: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x4, _x5) { + return _ref2.apply(this, arguments); + }; +}(); /** * Verifies signature expiration date - * @return {Boolean} true if expired + * @param {Date} date (optional) use the given date for verification instead of the current time + * @returns {Boolean} true if expired */ Signature.prototype.isExpired = function () { - if (!this.signatureNeverExpires) { - return Date.now() > this.created.getTime() + this.signatureExpirationTime * 1000; + var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date(); + + var normDate = _util2.default.normalizeDate(date); + if (normDate !== null) { + var expirationTime = !this.signatureNeverExpires ? this.created.getTime() + this.signatureExpirationTime * 1000 : Infinity; + return !(this.created <= normDate && normDate < expirationTime); } return false; }; @@ -19544,7 +44763,38 @@ Signature.prototype.postCloneTypeFix = function () { this.issuerKeyId = _keyid2.default.fromClone(this.issuerKeyId); }; -},{"../crypto":24,"../enums.js":35,"../type/keyid.js":67,"../type/mpi.js":68,"../util.js":70,"./packet.js":51}],59:[function(_dereq_,module,exports){ +exports.default = Signature; + +},{"../crypto":319,"../enums.js":337,"../type/keyid.js":372,"../type/mpi.js":373,"../util.js":376,"./packet.js":353,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],361:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +var _crypto = _dereq_('../crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var VERSION = 1; // A one-octet version number of the data packet. // OpenPGP.js - An OpenPGP implementation in javascript // Copyright (C) 2016 Tankred Hase // @@ -19563,36 +44813,17 @@ Signature.prototype.postCloneTypeFix = function () { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with Additional Data (AEAD) Protected Data Packet - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: AEAD Protected Data Packet + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = SymEncryptedAEADProtected; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _crypto = _dereq_('../crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VERSION = 1; // A one-octet version number of the data packet. var IV_LEN = _crypto2.default.gcm.ivLength; // currently only AES-GCM is supported /** - * @constructor + * @class */ function SymEncryptedAEADProtected() { this.tag = _enums2.default.packet.symEncryptedAEADProtected; @@ -19602,9 +44833,12 @@ function SymEncryptedAEADProtected() { this.packets = null; } +exports.default = SymEncryptedAEADProtected; + /** * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) */ + SymEncryptedAEADProtected.prototype.read = function (bytes) { var offset = 0; if (bytes[offset] !== VERSION) { @@ -19619,7 +44853,7 @@ SymEncryptedAEADProtected.prototype.read = function (bytes) { /** * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @return {Uint8Array} The encrypted payload + * @returns {Uint8Array} The encrypted payload */ SymEncryptedAEADProtected.prototype.write = function () { return _util2.default.concatUint8Array([new Uint8Array([this.version]), this.iv, this.encrypted]); @@ -19629,32 +44863,108 @@ SymEncryptedAEADProtected.prototype.write = function () { * Decrypt the encrypted payload. * @param {String} sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' * @param {Uint8Array} key The session key used to encrypt the payload - * @return {Promise} Nothing is returned + * @returns {Promise} + * @async */ -SymEncryptedAEADProtected.prototype.decrypt = function (sessionKeyAlgorithm, key) { - var _this = this; +SymEncryptedAEADProtected.prototype.decrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(sessionKeyAlgorithm, key) { + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.t0 = this.packets; + _context.next = 3; + return _crypto2.default.gcm.decrypt(sessionKeyAlgorithm, this.encrypted, key, this.iv); - return _crypto2.default.gcm.decrypt(sessionKeyAlgorithm, this.encrypted, key, this.iv).then(function (decrypted) { - _this.packets.read(decrypted); - }); -}; + case 3: + _context.t1 = _context.sent; + + _context.t0.read.call(_context.t0, _context.t1); + + return _context.abrupt('return', true); + + case 6: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; +}(); /** * Encrypt the packet list payload. * @param {String} sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' * @param {Uint8Array} key The session key used to encrypt the payload - * @return {Promise} Nothing is returned + * @returns {Promise} + * @async */ -SymEncryptedAEADProtected.prototype.encrypt = function (sessionKeyAlgorithm, key) { - var _this2 = this; +SymEncryptedAEADProtected.prototype.encrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(sessionKeyAlgorithm, key) { + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return _crypto2.default.random.getRandomBytes(IV_LEN); - this.iv = _crypto2.default.random.getRandomValues(new Uint8Array(IV_LEN)); // generate new random IV - return _crypto2.default.gcm.encrypt(sessionKeyAlgorithm, this.packets.write(), key, this.iv).then(function (encrypted) { - _this2.encrypted = encrypted; - }); -}; + case 2: + this.iv = _context2.sent; + _context2.next = 5; + return _crypto2.default.gcm.encrypt(sessionKeyAlgorithm, this.packets.write(), key, this.iv); + + case 5: + this.encrypted = _context2.sent; + return _context2.abrupt('return', true); + + case 7: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x3, _x4) { + return _ref2.apply(this, arguments); + }; +}(); + +},{"../crypto":319,"../enums":337,"../util":376,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],362:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _exports = _dereq_('asmcrypto.js/src/aes/cfb/exports'); + +var _crypto = _dereq_('../crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -},{"../crypto":24,"../enums.js":35,"../util.js":70}],60:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -19673,47 +44983,21 @@ SymEncryptedAEADProtected.prototype.encrypt = function (sessionKeyAlgorithm, key // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the Sym. Encrypted Integrity Protected Data - * Packet (Tag 18)
- *
+ * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: * The Symmetrically Encrypted Integrity Protected Data packet is * a variant of the Symmetrically Encrypted Data packet. It is a new feature * created for OpenPGP that addresses the problem of detecting a modification to * encrypted data. It is used in combination with a Modification Detection Code * packet. + * @requires asmcrypto.js * @requires crypto - * @requires util * @requires enums - * @requires config + * @requires util * @module packet/sym_encrypted_integrity_protected */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = SymEncryptedIntegrityProtected; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _crypto = _dereq_('../crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -var _asmcryptoLite = _dereq_('asmcrypto-lite'); - -var _asmcryptoLite2 = _interopRequireDefault(_asmcryptoLite); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var nodeCrypto = _util2.default.getNodeCrypto(); var Buffer = _util2.default.getNodeBuffer(); @@ -19757,61 +45041,112 @@ SymEncryptedIntegrityProtected.prototype.write = function () { * Encrypt the payload in the packet. * @param {String} sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' * @param {Uint8Array} key The key of cipher blocksize length to be used - * @return {Promise} + * @returns {Promise} + * @async */ -SymEncryptedIntegrityProtected.prototype.encrypt = function (sessionKeyAlgorithm, key) { - var bytes = this.packets.write(); - var prefixrandom = _crypto2.default.getPrefixRandom(sessionKeyAlgorithm); - var repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); - var prefix = _util2.default.concatUint8Array([prefixrandom, repeat]); - var mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet +SymEncryptedIntegrityProtected.prototype.encrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(sessionKeyAlgorithm, key) { + var bytes, prefixrandom, repeat, prefix, mdc, tohash, hash; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + bytes = this.packets.write(); + _context.next = 3; + return _crypto2.default.getPrefixRandom(sessionKeyAlgorithm); - var tohash = _util2.default.concatUint8Array([bytes, mdc]); - var hash = _crypto2.default.hash.sha1(_util2.default.concatUint8Array([prefix, tohash])); - tohash = _util2.default.concatUint8Array([tohash, hash]); + case 3: + prefixrandom = _context.sent; + repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]); + prefix = _util2.default.concatUint8Array([prefixrandom, repeat]); + mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet - if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { - // AES optimizations. Native code for node, asmCrypto for browser. - this.encrypted = aesEncrypt(sessionKeyAlgorithm, prefix, tohash, key); - } else { - this.encrypted = _crypto2.default.cfb.encrypt(prefixrandom, sessionKeyAlgorithm, tohash, key, false); - this.encrypted = this.encrypted.subarray(0, prefix.length + tohash.length); - } + tohash = _util2.default.concatUint8Array([bytes, mdc]); + hash = _crypto2.default.hash.sha1(_util2.default.concatUint8Array([prefix, tohash])); - return Promise.resolve(); -}; + tohash = _util2.default.concatUint8Array([tohash, hash]); + + if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { + // AES optimizations. Native code for node, asmCrypto for browser. + this.encrypted = aesEncrypt(sessionKeyAlgorithm, prefix, tohash, key); + } else { + this.encrypted = _crypto2.default.cfb.encrypt(prefixrandom, sessionKeyAlgorithm, tohash, key, false); + this.encrypted = this.encrypted.subarray(0, prefix.length + tohash.length); + } + return _context.abrupt('return', true); + + case 12: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; +}(); /** * Decrypts the encrypted data contained in the packet. * @param {String} sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' * @param {Uint8Array} key The key of cipher blocksize length to be used - * @return {Promise} + * @returns {Promise} + * @async */ -SymEncryptedIntegrityProtected.prototype.decrypt = function (sessionKeyAlgorithm, key) { - var decrypted = void 0; - if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { - // AES optimizations. Native code for node, asmCrypto for browser. - decrypted = aesDecrypt(sessionKeyAlgorithm, this.encrypted, key); - } else { - decrypted = _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, false); - } +SymEncryptedIntegrityProtected.prototype.decrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(sessionKeyAlgorithm, key) { + var decrypted, prefix, bytes, tohash, mdc; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + decrypted = void 0; - // there must be a modification detection code packet as the - // last packet and everything gets hashed except the hash itself - var prefix = _crypto2.default.cfb.mdc(sessionKeyAlgorithm, key, this.encrypted); - var bytes = decrypted.subarray(0, decrypted.length - 20); - var tohash = _util2.default.concatUint8Array([prefix, bytes]); - this.hash = _util2.default.Uint8Array2str(_crypto2.default.hash.sha1(tohash)); - var mdc = _util2.default.Uint8Array2str(decrypted.subarray(decrypted.length - 20, decrypted.length)); + if (sessionKeyAlgorithm.substr(0, 3) === 'aes') { + // AES optimizations. Native code for node, asmCrypto for browser. + decrypted = aesDecrypt(sessionKeyAlgorithm, this.encrypted, key); + } else { + decrypted = _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, false); + } - if (this.hash !== mdc) { - throw new Error('Modification detected.'); - } else { - this.packets.read(decrypted.subarray(0, decrypted.length - 22)); - } + // there must be a modification detection code packet as the + // last packet and everything gets hashed except the hash itself + prefix = _crypto2.default.cfb.mdc(sessionKeyAlgorithm, key, this.encrypted); + bytes = decrypted.subarray(0, decrypted.length - 20); + tohash = _util2.default.concatUint8Array([prefix, bytes]); - return Promise.resolve(); -}; + this.hash = _util2.default.Uint8Array_to_str(_crypto2.default.hash.sha1(tohash)); + mdc = _util2.default.Uint8Array_to_str(decrypted.subarray(decrypted.length - 20, decrypted.length)); + + if (!(this.hash !== mdc)) { + _context2.next = 11; + break; + } + + throw new Error('Modification detected.'); + + case 11: + this.packets.read(decrypted.subarray(0, decrypted.length - 22)); + + case 12: + return _context2.abrupt('return', true); + + case 13: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x3, _x4) { + return _ref2.apply(this, arguments); + }; +}(); + +exports.default = SymEncryptedIntegrityProtected; ////////////////////////// // // @@ -19824,10 +45159,8 @@ function aesEncrypt(algo, prefix, pt, key) { if (nodeCrypto) { // Node crypto library. return nodeEncrypt(algo, prefix, pt, key); - } else { - // asm.js fallback - return _asmcryptoLite2.default.AES_CFB.encrypt(_util2.default.concatUint8Array([prefix, pt]), key); - } + } // asm.js fallback + return _exports.AES_CFB.encrypt(_util2.default.concatUint8Array([prefix, pt]), key); } function aesDecrypt(algo, ct, key) { @@ -19837,7 +45170,7 @@ function aesDecrypt(algo, ct, key) { pt = nodeDecrypt(algo, ct, key); } else { // asm.js fallback - pt = _asmcryptoLite2.default.AES_CFB.decrypt(ct, key); + pt = _exports.AES_CFB.decrypt(ct, key); } return pt.subarray(_crypto2.default.cipher[algo].blockSize + 2, pt.length); // Remove random prefix } @@ -19859,51 +45192,24 @@ function nodeDecrypt(algo, ct, key) { return new Uint8Array(pt); } -},{"../crypto":24,"../enums.js":35,"../util.js":70,"asmcrypto-lite":1}],61:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * Public-Key Encrypted Session Key Packets (Tag 1)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - * @requires util - * @requires crypto - * @requires enums - * @requires type/s2k - * @module packet/sym_encrypted_session_key - */ - +},{"../crypto":319,"../enums":337,"../util":376,"asmcrypto.js/src/aes/cfb/exports":4,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],363:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SymEncryptedSessionKey; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _slicedToArray2 = _dereq_('babel-runtime/helpers/slicedToArray'); + +var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); var _util = _dereq_('../util.js'); @@ -19926,6 +45232,45 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de /** * @constructor */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Public-Key Encrypted Session Key Packets (Tag 1) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + * @requires util + * @requires crypto + * @requires enums + * @requires type/s2k + * @module packet/sym_encrypted_session_key + */ + function SymEncryptedSessionKey() { this.tag = _enums2.default.packet.symEncryptedSessionKey; this.version = 4; @@ -19933,7 +45278,7 @@ function SymEncryptedSessionKey() { this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; this.encrypted = null; - this.s2k = new _s2k2.default(); + this.s2k = null; } /** @@ -19944,16 +45289,20 @@ function SymEncryptedSessionKey() { * @param {Integer} len * Length of the packet or the remaining length of * input at position - * @return {module:packet/sym_encrypted_session_key} Object representation + * @returns {module:packet/sym_encrypted_session_key} Object representation */ SymEncryptedSessionKey.prototype.read = function (bytes) { - // A one-octet version number. The only currently defined version is 4. - this.version = bytes[0]; // A one-octet number describing the symmetric algorithm used. + var _bytes = (0, _slicedToArray3.default)(bytes, 1); + // A one-octet version number. The only currently defined version is 4. + + + this.version = _bytes[0]; var algo = _enums2.default.read(_enums2.default.symmetric, bytes[1]); // A string-to-key (S2K) specifier, length as defined above. + this.s2k = new _s2k2.default(); var s2klength = this.s2k.read(bytes.subarray(2, bytes.length)); // Optionally, the encrypted session key itself, which is decrypted @@ -19980,46 +45329,105 @@ SymEncryptedSessionKey.prototype.write = function () { }; /** - * Decrypts the session key (only for public key encrypted session key - * packets (tag 1) - * - * @return {Uint8Array} The unencrypted session key + * Decrypts the session key + * @param {String} passphrase The passphrase in string form + * @returns {Promise} + * @async */ -SymEncryptedSessionKey.prototype.decrypt = function (passphrase) { - var algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; +SymEncryptedSessionKey.prototype.decrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(passphrase) { + var algo, length, key, decrypted; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; + length = _crypto2.default.cipher[algo].keySize; + key = this.s2k.produce_key(passphrase, length); - var length = _crypto2.default.cipher[algo].keySize; - var key = this.s2k.produce_key(passphrase, length); - if (this.encrypted === null) { - this.sessionKey = key; - } else { - var decrypted = _crypto2.default.cfb.normalDecrypt(algo, key, this.encrypted, null); + if (this.encrypted === null) { + this.sessionKey = key; + } else { + decrypted = _crypto2.default.cfb.normalDecrypt(algo, key, this.encrypted, null); - this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decrypted[0]); - this.sessionKey = decrypted.subarray(1, decrypted.length); - } -}; + this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decrypted[0]); + this.sessionKey = decrypted.subarray(1, decrypted.length); + } + return _context.abrupt('return', true); -SymEncryptedSessionKey.prototype.encrypt = function (passphrase) { - var algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; + case 5: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); - this.sessionKeyEncryptionAlgorithm = algo; + return function (_x) { + return _ref.apply(this, arguments); + }; +}(); - var length = _crypto2.default.cipher[algo].keySize; - var key = this.s2k.produce_key(passphrase, length); +/** + * Encrypts the session key + * @param {String} passphrase The passphrase in string form + * @returns {Promise} + * @async + */ +SymEncryptedSessionKey.prototype.encrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(passphrase) { + var algo, length, key, algo_enum, private_key; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; - var algo_enum = new Uint8Array([_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)]); - var private_key; - if (this.sessionKey === null) { - this.sessionKey = _crypto2.default.getRandomBytes(_crypto2.default.cipher[this.sessionKeyAlgorithm].keySize); - } - private_key = _util2.default.concatUint8Array([algo_enum, this.sessionKey]); + this.sessionKeyEncryptionAlgorithm = algo; - this.encrypted = _crypto2.default.cfb.normalEncrypt(algo, key, private_key, null); -}; + this.s2k = new _s2k2.default(); + _context2.next = 5; + return _crypto2.default.random.getRandomBytes(8); + + case 5: + this.s2k.salt = _context2.sent; + length = _crypto2.default.cipher[algo].keySize; + key = this.s2k.produce_key(passphrase, length); + algo_enum = new Uint8Array([_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)]); + + if (!(this.sessionKey === null)) { + _context2.next = 13; + break; + } + + _context2.next = 12; + return _crypto2.default.generateSessionKey(this.sessionKeyAlgorithm); + + case 12: + this.sessionKey = _context2.sent; + + case 13: + private_key = _util2.default.concatUint8Array([algo_enum, this.sessionKey]); + + + this.encrypted = _crypto2.default.cfb.normalEncrypt(algo, key, private_key, null); + return _context2.abrupt('return', true); + + case 16: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x2) { + return _ref2.apply(this, arguments); + }; +}(); /** * Fix custom types after cloning @@ -20028,43 +45436,22 @@ SymEncryptedSessionKey.prototype.postCloneTypeFix = function () { this.s2k = _s2k2.default.fromClone(this.s2k); }; -},{"../crypto":24,"../enums.js":35,"../type/s2k.js":69,"../util.js":70}],62:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 3.0 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -/** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
- *
- * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: The Symmetrically Encrypted Data packet contains data encrypted - * with a symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - * @requires crypto - * @requires enums - * @module packet/symmetrically_encrypted - */ +exports.default = SymEncryptedSessionKey; +},{"../crypto":319,"../enums.js":337,"../type/s2k.js":375,"../util.js":376,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/helpers/slicedToArray":33,"babel-runtime/regenerator":35}],364:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = SymmetricallyEncrypted; + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _crypto = _dereq_('../crypto'); @@ -20090,79 +45477,7 @@ function SymmetricallyEncrypted() { * @type {module:packet/packetlist} */ this.packets = null; this.ignore_mdc_error = _config2.default.ignore_mdc_error; -} - -SymmetricallyEncrypted.prototype.read = function (bytes) { - this.encrypted = bytes; -}; - -SymmetricallyEncrypted.prototype.write = function () { - return this.encrypted; -}; - -/** - * Symmetrically decrypt the packet data - * - * @param {module:enums.symmetric} sessionKeyAlgorithm - * Symmetric key algorithm to use // See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880 9.2} - * @param {String} key - * Key as string with the corresponding length to the - * algorithm - */ -SymmetricallyEncrypted.prototype.decrypt = function (sessionKeyAlgorithm, key) { - var decrypted = _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, true); - // for modern cipher (blocklength != 64 bit, except for Twofish) MDC is required - if (!this.ignore_mdc_error && (sessionKeyAlgorithm === 'aes128' || sessionKeyAlgorithm === 'aes192' || sessionKeyAlgorithm === 'aes256')) { - throw new Error('Decryption failed due to missing MDC in combination with modern cipher.'); - } - this.packets.read(decrypted); - - return Promise.resolve(); -}; - -SymmetricallyEncrypted.prototype.encrypt = function (algo, key) { - var data = this.packets.write(); - - this.encrypted = _crypto2.default.cfb.encrypt(_crypto2.default.getPrefixRandom(algo), algo, data, key, true); - - return Promise.resolve(); -}; - -},{"../config":10,"../crypto":24,"../enums.js":35}],63:[function(_dereq_,module,exports){ -/** - * @requires enums - * @module packet/trust - */ - -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = Trust; - -var _enums = _dereq_('../enums.js'); - -var _enums2 = _interopRequireDefault(_enums); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @constructor - */ -function Trust() { - this.tag = _enums2.default.packet.trust; -} - -/** - * Parsing function for a trust packet (tag 12). - * Currently empty as we ignore trust packets - * @param {String} byptes payload of a tag 12 packet - */ -Trust.prototype.read = function () {}; - -},{"../enums.js":35}],64:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript +} // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or @@ -20180,32 +45495,153 @@ Trust.prototype.read = function () {}; // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the User Attribute Packet (Tag 17)
- *
- * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - *
- * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - * module packet/user_attribute + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + * @requires crypto * @requires enums - * @module packet/user_attribute + * @module packet/symmetrically_encrypted */ +SymmetricallyEncrypted.prototype.read = function (bytes) { + this.encrypted = bytes; +}; + +SymmetricallyEncrypted.prototype.write = function () { + return this.encrypted; +}; + +/** + * Decrypt the symmetrically-encrypted packet data + * @param {module:enums.symmetric} sessionKeyAlgorithm + * Symmetric key algorithm to use // See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880 9.2} + * @param {Uint8Array} key The key of cipher blocksize length to be used + * @returns {Promise} + * @async + */ +SymmetricallyEncrypted.prototype.decrypt = function () { + var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(sessionKeyAlgorithm, key) { + var decrypted; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + decrypted = _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted, true); + // for modern cipher (blocklength != 64 bit, except for Twofish) MDC is required + + if (!(!this.ignore_mdc_error && (sessionKeyAlgorithm === 'aes128' || sessionKeyAlgorithm === 'aes192' || sessionKeyAlgorithm === 'aes256'))) { + _context.next = 3; + break; + } + + throw new Error('Decryption failed due to missing MDC in combination with modern cipher.'); + + case 3: + this.packets.read(decrypted); + + return _context.abrupt('return', true); + + case 5: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; +}(); + +/** + * Encrypt the symmetrically-encrypted packet data + * @param {module:enums.symmetric} sessionKeyAlgorithm + * Symmetric key algorithm to use // See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880 9.2} + * @param {Uint8Array} key The key of cipher blocksize length to be used + * @returns {Promise} + * @async + */ +SymmetricallyEncrypted.prototype.encrypt = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(algo, key) { + var data; + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + data = this.packets.write(); + _context2.t0 = _crypto2.default.cfb; + _context2.next = 4; + return _crypto2.default.getPrefixRandom(algo); + + case 4: + _context2.t1 = _context2.sent; + _context2.t2 = algo; + _context2.t3 = data; + _context2.t4 = key; + this.encrypted = _context2.t0.encrypt.call(_context2.t0, _context2.t1, _context2.t2, _context2.t3, _context2.t4, true); + return _context2.abrupt('return', true); + + case 10: + case 'end': + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x3, _x4) { + return _ref2.apply(this, arguments); + }; +}(); + +exports.default = SymmetricallyEncrypted; + +},{"../config":306,"../crypto":319,"../enums.js":337,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}],365:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + */ +function Trust() { + this.tag = _enums2.default.packet.trust; +} + +/** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + * @param {String} byptes payload of a tag 12 packet + */ +/** + * @requires enums + * @module packet/trust + */ + +Trust.prototype.read = function () {}; // TODO + +exports.default = Trust; + +},{"../enums.js":337}],366:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = UserAttribute; var _util = _dereq_('../util.js'); @@ -20233,45 +45669,6 @@ function UserAttribute() { * parsing function for a user attribute packet (tag 17). * @param {Uint8Array} input payload of a tag 17 packet */ -UserAttribute.prototype.read = function (bytes) { - var i = 0; - while (i < bytes.length) { - var len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length)); - i += len.offset; - - this.attributes.push(_util2.default.Uint8Array2str(bytes.subarray(i, i + len.len))); - i += len.len; - } -}; - -/** - * Creates a binary representation of the user attribute packet - * @return {Uint8Array} string representation - */ -UserAttribute.prototype.write = function () { - var arr = []; - for (var i = 0; i < this.attributes.length; i++) { - arr.push(_packet2.default.writeSimpleLength(this.attributes[i].length)); - arr.push(_util2.default.str2Uint8Array(this.attributes[i])); - } - return _util2.default.concatUint8Array(arr); -}; - -/** - * Compare for equality - * @param {module:user_attribute~UserAttribute} usrAttr - * @return {Boolean} true if equal - */ -UserAttribute.prototype.equals = function (usrAttr) { - if (!usrAttr || !(usrAttr instanceof UserAttribute)) { - return false; - } - return this.attributes.every(function (attr, index) { - return attr === usrAttr.attributes[index]; - }); -}; - -},{"../enums.js":35,"../util.js":70,"./packet.js":51}],65:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -20290,24 +45687,72 @@ UserAttribute.prototype.equals = function (usrAttr) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the User ID Packet (Tag 13)
- *
- * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. - * @requires util + * Implementation of the User Attribute Packet (Tag 17) + * + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + * module packet/user_attribute * @requires enums - * @module packet/userid + * @module packet/user_attribute */ +UserAttribute.prototype.read = function (bytes) { + var i = 0; + while (i < bytes.length) { + var len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length)); + i += len.offset; + + this.attributes.push(_util2.default.Uint8Array_to_str(bytes.subarray(i, i + len.len))); + i += len.len; + } +}; + +/** + * Creates a binary representation of the user attribute packet + * @returns {Uint8Array} string representation + */ +UserAttribute.prototype.write = function () { + var arr = []; + for (var i = 0; i < this.attributes.length; i++) { + arr.push(_packet2.default.writeSimpleLength(this.attributes[i].length)); + arr.push(_util2.default.str_to_Uint8Array(this.attributes[i])); + } + return _util2.default.concatUint8Array(arr); +}; + +/** + * Compare for equality + * @param {module:user_attribute~UserAttribute} usrAttr + * @returns {Boolean} true if equal + */ +UserAttribute.prototype.equals = function (usrAttr) { + if (!usrAttr || !(usrAttr instanceof UserAttribute)) { + return false; + } + return this.attributes.every(function (attr, index) { + return attr === usrAttr.attributes[index]; + }); +}; + +exports.default = UserAttribute; + +},{"../enums.js":337,"../util.js":376,"./packet.js":353}],367:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Userid; var _util = _dereq_('../util.js'); @@ -20322,32 +45767,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de /** * @constructor */ -function Userid() { - this.tag = _enums2.default.packet.userid; - /** A string containing the user id. Usually in the form - * John Doe - * @type {String} - */ - this.userid = ''; -} - -/** - * Parsing function for a user id packet (tag 13). - * @param {Uint8Array} input payload of a tag 13 packet - */ -Userid.prototype.read = function (bytes) { - this.userid = _util2.default.decode_utf8(_util2.default.Uint8Array2str(bytes)); -}; - -/** - * Creates a binary representation of the user id packet - * @return {Uint8Array} binary representation - */ -Userid.prototype.write = function () { - return _util2.default.str2Uint8Array(_util2.default.encode_utf8(this.userid)); -}; - -},{"../enums.js":35,"../util.js":70}],66:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -20366,14 +45785,93 @@ Userid.prototype.write = function () { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * @requires config - * @requires crypto - * @requires encoding/armor + * Implementation of the User ID Packet (Tag 13) + * + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + * @requires util * @requires enums - * @requires packet - * @module signature + * @module packet/userid */ +function Userid() { + this.tag = _enums2.default.packet.userid; + /** A string containing the user id. Usually in the form + * John Doe + * @type {String} + */ + this.userid = ''; +} + +/** + * Parsing function for a user id packet (tag 13). + * @param {Uint8Array} input payload of a tag 13 packet + */ +Userid.prototype.read = function (bytes) { + this.userid = _util2.default.decode_utf8(_util2.default.Uint8Array_to_str(bytes)); +}; + +/** + * Creates a binary representation of the user id packet + * @returns {Uint8Array} binary representation + */ +Userid.prototype.write = function () { + return _util2.default.str_to_Uint8Array(_util2.default.encode_utf8(this.userid)); +}; + +exports.default = Userid; + +},{"../enums.js":337,"../util.js":376}],368:[function(_dereq_,module,exports){ +'use strict'; + +var _symbol = _dereq_('babel-runtime/core-js/symbol'); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _from = _dereq_('babel-runtime/core-js/array/from'); + +var _from2 = _interopRequireDefault(_from); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable import/no-extraneous-dependencies */ +// Old browser polyfills +// All are listed as dev dependencies because Node does not need them +// and for browser babel will take care of it + +if (typeof window.fetch === 'undefined') { + _dereq_('whatwg-fetch'); +} +if (typeof Array.prototype.fill === 'undefined') { + _dereq_('core-js/fn/array/fill'); +} +if (typeof Array.prototype.find === 'undefined') { + _dereq_('core-js/fn/array/find'); +} +if (typeof _from2.default === 'undefined') { + _dereq_('core-js/fn/array/from'); +} +if (typeof _promise2.default === 'undefined') { + _dereq_('core-js/fn/promise'); +} +if (typeof Uint8Array.from === 'undefined') { + _dereq_('core-js/fn/typed/uint8-array'); +} +if (typeof String.prototype.repeat === 'undefined') { + _dereq_('core-js/fn/string/repeat'); +} +if (typeof _symbol2.default === 'undefined') { + _dereq_('core-js/fn/symbol'); +} + +},{"babel-runtime/core-js/array/from":16,"babel-runtime/core-js/promise":25,"babel-runtime/core-js/symbol":26,"core-js/fn/array/fill":41,"core-js/fn/array/find":42,"core-js/fn/array/from":43,"core-js/fn/promise":44,"core-js/fn/string/repeat":45,"core-js/fn/symbol":46,"core-js/fn/typed/uint8-array":47,"whatwg-fetch":302}],369:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -20387,11 +45885,11 @@ var _packet = _dereq_('./packet'); var _packet2 = _interopRequireDefault(_packet); -var _enums = _dereq_('./enums.js'); +var _enums = _dereq_('./enums'); var _enums2 = _interopRequireDefault(_enums); -var _armor = _dereq_('./encoding/armor.js'); +var _armor = _dereq_('./encoding/armor'); var _armor2 = _interopRequireDefault(_armor); @@ -20412,36 +45910,8 @@ function Signature(packetlist) { /** * Returns ASCII armored text of signature - * @return {String} ASCII armor + * @returns {String} ASCII armor */ -Signature.prototype.armor = function () { - return _armor2.default.encode(_enums2.default.armor.signature, this.packets.write()); -}; - -/** - * reads an OpenPGP armored signature and returns a signature object - * @param {String} armoredText text to be parsed - * @return {Signature} new signature object - * @static - */ -function readArmored(armoredText) { - var input = _armor2.default.decode(armoredText).data; - return read(input); -} - -/** - * reads an OpenPGP signature as byte array and returns a signature object - * @param {Uint8Array} input binary signature - * @return {Signature} new signature object - * @static - */ -function read(input) { - var packetlist = new _packet2.default.List(); - packetlist.read(input); - return new Signature(packetlist); -} - -},{"./encoding/armor.js":33,"./enums.js":35,"./packet":47}],67:[function(_dereq_,module,exports){ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -20460,22 +45930,211 @@ function read(input) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of type key id ({@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3})
- *
- * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. - * @requires util - * @module type/keyid + * @requires enums + * @requires packet + * @requires encoding/armor + * @module signature */ +Signature.prototype.armor = function () { + return _armor2.default.encode(_enums2.default.armor.signature, this.packets.write()); +}; + +/** + * reads an OpenPGP armored signature and returns a signature object + * @param {String} armoredText text to be parsed + * @returns {Signature} new signature object + * @static + */ +function readArmored(armoredText) { + var input = _armor2.default.decode(armoredText).data; + return read(input); +} + +/** + * reads an OpenPGP signature as byte array and returns a signature object + * @param {Uint8Array} input binary signature + * @returns {Signature} new signature object + * @static + */ +function read(input) { + var packetlist = new _packet2.default.List(); + packetlist.read(input); + return new Signature(packetlist); +} + +},{"./encoding/armor":335,"./enums":337,"./packet":349}],370:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + */ +function ECDHSymmetricKey(data) { + if (typeof data === 'undefined') { + data = new Uint8Array([]); + } else if (_util2.default.isString(data)) { + data = _util2.default.str_to_Uint8Array(data); + } else { + data = new Uint8Array(data); + } + this.data = data; +} + +/** + * Read an ECDHSymmetricKey from an Uint8Array + * @param {Uint8Array} input Where to read the encoded symmetric key from + * @returns {Number} Number of read bytes + */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Encoded symmetric key for ECDH + * + * @requires util + * @module type/ecdh_symkey + */ + +ECDHSymmetricKey.prototype.read = function (input) { + if (input.length >= 1) { + var length = input[0]; + if (input.length >= 1 + length) { + this.data = input.subarray(1, 1 + length); + return 1 + this.data.length; + } + } + throw new Error('Invalid symmetric key'); +}; + +/** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns {Uint8Array} An array containing the value + */ +ECDHSymmetricKey.prototype.write = function () { + return _util2.default.concatUint8Array([new Uint8Array([this.data.length]), this.data]); +}; + +ECDHSymmetricKey.fromClone = function (clone) { + return new ECDHSymmetricKey(clone.data); +}; + +exports.default = ECDHSymmetricKey; + +},{"../util":376}],371:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _enums = _dereq_('../enums.js'); + +var _enums2 = _interopRequireDefault(_enums); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + * @param {enums.hash} hash Hash algorithm + * @param {enums.symmetric} cipher Symmetric algorithm + */ +function KDFParams(data) { + if (data && data.length === 2) { + this.hash = data[0]; + this.cipher = data[1]; + } else { + this.hash = _enums2.default.hash.sha1; + this.cipher = _enums2.default.symmetric.aes128; + } +} + +/** + * Read KDFParams from an Uint8Array + * @param {Uint8Array} input Where to read the KDFParams from + * @returns {Number} Number of read bytes + */ +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Implementation of type KDF parameters + * + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + * @requires enums + * @module type/kdf_params + */ + +KDFParams.prototype.read = function (input) { + if (input.length < 4 || input[0] !== 3 || input[1] !== 1) { + throw new Error('Cannot read KDFParams'); + } + this.hash = input[2]; + this.cipher = input[3]; + return 4; +}; + +/** + * Write KDFParams to an Uint8Array + * @returns {Uint8Array} Array with the KDFParams value + */ +KDFParams.prototype.write = function () { + return new Uint8Array([3, 1, this.hash, this.cipher]); +}; + +KDFParams.fromClone = function (clone) { + return new KDFParams([clone.hash, clone.cipher]); +}; + +exports.default = KDFParams; + +},{"../enums.js":337}],372:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = Keyid; var _util = _dereq_('../util.js'); @@ -20494,26 +46153,67 @@ function Keyid() { * Parsing method for a key id * @param {Uint8Array} input Input to read the key id from */ +// GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Implementation of type key id + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + * @requires util + * @module type/keyid + */ + Keyid.prototype.read = function (bytes) { - this.bytes = _util2.default.Uint8Array2str(bytes.subarray(0, 8)); + this.bytes = _util2.default.Uint8Array_to_str(bytes.subarray(0, 8)); }; Keyid.prototype.write = function () { - return _util2.default.str2Uint8Array(this.bytes); + return _util2.default.str_to_Uint8Array(this.bytes); }; Keyid.prototype.toHex = function () { - return _util2.default.hexstrdump(this.bytes); + return _util2.default.str_to_hex(this.bytes); }; +/** + * Checks equality of Key ID's + * @param {Keyid} keyid + * @param {Boolean} matchWildcard Indicates whether to check if either keyid is a wildcard + */ Keyid.prototype.equals = function (keyid) { - return this.bytes === keyid.bytes; + var matchWildcard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + return matchWildcard && (keyid.isWildcard() || this.isWildcard()) || this.bytes === keyid.bytes; }; Keyid.prototype.isNull = function () { return this.bytes === ''; }; +Keyid.prototype.isWildcard = function () { + return (/^0+$/.test(this.toHex()) + ); +}; + Keyid.mapToHex = function (keyId) { return keyId.toHex(); }; @@ -20526,11 +46226,38 @@ Keyid.fromClone = function (clone) { Keyid.fromId = function (hex) { var keyid = new Keyid(); - keyid.read(_util2.default.str2Uint8Array(_util2.default.hex2bin(hex))); + keyid.read(_util2.default.str_to_Uint8Array(_util2.default.hex_to_str(hex))); return keyid; }; -},{"../util.js":70}],68:[function(_dereq_,module,exports){ +Keyid.wildcard = function () { + var keyid = new Keyid(); + keyid.read(new Uint8Array(8)); + return keyid; +}; + +exports.default = Keyid; + +},{"../util.js":376}],373:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _bn = _dereq_('bn.js'); + +var _bn2 = _interopRequireDefault(_bn); + +var _util = _dereq_('../util'); + +var _util2 = _interopRequireDefault(_util); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @constructor + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -20554,116 +46281,149 @@ Keyid.fromId = function (hex) { // - MPI = c | d << 8 | e << ((MPI.length -2)*8) | f ((MPI.length -2)*8) /** - * Implementation of type MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2})
- *
+ * Implementation of type MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) * Multiprecision integers (also called MPIs) are unsigned integers used * to hold large integers such as the ones used in cryptographic * calculations. * An MPI consists of two pieces: a two-octet scalar that is the length * of the MPI in bits followed by a string of octets that contain the * actual integer. - * @requires crypto/public_key/jsbn + * @requires bn.js * @requires util * @module type/mpi */ +function MPI(data) { + /** An implementation dependent integer */ + if (data instanceof MPI) { + this.data = data.data; + } else if (_bn2.default.isBN(data)) { + this.fromBN(data); + } else if (_util2.default.isUint8Array(data)) { + this.fromUint8Array(data); + } else if (_util2.default.isString(data)) { + this.fromString(data); + } else { + this.data = null; + } +} + +/** + * Parsing function for a MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). + * @param {Uint8Array} input Payload of MPI data + * @param {String} endian Endianness of the data; 'be' for big-endian or 'le' for little-endian + * @returns {Integer} Length of data read + */ +MPI.prototype.read = function (bytes) { + var endian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'be'; + + if (_util2.default.isString(bytes)) { + bytes = _util2.default.str_to_Uint8Array(bytes); + } + + var bits = bytes[0] << 8 | bytes[1]; + var bytelen = bits + 7 >>> 3; + var payload = bytes.subarray(2, 2 + bytelen); + + this.fromUint8Array(payload, endian); + + return 2 + bytelen; +}; + +/** + * Converts the mpi object to a bytes as specified in + * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} + * @param {String} endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian + * @param {Integer} length Length of the data part of the MPI + * @returns {Uint8Aray} mpi Byte representation + */ +MPI.prototype.write = function (endian, length) { + return _util2.default.Uint8Array_to_MPI(this.toUint8Array(endian, length)); +}; + +MPI.prototype.bitLength = function () { + return (this.data.length - 1) * 8 + _util2.default.nbits(this.data[0]); +}; + +MPI.prototype.byteLength = function () { + return this.data.length; +}; + +MPI.prototype.toUint8Array = function (endian, length) { + endian = endian || 'be'; + length = length || this.data.length; + + var payload = new Uint8Array(length); + var start = length - this.data.length; + if (start < 0) { + throw new Error('Payload is too large.'); + } + + payload.set(this.data, start); + if (endian === 'le') { + payload.reverse(); + } + + return payload; +}; + +MPI.prototype.fromUint8Array = function (bytes) { + var endian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'be'; + + this.data = new Uint8Array(bytes.length); + this.data.set(bytes); + + if (endian === 'le') { + this.data.reverse(); + } +}; + +MPI.prototype.toString = function () { + return _util2.default.Uint8Array_to_str(this.toUint8Array()); +}; + +MPI.prototype.fromString = function (str) { + var endian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'be'; + + this.fromUint8Array(_util2.default.str_to_Uint8Array(str), endian); +}; + +MPI.prototype.toBN = function () { + return new _bn2.default(this.toUint8Array()); +}; + +MPI.prototype.fromBN = function (bn) { + this.data = bn.toArrayLike(Uint8Array); +}; + +MPI.fromClone = function (clone) { + return new MPI(clone.data); +}; + +exports.default = MPI; + +},{"../util":376,"bn.js":37}],374:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = MPI; -var _jsbn = _dereq_('../crypto/public_key/jsbn.js'); - -var _jsbn2 = _interopRequireDefault(_jsbn); - -var _util = _dereq_('../util.js'); +var _util = _dereq_('../util'); var _util2 = _interopRequireDefault(_util); +var _enums = _dereq_('../enums'); + +var _enums2 = _interopRequireDefault(_enums); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @constructor */ -function MPI() { - /** An implementation dependent integer */ - this.data = null; -} - -/** - * Parsing function for a mpi ({@link https://tools.ietf.org/html/rfc4880#section3.2|RFC 4880 3.2}). - * @param {String} input Payload of mpi data - * @return {Integer} Length of data read - */ -MPI.prototype.read = function (bytes) { - - if (typeof bytes === 'string' || String.prototype.isPrototypeOf(bytes)) { - bytes = _util2.default.str2Uint8Array(bytes); - } - - var bits = bytes[0] << 8 | bytes[1]; - - // Additional rules: - // - // The size of an MPI is ((MPI.length + 7) / 8) + 2 octets. - // - // The length field of an MPI describes the length starting from its - // most significant non-zero bit. Thus, the MPI [00 02 01] is not - // formed correctly. It should be [00 01 01]. - - // TODO: Verification of this size method! This size calculation as - // specified above is not applicable in JavaScript - var bytelen = Math.ceil(bits / 8); - - var raw = _util2.default.Uint8Array2str(bytes.subarray(2, 2 + bytelen)); - this.fromBytes(raw); - - return 2 + bytelen; -}; - -MPI.prototype.fromBytes = function (bytes) { - this.data = new _jsbn2.default(_util2.default.hexstrdump(bytes), 16); -}; - -MPI.prototype.toBytes = function () { - var bytes = _util2.default.Uint8Array2str(this.write()); - return bytes.substr(2); -}; - -MPI.prototype.byteLength = function () { - return this.toBytes().length; -}; - -/** - * Converts the mpi object to a bytes as specified in {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} - * @return {Uint8Aray} mpi Byte representation - */ -MPI.prototype.write = function () { - return _util2.default.str2Uint8Array(this.data.toMPI()); -}; - -MPI.prototype.toBigInteger = function () { - return this.data.clone(); -}; - -MPI.prototype.fromBigInteger = function (bn) { - this.data = bn.clone(); -}; - -MPI.fromClone = function (clone) { - clone.data.copyTo = _jsbn2.default.prototype.copyTo; - var bn = new _jsbn2.default(); - clone.data.copyTo(bn); - var mpi = new MPI(); - mpi.data = bn; - return mpi; -}; - -},{"../crypto/public_key/jsbn.js":29,"../util.js":70}],69:[function(_dereq_,module,exports){ -// GPG4Browsers - An OpenPGP implementation in javascript -// Copyright (C) 2011 Recurity Labs GmbH +// OpenPGP.js - An OpenPGP implementation in javascript +// Copyright (C) 2015-2016 Decentral // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -20680,25 +46440,96 @@ MPI.fromClone = function (clone) { // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** - * Implementation of the String-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7})
- *
- * String-to-key (S2K) specifiers are used to convert passphrase strings - * into symmetric-key encryption/decryption keys. They are used in two - * places, currently: to encrypt the secret part of private keys in the - * private keyring, and to convert passphrases to encryption keys for - * symmetrically encrypted messages. - * @requires crypto - * @requires enums + * Wrapper to an OID value + * + * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: + * The sequence of octets in the third column is the result of applying + * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier + * with subsequent truncation. The truncation removes the two fields of + * encoded Object Identifier. The first omitted field is one octet + * representing the Object Identifier tag, and the second omitted field + * is the length of the Object Identifier body. For example, the + * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A + * 86 48 CE 3D 03 01 07", from which the first entry in the table above + * is constructed by omitting the first two octets. Only the truncated + * sequence of octets is the valid representation of a curve OID. * @requires util - * @module type/s2k + * @requires enums + * @module type/oid */ +function OID(oid) { + if (oid instanceof OID) { + this.oid = oid.oid; + } else if (_util2.default.isArray(oid) || _util2.default.isUint8Array(oid)) { + oid = new Uint8Array(oid); + if (oid[0] === 0x06) { + // DER encoded oid byte array + oid = oid.subarray(2); + } + this.oid = oid; + } else { + this.oid = ''; + } +} + +/** + * Method to read an OID object + * @param {Uint8Array} input Where to read the OID from + * @returns {Number} Number of read bytes + */ +OID.prototype.read = function (input) { + if (input.length >= 1) { + var length = input[0]; + if (input.length >= 1 + length) { + this.oid = input.subarray(1, 1 + length); + return 1 + this.oid.length; + } + } + throw new Error('Invalid oid'); +}; + +/** + * Serialize an OID object + * @returns {Uint8Array} Array with the serialized value the OID + */ +OID.prototype.write = function () { + return _util2.default.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]); +}; + +/** + * Serialize an OID object as a hex string + * @returns {string} String with the hex value of the OID + */ +OID.prototype.toHex = function () { + return _util2.default.Uint8Array_to_hex(this.oid); +}; + +/** + * If a known curve object identifier, return the canonical name of the curve + * @returns {string} String with the canonical name of the curve + */ +OID.prototype.getName = function () { + var hex = this.toHex(); + if (_enums2.default.curve[hex]) { + return _enums2.default.write(_enums2.default.curve, hex); + } else { + throw new Error('Unknown curve object identifier.'); + } +}; + +OID.fromClone = function (clone) { + return new OID(clone.oid); +}; + +exports.default = OID; + +},{"../enums":337,"../util":376}],375:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = S2K; var _enums = _dereq_('../enums.js'); @@ -20726,8 +46557,38 @@ function S2K() { /** Eight bytes of salt in a binary string. * @type {String} */ - this.salt = _crypto2.default.random.getRandomBytes(8); -} + this.salt = null; +} // GPG4Browsers - An OpenPGP implementation in javascript +// Copyright (C) 2011 Recurity Labs GmbH +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 3.0 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +/** + * Implementation of the String-to-key specifier + * + * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: + * String-to-key (S2K) specifiers are used to convert passphrase strings + * into symmetric-key encryption/decryption keys. They are used in two + * places, currently: to encrypt the secret part of private keys in the + * private keyring, and to convert passphrases to encryption keys for + * symmetrically encrypted messages. + * @requires crypto + * @requires enums + * @requires util + * @module type/s2k + */ S2K.prototype.get_count = function () { // Exponent bias, defined in RFC4880 @@ -20739,7 +46600,7 @@ S2K.prototype.get_count = function () { /** * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). * @param {String} input Payload of string-to-key specifier - * @return {Integer} Actual length of the object + * @returns {Integer} Actual length of the object */ S2K.prototype.read = function (bytes) { var i = 0; @@ -20764,7 +46625,7 @@ S2K.prototype.read = function (bytes) { break; case 'gnu': - if (_util2.default.Uint8Array2str(bytes.subarray(i, 3)) === "GNU") { + if (_util2.default.Uint8Array_to_str(bytes.subarray(i, 3)) === "GNU") { i += 3; // GNU var gnuExtType = 1000 + bytes[i++]; if (gnuExtType === 1001) { @@ -20787,10 +46648,9 @@ S2K.prototype.read = function (bytes) { /** * Serializes s2k information - * @return {Uint8Array} binary representation of s2k + * @returns {Uint8Array} binary representation of s2k */ S2K.prototype.write = function () { - var arr = [new Uint8Array([_enums2.default.write(_enums2.default.s2k, this.type), _enums2.default.write(_enums2.default.hash, this.algorithm)])]; switch (this.type) { @@ -20816,11 +46676,11 @@ S2K.prototype.write = function () { * Produces a key using the specified passphrase and the defined * hashAlgorithm * @param {String} passphrase Passphrase containing user input - * @return {Uint8Array} Produced key with a length corresponding to + * @returns {Uint8Array} Produced key with a length corresponding to * hashAlgorithm hash length */ S2K.prototype.produce_key = function (passphrase, numBytes) { - passphrase = _util2.default.str2Uint8Array(_util2.default.encode_utf8(passphrase)); + passphrase = _util2.default.str_to_Uint8Array(_util2.default.encode_utf8(passphrase)); function round(prefix, s2k) { var algorithm = _enums2.default.write(_enums2.default.hash, s2k.algorithm); @@ -20833,22 +46693,19 @@ S2K.prototype.produce_key = function (passphrase, numBytes) { return _crypto2.default.hash.digest(algorithm, _util2.default.concatUint8Array([prefix, s2k.salt, passphrase])); case 'iterated': - var isp = [], - count = s2k.get_count(), - data = _util2.default.concatUint8Array([s2k.salt, passphrase]); + { + var count = s2k.get_count(); + var data = _util2.default.concatUint8Array([s2k.salt, passphrase]); + var isp = new Array(Math.ceil(count / data.length)); - while (isp.length * data.length < count) { - isp.push(data); + isp = _util2.default.concatUint8Array(isp.fill(data)); + + if (isp.length > count) { + isp = isp.subarray(0, count); + } + + return _crypto2.default.hash.digest(algorithm, _util2.default.concatUint8Array([prefix, isp])); } - - isp = _util2.default.concatUint8Array(isp); - - if (isp.length > count) { - isp = isp.subarray(0, count); - } - - return _crypto2.default.hash.digest(algorithm, _util2.default.concatUint8Array([prefix, isp])); - case 'gnu': throw new Error("GNU s2k type not supported."); @@ -20857,15 +46714,15 @@ S2K.prototype.produce_key = function (passphrase, numBytes) { } } - var arr = [], - rlength = 0, - prefix = new Uint8Array(numBytes); + var arr = []; + var rlength = 0; + var prefix = new Uint8Array(numBytes); - for (var i = 0; i < numBytes; i++) { - prefix[i] = 0; + for (var _i = 0; _i < numBytes; _i++) { + prefix[_i] = 0; } - i = 0; + var i = 0; while (rlength < numBytes) { var result = round(prefix.subarray(0, i), this); arr.push(result); @@ -20885,7 +46742,25 @@ S2K.fromClone = function (clone) { return s2k; }; -},{"../crypto":24,"../enums.js":35,"../util.js":70}],70:[function(_dereq_,module,exports){ +exports.default = S2K; + +},{"../crypto":319,"../enums.js":337,"../util.js":376}],376:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _config = _dereq_('./config'); + +var _config2 = _interopRequireDefault(_config); + +var _base = _dereq_('./encoding/base64'); + +var _base2 = _interopRequireDefault(_base); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -20906,22 +46781,11 @@ S2K.fromClone = function (clone) { /** * This object contains utility functions * @requires config + * @requires encoding/base64 * @module util */ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _config = _dereq_('./config'); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = { +var util = { isString: function isString(data) { return typeof data === 'string' || String.prototype.isPrototypeOf(data); @@ -20935,32 +46799,16 @@ exports.default = { return Uint8Array.prototype.isPrototypeOf(data); }, - isEmailAddress: function isEmailAddress(data) { - if (!this.isString(data)) { - return false; - } - var 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,}))$/; - return re.test(data); - }, - - isUserId: function isUserId(data) { - if (!this.isString(data)) { - return false; - } - return (/$/.test(data) - ); - }, - /** * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage * @param {Object} obj the options object to be passed to the web worker - * @return {Array} an array of binary data to be passed + * @returns {Array} an array of binary data to be passed */ getTransferables: function getTransferables(obj) { if (_config2.default.zero_copy && Object.prototype.isPrototypeOf(obj)) { var transferables = []; - this.collectBuffers(obj, transferables); + util.collectBuffers(obj, transferables); return transferables.length ? transferables : undefined; } }, @@ -20969,14 +46817,14 @@ exports.default = { if (!obj) { return; } - if (this.isUint8Array(obj) && collection.indexOf(obj.buffer) === -1) { + if (util.isUint8Array(obj) && collection.indexOf(obj.buffer) === -1) { collection.push(obj.buffer); return; } if (Object.prototype.isPrototypeOf(obj)) { for (var key in obj) { // recursively search all children - this.collectBuffers(obj[key], collection); + util.collectBuffers(obj[key], collection); } } }, @@ -20999,51 +46847,36 @@ exports.default = { }, readDate: function readDate(bytes) { - var n = this.readNumber(bytes); - var d = new Date(); - d.setTime(n * 1000); + var n = util.readNumber(bytes); + var d = new Date(n * 1000); return d; }, writeDate: function writeDate(time) { - var numeric = Math.round(time.getTime() / 1000); + var numeric = Math.floor(time.getTime() / 1000); - return this.writeNumber(numeric, 4); + return util.writeNumber(numeric, 4); }, - hexdump: function hexdump(str) { - var r = []; - var e = str.length; - var c = 0; - var h; - var i = 0; - while (c < e) { - h = str.charCodeAt(c++).toString(16); - while (h.length < 2) { - h = "0" + h; - } - r.push(" " + h); - i++; - if (i % 32 === 0) { - r.push("\n "); - } - } - return r.join(''); + normalizeDate: function normalizeDate() { + var time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Date.now(); + + return time === null ? time : new Date(Math.floor(+time / 1000) * 1000); }, /** - * Create hexstring from a binary + * Create hex string from a binary * @param {String} str String to convert - * @return {String} String containing the hexadecimal values + * @returns {String} String containing the hexadecimal values */ - hexstrdump: function hexstrdump(str) { + str_to_hex: function str_to_hex(str) { if (str === null) { return ""; } var r = []; var e = str.length; var c = 0; - var h; + var h = void 0; while (c < e) { h = str.charCodeAt(c++).toString(16); while (h.length < 2) { @@ -21057,9 +46890,9 @@ exports.default = { /** * Create binary string from a hex encoded string * @param {String} str Hex string to convert - * @return {String} String containing the binary values + * @returns {String} */ - hex2bin: function hex2bin(hex) { + hex_to_str: function hex_to_str(hex) { var str = ''; for (var i = 0; i < hex.length; i += 2) { str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); @@ -21068,17 +46901,67 @@ exports.default = { }, /** - * Creating a hex string from an binary array of integers (0..255) - * @param {String} str Array of bytes to convert - * @return {String} Hexadecimal representation of the array + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * Note: the output is **not** an MPI object. + * @see {@link module:type/mpi/MPI.fromUint8Array} + * @see {@link module:type/mpi/MPI.toUint8Array} + * @param {Uint8Array} bin An array of 8-bit integers to convert + * @returns {Uint8Array} MPI-formatted Uint8Array */ - hexidump: function hexidump(str) { + Uint8Array_to_MPI: function Uint8Array_to_MPI(bin) { + var size = (bin.length - 1) * 8 + util.nbits(bin[0]); + var prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]); + return util.concatUint8Array([prefix, bin]); + }, + + /** + * Convert a Base-64 encoded string an array of 8-bit integer + * + * Note: accepts both Radix-64 and URL-safe strings + * @param {String} base64 Base-64 encoded string to convert + * @returns {Uint8Array} An array of 8-bit integers + */ + b64_to_Uint8Array: function b64_to_Uint8Array(base64) { + // atob(base64.replace(/\-/g, '+').replace(/_/g, '/')); + return _base2.default.decode(base64.replace(/\-/g, '+').replace(/_/g, '/')); + }, + + /** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param {Uint8Array} bytes An array of 8-bit integers to convert + * @param {bool} url If true, output is URL-safe + * @returns {String} Base-64 encoded string + */ + Uint8Array_to_b64: function Uint8Array_to_b64(bytes, url) { + // btoa(util.Uint8Array_to_str(bytes)).replace(/\+/g, '-').replace(/\//g, '_'); + return _base2.default.encode(bytes, url).replace('\n', ''); + }, + + /** + * Convert a hex string to an array of 8-bit integers + * @param {String} hex A hex string to convert + * @returns {Uint8Array} An array of 8-bit integers + */ + hex_to_Uint8Array: function hex_to_Uint8Array(hex) { + var result = new Uint8Array(hex.length >> 1); + for (var k = 0; k < hex.length >> 1; k++) { + result[k] = parseInt(hex.substr(k << 1, 2), 16); + } + return result; + }, + + /** + * Convert an array of 8-bit integers to a hex string + * @param {Uint8Array} bytes Array of 8-bit integers to convert + * @returns {String} Hexadecimal representation of the array + */ + Uint8Array_to_hex: function Uint8Array_to_hex(bytes) { var r = []; - var e = str.length; + var e = bytes.length; var c = 0; - var h; + var h = void 0; while (c < e) { - h = str[c++].toString(16); + h = bytes[c++].toString(16); while (h.length < 2) { h = "0" + h; } @@ -21087,10 +46970,44 @@ exports.default = { return r.join(''); }, + /** + * Convert a string to an array of 8-bit integers + * @param {String} str String to convert + * @returns {Uint8Array} An array of 8-bit integers + */ + str_to_Uint8Array: function str_to_Uint8Array(str) { + if (!util.isString(str)) { + throw new Error('str_to_Uint8Array: Data must be in the form of a string'); + } + + var result = new Uint8Array(str.length); + for (var i = 0; i < str.length; i++) { + result[i] = str.charCodeAt(i); + } + return result; + }, + + /** + * Convert an array of 8-bit integers to a string + * @param {Uint8Array} bytes An array of 8-bit integers to convert + * @returns {String} String representation of the array + */ + Uint8Array_to_str: function Uint8Array_to_str(bytes) { + bytes = new Uint8Array(bytes); + var result = []; + var bs = 1 << 14; + var j = bytes.length; + + for (var i = 0; i < j; i += bs) { + result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j))); + } + return result.join(''); + }, + /** * Convert a native javascript string to a string of utf8 bytes * @param {String} str The string to convert - * @return {String} A valid squence of utf8 bytes + * @returns {String} A valid squence of utf8 bytes */ encode_utf8: function encode_utf8(str) { return unescape(encodeURIComponent(str)); @@ -21099,7 +47016,7 @@ exports.default = { /** * Convert a string of utf8 bytes to a native javascript string * @param {String} utf8 A valid squence of utf8 bytes - * @return {String} A native javascript string + * @returns {String} A native javascript string */ decode_utf8: function decode_utf8(utf8) { if (typeof utf8 !== 'string') { @@ -21112,86 +47029,20 @@ exports.default = { } }, - /** - * Convert an array of integers(0.255) to a string - * @param {Array} bin An array of (binary) integers to convert - * @return {String} The string representation of the array - */ - bin2str: function bin2str(bin) { - var result = []; - for (var i = 0; i < bin.length; i++) { - result[i] = String.fromCharCode(bin[i]); - } - return result.join(''); - }, - - /** - * Convert a string to an array of integers(0.255) - * @param {String} str String to convert - * @return {Array} An array of (binary) integers - */ - str2bin: function str2bin(str) { - var result = []; - for (var i = 0; i < str.length; i++) { - result[i] = str.charCodeAt(i); - } - return result; - }, - - /** - * Convert a string to a Uint8Array - * @param {String} str String to convert - * @return {Uint8Array} The array of (binary) integers - */ - str2Uint8Array: function str2Uint8Array(str) { - if (typeof str !== 'string' && !String.prototype.isPrototypeOf(str)) { - throw new Error('str2Uint8Array: Data must be in the form of a string'); - } - - var result = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - result[i] = str.charCodeAt(i); - } - return result; - }, - - /** - * Convert a Uint8Array to a string. This currently functions - * the same as bin2str. - * @function module:util.Uint8Array2str - * @param {Uint8Array} bin An array of (binary) integers to convert - * @return {String} String representation of the array - */ - Uint8Array2str: function Uint8Array2str(bin) { - if (!Uint8Array.prototype.isPrototypeOf(bin)) { - throw new Error('Uint8Array2str: Data must be in the form of a Uint8Array'); - } - - var result = [], - bs = 16384, - j = bin.length; - - for (var i = 0; i < j; i += bs) { - result.push(String.fromCharCode.apply(String, bin.subarray(i, i + bs < j ? i + bs : j))); - } - return result.join(''); - }, - /** * Concat Uint8arrays - * @function module:util.concatUint8Array * @param {Array} Array of Uint8Arrays to concatenate - * @return {Uint8array} Concatenated array + * @returns {Uint8array} Concatenated array */ concatUint8Array: function concatUint8Array(arrays) { var totalLength = 0; - arrays.forEach(function (element) { - if (!Uint8Array.prototype.isPrototypeOf(element)) { + for (var i = 0; i < arrays.length; i++) { + if (!util.isUint8Array(arrays[i])) { throw new Error('concatUint8Array: Data must be in the form of a Uint8Array'); } - totalLength += element.length; - }); + totalLength += arrays[i].length; + } var result = new Uint8Array(totalLength); var pos = 0; @@ -21205,12 +47056,11 @@ exports.default = { /** * Deep copy Uint8Array - * @function module:util.copyUint8Array * @param {Uint8Array} Array to copy - * @return {Uint8Array} new Uint8Array + * @returns {Uint8Array} new Uint8Array */ copyUint8Array: function copyUint8Array(array) { - if (!Uint8Array.prototype.isPrototypeOf(array)) { + if (!util.isUint8Array(array)) { throw new Error('Data must be in the form of a Uint8Array'); } @@ -21221,13 +47071,12 @@ exports.default = { /** * Check Uint8Array equality - * @function module:util.equalsUint8Array * @param {Uint8Array} first array * @param {Uint8Array} second array - * @return {Boolean} equality + * @returns {Boolean} equality */ equalsUint8Array: function equalsUint8Array(array1, array2) { - if (!Uint8Array.prototype.isPrototypeOf(array1) || !Uint8Array.prototype.isPrototypeOf(array2)) { + if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) { throw new Error('Data must be in the form of a Uint8Array'); } @@ -21247,7 +47096,7 @@ exports.default = { * Calculates a 16bit sum of a Uint8Array by adding each character * codes modulus 65535 * @param {Uint8Array} Uint8Array to create a sum of - * @return {Integer} An integer containing the sum of all character + * @returns {Integer} An integer containing the sum of all character * codes % 65535 */ calc_checksum: function calc_checksum(text) { @@ -21279,16 +47128,17 @@ exports.default = { * Helper function to print a debug message. Debug * messages are only printed if * @link module:config/config.debug is set to true. - * Different than print_debug because will call hexstrdump iff necessary. + * Different than print_debug because will call str_to_hex iff necessary. * @param {String} str String of the debug message */ print_debug_hexstr_dump: function print_debug_hexstr_dump(str, strToHex) { if (_config2.default.debug) { - str = str + this.hexstrdump(strToHex); + str += util.str_to_hex(strToHex); console.log(str); } }, + // TODO rewrite getLeftNBits to work with Uint8Arrays getLeftNBits: function getLeftNBits(string, bitcount) { var rest = bitcount % 8; if (rest === 0) { @@ -21296,7 +47146,38 @@ exports.default = { } var bytes = (bitcount - rest) / 8 + 1; var result = string.substring(0, bytes); - return this.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF); + return util.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF); + }, + + // returns bit length of the integer x + nbits: function nbits(x) { + var r = 1; + var t = x >>> 16; + if (t !== 0) { + x = t; + r += 16; + } + t = x >> 8; + if (t !== 0) { + x = t; + r += 8; + } + t = x >> 4; + if (t !== 0) { + x = t; + r += 4; + } + t = x >> 2; + if (t !== 0) { + x = t; + r += 2; + } + t = x >> 1; + if (t !== 0) { + x = t; + r += 1; + } + return r; }, /** @@ -21304,10 +47185,10 @@ exports.default = { * @param {String} value The string to shift * @param {Integer} bitcount Amount of bits to shift (MUST be smaller * than 9) - * @return {String} Resulting string. + * @returns {String} Resulting string. */ shiftRight: function shiftRight(value, bitcount) { - var temp = this.str2bin(value); + var temp = util.str_to_Uint8Array(value); if (bitcount % 8 !== 0) { for (var i = temp.length - 1; i >= 0; i--) { temp[i] >>= bitcount % 8; @@ -21318,38 +47199,14 @@ exports.default = { } else { return value; } - return this.bin2str(temp); - }, - - /** - * Return the algorithm type as string - * @return {String} String representing the message type - */ - get_hashAlgorithmString: function get_hashAlgorithmString(algo) { - switch (algo) { - case 1: - return "MD5"; - case 2: - return "SHA1"; - case 3: - return "RIPEMD160"; - case 8: - return "SHA256"; - case 9: - return "SHA384"; - case 10: - return "SHA512"; - case 11: - return "SHA224"; - } - return "unknown"; + return util.Uint8Array_to_str(temp); }, /** * Get native Web Cryptography api, only the current version of the spec. * The default configuration is to use the api when available. But it can * be deactivated with config.use_native - * @return {Object} The SubtleCrypto api or 'undefined' + * @returns {Object} The SubtleCrypto api or 'undefined' */ getWebCrypto: function getWebCrypto() { if (!_config2.default.use_native) { @@ -21364,7 +47221,7 @@ exports.default = { * implementations of the spec e.g IE11 and Safari 8/9. The default * configuration is to use the api when available. But it can be deactivated * with config.use_native - * @return {Object} The SubtleCrypto api or 'undefined' + * @returns {Object} The SubtleCrypto api or 'undefined' */ getWebCryptoAll: function getWebCryptoAll() { if (!_config2.default.use_native) { @@ -21381,40 +47238,6 @@ exports.default = { } }, - /** - * Wraps a generic synchronous function in an ES6 Promise. - * @param {Function} fn The function to be wrapped - * @return {Function} The function wrapped in a Promise - */ - promisify: function promisify(fn) { - return function () { - var args = arguments; - return new Promise(function (resolve) { - var result = fn.apply(null, args); - resolve(result); - }); - }; - }, - - /** - * Converts an IE11 web crypro api result to a promise. - * This is required since IE11 implements an old version of the - * Web Crypto specification that does not use promises. - * @param {Object} cryptoOp The return value of an IE11 web cryptro api call - * @param {String} errmsg An error message for a specific operation - * @return {Promise} The resulting Promise - */ - promisifyIE11Op: function promisifyIE11Op(cryptoOp, errmsg) { - return new Promise(function (resolve, reject) { - cryptoOp.onerror = function () { - reject(new Error(errmsg)); - }; - cryptoOp.oncomplete = function (e) { - resolve(e.target.result); - }; - }); - }, - /** * Detect Node.js runtime. */ @@ -21425,10 +47248,10 @@ exports.default = { /** * Get native Node.js crypto api. The default configuration is to use * the api when available. But it can also be deactivated with config.use_native - * @return {Object} The crypto module or 'undefined' + * @returns {Object} The crypto module or 'undefined' */ getNodeCrypto: function getNodeCrypto() { - if (!this.detectNode() || !_config2.default.use_native) { + if (!util.detectNode() || !_config2.default.use_native) { return; } @@ -21438,19 +47261,117 @@ exports.default = { /** * Get native Node.js Buffer constructor. This should be used since * Buffer is not available under browserify. - * @return {Function} The Buffer constructor or 'undefined' + * @returns {Function} The Buffer constructor or 'undefined' */ getNodeBuffer: function getNodeBuffer() { - if (!this.detectNode()) { + if (!util.detectNode()) { return; } - return _dereq_('buffer').Buffer; - } + // This "hack" allows us to access the native node buffer module. + // otherwise, it gets replaced with the browserified version + // eslint-disable-next-line no-useless-concat, import/no-dynamic-require + return _dereq_('buf' + 'fer').Buffer; + }, + getNodeZlib: function getNodeZlib() { + if (!util.detectNode() || !_config2.default.use_native) { + return; + } + + return _dereq_('zlib'); + }, + + isEmailAddress: function isEmailAddress(data) { + if (!util.isString(data)) { + return false; + } + var 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]+)))$/; + return re.test(data); + }, + + isUserId: function isUserId(data) { + if (!util.isString(data)) { + return false; + } + return (/$/.test(data) + ); + } }; -},{"./config":10,"buffer":"buffer","crypto":"crypto"}],71:[function(_dereq_,module,exports){ +exports.default = util; + +},{"./config":306,"./encoding/base64":336,"crypto":"crypto","zlib":"zlib"}],377:[function(_dereq_,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _promise = _dereq_('babel-runtime/core-js/promise'); + +var _promise2 = _interopRequireDefault(_promise); + +var _regenerator = _dereq_('babel-runtime/regenerator'); + +var _regenerator2 = _interopRequireDefault(_regenerator); + +var _asyncToGenerator2 = _dereq_('babel-runtime/helpers/asyncToGenerator'); + +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); + +var _util = _dereq_('../util.js'); + +var _util2 = _interopRequireDefault(_util); + +var _crypto = _dereq_('../crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +var _packet = _dereq_('../packet'); + +var _packet2 = _interopRequireDefault(_packet); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Message handling + */ +function handleMessage(workerId) { + return function (event) { + var msg = event.data; + switch (msg.event) { + case 'method-return': + if (msg.err) { + // fail + var err = new Error(msg.err); + // add worker stack + err.workerStack = msg.stack; + this.tasks[msg.id].reject(err); + } else { + // success + this.tasks[msg.id].resolve(msg.data); + } + delete this.tasks[msg.id]; + this.workers[workerId].requests--; + break; + case 'request-seed': + this.seedRandom(workerId, msg.amount); + break; + default: + throw new Error('Unknown Worker Event.'); + } + }; +} + +/** + * Initializes a new proxy and loads the web worker + * @constructor + * @param {String} path The path to the worker or 'openpgp.worker.js' by default + * @param {Number} n number of workers to initialize if path given + * @param {Object} config config The worker configuration + * @param {Array} worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' + */ // GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // @@ -21468,57 +47389,40 @@ exports.default = { // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = AsyncProxy; - -var _util = _dereq_('../util.js'); - -var _util2 = _interopRequireDefault(_util); - -var _crypto = _dereq_('../crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -var _packet = _dereq_('../packet'); - -var _packet2 = _interopRequireDefault(_packet); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var INITIAL_RANDOM_SEED = 50000, - // random bytes seeded to worker -RANDOM_SEED_REQUEST = 20000; // random bytes seeded after worker request - -/** - * Initializes a new proxy and loads the web worker - * @constructor - * @param {String} path The path to the worker or 'openpgp.worker.js' by default - * @param {Object} config config The worker configuration - * @param {Object} worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' - * @return {Promise} - */ function AsyncProxy() { + var _this = this; + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$path = _ref.path, path = _ref$path === undefined ? 'openpgp.worker.js' : _ref$path, - worker = _ref.worker, + _ref$n = _ref.n, + n = _ref$n === undefined ? 1 : _ref$n, + _ref$workers = _ref.workers, + workers = _ref$workers === undefined ? [] : _ref$workers, config = _ref.config; - this.worker = worker || new Worker(path); - this.worker.onmessage = this.onMessage.bind(this); - this.worker.onerror = function (e) { - throw new Error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')'); - }; - this.seedRandom(INITIAL_RANDOM_SEED); - - if (config) { - this.worker.postMessage({ event: 'configure', config: config }); + if (workers.length) { + this.workers = workers; + } else { + this.workers = []; + while (this.workers.length < n) { + this.workers.push(new Worker(path)); + } } + var workerId = 0; + this.workers.forEach(function (worker) { + worker.requests = 0; + worker.onmessage = handleMessage(workerId++).bind(_this); + worker.onerror = function (e) { + throw new Error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')'); + }; + + if (config) { + worker.postMessage({ event: 'configure', config: config }); + } + }); + // Cannot rely on task order being maintained, use object keyed by request ID to track tasks this.tasks = {}; this.currentID = 0; @@ -21526,90 +47430,87 @@ function AsyncProxy() { /** * Get new request ID - * @return {integer} New unique request ID + * @returns {integer} New unique request ID */ AsyncProxy.prototype.getID = function () { return this.currentID++; }; -/** - * Message handling - */ -AsyncProxy.prototype.onMessage = function (event) { - var msg = event.data; - switch (msg.event) { - case 'method-return': - if (msg.err) { - // fail - var err = new Error(msg.err); - // add worker stack - err.workerStack = msg.stack; - this.tasks[msg.id].reject(err); - } else { - // success - this.tasks[msg.id].resolve(msg.data); - } - delete this.tasks[msg.id]; - break; - case 'request-seed': - this.seedRandom(RANDOM_SEED_REQUEST); - break; - default: - throw new Error('Unknown Worker Event.'); - } -}; - /** * Send message to worker with random data * @param {Integer} size Number of bytes to send */ -AsyncProxy.prototype.seedRandom = function (size) { - var buf = this.getRandomBuffer(size); - this.worker.postMessage({ event: 'seed-random', buf: buf }, _util2.default.getTransferables.call(_util2.default, buf)); -}; +AsyncProxy.prototype.seedRandom = function () { + var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(workerId, size) { + var buf; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _crypto2.default.random.getRandomBytes(size); + + case 2: + buf = _context.sent; + + this.workers[workerId].postMessage({ event: 'seed-random', buf: buf }, _util2.default.getTransferables(buf)); + + case 4: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x2, _x3) { + return _ref2.apply(this, arguments); + }; +}(); /** - * Get Uint8Array with random numbers - * @param {Integer} size Length of buffer - * @return {Uint8Array} - */ -AsyncProxy.prototype.getRandomBuffer = function (size) { - if (!size) { - return null; - } - var buf = new Uint8Array(size); - _crypto2.default.random.getRandomValues(buf); - return buf; -}; - -/** - * Terminates the worker + * Terminates the workers */ AsyncProxy.prototype.terminate = function () { - this.worker.terminate(); + this.workers.forEach(function (worker) { + worker.terminate(); + }); }; /** * Generic proxy function that handles all commands from the public api. * @param {String} method the public api function to be delegated to the worker thread * @param {Object} options the api function's options - * @return {Promise} see the corresponding public api functions for their return types + * @returns {Promise} see the corresponding public api functions for their return types */ AsyncProxy.prototype.delegate = function (method, options) { - var _this = this; + var _this2 = this; var id = this.getID(); + var requests = this.workers.map(function (worker) { + return worker.requests; + }); + var minRequests = Math.min(requests); + var workerId = 0; + for (; workerId < this.workers.length; workerId++) { + if (this.workers[workerId].requests === minRequests) { + break; + } + } - return new Promise(function (_resolve, reject) { + return new _promise2.default(function (_resolve, reject) { // clone packets (for web worker structured cloning algorithm) - _this.worker.postMessage({ id: id, event: method, options: _packet2.default.clone.clonePackets(options) }, _util2.default.getTransferables.call(_util2.default, options)); + _this2.workers[workerId].postMessage({ id: id, event: method, options: _packet2.default.clone.clonePackets(options) }, _util2.default.getTransferables(options)); + _this2.workers[workerId].requests++; // remember to handle parsing cloned packets from worker - _this.tasks[id] = { resolve: function resolve(data) { + _this2.tasks[id] = { resolve: function resolve(data) { return _resolve(_packet2.default.clone.parseClonedPackets(data, method)); }, reject: reject }; }); }; -},{"../crypto":24,"../packet":47,"../util.js":70}]},{},[37])(37) -}); +exports.default = AsyncProxy; + +},{"../crypto":319,"../packet":349,"../util.js":376,"babel-runtime/core-js/promise":25,"babel-runtime/helpers/asyncToGenerator":28,"babel-runtime/regenerator":35}]},{},[339])(339) +}); \ No newline at end of file diff --git a/dist/openpgp.min.js b/dist/openpgp.min.js index c11b4f17..d28d5963 100644 --- a/dist/openpgp.min.js +++ b/dist/openpgp.min.js @@ -1,2 +1,2 @@ -/*! OpenPGP.js v2.6.2 - 2018-01-21 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).openpgp=e()}}(function(){return function e(t,r,n){function i(a,o){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!o&&u)return u(a,!0);if(s)return s(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var h=r[a]={exports:{}};t[a][0].call(h.exports,function(e){var r=t[a][1][e];return i(r||e)},h,h.exports,e,t,r,n)}return r[a].exports}for(var s="function"==typeof require&&require,a=0;a=r)throw new Error("Malformed string, low surrogate expected at position "+i);a=(55296^a)<<10|65536|56320^e.charCodeAt(i)}else if(!t&&a>>>8)throw new Error("Wide characters are not allowed.");!t||a<=127?n[s++]=a:a<=2047?(n[s++]=192|a>>6,n[s++]=128|63&a):a<=65535?(n[s++]=224|a>>12,n[s++]=128|a>>6&63,n[s++]=128|63&a):(n[s++]=240|a>>18,n[s++]=128|a>>12&63,n[s++]=128|a>>6&63,n[s++]=128|63&a)}return n.subarray(0,s)}function o(e){return btoa(function(e,t){t=!!t;for(var r=e.length,n=new Array(r),i=0,s=0;i=192&&a<224&&i+1=224&&a<240&&i+2=240&&a<248&&i+3>10,n[s++]=56320|1023&o)}}for(var u="",i=0;i>2,r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12),t>16?r.getUint32(16):0,t>16?r.getUint32(20):0,t>24?r.getUint32(24):0,t>24?r.getUint32(28):0),this.key=e}else if(!this.key)throw new Error("key is required")}.call(this,e.key),this.hasOwnProperty("iv")&&y.call(this,e.iv),this.hasOwnProperty("padding")&&function(e){this.padding=void 0===e||!!e}.call(this,e.padding),this}function m(e){if(f(e)&&(e=a(e)),h(e)&&(e=new Uint8Array(e)),!l(e))throw new TypeError("data isn't of expected type");for(var t=this.asm,r=this.heap,n=D.ENC[this.mode],i=D.HEAP_DATA,s=this.pos,o=this.len,u=0,c=e.length||0,p=0,y=o+c&-16,g=0,m=new Uint8Array(y);c>0;)o+=g=d(r,s+o,e,u,c),u+=g,c-=g,(g=t.cipher(n,i+s,o))&&m.set(r.subarray(s,s+g),p),p+=g,g0;)o+=m=d(r,s+o,e,u,c),u+=m,c-=m,(m=t.cipher(n,i+s,o-(c?0:g)))&&v.set(r.subarray(s,s+m),p),p+=m,m0){if(h%16){if(this.hasOwnProperty("padding"))throw new i("data length must be a multiple of the block size");h+=16-h%16}if(n.cipher(o,u+f,h),this.hasOwnProperty("padding")&&this.padding){var c=a[f+l-1];if(c<1||c>16||c>l)throw new s("bad padding");for(var d=0,p=c;p>1;p--)d|=c^a[f+l-p];if(d)throw new s("bad padding");l-=c}}var y=new Uint8Array(r+l);return r>0&&y.set(t),l>0&&y.set(a.subarray(f,f+l),r),this.result=y,this.pos=0,this.len=0,this}function k(e){this.iv=null,p.call(this,e),this.mode="CFB"}function A(e){k.call(this,e)}function _(e){k.call(this,e)}function E(e){this.nonce=null,this.counter=0,this.counterSize=0,p.call(this,e),this.mode="CTR"}function S(e){return e=e||{},g.call(this,e),function(e,t,r){if(void 0!==r){if(r<8||r>48)throw new i("illegal counter size");this.counterSize=r;var n=Math.pow(2,r)-1;this.asm.set_mask(0,0,n/4294967296|0,0|n)}else this.counterSize=r=48,this.asm.set_mask(0,0,65535,4294967295);if(void 0===e)throw new Error("nonce is required");if(h(e)||l(e))e=new Uint8Array(e);else{if(!f(e))throw new TypeError("unexpected nonce type");e=a(e)}var s=e.length;if(!s||s>16)throw new i("illegal nonce size");this.nonce=e;var o=new DataView(new ArrayBuffer(16));if(new Uint8Array(o.buffer).set(e),this.asm.set_nonce(o.getUint32(0),o.getUint32(4),o.getUint32(8),o.getUint32(12)),void 0!==t){if(!u(t))throw new TypeError("unexpected counter type");if(t<0||t>=Math.pow(2,r))throw new i("illegal counter value");this.counter=t,this.asm.set_counter(0,0,t/4294967296|0,0|t)}else this.counter=t=0}.call(this,e.nonce,e.counter,e.counterSize),this}function U(e){for(var t=this.heap,r=this.asm,n=0,i=e.length||0,s=0;i>0;){for(n+=s=d(t,0,e,n,i),i-=s;15&s;)t[s++]=0;r.mac(D.MAC.GCM,D.HEAP_DATA,s)}}function K(e){this.nonce=null,this.adata=null,this.iv=null,this.counter=1,this.tagSize=16,p.call(this,e),this.mode="GCM"}function P(e){K.call(this,e)}function j(e){K.call(this,e)}function x(e){g.call(this,e=e||{});var t=this.asm,r=this.heap;t.gcm_init();var n=e.tagSize;if(void 0!==n){if(!u(n))throw new TypeError("tagSize must be a number");if(n<4||n>16)throw new i("illegal tagSize value");this.tagSize=n}else this.tagSize=16;var s=e.nonce;if(void 0===s)throw new Error("nonce is required");if(l(s)||h(s))s=new Uint8Array(s);else{if(!f(s))throw new TypeError("unexpected nonce type");s=a(s)}this.nonce=s;var o=s.length||0,c=new Uint8Array(16);12!==o?(U.call(this,s),r[0]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=0,r[11]=o>>>29,r[12]=o>>>21&255,r[13]=o>>>13&255,r[14]=o>>>5&255,r[15]=o<<3&255,t.mac(D.MAC.GCM,D.HEAP_DATA,16),t.get_iv(D.HEAP_DATA),t.set_iv(),c.set(r.subarray(0,16))):(c.set(s),c[15]=1);var d=new DataView(c.buffer);this.gamma0=d.getUint32(12),t.set_nonce(d.getUint32(0),d.getUint32(4),d.getUint32(8),0),t.set_mask(0,0,0,4294967295);var p=e.adata;if(void 0!==p&&null!==p){if(l(p)||h(p))p=new Uint8Array(p);else{if(!f(p))throw new TypeError("unexpected adata type");p=a(p)}if(p.length>z)throw new i("illegal adata length");p.length?(this.adata=p,U.call(this,p)):this.adata=null}else this.adata=null;var m=e.counter;if(void 0!==m){if(!u(m))throw new TypeError("counter must be a number");if(m<1||m>4294967295)throw new RangeError("counter must be a positive 32-bit integer");this.counter=m,t.set_counter(0,0,0,this.gamma0+m|0)}else this.counter=1,t.set_counter(0,0,0,this.gamma0+1|0);var v=e.iv;if(void 0!==v){if(!u(m))throw new TypeError("counter must be a number");this.iv=v,y.call(this,v)}return this}function T(e){if(f(e)&&(e=a(e)),h(e)&&(e=new Uint8Array(e)),!l(e))throw new TypeError("data isn't of expected type");var t=0,r=e.length||0,n=this.asm,i=this.heap,s=this.counter,o=this.pos,u=this.len,c=0,p=u+r&-16,y=0;if((s-1<<4)+u+r>z)throw new RangeError("counter overflow");for(var g=new Uint8Array(p);r>0;)u+=y=d(i,o+u,e,t,r),t+=y,r-=y,y=n.cipher(D.ENC.CTR,D.HEAP_DATA+o,u),(y=n.mac(D.MAC.GCM,D.HEAP_DATA+o,y))&&g.set(i.subarray(o,o+y),c),s+=y>>>4,c+=y,y>>29,t[4]=f>>>21,t[5]=f>>>13&255,t[6]=f>>>5&255,t[7]=f<<3&255,t[8]=t[9]=t[10]=0,t[11]=h>>>29,t[12]=h>>>21&255,t[13]=h>>>13&255,t[14]=h>>>5&255,t[15]=h<<3&255,e.mac(D.MAC.GCM,D.HEAP_DATA,16),e.get_iv(D.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(D.ENC.CTR,D.HEAP_DATA,16),o.set(t.subarray(0,n),a),this.result=o,this.counter=1,this.pos=0,this.len=0,this}function C(e){if(f(e)&&(e=a(e)),h(e)&&(e=new Uint8Array(e)),!l(e))throw new TypeError("data isn't of expected type");var t=0,r=e.length||0,n=this.asm,i=this.heap,s=this.counter,o=this.tagSize,u=this.pos,c=this.len,p=0,y=c+r>o?c+r-o&-16:0,g=c+r-y,m=0;if((s-1<<4)+c+r>z)throw new RangeError("counter overflow");for(var v=new Uint8Array(y);r>g;)c+=m=d(i,u+c,e,t,r-g),t+=m,r-=m,m=n.mac(D.MAC.GCM,D.HEAP_DATA+u,m),(m=n.cipher(D.DEC.CTR,D.HEAP_DATA+u,m))&&v.set(i.subarray(u,u+m),p),s+=m>>>4,p+=m,u=0,c=0;return r>0&&(c+=d(i,0,e,t,r)),this.result=v,this.counter=s,this.pos=u,this.len=c,this}function I(){var e=this.asm,t=this.heap,r=this.tagSize,i=this.adata,a=this.counter,o=this.pos,u=this.len,f=u-r;if(u>>29,t[4]=d>>>21,t[5]=d>>>13&255,t[6]=d>>>5&255,t[7]=d<<3&255,t[8]=t[9]=t[10]=0,t[11]=p>>>29,t[12]=p>>>21&255,t[13]=p>>>13&255,t[14]=p>>>5&255,t[15]=p<<3&255,e.mac(D.MAC.GCM,D.HEAP_DATA,16),e.get_iv(D.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(D.ENC.CTR,D.HEAP_DATA,16);for(var y=0,c=0;c>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x428a2f98|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=t+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x71374491|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=r+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xb5c0fbcf|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=l+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xe9b5dba5|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=c+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x3956c25b|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=d+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x59f111f1|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=p+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x923f82a4|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=y+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xab1c5ed5|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=g+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xd807aa98|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=m+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x12835b01|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=v+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x243185be|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=w+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x550c7dc3|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=b+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x72be5d74|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=k+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x80deb1fe|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=A+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x9bdc06a7|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;O=_+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xc19bf174|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=O=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xe49b69c1|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=O=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+v|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xefbe4786|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;r=O=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x0fc19dc6|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;l=O=(c>>>7^c>>>18^c>>>3^c<<25^c<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+b|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x240ca1cc|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;c=O=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+c+k|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x2de92c6f|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;d=O=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x4a7484aa|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;p=O=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(c>>>17^c>>>19^c>>>10^c<<15^c<<13)+p+_|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x5cb0a9dc|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;y=O=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+y+e|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x76f988da|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=O=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x983e5152|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=O=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xa831c66d|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;v=O=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xb00327c8|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;w=O=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+c|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xbf597fc7|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=O=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+b+d|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xc6e00bf3|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;k=O=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+p|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xd5a79147|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;A=O=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+y|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x06ca6351|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;_=O=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+_+g|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x14292967|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=O=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x27b70a85|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=O=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+v|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x2e1b2138|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;r=O=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x4d2c6dfc|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;l=O=(c>>>7^c>>>18^c>>>3^c<<25^c<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+b|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x53380d13|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;c=O=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+c+k|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x650a7354|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;d=O=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x766a0abb|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;p=O=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(c>>>17^c>>>19^c>>>10^c<<15^c<<13)+p+_|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x81c2c92e|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;y=O=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+y+e|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x92722c85|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=O=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xa2bfe8a1|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=O=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xa81a664b|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;v=O=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xc24b8b70|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;w=O=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+c|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xc76c51a3|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=O=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+b+d|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xd192e819|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;k=O=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+p|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xd6990624|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;A=O=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+y|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xf40e3585|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;_=O=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+_+g|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x106aa070|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=O=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x19a4c116|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;t=O=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+t+v|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x1e376c08|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;r=O=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+w|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x2748774c|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;l=O=(c>>>7^c>>>18^c>>>3^c<<25^c<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+l+b|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x34b0bcb5|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;c=O=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+c+k|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x391c0cb3|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;d=O=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+d+A|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x4ed8aa4a|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;p=O=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(c>>>17^c>>>19^c>>>10^c<<15^c<<13)+p+_|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x5b9cca4f|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;y=O=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+y+e|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x682e6ff3|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;g=O=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+g+t|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x748f82ee|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;m=O=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x78a5636f|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;v=O=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+v+l|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x84c87814|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;w=O=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+w+c|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x8cc70208|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=O=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+b+d|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0x90befffa|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;k=O=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+k+p|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xa4506ceb|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;A=O=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+y|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xbef9a3f7|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;_=O=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+_+g|0;O=O+T+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(x^P&(j^x))+0xc67178f2|0;T=x;x=j;j=P;P=K+O|0;K=U;U=S;S=E;E=O+(S&U^K&(S^U))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;n=n+E|0;i=i+S|0;s=s+U|0;a=a+K|0;o=o+P|0;u=u+j|0;f=f+x|0;h=h+T|0}function T(e){e=e|0;x(j[e|0]<<24|j[e|1]<<16|j[e|2]<<8|j[e|3],j[e|4]<<24|j[e|5]<<16|j[e|6]<<8|j[e|7],j[e|8]<<24|j[e|9]<<16|j[e|10]<<8|j[e|11],j[e|12]<<24|j[e|13]<<16|j[e|14]<<8|j[e|15],j[e|16]<<24|j[e|17]<<16|j[e|18]<<8|j[e|19],j[e|20]<<24|j[e|21]<<16|j[e|22]<<8|j[e|23],j[e|24]<<24|j[e|25]<<16|j[e|26]<<8|j[e|27],j[e|28]<<24|j[e|29]<<16|j[e|30]<<8|j[e|31],j[e|32]<<24|j[e|33]<<16|j[e|34]<<8|j[e|35],j[e|36]<<24|j[e|37]<<16|j[e|38]<<8|j[e|39],j[e|40]<<24|j[e|41]<<16|j[e|42]<<8|j[e|43],j[e|44]<<24|j[e|45]<<16|j[e|46]<<8|j[e|47],j[e|48]<<24|j[e|49]<<16|j[e|50]<<8|j[e|51],j[e|52]<<24|j[e|53]<<16|j[e|54]<<8|j[e|55],j[e|56]<<24|j[e|57]<<16|j[e|58]<<8|j[e|59],j[e|60]<<24|j[e|61]<<16|j[e|62]<<8|j[e|63])}function O(e){e=e|0;j[e|0]=n>>>24;j[e|1]=n>>>16&255;j[e|2]=n>>>8&255;j[e|3]=n&255;j[e|4]=i>>>24;j[e|5]=i>>>16&255;j[e|6]=i>>>8&255;j[e|7]=i&255;j[e|8]=s>>>24;j[e|9]=s>>>16&255;j[e|10]=s>>>8&255;j[e|11]=s&255;j[e|12]=a>>>24;j[e|13]=a>>>16&255;j[e|14]=a>>>8&255;j[e|15]=a&255;j[e|16]=o>>>24;j[e|17]=o>>>16&255;j[e|18]=o>>>8&255;j[e|19]=o&255;j[e|20]=u>>>24;j[e|21]=u>>>16&255;j[e|22]=u>>>8&255;j[e|23]=u&255;j[e|24]=f>>>24;j[e|25]=f>>>16&255;j[e|26]=f>>>8&255;j[e|27]=f&255;j[e|28]=h>>>24;j[e|29]=h>>>16&255;j[e|30]=h>>>8&255;j[e|31]=h&255}function C(){n=0x6a09e667;i=0xbb67ae85;s=0x3c6ef372;a=0xa54ff53a;o=0x510e527f;u=0x9b05688c;f=0x1f83d9ab;h=0x5be0cd19;l=c=0}function I(e,t,r,d,p,y,g,m,v,w){e=e|0;t=t|0;r=r|0;d=d|0;p=p|0;y=y|0;g=g|0;m=m|0;v=v|0;w=w|0;n=e;i=t;s=r;a=d;o=p;u=y;f=g;h=m;l=v;c=w}function M(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){T(e);e=e+64|0;t=t-64|0;r=r+64|0}l=l+r|0;if(l>>>0>>0)c=c+1|0;return r|0}function B(e,t,r){e=e|0;t=t|0;r=r|0;var n=0,i=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){n=M(e,t)|0;if((n|0)==-1)return-1;e=e+n|0;t=t-n|0}n=n+t|0;l=l+t|0;if(l>>>0>>0)c=c+1|0;j[e|t]=0x80;if((t|0)>=56){for(i=t+1|0;(i|0)<64;i=i+1|0)j[e|i]=0x00;T(e);t=0;j[e|0]=0}for(i=t+1|0;(i|0)<59;i=i+1|0)j[e|i]=0;j[e|56]=c>>>21&255;j[e|57]=c>>>13&255;j[e|58]=c>>>5&255;j[e|59]=c<<3&255|l>>>29;j[e|60]=l>>>21&255;j[e|61]=l>>>13&255;j[e|62]=l>>>5&255;j[e|63]=l<<3&255;T(e);if(~r)O(r);return n|0}function D(){n=d;i=p;s=y;a=g;o=m;u=v;f=w;h=b;l=64;c=0}function N(){n=k;i=A;s=_;a=E;o=S;u=U;f=K;h=P;l=64;c=0}function L(e,t,r,j,T,O,I,M,B,D,N,L,R,H,F,z){e=e|0;t=t|0;r=r|0;j=j|0;T=T|0;O=O|0;I=I|0;M=M|0;B=B|0;D=D|0;N=N|0;L=L|0;R=R|0;H=H|0;F=F|0;z=z|0;C();x(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,j^0x5c5c5c5c,T^0x5c5c5c5c,O^0x5c5c5c5c,I^0x5c5c5c5c,M^0x5c5c5c5c,B^0x5c5c5c5c,D^0x5c5c5c5c,N^0x5c5c5c5c,L^0x5c5c5c5c,R^0x5c5c5c5c,H^0x5c5c5c5c,F^0x5c5c5c5c,z^0x5c5c5c5c);k=n;A=i;_=s;E=a;S=o;U=u;K=f;P=h;C();x(e^0x36363636,t^0x36363636,r^0x36363636,j^0x36363636,T^0x36363636,O^0x36363636,I^0x36363636,M^0x36363636,B^0x36363636,D^0x36363636,N^0x36363636,L^0x36363636,R^0x36363636,H^0x36363636,F^0x36363636,z^0x36363636);d=n;p=i;y=s;g=a;m=o;v=u;w=f;b=h;l=64;c=0}function R(e,t,r){e=e|0;t=t|0;r=r|0;var l=0,c=0,d=0,p=0,y=0,g=0,m=0,v=0,w=0;if(e&63)return-1;if(~r)if(r&31)return-1;w=B(e,t,-1)|0;l=n,c=i,d=s,p=a,y=o,g=u,m=f,v=h;N();x(l,c,d,p,y,g,m,v,0x80000000,0,0,0,0,0,0,768);if(~r)O(r);return w|0}function H(e,t,r,l,c){e=e|0;t=t|0;r=r|0;l=l|0;c=c|0;var d=0,p=0,y=0,g=0,m=0,v=0,w=0,b=0,k=0,A=0,_=0,E=0,S=0,U=0,K=0,P=0;if(e&63)return-1;if(~c)if(c&31)return-1;j[e+t|0]=r>>>24;j[e+t+1|0]=r>>>16&255;j[e+t+2|0]=r>>>8&255;j[e+t+3|0]=r&255;R(e,t+4|0,-1)|0;d=k=n,p=A=i,y=_=s,g=E=a,m=S=o,v=U=u,w=K=f,b=P=h;l=l-1|0;while((l|0)>0){D();x(k,A,_,E,S,U,K,P,0x80000000,0,0,0,0,0,0,768);k=n,A=i,_=s,E=a,S=o,U=u,K=f,P=h;N();x(k,A,_,E,S,U,K,P,0x80000000,0,0,0,0,0,0,768);k=n,A=i,_=s,E=a,S=o,U=u,K=f,P=h;d=d^n;p=p^i;y=y^s;g=g^a;m=m^o;v=v^u;w=w^f;b=b^h;l=l-1|0}n=d;i=p;s=y;a=g;o=m;u=v;f=w;h=b;if(~c)O(c);return 0}return{reset:C,init:I,process:M,finish:B,hmac_reset:D,hmac_init:L,hmac_finish:R,pbkdf2_generate_block:H}}(r,null,this.heap.buffer),this.BLOCK_SIZE=X,this.HASH_SIZE=W,this.reset()}function B(e){if(void 0===e)throw new SyntaxError("data required");return(null===J&&(J=new M({heapSize:1048576})),J).reset().process(e).finish().result}n.prototype=Object.create(Error.prototype,{name:{value:"IllegalStateError"}}),i.prototype=Object.create(Error.prototype,{name:{value:"IllegalArgumentError"}}),s.prototype=Object.create(Error.prototype,{name:{value:"SecurityError"}});r.Float64Array||r.Float32Array;r.IllegalStateError=n,r.IllegalArgumentError=i,r.SecurityError=s;var D=function(){"use strict";function e(e,t){var i=r[(n[e]+n[t])%255];return 0!==e&&0!==t||(i=0),i}function t(){function t(e){var t,i,s;for(i=s=function(e){var t=r[255-n[e]];return 0===e&&(t=0),t}(e),t=0;t<4;t++)s^=i=255&(i<<1|i>>>7);return s^=99}u||function(){r=[],n=[];var e,t,i=1;for(e=0;e<255;e++)r[e]=i,t=128&i,i<<=1,i&=255,128===t&&(i^=27),i^=r[e],n[r[e]]=e;r[255]=r[0],n[0]=0,u=!0}(),i=[],s=[],a=[[],[],[],[]],o=[[],[],[],[]];for(var f=0;f<256;f++){var h=t(f);i[f]=h,s[h]=f,a[0][f]=e(2,h)<<24|h<<16|h<<8|e(3,h),o[0][h]=e(14,f)<<24|e(9,f)<<16|e(13,f)<<8|e(11,f);for(var l=1;l<4;l++)a[l][f]=a[l-1][f]>>>8|a[l-1][f]<<24,o[l][h]=o[l-1][h]>>>8|o[l-1][h]<<24}}var r,n,i,s,a,o,u=!1,f=function(e,r,n){t();var u=new Uint32Array(n);u.set(i,512),u.set(s,768);for(var f=0;f<4;f++)u.set(a[f],4096+1024*f>>2),u.set(o[f],8192+1024*f>>2);var h=function(e,t,r){"use asm";var n=0,i=0,s=0,a=0,o=0,u=0,f=0,h=0,l=0,c=0,d=0,p=0,y=0,g=0,m=0,v=0,w=0,b=0,k=0,A=0,_=0;var E=new e.Uint32Array(r),S=new e.Uint8Array(r);function U(e,t,r,o,u,f,h,l){e=e|0;t=t|0;r=r|0;o=o|0;u=u|0;f=f|0;h=h|0;l=l|0;var c=0,d=0,p=0,y=0,g=0,m=0,v=0,w=0;c=r|0x400,d=r|0x800,p=r|0xc00;u=u^E[(e|0)>>2],f=f^E[(e|4)>>2],h=h^E[(e|8)>>2],l=l^E[(e|12)>>2];for(w=16;(w|0)<=o<<4;w=w+16|0){y=E[(r|u>>22&1020)>>2]^E[(c|f>>14&1020)>>2]^E[(d|h>>6&1020)>>2]^E[(p|l<<2&1020)>>2]^E[(e|w|0)>>2],g=E[(r|f>>22&1020)>>2]^E[(c|h>>14&1020)>>2]^E[(d|l>>6&1020)>>2]^E[(p|u<<2&1020)>>2]^E[(e|w|4)>>2],m=E[(r|h>>22&1020)>>2]^E[(c|l>>14&1020)>>2]^E[(d|u>>6&1020)>>2]^E[(p|f<<2&1020)>>2]^E[(e|w|8)>>2],v=E[(r|l>>22&1020)>>2]^E[(c|u>>14&1020)>>2]^E[(d|f>>6&1020)>>2]^E[(p|h<<2&1020)>>2]^E[(e|w|12)>>2];u=y,f=g,h=m,l=v}n=E[(t|u>>22&1020)>>2]<<24^E[(t|f>>14&1020)>>2]<<16^E[(t|h>>6&1020)>>2]<<8^E[(t|l<<2&1020)>>2]^E[(e|w|0)>>2],i=E[(t|f>>22&1020)>>2]<<24^E[(t|h>>14&1020)>>2]<<16^E[(t|l>>6&1020)>>2]<<8^E[(t|u<<2&1020)>>2]^E[(e|w|4)>>2],s=E[(t|h>>22&1020)>>2]<<24^E[(t|l>>14&1020)>>2]<<16^E[(t|u>>6&1020)>>2]<<8^E[(t|f<<2&1020)>>2]^E[(e|w|8)>>2],a=E[(t|l>>22&1020)>>2]<<24^E[(t|u>>14&1020)>>2]<<16^E[(t|f>>6&1020)>>2]<<8^E[(t|h<<2&1020)>>2]^E[(e|w|12)>>2]}function K(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;U(0x0000,0x0800,0x1000,_,e,t,r,n)}function P(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var s=0;U(0x0400,0x0c00,0x2000,_,e,n,r,t);s=i,i=a,a=s}function j(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;U(0x0000,0x0800,0x1000,_,o^e,u^t,f^r,h^l);o=n,u=i,f=s,h=a}function x(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;var c=0;U(0x0400,0x0c00,0x2000,_,e,l,r,t);c=i,i=a,a=c;n=n^o,i=i^u,s=s^f,a=a^h;o=e,u=t,f=r,h=l}function T(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;U(0x0000,0x0800,0x1000,_,o,u,f,h);o=n=n^e,u=i=i^t,f=s=s^r,h=a=a^l}function O(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;U(0x0000,0x0800,0x1000,_,o,u,f,h);n=n^e,i=i^t,s=s^r,a=a^l;o=e,u=t,f=r,h=l}function C(e,t,r,l){e=e|0;t=t|0;r=r|0;l=l|0;U(0x0000,0x0800,0x1000,_,o,u,f,h);o=n,u=i,f=s,h=a;n=n^e,i=i^t,s=s^r,a=a^l}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;U(0x0000,0x0800,0x1000,_,l,c,d,p);p=~v&p|v&p+1,d=~m&d|m&d+((p|0)==0),c=~g&c|g&c+((d|0)==0),l=~y&l|y&l+((c|0)==0);n=n^e,i=i^t,s=s^r,a=a^o}function M(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var i=0,s=0,a=0,l=0,c=0,d=0,p=0,y=0,g=0,m=0;e=e^o,t=t^u,r=r^f,n=n^h;i=w|0,s=b|0,a=k|0,l=A|0;for(;(g|0)<128;g=g+1|0){if(i>>>31){c=c^e,d=d^t,p=p^r,y=y^n}i=i<<1|s>>>31,s=s<<1|a>>>31,a=a<<1|l>>>31,l=l<<1;m=n&1;n=n>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(m)e=e^0xe1000000}o=c,u=d,f=p,h=y}function B(e){e=e|0;_=e}function D(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;n=e,i=t,s=r,a=o}function N(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;o=e,u=t,f=r,h=n}function L(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;l=e,c=t,d=r,p=n}function R(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;y=e,g=t,m=r,v=n}function H(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;p=~v&p|v&n,d=~m&d|m&r,c=~g&c|g&t,l=~y&l|y&e}function F(e){e=e|0;if(e&15)return-1;S[e|0]=n>>>24,S[e|1]=n>>>16&255,S[e|2]=n>>>8&255,S[e|3]=n&255,S[e|4]=i>>>24,S[e|5]=i>>>16&255,S[e|6]=i>>>8&255,S[e|7]=i&255,S[e|8]=s>>>24,S[e|9]=s>>>16&255,S[e|10]=s>>>8&255,S[e|11]=s&255,S[e|12]=a>>>24,S[e|13]=a>>>16&255,S[e|14]=a>>>8&255,S[e|15]=a&255;return 16}function z(e){e=e|0;if(e&15)return-1;S[e|0]=o>>>24,S[e|1]=o>>>16&255,S[e|2]=o>>>8&255,S[e|3]=o&255,S[e|4]=u>>>24,S[e|5]=u>>>16&255,S[e|6]=u>>>8&255,S[e|7]=u&255,S[e|8]=f>>>24,S[e|9]=f>>>16&255,S[e|10]=f>>>8&255,S[e|11]=f&255,S[e|12]=h>>>24,S[e|13]=h>>>16&255,S[e|14]=h>>>8&255,S[e|15]=h&255;return 16}function q(){K(0,0,0,0);w=n,b=i,k=s,A=a}function G(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){Z[e&7](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);S[t|0]=n>>>24,S[t|1]=n>>>16&255,S[t|2]=n>>>8&255,S[t|3]=n&255,S[t|4]=i>>>24,S[t|5]=i>>>16&255,S[t|6]=i>>>8&255,S[t|7]=i&255,S[t|8]=s>>>24,S[t|9]=s>>>16&255,S[t|10]=s>>>8&255,S[t|11]=s&255,S[t|12]=a>>>24,S[t|13]=a>>>16&255,S[t|14]=a>>>8&255,S[t|15]=a&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function V(e,t,r){e=e|0;t=t|0;r=r|0;var n=0;if(t&15)return-1;while((r|0)>=16){Y[e&1](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);n=n+16|0,t=t+16|0,r=r-16|0}return n|0}var Z=[K,P,j,x,T,O,C,I];var Y=[j,M];return{set_rounds:B,set_state:D,set_iv:N,set_nonce:L,set_mask:R,set_counter:H,get_state:F,get_iv:z,gcm_init:q,cipher:G,mac:V}}(e,r,n);return h.set_key=function(e,t,r,n,s,a,f,l,c){var d=u.subarray(0,60),p=u.subarray(256,316);d.set([t,r,n,s,a,f,l,c]);for(var y=e,g=1;y<4*e+28;y++)w=d[y-1],(y%e==0||8===e&&y%e==4)&&(w=i[w>>>24]<<24^i[w>>>16&255]<<16^i[w>>>8&255]<<8^i[255&w]),y%e==0&&(w=w<<8^w>>>24^g<<24,g=g<<1^(128&g?27:0)),d[y]=d[y-e]^w;for(var m=0;m=y-4?w:o[0][i[w>>>24]]^o[1][i[w>>>16&255]]^o[2][i[w>>>8&255]]^o[3][i[255&w]]}h.set_rounds(e+5)},h};return f.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},f.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},f.MAC={CBC:0,GCM:1},f.HEAP_DATA=16384,f}(),N=k.prototype;N.BLOCK_SIZE=16,N.reset=g,N.encrypt=v,N.decrypt=b;var L=A.prototype;L.BLOCK_SIZE=16,L.reset=g,L.process=m,L.finish=v;var R=_.prototype;R.BLOCK_SIZE=16,R.reset=g,R.process=w,R.finish=b;var H=E.prototype;H.BLOCK_SIZE=16,H.reset=S,H.encrypt=v,H.decrypt=v;var F=function(e){E.call(this,e)}.prototype;F.BLOCK_SIZE=16,F.reset=S,F.process=m,F.finish=v;var z=68719476704,q=K.prototype;q.BLOCK_SIZE=16,q.reset=x,q.encrypt=function(e){var t=T.call(this,e).result,r=O.call(this).result,n=new Uint8Array(t.length+r.length);return t.length&&n.set(t),r.length&&n.set(r,t.length),this.result=n,this},q.decrypt=function(e){var t=C.call(this,e).result,r=I.call(this).result,n=new Uint8Array(t.length+r.length);return t.length&&n.set(t),r.length&&n.set(r,t.length),this.result=n,this};var G=P.prototype;G.BLOCK_SIZE=16,G.reset=x,G.process=T,G.finish=O;var V=j.prototype;V.BLOCK_SIZE=16,V.reset=x,V.process=C,V.finish=I;var Z=new Uint8Array(1048576),Y=D(r,null,Z.buffer);e.AES_CFB=k,e.AES_CFB.encrypt=function(e,t,r){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new k({heap:Z,asm:Y,key:t,iv:r}).encrypt(e).result},e.AES_CFB.decrypt=function(e,t,r){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new k({heap:Z,asm:Y,key:t,iv:r}).decrypt(e).result},e.AES_CFB.Encrypt=A,e.AES_CFB.Decrypt=_,e.AES_GCM=K,e.AES_GCM.encrypt=function(e,t,r,n,i){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");if(void 0===r)throw new SyntaxError("nonce required");return new K({heap:Z,asm:Y,key:t,nonce:r,adata:n,tagSize:i}).encrypt(e).result},e.AES_GCM.decrypt=function(e,t,r,n,i){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");if(void 0===r)throw new SyntaxError("nonce required");return new K({heap:Z,asm:Y,key:t,nonce:r,adata:n,tagSize:i}).decrypt(e).result},e.AES_GCM.Encrypt=P,e.AES_GCM.Decrypt=j;var X=64,W=32;M.BLOCK_SIZE=X,M.HASH_SIZE=W;var $=M.prototype;$.reset=function(){return this.result=null,this.pos=0,this.len=0,this.asm.reset(),this},$.process=function(e){if(null!==this.result)throw new n("state must be reset before processing new data");if(f(e)&&(e=a(e)),h(e)&&(e=new Uint8Array(e)),!l(e))throw new TypeError("data isn't of expected type");for(var t=this.asm,r=this.heap,i=this.pos,s=this.len,o=0,u=e.length,c=0;u>0;)s+=c=d(r,i+s,e,o,u),o+=c,u-=c,i+=c=t.process(i,s),(s-=c)||(i=0);return this.pos=i,this.len=s,this},$.finish=function(){if(null!==this.result)throw new n("state must be reset before processing new data");return this.asm.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(this.heap.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this};var J=null;M.bytes=B,M.hex=function(e){return function(e){for(var t="",r=0;r1)for(var r=1;r0;e+=1);return e},o=function(e,t,r,n,i){var s,a=i%4,o=(n+a)%4,u=n-o;switch(a){case 0:e[i]=this[r+3];case 1:e[i+1-(a<<1)|0]=this[r+2];case 2:e[i+2-(a<<1)|0]=this[r+1];case 3:e[i+3-(a<<1)|0]=this[r]}if(!(n>2|0]=this[r+s]<<24|this[r+s+1]<<16|this[r+s+2]<<8|this[r+s+3];switch(o){case 3:e[i+u+1|0]=this[r+u+2];case 2:e[i+u+2|0]=this[r+u+1];case 1:e[i+u+3|0]=this[r+u]}}},u=function(e){switch(i(e)){case"string":return function(e,t,r,n,i){var s,a=i%4,o=(n+a)%4,u=n-o;switch(a){case 0:e[i]=this.charCodeAt(r+3);case 1:e[i+1-(a<<1)|0]=this.charCodeAt(r+2);case 2:e[i+2-(a<<1)|0]=this.charCodeAt(r+1);case 3:e[i+3-(a<<1)|0]=this.charCodeAt(r)}if(!(n>2]=this.charCodeAt(r+s)<<24|this.charCodeAt(r+s+1)<<16|this.charCodeAt(r+s+2)<<8|this.charCodeAt(r+s+3);switch(o){case 3:e[i+u+1|0]=this.charCodeAt(r+u+2);case 2:e[i+u+2|0]=this.charCodeAt(r+u+1);case 1:e[i+u+3|0]=this.charCodeAt(r+u)}}}.bind(e);case"array":case"buffer":return o.bind(e);case"arraybuffer":return o.bind(new Uint8Array(e));case"view":return o.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return function(e,t,r,i,s){var a,o=s%4,u=(i+o)%4,f=i-u,h=new Uint8Array(n.readAsArrayBuffer(this.slice(r,r+i)));switch(o){case 0:e[s]=h[3];case 1:e[s+1-(o<<1)|0]=h[2];case 2:e[s+2-(o<<1)|0]=h[1];case 3:e[s+3-(o<<1)|0]=h[0]}if(!(i>2|0]=h[a]<<24|h[a+1]<<16|h[a+2]<<8|h[a+3];switch(u){case 3:e[s+f+1|0]=h[f+2];case 2:e[s+f+2|0]=h[f+1];case 1:e[s+f+3|0]=h[f]}}}.bind(e)}},f=new Array(256),h=0;h<256;h++)f[h]=(h<16?"0":"")+h.toString(16);var l=function(e){for(var t=new Uint8Array(e),r=new Array(e.byteLength),n=0;n0)throw new Error("Chunk size must be a multiple of 128 bit");s.offset=0,s.maxChunkLen=e,s.padMaxChunkLen=a(e),s.heap=new ArrayBuffer(function(e){var t;if(e<=65536)return 65536;if(e<16777216)for(t=1;t>2);return function(e,t){var r=new Uint8Array(e.buffer),n=t%4,i=t-n;switch(n){case 0:r[i+3]=0;case 1:r[i+2]=0;case 2:r[i+1]=0;case 3:r[i+0]=0}for(var s=1+(t>>2);s>2]|=128<<24-(t%4<<3),e[14+(2+(t>>2)&-16)]=r/(1<<29)|0,e[15+(2+(t>>2)&-16)]=r<<3}(n,e,t),r},p=function(e,t,r,n){u(e)(s.h8,s.h32,t,r,n||0)},y=function(e,t,r,n,i){var a=r;p(e,t,r),i&&(a=d(r,n)),s.core.hash(a,s.padMaxChunkLen)},g=function(e,t){var r=new Int32Array(e,t+320,5),n=new Int32Array(5),i=new DataView(n.buffer);return i.setInt32(0,r[0],!1),i.setInt32(4,r[1],!1),i.setInt32(8,r[2],!1),i.setInt32(12,r[3],!1),i.setInt32(16,r[4],!1),n},m=this.rawDigest=function(e){var t=e.byteLength||e.length||e.size||0;c(s.heap,s.padMaxChunkLen);var r=0,n=s.maxChunkLen;for(r=0;t>r+n;r+=n)y(e,r,n,t,!1);return y(e,r,t-r,t,!0),g(s.heap,s.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return l(m(e).buffer)},this.resetState=function(){return c(s.heap,s.padMaxChunkLen),this},this.append=function(e){var t,r=0,n=e.byteLength||e.length||e.size||0,i=s.offset%s.maxChunkLen;for(s.offset+=n;r>2]|0;o=n[t+324>>2]|0;f=n[t+328>>2]|0;l=n[t+332>>2]|0;d=n[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){a=s;u=o;h=f;c=l;p=d;for(i=0;(i|0)<64;i=i+4|0){g=n[r+i>>2]|0;y=((s<<5|s>>>27)+(o&f|~o&l)|0)+((g+d|0)+1518500249|0)|0;d=l;l=f;f=o<<30|o>>>2;o=s;s=y;n[e+i>>2]=g}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){g=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;y=((s<<5|s>>>27)+(o&f|~o&l)|0)+((g+d|0)+1518500249|0)|0;d=l;l=f;f=o<<30|o>>>2;o=s;s=y;n[i>>2]=g}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){g=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;y=((s<<5|s>>>27)+(o^f^l)|0)+((g+d|0)+1859775393|0)|0;d=l;l=f;f=o<<30|o>>>2;o=s;s=y;n[i>>2]=g}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){g=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;y=((s<<5|s>>>27)+(o&f|o&l|f&l)|0)+((g+d|0)-1894007588|0)|0;d=l;l=f;f=o<<30|o>>>2;o=s;s=y;n[i>>2]=g}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){g=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;y=((s<<5|s>>>27)+(o^f^l)|0)+((g+d|0)-899497514|0)|0;d=l;l=f;f=o<<30|o>>>2;o=s;s=y;n[i>>2]=g}s=s+a|0;o=o+u|0;f=f+h|0;l=l+c|0;d=d+p|0}n[t+320>>2]=s;n[t+324>>2]=o;n[t+328>>2]=f;n[t+332>>2]=l;n[t+336>>2]=d}return{hash:i}},void 0!==t?t.exports=r:"undefined"!=typeof window&&(window.Rusha=r),"undefined"!=typeof FileReaderSync){var n=new FileReaderSync,i=function(e,t,r,n,s){var a=new self.FileReader;a.onloadend=function(){var o=a.result;t+=a.result.byteLength;try{e.append(o)}catch(e){return void s(e)}t>16&255,i[s++]=r>>24;var a;switch(f){case 1===n:a=[0,n-1,0];break;case 2===n:a=[1,n-2,0];break;case 3===n:a=[2,n-3,0];break;case 4===n:a=[3,n-4,0];break;case 6>=n:a=[4,n-5,1];break;case 8>=n:a=[5,n-7,1];break;case 12>=n:a=[6,n-9,2];break;case 16>=n:a=[7,n-13,2];break;case 24>=n:a=[8,n-17,3];break;case 32>=n:a=[9,n-25,3];break;case 48>=n:a=[10,n-33,4];break;case 64>=n:a=[11,n-49,4];break;case 96>=n:a=[12,n-65,5];break;case 128>=n:a=[13,n-97,5];break;case 192>=n:a=[14,n-129,6];break;case 256>=n:a=[15,n-193,6];break;case 384>=n:a=[16,n-257,7];break;case 512>=n:a=[17,n-385,7];break;case 768>=n:a=[18,n-513,8];break;case 1024>=n:a=[19,n-769,8];break;case 1536>=n:a=[20,n-1025,9];break;case 2048>=n:a=[21,n-1537,9];break;case 3072>=n:a=[22,n-2049,10];break;case 4096>=n:a=[23,n-3073,10];break;case 6144>=n:a=[24,n-4097,11];break;case 8192>=n:a=[25,n-6145,11];break;case 12288>=n:a=[26,n-8193,12];break;case 16384>=n:a=[27,n-12289,12];break;case 24576>=n:a=[28,n-16385,13];break;case 32768>=n:a=[29,n-24577,13];break;default:throw"invalid distance"}r=a,i[s++]=r[0],i[s++]=r[1],i[s++]=r[2];var o,u;for(o=0,u=i.length;o=s;)w[s++]=0;for(s=0;29>=s;)b[s++]=0}for(w[256]=1,n=0,i=t.length;n=i){for(d&&r(d,-1),s=0,a=i-n;ss&&t+sf&&(i=n,f=s),258===s)break}return new function(e,t){this.length=e,this.g=t}(f,t-i)}(t,n,h),d?d.length2*f[s-1]+h[s]&&(f[s]=2*f[s-1]+h[s]),d[s]=Array(f[s]),p[s]=Array(f[s]);for(i=0;ie[i]?(d[s][a]=o,p[s][a]=t,u+=2):(d[s][a]=e[i],p[s][a]=i,++i);y[s]=0,1===h[s]&&n(s)}return c}(i,i.length,t),a=0,o=r.length;a>>=1;return s}var u=void 0,f=!0,h=this,l="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array&&"undefined"!=typeof DataView;t.prototype.a=function(e,t,n){var i,s=this.buffer,a=this.index,o=this.d,u=s[a];if(n&&1>>8&255]<<16|m[e>>>16&255]<<8|m[e>>>24&255])>>32-t:m[e]>>8-t),8>t+o)u=u<>t-i-1&1,8==++o&&(o=0,s[a++]=m[u],u=0,a===s.length&&(s=r(this)));s[a]=u,this.buffer=s,this.d=o,this.index=a},t.prototype.finish=function(){var e,t=this.buffer,r=this.index;return 0c;++c){for(var p=g=c,y=7,g=g>>>1;g;g>>>=1)p<<=1,p|=1&g,--y;d[c]=(p<>>0}var m=d;n.prototype.getParent=function(e){return 2*((e-2)/4|0)},n.prototype.push=function(e,t){var r,n,i,s=this.buffer;for(r=this.length,s[this.length++]=t,s[this.length++]=e;0s[n]);)i=s[r],s[r]=s[n],s[n]=i,i=s[r+1],s[r+1]=s[n+1],s[n+1]=i,r=n;return this.length},n.prototype.pop=function(){var e,t,r,n,i,s=this.buffer;for(t=s[0],e=s[1],this.length-=2,s[0]=s[this.length],s[1]=s[this.length+1],i=0;!((n=2*i+2)>=this.length)&&(n+2s[n]&&(n+=2),s[n]>s[i]);)r=s[i],s[i]=s[n],s[n]=r,r=s[i+1],s[i+1]=s[n+1],s[n+1]=r,i=n;return{index:e,value:t,length:this.length}};var v,w=2,b=[];for(v=0;288>v;v++)switch(f){case 143>=v:b.push([v+48,8]);break;case 255>=v:b.push([v-144+400,9]);break;case 279>=v:b.push([v-256+0,7]);break;case 287>=v:b.push([v-280+192,8]);break;default:throw"invalid literal: "+v}i.prototype.h=function(){var e,r,n,i,h=this.input;switch(this.e){case 0:for(n=0,i=h.length;n>>8&255,k[A++]=255&g,k[A++]=g>>>8&255,l)k.set(c,A),A+=c.length,k=k.subarray(0,A);else{for(m=0,v=c.length;mY)for(;0Y?Y:138)>Y-3&&$=$?(te[W++]=17,te[W++]=$-3,re[17]++):(te[W++]=18,te[W++]=$-11,re[18]++),Y-=$;else if(te[W++]=ee[V],re[ee[V]]++,3>--Y)for(;0Y?Y:6)>Y-3&&$H;H++)G[H]=D[q[H]];for(O=19;4=e:return[265,e-11,1];case 14>=e:return[266,e-13,1];case 16>=e:return[267,e-15,1];case 18>=e:return[268,e-17,1];case 22>=e:return[269,e-19,2];case 26>=e:return[270,e-23,2];case 30>=e:return[271,e-27,2];case 34>=e:return[272,e-31,2];case 42>=e:return[273,e-35,3];case 50>=e:return[274,e-43,3];case 58>=e:return[275,e-51,3];case 66>=e:return[276,e-59,3];case 82>=e:return[277,e-67,4];case 98>=e:return[278,e-83,4];case 114>=e:return[279,e-99,4];case 130>=e:return[280,e-115,4];case 162>=e:return[281,e-131,5];case 194>=e:return[282,e-163,5];case 226>=e:return[283,e-195,5];case 257>=e:return[284,e-227,5];case 258===e:return[285,e-258,0];default:throw"invalid length: "+e}}var t,r,n=[];for(t=3;258>=t;t++)r=e(t),n[t]=r[2]<<24|r[1]<<16|r[0];return n}(),A=l?new Uint32Array(k):k;e("Zlib.RawDeflate",i),e("Zlib.RawDeflate.prototype.compress",i.prototype.h);var _,E,S,U,K={NONE:0,FIXED:1,DYNAMIC:w};if(Object.keys)_=Object.keys(K);else for(E in _=[],S=0,K)_[S++]=E;for(S=0,U=_.length;Sd&&(d=e[f]),e[f]>=1;for(l=n<<16|f,h=a;h=o)throw Error("input buffer is broken");n|=s[a++]<>>t,e.c=i-t,e.d=a,r}function i(e,t){for(var r,n,i=e.f,s=e.c,a=e.input,o=e.d,u=a.length,f=t[0],h=t[1];s=u);)i|=a[o++]<>>16)>s)throw Error("invalid code length: "+n);return e.f=i>>n,e.c=s-n,e.d=o,65535&r}var s=void 0,a=this,o="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array&&"undefined"!=typeof DataView,u=0,f=1;r.prototype.t=function(){for(;!this.l;){var e=n(this,3);switch(1&e&&(this.l=!0),e>>>=1){case 0:var r=this.input,a=this.d,h=this.b,l=this.a,c=r.length,p=s,y=s,g=h.length,m=s;if(this.c=this.f=0,a+1>=c)throw Error("invalid uncompressed block header: LEN");if(p=r[a++]|r[a++]<<8,a+1>=c)throw Error("invalid uncompressed block header: NLEN");if(y=r[a++]|r[a++]<<8,p===~y)throw Error("invalid uncompressed block header: length verify");if(a+p>r.length)throw Error("input buffer is broken");switch(this.i){case u:for(;l+p>h.length;){if(m=g-l,p-=m,o)h.set(r.subarray(a,a+m),l),l+=m,a+=m;else for(;m--;)h[l++]=r[a++];this.a=l,h=this.e(),l=this.a}break;case f:for(;l+p>h.length;)h=this.e({o:2});break;default:throw Error("invalid inflate mode")}if(o)h.set(r.subarray(a,a+p),l),l+=p,a+=p;else for(;p--;)h[l++]=r[a++];this.d=a,this.a=l,this.b=h;break;case 1:this.j(S,K);break;case 2:for(var v=n(this,5)+257,w=n(this,5)+1,b=n(this,4)+4,k=new(o?Uint8Array:Array)(d.length),A=s,_=s,E=s,U=s,P=s,j=s,x=s,T=s,O=s,T=0;T=h?8:255>=h?9:279>=h?7:8;var _,E,S=t(A),U=new(o?Uint8Array:Array)(30);for(_=0,E=U.length;_a)s>=h&&(this.a=s,r=this.e(),s=this.a),r[s++]=a;else for(f=y[o=a-257],0=h&&(this.a=s,r=this.e(),s=this.a);f--;)r[s]=r[s++-u];for(;8<=this.c;)this.c-=8,this.d--;this.a=s},r.prototype.s=function(e,t){var r=this.b,s=this.a;this.n=e;for(var a,o,u,f,h=r.length;256!==(a=i(this,e));)if(256>a)s>=h&&(r=this.e(),h=r.length),r[s++]=a;else for(f=y[o=a-257],0h&&(r=this.e(),h=r.length);f--;)r[s]=r[s++-u];for(;8<=this.c;)this.c-=8,this.d--;this.a=s},r.prototype.e=function(){var e,t,r=new(o?Uint8Array:Array)(this.a-32768),n=this.a-32768,i=this.b;if(o)r.set(i.subarray(32768,r.length));else for(e=0,t=r.length;ee;++e)i[e]=i[n+e];return this.a=32768,i},r.prototype.u=function(e){var t,r,n,i,s=this.input.length/this.d+1|0,a=this.input,u=this.b;return e&&("number"==typeof e.o&&(s=e.o),"number"==typeof e.q&&(s+=e.q)),2>s?(r=(a.length-this.d)/this.n[2],i=r/2*258|0,n=it&&(this.b.length=t),e=this.b),this.buffer=e},e("Zlib.RawInflate",r),e("Zlib.RawInflate.prototype.decompress",r.prototype.t);var P,j,x,T,O={ADAPTIVE:f,BLOCK:u};if(Object.keys)P=Object.keys(O);else for(j in P=[],x=0,O)P[x++]=j;for(x=0,T=P.length;xc&&(c=e[u]),e[u]>=1;for(h=n<<16|u,f=a;f>16&255,s[a++]=n>>24;var o;switch(m){case 1===i:o=[0,i-1,0];break;case 2===i:o=[1,i-2,0];break;case 3===i:o=[2,i-3,0];break;case 4===i:o=[3,i-4,0];break;case 6>=i:o=[4,i-5,1];break;case 8>=i:o=[5,i-7,1];break;case 12>=i:o=[6,i-9,2];break;case 16>=i:o=[7,i-13,2];break;case 24>=i:o=[8,i-17,3];break;case 32>=i:o=[9,i-25,3];break;case 48>=i:o=[10,i-33,4];break;case 64>=i:o=[11,i-49,4];break;case 96>=i:o=[12,i-65,5];break;case 128>=i:o=[13,i-97,5];break;case 192>=i:o=[14,i-129,6];break;case 256>=i:o=[15,i-193,6];break;case 384>=i:o=[16,i-257,7];break;case 512>=i:o=[17,i-385,7];break;case 768>=i:o=[18,i-513,8];break;case 1024>=i:o=[19,i-769,8];break;case 1536>=i:o=[20,i-1025,9];break;case 2048>=i:o=[21,i-1537,9];break;case 3072>=i:o=[22,i-2049,10];break;case 4096>=i:o=[23,i-3073,10];break;case 6144>=i:o=[24,i-4097,11];break;case 8192>=i:o=[25,i-6145,11];break;case 12288>=i:o=[26,i-8193,12];break;case 16384>=i:o=[27,i-12289,12];break;case 24576>=i:o=[28,i-16385,13];break;case 32768>=i:o=[29,i-24577,13];break;default:e("invalid distance")}n=o,s[a++]=n[0],s[a++]=n[1],s[a++]=n[2];var u,f;for(u=0,f=s.length;u=a;)b[a++]=0;for(a=0;29>=a;)k[a++]=0}for(b[256]=1,i=0,s=r.length;i=s){for(l&&n(l,-1),a=0,o=s-i;as&&t+sf&&(i=n,f=s),258===s)break}return new function(e,t){this.length=e,this.G=t}(f,t-i)}(r,i,f),l?l.length2*f[s-1]+h[s]&&(f[s]=2*f[s-1]+h[s]),c[s]=Array(f[s]),d[s]=Array(f[s]);for(i=0;ie[i]?(c[s][a]=o,d[s][a]=t,u+=2):(c[s][a]=e[i],d[s][a]=i,++i);p[s]=0,1===h[s]&&n(s)}return l}(i,i.length,t),a=0,o=r.length;a>>=1;return s}function f(t,r){switch(this.l=[],this.m=32768,this.e=this.g=this.c=this.q=0,this.input=w?new Uint8Array(t):t,this.s=!1,this.n=C,this.B=!1,!r&&(r={})||(r.index&&(this.c=r.index),r.bufferSize&&(this.m=r.bufferSize),r.bufferType&&(this.n=r.bufferType),r.resize&&(this.B=r.resize)),this.n){case O:this.b=32768,this.a=new(w?Uint8Array:Array)(32768+this.m+258);break;case C:this.b=0,this.a=new(w?Uint8Array:Array)(this.m),this.f=this.J,this.t=this.H,this.o=this.I;break;default:e(Error("invalid inflate mode"))}}function h(t,r){for(var n,i=t.g,s=t.e,a=t.input,o=t.c,u=a.length;s=u&&e(Error("input buffer is broken")),i|=a[o++]<>>r,t.e=s-r,t.c=o,n}function l(t,r){for(var n,i,s=t.g,a=t.e,o=t.input,u=t.c,f=o.length,h=r[0],l=r[1];a=f);)s|=o[u++]<>>16)>a&&e(Error("invalid code length: "+i)),t.g=s>>i,t.e=a-i,t.c=u,65535&n}function c(e){if("string"==typeof e){var t,r,n=e.split("");for(t=0,r=n.length;t>>0;e=n}for(var i,s=1,a=0,o=e.length,u=0;0>>0}function d(t,r){var n,i;switch(this.input=t,this.c=0,!r&&(r={})||(r.index&&(this.c=r.index),r.verify&&(this.M=r.verify)),n=t[this.c++],i=t[this.c++],15&n){case Q:this.method=Q;break;default:e(Error("unsupported compression method"))}0!=((n<<8)+i)%31&&e(Error("invalid fcheck flag:"+((n<<8)+i)%31)),32&i&&e(Error("fdict flag is not supported")),this.A=new f(t,{index:this.c,bufferSize:r.bufferSize,bufferType:r.bufferType,resize:r.resize})}function p(e,t){this.input=e,this.a=new(w?Uint8Array:Array)(32768),this.h=ee.k;var r,n={};!t&&(t={})||"number"!=typeof t.compressionType||(this.h=t.compressionType);for(r in t)n[r]=t[r];n.outputBuffer=this.a,this.z=new s(this.input,n)}function y(e,r){var n,i,s,a;if(Object.keys)n=Object.keys(r);else for(i in n=[],s=0,r)n[s++]=i;for(s=0,a=n.length;s>>8&255]<<16|S[e>>>16&255]<<8|S[e>>>24&255])>>32-t:S[e]>>8-t),8>t+a)o=o<>t-n-1&1,8==++a&&(a=0,i[s++]=S[o],o=0,s===i.length&&(i=this.f()));i[s]=o,this.buffer=i,this.i=a,this.index=s},r.prototype.finish=function(){var e,t=this.buffer,r=this.index;return 0b;++b){for(var A=E=b,_=7,E=E>>>1;E;E>>>=1)A<<=1,A|=1&E,--_;k[b]=(A<<_&255)>>>0}var S=k;n.prototype.getParent=function(e){return 2*((e-2)/4|0)},n.prototype.push=function(e,t){var r,n,i,s=this.buffer;for(r=this.length,s[this.length++]=t,s[this.length++]=e;0s[n]);)i=s[r],s[r]=s[n],s[n]=i,i=s[r+1],s[r+1]=s[n+1],s[n+1]=i,r=n;return this.length},n.prototype.pop=function(){var e,t,r,n,i,s=this.buffer;for(t=s[0],e=s[1],this.length-=2,s[0]=s[this.length],s[1]=s[this.length+1],i=0;!((n=2*i+2)>=this.length)&&(n+2s[n]&&(n+=2),s[n]>s[i]);)r=s[i],s[i]=s[n],s[n]=r,r=s[i+1],s[i+1]=s[n+1],s[n+1]=r,i=n;return{index:e,value:t,length:this.length}};var U,K=2,P={NONE:0,r:1,k:K,N:3},j=[];for(U=0;288>U;U++)switch(m){case 143>=U:j.push([U+48,8]);break;case 255>=U:j.push([U-144+400,9]);break;case 279>=U:j.push([U-256+0,7]);break;case 287>=U:j.push([U-280+192,8]);break;default:e("invalid literal: "+U)}s.prototype.j=function(){var t,n,i,s,f=this.input;switch(this.h){case 0:for(i=0,s=f.length;i>>8&255,b[k++]=255&p,b[k++]=p>>>8&255,w)b.set(h,k),k+=h.length,b=b.subarray(0,k);else{for(y=0,v=h.length;yX)for(;0X?X:138)>X-3&&J=J?(re[$++]=17,re[$++]=J-3,ne[17]++):(re[$++]=18,re[$++]=J-11,ne[18]++),X-=J;else if(re[$++]=te[Z],ne[te[Z]]++,3>--X)for(;0X?X:6)>X-3&&JF;F++)V[F]=N[G[F]];for(C=19;4=t:return[265,t-11,1];case 14>=t:return[266,t-13,1];case 16>=t:return[267,t-15,1];case 18>=t:return[268,t-17,1];case 22>=t:return[269,t-19,2];case 26>=t:return[270,t-23,2];case 30>=t:return[271,t-27,2];case 34>=t:return[272,t-31,2];case 42>=t:return[273,t-35,3];case 50>=t:return[274,t-43,3];case 58>=t:return[275,t-51,3];case 66>=t:return[276,t-59,3];case 82>=t:return[277,t-67,4];case 98>=t:return[278,t-83,4];case 114>=t:return[279,t-99,4];case 130>=t:return[280,t-115,4];case 162>=t:return[281,t-131,5];case 194>=t:return[282,t-163,5];case 226>=t:return[283,t-195,5];case 257>=t:return[284,t-227,5];case 258===t:return[285,t-258,0];default:e("invalid length: "+t)}}var r,n,i=[];for(r=3;258>=r;r++)n=t(r),i[r]=n[2]<<24|n[1]<<16|n[0];return i}(),T=w?new Uint32Array(x):x,O=0,C=1,I={D:O,C:C};f.prototype.p=function(){for(;!this.s;){var t=h(this,3);switch(1&t&&(this.s=m),t>>>=1){case 0:var r=this.input,n=this.c,s=this.a,a=this.b,o=r.length,u=g,f=g,c=s.length,d=g;switch(this.e=this.g=0,n+1>=o&&e(Error("invalid uncompressed block header: LEN")),u=r[n++]|r[n++]<<8,n+1>=o&&e(Error("invalid uncompressed block header: NLEN")),f=r[n++]|r[n++]<<8,u===~f&&e(Error("invalid uncompressed block header: length verify")),n+u>r.length&&e(Error("input buffer is broken")),this.n){case O:for(;a+u>s.length;){if(d=c-a,u-=d,w)s.set(r.subarray(n,n+d),a),a+=d,n+=d;else for(;d--;)s[a++]=r[n++];this.b=a,s=this.f(),a=this.b}break;case C:for(;a+u>s.length;)s=this.f({v:2});break;default:e(Error("invalid inflate mode"))}if(w)s.set(r.subarray(n,n+u),a),a+=u,n+=u;else for(;u--;)s[a++]=r[n++];this.c=n,this.b=a,this.a=s;break;case 1:this.o(W,J);break;case 2:for(var p=h(this,5)+257,y=h(this,5)+1,v=h(this,4)+4,b=new(w?Uint8Array:Array)(N.length),k=g,A=g,_=g,E=g,S=g,U=g,K=g,P=g,j=g,P=0;P=M?8:255>=M?9:279>=M?7:8;var Y,X,W=i(Z),$=new(w?Uint8Array:Array)(30);for(Y=0,X=$.length;Yi)n>=u&&(this.b=n,r=this.f(),n=this.b),r[n++]=i;else for(o=R[s=i-257],0=u&&(this.b=n,r=this.f(),n=this.b);o--;)r[n]=r[n++-a];for(;8<=this.e;)this.e-=8,this.c--;this.b=n},f.prototype.I=function(e,t){var r=this.a,n=this.b;this.u=e;for(var i,s,a,o,u=r.length;256!==(i=l(this,e));)if(256>i)n>=u&&(r=this.f(),u=r.length),r[n++]=i;else for(o=R[s=i-257],0u&&(r=this.f(),u=r.length);o--;)r[n]=r[n++-a];for(;8<=this.e;)this.e-=8,this.c--;this.b=n},f.prototype.f=function(){var e,t,r=new(w?Uint8Array:Array)(this.b-32768),n=this.b-32768,i=this.a;if(w)r.set(i.subarray(32768,r.length));else for(e=0,t=r.length;ee;++e)i[e]=i[n+e];return this.b=32768,i},f.prototype.J=function(e){var t,r,n,i,s=this.input.length/this.c+1|0,a=this.input,o=this.a;return e&&("number"==typeof e.v&&(s=e.v),"number"==typeof e.F&&(s+=e.F)),2>s?(r=(a.length-this.c)/this.u[2],i=r/2*258|0,n=it&&(this.a.length=t),e=this.a),this.buffer=e},d.prototype.p=function(){var t,r=this.input;return t=this.A.p(),this.c=this.A.c,this.M&&(r[this.c++]<<24|r[this.c++]<<16|r[this.c++]<<8|r[this.c++])>>>0!==c(t)&&e(Error("invalid adler-32 checksum")),t};var Q=8,ee=P;p.prototype.j=function(){var t,r,n,i,s,a,o,u=0;switch(o=this.a,t=Q){case Q:r=Math.LOG2E*Math.log(32768)-8;break;default:e(Error("invalid compression method"))}switch(n=r<<4|t,o[u++]=n,t){case Q:switch(this.h){case ee.NONE:s=0;break;case ee.r:s=1;break;case ee.k:s=2;break;default:e(Error("unsupported compression type"))}break;default:e(Error("invalid compression method"))}return i=s<<6|0,o[u++]=i|31-(256*n+i)%31,a=c(this.input),this.z.b=u,o=this.z.j(),u=o.length,w&&((o=new Uint8Array(o.buffer)).length<=u+4&&(this.a=new Uint8Array(o.length+4),this.a.set(o),o=this.a),o=o.subarray(0,u+4)),o[u++]=a>>24&255,o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a,o},t("Zlib.Inflate",d),t("Zlib.Inflate.prototype.decompress",d.prototype.p),y("Zlib.Inflate.BufferType",{ADAPTIVE:I.C,BLOCK:I.D}),t("Zlib.Deflate",p),t("Zlib.Deflate.compress",function(e,t){return new p(e,t).j()}),t("Zlib.Deflate.prototype.compress",p.prototype.j),y("Zlib.Deflate.CompressionType",{NONE:ee.NONE,FIXED:ee.r,DYNAMIC:ee.k})}).call(this)},{}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(e){return e&&e.__esModule?e:{default:e}}(e("../enums.js"));r.default={prefer_hash_algorithm:n.default.hash.sha256,encryption_cipher:n.default.symmetric.aes256,compression:n.default.compression.zip,aead_protect:!1,integrity_protect:!0,ignore_mdc_error:!1,checksum_required:!1,verify_expired_keys:!0,rsa_blinding:!0,use_native:!0,zero_copy:!1,debug:!1,tolerant:!0,show_version:!0,show_comment:!0,versionstring:"OpenPGP.js v2.6.2",commentstring:"https://openpgpjs.org",keyserver:"https://keyserver.ubuntu.com",node_store:"./openpgp.store"}},{"../enums.js":35}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./config.js");Object.defineProperty(r,"default",{enumerable:!0,get:function(){return function(e){return e&&e.__esModule?e:{default:e}}(n).default}})},{"./config.js":9}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(e){return e&&e.__esModule?e:{default:e}}(e("./cipher"));r.default={encrypt:function(e,t,r,i,s){var a=(t=new n.default[t](i)).blockSize,o=new Uint8Array(a),u=new Uint8Array(a),f=new Uint8Array(e.length+2);f.set(e),f[e.length]=e[a-2],f[e.length+1]=e[a-1],e=f;var h,l,c,d=new Uint8Array(r.length+2+2*a),p=s?0:2;for(h=0;ha*f;){var c=e.encrypt(u);for(o=r.subarray(f*a,f*a+a),s=0;so*u;){var l=e.encrypt(s);for(s=r.subarray(u*o+0,u*o+o+0),a=0;a>8&255}function s(e){return e>>16&255}function a(e){return e>>24&255}function o(e,t,r,n){return i(c[255&e])|i(c[t>>8&255])<<8|i(c[r>>16&255])<<16|i(c[n>>>24])<<24}function u(e,t,r){var u,f,h;for(h=function(e){var t,r,n=e.length,i=new Array(n/4);if(e&&!(n%4)){for(t=0,r=0;r>8&255]^p[r[2]>>16&255]^y[r[3]>>>24],h[1]=c[255&r[1]]^d[r[2]>>8&255]^p[r[3]>>16&255]^y[r[0]>>>24],h[2]=c[255&r[2]]^d[r[3]>>8&255]^p[r[0]>>16&255]^y[r[1]>>>24],h[3]=c[255&r[3]]^d[r[0]>>8&255]^p[r[1]>>16&255]^y[r[2]>>>24];return u=f-1,r[0]=h[0]^t.rk[u][0],r[1]=h[1]^t.rk[u][1],r[2]=h[2]^t.rk[u][2],r[3]=h[3]^t.rk[u][3],h[0]=o(r[0],r[1],r[2],r[3])^t.rk[f][0],h[1]=o(r[1],r[2],r[3],r[0])^t.rk[f][1],h[2]=o(r[2],r[3],r[0],r[1])^t.rk[f][2],h[3]=o(r[3],r[0],r[1],r[2])^t.rk[f][3],function(e){var t,r=0,o=e.length,u=new Array(4*o);for(t=0;t=0;o--)v[o]=y[o];for(u=0,f=0,o=0;o>>=8,n=255&e,e>>>=8,r=255&e,e>>>=8,t=255&e,s=this.sboxes[0][t]+this.sboxes[1][r],s^=this.sboxes[2][n],s+=this.sboxes[3][i]},n.prototype._encrypt_block=function(e){var t,r=e[0],n=e[1];for(t=0;t>>24-8*t&255,i[t+n]=r[1]>>>24-8*t&255;return i},n.prototype._decrypt_block=function(e){var t,r=e[0],n=e[1];for(t=this.NN+1;t>1;--t){var i=r^=this.parray[t];r=n=this._F(r)^n,n=i}r^=this.parray[1],n^=this.parray[0],e[0]=this._clean(n),e[1]=this._clean(r)},n.prototype.init=function(e){var t,r=0;for(this.parray=[],t=0;t=e.length&&(r=0);this.parray[t]=this.PARRAY[t]^i}for(this.sboxes=[],t=0;t<4;++t)for(this.sboxes[t]=[],r=0;r<256;++r)this.sboxes[t][r]=this.SBOXES[t][r];var s=[0,0];for(t=0;t>>32-r;return(s[0][i>>>24]^s[1][i>>>16&255])-s[2][i>>>8&255]+s[3][255&i]}function t(e,t,r){var n=t^e,i=n<>>32-r;return s[0][i>>>24]-s[1][i>>>16&255]+s[2][i>>>8&255]^s[3][255&i]}function r(e,t,r){var n=t-e,i=n<>>32-r;return(s[0][i>>>24]+s[1][i>>>16&255]^s[2][i>>>8&255])-s[3][255&i]}this.BlockSize=8,this.KeySize=16,this.setKey=function(e){if(this.masking=new Array(16),this.rotate=new Array(16),this.reset(),e.length!==this.KeySize)throw new Error("CAST-128: keys must be 16 bytes");return this.keySchedule(e),!0},this.reset=function(){for(var e=0;e<16;e++)this.masking[e]=0,this.rotate[e]=0},this.getBlockSize=function(){return this.BlockSize},this.encrypt=function(n){for(var i=new Array(n.length),s=0;s>>24&255,i[s+1]=u>>>16&255,i[s+2]=u>>>8&255,i[s+3]=255&u,i[s+4]=o>>>24&255,i[s+5]=o>>>16&255,i[s+6]=o>>>8&255,i[s+7]=255&o}return i},this.decrypt=function(n){for(var i=new Array(n.length),s=0;s>>24&255,i[s+1]=u>>>16&255,i[s+2]=u>>>8&255,i[s+3]=255&u,i[s+4]=o>>>24&255,i[s+5]=o>>16&255,i[s+6]=o>>8&255,i[s+7]=255&o}return i};var n=new Array(4);n[0]=new Array(4),n[0][0]=new Array(4,0,13,15,12,14,8),n[0][1]=new Array(5,2,16,18,17,19,10),n[0][2]=new Array(6,3,23,22,21,20,9),n[0][3]=new Array(7,1,26,25,27,24,11),n[1]=new Array(4),n[1][0]=new Array(0,6,21,23,20,22,16),n[1][1]=new Array(1,4,0,2,1,3,18),n[1][2]=new Array(2,5,7,6,5,4,17),n[1][3]=new Array(3,7,10,9,11,8,19),n[2]=new Array(4),n[2][0]=new Array(4,0,13,15,12,14,8),n[2][1]=new Array(5,2,16,18,17,19,10),n[2][2]=new Array(6,3,23,22,21,20,9),n[2][3]=new Array(7,1,26,25,27,24,11),n[3]=new Array(4),n[3][0]=new Array(0,6,21,23,20,22,16),n[3][1]=new Array(1,4,0,2,1,3,18),n[3][2]=new Array(2,5,7,6,5,4,17),n[3][3]=new Array(3,7,10,9,11,8,19);var i=new Array(4);i[0]=new Array(4),i[0][0]=new Array(24,25,23,22,18),i[0][1]=new Array(26,27,21,20,22),i[0][2]=new Array(28,29,19,18,25),i[0][3]=new Array(30,31,17,16,28),i[1]=new Array(4),i[1][0]=new Array(3,2,12,13,8),i[1][1]=new Array(1,0,14,15,13),i[1][2]=new Array(7,6,8,9,3),i[1][3]=new Array(5,4,10,11,7),i[2]=new Array(4),i[2][0]=new Array(19,18,28,29,25),i[2][1]=new Array(17,16,30,31,28),i[2][2]=new Array(23,22,24,25,18),i[2][3]=new Array(21,20,26,27,22),i[3]=new Array(4),i[3][0]=new Array(8,9,7,6,3),i[3][1]=new Array(10,11,5,4,7),i[3][2]=new Array(12,13,3,2,8),i[3][3]=new Array(14,15,1,0,13),this.keySchedule=function(e){var t,r,a=new Array(8),o=new Array(32);for(t=0;t<4;t++)r=4*t,a[t]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3];for(var u,f=[6,7,4,5],h=0,l=0;l<2;l++)for(var c=0;c<4;c++){for(r=0;r<4;r++){var d=n[c][r];u=a[d[1]],u^=s[4][a[d[2]>>>2]>>>24-8*(3&d[2])&255],u^=s[5][a[d[3]>>>2]>>>24-8*(3&d[3])&255],u^=s[6][a[d[4]>>>2]>>>24-8*(3&d[4])&255],u^=s[7][a[d[5]>>>2]>>>24-8*(3&d[5])&255],u^=s[f[r]][a[d[6]>>>2]>>>24-8*(3&d[6])&255],a[d[0]]=u}for(r=0;r<4;r++){var p=i[c][r];u=s[4][a[p[0]>>>2]>>>24-8*(3&p[0])&255],u^=s[5][a[p[1]>>>2]>>>24-8*(3&p[1])&255],u^=s[6][a[p[2]>>>2]>>>24-8*(3&p[2])&255],u^=s[7][a[p[3]>>>2]>>>24-8*(3&p[3])&255],u^=s[4+r][a[p[4]>>>2]>>>24-8*(3&p[4])&255],o[h]=u,h++}}for(t=0;t<16;t++)this.masking[t]=o[t],this.rotate[t]=31&o[16+t]};var s=new Array(8);s[0]=new Array(821772500,2678128395,1810681135,1059425402,505495343,2617265619,1610868032,3483355465,3218386727,2294005173,3791863952,2563806837,1852023008,365126098,3269944861,584384398,677919599,3229601881,4280515016,2002735330,1136869587,3744433750,2289869850,2731719981,2714362070,879511577,1639411079,575934255,717107937,2857637483,576097850,2731753936,1725645e3,2810460463,5111599,767152862,2543075244,1251459544,1383482551,3052681127,3089939183,3612463449,1878520045,1510570527,2189125840,2431448366,582008916,3163445557,1265446783,1354458274,3529918736,3202711853,3073581712,3912963487,3029263377,1275016285,4249207360,2905708351,3304509486,1442611557,3585198765,2712415662,2731849581,3248163920,2283946226,208555832,2766454743,1331405426,1447828783,3315356441,3108627284,2957404670,2981538698,3339933917,1669711173,286233437,1465092821,1782121619,3862771680,710211251,980974943,1651941557,430374111,2051154026,704238805,4128970897,3144820574,2857402727,948965521,3333752299,2227686284,718756367,2269778983,2731643755,718440111,2857816721,3616097120,1113355533,2478022182,410092745,1811985197,1944238868,2696854588,1415722873,1682284203,1060277122,1998114690,1503841958,82706478,2315155686,1068173648,845149890,2167947013,1768146376,1993038550,3566826697,3390574031,940016341,3355073782,2328040721,904371731,1205506512,4094660742,2816623006,825647681,85914773,2857843460,1249926541,1417871568,3287612,3211054559,3126306446,1975924523,1353700161,2814456437,2438597621,1800716203,722146342,2873936343,1151126914,4160483941,2877670899,458611604,2866078500,3483680063,770352098,2652916994,3367839148,3940505011,3585973912,3809620402,718646636,2504206814,2914927912,3631288169,2857486607,2860018678,575749918,2857478043,718488780,2069512688,3548183469,453416197,1106044049,3032691430,52586708,3378514636,3459808877,3211506028,1785789304,218356169,3571399134,3759170522,1194783844,1523787992,3007827094,1975193539,2555452411,1341901877,3045838698,3776907964,3217423946,2802510864,2889438986,1057244207,1636348243,3761863214,1462225785,2632663439,481089165,718503062,24497053,3332243209,3344655856,3655024856,3960371065,1195698900,2971415156,3710176158,2115785917,4027663609,3525578417,2524296189,2745972565,3564906415,1372086093,1452307862,2780501478,1476592880,3389271281,18495466,2378148571,901398090,891748256,3279637769,3157290713,2560960102,1447622437,4284372637,216884176,2086908623,1879786977,3588903153,2242455666,2938092967,3559082096,2810645491,758861177,1121993112,215018983,642190776,4169236812,1196255959,2081185372,3508738393,941322904,4124243163,2877523539,1848581667,2205260958,3180453958,2589345134,3694731276,550028657,2519456284,3789985535,2973870856,2093648313,443148163,46942275,2734146937,1117713533,1115362972,1523183689,3717140224,1551984063),s[1]=new Array(522195092,4010518363,1776537470,960447360,4267822970,4005896314,1435016340,1929119313,2913464185,1310552629,3579470798,3724818106,2579771631,1594623892,417127293,2715217907,2696228731,1508390405,3994398868,3925858569,3695444102,4019471449,3129199795,3770928635,3520741761,990456497,4187484609,2783367035,21106139,3840405339,631373633,3783325702,532942976,396095098,3548038825,4267192484,2564721535,2011709262,2039648873,620404603,3776170075,2898526339,3612357925,4159332703,1645490516,223693667,1567101217,3362177881,1029951347,3470931136,3570957959,1550265121,119497089,972513919,907948164,3840628539,1613718692,3594177948,465323573,2659255085,654439692,2575596212,2699288441,3127702412,277098644,624404830,4100943870,2717858591,546110314,2403699828,3655377447,1321679412,4236791657,1045293279,4010672264,895050893,2319792268,494945126,1914543101,2777056443,3894764339,2219737618,311263384,4275257268,3458730721,669096869,3584475730,3835122877,3319158237,3949359204,2005142349,2713102337,2228954793,3769984788,569394103,3855636576,1425027204,108000370,2736431443,3671869269,3043122623,1750473702,2211081108,762237499,3972989403,2798899386,3061857628,2943854345,867476300,964413654,1591880597,1594774276,2179821409,552026980,3026064248,3726140315,2283577634,3110545105,2152310760,582474363,1582640421,1383256631,2043843868,3322775884,1217180674,463797851,2763038571,480777679,2718707717,2289164131,3118346187,214354409,200212307,3810608407,3025414197,2674075964,3997296425,1847405948,1342460550,510035443,4080271814,815934613,833030224,1620250387,1945732119,2703661145,3966000196,1388869545,3456054182,2687178561,2092620194,562037615,1356438536,3409922145,3261847397,1688467115,2150901366,631725691,3840332284,549916902,3455104640,394546491,837744717,2114462948,751520235,2221554606,2415360136,3999097078,2063029875,803036379,2702586305,821456707,3019566164,360699898,4018502092,3511869016,3677355358,2402471449,812317050,49299192,2570164949,3259169295,2816732080,3331213574,3101303564,2156015656,3705598920,3546263921,143268808,3200304480,1638124008,3165189453,3341807610,578956953,2193977524,3638120073,2333881532,807278310,658237817,2969561766,1641658566,11683945,3086995007,148645947,1138423386,4158756760,1981396783,2401016740,3699783584,380097457,2680394679,2803068651,3334260286,441530178,4016580796,1375954390,761952171,891809099,2183123478,157052462,3683840763,1592404427,341349109,2438483839,1417898363,644327628,2233032776,2353769706,2201510100,220455161,1815641738,182899273,2995019788,3627381533,3702638151,2890684138,1052606899,588164016,1681439879,4038439418,2405343923,4229449282,167996282,1336969661,1688053129,2739224926,1543734051,1046297529,1138201970,2121126012,115334942,1819067631,1902159161,1941945968,2206692869,1159982321),s[2]=new Array(2381300288,637164959,3952098751,3893414151,1197506559,916448331,2350892612,2932787856,3199334847,4009478890,3905886544,1373570990,2450425862,4037870920,3778841987,2456817877,286293407,124026297,3001279700,1028597854,3115296800,4208886496,2691114635,2188540206,1430237888,1218109995,3572471700,308166588,570424558,2187009021,2455094765,307733056,1310360322,3135275007,1384269543,2388071438,863238079,2359263624,2801553128,3380786597,2831162807,1470087780,1728663345,4072488799,1090516929,532123132,2389430977,1132193179,2578464191,3051079243,1670234342,1434557849,2711078940,1241591150,3314043432,3435360113,3091448339,1812415473,2198440252,267246943,796911696,3619716990,38830015,1526438404,2806502096,374413614,2943401790,1489179520,1603809326,1920779204,168801282,260042626,2358705581,1563175598,2397674057,1356499128,2217211040,514611088,2037363785,2186468373,4022173083,2792511869,2913485016,1173701892,4200428547,3896427269,1334932762,2455136706,602925377,2835607854,1613172210,41346230,2499634548,2457437618,2188827595,41386358,4172255629,1313404830,2405527007,3801973774,2217704835,873260488,2528884354,2478092616,4012915883,2555359016,2006953883,2463913485,575479328,2218240648,2099895446,660001756,2341502190,3038761536,3888151779,3848713377,3286851934,1022894237,1620365795,3449594689,1551255054,15374395,3570825345,4249311020,4151111129,3181912732,310226346,1133119310,530038928,136043402,2476768958,3107506709,2544909567,1036173560,2367337196,1681395281,1758231547,3641649032,306774401,1575354324,3716085866,1990386196,3114533736,2455606671,1262092282,3124342505,2768229131,4210529083,1833535011,423410938,660763973,2187129978,1639812e3,3508421329,3467445492,310289298,272797111,2188552562,2456863912,310240523,677093832,1013118031,901835429,3892695601,1116285435,3036471170,1337354835,243122523,520626091,277223598,4244441197,4194248841,1766575121,594173102,316590669,742362309,3536858622,4176435350,3838792410,2501204839,1229605004,3115755532,1552908988,2312334149,979407927,3959474601,1148277331,176638793,3614686272,2083809052,40992502,1340822838,2731552767,3535757508,3560899520,1354035053,122129617,7215240,2732932949,3118912700,2718203926,2539075635,3609230695,3725561661,1928887091,2882293555,1988674909,2063640240,2491088897,1459647954,4189817080,2302804382,1113892351,2237858528,1927010603,4002880361,1856122846,1594404395,2944033133,3855189863,3474975698,1643104450,4054590833,3431086530,1730235576,2984608721,3084664418,2131803598,4178205752,267404349,1617849798,1616132681,1462223176,736725533,2327058232,551665188,2945899023,1749386277,2575514597,1611482493,674206544,2201269090,3642560800,728599968,1680547377,2620414464,1388111496,453204106,4156223445,1094905244,2754698257,2201108165,3757000246,2704524545,3922940700,3996465027),s[3]=new Array(2645754912,532081118,2814278639,3530793624,1246723035,1689095255,2236679235,4194438865,2116582143,3859789411,157234593,2045505824,4245003587,1687664561,4083425123,605965023,672431967,1336064205,3376611392,214114848,4258466608,3232053071,489488601,605322005,3998028058,264917351,1912574028,756637694,436560991,202637054,135989450,85393697,2152923392,3896401662,2895836408,2145855233,3535335007,115294817,3147733898,1922296357,3464822751,4117858305,1037454084,2725193275,2127856640,1417604070,1148013728,1827919605,642362335,2929772533,909348033,1346338451,3547799649,297154785,1917849091,4161712827,2883604526,3968694238,1469521537,3780077382,3375584256,1763717519,136166297,4290970789,1295325189,2134727907,2798151366,1566297257,3672928234,2677174161,2672173615,965822077,2780786062,289653839,1133871874,3491843819,35685304,1068898316,418943774,672553190,642281022,2346158704,1954014401,3037126780,4079815205,2030668546,3840588673,672283427,1776201016,359975446,3750173538,555499703,2769985273,1324923,69110472,152125443,3176785106,3822147285,1340634837,798073664,1434183902,15393959,216384236,1303690150,3881221631,3711134124,3960975413,106373927,2578434224,1455997841,1801814300,1578393881,1854262133,3188178946,3258078583,2302670060,1539295533,3505142565,3078625975,2372746020,549938159,3278284284,2620926080,181285381,2865321098,3970029511,68876850,488006234,1728155692,2608167508,836007927,2435231793,919367643,3339422534,3655756360,1457871481,40520939,1380155135,797931188,234455205,2255801827,3990488299,397000196,739833055,3077865373,2871719860,4022553888,772369276,390177364,3853951029,557662966,740064294,1640166671,1699928825,3535942136,622006121,3625353122,68743880,1742502,219489963,1664179233,1577743084,1236991741,410585305,2366487942,823226535,1050371084,3426619607,3586839478,212779912,4147118561,1819446015,1911218849,530248558,3486241071,3252585495,2886188651,3410272728,2342195030,20547779,2982490058,3032363469,3631753222,312714466,1870521650,1493008054,3491686656,615382978,4103671749,2534517445,1932181,2196105170,278426614,6369430,3274544417,2913018367,697336853,2143000447,2946413531,701099306,1558357093,2805003052,3500818408,2321334417,3567135975,216290473,3591032198,23009561,1996984579,3735042806,2024298078,3739440863,569400510,2339758983,3016033873,3097871343,3639523026,3844324983,3256173865,795471839,2951117563,4101031090,4091603803,3603732598,971261452,534414648,428311343,3389027175,2844869880,694888862,1227866773,2456207019,3043454569,2614353370,3749578031,3676663836,459166190,4132644070,1794958188,51825668,2252611902,3084671440,2036672799,3436641603,1099053433,2469121526,3059204941,1323291266,2061838604,1018778475,2233344254,2553501054,334295216,3556750194,1065731521,183467730),s[4]=new Array(2127105028,745436345,2601412319,2788391185,3093987327,500390133,1155374404,389092991,150729210,3891597772,3523549952,1935325696,716645080,946045387,2901812282,1774124410,3869435775,4039581901,3293136918,3438657920,948246080,363898952,3867875531,1286266623,1598556673,68334250,630723836,1104211938,1312863373,613332731,2377784574,1101634306,441780740,3129959883,1917973735,2510624549,3238456535,2544211978,3308894634,1299840618,4076074851,1756332096,3977027158,297047435,3790297736,2265573040,3621810518,1311375015,1667687725,47300608,3299642885,2474112369,201668394,1468347890,576830978,3594690761,3742605952,1958042578,1747032512,3558991340,1408974056,3366841779,682131401,1033214337,1545599232,4265137049,206503691,103024618,2855227313,1337551222,2428998917,2963842932,4015366655,3852247746,2796956967,3865723491,3747938335,247794022,3755824572,702416469,2434691994,397379957,851939612,2314769512,218229120,1380406772,62274761,214451378,3170103466,2276210409,3845813286,28563499,446592073,1693330814,3453727194,29968656,3093872512,220656637,2470637031,77972100,1667708854,1358280214,4064765667,2395616961,325977563,4277240721,4220025399,3605526484,3355147721,811859167,3069544926,3962126810,652502677,3075892249,4132761541,3498924215,1217549313,3250244479,3858715919,3053989961,1538642152,2279026266,2875879137,574252750,3324769229,2651358713,1758150215,141295887,2719868960,3515574750,4093007735,4194485238,1082055363,3417560400,395511885,2966884026,179534037,3646028556,3738688086,1092926436,2496269142,257381841,3772900718,1636087230,1477059743,2499234752,3811018894,2675660129,3285975680,90732309,1684827095,1150307763,1723134115,3237045386,1769919919,1240018934,815675215,750138730,2239792499,1234303040,1995484674,138143821,675421338,1145607174,1936608440,3238603024,2345230278,2105974004,323969391,779555213,3004902369,2861610098,1017501463,2098600890,2628620304,2940611490,2682542546,1171473753,3656571411,3687208071,4091869518,393037935,159126506,1662887367,1147106178,391545844,3452332695,1891500680,3016609650,1851642611,546529401,1167818917,3194020571,2848076033,3953471836,575554290,475796850,4134673196,450035699,2351251534,844027695,1080539133,86184846,1554234488,3692025454,1972511363,2018339607,1491841390,1141460869,1061690759,4244549243,2008416118,2351104703,2868147542,1598468138,722020353,1027143159,212344630,1387219594,1725294528,3745187956,2500153616,458938280,4129215917,1828119673,544571780,3503225445,2297937496,1241802790,267843827,2694610800,1397140384,1558801448,3782667683,1806446719,929573330,2234912681,400817706,616011623,4121520928,3603768725,1761550015,1968522284,4053731006,4192232858,4005120285,872482584,3140537016,3894607381,2287405443,1963876937,3663887957,1584857e3,2975024454,1833426440,4025083860),s[5]=new Array(4143615901,749497569,1285769319,3795025788,2514159847,23610292,3974978748,844452780,3214870880,3751928557,2213566365,1676510905,448177848,3730751033,4086298418,2307502392,871450977,3222878141,4110862042,3831651966,2735270553,1310974780,2043402188,1218528103,2736035353,4274605013,2702448458,3936360550,2693061421,162023535,2827510090,687910808,23484817,3784910947,3371371616,779677500,3503626546,3473927188,4157212626,3500679282,4248902014,2466621104,3899384794,1958663117,925738300,1283408968,3669349440,1840910019,137959847,2679828185,1239142320,1315376211,1547541505,1690155329,739140458,3128809933,3933172616,3876308834,905091803,1548541325,4040461708,3095483362,144808038,451078856,676114313,2861728291,2469707347,993665471,373509091,2599041286,4025009006,4170239449,2149739950,3275793571,3749616649,2794760199,1534877388,572371878,2590613551,1753320020,3467782511,1405125690,4270405205,633333386,3026356924,3475123903,632057672,2846462855,1404951397,3882875879,3915906424,195638627,2385783745,3902872553,1233155085,3355999740,2380578713,2702246304,2144565621,3663341248,3894384975,2502479241,4248018925,3094885567,1594115437,572884632,3385116731,767645374,1331858858,1475698373,3793881790,3532746431,1321687957,619889600,1121017241,3440213920,2070816767,2833025776,1933951238,4095615791,890643334,3874130214,859025556,360630002,925594799,1764062180,3920222280,4078305929,979562269,2810700344,4087740022,1949714515,546639971,1165388173,3069891591,1495988560,922170659,1291546247,2107952832,1813327274,3406010024,3306028637,4241950635,153207855,2313154747,1608695416,1150242611,1967526857,721801357,1220138373,3691287617,3356069787,2112743302,3281662835,1111556101,1778980689,250857638,2298507990,673216130,2846488510,3207751581,3562756981,3008625920,3417367384,2198807050,529510932,3547516680,3426503187,2364944742,102533054,2294910856,1617093527,1204784762,3066581635,1019391227,1069574518,1317995090,1691889997,3661132003,510022745,3238594800,1362108837,1817929911,2184153760,805817662,1953603311,3699844737,120799444,2118332377,207536705,2282301548,4120041617,145305846,2508124933,3086745533,3261524335,1877257368,2977164480,3160454186,2503252186,4221677074,759945014,254147243,2767453419,3801518371,629083197,2471014217,907280572,3900796746,940896768,2751021123,2625262786,3161476951,3661752313,3260732218,1425318020,2977912069,1496677566,3988592072,2140652971,3126511541,3069632175,977771578,1392695845,1698528874,1411812681,1369733098,1343739227,3620887944,1142123638,67414216,3102056737,3088749194,1626167401,2546293654,3941374235,697522451,33404913,143560186,2595682037,994885535,1247667115,3859094837,2699155541,3547024625,4114935275,2968073508,3199963069,2732024527,1237921620,951448369,1898488916,1211705605,2790989240,2233243581,3598044975),s[6]=new Array(2246066201,858518887,1714274303,3485882003,713916271,2879113490,3730835617,539548191,36158695,1298409750,419087104,1358007170,749914897,2989680476,1261868530,2995193822,2690628854,3443622377,3780124940,3796824509,2976433025,4259637129,1551479e3,512490819,1296650241,951993153,2436689437,2460458047,144139966,3136204276,310820559,3068840729,643875328,1969602020,1680088954,2185813161,3283332454,672358534,198762408,896343282,276269502,3014846926,84060815,197145886,376173866,3943890818,3813173521,3545068822,1316698879,1598252827,2633424951,1233235075,859989710,2358460855,3503838400,3409603720,1203513385,1193654839,2792018475,2060853022,207403770,1144516871,3068631394,1121114134,177607304,3785736302,326409831,1929119770,2983279095,4183308101,3474579288,3200513878,3228482096,119610148,1170376745,3378393471,3163473169,951863017,3337026068,3135789130,2907618374,1183797387,2015970143,4045674555,2182986399,2952138740,3928772205,384012900,2454997643,10178499,2879818989,2596892536,111523738,2995089006,451689641,3196290696,235406569,1441906262,3890558523,3013735005,4158569349,1644036924,376726067,1006849064,3664579700,2041234796,1021632941,1374734338,2566452058,371631263,4007144233,490221539,206551450,3140638584,1053219195,1853335209,3412429660,3562156231,735133835,1623211703,3104214392,2738312436,4096837757,3366392578,3110964274,3956598718,3196820781,2038037254,3877786376,2339753847,300912036,3766732888,2372630639,1516443558,4200396704,1574567987,4069441456,4122592016,2699739776,146372218,2748961456,2043888151,35287437,2596680554,655490400,1132482787,110692520,1031794116,2188192751,1324057718,1217253157,919197030,686247489,3261139658,1028237775,3135486431,3059715558,2460921700,986174950,2661811465,4062904701,2752986992,3709736643,367056889,1353824391,731860949,1650113154,1778481506,784341916,357075625,3608602432,1074092588,2480052770,3811426202,92751289,877911070,3600361838,1231880047,480201094,3756190983,3094495953,434011822,87971354,363687820,1717726236,1901380172,3926403882,2481662265,400339184,1490350766,2661455099,1389319756,2558787174,784598401,1983468483,30828846,3550527752,2716276238,3841122214,1765724805,1955612312,1277890269,1333098070,1564029816,2704417615,1026694237,3287671188,1260819201,3349086767,1016692350,1582273796,1073413053,1995943182,694588404,1025494639,3323872702,3551898420,4146854327,453260480,1316140391,1435673405,3038941953,3486689407,1622062951,403978347,817677117,950059133,4246079218,3278066075,1486738320,1417279718,481875527,2549965225,3933690356,760697757,1452955855,3897451437,1177426808,1702951038,4085348628,2447005172,1084371187,3516436277,3068336338,1073369276,1027665953,3284188590,1230553676,1368340146,2226246512,267243139,2274220762,4070734279,2497715176,2423353163,2504755875),s[7]=new Array(3793104909,3151888380,2817252029,895778965,2005530807,3871412763,237245952,86829237,296341424,3851759377,3974600970,2475086196,709006108,1994621201,2972577594,937287164,3734691505,168608556,3189338153,2225080640,3139713551,3033610191,3025041904,77524477,185966941,1208824168,2344345178,1721625922,3354191921,1066374631,1927223579,1971335949,2483503697,1551748602,2881383779,2856329572,3003241482,48746954,1398218158,2050065058,313056748,4255789917,393167848,1912293076,940740642,3465845460,3091687853,2522601570,2197016661,1727764327,364383054,492521376,1291706479,3264136376,1474851438,1685747964,2575719748,1619776915,1814040067,970743798,1561002147,2925768690,2123093554,1880132620,3151188041,697884420,2550985770,2607674513,2659114323,110200136,1489731079,997519150,1378877361,3527870668,478029773,2766872923,1022481122,431258168,1112503832,897933369,2635587303,669726182,3383752315,918222264,163866573,3246985393,3776823163,114105080,1903216136,761148244,3571337562,1690750982,3166750252,1037045171,1888456500,2010454850,642736655,616092351,365016990,1185228132,4174898510,1043824992,2023083429,2241598885,3863320456,3279669087,3674716684,108438443,2132974366,830746235,606445527,4173263986,2204105912,1844756978,2532684181,4245352700,2969441100,3796921661,1335562986,4061524517,2720232303,2679424040,634407289,885462008,3294724487,3933892248,2094100220,339117932,4048830727,3202280980,1458155303,2689246273,1022871705,2464987878,3714515309,353796843,2822958815,4256850100,4052777845,551748367,618185374,3778635579,4020649912,1904685140,3069366075,2670879810,3407193292,2954511620,4058283405,2219449317,3135758300,1120655984,3447565834,1474845562,3577699062,550456716,3466908712,2043752612,881257467,869518812,2005220179,938474677,3305539448,3850417126,1315485940,3318264702,226533026,965733244,321539988,1136104718,804158748,573969341,3708209826,937399083,3290727049,2901666755,1461057207,4013193437,4066861423,3242773476,2421326174,1581322155,3028952165,786071460,3900391652,3918438532,1485433313,4023619836,3708277595,3678951060,953673138,1467089153,1930354364,1533292819,2492563023,1346121658,1685000834,1965281866,3765933717,4190206607,2052792609,3515332758,690371149,3125873887,2180283551,2903598061,3933952357,436236910,289419410,14314871,1242357089,2904507907,1616633776,2666382180,585885352,3471299210,2699507360,1432659641,277164553,3354103607,770115018,2303809295,3741942315,3177781868,2853364978,2269453327,3774259834,987383833,1290892879,225909803,1741533526,890078084,1496906255,1111072499,916028167,243534141,1252605537,2204162171,531204876,290011180,3916834213,102027703,237315147,209093447,1486785922,220223953,2758195998,4175039106,82940208,3127791296,2569425252,518464269,1353887104,3941492737,2377294467,3935040926)},this.cast5.setKey(e),this.encrypt=function(e){return this.cast5.encrypt(e)}}Object.defineProperty(r,"__esModule",{value:!0}),r.default=n,n.blockSize=n.prototype.blockSize=8,n.keySize=n.prototype.keySize=16},{}],15:[function(e,t,r){"use strict";function n(e,t,r,n,i,s){var a,o,u,f,h,l,c,d,p,y,g,m,v,w,b=new Array(16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756),k=new Array(-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344),A=new Array(520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584),_=new Array(8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928),E=new Array(256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080),S=new Array(536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312),U=new Array(2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154),K=new Array(268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696),P=0,j=t.length,x=32===e.length?3:9;d=3===x?r?new Array(0,32,2):new Array(30,-2,-2):r?new Array(0,32,2,62,30,-2,64,96,2):new Array(94,62,-2,32,64,2,30,-2,-2),r&&(j=(t=function(e,t){var r,n=8-e.length%8;if(2===t&&n<8)r=" ".charCodeAt(0);else if(1===t)r=n;else{if(t||!(n<8)){if(8===n)return e;throw new Error("des: invalid padding")}r=0}for(var i=new Uint8Array(e.length+n),s=0;s>>4^c))<<4,l^=(u=65535&(l>>>16^(c^=u)))<<16,l^=u=858993459&((c^=u)>>>2^l),l^=u=16711935&((c^=u<<2)>>>8^l),l=(l^=(u=1431655765&(l>>>1^(c^=u<<8)))<<1)<<1|l>>>31,c=(c^=u)<<1|c>>>31,o=0;o>>4|c<<28)^e[a+1],u=l,l=c,c=u^(k[f>>>24&63]|_[f>>>16&63]|S[f>>>8&63]|K[63&f]|b[h>>>24&63]|A[h>>>16&63]|E[h>>>8&63]|U[63&h]);u=l,l=c,c=u}c=c>>>1|c<<31,c^=u=1431655765&((l=l>>>1|l<<31)>>>1^c),c^=(u=16711935&(c>>>8^(l^=u<<1)))<<8,c^=(u=858993459&(c>>>2^(l^=u)))<<2,c^=u=65535&((l^=u)>>>16^c),c^=u=252645135&((l^=u<<16)>>>4^c),l^=u<<4,1===n&&(r?(p=l,g=c):(l^=y,c^=m)),T[O++]=l>>>24,T[O++]=l>>>16&255,T[O++]=l>>>8&255,T[O++]=255&l,T[O++]=c>>>24,T[O++]=c>>>16&255,T[O++]=c>>>8&255,T[O++]=255&c}return r||(T=function(e,t){var r,n=null;if(2===t)r=" ".charCodeAt(0);else if(1===t)n=e[e.length-1];else{if(t)throw new Error("des: invalid padding");r=0}if(!n){for(n=1;e[e.length-n]===r;)n++;n--}return e.subarray(0,e.length-n)}(T,s)),T}function i(e){for(var t,r,n,i=new Array(0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964),s=new Array(0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697),a=new Array(0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272),o=new Array(0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144),u=new Array(0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256),f=new Array(0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488),h=new Array(0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746),l=new Array(0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568),c=new Array(0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578),d=new Array(0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488),p=new Array(0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800),y=new Array(0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744),g=new Array(0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128),m=new Array(0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261),v=e.length>8?3:1,w=new Array(32*v),b=new Array(0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0),k=0,A=0,_=0;_>>4^S))<<4,E^=n=65535&((S^=n)>>>-16^E),E^=(n=858993459&(E>>>2^(S^=n<<-16)))<<2,E^=n=65535&((S^=n)>>>-16^E),E^=(n=1431655765&(E>>>1^(S^=n<<-16)))<<1,E^=n=16711935&((S^=n)>>>8^E),n=(E^=(n=1431655765&(E>>>1^(S^=n<<8)))<<1)<<8|(S^=n)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=n;for(var U=0;U>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15,t=i[(E&=-15)>>>28]|s[E>>>24&15]|a[E>>>20&15]|o[E>>>16&15]|u[E>>>12&15]|f[E>>>8&15]|h[E>>>4&15],n=65535&((r=l[S>>>28]|c[S>>>24&15]|d[S>>>20&15]|p[S>>>16&15]|y[S>>>12&15]|g[S>>>8&15]|m[S>>>4&15])>>>16^t),w[A++]=t^n,w[A++]=r^n<<16}return w}function s(e){this.key=[];for(var t=0;t<3;t++)this.key.push(new Uint8Array(e.subarray(8*t,8*t+8)));this.encrypt=function(e){return n(i(this.key[2]),n(i(this.key[1]),n(i(this.key[0]),e,!0,0,null,null),!1,0,null,null),!0,0,null,null)}}Object.defineProperty(r,"__esModule",{value:!0}),s.keySize=s.prototype.keySize=24,s.blockSize=s.prototype.blockSize=8,r.default={des:s,originalDes:function(e){this.key=e,this.encrypt=function(e,t){return n(i(this.key),e,!0,0,null,t)},this.decrypt=function(e,t){return n(i(this.key),e,!1,0,null,t)}}}},{}],16:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("./aes.js")),s=n(e("./des.js")),a=n(e("./cast5.js")),o=n(e("./twofish.js")),u=n(e("./blowfish.js"));r.default={aes128:i.default[128],aes192:i.default[192],aes256:i.default[256],des:s.default.originalDes,tripledes:s.default.des,cast5:a.default,twofish:o.default,blowfish:u.default,idea:function(){throw new Error("IDEA symmetric-key algorithm not implemented")}}},{"./aes.js":12,"./blowfish.js":13,"./cast5.js":14,"./des.js":15,"./twofish.js":17}],17:[function(e,t,r){"use strict";function n(e,t){return(e<>>32-t)&f}function i(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function s(e,t,r){e.splice(t,4,255&r,r>>>8&255,r>>>16&255,r>>>24&255)}function a(e,t){return e>>>8*t&255}function o(e){this.tf=function(){function e(e){return d[0][a(e,0)]^d[1][a(e,1)]^d[2][a(e,2)]^d[3][a(e,3)]}function t(e){return d[0][a(e,3)]^d[1][a(e,0)]^d[2][a(e,1)]^d[3][a(e,2)]}function r(r,i){var s=e(i[0]),a=t(i[1]);i[2]=n(i[2]^s+a+c[4*r+8]&f,31),i[3]=n(i[3],1)^s+2*a+c[4*r+9]&f,s=e(i[2]),a=t(i[3]),i[0]=n(i[0]^s+a+c[4*r+10]&f,31),i[1]=n(i[1],1)^s+2*a+c[4*r+11]&f}function o(r,i){var s=e(i[0]),a=t(i[1]);i[2]=n(i[2],1)^s+a+c[4*r+10]&f,i[3]=n(i[3]^s+2*a+c[4*r+11]&f,31),s=e(i[2]),a=t(i[3]),i[0]=n(i[0],1)^s+a+c[4*r+8]&f,i[1]=n(i[1]^s+2*a+c[4*r+9]&f,31)}var u=null,h=null,l=-1,c=[],d=[[],[],[],[]];return{name:"twofish",blocksize:16,open:function(e){function t(e){return e^e>>2^[0,90,180,238][3&e]}function r(e){return e^e>>1^e>>2^[0,238,180,90][3&e]}function s(e,t){var r,n,i;for(r=0;r<8;r++)n=t>>>24,t=t<<8&f|e>>>24,e=e<<8&f,i=n<<1,128&n&&(i^=333),t^=n^i<<16,i^=n>>>1,1&n&&(i^=166),t^=i<<24|i<<8;return t}function o(e,t){var r,n,i,s;return r=t>>4,n=15&t,i=U[e][r^n],s=K[e][x[n]^T[r]],j[e][x[s]^T[i]]<<4|P[e][i^s]}function h(e,t){var r=a(e,0),n=a(e,1),i=a(e,2),s=a(e,3);switch(v){case 4:r=O[1][r]^a(t[3],0),n=O[0][n]^a(t[3],1),i=O[0][i]^a(t[3],2),s=O[1][s]^a(t[3],3);case 3:r=O[1][r]^a(t[2],0),n=O[1][n]^a(t[2],1),i=O[0][i]^a(t[2],2),s=O[0][s]^a(t[2],3);case 2:r=O[0][O[0][r]^a(t[1],0)]^a(t[0],0),n=O[0][O[1][n]^a(t[1],1)]^a(t[0],1),i=O[1][O[0][i]^a(t[1],2)]^a(t[0],2),s=O[1][O[1][s]^a(t[1],3)]^a(t[0],3)}return C[0][r]^C[1][n]^C[2][i]^C[3][s]}var l,p,y,g,m,v,w,b,k,A=[],_=[],E=[],S=[],U=[[8,1,7,13,6,15,3,2,0,11,5,9,14,12,10,4],[2,8,11,13,15,7,6,14,3,1,9,4,0,10,12,5]],K=[[14,12,11,8,1,2,3,5,15,4,10,6,7,0,9,13],[1,14,2,11,4,12,3,7,6,13,10,5,15,9,0,8]],P=[[11,10,5,14,6,13,9,0,12,8,15,3,2,4,7,1],[4,12,7,5,1,6,9,10,0,14,13,8,2,11,3,15]],j=[[13,7,15,4,1,2,6,14,9,11,3,0,8,5,12,10],[11,9,5,1,12,3,13,14,6,4,7,15,2,0,8,10]],x=[0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15],T=[0,9,2,11,4,13,6,15,8,1,10,3,12,5,14,7],O=[[],[]],C=[[],[],[],[]];for(l=(u=(u=e).slice(0,32)).length;16!==l&&24!==l&&32!==l;)u[l++]=0;for(l=0;l>2]=i(u,l);for(l=0;l<256;l++)O[0][l]=o(0,l),O[1][l]=o(1,l);for(l=0;l<256;l++)b=t(w=O[1][l]),k=r(w),C[0][l]=w+(b<<8)+(k<<16)+(k<<24),C[2][l]=b+(k<<8)+(w<<16)+(k<<24),b=t(w=O[0][l]),k=r(w),C[1][l]=k+(k<<8)+(b<<16)+(w<<24),C[3][l]=b+(w<<8)+(k<<16)+(b<<24);for(v=E.length/2,l=0;l=0;n--)o(n,r);s(h,l,r[2]^c[0]),s(h,l+4,r[3]^c[1]),s(h,l+8,r[0]^c[2]),s(h,l+12,r[1]^c[3]),l+=16},finalize:function(){return h}}}(),this.tf.open(u(e),0),this.encrypt=function(e){return this.tf.encrypt(u(e),0)}}function u(e){for(var t=[],r=0;r>>32-i,r)}function s(e,t,r,n,s,a,o){return i(t&r|~t&n,e,t,s,a,o)}function a(e,t,r,n,s,a,o){return i(t&n|r&~n,e,t,s,a,o)}function o(e,t,r,n,s,a,o){return i(t^r^n,e,t,s,a,o)}function u(e,t,r,n,s,a,o){return i(r^(t|~n),e,t,s,a,o)}function f(e){for(var t="",r=0;r<4;r++)t+=d[e>>8*r+4&15]+d[e>>8*r&15];return t}function h(e){return function(e){for(var t=0;t>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return r}(e.substring(t-64,t)));e=e.substring(t-64);var s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(s[t>>2]|=128<<(t%4<<3),t>55)for(n(i,s),t=0;t<16;t++)s[t]=0;return s[14]=8*r,n(i,s),i}(e))}function l(e,t){return e+t&4294967295}Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){var t=h(c.default.Uint8Array2str(e));return c.default.str2Uint8Array(c.default.hex2bin(t))};var c=function(e){return e&&e.__esModule?e:{default:e}}(e("../../util.js")),d="0123456789abcdef".split("")},{"../../util.js":70}],22:[function(e,t,r){"use strict";function n(e,t){return new Number(e<>>32-t)}function i(e,t,r){return new Number(e^t^r)}function s(e,t,r){return new Number(e&t|~e&r)}function a(e,t,r){return new Number((e|~t)^r)}function o(e,t,r){return new Number(e&r|t&~r)}function u(e,t,r){return new Number(e^(t|~r))}function f(e,t,r,f,h,l,c,d){switch(d){case 0:e+=i(t,r,f)+l+0;break;case 1:e+=s(t,r,f)+l+1518500249;break;case 2:e+=a(t,r,f)+l+1859775393;break;case 3:e+=o(t,r,f)+l+2400959708;break;case 4:e+=u(t,r,f)+l+2840853838;break;case 5:e+=u(t,r,f)+l+1352829926;break;case 6:e+=o(t,r,f)+l+1548603684;break;case 7:e+=a(t,r,f)+l+1836072691;break;case 8:e+=s(t,r,f)+l+2053994217;break;case 9:e+=i(t,r,f)+l+0;break;default:throw new Error("Bogus round number")}e=n(e,c)+h,r=n(r,10),e&=4294967295,t&=4294967295,r&=4294967295,f&=4294967295,h&=4294967295;var p=[];return p[0]=e,p[1]=t,p[2]=r,p[3]=f,p[4]=h,p[5]=l,p[6]=c,p}function h(e,t){var r,n,i,s=[],a=[];for(n=0;n<5;n++)s[n]=new Number(e[n]),a[n]=new Number(e[n]);var o=0;for(i=0;i<5;i++)for(n=0;n<16;n++)r=f(s[(o+0)%5],s[(o+1)%5],s[(o+2)%5],s[(o+3)%5],s[(o+4)%5],t[m[i][n]],g[i][n],i),s[(o+0)%5]=r[0],s[(o+1)%5]=r[1],s[(o+2)%5]=r[2],s[(o+3)%5]=r[3],s[(o+4)%5]=r[4],o+=4;for(o=0,i=5;i<10;i++)for(n=0;n<16;n++)r=f(a[(o+0)%5],a[(o+1)%5],a[(o+2)%5],a[(o+3)%5],a[(o+4)%5],t[m[i][n]],g[i][n],i),a[(o+0)%5]=r[0],a[(o+1)%5]=r[1],a[(o+2)%5]=r[2],a[(o+3)%5]=r[3],a[(o+4)%5]=r[4],o+=4;a[3]+=s[2]+e[1],e[1]=e[2]+s[3]+a[4],e[2]=e[3]+s[4]+a[0],e[3]=e[4]+s[0]+a[1],e[4]=e[0]+s[1]+a[2],e[0]=a[3]}function l(e){for(var t=0;t<16;t++)e[t]=0}function c(e){var t=(255&e.charCodeAt(3))<<24;return t|=(255&e.charCodeAt(2))<<16,t|=(255&e.charCodeAt(1))<<8,t|=255&e.charCodeAt(0)}function d(e){var t,r,n=new Array(y/32),i=new Array(y/8);!function(e){e[0]=1732584193,e[1]=4023233417,e[2]=2562383102,e[3]=271733878,e[4]=3285377520}(n),t=e.length;var s=new Array(16);l(s);var a,o=0;for(r=t;r>63;r-=64){for(a=0;a<16;a++)s[a]=c(e.substr(o,4)),o+=4;h(n,s)}for(function(e,t,r,n){var i=new Array(16);l(i);for(var s=0,a=0;a<(63&r);a++)i[a>>>2]^=(255&t.charCodeAt(s++))<<8*(3&a);i[r>>>2&15]^=1<<8*(3&r)+7,(63&r)>55&&(h(e,i),l(i=new Array(16))),i[14]=r<<3,i[15]=r>>>29|n<<3,h(e,i)}(n,e.substr(o),t,0),a=0;a>>2],i[a+1]=n[a>>>2]>>>8&255,i[a+2]=n[a>>>2]>>>16&255,i[a+3]=n[a>>>2]>>>24&255;return i}Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){for(var t=d(p.default.Uint8Array2str(e)),r="",n=0;n(r=e.charCodeAt(n))?o.push(r):2048>r?(o.push(192|r>>>6),o.push(128|63&r)):55296>r||57344<=r?o.push(224|r>>>12,128|r>>>6&63,128|63&r):(n+=1,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),o.push(240|r>>>18,128|r>>>12&63,128|r>>>6&63,128|63&r)),i=0;i>>2;a.length<=s;)a.push(0);a[s]|=o[i]<<24-u%4*8,u+=1}else if("UTF16BE"===t||"UTF16LE"===t)for(n=0;n>8),s=u>>>2;a.length<=s;)a.push(0);a[s]|=r<<16-u%4*8,u+=2}return{value:a,binLen:8*u}}function s(e){var t,r,n,i=[],s=e.length;if(0!=s%2)throw"String of HEX type must be in byte increments";for(t=0;t>>3;i.length<=n;)i.push(0);i[t>>>3]|=r<<24-t%8*4}return{value:i,binLen:4*s}}function a(e){var t,r,n,i=[];for(r=0;r>>2,i.length<=n&&i.push(0),i[n]|=t<<24-r%4*8;return{value:i,binLen:8*e.length}}function o(e){var t,r,n,i,s,a,o=[],u=0;if(-1===e.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";if(s=e.indexOf("="),e=e.replace(/\=/g,""),-1!==s&&s>2&63)),r=(3&i)<<4):1===u?(a.push(n.charAt(r|i>>4&15)),r=(15&i)<<2):2===u&&(a.push(n.charAt(r|i>>6&3)),(o+=1)%60==0&&a.push("\n"),a.push(n.charAt(63&i))),(o+=1)%60==0&&a.push("\n"),3===(u+=1)&&(u=0);if(u>0&&(a.push(n.charAt(r)),(o+=1)%60==0&&a.push("\n"),a.push("="),o+=1),1===u&&(o%60==0&&a.push("\n"),a.push("=")),!t)return a.join("")},decode:function(e){var t,r,i=[],s=0,a=0,o=e.length;for(r=0;r=0&&(s&&i.push(a|t>>6-s&255),a=t<<(s=s+2&7)&255);return new Uint8Array(i)}}},{}],35:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default={s2k:{simple:0,salted:1,iterated:3,gnu:101},publicKey:{rsa_encrypt_sign:1,rsa_encrypt:2,rsa_sign:3,elgamal:16,dsa:17},symmetric:{plaintext:0,idea:1,tripledes:2,cast5:3,blowfish:4,aes128:7,aes192:8,aes256:9,twofish:10},compression:{uncompressed:0,zip:1,zlib:2,bzip2:3},hash:{md5:1,sha1:2,ripemd:3,sha256:8,sha384:9,sha512:10,sha224:11},packet:{publicKeyEncryptedSessionKey:1,signature:2,symEncryptedSessionKey:3,onePassSignature:4,secretKey:5,publicKey:6,secretSubkey:7,compressed:8,symmetricallyEncrypted:9,marker:10,literal:11,trust:12,userid:13,publicSubkey:14,userAttribute:17,symEncryptedIntegrityProtected:18,modificationDetectionCode:19,symEncryptedAEADProtected:20},literal:{binary:"b".charCodeAt(),text:"t".charCodeAt(),utf8:"u".charCodeAt()},signature:{binary:0,text:1,standalone:2,cert_generic:16,cert_persona:17,cert_casual:18,cert_positive:19,cert_revocation:48,subkey_binding:24,key_binding:25,key:31,key_revocation:32,subkey_revocation:40,timestamp:64,third_party:80},signatureSubpacket:{signature_creation_time:2,signature_expiration_time:3,exportable_certification:4,trust_signature:5,regular_expression:6,revocable:7,key_expiration_time:9,placeholder_backwards_compatibility:10,preferred_symmetric_algorithms:11,revocation_key:12,issuer:16,notation_data:20,preferred_hash_algorithms:21,preferred_compression_algorithms:22,key_server_preferences:23,preferred_key_server:24,primary_user_id:25,policy_uri:26,key_flags:27,signers_user_id:28,reason_for_revocation:29,features:30,signature_target:31,embedded_signature:32},keyFlags:{certify_keys:1,sign_data:2,encrypt_communication:4,encrypt_storage:8,split_private_key:16,authentication:32,shared_private_key:128},keyStatus:{invalid:0,expired:1,revoked:2,valid:3,no_self_cert:4},armor:{multipart_section:0,multipart_last:1,signed:2,message:3,public_key:4,private_key:5,signature:6},write:function(e,t){if("number"==typeof t&&(t=this.read(e,t)),void 0!==e[t])return e[t];throw new Error("Invalid enum value.")},read:function(e,t){for(var r in e)if(e[r]===parseInt(t))return r;throw new Error("Invalid enum value.")}}},{}],36:[function(e,t,r){"use strict";function n(t){this._baseUrl=t||i.default.keyserver,this._fetch="undefined"!=typeof window?window.fetch:e("node-fetch")}Object.defineProperty(r,"__esModule",{value:!0}),r.default=n;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("./config"));n.prototype.lookup=function(e){var t=this._baseUrl+"/pks/lookup?op=get&options=mr&search=",r=this._fetch;if(e.keyId)t+="0x"+encodeURIComponent(e.keyId);else{if(!e.query)throw new Error("You must provide a query parameter!");t+=encodeURIComponent(e.query)}return r(t).then(function(e){if(200===e.status)return e.text()}).then(function(e){if(e&&!(e.indexOf("-----END PGP PUBLIC KEY BLOCK-----")<0))return e.trim()})},n.prototype.upload=function(e){var t=this._baseUrl+"/pks/add";return(0,this._fetch)(t,{method:"post",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:"keytext="+encodeURIComponent(e)})}},{"./config":10,"node-fetch":"node-fetch"}],37:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(r,"__esModule",{value:!0}),r.HKP=r.AsyncProxy=r.Keyring=r.crypto=r.config=r.enums=r.armor=r.Keyid=r.S2K=r.MPI=r.packet=r.util=r.cleartext=r.message=r.signature=r.key=void 0;var s=e("./openpgp");Object.keys(s).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(r,e,{enumerable:!0,get:function(){return s[e]}})});var a=e("./util");Object.defineProperty(r,"util",{enumerable:!0,get:function(){return i(a).default}});var o=e("./packet");Object.defineProperty(r,"packet",{enumerable:!0,get:function(){return i(o).default}});var u=e("./type/mpi");Object.defineProperty(r,"MPI",{enumerable:!0,get:function(){return i(u).default}});var f=e("./type/s2k");Object.defineProperty(r,"S2K",{enumerable:!0,get:function(){return i(f).default}});var h=e("./type/keyid");Object.defineProperty(r,"Keyid",{enumerable:!0,get:function(){return i(h).default}});var l=e("./encoding/armor");Object.defineProperty(r,"armor",{enumerable:!0,get:function(){return i(l).default}});var c=e("./enums");Object.defineProperty(r,"enums",{enumerable:!0,get:function(){return i(c).default}});var d=e("./config/config");Object.defineProperty(r,"config",{enumerable:!0,get:function(){return i(d).default}});var p=e("./crypto");Object.defineProperty(r,"crypto",{enumerable:!0,get:function(){return i(p).default}});var y=e("./keyring");Object.defineProperty(r,"Keyring",{enumerable:!0,get:function(){return i(y).default}});var g=e("./worker/async_proxy");Object.defineProperty(r,"AsyncProxy",{enumerable:!0,get:function(){return i(g).default}});var m=e("./hkp");Object.defineProperty(r,"HKP",{enumerable:!0,get:function(){return i(m).default}});var v=n(s),w=n(e("./key")),b=n(e("./signature")),k=n(e("./message")),A=n(e("./cleartext"));r.default=v;r.key=w,r.signature=b,r.message=k,r.cleartext=A},{"./cleartext":5,"./config/config":9,"./crypto":24,"./encoding/armor":33,"./enums":35,"./hkp":36,"./key":38,"./keyring":39,"./message":42,"./openpgp":43,"./packet":47,"./signature":66,"./type/keyid":67,"./type/mpi":68,"./type/s2k":69,"./util":70,"./worker/async_proxy":71}],38:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(!(this instanceof i))return new i(e);if(this.primaryKey=null,this.revocationSignature=null,this.directSignatures=null,this.users=null,this.subKeys=null,this.packetlist2structure(e),!this.primaryKey||!this.users)throw new Error("Invalid key: need at least key and user ID packet")}function s(e,t){return e.algorithm!==p.default.read(p.default.publicKey,p.default.publicKey.dsa)&&e.algorithm!==p.default.read(p.default.publicKey,p.default.publicKey.rsa_sign)&&(!t.keyFlags||0!=(t.keyFlags[0]&p.default.keyFlags.encrypt_communication)||0!=(t.keyFlags[0]&p.default.keyFlags.encrypt_storage))}function a(e,t){return!(e.algorithm!==p.default.read(p.default.publicKey,p.default.publicKey.dsa)&&e.algorithm!==p.default.read(p.default.publicKey,p.default.publicKey.rsa_sign)&&e.algorithm!==p.default.read(p.default.publicKey,p.default.publicKey.rsa_encrypt_sign)||t.keyFlags&&0==(t.keyFlags[0]&p.default.keyFlags.sign_data))}function o(e,t){return 3===e.version&&0!==e.expirationTimeV3?new Date(e.created.getTime()+24*e.expirationTimeV3*3600*1e3):4===e.version&&!1===t.keyNeverExpires?new Date(e.created.getTime()+1e3*t.keyExpirationTime):null}function u(e,t,r,n){(e=e[r])&&(t[r]?e.forEach(function(e){e.isExpired()||n&&!n(e)||t[r].some(function(t){return m.default.equalsUint8Array(t.signature,e.signature)})||t[r].push(e)}):t[r]=e)}function f(e){if(!(this instanceof f))return new f(e);this.userId=e.tag===p.default.packet.userid?e:null,this.userAttribute=e.tag===p.default.packet.userAttribute?e:null,this.selfCertifications=null,this.otherCertifications=null,this.revocationCertifications=null}function h(e){if(!(this instanceof h))return new h(e);this.subKey=e,this.bindingSignatures=[],this.revocationSignature=null}function l(e){var t={};t.keys=[];try{var r=new d.default.List;r.read(e);var n=r.indexOfTag(p.default.packet.publicKey,p.default.packet.secretKey);if(0===n.length)throw new Error("No key packet found");for(var s=0;s0&&(o.keyExpirationTime=r.keyExpirationTime,o.keyNeverExpires=!1),o.sign(e,a),n.push(s),n.push(o)});var s={};s.key=e,s.bind=t;var a=new d.default.Signature;return a.signatureType=p.default.signature.subkey_binding,a.publicKeyAlgorithm=r.keyType,a.hashAlgorithm=g.default.prefer_hash_algorithm,a.keyFlags=[p.default.keyFlags.encrypt_communication|p.default.keyFlags.encrypt_storage],r.keyExpirationTime>0&&(a.keyExpirationTime=r.keyExpirationTime,a.keyNeverExpires=!1),a.sign(e,s),n.push(t),n.push(a),r.unlocked||(e.clearPrivateMPIs(),t.clearPrivateMPIs()),new i(n)}Object.defineProperty(r,"__esModule",{value:!0}),r.Key=i,r.read=l,r.readArmored=function(e){try{var t=y.default.decode(e);if(t.type!==p.default.armor.public_key&&t.type!==p.default.armor.private_key)throw new Error("Armored text not of type key");return l(t.data)}catch(e){var r={keys:[],err:[]};return r.err.push(e),r}},r.generate=function(e){var t,r;return Promise.resolve().then(function(){if(e.keyType=e.keyType||p.default.publicKey.rsa_encrypt_sign,e.keyType!==p.default.publicKey.rsa_encrypt_sign)throw new Error("Only RSA Encrypt or Sign supported");return e.passphrase||(e.unlocked=!0),(String.prototype.isPrototypeOf(e.userIds)||"string"==typeof e.userIds)&&(e.userIds=[e.userIds]),Promise.all([(t=new d.default.SecretKey,t.algorithm=p.default.read(p.default.publicKey,e.keyType),t.generate(e.numBits)),(r=new d.default.SecretSubkey,r.algorithm=p.default.read(p.default.publicKey,e.keyType),r.generate(e.numBits))]).then(function(){return c(t,r,e)})})},r.reformat=function(e){var t,r;return Promise.resolve().then(function(){if(e.keyType=e.keyType||p.default.publicKey.rsa_encrypt_sign,e.keyType!==p.default.publicKey.rsa_encrypt_sign)throw new Error("Only RSA Encrypt or Sign supported");if(!e.privateKey.decrypt())throw new Error("Key not decrypted");e.passphrase||(e.unlocked=!0),(String.prototype.isPrototypeOf(e.userIds)||"string"==typeof e.userIds)&&(e.userIds=[e.userIds]);for(var n=e.privateKey.toPacketlist(),i=0;i>r,n.count++})});var r={prio:0,algo:g.default.encryption_cipher};for(var n in t)try{n!==p.default.symmetric.plaintext&&n!==p.default.symmetric.idea&&p.default.read(p.default.symmetric,n)&&t[n].count===e.length&&t[n].prio>r.prio&&(r=t[n])}catch(e){}return r.algo};var d=n(e("./packet")),p=n(e("./enums.js")),y=n(e("./encoding/armor.js")),g=n(e("./config")),m=n(e("./util"));i.prototype.packetlist2structure=function(e){for(var t,r,n,i=0;i1&&void 0!==arguments[1]&&arguments[1],r=this.getPrimaryUser(t);if(r&&a(this.primaryKey,r.selfCertificate)&&(!e||this.primaryKey.getKeyId().equals(e))&&this.verifyPrimaryKey(t)===p.default.keyStatus.valid)return this.primaryKey;if(this.subKeys)for(var n=0;n0&&void 0!==arguments[0]&&arguments[0];if(this.revocationSignature&&!this.revocationSignature.isExpired()&&(this.revocationSignature.verified||this.revocationSignature.verify(this.primaryKey,{key:this.primaryKey})))return p.default.keyStatus.revoked;if(!e&&3===this.primaryKey.version&&0!==this.primaryKey.expirationTimeV3&&Date.now()>this.primaryKey.created.getTime()+24*this.primaryKey.expirationTimeV3*3600*1e3)return p.default.keyStatus.expired;for(var t=!1,r=0;rthis.primaryKey.created.getTime()+1e3*n.selfCertificate.keyExpirationTime?p.default.keyStatus.expired:p.default.keyStatus.valid:p.default.keyStatus.invalid},i.prototype.getExpirationTime=function(){if(3===this.primaryKey.version)return o(this.primaryKey);if(4===this.primaryKey.version){var e=this.getPrimaryUser();return e?o(this.primaryKey,e.selfCertificate):null}},i.prototype.getPrimaryUser=function(){for(var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=[],r=0;rt.selfCertificate.isPrimaryUserID?-1:e.selfCertificate.isPrimaryUserIDt.selfCertificate.created?-1:e.selfCertificate.created2&&void 0!==arguments[2]&&arguments[2];return!this.isRevoked(t,e)&&!(t.isExpired()&&!r||!t.verified&&!t.verify(e,{userid:this.userId||this.userAttribute,key:e}))},f.prototype.sign=function(e,t){var r,n,i,s;return n={},n.key=e,n.userid=this.userId||this.userAttribute,r=new f(this.userId||this.userAttribute),r.otherCertifications=[],t.forEach(function(t){if(t.isPublic())throw new Error("Need private key for signing");if(t.primaryKey.getFingerprint()===e.getFingerprint())throw new Error("Not implemented for self signing");if(!(i=t.getSigningKeyPacket()))throw new Error("Could not find valid signing key packet");if(!i.isDecrypted)throw new Error("Private key is not decrypted.");(s=new d.default.Signature).signatureType=p.default.write(p.default.signature,p.default.signature.cert_generic),s.keyFlags=[p.default.keyFlags.certify_keys|p.default.keyFlags.sign_data],s.hashAlgorithm=t.getPreferredHashAlgorithm(),s.publicKeyAlgorithm=i.algorithm,s.signingKeyId=i.getKeyId(),s.sign(i,n),r.otherCertifications.push(s)}),r.update(this,e),r},f.prototype.verifyAllSignatures=function(e,t){var r={userid:this.userId||this.userAttribute,key:e};return this.selfCertifications.concat(this.otherCertifications||[]).map(function(e){var n=t.filter(function(t){return t.getSigningKeyPacket(e.issuerKeyId)}),i=null;return n.length>0&&(i=n.some(function(t){return e.verify(t.primaryKey,r)})),{keyid:e.issuerKeyId,valid:i}})},f.prototype.verify=function(e){if(!this.selfCertifications)return p.default.keyStatus.no_self_cert;for(var t,r=0;r1&&void 0!==arguments[1]&&arguments[1];if(this.verify(e,t)!==p.default.keyStatus.valid)return!1;for(var r=0;r1&&void 0!==arguments[1]&&arguments[1];if(this.revocationSignature&&!this.revocationSignature.isExpired()&&(this.revocationSignature.verified||this.revocationSignature.verify(e,{key:e,bind:this.subKey})))return p.default.keyStatus.revoked;if(!t&&3===this.subKey.version&&0!==this.subKey.expirationTimeV3&&Date.now()>this.subKey.created.getTime()+24*this.subKey.expirationTimeV3*3600*1e3)return p.default.keyStatus.expired;for(var r=0;rthis.subKey.created.getTime()+1e3*i.keyExpirationTime))return p.default.keyStatus.valid;if(n)return p.default.keyStatus.expired}else if(n)return p.default.keyStatus.invalid}else if(n)return p.default.keyStatus.expired}return p.default.keyStatus.invalid},h.prototype.getExpirationTime=function(){for(var e,t=0;te)&&(e=r)}return e},h.prototype.update=function(e,t){if(e.verify(t)!==p.default.keyStatus.invalid){if(this.subKey.getFingerprint()!==e.subKey.getFingerprint())throw new Error("SubKey update method: fingerprints of subkeys not equal");if(this.subKey.tag===p.default.packet.publicSubkey&&e.subKey.tag===p.default.packet.secretSubkey&&(this.subKey=e.subKey),this.bindingSignatures.length"),i=t.getUserIds(),s=0;s0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=new h.default.List,n=this.packets.findPacket(l.default.packet.literal);if(!n)throw new Error("No literal data packet to sign.");var i,a,o,u,f=l.default.write(l.default.literal,n.format)===l.default.literal.binary?l.default.signature.binary:l.default.signature.text;if(t&&(o=t.packets.filterByTag(l.default.packet.signature)).length)for(i=o.length-1;i>=0;i--){var c=o[i];(u=new h.default.OnePassSignature).type=f,u.hashAlgorithm=d.default.prefer_hash_algorithm,u.publicKeyAlgorithm=c.publicKeyAlgorithm,u.signingKeyId=c.issuerKeyId,e.length||0!==i||(u.flags=1),r.push(u)}for(i=0;i=0;i--){var p=new h.default.Signature;if(p.signatureType=f,p.hashAlgorithm=d.default.prefer_hash_algorithm,p.publicKeyAlgorithm=a.algorithm,!a.isDecrypted)throw new Error("Private key is not decrypted.");p.sign(a,n),r.push(p)}return t&&r.concat(o),new s(r)},s.prototype.signDetached=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=new h.default.List,n=this.packets.findPacket(l.default.packet.literal);if(!n)throw new Error("No literal data packet to sign.");for(var i=l.default.write(l.default.literal,n.format)===l.default.literal.binary?l.default.signature.binary:l.default.signature.text,s=0;s0&&(e.name+=" "),e.name+"<"+e.email+">"}),e):e}function u(e){return e&&!g.default.isArray(e)&&(e=[e]),e}function f(e,t){return new Promise(function(t){return t(e())}).catch(h.bind(null,t))}function h(e,t){throw y.default.debug&&console.error(t.stack),t.message=e+": "+t.message,t}function l(){return g.default.getWebCrypto()&&y.default.aead_protect}Object.defineProperty(r,"__esModule",{value:!0}),r.initWorker=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,r=void 0===t?"openpgp.worker.min.js":t,n=e.worker;if(n||"undefined"!=typeof window&&window.Worker)return v=new m.default({path:r,worker:n,config:y.default}),!0},r.getWorker=function(){return v},r.destroyWorker=function(){v=void 0},r.generateKey=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.userIds,r=void 0===t?[]:t,n=e.passphrase,i=e.numBits,s=void 0===i?2048:i,a=e.unlocked,u=void 0!==a&&a,f=e.keyExpirationTime,l=o({userIds:r,passphrase:n,numBits:s,unlocked:u,keyExpirationTime:void 0===f?0:f});return!g.default.getWebCryptoAll()&&v?v.delegate("generateKey",l):p.generate(l).then(function(e){return{key:e,privateKeyArmored:e.armor(),publicKeyArmored:e.toPublic().armor()}}).catch(h.bind(null,"Error generating keypair"))},r.reformatKey=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.privateKey,r=e.userIds,n=void 0===r?[]:r,i=e.passphrase,s=void 0===i?"":i,a=e.unlocked,u=void 0!==a&&a,f=e.keyExpirationTime,l=o({privateKey:t,userIds:n,passphrase:s,unlocked:u,keyExpirationTime:void 0===f?0:f});return v?v.delegate("reformatKey",l):p.reformat(l).then(function(e){return{key:e,privateKeyArmored:e.armor(),publicKeyArmored:e.toPublic().armor()}}).catch(h.bind(null,"Error reformatting keypair"))},r.decryptKey=function(e){var t=e.privateKey,r=e.passphrase;return v?v.delegate("decryptKey",{privateKey:t,passphrase:r}):f(function(){if(!t.decrypt(r))throw new Error("Invalid passphrase");return{key:t}},"Error decrypting private key")},r.encrypt=function(e){var t=e.data,r=e.publicKeys,n=e.privateKeys,i=e.passwords,a=e.sessionKey,o=e.filename,f=e.armor,d=void 0===f||f,p=e.detached,y=void 0!==p&&p,m=e.signature,w=void 0===m?null:m,b=e.returnSessionKey,k=void 0!==b&&b;if(s(t),r=u(r),n=u(n),i=u(i),!l()&&v)return v.delegate("encrypt",{data:t,publicKeys:r,privateKeys:n,passwords:i,sessionKey:a,filename:o,armor:d,detached:y,signature:w,returnSessionKey:k});var A={};return Promise.resolve().then(function(){var e=function(e,t){var r=void 0;if(g.default.isUint8Array(e))r=c.fromBinary(e,t);else{if(!g.default.isString(e))throw new Error("Data must be of type String or Uint8Array");r=c.fromText(e,t)}return r}(t,o);if(n||(n=[]),n.length||w)if(y){var s=e.signDetached(n,w);A.signature=d?s.armor():s}else e=e.sign(n,w);return e.encrypt(r,i,a)}).then(function(e){return d?A.data=e.message.armor():A.message=e.message,k&&(A.sessionKey=e.sessionKey),A}).catch(h.bind(null,"Error encrypting message"))},r.decrypt=function(e){var t=e.message,r=e.privateKey,n=e.publicKeys,i=e.sessionKey,s=e.password,o=e.format,f=void 0===o?"utf8":o,c=e.signature,d=void 0===c?null:c;return a(t),n=u(n),!l()&&v?v.delegate("decrypt",{message:t,privateKey:r,publicKeys:n,sessionKey:i,password:s,format:f,signature:d}):t.decrypt(r,i,s).then(function(e){var t=function(e,t){if("binary"===t)return{data:e.getLiteralData(),filename:e.getFilename()};if("utf8"===t)return{data:e.getText(),filename:e.getFilename()};throw new Error("Invalid format")}(e,f);return n||(n=[]),t.signatures=d?e.verifyDetached(d,n):e.verify(n),t}).catch(h.bind(null,"Error decrypting message"))},r.sign=function(e){var t=e.data,r=e.privateKeys,n=e.armor,i=void 0===n||n,a=e.detached,o=void 0!==a&&a;if(s(t),r=u(r),v)return v.delegate("sign",{data:t,privateKeys:r,armor:i,detached:o});var h={};return f(function(){var e;if(e=g.default.isString(t)?new d.CleartextMessage(t):c.fromBinary(t),o){var n=e.signDetached(r);h.signature=i?n.armor():n}else e=e.sign(r),i?h.data=e.armor():h.message=e;return h},"Error signing cleartext message")},r.verify=function(e){var t=e.message,r=e.publicKeys,n=e.signature,i=void 0===n?null:n;if(function(e){if(!d.CleartextMessage.prototype.isPrototypeOf(e)&&!c.Message.prototype.isPrototypeOf(e))throw new Error("Parameter [message] needs to be of type Message or CleartextMessage")}(t),r=u(r),v)return v.delegate("verify",{message:t,publicKeys:r,signature:i});var s={};return f(function(){return d.CleartextMessage.prototype.isPrototypeOf(t)?s.data=t.getText():s.data=t.getLiteralData(),s.signatures=i?t.verifyDetached(i,r):t.verify(r),s},"Error verifying cleartext signed message")},r.encryptSessionKey=function(e){var t=e.data,r=e.algorithm,n=e.publicKeys,i=e.passwords;return function(e,t){if(!g.default.isUint8Array(e))throw new Error("Parameter ["+(t||"data")+"] must be of type Uint8Array")}(t),function(e,t){if(!g.default.isString(e))throw new Error("Parameter ["+(t||"data")+"] must be of type String")}(r,"algorithm"),n=u(n),i=u(i),v?v.delegate("encryptSessionKey",{data:t,algorithm:r,publicKeys:n,passwords:i}):f(function(){return{message:c.encryptSessionKey(t,r,n,i)}},"Error encrypting session key")},r.decryptSessionKey=function(e){var t=e.message,r=e.privateKey,n=e.password;return a(t),v?v.delegate("decryptSessionKey",{message:t,privateKey:r,password:n}):f(function(){return t.decryptSessionKey(r,n)},"Error decrypting session key")};var c=i(e("./message.js")),d=i(e("./cleartext.js")),p=i(e("./key.js")),y=n(e("./config/config.js")),g=n(e("./util")),m=n(e("./worker/async_proxy.js"));n(e("es6-promise")).default.polyfill();var v=void 0},{"./cleartext.js":5,"./config/config.js":9,"./key.js":38,"./message.js":42,"./util":70,"./worker/async_proxy.js":71,"es6-promise":2}],44:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return new(_[function(e){return e.substr(0,1).toUpperCase()+e.substr(1)}(e)])}Object.defineProperty(r,"__esModule",{value:!0}),r.Trust=r.Signature=r.SecretSubkey=r.Userid=r.SecretKey=r.OnePassSignature=r.UserAttribute=r.PublicSubkey=r.Marker=r.SymmetricallyEncrypted=r.PublicKey=r.Literal=r.SymEncryptedSessionKey=r.PublicKeyEncryptedSessionKey=r.SymEncryptedAEADProtected=r.SymEncryptedIntegrityProtected=r.Compressed=void 0;var s=e("./compressed.js");Object.defineProperty(r,"Compressed",{enumerable:!0,get:function(){return n(s).default}});var a=e("./sym_encrypted_integrity_protected.js");Object.defineProperty(r,"SymEncryptedIntegrityProtected",{enumerable:!0,get:function(){return n(a).default}});var o=e("./sym_encrypted_aead_protected.js");Object.defineProperty(r,"SymEncryptedAEADProtected",{enumerable:!0,get:function(){return n(o).default}});var u=e("./public_key_encrypted_session_key.js");Object.defineProperty(r,"PublicKeyEncryptedSessionKey",{enumerable:!0,get:function(){return n(u).default}});var f=e("./sym_encrypted_session_key.js");Object.defineProperty(r,"SymEncryptedSessionKey",{enumerable:!0,get:function(){return n(f).default}});var h=e("./literal.js");Object.defineProperty(r,"Literal",{enumerable:!0,get:function(){return n(h).default}});var l=e("./public_key.js");Object.defineProperty(r,"PublicKey",{enumerable:!0,get:function(){return n(l).default}});var c=e("./symmetrically_encrypted.js");Object.defineProperty(r,"SymmetricallyEncrypted",{enumerable:!0,get:function(){return n(c).default}});var d=e("./marker.js");Object.defineProperty(r,"Marker",{enumerable:!0,get:function(){return n(d).default}});var p=e("./public_subkey.js");Object.defineProperty(r,"PublicSubkey",{enumerable:!0,get:function(){return n(p).default}});var y=e("./user_attribute.js");Object.defineProperty(r,"UserAttribute",{enumerable:!0,get:function(){return n(y).default}});var g=e("./one_pass_signature.js");Object.defineProperty(r,"OnePassSignature",{enumerable:!0,get:function(){return n(g).default}});var m=e("./secret_key.js");Object.defineProperty(r,"SecretKey",{enumerable:!0,get:function(){return n(m).default}});var v=e("./userid.js");Object.defineProperty(r,"Userid",{enumerable:!0,get:function(){return n(v).default}});var w=e("./secret_subkey.js");Object.defineProperty(r,"SecretSubkey",{enumerable:!0,get:function(){return n(w).default}});var b=e("./signature.js");Object.defineProperty(r,"Signature",{enumerable:!0,get:function(){return n(b).default}});var k=e("./trust.js");Object.defineProperty(r,"Trust",{enumerable:!0,get:function(){return n(k).default}}),r.newPacketFromTag=i,r.fromStructuredClone=function(e){var t=i(A.default.read(A.default.packet,e.tag));for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t.postCloneTypeFix&&t.postCloneTypeFix(),t};var A=n(e("../enums.js")),_=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./all_packets.js"))},{"../enums.js":35,"./all_packets.js":44,"./compressed.js":46,"./literal.js":48,"./marker.js":49,"./one_pass_signature.js":50,"./public_key.js":53,"./public_key_encrypted_session_key.js":54,"./public_subkey.js":55,"./secret_key.js":56,"./secret_subkey.js":57,"./signature.js":58,"./sym_encrypted_aead_protected.js":59,"./sym_encrypted_integrity_protected.js":60,"./sym_encrypted_session_key.js":61,"./symmetrically_encrypted.js":62,"./trust.js":63,"./user_attribute.js":64,"./userid.js":65}],45:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function s(e){var t=l.default.fromStructuredClone(e);return new o.Key(t)}function a(e){return e.keyid=c.default.fromClone(e.keyid),e.signature=new h.Signature(e.signature),e}Object.defineProperty(r,"__esModule",{value:!0}),r.clonePackets=function(e){return e.publicKeys&&(e.publicKeys=e.publicKeys.map(function(e){return e.toPacketlist()})),e.privateKeys&&(e.privateKeys=e.privateKeys.map(function(e){return e.toPacketlist()})),e.privateKey&&(e.privateKey=e.privateKey.toPacketlist()),e.key&&(e.key=e.key.toPacketlist()),e.message&&(e.message instanceof u.Message?e.message=e.message.packets:e.message instanceof f.CleartextMessage&&(e.message.signature=e.message.signature.packets)),e.signature&&e.signature instanceof h.Signature&&(e.signature=e.signature.packets),e.signatures&&(e.signatures=e.signatures.map(function(e){return function(e){return e.signature=e.signature.packets,e}(e)})),e},r.parseClonedPackets=function(e,t){return e.publicKeys&&(e.publicKeys=e.publicKeys.map(s)),e.privateKeys&&(e.privateKeys=e.privateKeys.map(s)),e.privateKey&&(e.privateKey=s(e.privateKey)),e.key&&(e.key=s(e.key)),e.message&&e.message.signature?e.message=function(e){var t=l.default.fromStructuredClone(e.signature);return new f.CleartextMessage(e.text,new h.Signature(t))}(e.message):e.message&&(e.message=function(e){var t=l.default.fromStructuredClone(e);return new u.Message(t)}(e.message)),e.signatures&&(e.signatures=e.signatures.map(a)),e.signature&&(e.signature=function(e){if("string"==typeof e)return e;var t=l.default.fromStructuredClone(e);return new h.Signature(t)}(e.signature)),e};var o=i(e("../key.js")),u=i(e("../message.js")),f=i(e("../cleartext.js")),h=i(e("../signature.js")),l=n(e("./packetlist.js")),c=n(e("../type/keyid.js"))},{"../cleartext.js":5,"../key.js":38,"../message.js":42,"../signature.js":66,"../type/keyid.js":67,"./packetlist.js":52}],46:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=s.default.packet.compressed,this.packets=null,this.algorithm="zip",this.compressed=null}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../enums.js")),a=n(e("../util.js")),o=n(e("../compression/zlib.min.js")),u=n(e("../compression/rawinflate.min.js")),f=n(e("../compression/rawdeflate.min.js"));i.prototype.read=function(e){this.algorithm=s.default.read(s.default.compression,e[0]),this.compressed=e.subarray(1,e.length),this.decompress()},i.prototype.write=function(){return null===this.compressed&&this.compress(),a.default.concatUint8Array(new Uint8Array([s.default.write(s.default.compression,this.algorithm)]),this.compressed)},i.prototype.decompress=function(){var e;switch(this.algorithm){case"uncompressed":e=this.compressed;break;case"zip":e=new u.default.Zlib.RawInflate(this.compressed).decompress();break;case"zlib":e=new o.default.Zlib.Inflate(this.compressed).decompress();break;case"bzip2":throw new Error("Compression algorithm BZip2 [BZ2] is not implemented.");default:throw new Error("Compression algorithm unknown :"+this.algorithm)}this.packets.read(e)},i.prototype.compress=function(){var e,t;switch(e=this.packets.write(),this.algorithm){case"uncompressed":this.compressed=e;break;case"zip":t=new f.default.Zlib.RawDeflate(e),this.compressed=t.compress();break;case"zlib":t=new o.default.Zlib.Deflate(e),this.compressed=t.compress();break;case"bzip2":throw new Error("Compression algorithm BZip2 [BZ2] is not implemented.");default:throw new Error("Compression algorithm unknown :"+this.type)}}},{"../compression/rawdeflate.min.js":6,"../compression/rawinflate.min.js":7,"../compression/zlib.min.js":8,"../enums.js":35,"../util.js":70}],47:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("./all_packets.js")),s=n(e("./clone.js")),a={List:function(e){return e&&e.__esModule?e:{default:e}}(e("./packetlist.js")).default,clone:s};for(var o in i)a[o]=i[o];r.default=a},{"./all_packets.js":44,"./clone.js":45,"./packetlist.js":52}],48:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=a.default.packet.literal,this.format="utf8",this.date=new Date,this.data=new Uint8Array(0),this.filename="msg.txt"}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util.js")),a=n(e("../enums.js"));i.prototype.setText=function(e){e=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\n/g,"\r\n"),this.data="utf8"===this.format?s.default.str2Uint8Array(s.default.encode_utf8(e)):s.default.str2Uint8Array(e)},i.prototype.getText=function(){return s.default.decode_utf8(s.default.Uint8Array2str(this.data)).replace(/\r\n/g,"\n")},i.prototype.setBytes=function(e,t){this.format=t,this.data=e},i.prototype.getBytes=function(){return this.data},i.prototype.setFilename=function(e){this.filename=e},i.prototype.getFilename=function(){return this.filename},i.prototype.read=function(e){var t=a.default.read(a.default.literal,e[0]),r=e[1];this.filename=s.default.decode_utf8(s.default.Uint8Array2str(e.subarray(2,2+r))),this.date=s.default.readDate(e.subarray(2+r,2+r+4));var n=e.subarray(6+r,e.length);this.setBytes(n,t)},i.prototype.write=function(){var e=s.default.str2Uint8Array(s.default.encode_utf8(this.filename)),t=new Uint8Array([e.length]),r=new Uint8Array([a.default.write(a.default.literal,this.format)]),n=s.default.writeDate(this.date),i=this.getBytes();return s.default.concatUint8Array([r,t,e,n,i])}},{"../enums.js":35,"../util.js":70}],49:[function(e,t,r){"use strict";function n(){this.tag=i.default.packet.marker}Object.defineProperty(r,"__esModule",{value:!0}),r.default=n;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("../enums.js"));n.prototype.read=function(e){return 80===e[0]&&71===e[1]&&80===e[2]}},{"../enums.js":35}],50:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=a.default.packet.onePassSignature,this.version=null,this.type=null,this.hashAlgorithm=null,this.publicKeyAlgorithm=null,this.signingKeyId=null,this.flags=null}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util.js")),a=n(e("../enums.js")),o=n(e("../type/keyid.js"));i.prototype.read=function(e){var t=0;return this.version=e[t++],this.type=a.default.read(a.default.signature,e[t++]),this.hashAlgorithm=a.default.read(a.default.hash,e[t++]),this.publicKeyAlgorithm=a.default.read(a.default.publicKey,e[t++]),this.signingKeyId=new o.default,this.signingKeyId.read(e.subarray(t,t+8)),t+=8,this.flags=e[t++],this},i.prototype.write=function(){var e=new Uint8Array([3,a.default.write(a.default.signature,this.type),a.default.write(a.default.hash,this.hashAlgorithm),a.default.write(a.default.publicKey,this.publicKeyAlgorithm)]),t=new Uint8Array([this.flags]);return s.default.concatUint8Array([e,this.signingKeyId.write(),t])},i.prototype.postCloneTypeFix=function(){this.signingKeyId=o.default.fromClone(this.signingKeyId)}},{"../enums.js":35,"../type/keyid.js":67,"../util.js":70}],51:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(e){return e&&e.__esModule?e:{default:e}}(e("../util.js"));r.default={readSimpleLength:function(e){var t,r=0,i=e[0];return i<192?(r=e[0],t=1):i<255?(r=(e[0]-192<<8)+e[1]+192,t=2):255===i&&(r=n.default.readNumber(e.subarray(1,5)),t=5),{len:r,offset:t}},writeSimpleLength:function(e){return e<192?new Uint8Array([e]):e>191&&e<8384?new Uint8Array([192+(e-192>>8),e-192&255]):n.default.concatUint8Array([new Uint8Array([255]),n.default.writeNumber(e,4)])},writeHeader:function(e,t){return n.default.concatUint8Array([new Uint8Array([192|e]),this.writeSimpleLength(t)])},writeOldHeader:function(e,t){return t<256?new Uint8Array([128|e<<2,t]):t<65536?n.default.concatUint8Array([new Uint8Array([129|e<<2]),n.default.writeNumber(t,2)]):n.default.concatUint8Array([new Uint8Array([130|e<<2]),n.default.writeNumber(t,4)])},read:function(e,t,r){if(null===e||e.length<=t||e.subarray(t,e.length).length<2||0==(128&e[t]))throw new Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");var i,s=t,a=-1,o=-1;o=0,0!=(64&e[s])&&(o=1);var u;o?a=63&e[s]:(a=(63&e[s])>>2,u=3&e[s]),s++;var f=null,h=-1;if(o)if(e[s]<192)i=e[s++],n.default.print_debug("1 byte length:"+i);else if(e[s]>=192&&e[s]<224)i=(e[s++]-192<<8)+e[s++]+192,n.default.print_debug("2 byte length:"+i);else if(e[s]>223&&e[s]<255){i=1<<(31&e[s++]),n.default.print_debug("4 byte length:"+i);var l=s+i;f=[e.subarray(s,s+i)];for(var c;;){if(e[l]<192){i+=c=e[l++],f.push(e.subarray(l,l+c)),l+=c;break}if(e[l]>=192&&e[l]<224){i+=c=(e[l++]-192<<8)+e[l++]+192,f.push(e.subarray(l,l+c)),l+=c;break}if(!(e[l]>223&&e[l]<255)){l++,c=e[l++]<<24|e[l++]<<16|e[l++]<<8|e[l++],f.push(e.subarray(l,l+c)),i+=c,l+=c;break}i+=c=1<<(31&e[l++]),f.push(e.subarray(l,l+c)),l+=c}h=l-s}else s++,i=e[s++]<<24|e[s++]<<16|e[s++]<<8|e[s++];else switch(u){case 0:i=e[s++];break;case 1:i=e[s++]<<8|e[s++];break;case 2:i=e[s++]<<24|e[s++]<<16|e[s++]<<8|e[s++];break;default:i=r}return-1===h&&(h=i),null===f?f=e.subarray(s,s+h):f instanceof Array&&(f=n.default.concatUint8Array(f)),{tag:a,packet:f,offset:s+h}}}},{"../util.js":70}],52:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.length=0}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util")),a=n(e("./packet.js")),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./all_packets.js")),u=n(e("../enums.js")),f=n(e("../config"));i.prototype.read=function(e){for(var t=0;tn.length)throw new Error("Error reading MPI @:"+i);return i+6}throw new Error("Version "+this.version+" of the key packet is unsupported.")},i.prototype.readPublicKey=i.prototype.read,i.prototype.write=function(){var e=[];e.push(new Uint8Array([this.version])),e.push(s.default.writeDate(this.created)),3===this.version&&e.push(s.default.writeNumber(this.expirationTimeV3,2)),e.push(new Uint8Array([u.default.write(u.default.publicKey,this.algorithm)]));for(var t=f.default.getPublicMpiCount(this.algorithm),r=0;r0&&n<4?l=1:17===n&&(l=2);for(var c=[],d=0,p=0;pthis.created.getTime()+1e3*this.signatureExpirationTime},i.prototype.postCloneTypeFix=function(){this.issuerKeyId=l.default.fromClone(this.issuerKeyId)}},{"../crypto":24,"../enums.js":35,"../type/keyid.js":67,"../type/mpi.js":68,"../util.js":70,"./packet.js":51}],59:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=o.default.packet.symEncryptedAEADProtected,this.version=u,this.iv=null,this.encrypted=null,this.packets=null}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util.js")),a=n(e("../crypto")),o=n(e("../enums.js")),u=1,f=a.default.gcm.ivLength;i.prototype.read=function(e){var t=0;if(e[t]!==u)throw new Error("Invalid packet version.");t++,this.iv=e.subarray(t,f+t),t+=f,this.encrypted=e.subarray(t,e.length)},i.prototype.write=function(){return s.default.concatUint8Array([new Uint8Array([this.version]),this.iv,this.encrypted])},i.prototype.decrypt=function(e,t){var r=this;return a.default.gcm.decrypt(e,this.encrypted,t,this.iv).then(function(e){r.packets.read(e)})},i.prototype.encrypt=function(e,t){var r=this;return this.iv=a.default.random.getRandomValues(new Uint8Array(f)),a.default.gcm.encrypt(e,this.packets.write(),t,this.iv).then(function(e){r.encrypted=e})}},{"../crypto":24,"../enums.js":35,"../util.js":70}],60:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=f.default.packet.symEncryptedIntegrityProtected,this.version=d,this.encrypted=null,this.modification=!1,this.packets=null}function s(e,t,r,n){return l?function(e,t,r,n){n=new c(n);var i=new c(new Uint8Array(u.default.cipher[e].blockSize)),s=new l.createCipheriv("aes-"+e.substr(3,3)+"-cfb",n,i).update(new c(o.default.concatUint8Array([t,r])));return new Uint8Array(s)}(e,t,r,n):h.default.AES_CFB.encrypt(o.default.concatUint8Array([t,r]),n)}function a(e,t,r){var n=void 0;return(n=l?function(e,t,r){t=new c(t),r=new c(r);var n=new c(new Uint8Array(u.default.cipher[e].blockSize)),i=new l.createDecipheriv("aes-"+e.substr(3,3)+"-cfb",r,n).update(t);return new Uint8Array(i)}(e,t,r):h.default.AES_CFB.decrypt(t,r)).subarray(u.default.cipher[e].blockSize+2,n.length)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var o=n(e("../util.js")),u=n(e("../crypto")),f=n(e("../enums.js")),h=n(e("asmcrypto-lite")),l=o.default.getNodeCrypto(),c=o.default.getNodeBuffer(),d=1;i.prototype.read=function(e){if(e[0]!==d)throw new Error("Invalid packet version.");this.encrypted=e.subarray(1,e.length)},i.prototype.write=function(){return o.default.concatUint8Array([new Uint8Array([d]),this.encrypted])},i.prototype.encrypt=function(e,t){var r=this.packets.write(),n=u.default.getPrefixRandom(e),i=new Uint8Array([n[n.length-2],n[n.length-1]]),a=o.default.concatUint8Array([n,i]),f=new Uint8Array([211,20]),h=o.default.concatUint8Array([r,f]),l=u.default.hash.sha1(o.default.concatUint8Array([a,h]));return h=o.default.concatUint8Array([h,l]),"aes"===e.substr(0,3)?this.encrypted=s(e,a,h,t):(this.encrypted=u.default.cfb.encrypt(n,e,h,t,!1),this.encrypted=this.encrypted.subarray(0,a.length+h.length)),Promise.resolve()},i.prototype.decrypt=function(e,t){var r=void 0;r="aes"===e.substr(0,3)?a(e,this.encrypted,t):u.default.cfb.decrypt(e,t,this.encrypted,!1);var n=u.default.cfb.mdc(e,t,this.encrypted),i=r.subarray(0,r.length-20),s=o.default.concatUint8Array([n,i]);this.hash=o.default.Uint8Array2str(u.default.hash.sha1(s));var f=o.default.Uint8Array2str(r.subarray(r.length-20,r.length));if(this.hash!==f)throw new Error("Modification detected.");return this.packets.read(r.subarray(0,r.length-22)),Promise.resolve()}},{"../crypto":24,"../enums.js":35,"../util.js":70,"asmcrypto-lite":1}],61:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){this.tag=o.default.packet.symEncryptedSessionKey,this.version=4,this.sessionKey=null,this.sessionKeyEncryptionAlgorithm=null,this.sessionKeyAlgorithm="aes256",this.encrypted=null,this.s2k=new a.default}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util.js")),a=n(e("../type/s2k.js")),o=n(e("../enums.js")),u=n(e("../crypto"));i.prototype.read=function(e){this.version=e[0];var t=o.default.read(o.default.symmetric,e[1]),r=this.s2k.read(e.subarray(2,e.length))+2;r>4)},i.prototype.read=function(e){var t=0;switch(this.type=s.default.read(s.default.s2k,e[t++]),this.algorithm=s.default.read(s.default.hash,e[t++]),this.type){case"simple":break;case"salted":this.salt=e.subarray(t,t+8),t+=8;break;case"iterated":this.salt=e.subarray(t,t+8),t+=8,this.c=e[t++];break;case"gnu":if("GNU"!==a.default.Uint8Array2str(e.subarray(t,3)))throw new Error("Unknown s2k type.");t+=3;var r=1e3+e[t++];if(1001!==r)throw new Error("Unknown s2k gnu protection mode.");this.type=r;break;default:throw new Error("Unknown s2k type.")}return t},i.prototype.write=function(){var e=[new Uint8Array([s.default.write(s.default.s2k,this.type),s.default.write(s.default.hash,this.algorithm)])];switch(this.type){case"simple":break;case"salted":e.push(this.salt);break;case"iterated":e.push(this.salt),e.push(new Uint8Array([this.c]));break;case"gnu":throw new Error("GNU s2k type not supported.");default:throw new Error("Unknown s2k type.")}return a.default.concatUint8Array(e)},i.prototype.produce_key=function(e,t){function r(t,r){var n=s.default.write(s.default.hash,r.algorithm);switch(r.type){case"simple":return o.default.hash.digest(n,a.default.concatUint8Array([t,e]));case"salted":return o.default.hash.digest(n,a.default.concatUint8Array([t,r.salt,e]));case"iterated":for(var i=[],u=r.get_count(),f=a.default.concatUint8Array([r.salt,e]);i.length*f.lengthu&&(i=i.subarray(0,u)),o.default.hash.digest(n,a.default.concatUint8Array([t,i]));case"gnu":throw new Error("GNU s2k type not supported.");default:throw new Error("Unknown s2k type.")}}e=a.default.str2Uint8Array(a.default.encode_utf8(e));for(var n=[],i=0,u=new Uint8Array(t),f=0;f()[\]\\.,;:\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,}))$/.test(e)},isUserId:function(e){return!!this.isString(e)&&(/$/.test(e))},getTransferables:function(e){if(n.default.zero_copy&&Object.prototype.isPrototypeOf(e)){var t=[];return this.collectBuffers(e,t),t.length?t:void 0}},collectBuffers:function(e,t){if(e)if(this.isUint8Array(e)&&-1===t.indexOf(e.buffer))t.push(e.buffer);else if(Object.prototype.isPrototypeOf(e))for(var r in e)this.collectBuffers(e[r],t)},readNumber:function(e){for(var t=0,r=0;r>8*(t-n-1)&255;return r},readDate:function(e){var t=this.readNumber(e),r=new Date;return r.setTime(1e3*t),r},writeDate:function(e){var t=Math.round(e.getTime()/1e3);return this.writeNumber(t,4)},hexdump:function(e){for(var t,r=[],n=e.length,i=0,s=0;i=0;n--)r[n]>>=t%8,n>0&&(r[n]|=r[n-1]<<8-t%8&255);return this.bin2str(r)},get_hashAlgorithmString:function(e){switch(e){case 1:return"MD5";case 2:return"SHA1";case 3:return"RIPEMD160";case 8:return"SHA256";case 9:return"SHA384";case 10:return"SHA512";case 11:return"SHA224"}return"unknown"},getWebCrypto:function(){if(n.default.use_native)return"undefined"!=typeof window&&window.crypto&&window.crypto.subtle},getWebCryptoAll:function(){if(n.default.use_native&&"undefined"!=typeof window){if(window.crypto)return window.crypto.subtle||window.crypto.webkitSubtle;if(window.msCrypto)return window.msCrypto.subtle}},promisify:function(e){return function(){var t=arguments;return new Promise(function(r){r(e.apply(null,t))})}},promisifyIE11Op:function(e,t){return new Promise(function(r,n){e.onerror=function(){n(new Error(t))},e.oncomplete=function(e){r(e.target.result)}})},detectNode:function(){return"undefined"==typeof window},getNodeCrypto:function(){if(this.detectNode()&&n.default.use_native)return e("crypto")},getNodeBuffer:function(){if(this.detectNode())return e("buffer").Buffer}}},{"./config":10,buffer:"buffer",crypto:"crypto"}],71:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,r=void 0===t?"openpgp.worker.min.js":t,n=e.worker,i=e.config;this.worker=n||new Worker(r),this.worker.onmessage=this.onMessage.bind(this),this.worker.onerror=function(e){throw new Error("Unhandled error in openpgp worker: "+e.message+" ("+e.filename+":"+e.lineno+")")},this.seedRandom(u),i&&this.worker.postMessage({event:"configure",config:i}),this.tasks={},this.currentID=0}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i;var s=n(e("../util.js")),a=n(e("../crypto")),o=n(e("../packet")),u=5e4;i.prototype.getID=function(){return this.currentID++},i.prototype.onMessage=function(e){var t=e.data;switch(t.event){case"method-return":if(t.err){var r=new Error(t.err);r.workerStack=t.stack,this.tasks[t.id].reject(r)}else this.tasks[t.id].resolve(t.data);delete this.tasks[t.id];break;case"request-seed":this.seedRandom(2e4);break;default:throw new Error("Unknown Worker Event.")}},i.prototype.seedRandom=function(e){var t=this.getRandomBuffer(e);this.worker.postMessage({event:"seed-random",buf:t},s.default.getTransferables.call(s.default,t))},i.prototype.getRandomBuffer=function(e){if(!e)return null;var t=new Uint8Array(e);return a.default.random.getRandomValues(t),t},i.prototype.terminate=function(){this.worker.terminate()},i.prototype.delegate=function(e,t){var r=this,n=this.getID();return new Promise(function(i,a){r.worker.postMessage({id:n,event:e,options:o.default.clone.clonePackets(t)},s.default.getTransferables.call(s.default,t)),r.tasks[n]={resolve:function(t){return i(o.default.clone.parseClonedPackets(t,e))},reject:a}})}},{"../crypto":24,"../packet":47,"../util.js":70}]},{},[37])(37)}); +/*! OpenPGP.js v3.0.0 - 2018-03-08 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).openpgp=e()}}(function(){return function e(t,r,n){function i(s,o){if(!r[s]){if(!t[s]){var u="function"==typeof require&&require;if(!o&&u)return u(s,!0);if(a)return a(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var c=r[s]={exports:{}};t[s][0].call(c.exports,function(e){var r=t[s][1][e];return i(r||e)},c,c.exports,e,t,r,n)}return r[s].exports}for(var a="function"==typeof require&&require,s=0;s>>7);return a^=99}r||function(){e=[],t=[];var n,i,a=1;for(n=0;n<255;n++)e[n]=a,i=128&a,a<<=1,a&=255,128===i&&(a^=27),a^=e[n],t[e[n]]=n;e[255]=e[0],t[0]=0,r=!0}(),i=[],a=[],s=[[],[],[],[]],o=[[],[],[],[]];for(var f=0;f<256;f++){var c=u(f);i[f]=c,a[c]=f,s[0][f]=n(2,c)<<24|c<<16|c<<8|n(3,c),o[0][c]=n(14,f)<<24|n(9,f)<<16|n(13,f)<<8|n(11,f);for(var d=1;d<4;d++)s[d][f]=s[d-1][f]>>>8|s[d-1][f]<<24,o[d][c]=o[d-1][c]>>>8|o[d-1][c]<<24}}var f=function(e,t){u();var r=new Uint32Array(t);r.set(i,512),r.set(a,768);for(var n=0;n<4;n++)r.set(s[n],4096+1024*n>>2),r.set(o[n],8192+1024*n>>2);var f=function(e,t,r){"use asm";var n=0,i=0,a=0,s=0,o=0,u=0,f=0,c=0,d=0,l=0,h=0,p=0,y=0,b=0,m=0,g=0,v=0,_=0,w=0,k=0,x=0;var A=new e.Uint32Array(r),S=new e.Uint8Array(r);function E(e,t,r,o,u,f,c,d){e=e|0;t=t|0;r=r|0;o=o|0;u=u|0;f=f|0;c=c|0;d=d|0;var l=0,h=0,p=0,y=0,b=0,m=0,g=0,v=0;l=r|0x400,h=r|0x800,p=r|0xc00;u=u^A[(e|0)>>2],f=f^A[(e|4)>>2],c=c^A[(e|8)>>2],d=d^A[(e|12)>>2];for(v=16;(v|0)<=o<<4;v=v+16|0){y=A[(r|u>>22&1020)>>2]^A[(l|f>>14&1020)>>2]^A[(h|c>>6&1020)>>2]^A[(p|d<<2&1020)>>2]^A[(e|v|0)>>2],b=A[(r|f>>22&1020)>>2]^A[(l|c>>14&1020)>>2]^A[(h|d>>6&1020)>>2]^A[(p|u<<2&1020)>>2]^A[(e|v|4)>>2],m=A[(r|c>>22&1020)>>2]^A[(l|d>>14&1020)>>2]^A[(h|u>>6&1020)>>2]^A[(p|f<<2&1020)>>2]^A[(e|v|8)>>2],g=A[(r|d>>22&1020)>>2]^A[(l|u>>14&1020)>>2]^A[(h|f>>6&1020)>>2]^A[(p|c<<2&1020)>>2]^A[(e|v|12)>>2];u=y,f=b,c=m,d=g}n=A[(t|u>>22&1020)>>2]<<24^A[(t|f>>14&1020)>>2]<<16^A[(t|c>>6&1020)>>2]<<8^A[(t|d<<2&1020)>>2]^A[(e|v|0)>>2],i=A[(t|f>>22&1020)>>2]<<24^A[(t|c>>14&1020)>>2]<<16^A[(t|d>>6&1020)>>2]<<8^A[(t|u<<2&1020)>>2]^A[(e|v|4)>>2],a=A[(t|c>>22&1020)>>2]<<24^A[(t|d>>14&1020)>>2]<<16^A[(t|u>>6&1020)>>2]<<8^A[(t|f<<2&1020)>>2]^A[(e|v|8)>>2],s=A[(t|d>>22&1020)>>2]<<24^A[(t|u>>14&1020)>>2]<<16^A[(t|f>>6&1020)>>2]<<8^A[(t|c<<2&1020)>>2]^A[(e|v|12)>>2]}function M(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;E(0x0000,0x0800,0x1000,x,e,t,r,n)}function j(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var a=0;E(0x0400,0x0c00,0x2000,x,e,n,r,t);a=i,i=s,s=a}function P(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;E(0x0000,0x0800,0x1000,x,o^e,u^t,f^r,c^d);o=n,u=i,f=a,c=s}function K(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;var l=0;E(0x0400,0x0c00,0x2000,x,e,d,r,t);l=i,i=s,s=l;n=n^o,i=i^u,a=a^f,s=s^c;o=e,u=t,f=r,c=d}function U(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;E(0x0000,0x0800,0x1000,x,o,u,f,c);o=n=n^e,u=i=i^t,f=a=a^r,c=s=s^d}function C(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;E(0x0000,0x0800,0x1000,x,o,u,f,c);n=n^e,i=i^t,a=a^r,s=s^d;o=e,u=t,f=r,c=d}function B(e,t,r,d){e=e|0;t=t|0;r=r|0;d=d|0;E(0x0000,0x0800,0x1000,x,o,u,f,c);o=n,u=i,f=a,c=s;n=n^e,i=i^t,a=a^r,s=s^d}function I(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;E(0x0000,0x0800,0x1000,x,d,l,h,p);p=~g&p|g&p+1;h=~m&h|m&h+((p|0)==0);l=~b&l|b&l+((h|0)==0);d=~y&d|y&d+((l|0)==0);n=n^e;i=i^t;a=a^r;s=s^o}function T(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;var i=0,a=0,s=0,d=0,l=0,h=0,p=0,y=0,b=0,m=0;e=e^o,t=t^u,r=r^f,n=n^c;i=v|0,a=_|0,s=w|0,d=k|0;for(;(b|0)<128;b=b+1|0){if(i>>>31){l=l^e,h=h^t,p=p^r,y=y^n}i=i<<1|a>>>31,a=a<<1|s>>>31,s=s<<1|d>>>31,d=d<<1;m=n&1;n=n>>>1|r<<31,r=r>>>1|t<<31,t=t>>>1|e<<31,e=e>>>1;if(m)e=e^0xe1000000}o=l,u=h,f=p,c=y}function O(e){e=e|0;x=e}function R(e,t,r,o){e=e|0;t=t|0;r=r|0;o=o|0;n=e,i=t,a=r,s=o}function z(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;o=e,u=t,f=r,c=n}function L(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;d=e,l=t,h=r,p=n}function N(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;y=e,b=t,m=r,g=n}function D(e,t,r,n){e=e|0;t=t|0;r=r|0;n=n|0;p=~g&p|g&n,h=~m&h|m&r,l=~b&l|b&t,d=~y&d|y&e}function F(e){e=e|0;if(e&15)return-1;S[e|0]=n>>>24,S[e|1]=n>>>16&255,S[e|2]=n>>>8&255,S[e|3]=n&255,S[e|4]=i>>>24,S[e|5]=i>>>16&255,S[e|6]=i>>>8&255,S[e|7]=i&255,S[e|8]=a>>>24,S[e|9]=a>>>16&255,S[e|10]=a>>>8&255,S[e|11]=a&255,S[e|12]=s>>>24,S[e|13]=s>>>16&255,S[e|14]=s>>>8&255,S[e|15]=s&255;return 16}function q(e){e=e|0;if(e&15)return-1;S[e|0]=o>>>24,S[e|1]=o>>>16&255,S[e|2]=o>>>8&255,S[e|3]=o&255,S[e|4]=u>>>24,S[e|5]=u>>>16&255,S[e|6]=u>>>8&255,S[e|7]=u&255,S[e|8]=f>>>24,S[e|9]=f>>>16&255,S[e|10]=f>>>8&255,S[e|11]=f&255,S[e|12]=c>>>24,S[e|13]=c>>>16&255,S[e|14]=c>>>8&255,S[e|15]=c&255;return 16}function G(){M(0,0,0,0);v=n,_=i,w=a,k=s}function H(e,t,r){e=e|0;t=t|0;r=r|0;var o=0;if(t&15)return-1;while((r|0)>=16){V[e&7](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);S[t|0]=n>>>24,S[t|1]=n>>>16&255,S[t|2]=n>>>8&255,S[t|3]=n&255,S[t|4]=i>>>24,S[t|5]=i>>>16&255,S[t|6]=i>>>8&255,S[t|7]=i&255,S[t|8]=a>>>24,S[t|9]=a>>>16&255,S[t|10]=a>>>8&255,S[t|11]=a&255,S[t|12]=s>>>24,S[t|13]=s>>>16&255,S[t|14]=s>>>8&255,S[t|15]=s&255;o=o+16|0,t=t+16|0,r=r-16|0}return o|0}function Z(e,t,r){e=e|0;t=t|0;r=r|0;var n=0;if(t&15)return-1;while((r|0)>=16){W[e&1](S[t|0]<<24|S[t|1]<<16|S[t|2]<<8|S[t|3],S[t|4]<<24|S[t|5]<<16|S[t|6]<<8|S[t|7],S[t|8]<<24|S[t|9]<<16|S[t|10]<<8|S[t|11],S[t|12]<<24|S[t|13]<<16|S[t|14]<<8|S[t|15]);n=n+16|0,t=t+16|0,r=r-16|0}return n|0}var V=[M,j,P,K,U,C,B,I];var W=[P,T];return{set_rounds:O,set_state:R,set_iv:z,set_nonce:L,set_mask:N,set_counter:D,get_state:F,get_iv:q,gcm_init:G,cipher:H,mac:Z}}({Uint8Array:Uint8Array,Uint32Array:Uint32Array},e,t);return f.set_key=function(e,t,n,a,s,u,c,d,l){var h=r.subarray(0,60),p=r.subarray(256,316);h.set([t,n,a,s,u,c,d,l]);for(var y=e,b=1;y<4*e+28;y++){var m=h[y-1];(y%e==0||8===e&&y%e==4)&&(m=i[m>>>24]<<24^i[m>>>16&255]<<16^i[m>>>8&255]<<8^i[255&m]),y%e==0&&(m=m<<8^m>>>24^b<<24,b=b<<1^(128&b?27:0)),h[y]=h[y-e]^m}for(var g=0;g=y-4?m:o[0][i[m>>>24]]^o[1][i[m>>>16&255]]^o[2][i[m>>>8&255]]^o[3][i[255&m]];f.set_rounds(e+5)},f};return f.ENC={ECB:0,CBC:2,CFB:4,OFB:6,CTR:7},f.DEC={ECB:1,CBC:3,CFB:5,OFB:6,CTR:7},f.MAC={CBC:0,GCM:1},f.HEAP_DATA=16384,f}()},{}],2:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES=void 0;var n=u(e("babel-runtime/helpers/classCallCheck")),i=u(e("babel-runtime/helpers/createClass")),a=e("./aes.asm"),s=e("../utils"),o=e("../errors");function u(e){return e&&e.__esModule?e:{default:e}}r.AES=function(){function e(t,r,i,o,u){(0,n.default)(this,e),this.nonce=null,this.counter=0,this.counterSize=0,this.heap=(0,s._heap_init)(Uint8Array,o).subarray(a.AES_asm.HEAP_DATA),this.asm=u||(0,a.AES_asm)(null,this.heap.buffer),this.mode=null,this.key=null,this.AES_reset(t,r,i)}return(0,i.default)(e,[{key:"AES_set_key",value:function(e){if(void 0!==e){if(!(0,s.is_bytes)(e))throw new TypeError("unexpected key type");var t=e.length;if(16!==t&&24!==t&&32!==t)throw new o.IllegalArgumentError("illegal key size");var r=new DataView(e.buffer,e.byteOffset,e.byteLength);this.asm.set_key(t>>2,r.getUint32(0),r.getUint32(4),r.getUint32(8),r.getUint32(12),t>16?r.getUint32(16):0,t>16?r.getUint32(20):0,t>24?r.getUint32(24):0,t>24?r.getUint32(28):0),this.key=e}else if(!this.key)throw new Error("key is required")}},{key:"AES_CTR_set_options",value:function(e,t,r){if(void 0!==r){if(r<8||r>48)throw new o.IllegalArgumentError("illegal counter size");this.counterSize=r;var n=Math.pow(2,r)-1;this.asm.set_mask(0,0,n/4294967296|0,0|n)}else this.counterSize=r=48,this.asm.set_mask(0,0,65535,4294967295);if(void 0===e)throw new Error("nonce is required");if(!(0,s.is_bytes)(e))throw new TypeError("unexpected nonce type");var i=e.length;if(!i||i>16)throw new o.IllegalArgumentError("illegal nonce size");this.nonce=e;var a=new DataView(new ArrayBuffer(16));if(new Uint8Array(a.buffer).set(e),this.asm.set_nonce(a.getUint32(0),a.getUint32(4),a.getUint32(8),a.getUint32(12)),void 0!==t){if(!(0,s.is_number)(t))throw new TypeError("unexpected counter type");if(t<0||t>=Math.pow(2,r))throw new o.IllegalArgumentError("illegal counter value");this.counter=t,this.asm.set_counter(0,0,t/4294967296|0,0|t)}else this.counter=0}},{key:"AES_set_iv",value:function(e){if(void 0!==e){if(!(0,s.is_bytes)(e))throw new TypeError("unexpected iv type");if(16!==e.length)throw new o.IllegalArgumentError("illegal iv size");var t=new DataView(e.buffer,e.byteOffset,e.byteLength);this.iv=e,this.asm.set_iv(t.getUint32(0),t.getUint32(4),t.getUint32(8),t.getUint32(12))}else this.iv=null,this.asm.set_iv(0,0,0,0)}},{key:"AES_set_padding",value:function(e){this.padding=void 0===e||!!e}},{key:"AES_reset",value:function(e,t,r){return this.result=null,this.pos=0,this.len=0,this.AES_set_key(e),this.AES_set_iv(t),this.AES_set_padding(r),this}},{key:"AES_Encrypt_process",value:function(e){if(!(0,s.is_bytes)(e))throw new TypeError("data isn't of expected type");for(var t=this.asm,r=this.heap,n=a.AES_asm.ENC[this.mode],i=a.AES_asm.HEAP_DATA,o=this.pos,u=this.len,f=0,c=e.length||0,d=0,l=0,h=new Uint8Array(u+c&-16);c>0;)u+=l=(0,s._heap_write)(r,o+u,e,f,c),f+=l,c-=l,(l=t.cipher(n,i+o,u))&&h.set(r.subarray(o,o+l),d),d+=l,l0;)u+=p=(0,s._heap_write)(r,o+u,e,f,c),f+=p,c-=p,(p=t.cipher(n,i+o,u-(c?0:h)))&&y.set(r.subarray(o,o+p),d),d+=p,p0){if(c%16){if(this.hasOwnProperty("padding"))throw new o.IllegalArgumentError("data length must be a multiple of the block size");c+=16-c%16}if(n.cipher(s,u+f,c),this.hasOwnProperty("padding")&&this.padding){var l=i[f+d-1];if(l<1||l>16||l>d)throw new o.SecurityError("bad padding");for(var h=0,p=l;p>1;p--)h|=l^i[f+d-p];if(h)throw new o.SecurityError("bad padding");d-=l}}var y=new Uint8Array(r+d);return r>0&&y.set(t),d>0&&y.set(i.subarray(f,f+d),r),this.result=y,this.pos=0,this.len=0,this}}]),e}()},{"../errors":10,"../utils":15,"./aes.asm":1,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_CFB_Decrypt=r.AES_CFB_Encrypt=r.AES_CFB=void 0;var n=f(e("babel-runtime/core-js/object/get-prototype-of")),i=f(e("babel-runtime/helpers/classCallCheck")),a=f(e("babel-runtime/helpers/createClass")),s=f(e("babel-runtime/helpers/possibleConstructorReturn")),o=f(e("babel-runtime/helpers/inherits")),u=e("../aes");function f(e){return e&&e.__esModule?e:{default:e}}var c=r.AES_CFB=function(e){function t(e,r,a,o){(0,i.default)(this,t);var u=(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,!0,a,o));return delete u.padding,u.mode="CFB",u.BLOCK_SIZE=16,u}return(0,o.default)(t,e),(0,a.default)(t,[{key:"encrypt",value:function(e){return this.AES_Encrypt_finish(e)}},{key:"decrypt",value:function(e){return this.AES_Decrypt_finish(e)}}]),t}(u.AES);r.AES_CFB_Encrypt=function(e){function t(e,r,a,o){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a,o))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"reset",value:function(e,t,r){return this.AES_reset(e,t,r)}},{key:"process",value:function(e){return this.AES_Encrypt_process(e)}},{key:"finish",value:function(e){return this.AES_Encrypt_finish(e)}}]),t}(c),r.AES_CFB_Decrypt=function(e){function t(e,r,a,o){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a,o))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"reset",value:function(e,t,r){return this.AES_reset(e,t,r)}},{key:"process",value:function(e){return this.AES_Decrypt_process(e)}},{key:"finish",value:function(e){return this.AES_Decrypt_finish(e)}}]),t}(c)},{"../aes":2,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],4:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_CFB_Decrypt=r.AES_CFB_Encrypt=r.AES_CFB=void 0;var n=e("../exports"),i=e("./cfb");i.AES_CFB.encrypt=function(e,t,r){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new i.AES_CFB(t,r,n._AES_heap_instance,n._AES_asm_instance).encrypt(e).result},i.AES_CFB.decrypt=function(e,t,r){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new i.AES_CFB(t,r,n._AES_heap_instance,n._AES_asm_instance).decrypt(e).result},r.AES_CFB=i.AES_CFB,r.AES_CFB_Encrypt=i.AES_CFB_Encrypt,r.AES_CFB_Decrypt=i.AES_CFB_Decrypt},{"../exports":7,"./cfb":3}],5:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_ECB_Decrypt=r.AES_ECB_Encrypt=r.AES_ECB=void 0;var n=f(e("babel-runtime/core-js/object/get-prototype-of")),i=f(e("babel-runtime/helpers/classCallCheck")),a=f(e("babel-runtime/helpers/createClass")),s=f(e("babel-runtime/helpers/possibleConstructorReturn")),o=f(e("babel-runtime/helpers/inherits")),u=e("../aes");function f(e){return e&&e.__esModule?e:{default:e}}var c=r.AES_ECB=function(e){function t(e,r,a){(0,i.default)(this,t);var o=(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,void 0,!1,r,a));return o.mode="ECB",o.BLOCK_SIZE=16,o}return(0,o.default)(t,e),(0,a.default)(t,[{key:"encrypt",value:function(e){return this.AES_Encrypt_finish(e)}},{key:"decrypt",value:function(e){return this.AES_Decrypt_finish(e)}}]),t}(u.AES);r.AES_ECB_Encrypt=function(e){function t(e,r,a){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"reset",value:function(e){return this.AES_reset(e,null,!0)}},{key:"process",value:function(e){return this.AES_Encrypt_process(e)}},{key:"finish",value:function(e){return this.AES_Encrypt_finish(e)}}]),t}(c),r.AES_ECB_Decrypt=function(e){function t(e,r,a){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"reset",value:function(e){return this.AES_reset(e,null,!0)}},{key:"process",value:function(e){return this.AES_Decrypt_process(e)}},{key:"finish",value:function(e){return this.AES_Decrypt_finish(e)}}]),t}(c)},{"../aes":2,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_ECB_Decrypt=r.AES_ECB_Encrypt=r.AES_ECB=void 0;var n=e("../exports"),i=e("./ecb");i.AES_ECB.encrypt=function(e,t){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new i.AES_ECB(t,n._AES_heap_instance,n._AES_asm_instance).encrypt(e).result},i.AES_ECB.decrypt=function(e,t){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");return new i.AES_ECB(t,n._AES_heap_instance,n._AES_asm_instance).decrypt(e).result},r.AES_ECB=i.AES_ECB,r.AES_ECB_Encrypt=i.AES_ECB_Encrypt,r.AES_ECB_Decrypt=i.AES_ECB_Decrypt},{"../exports":7,"./ecb":5}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r._AES_asm_instance=r._AES_heap_instance=void 0;var n=e("./aes.asm"),i=r._AES_heap_instance=new Uint8Array(1048576);r._AES_asm_instance=(0,n.AES_asm)(null,i.buffer)},{"./aes.asm":1}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_GCM_Decrypt=r.AES_GCM_Encrypt=r.AES_GCM=void 0;var n=e("../exports"),i=e("./gcm");i.AES_GCM.encrypt=function(e,t,r,a,s){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");if(void 0===r)throw new SyntaxError("nonce required");return new i.AES_GCM(t,r,a,s,n._AES_heap_instance,n._AES_asm_instance).encrypt(e).result},i.AES_GCM.decrypt=function(e,t,r,a,s){if(void 0===e)throw new SyntaxError("data required");if(void 0===t)throw new SyntaxError("key required");if(void 0===r)throw new SyntaxError("nonce required");return new i.AES_GCM(t,r,a,s,n._AES_heap_instance,n._AES_asm_instance).decrypt(e).result},r.AES_GCM=i.AES_GCM,r.AES_GCM_Encrypt=i.AES_GCM_Encrypt,r.AES_GCM_Decrypt=i.AES_GCM_Decrypt},{"../exports":7,"./gcm":9}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.AES_GCM_Decrypt=r.AES_GCM_Encrypt=r.AES_GCM=void 0;var n=l(e("babel-runtime/core-js/object/get-prototype-of")),i=l(e("babel-runtime/helpers/classCallCheck")),a=l(e("babel-runtime/helpers/createClass")),s=l(e("babel-runtime/helpers/possibleConstructorReturn")),o=l(e("babel-runtime/helpers/inherits")),u=e("../../errors"),f=e("../../utils"),c=e("../aes"),d=e("../aes.asm");function l(e){return e&&e.__esModule?e:{default:e}}var h=r.AES_GCM=function(e){function t(e,r,a,o,u,f){(0,i.default)(this,t);var c=(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,void 0,!1,u,f));return c.nonce=null,c.adata=null,c.iv=null,c.counter=1,c.tagSize=16,c.mode="GCM",c.BLOCK_SIZE=16,c.reset(e,o,r,a),c}return(0,o.default)(t,e),(0,a.default)(t,[{key:"reset",value:function(e,t,r,n){return this.AES_GCM_reset(e,t,r,n)}},{key:"encrypt",value:function(e){return this.AES_GCM_encrypt(e)}},{key:"decrypt",value:function(e){return this.AES_GCM_decrypt(e)}},{key:"AES_GCM_Encrypt_process",value:function(e){if(!(0,f.is_bytes)(e))throw new TypeError("data isn't of expected type");var t=0,r=e.length||0,n=this.asm,i=this.heap,a=this.counter,s=this.pos,o=this.len,u=0,c=o+r&-16,l=0;if((a-1<<4)+o+r>68719476704)throw new RangeError("counter overflow");for(var h=new Uint8Array(c);r>0;)o+=l=(0,f._heap_write)(i,s+o,e,t,r),t+=l,r-=l,l=n.cipher(d.AES_asm.ENC.CTR,d.AES_asm.HEAP_DATA+s,o),(l=n.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA+s,l))&&h.set(i.subarray(s,s+l),u),a+=l>>>4,u+=l,l>>29,t[4]=f>>>21,t[5]=f>>>13&255,t[6]=f>>>5&255,t[7]=f<<3&255,t[8]=t[9]=t[10]=0,t[11]=c>>>29,t[12]=c>>>21&255,t[13]=c>>>13&255,t[14]=c>>>5&255,t[15]=c<<3&255,e.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA,16),e.get_iv(d.AES_asm.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(d.AES_asm.ENC.CTR,d.AES_asm.HEAP_DATA,16),o.set(t.subarray(0,n),s),this.result=o,this.counter=1,this.pos=0,this.len=0,this}},{key:"AES_GCM_Decrypt_process",value:function(e){if(!(0,f.is_bytes)(e))throw new TypeError("data isn't of expected type");var t=0,r=e.length||0,n=this.asm,i=this.heap,a=this.counter,s=this.tagSize,o=this.pos,u=this.len,c=0,l=u+r>s?u+r-s&-16:0,h=u+r-l,p=0;if((a-1<<4)+u+r>68719476704)throw new RangeError("counter overflow");for(var y=new Uint8Array(l);r>h;)u+=p=(0,f._heap_write)(i,o+u,e,t,r-h),t+=p,r-=p,p=n.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA+o,p),(p=n.cipher(d.AES_asm.DEC.CTR,d.AES_asm.HEAP_DATA+o,p))&&y.set(i.subarray(o,o+p),c),a+=p>>>4,c+=p,o=0,u=0;return r>0&&(u+=(0,f._heap_write)(i,0,e,t,r)),this.result=y,this.counter=a,this.pos=o,this.len=u,this}},{key:"AES_GCM_Decrypt_finish",value:function(){var e=this.asm,t=this.heap,r=this.tagSize,n=this.adata,i=this.counter,a=this.pos,s=this.len,o=s-r;if(s>>29,t[4]=h>>>21,t[5]=h>>>13&255,t[6]=h>>>5&255,t[7]=h<<3&255,t[8]=t[9]=t[10]=0,t[11]=p>>>29,t[12]=p>>>21&255,t[13]=p>>>13&255,t[14]=p>>>5&255,t[15]=p<<3&255,e.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA,16),e.get_iv(d.AES_asm.HEAP_DATA),e.set_counter(0,0,0,this.gamma0),e.cipher(d.AES_asm.ENC.CTR,d.AES_asm.HEAP_DATA,16);var y=0;for(l=0;l16)throw new u.IllegalArgumentError("illegal tagSize value");this.tagSize=t}else this.tagSize=16;if(void 0===r)throw new Error("nonce is required");if(!(0,f.is_bytes)(r))throw new TypeError("unexpected nonce type");this.nonce=r;var c=r.length||0,l=new Uint8Array(16);12!==c?(this._gcm_mac_process(r),o[0]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=0,o[11]=c>>>29,o[12]=c>>>21&255,o[13]=c>>>13&255,o[14]=c>>>5&255,o[15]=c<<3&255,s.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA,16),s.get_iv(d.AES_asm.HEAP_DATA),s.set_iv(),l.set(o.subarray(0,16))):(l.set(r),l[15]=1);var h=new DataView(l.buffer);if(this.gamma0=h.getUint32(12),s.set_nonce(h.getUint32(0),h.getUint32(4),h.getUint32(8),0),s.set_mask(0,0,0,4294967295),void 0!==n&&null!==n){if(!(0,f.is_bytes)(n))throw new TypeError("unexpected adata type");if(n.length>68719476704)throw new u.IllegalArgumentError("illegal adata length");n.length?(this.adata=n,this._gcm_mac_process(n)):this.adata=null}else this.adata=null;if(void 0!==i){if(!(0,f.is_number)(i))throw new TypeError("counter must be a number");if(i<1||i>4294967295)throw new RangeError("counter must be a positive 32-bit integer");this.counter=i,s.set_counter(0,0,0,this.gamma0+i|0)}else this.counter=1,s.set_counter(0,0,0,this.gamma0+1|0);if(void 0!==a){if(!(0,f.is_number)(a))throw new TypeError("iv must be a number");this.iv=a,this.AES_set_iv(a)}return this}},{key:"_gcm_mac_process",value:function(e){for(var t=this.heap,r=this.asm,n=0,i=e.length||0,a=0;i>0;){for(n+=a=(0,f._heap_write)(t,0,e,n,i),i-=a;15&a;)t[a++]=0;r.mac(d.AES_asm.MAC.GCM,d.AES_asm.HEAP_DATA,a)}}}]),t}(c.AES);r.AES_GCM_Encrypt=function(e){function t(e,r,a,o,u,f){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a,o,u,f))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"process",value:function(e){return this.AES_GCM_Encrypt_process(e)}},{key:"finish",value:function(){return this.AES_GCM_Encrypt_finish()}}]),t}(h),r.AES_GCM_Decrypt=function(e){function t(e,r,a,o,u,f){return(0,i.default)(this,t),(0,s.default)(this,(t.__proto__||(0,n.default)(t)).call(this,e,r,a,o,u,f))}return(0,o.default)(t,e),(0,a.default)(t,[{key:"process",value:function(e){return this.AES_GCM_Decrypt_process(e)}},{key:"finish",value:function(){return this.AES_GCM_Decrypt_finish()}}]),t}(h)},{"../../errors":10,"../../utils":15,"../aes":2,"../aes.asm":1,"babel-runtime/core-js/object/get-prototype-of":23,"babel-runtime/helpers/classCallCheck":29,"babel-runtime/helpers/createClass":30,"babel-runtime/helpers/inherits":31,"babel-runtime/helpers/possibleConstructorReturn":32}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,i=e("babel-runtime/core-js/object/create"),a=(n=i)&&n.__esModule?n:{default:n};function s(){var e=Error.apply(this,arguments);this.message=e.message,this.stack=e.stack}function o(){var e=Error.apply(this,arguments);this.message=e.message,this.stack=e.stack}function u(){var e=Error.apply(this,arguments);this.message=e.message,this.stack=e.stack}r.IllegalStateError=s,r.IllegalArgumentError=o,r.SecurityError=u,s.prototype=(0,a.default)(Error.prototype,{name:{value:"IllegalStateError"}}),o.prototype=(0,a.default)(Error.prototype,{name:{value:"IllegalArgumentError"}}),u.prototype=(0,a.default)(Error.prototype,{name:{value:"SecurityError"}})},{"babel-runtime/core-js/object/create":20}],11:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.hash_reset=function(){return this.result=null,this.pos=0,this.len=0,this.asm.reset(),this},r.hash_process=function(e){if(null!==this.result)throw new i.IllegalStateError("state must be reset before processing new data");(0,n.is_string)(e)&&(e=(0,n.string_to_bytes)(e));(0,n.is_buffer)(e)&&(e=new Uint8Array(e));if(!(0,n.is_bytes)(e))throw new TypeError("data isn't of expected type");var t=this.asm,r=this.heap,a=this.pos,s=this.len,o=0,u=e.length,f=0;for(;u>0;)f=(0,n._heap_write)(r,a+s,e,o,u),s+=f,o+=f,u-=f,f=t.process(a,s),a+=f,(s-=f)||(a=0);return this.pos=a,this.len=s,this},r.hash_finish=function(){if(null!==this.result)throw new i.IllegalStateError("state must be reset before processing new data");return this.asm.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(this.heap.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this};var n=e("../utils"),i=e("../errors")},{"../errors":10,"../utils":15}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.SHA256=void 0;var n=e("./sha256"),i=e("../../utils");function a(e){if(void 0===e)throw new SyntaxError("data required");return(0,n.get_sha256_instance)().reset().process(e).finish().result}var s=r.SHA256=n.sha256_constructor;s.bytes=a,s.hex=function(e){var t=a(e);return(0,i.bytes_to_hex)(t)},s.base64=function(e){var t=a(e);return(0,i.bytes_to_base64)(t)}},{"../../utils":15,"./sha256":14}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sha256_asm=function(e,t,r){"use asm";var n=0,i=0,a=0,s=0,o=0,u=0,f=0,c=0,d=0,l=0,h=0,p=0,y=0,b=0,m=0,g=0,v=0,_=0,w=0,k=0,x=0,A=0,S=0,E=0,M=0,j=0,P=new e.Uint8Array(r);function K(e,t,r,d,l,h,p,y,b,m,g,v,_,w,k,x){e=e|0;t=t|0;r=r|0;d=d|0;l=l|0;h=h|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;v=v|0;_=_|0;w=w|0;k=k|0;x=x|0;var A=0,S=0,E=0,M=0,j=0,P=0,K=0,U=0;A=n;S=i;E=a;M=s;j=o;P=u;K=f;U=c;U=e+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0x428a2f98|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;K=t+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0x71374491|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;P=r+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0xb5c0fbcf|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;j=d+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0xe9b5dba5|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;M=l+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x3956c25b|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;E=h+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0x59f111f1|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;S=p+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x923f82a4|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;A=y+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0xab1c5ed5|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;U=b+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0xd807aa98|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;K=m+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0x12835b01|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;P=g+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0x243185be|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;j=v+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0x550c7dc3|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;M=_+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x72be5d74|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;E=w+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0x80deb1fe|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;S=k+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x9bdc06a7|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;A=x+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0xc19bf174|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;U=e+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0xe49b69c1|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(x>>>17^x>>>19^x>>>10^x<<15^x<<13)+t+g|0;K=t+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0xefbe4786|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+v|0;P=r+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0x0fc19dc6|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;d=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+_|0;j=d+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0x240ca1cc|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;l=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+l+w|0;M=l+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x2de92c6f|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;h=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+h+k|0;E=h+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0x4a7484aa|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+p+x|0;S=p+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x5cb0a9dc|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;A=y+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0x76f988da|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;U=b+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0x983e5152|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;K=m+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0xa831c66d|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;g=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;P=g+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0xb00327c8|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;j=v+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0xbf597fc7|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;_=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+_+h|0;M=_+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0xc6e00bf3|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;w=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+w+p|0;E=w+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0xd5a79147|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;k=(x>>>7^x>>>18^x>>>3^x<<25^x<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+k+y|0;S=k+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x06ca6351|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;x=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+x+b|0;A=x+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0x14292967|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;U=e+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0x27b70a85|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(x>>>17^x>>>19^x>>>10^x<<15^x<<13)+t+g|0;K=t+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0x2e1b2138|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+v|0;P=r+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0x4d2c6dfc|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;d=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+_|0;j=d+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0x53380d13|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;l=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+l+w|0;M=l+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x650a7354|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;h=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+h+k|0;E=h+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0x766a0abb|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+p+x|0;S=p+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x81c2c92e|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;A=y+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0x92722c85|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;U=b+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0xa2bfe8a1|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;K=m+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0xa81a664b|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;g=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;P=g+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0xc24b8b70|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;j=v+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0xc76c51a3|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;_=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+_+h|0;M=_+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0xd192e819|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;w=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+w+p|0;E=w+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0xd6990624|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;k=(x>>>7^x>>>18^x>>>3^x<<25^x<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+k+y|0;S=k+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0xf40e3585|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;x=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+x+b|0;A=x+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0x106aa070|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;e=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(k>>>17^k>>>19^k>>>10^k<<15^k<<13)+e+m|0;U=e+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0x19a4c116|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;t=(r>>>7^r>>>18^r>>>3^r<<25^r<<14)+(x>>>17^x>>>19^x>>>10^x<<15^x<<13)+t+g|0;K=t+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0x1e376c08|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;r=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+r+v|0;P=r+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0x2748774c|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;d=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+_|0;j=d+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0x34b0bcb5|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;l=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(r>>>17^r>>>19^r>>>10^r<<15^r<<13)+l+w|0;M=l+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x391c0cb3|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;h=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+h+k|0;E=h+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0x4ed8aa4a|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;p=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+p+x|0;S=p+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0x5b9cca4f|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;y=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;A=y+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0x682e6ff3|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;b=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+b+t|0;U=b+U+(j>>>6^j>>>11^j>>>25^j<<26^j<<21^j<<7)+(K^j&(P^K))+0x748f82ee|0;M=M+U|0;U=U+(A&S^E&(A^S))+(A>>>2^A>>>13^A>>>22^A<<30^A<<19^A<<10)|0;m=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+r|0;K=m+K+(M>>>6^M>>>11^M>>>25^M<<26^M<<21^M<<7)+(P^M&(j^P))+0x78a5636f|0;E=E+K|0;K=K+(U&A^S&(U^A))+(U>>>2^U>>>13^U>>>22^U<<30^U<<19^U<<10)|0;g=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+g+d|0;P=g+P+(E>>>6^E>>>11^E>>>25^E<<26^E<<21^E<<7)+(j^E&(M^j))+0x84c87814|0;S=S+P|0;P=P+(K&U^A&(K^U))+(K>>>2^K>>>13^K>>>22^K<<30^K<<19^K<<10)|0;v=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+v+l|0;j=v+j+(S>>>6^S>>>11^S>>>25^S<<26^S<<21^S<<7)+(M^S&(E^M))+0x8cc70208|0;A=A+j|0;j=j+(P&K^U&(P^K))+(P>>>2^P>>>13^P>>>22^P<<30^P<<19^P<<10)|0;_=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+_+h|0;M=_+M+(A>>>6^A>>>11^A>>>25^A<<26^A<<21^A<<7)+(E^A&(S^E))+0x90befffa|0;U=U+M|0;M=M+(j&P^K&(j^P))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;w=(k>>>7^k>>>18^k>>>3^k<<25^k<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+w+p|0;E=w+E+(U>>>6^U>>>11^U>>>25^U<<26^U<<21^U<<7)+(S^U&(A^S))+0xa4506ceb|0;K=K+E|0;E=E+(M&j^P&(M^j))+(M>>>2^M>>>13^M>>>22^M<<30^M<<19^M<<10)|0;k=(x>>>7^x>>>18^x>>>3^x<<25^x<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+k+y|0;S=k+S+(K>>>6^K>>>11^K>>>25^K<<26^K<<21^K<<7)+(A^K&(U^A))+0xbef9a3f7|0;P=P+S|0;S=S+(E&M^j&(E^M))+(E>>>2^E>>>13^E>>>22^E<<30^E<<19^E<<10)|0;x=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+x+b|0;A=x+A+(P>>>6^P>>>11^P>>>25^P<<26^P<<21^P<<7)+(U^P&(K^U))+0xc67178f2|0;j=j+A|0;A=A+(S&E^M&(S^E))+(S>>>2^S>>>13^S>>>22^S<<30^S<<19^S<<10)|0;n=n+A|0;i=i+S|0;a=a+E|0;s=s+M|0;o=o+j|0;u=u+P|0;f=f+K|0;c=c+U|0}function U(e){e=e|0;K(P[e|0]<<24|P[e|1]<<16|P[e|2]<<8|P[e|3],P[e|4]<<24|P[e|5]<<16|P[e|6]<<8|P[e|7],P[e|8]<<24|P[e|9]<<16|P[e|10]<<8|P[e|11],P[e|12]<<24|P[e|13]<<16|P[e|14]<<8|P[e|15],P[e|16]<<24|P[e|17]<<16|P[e|18]<<8|P[e|19],P[e|20]<<24|P[e|21]<<16|P[e|22]<<8|P[e|23],P[e|24]<<24|P[e|25]<<16|P[e|26]<<8|P[e|27],P[e|28]<<24|P[e|29]<<16|P[e|30]<<8|P[e|31],P[e|32]<<24|P[e|33]<<16|P[e|34]<<8|P[e|35],P[e|36]<<24|P[e|37]<<16|P[e|38]<<8|P[e|39],P[e|40]<<24|P[e|41]<<16|P[e|42]<<8|P[e|43],P[e|44]<<24|P[e|45]<<16|P[e|46]<<8|P[e|47],P[e|48]<<24|P[e|49]<<16|P[e|50]<<8|P[e|51],P[e|52]<<24|P[e|53]<<16|P[e|54]<<8|P[e|55],P[e|56]<<24|P[e|57]<<16|P[e|58]<<8|P[e|59],P[e|60]<<24|P[e|61]<<16|P[e|62]<<8|P[e|63])}function C(e){e=e|0;P[e|0]=n>>>24;P[e|1]=n>>>16&255;P[e|2]=n>>>8&255;P[e|3]=n&255;P[e|4]=i>>>24;P[e|5]=i>>>16&255;P[e|6]=i>>>8&255;P[e|7]=i&255;P[e|8]=a>>>24;P[e|9]=a>>>16&255;P[e|10]=a>>>8&255;P[e|11]=a&255;P[e|12]=s>>>24;P[e|13]=s>>>16&255;P[e|14]=s>>>8&255;P[e|15]=s&255;P[e|16]=o>>>24;P[e|17]=o>>>16&255;P[e|18]=o>>>8&255;P[e|19]=o&255;P[e|20]=u>>>24;P[e|21]=u>>>16&255;P[e|22]=u>>>8&255;P[e|23]=u&255;P[e|24]=f>>>24;P[e|25]=f>>>16&255;P[e|26]=f>>>8&255;P[e|27]=f&255;P[e|28]=c>>>24;P[e|29]=c>>>16&255;P[e|30]=c>>>8&255;P[e|31]=c&255}function B(){n=0x6a09e667;i=0xbb67ae85;a=0x3c6ef372;s=0xa54ff53a;o=0x510e527f;u=0x9b05688c;f=0x1f83d9ab;c=0x5be0cd19;d=l=0}function I(e,t,r,h,p,y,b,m,g,v){e=e|0;t=t|0;r=r|0;h=h|0;p=p|0;y=y|0;b=b|0;m=m|0;g=g|0;v=v|0;n=e;i=t;a=r;s=h;o=p;u=y;f=b;c=m;d=g;l=v}function T(e,t){e=e|0;t=t|0;var r=0;if(e&63)return-1;while((t|0)>=64){U(e);e=e+64|0;t=t-64|0;r=r+64|0}d=d+r|0;if(d>>>0>>0)l=l+1|0;return r|0}function O(e,t,r){e=e|0;t=t|0;r=r|0;var n=0,i=0;if(e&63)return-1;if(~r)if(r&31)return-1;if((t|0)>=64){n=T(e,t)|0;if((n|0)==-1)return-1;e=e+n|0;t=t-n|0}n=n+t|0;d=d+t|0;if(d>>>0>>0)l=l+1|0;P[e|t]=0x80;if((t|0)>=56){for(i=t+1|0;(i|0)<64;i=i+1|0){P[e|i]=0x00}U(e);t=0;P[e|0]=0}for(i=t+1|0;(i|0)<59;i=i+1|0){P[e|i]=0}P[e|56]=l>>>21&255;P[e|57]=l>>>13&255;P[e|58]=l>>>5&255;P[e|59]=l<<3&255|d>>>29;P[e|60]=d>>>21&255;P[e|61]=d>>>13&255;P[e|62]=d>>>5&255;P[e|63]=d<<3&255;U(e);if(~r)C(r);return n|0}function R(){n=h;i=p;a=y;s=b;o=m;u=g;f=v;c=_;d=64;l=0}function z(){n=w;i=k;a=x;s=A;o=S;u=E;f=M;c=j;d=64;l=0}function L(e,t,r,P,U,C,I,T,O,R,z,L,N,D,F,q){e=e|0;t=t|0;r=r|0;P=P|0;U=U|0;C=C|0;I=I|0;T=T|0;O=O|0;R=R|0;z=z|0;L=L|0;N=N|0;D=D|0;F=F|0;q=q|0;B();K(e^0x5c5c5c5c,t^0x5c5c5c5c,r^0x5c5c5c5c,P^0x5c5c5c5c,U^0x5c5c5c5c,C^0x5c5c5c5c,I^0x5c5c5c5c,T^0x5c5c5c5c,O^0x5c5c5c5c,R^0x5c5c5c5c,z^0x5c5c5c5c,L^0x5c5c5c5c,N^0x5c5c5c5c,D^0x5c5c5c5c,F^0x5c5c5c5c,q^0x5c5c5c5c);w=n;k=i;x=a;A=s;S=o;E=u;M=f;j=c;B();K(e^0x36363636,t^0x36363636,r^0x36363636,P^0x36363636,U^0x36363636,C^0x36363636,I^0x36363636,T^0x36363636,O^0x36363636,R^0x36363636,z^0x36363636,L^0x36363636,N^0x36363636,D^0x36363636,F^0x36363636,q^0x36363636);h=n;p=i;y=a;b=s;m=o;g=u;v=f;_=c;d=64;l=0}function N(e,t,r){e=e|0;t=t|0;r=r|0;var d=0,l=0,h=0,p=0,y=0,b=0,m=0,g=0,v=0;if(e&63)return-1;if(~r)if(r&31)return-1;v=O(e,t,-1)|0;d=n,l=i,h=a,p=s,y=o,b=u,m=f,g=c;z();K(d,l,h,p,y,b,m,g,0x80000000,0,0,0,0,0,0,768);if(~r)C(r);return v|0}function D(e,t,r,d,l){e=e|0;t=t|0;r=r|0;d=d|0;l=l|0;var h=0,p=0,y=0,b=0,m=0,g=0,v=0,_=0,w=0,k=0,x=0,A=0,S=0,E=0,M=0,j=0;if(e&63)return-1;if(~l)if(l&31)return-1;P[e+t|0]=r>>>24;P[e+t+1|0]=r>>>16&255;P[e+t+2|0]=r>>>8&255;P[e+t+3|0]=r&255;N(e,t+4|0,-1)|0;h=w=n,p=k=i,y=x=a,b=A=s,m=S=o,g=E=u,v=M=f,_=j=c;d=d-1|0;while((d|0)>0){R();K(w,k,x,A,S,E,M,j,0x80000000,0,0,0,0,0,0,768);w=n,k=i,x=a,A=s,S=o,E=u,M=f,j=c;z();K(w,k,x,A,S,E,M,j,0x80000000,0,0,0,0,0,0,768);w=n,k=i,x=a,A=s,S=o,E=u,M=f,j=c;h=h^n;p=p^i;y=y^a;b=b^s;m=m^o;g=g^u;v=v^f;_=_^c;d=d-1|0}n=h;i=p;a=y;s=b;o=m;u=g;f=v;c=_;if(~l)C(l);return 0}return{reset:B,init:I,process:T,finish:O,hmac_reset:R,hmac_init:L,hmac_finish:N,pbkdf2_generate_block:D}}},{}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r._sha256_hash_size=r._sha256_block_size=void 0,r.sha256_constructor=u,r.get_sha256_instance=function(){null===c&&(c=new u({heapSize:1048576}));return c};var n=e("./sha256.asm"),i=e("../hash"),a=e("../../utils"),s=r._sha256_block_size=64,o=r._sha256_hash_size=32;function u(e){e=e||{},this.heap=(0,a._heap_init)(Uint8Array,e.heap),this.asm=e.asm||(0,n.sha256_asm)({Uint8Array:Uint8Array},null,this.heap.buffer),this.BLOCK_SIZE=s,this.HASH_SIZE=o,this.reset()}u.BLOCK_SIZE=s,u.HASH_SIZE=o,u.NAME="sha256";var f=u.prototype;f.reset=i.hash_reset,f.process=i.hash_process,f.finish=i.hash_finish;var c=null},{"../../utils":15,"../hash":11,"./sha256.asm":13}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.string_to_bytes=n,r.hex_to_bytes=function(e){var t=e.length;1&t&&(e="0"+e,t++);for(var r=new Uint8Array(t>>1),n=0;n>1]=parseInt(e.substr(n,2),16);return r},r.base64_to_bytes=function(e){return n(atob(e))},r.bytes_to_string=i,r.bytes_to_hex=function(e){for(var t="",r=0;r>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+=1},r.is_number=function(e){return"number"==typeof e},r.is_string=function(e){return"string"==typeof e},r.is_buffer=function(e){return e instanceof ArrayBuffer},r.is_bytes=function(e){return e instanceof Uint8Array},r.is_typed_array=function(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array},r._heap_init=function(e,t,r){var n=t?t.byteLength:r||65536;if(4095&n||n<=0)throw new Error("heap size must be a positive integer and a multiple of 4096");return t=t||new e(new ArrayBuffer(n))},r._heap_write=function(e,t,r,n,i){var a=e.length-t,s=a=r)throw new Error("Malformed string, low surrogate expected at position "+i);s=(55296^s)<<10|65536|56320^e.charCodeAt(i)}else if(!t&&s>>>8)throw new Error("Wide characters are not allowed.");!t||s<=127?n[a++]=s:s<=2047?(n[a++]=192|s>>6,n[a++]=128|63&s):s<=65535?(n[a++]=224|s>>12,n[a++]=128|s>>6&63,n[a++]=128|63&s):(n[a++]=240|s>>18,n[a++]=128|s>>12&63,n[a++]=128|s>>6&63,n[a++]=128|63&s)}return n.subarray(0,a)}function i(e,t){t=!!t;for(var r=e.length,n=new Array(r),i=0,a=0;i=192&&s<224&&i+1=224&&s<240&&i+2=240&&s<248&&i+3>10,n[a++]=56320|1023&o)}}var u="";for(i=0;i0?u-4:u;var c=0;for(t=0;t>16&255,o[c++]=n>>8&255,o[c++]=255&n;2===s?(n=i[e.charCodeAt(t)]<<2|i[e.charCodeAt(t+1)]>>4,o[c++]=255&n):1===s&&(n=i[e.charCodeAt(t)]<<10|i[e.charCodeAt(t+1)]<<4|i[e.charCodeAt(t+2)]>>2,o[c++]=n>>8&255,o[c++]=255&n);return o},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,a="",s=[],o=0,u=r-i;ou?u:o+16383));1===i?(t=e[r-1],a+=n[t>>2],a+=n[t<<4&63],a+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],a+=n[t>>10],a+=n[t>>4&63],a+=n[t<<2&63],a+="=");return s.push(a),s.join("")};for(var n=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,u=s.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function c(e,t,r){for(var i,a,s=[],o=t;o>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],37:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function a(e,t,r){if(a.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var s;"object"==typeof t?t.exports=a:r.BN=a,a.BN=a,a.wordSize=26;try{s=e("buffer").Buffer}catch(e){}function o(e,t,r){for(var n=0,i=Math.min(e.length,r),a=t;a=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return n}function u(e,t,r,n){for(var i=0,a=Math.min(e.length,r),s=t;s=49?o-49+10:o>=17?o-17+10:o}return i}a.isBN=function(e){return e instanceof a||null!==e&&"object"==typeof e&&e.constructor.wordSize===a.wordSize&&Array.isArray(e.words)},a.max=function(e,t){return e.cmp(t)>0?e:t},a.min=function(e,t){return e.cmp(t)<0?e:t},a.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},a.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},a.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[a]|=s<>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);else if("le"===r)for(i=0,a=0;i>>26-o&67108863,(o+=24)>=26&&(o-=26,a++);return this.strip()},a.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=o(e,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==t&&(i=o(e,t,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},a.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var a=e.length-r,s=a%n,o=Math.min(a,a-s)+r,f=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var f=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],c=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],a=0|t.words[0],s=i*a,o=67108863&s,u=s/67108864|0;r.words[0]=o;for(var f=1;f>>26,d=67108863&u,l=Math.min(f,t.length-1),h=Math.max(0,f-e.length+1);h<=l;h++){var p=f-h|0;c+=(s=(i=0|e.words[p])*(a=0|t.words[h])+d)/67108864|0,d=67108863&s}r.words[f]=0|d,u=0|c}return 0!==u?r.words[f]=0|u:r.length--,r.strip()}a.prototype.toString=function(e,t){var r;if(e=e||10,t=0|t||1,16===e||"hex"===e){r="";for(var i=0,a=0,s=0;s>>24-i&16777215)||s!==this.length-1?f[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,s--)}for(0!==a&&(r=a.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=c[e],h=d[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var y=p.modn(h).toString(e);r=(p=p.idivn(h)).isZero()?y+r:f[l-y.length]+y+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(e,t){return n(void 0!==s),this.toArrayLike(s,e,t)},a.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},a.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),a=r||Math.max(1,i);n(i<=a,"byte array longer than desired length"),n(a>0,"Requested array length <= 0"),this.strip();var s,o,u="le"===t,f=new e(a),c=this.clone();if(u){for(o=0;!c.isZero();o++)s=c.andln(255),c.iushrn(8),f[o]=s;for(;o=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},a.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},a.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},a.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},a.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},a.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},a.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},a.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},a.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},a.prototype.notn=function(e){return this.clone().inotn(e)},a.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ae.length?this.clone().iadd(e):e.clone().iadd(this)},a.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var a=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==a&&s>26,this.words[s]=67108863&t;if(0===a&&s>>13,h=0|s[1],p=8191&h,y=h>>>13,b=0|s[2],m=8191&b,g=b>>>13,v=0|s[3],_=8191&v,w=v>>>13,k=0|s[4],x=8191&k,A=k>>>13,S=0|s[5],E=8191&S,M=S>>>13,j=0|s[6],P=8191&j,K=j>>>13,U=0|s[7],C=8191&U,B=U>>>13,I=0|s[8],T=8191&I,O=I>>>13,R=0|s[9],z=8191&R,L=R>>>13,N=0|o[0],D=8191&N,F=N>>>13,q=0|o[1],G=8191&q,H=q>>>13,Z=0|o[2],V=8191&Z,W=Z>>>13,Y=0|o[3],J=8191&Y,X=Y>>>13,$=0|o[4],Q=8191&$,ee=$>>>13,te=0|o[5],re=8191&te,ne=te>>>13,ie=0|o[6],ae=8191&ie,se=ie>>>13,oe=0|o[7],ue=8191&oe,fe=oe>>>13,ce=0|o[8],de=8191&ce,le=ce>>>13,he=0|o[9],pe=8191&he,ye=he>>>13;r.negative=e.negative^t.negative,r.length=19;var be=(f+(n=Math.imul(d,D))|0)+((8191&(i=(i=Math.imul(d,F))+Math.imul(l,D)|0))<<13)|0;f=((a=Math.imul(l,F))+(i>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(p,D),i=(i=Math.imul(p,F))+Math.imul(y,D)|0,a=Math.imul(y,F);var me=(f+(n=n+Math.imul(d,G)|0)|0)+((8191&(i=(i=i+Math.imul(d,H)|0)+Math.imul(l,G)|0))<<13)|0;f=((a=a+Math.imul(l,H)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,D),i=(i=Math.imul(m,F))+Math.imul(g,D)|0,a=Math.imul(g,F),n=n+Math.imul(p,G)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(y,G)|0,a=a+Math.imul(y,H)|0;var ge=(f+(n=n+Math.imul(d,V)|0)|0)+((8191&(i=(i=i+Math.imul(d,W)|0)+Math.imul(l,V)|0))<<13)|0;f=((a=a+Math.imul(l,W)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(_,D),i=(i=Math.imul(_,F))+Math.imul(w,D)|0,a=Math.imul(w,F),n=n+Math.imul(m,G)|0,i=(i=i+Math.imul(m,H)|0)+Math.imul(g,G)|0,a=a+Math.imul(g,H)|0,n=n+Math.imul(p,V)|0,i=(i=i+Math.imul(p,W)|0)+Math.imul(y,V)|0,a=a+Math.imul(y,W)|0;var ve=(f+(n=n+Math.imul(d,J)|0)|0)+((8191&(i=(i=i+Math.imul(d,X)|0)+Math.imul(l,J)|0))<<13)|0;f=((a=a+Math.imul(l,X)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(x,D),i=(i=Math.imul(x,F))+Math.imul(A,D)|0,a=Math.imul(A,F),n=n+Math.imul(_,G)|0,i=(i=i+Math.imul(_,H)|0)+Math.imul(w,G)|0,a=a+Math.imul(w,H)|0,n=n+Math.imul(m,V)|0,i=(i=i+Math.imul(m,W)|0)+Math.imul(g,V)|0,a=a+Math.imul(g,W)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,X)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,X)|0;var _e=(f+(n=n+Math.imul(d,Q)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(l,Q)|0))<<13)|0;f=((a=a+Math.imul(l,ee)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(E,D),i=(i=Math.imul(E,F))+Math.imul(M,D)|0,a=Math.imul(M,F),n=n+Math.imul(x,G)|0,i=(i=i+Math.imul(x,H)|0)+Math.imul(A,G)|0,a=a+Math.imul(A,H)|0,n=n+Math.imul(_,V)|0,i=(i=i+Math.imul(_,W)|0)+Math.imul(w,V)|0,a=a+Math.imul(w,W)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,X)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(y,Q)|0,a=a+Math.imul(y,ee)|0;var we=(f+(n=n+Math.imul(d,re)|0)|0)+((8191&(i=(i=i+Math.imul(d,ne)|0)+Math.imul(l,re)|0))<<13)|0;f=((a=a+Math.imul(l,ne)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(P,D),i=(i=Math.imul(P,F))+Math.imul(K,D)|0,a=Math.imul(K,F),n=n+Math.imul(E,G)|0,i=(i=i+Math.imul(E,H)|0)+Math.imul(M,G)|0,a=a+Math.imul(M,H)|0,n=n+Math.imul(x,V)|0,i=(i=i+Math.imul(x,W)|0)+Math.imul(A,V)|0,a=a+Math.imul(A,W)|0,n=n+Math.imul(_,J)|0,i=(i=i+Math.imul(_,X)|0)+Math.imul(w,J)|0,a=a+Math.imul(w,X)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(g,Q)|0,a=a+Math.imul(g,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(y,re)|0,a=a+Math.imul(y,ne)|0;var ke=(f+(n=n+Math.imul(d,ae)|0)|0)+((8191&(i=(i=i+Math.imul(d,se)|0)+Math.imul(l,ae)|0))<<13)|0;f=((a=a+Math.imul(l,se)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(C,D),i=(i=Math.imul(C,F))+Math.imul(B,D)|0,a=Math.imul(B,F),n=n+Math.imul(P,G)|0,i=(i=i+Math.imul(P,H)|0)+Math.imul(K,G)|0,a=a+Math.imul(K,H)|0,n=n+Math.imul(E,V)|0,i=(i=i+Math.imul(E,W)|0)+Math.imul(M,V)|0,a=a+Math.imul(M,W)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,X)|0)+Math.imul(A,J)|0,a=a+Math.imul(A,X)|0,n=n+Math.imul(_,Q)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(w,Q)|0,a=a+Math.imul(w,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(g,re)|0,a=a+Math.imul(g,ne)|0,n=n+Math.imul(p,ae)|0,i=(i=i+Math.imul(p,se)|0)+Math.imul(y,ae)|0,a=a+Math.imul(y,se)|0;var xe=(f+(n=n+Math.imul(d,ue)|0)|0)+((8191&(i=(i=i+Math.imul(d,fe)|0)+Math.imul(l,ue)|0))<<13)|0;f=((a=a+Math.imul(l,fe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(T,D),i=(i=Math.imul(T,F))+Math.imul(O,D)|0,a=Math.imul(O,F),n=n+Math.imul(C,G)|0,i=(i=i+Math.imul(C,H)|0)+Math.imul(B,G)|0,a=a+Math.imul(B,H)|0,n=n+Math.imul(P,V)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(K,V)|0,a=a+Math.imul(K,W)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,X)|0)+Math.imul(M,J)|0,a=a+Math.imul(M,X)|0,n=n+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(A,Q)|0,a=a+Math.imul(A,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(w,re)|0,a=a+Math.imul(w,ne)|0,n=n+Math.imul(m,ae)|0,i=(i=i+Math.imul(m,se)|0)+Math.imul(g,ae)|0,a=a+Math.imul(g,se)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,fe)|0)+Math.imul(y,ue)|0,a=a+Math.imul(y,fe)|0;var Ae=(f+(n=n+Math.imul(d,de)|0)|0)+((8191&(i=(i=i+Math.imul(d,le)|0)+Math.imul(l,de)|0))<<13)|0;f=((a=a+Math.imul(l,le)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(z,D),i=(i=Math.imul(z,F))+Math.imul(L,D)|0,a=Math.imul(L,F),n=n+Math.imul(T,G)|0,i=(i=i+Math.imul(T,H)|0)+Math.imul(O,G)|0,a=a+Math.imul(O,H)|0,n=n+Math.imul(C,V)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(B,V)|0,a=a+Math.imul(B,W)|0,n=n+Math.imul(P,J)|0,i=(i=i+Math.imul(P,X)|0)+Math.imul(K,J)|0,a=a+Math.imul(K,X)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Q)|0,a=a+Math.imul(M,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(A,re)|0,a=a+Math.imul(A,ne)|0,n=n+Math.imul(_,ae)|0,i=(i=i+Math.imul(_,se)|0)+Math.imul(w,ae)|0,a=a+Math.imul(w,se)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,fe)|0)+Math.imul(g,ue)|0,a=a+Math.imul(g,fe)|0,n=n+Math.imul(p,de)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(y,de)|0,a=a+Math.imul(y,le)|0;var Se=(f+(n=n+Math.imul(d,pe)|0)|0)+((8191&(i=(i=i+Math.imul(d,ye)|0)+Math.imul(l,pe)|0))<<13)|0;f=((a=a+Math.imul(l,ye)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(z,G),i=(i=Math.imul(z,H))+Math.imul(L,G)|0,a=Math.imul(L,H),n=n+Math.imul(T,V)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(O,V)|0,a=a+Math.imul(O,W)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,X)|0)+Math.imul(B,J)|0,a=a+Math.imul(B,X)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(K,Q)|0,a=a+Math.imul(K,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,a=a+Math.imul(M,ne)|0,n=n+Math.imul(x,ae)|0,i=(i=i+Math.imul(x,se)|0)+Math.imul(A,ae)|0,a=a+Math.imul(A,se)|0,n=n+Math.imul(_,ue)|0,i=(i=i+Math.imul(_,fe)|0)+Math.imul(w,ue)|0,a=a+Math.imul(w,fe)|0,n=n+Math.imul(m,de)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(g,de)|0,a=a+Math.imul(g,le)|0;var Ee=(f+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,ye)|0)+Math.imul(y,pe)|0))<<13)|0;f=((a=a+Math.imul(y,ye)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(z,V),i=(i=Math.imul(z,W))+Math.imul(L,V)|0,a=Math.imul(L,W),n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(O,J)|0,a=a+Math.imul(O,X)|0,n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,ee)|0)+Math.imul(B,Q)|0,a=a+Math.imul(B,ee)|0,n=n+Math.imul(P,re)|0,i=(i=i+Math.imul(P,ne)|0)+Math.imul(K,re)|0,a=a+Math.imul(K,ne)|0,n=n+Math.imul(E,ae)|0,i=(i=i+Math.imul(E,se)|0)+Math.imul(M,ae)|0,a=a+Math.imul(M,se)|0,n=n+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,fe)|0)+Math.imul(A,ue)|0,a=a+Math.imul(A,fe)|0,n=n+Math.imul(_,de)|0,i=(i=i+Math.imul(_,le)|0)+Math.imul(w,de)|0,a=a+Math.imul(w,le)|0;var Me=(f+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,ye)|0)+Math.imul(g,pe)|0))<<13)|0;f=((a=a+Math.imul(g,ye)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(z,J),i=(i=Math.imul(z,X))+Math.imul(L,J)|0,a=Math.imul(L,X),n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(O,Q)|0,a=a+Math.imul(O,ee)|0,n=n+Math.imul(C,re)|0,i=(i=i+Math.imul(C,ne)|0)+Math.imul(B,re)|0,a=a+Math.imul(B,ne)|0,n=n+Math.imul(P,ae)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(K,ae)|0,a=a+Math.imul(K,se)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,fe)|0)+Math.imul(M,ue)|0,a=a+Math.imul(M,fe)|0,n=n+Math.imul(x,de)|0,i=(i=i+Math.imul(x,le)|0)+Math.imul(A,de)|0,a=a+Math.imul(A,le)|0;var je=(f+(n=n+Math.imul(_,pe)|0)|0)+((8191&(i=(i=i+Math.imul(_,ye)|0)+Math.imul(w,pe)|0))<<13)|0;f=((a=a+Math.imul(w,ye)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(z,Q),i=(i=Math.imul(z,ee))+Math.imul(L,Q)|0,a=Math.imul(L,ee),n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(O,re)|0,a=a+Math.imul(O,ne)|0,n=n+Math.imul(C,ae)|0,i=(i=i+Math.imul(C,se)|0)+Math.imul(B,ae)|0,a=a+Math.imul(B,se)|0,n=n+Math.imul(P,ue)|0,i=(i=i+Math.imul(P,fe)|0)+Math.imul(K,ue)|0,a=a+Math.imul(K,fe)|0,n=n+Math.imul(E,de)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(M,de)|0,a=a+Math.imul(M,le)|0;var Pe=(f+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,ye)|0)+Math.imul(A,pe)|0))<<13)|0;f=((a=a+Math.imul(A,ye)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(z,re),i=(i=Math.imul(z,ne))+Math.imul(L,re)|0,a=Math.imul(L,ne),n=n+Math.imul(T,ae)|0,i=(i=i+Math.imul(T,se)|0)+Math.imul(O,ae)|0,a=a+Math.imul(O,se)|0,n=n+Math.imul(C,ue)|0,i=(i=i+Math.imul(C,fe)|0)+Math.imul(B,ue)|0,a=a+Math.imul(B,fe)|0,n=n+Math.imul(P,de)|0,i=(i=i+Math.imul(P,le)|0)+Math.imul(K,de)|0,a=a+Math.imul(K,le)|0;var Ke=(f+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,ye)|0)+Math.imul(M,pe)|0))<<13)|0;f=((a=a+Math.imul(M,ye)|0)+(i>>>13)|0)+(Ke>>>26)|0,Ke&=67108863,n=Math.imul(z,ae),i=(i=Math.imul(z,se))+Math.imul(L,ae)|0,a=Math.imul(L,se),n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,fe)|0)+Math.imul(O,ue)|0,a=a+Math.imul(O,fe)|0,n=n+Math.imul(C,de)|0,i=(i=i+Math.imul(C,le)|0)+Math.imul(B,de)|0,a=a+Math.imul(B,le)|0;var Ue=(f+(n=n+Math.imul(P,pe)|0)|0)+((8191&(i=(i=i+Math.imul(P,ye)|0)+Math.imul(K,pe)|0))<<13)|0;f=((a=a+Math.imul(K,ye)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(z,ue),i=(i=Math.imul(z,fe))+Math.imul(L,ue)|0,a=Math.imul(L,fe),n=n+Math.imul(T,de)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(O,de)|0,a=a+Math.imul(O,le)|0;var Ce=(f+(n=n+Math.imul(C,pe)|0)|0)+((8191&(i=(i=i+Math.imul(C,ye)|0)+Math.imul(B,pe)|0))<<13)|0;f=((a=a+Math.imul(B,ye)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(z,de),i=(i=Math.imul(z,le))+Math.imul(L,de)|0,a=Math.imul(L,le);var Be=(f+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,ye)|0)+Math.imul(O,pe)|0))<<13)|0;f=((a=a+Math.imul(O,ye)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863;var Ie=(f+(n=Math.imul(z,pe))|0)+((8191&(i=(i=Math.imul(z,ye))+Math.imul(L,pe)|0))<<13)|0;return f=((a=Math.imul(L,ye))+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,u[0]=be,u[1]=me,u[2]=ge,u[3]=ve,u[4]=_e,u[5]=we,u[6]=ke,u[7]=xe,u[8]=Ae,u[9]=Se,u[10]=Ee,u[11]=Me,u[12]=je,u[13]=Pe,u[14]=Ke,u[15]=Ue,u[16]=Ce,u[17]=Be,u[18]=Ie,0!==f&&(u[19]=f,r.length++),r};function p(e,t,r){return(new y).mulp(e,t,r)}function y(e,t){this.x=e,this.y=t}Math.imul||(h=l),a.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?h(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,s&=67108863}r.words[a]=o,n=s,s=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},y.prototype.makeRBT=function(e){for(var t=new Array(e),r=a.prototype._countBits(e)-1,n=0;n>=1;return n},y.prototype.permute=function(e,t,r,n,i,a){for(var s=0;s>>=1)i++;return 1<>>=13,r[2*s+1]=8191&a,a>>>=13;for(s=2*t;s>=26,t+=i/67108864|0,t+=a>>>26,this.words[r]=67108863&a}return 0!==t&&(this.words[r]=t,this.length++),this},a.prototype.muln=function(e){return this.clone().imuln(e)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new a(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,a=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var a=e%26,s=Math.min((e-a)/26,this.length),o=67108863^67108863>>>a<s)for(this.length-=s,f=0;f=0&&(0!==c||f>=i);f--){var d=0|this.words[f];this.words[f]=c<<26-a|d>>>a,c=d&o}return u&&0!==c&&(u.words[u.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},a.prototype.shln=function(e){return this.clone().ishln(e)},a.prototype.ushln=function(e){return this.clone().iushln(e)},a.prototype.shrn=function(e){return this.clone().ishrn(e)},a.prototype.ushrn=function(e){return this.clone().iushrn(e)},a.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},a.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&a}for(;i>26,this.words[i+r]=67108863&a;if(0===o)return this.strip();for(n(-1===o),o=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},a.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,s=0|i.words[i.length-1];0!==(r=26-this._countBits(s))&&(i=i.ushln(r),n.iushln(r),s=0|i.words[i.length-1]);var o,u=n.length-i.length;if("mod"!==t){(o=new a(null)).length=u+1,o.words=new Array(o.length);for(var f=0;f=0;d--){var l=67108864*(0|n.words[i.length+d])+(0|n.words[i.length+d-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(i,l,d);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,d),n.isZero()||(n.negative^=1);o&&(o.words[d]=l)}return o&&o.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:o||null,mod:n}},a.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(i=o.div.neg()),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(i=o.div.neg()),{div:i,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new a(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new a(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new a(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,s,o},a.prototype.div=function(e){return this.divmod(e,"div",!1).div},a.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},a.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},a.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},a.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},a.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},a.prototype.divn=function(e){return this.clone().idivn(e)},a.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new a(1),s=new a(0),o=new a(0),u=new a(1),f=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++f;for(var c=r.clone(),d=t.clone();!t.isZero();){for(var l=0,h=1;0==(t.words[0]&h)&&l<26;++l,h<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(c),s.isub(d)),i.iushrn(1),s.iushrn(1);for(var p=0,y=1;0==(r.words[0]&y)&&p<26;++p,y<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(o.isOdd()||u.isOdd())&&(o.iadd(c),u.isub(d)),o.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(o),s.isub(u)):(r.isub(t),o.isub(i),u.isub(s))}return{a:o,b:u,gcd:r.iushln(f)}},a.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new a(1),o=new a(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var f=0,c=1;0==(t.words[0]&c)&&f<26;++f,c<<=1);if(f>0)for(t.iushrn(f);f-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);for(var d=0,l=1;0==(r.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(r.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(o)):(r.isub(t),o.isub(s))}return(i=0===t.cmpn(1)?s:o).cmpn(0)<0&&i.iadd(e),i},a.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var a=t;t=r,r=a}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},a.prototype.invm=function(e){return this.egcd(e).a.umod(e)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(e){return this.words[0]&e},a.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,o&=67108863,this.words[s]=o}return 0!==a&&(this.words[s]=a,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},a.prototype.gtn=function(e){return 1===this.cmpn(e)},a.prototype.gt=function(e){return 1===this.cmp(e)},a.prototype.gten=function(e){return this.cmpn(e)>=0},a.prototype.gte=function(e){return this.cmp(e)>=0},a.prototype.ltn=function(e){return-1===this.cmpn(e)},a.prototype.lt=function(e){return-1===this.cmp(e)},a.prototype.lten=function(e){return this.cmpn(e)<=0},a.prototype.lte=function(e){return this.cmp(e)<=0},a.prototype.eqn=function(e){return 0===this.cmpn(e)},a.prototype.eq=function(e){return 0===this.cmp(e)},a.red=function(e){return new k(e)},a.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},a.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(e){return this.red=e,this},a.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},a.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},a.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},a.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},a.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},a.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},a.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},a.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},a.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var b={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new a(t,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function _(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function w(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function k(e){if("string"==typeof e){var t=a._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function x(e){k.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var e=new a(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(g,m),g.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=a}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},g.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},a._prime=function(e){if(b[e])return b[e];var t;if("k256"===e)t=new g;else if("p224"===e)t=new v;else if("p192"===e)t=new _;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new w}return b[e]=t,t},k.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},k.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},k.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},k.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},k.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},k.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},k.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},k.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},k.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},k.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},k.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},k.prototype.isqr=function(e){return this.imul(e,e.clone())},k.prototype.sqr=function(e){return this.mul(e,e)},k.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new a(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);n(!i.isZero());var o=new a(1).toRed(this),u=o.redNeg(),f=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new a(2*c*c).toRed(this);0!==this.pow(c,f).cmp(u);)c.redIAdd(u);for(var d=this.pow(c,i),l=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=s;0!==h.cmp(o);){for(var y=h,b=0;0!==y.cmp(o);b++)y=y.redSqr();n(b=0;n--){for(var f=t.words[n],c=u-1;c>=0;c--){var d=f>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==d||0!==s?(s<<=1,s|=d,(4===++o||0===n&&0===c)&&(i=this.mul(i,r[s]),o=0,s=0)):o=0}u=26}return i},k.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},k.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},a.mont=function(e){return new x(e)},i(x,k),x.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},x.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},x.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},x.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new a(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},x.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:39}],38:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;ra)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return c(e)}return u(e,t,r)}function u(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return N(e)?function(e,t,r){if(t<0||e.byteLength=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function h(e,t){if(o.isBuffer(e))return e.length;if(D(e)||N(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return R(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return z(e).length;default:if(n)return R(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),F(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=o.from(t,n)),o.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){var a,s=1,o=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,o/=2,u/=2,r/=2}function f(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var c=-1;for(a=r;ao&&(r=o-u),a=r;a>=0;a--){for(var d=!0,l=0;li&&(n=i):n=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var s=0;s>8,i=r%256,a.push(i),a.push(n);return a}(t,e.length-r),e,r,n)}function x(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:f>223?3:f>191?2:1;if(i+d<=r)switch(d){case 1:f<128&&(c=f);break;case 2:128==(192&(a=e[i+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=e[i+1],s=e[i+2],128==(192&a)&&128==(192&s)&&(u=(15&f)<<12|(63&a)<<6|63&s)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=e[i+1],s=e[i+2],o=e[i+3],128==(192&a)&&128==(192&s)&&128==(192&o)&&(u=(15&f)<<18|(63&a)<<12|(63&s)<<6|63&o)>65535&&u<1114112&&(c=u)}null===c?(c=65533,d=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=d}return function(e){var t=e.length;if(t<=S)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return j(this,t,r);case"utf8":case"utf-8":return A(this,t,r);case"ascii":return E(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},o.prototype.compare=function(e,t,r,n,i){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var a=i-n,s=r-t,u=Math.min(a,s),f=this.slice(n,i),c=e.slice(t,r),d=0;d>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return g(this,e,t,r);case"ascii":return v(this,e,t,r);case"latin1":case"binary":return _(this,e,t,r);case"base64":return w(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var S=4096;function E(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,r,n,i,a){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function C(e,t,r,n,i,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(e,t,r,n,a){return t=+t,r>>>=0,a||C(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function I(e,t,r,n,a){return t=+t,r>>>=0,a||C(e,0,r,8),i.write(e,t,r,n,52,8),r+8}o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||K(e,t,this.length);for(var n=this[e],i=1,a=0;++a>>=0,t>>>=0,r||K(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},o.prototype.readUInt8=function(e,t){return e>>>=0,t||K(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||K(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||K(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||K(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||K(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||K(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||K(e,t,this.length);for(var n=t,i=1,a=this[e+--n];n>0&&(i*=256);)a+=this[e+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},o.prototype.readInt8=function(e,t){return e>>>=0,t||K(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||K(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||K(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||K(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||K(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||K(e,4,this.length),i.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||K(e,4,this.length),i.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||K(e,8,this.length),i.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||K(e,8,this.length),i.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||U(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,n)||U(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[t+i]=255&e;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);U(this,e,t,r,i-1,-i)}var a=0,s=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);U(this,e,t,r,i-1,-i)}var a=r-1,s=1,o=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/s>>0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return B(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return B(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return I(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return I(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(a<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function z(e){return n.toByteArray(function(e){if((e=e.trim().replace(T,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function L(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function N(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function D(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function F(e){return e!=e}},{"base64-js":36,ieee754:278}],41:[function(e,t,r){e("../../modules/es6.array.fill"),t.exports=e("../../modules/_core").Array.fill},{"../../modules/_core":164,"../../modules/es6.array.fill":234}],42:[function(e,t,r){e("../../modules/es6.array.find"),t.exports=e("../../modules/_core").Array.find},{"../../modules/_core":164,"../../modules/es6.array.find":235}],43:[function(e,t,r){e("../../modules/es6.string.iterator"),e("../../modules/es6.array.from"),t.exports=e("../../modules/_core").Array.from},{"../../modules/_core":164,"../../modules/es6.array.from":236,"../../modules/es6.string.iterator":240}],44:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/es6.string.iterator"),e("../modules/web.dom.iterable"),e("../modules/es6.promise"),e("../modules/es7.promise.finally"),e("../modules/es7.promise.try"),t.exports=e("../modules/_core").Promise},{"../modules/_core":164,"../modules/es6.object.to-string":238,"../modules/es6.promise":239,"../modules/es6.string.iterator":240,"../modules/es7.promise.finally":244,"../modules/es7.promise.try":245,"../modules/web.dom.iterable":248}],45:[function(e,t,r){e("../../modules/es6.string.repeat"),t.exports=e("../../modules/_core").String.repeat},{"../../modules/_core":164,"../../modules/es6.string.repeat":241}],46:[function(e,t,r){e("../../modules/es6.symbol"),e("../../modules/es6.object.to-string"),e("../../modules/es7.symbol.async-iterator"),e("../../modules/es7.symbol.observable"),t.exports=e("../../modules/_core").Symbol},{"../../modules/_core":164,"../../modules/es6.object.to-string":238,"../../modules/es6.symbol":242,"../../modules/es7.symbol.async-iterator":246,"../../modules/es7.symbol.observable":247}],47:[function(e,t,r){e("../../modules/es6.typed.uint8-array"),t.exports=e("../../modules/_core").Uint8Array},{"../../modules/_core":164,"../../modules/es6.typed.uint8-array":243}],48:[function(e,t,r){arguments[4][43][0].apply(r,arguments)},{"../../modules/_core":67,"../../modules/es6.array.from":136,"../../modules/es6.string.iterator":145,dup:43}],49:[function(e,t,r){e("../modules/web.dom.iterable"),e("../modules/es6.string.iterator"),t.exports=e("../modules/core.get-iterator")},{"../modules/core.get-iterator":134,"../modules/es6.string.iterator":145,"../modules/web.dom.iterable":151}],50:[function(e,t,r){e("../modules/web.dom.iterable"),e("../modules/es6.string.iterator"),t.exports=e("../modules/core.is-iterable")},{"../modules/core.is-iterable":135,"../modules/es6.string.iterator":145,"../modules/web.dom.iterable":151}],51:[function(e,t,r){var n=e("../../modules/_core"),i=n.JSON||(n.JSON={stringify:JSON.stringify});t.exports=function(e){return i.stringify.apply(i,arguments)}},{"../../modules/_core":67}],52:[function(e,t,r){e("../../modules/es6.object.create");var n=e("../../modules/_core").Object;t.exports=function(e,t){return n.create(e,t)}},{"../../modules/_core":67,"../../modules/es6.object.create":138}],53:[function(e,t,r){e("../../modules/es6.object.define-property");var n=e("../../modules/_core").Object;t.exports=function(e,t,r){return n.defineProperty(e,t,r)}},{"../../modules/_core":67,"../../modules/es6.object.define-property":139}],54:[function(e,t,r){e("../../modules/es6.object.freeze"),t.exports=e("../../modules/_core").Object.freeze},{"../../modules/_core":67,"../../modules/es6.object.freeze":140}],55:[function(e,t,r){e("../../modules/es6.object.get-prototype-of"),t.exports=e("../../modules/_core").Object.getPrototypeOf},{"../../modules/_core":67,"../../modules/es6.object.get-prototype-of":141}],56:[function(e,t,r){e("../../modules/es6.object.set-prototype-of"),t.exports=e("../../modules/_core").Object.setPrototypeOf},{"../../modules/_core":67,"../../modules/es6.object.set-prototype-of":142}],57:[function(e,t,r){arguments[4][44][0].apply(r,arguments)},{"../modules/_core":67,"../modules/es6.object.to-string":143,"../modules/es6.promise":144,"../modules/es6.string.iterator":145,"../modules/es7.promise.finally":147,"../modules/es7.promise.try":148,"../modules/web.dom.iterable":151,dup:44}],58:[function(e,t,r){arguments[4][46][0].apply(r,arguments)},{"../../modules/_core":67,"../../modules/es6.object.to-string":143,"../../modules/es6.symbol":146,"../../modules/es7.symbol.async-iterator":149,"../../modules/es7.symbol.observable":150,dup:46}],59:[function(e,t,r){e("../../modules/es6.string.iterator"),e("../../modules/web.dom.iterable"),t.exports=e("../../modules/_wks-ext").f("iterator")},{"../../modules/_wks-ext":131,"../../modules/es6.string.iterator":145,"../../modules/web.dom.iterable":151}],60:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},{}],61:[function(e,t,r){t.exports=function(){}},{}],62:[function(e,t,r){t.exports=function(e,t,r,n){if(!(e instanceof t)||void 0!==n&&n in e)throw TypeError(r+": incorrect invocation!");return e}},{}],63:[function(e,t,r){var n=e("./_is-object");t.exports=function(e){if(!n(e))throw TypeError(e+" is not an object!");return e}},{"./_is-object":87}],64:[function(e,t,r){var n=e("./_to-iobject"),i=e("./_to-length"),a=e("./_to-absolute-index");t.exports=function(e){return function(t,r,s){var o,u=n(t),f=i(u.length),c=a(s,f);if(e&&r!=r){for(;f>c;)if((o=u[c++])!=o)return!0}else for(;f>c;c++)if((e||c in u)&&u[c]===r)return e||c||0;return!e&&-1}}},{"./_to-absolute-index":123,"./_to-iobject":125,"./_to-length":126}],65:[function(e,t,r){var n=e("./_cof"),i=e("./_wks")("toStringTag"),a="Arguments"==n(function(){return arguments}());t.exports=function(e){var t,r,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),i))?r:a?n(t):"Object"==(s=n(t))&&"function"==typeof t.callee?"Arguments":s}},{"./_cof":66,"./_wks":132}],66:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],67:[function(e,t,r){var n=t.exports={version:"2.5.3"};"number"==typeof __e&&(__e=n)},{}],68:[function(e,t,r){"use strict";var n=e("./_object-dp"),i=e("./_property-desc");t.exports=function(e,t,r){t in e?n.f(e,t,i(0,r)):e[t]=r}},{"./_object-dp":99,"./_property-desc":112}],69:[function(e,t,r){var n=e("./_a-function");t.exports=function(e,t,r){if(n(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)}}return function(){return e.apply(t,arguments)}}},{"./_a-function":60}],70:[function(e,t,r){t.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},{}],71:[function(e,t,r){t.exports=!e("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":76}],72:[function(e,t,r){var n=e("./_is-object"),i=e("./_global").document,a=n(i)&&n(i.createElement);t.exports=function(e){return a?i.createElement(e):{}}},{"./_global":78,"./_is-object":87}],73:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],74:[function(e,t,r){var n=e("./_object-keys"),i=e("./_object-gops"),a=e("./_object-pie");t.exports=function(e){var t=n(e),r=i.f;if(r)for(var s,o=r(e),u=a.f,f=0;o.length>f;)u.call(e,s=o[f++])&&t.push(s);return t}},{"./_object-gops":104,"./_object-keys":107,"./_object-pie":108}],75:[function(e,t,r){var n=e("./_global"),i=e("./_core"),a=e("./_ctx"),s=e("./_hide"),o=function(e,t,r){var u,f,c,d=e&o.F,l=e&o.G,h=e&o.S,p=e&o.P,y=e&o.B,b=e&o.W,m=l?i:i[t]||(i[t]={}),g=m.prototype,v=l?n:h?n[t]:(n[t]||{}).prototype;for(u in l&&(r=t),r)(f=!d&&v&&void 0!==v[u])&&u in m||(c=f?v[u]:r[u],m[u]=l&&"function"!=typeof v[u]?r[u]:y&&f?a(c,n):b&&v[u]==c?function(e){var t=function(t,r,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,n)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(c):p&&"function"==typeof c?a(Function.call,c):c,p&&((m.virtual||(m.virtual={}))[u]=c,e&o.R&&g&&!g[u]&&s(g,u,c)))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,t.exports=o},{"./_core":67,"./_ctx":69,"./_global":78,"./_hide":80}],76:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],77:[function(e,t,r){var n=e("./_ctx"),i=e("./_iter-call"),a=e("./_is-array-iter"),s=e("./_an-object"),o=e("./_to-length"),u=e("./core.get-iterator-method"),f={},c={};(r=t.exports=function(e,t,r,d,l){var h,p,y,b,m=l?function(){return e}:u(e),g=n(r,d,t?2:1),v=0;if("function"!=typeof m)throw TypeError(e+" is not iterable!");if(a(m)){for(h=o(e.length);h>v;v++)if((b=t?g(s(p=e[v])[0],p[1]):g(e[v]))===f||b===c)return b}else for(y=m.call(e);!(p=y.next()).done;)if((b=i(y,g,p.value,t))===f||b===c)return b}).BREAK=f,r.RETURN=c},{"./_an-object":63,"./_ctx":69,"./_is-array-iter":85,"./_iter-call":88,"./_to-length":126,"./core.get-iterator-method":133}],78:[function(e,t,r){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},{}],79:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],80:[function(e,t,r){var n=e("./_object-dp"),i=e("./_property-desc");t.exports=e("./_descriptors")?function(e,t,r){return n.f(e,t,i(1,r))}:function(e,t,r){return e[t]=r,e}},{"./_descriptors":71,"./_object-dp":99,"./_property-desc":112}],81:[function(e,t,r){var n=e("./_global").document;t.exports=n&&n.documentElement},{"./_global":78}],82:[function(e,t,r){t.exports=!e("./_descriptors")&&!e("./_fails")(function(){return 7!=Object.defineProperty(e("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":71,"./_dom-create":72,"./_fails":76}],83:[function(e,t,r){t.exports=function(e,t,r){var n=void 0===r;switch(t.length){case 0:return n?e():e.call(r);case 1:return n?e(t[0]):e.call(r,t[0]);case 2:return n?e(t[0],t[1]):e.call(r,t[0],t[1]);case 3:return n?e(t[0],t[1],t[2]):e.call(r,t[0],t[1],t[2]);case 4:return n?e(t[0],t[1],t[2],t[3]):e.call(r,t[0],t[1],t[2],t[3])}return e.apply(r,t)}},{}],84:[function(e,t,r){var n=e("./_cof");t.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},{"./_cof":66}],85:[function(e,t,r){var n=e("./_iterators"),i=e("./_wks")("iterator"),a=Array.prototype;t.exports=function(e){return void 0!==e&&(n.Array===e||a[i]===e)}},{"./_iterators":93,"./_wks":132}],86:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":66}],87:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],88:[function(e,t,r){var n=e("./_an-object");t.exports=function(e,t,r,i){try{return i?t(n(r)[0],r[1]):t(r)}catch(t){var a=e.return;throw void 0!==a&&n(a.call(e)),t}}},{"./_an-object":63}],89:[function(e,t,r){"use strict";var n=e("./_object-create"),i=e("./_property-desc"),a=e("./_set-to-string-tag"),s={};e("./_hide")(s,e("./_wks")("iterator"),function(){return this}),t.exports=function(e,t,r){e.prototype=n(s,{next:i(1,r)}),a(e,t+" Iterator")}},{"./_hide":80,"./_object-create":98,"./_property-desc":112,"./_set-to-string-tag":117,"./_wks":132}],90:[function(e,t,r){"use strict";var n=e("./_library"),i=e("./_export"),a=e("./_redefine"),s=e("./_hide"),o=e("./_has"),u=e("./_iterators"),f=e("./_iter-create"),c=e("./_set-to-string-tag"),d=e("./_object-gpo"),l=e("./_wks")("iterator"),h=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(e,t,r,y,b,m,g){f(r,t,y);var v,_,w,k=function(e){if(!h&&e in E)return E[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},x=t+" Iterator",A="values"==b,S=!1,E=e.prototype,M=E[l]||E["@@iterator"]||b&&E[b],j=!h&&M||k(b),P=b?A?k("entries"):j:void 0,K="Array"==t&&E.entries||M;if(K&&(w=d(K.call(new e)))!==Object.prototype&&w.next&&(c(w,x,!0),n||o(w,l)||s(w,l,p)),A&&M&&"values"!==M.name&&(S=!0,j=function(){return M.call(this)}),n&&!g||!h&&!S&&E[l]||s(E,l,j),u[t]=j,u[x]=p,b)if(v={values:A?j:k("values"),keys:m?j:k("keys"),entries:P},g)for(_ in v)_ in E||a(E,_,v[_]);else i(i.P+i.F*(h||S),t,v);return v}},{"./_export":75,"./_has":79,"./_hide":80,"./_iter-create":89,"./_iterators":93,"./_library":94,"./_object-gpo":105,"./_redefine":114,"./_set-to-string-tag":117,"./_wks":132}],91:[function(e,t,r){var n=e("./_wks")("iterator"),i=!1;try{var a=[7][n]();a.return=function(){i=!0},Array.from(a,function(){throw 2})}catch(e){}t.exports=function(e,t){if(!t&&!i)return!1;var r=!1;try{var a=[7],s=a[n]();s.next=function(){return{done:r=!0}},a[n]=function(){return s},e(a)}catch(e){}return r}},{"./_wks":132}],92:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],93:[function(e,t,r){t.exports={}},{}],94:[function(e,t,r){t.exports=!0},{}],95:[function(e,t,r){var n=e("./_uid")("meta"),i=e("./_is-object"),a=e("./_has"),s=e("./_object-dp").f,o=0,u=Object.isExtensible||function(){return!0},f=!e("./_fails")(function(){return u(Object.preventExtensions({}))}),c=function(e){s(e,n,{value:{i:"O"+ ++o,w:{}}})},d=t.exports={KEY:n,NEED:!1,fastKey:function(e,t){if(!i(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!a(e,n)){if(!u(e))return"F";if(!t)return"E";c(e)}return e[n].i},getWeak:function(e,t){if(!a(e,n)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[n].w},onFreeze:function(e){return f&&d.NEED&&u(e)&&!a(e,n)&&c(e),e}}},{"./_fails":76,"./_has":79,"./_is-object":87,"./_object-dp":99,"./_uid":129}],96:[function(e,t,r){var n=e("./_global"),i=e("./_task").set,a=n.MutationObserver||n.WebKitMutationObserver,s=n.process,o=n.Promise,u="process"==e("./_cof")(s);t.exports=function(){var e,t,r,f=function(){var n,i;for(u&&(n=s.domain)&&n.exit();e;){i=e.fn,e=e.next;try{i()}catch(n){throw e?r():t=void 0,n}}t=void 0,n&&n.enter()};if(u)r=function(){s.nextTick(f)};else if(!a||n.navigator&&n.navigator.standalone)if(o&&o.resolve){var c=o.resolve();r=function(){c.then(f)}}else r=function(){i.call(n,f)};else{var d=!0,l=document.createTextNode("");new a(f).observe(l,{characterData:!0}),r=function(){l.data=d=!d}}return function(n){var i={fn:n,next:void 0};t&&(t.next=i),e||(e=i,r()),t=i}}},{"./_cof":66,"./_global":78,"./_task":122}],97:[function(e,t,r){"use strict";var n=e("./_a-function");t.exports.f=function(e){return new function(e){var t,r;this.promise=new e(function(e,n){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=n}),this.resolve=n(t),this.reject=n(r)}(e)}},{"./_a-function":60}],98:[function(e,t,r){var n=e("./_an-object"),i=e("./_object-dps"),a=e("./_enum-bug-keys"),s=e("./_shared-key")("IE_PROTO"),o=function(){},u=function(){var t,r=e("./_dom-create")("iframe"),n=a.length;for(r.style.display="none",e("./_html").appendChild(r),r.src="javascript:",(t=r.contentWindow.document).open(),t.write("