From 91cca7ddf012770bf10824d3335ae4e3341953ea Mon Sep 17 00:00:00 2001 From: Juho Enala Date: Wed, 16 Sep 2020 12:24:57 +0300 Subject: [PATCH] Update package version --- package.json | 2 +- web/hybrid-crypto.js | 2 +- web/hybrid-crypto.min.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 66402ca..7f77fa0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hybrid-crypto-js", - "version": "0.2.3", + "version": "0.2.4", "description": "Hybrid (RSA+AES) encryption and decryption toolkit for JavaScript", "main": "lib/index.js", "scripts": { diff --git a/web/hybrid-crypto.js b/web/hybrid-crypto.js index ed485a7..45ea735 100644 --- a/web/hybrid-crypto.js +++ b/web/hybrid-crypto.js @@ -29849,7 +29849,7 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : },{"process/browser.js":50,"timers":51}],52:[function(require,module,exports){ module.exports={ "name": "hybrid-crypto-js", - "version": "0.2.3", + "version": "0.2.4", "description": "Hybrid (RSA+AES) encryption and decryption toolkit for JavaScript", "main": "lib/index.js", "scripts": { diff --git a/web/hybrid-crypto.min.js b/web/hybrid-crypto.min.js index 62c126e..8c6da03 100644 --- a/web/hybrid-crypto.min.js +++ b/web/hybrid-crypto.min.js @@ -1 +1 @@ -(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,Crypt);this.options=_objectSpread({md:DEFAULT_MESSAGE_DIGEST,aesKeySize:DEFAULT_AES_KEY_SIZE,aesIvSize:DEFAULT_AES_IV_SIZE,aesStandard:AES_STANDARD,rsaStandard:RSA_STANDARD,entropy:undefined},options);if(this.options.entropy){this._entropy(this.options.entropy)}}_createClass(Crypt,[{key:"_getMessageDigest",value:function _getMessageDigest(messageDigest){switch(messageDigest){case"sha1":return forge.md.sha1.create();case"sha256":return forge.md.sha256.create();case"sha384":return forge.md.sha384.create();case"sha512":return forge.md.sha512.create();case"md5":return forge.md.md5.create();default:console.warn('Message digest "'.concat(this.options.md,'" not found. Using default message digest "sha1" instead'));return forge.md.sha1.create()}}},{key:"_parseSignature",value:function _parseSignature(_signature){try{return JSON.parse(_signature)}catch(e){return{signature:_signature,md:"sha1",v:helpers.version()}}}},{key:"fingerprint",value:function fingerprint(publicKey){return pki.getPublicKeyFingerprint(publicKey,{encoding:"hex",delimiter:":"})}},{key:"signature",value:function signature(privateKey,message){var checkSum=this._getMessageDigest(this.options.md);checkSum.update(message,"utf8");if(typeof privateKey==="string")privateKey=pki.privateKeyFromPem(privateKey);var signature=privateKey.sign(checkSum);var signature64=forge.util.encode64(signature);return JSON.stringify({signature:signature64,md:this.options.md})}},{key:"verify",value:function verify(publicKey,_signature,decrypted){if(!_signature)return false;var _this$_parseSignature=this._parseSignature(_signature),signature=_this$_parseSignature.signature,md=_this$_parseSignature.md;var checkSum=this._getMessageDigest(md);checkSum.update(decrypted,"utf8");signature=forge.util.decode64(signature);if(typeof publicKey==="string")publicKey=pki.publicKeyFromPem(publicKey);return publicKey.verify(checkSum.digest().getBytes(),signature)}},{key:"encrypt",value:function encrypt(publicKeys,message,signature){var _this=this;publicKeys=helpers.toArray(publicKeys);publicKeys=publicKeys.map(function(key){return typeof key==="string"?pki.publicKeyFromPem(key):key});var iv=forge.random.getBytesSync(this.options.aesIvSize);var key=forge.random.getBytesSync(this.options.aesKeySize/8);var encryptedKeys={};publicKeys.forEach(function(publicKey){var encryptedKey=publicKey.encrypt(key,_this.options.rsaStandard);var fingerprint=_this.fingerprint(publicKey);encryptedKeys[fingerprint]=forge.util.encode64(encryptedKey)});var buffer=forge.util.createBuffer(message,"utf8");var cipher=forge.cipher.createCipher(this.options.aesStandard,key);cipher.start({iv:iv});cipher.update(buffer);cipher.finish();var payload={};payload.v=helpers.version();payload.iv=forge.util.encode64(iv);payload.keys=encryptedKeys;payload.cipher=forge.util.encode64(cipher.output.data);payload.signature=signature;payload.tag=cipher.mode.tag&&forge.util.encode64(cipher.mode.tag.getBytes());return JSON.stringify(payload)}},{key:"decrypt",value:function decrypt(privateKey,encrypted){this._validate(encrypted);var payload=JSON.parse(encrypted);if(typeof privateKey==="string")privateKey=pki.privateKeyFromPem(privateKey);var fingerprint=this.fingerprint(privateKey);var encryptedKey=payload.keys[fingerprint];if(!encryptedKey)throw"RSA fingerprint doesn't match with any of the encrypted message's fingerprints";var keyBytes=forge.util.decode64(encryptedKey);var iv=forge.util.decode64(payload.iv);var cipher=forge.util.decode64(payload.cipher);var tag=payload.tag&&forge.util.decode64(payload.tag);var key=privateKey.decrypt(keyBytes,this.options.rsaStandard);var buffer=forge.util.createBuffer(cipher);var decipher=forge.cipher.createDecipher(this.options.aesStandard,key);decipher.start({iv:iv,tag:tag});decipher.update(buffer);decipher.finish();var bytes=decipher.output.getBytes();var decrypted=forge.util.decodeUtf8(bytes);var output={};output.message=decrypted;output.signature=payload.signature;return output}},{key:"_validate",value:function _validate(encrypted){var p=JSON.parse(encrypted);if(!(p.hasOwnProperty("v")&&p.hasOwnProperty("iv")&&p.hasOwnProperty("keys")&&p.hasOwnProperty("cipher")))throw"Encrypted message is not valid"}},{key:"_entropy",value:function _entropy(input){var inputString=String(input);var bytes=forge.util.encodeUtf8(inputString);forge.random.collect(bytes)}}]);return Crypt}();module.exports=Crypt},{"./constants":1,"./helpers":3,"node-forge":18}],3:[function(require,module,exports){"use strict";var pkg=require("../package.json");module.exports={version:function version(){return"".concat(pkg.name,"_").concat(pkg.version)},toArray:function toArray(obj){return Array.isArray(obj)?obj:[obj]}}},{"../package.json":52}],4:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,RSA);this.options=_objectSpread({keySize:4096,entropy:undefined},options);if(this.options.entropy){this._entropy(this.options.entropy)}}_createClass(RSA,[{key:"generateKeyPair",value:function generateKeyPair(callback,keySize){pki.rsa.generateKeyPair({bits:keySize||this.options.keySize,workers:-1},function(err,keyPair){keyPair.publicKey=pki.publicKeyToPem(keyPair.publicKey);keyPair.privateKey=pki.privateKeyToPem(keyPair.privateKey);callback(keyPair)})}},{key:"generateKeyPairAsync",value:function generateKeyPairAsync(keySize){var _this=this;return new Promise(function(resolve){_this.generateKeyPair(resolve,keySize)})}},{key:"_entropy",value:function _entropy(input){var inputString=String(input);var bytes=forge.util.encodeUtf8(inputString);forge.random.collect(bytes)}}]);return RSA}();module.exports=RSA},{"node-forge":18}],5:[function(require,module,exports){"use strict";var _crypt=_interopRequireDefault(require("./crypt"));var _rsa=_interopRequireDefault(require("./rsa"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}window.Crypt=_crypt.default;window.RSA=_rsa.default},{"./crypt":2,"./rsa":4}],6:[function(require,module,exports){},{}],7:[function(require,module,exports){var forge=require("./forge");require("./cipher");require("./cipherModes");require("./util");module.exports=forge.aes=forge.aes||{};forge.aes.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:false,mode:mode});cipher.start(iv);return cipher};forge.aes.createEncryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:false,mode:mode})};forge.aes.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:true,mode:mode});cipher.start(iv);return cipher};forge.aes.createDecryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:true,mode:mode})};forge.aes.Algorithm=function(name,mode){if(!init){initialize()}var self=this;self.name=name;self.mode=new mode({blockSize:16,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,true)}}});self._init=false};forge.aes.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=options.key;var tmp;if(typeof key==="string"&&(key.length===16||key.length===24||key.length===32)){key=forge.util.createBuffer(key)}else if(forge.util.isArray(key)&&(key.length===16||key.length===24||key.length===32)){tmp=key;key=forge.util.createBuffer();for(var i=0;i>>2;for(var i=0;i>8^sx&255^99;sbox[e]=sx;isbox[sx]=e;sx2=xtime[sx];e2=xtime[e];e4=xtime[e2];e8=xtime[e4];me=sx2<<24^sx<<16^sx<<8^(sx^sx2);ime=(e2^e4^e8)<<24^(e^e8)<<16^(e^e4^e8)<<8^(e^e2^e8);for(var n=0;n<4;++n){mix[n][e]=me;imix[n][sx]=ime;me=me<<24|me>>>8;ime=ime<<24|ime>>>8}if(e===0){e=ei=1}else{e=e2^xtime[xtime[xtime[e2^e8]]];ei^=xtime[xtime[ei]]}}}function _expandKey(key,decrypt){var w=key.slice(0);var temp,iNk=1;var Nk=w.length;var Nr1=Nk+6+1;var end=Nb*Nr1;for(var i=Nk;i>>16&255]<<24^sbox[temp>>>8&255]<<16^sbox[temp&255]<<8^sbox[temp>>>24]^rcon[iNk]<<24;iNk++}else if(Nk>6&&i%Nk===4){temp=sbox[temp>>>24]<<24^sbox[temp>>>16&255]<<16^sbox[temp>>>8&255]<<8^sbox[temp&255]}w[i]=w[i-Nk]^temp}if(decrypt){var tmp;var m0=imix[0];var m1=imix[1];var m2=imix[2];var m3=imix[3];var wnew=w.slice(0);end=w.length;for(var i=0,wi=end-Nb;i>>24]]^m1[sbox[tmp>>>16&255]]^m2[sbox[tmp>>>8&255]]^m3[sbox[tmp&255]]}}}w=wnew}return w}function _updateBlock(w,input,output,decrypt){var Nr=w.length/4-1;var m0,m1,m2,m3,sub;if(decrypt){m0=imix[0];m1=imix[1];m2=imix[2];m3=imix[3];sub=isbox}else{m0=mix[0];m1=mix[1];m2=mix[2];m3=mix[3];sub=sbox}var a,b,c,d,a2,b2,c2;a=input[0]^w[0];b=input[decrypt?3:1]^w[1];c=input[2]^w[2];d=input[decrypt?1:3]^w[3];var i=3;for(var round=1;round>>24]^m1[b>>>16&255]^m2[c>>>8&255]^m3[d&255]^w[++i];b2=m0[b>>>24]^m1[c>>>16&255]^m2[d>>>8&255]^m3[a&255]^w[++i];c2=m0[c>>>24]^m1[d>>>16&255]^m2[a>>>8&255]^m3[b&255]^w[++i];d=m0[d>>>24]^m1[a>>>16&255]^m2[b>>>8&255]^m3[c&255]^w[++i];a=a2;b=b2;c=c2}output[0]=sub[a>>>24]<<24^sub[b>>>16&255]<<16^sub[c>>>8&255]<<8^sub[d&255]^w[++i];output[decrypt?3:1]=sub[b>>>24]<<24^sub[c>>>16&255]<<16^sub[d>>>8&255]<<8^sub[a&255]^w[++i];output[2]=sub[c>>>24]<<24^sub[d>>>16&255]<<16^sub[a>>>8&255]<<8^sub[b&255]^w[++i];output[decrypt?1:3]=sub[d>>>24]<<24^sub[a>>>16&255]<<16^sub[b>>>8&255]<<8^sub[c&255]^w[++i]}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="AES-"+mode;var cipher;if(options.decrypt){cipher=forge.cipher.createDecipher(algorithm,options.key)}else{cipher=forge.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options){var output=null;if(options instanceof forge.util.ByteBuffer){output=options;options={}}options=options||{};options.output=output;options.iv=iv;start.call(cipher,options)};return cipher}},{"./cipher":11,"./cipherModes":12,"./forge":16,"./util":48}],8:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./tls");var tls=module.exports=forge.tls;tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"]={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes;sp.cipher_type=tls.CipherType.block;sp.enc_key_length=16;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState:initConnectionState};tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"]={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes;sp.cipher_type=tls.CipherType.block;sp.enc_key_length=32;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState:initConnectionState};function initConnectionState(state,c,sp){var client=c.entity===forge.tls.ConnectionEnd.client;state.read.cipherState={init:false,cipher:forge.cipher.createDecipher("AES-CBC",client?sp.keys.server_write_key:sp.keys.client_write_key),iv:client?sp.keys.server_write_IV:sp.keys.client_write_IV};state.write.cipherState={init:false,cipher:forge.cipher.createCipher("AES-CBC",client?sp.keys.client_write_key:sp.keys.server_write_key),iv:client?sp.keys.client_write_IV:sp.keys.server_write_IV};state.read.cipherFunction=decrypt_aes_cbc_sha1;state.write.cipherFunction=encrypt_aes_cbc_sha1;state.read.macLength=state.write.macLength=sp.mac_length;state.read.macFunction=state.write.macFunction=tls.hmac_sha1}function encrypt_aes_cbc_sha1(record,s){var rval=false;var mac=s.macFunction(s.macKey,s.sequenceNumber,record);record.fragment.putBytes(mac);s.updateSequenceNumber();var iv;if(record.version.minor===tls.Versions.TLS_1_0.minor){iv=s.cipherState.init?null:s.cipherState.iv}else{iv=forge.random.getBytesSync(16)}s.cipherState.init=true;var cipher=s.cipherState.cipher;cipher.start({iv:iv});if(record.version.minor>=tls.Versions.TLS_1_1.minor){cipher.output.putBytes(iv)}cipher.update(record.fragment);if(cipher.finish(encrypt_aes_cbc_sha1_padding)){record.fragment=cipher.output;record.length=record.fragment.length();rval=true}return rval}function encrypt_aes_cbc_sha1_padding(blockSize,input,decrypt){if(!decrypt){var padding=blockSize-input.length()%blockSize;input.fillWithByte(padding-1,padding)}return true}function decrypt_aes_cbc_sha1_padding(blockSize,output,decrypt){var rval=true;if(decrypt){var len=output.length();var paddingLength=output.last();for(var i=len-1-paddingLength;i=macLen){record.fragment=cipher.output.getBytes(len-macLen);mac=cipher.output.getBytes(macLen)}else{record.fragment=cipher.output.getBytes()}record.fragment=forge.util.createBuffer(record.fragment);record.length=record.fragment.length();var mac2=s.macFunction(s.macKey,s.sequenceNumber,record);s.updateSequenceNumber();rval=compareMacs(s.macKey,mac,mac2)&&rval;return rval}function compareMacs(key,mac1,mac2){var hmac=forge.hmac.create();hmac.start("SHA1",key);hmac.update(mac1);mac1=hmac.digest().getBytes();hmac.start(null,null);hmac.update(mac2);mac2=hmac.digest().getBytes();return mac1===mac2}},{"./aes":7,"./forge":16,"./tls":47}],9:[function(require,module,exports){var forge=require("./forge");require("./util");require("./oids");var asn1=module.exports=forge.asn1=forge.asn1||{};asn1.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};asn1.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};asn1.create=function(tagClass,type,constructed,value,options){if(forge.util.isArray(value)){var tmp=[];for(var i=0;iremaining){var error=new Error("Too few bytes to parse DER.");error.available=bytes.length();error.remaining=remaining;error.requested=n;throw error}}var _getValueLength=function(bytes,remaining){var b2=bytes.getByte();remaining--;if(b2===128){return undefined}var length;var longForm=b2&128;if(!longForm){length=b2}else{var longFormBytes=b2&127;_checkBufferLength(bytes,remaining,longFormBytes);length=bytes.getInt(longFormBytes<<3)}if(length<0){throw new Error("Negative length: "+length)}return length};asn1.fromDer=function(bytes,options){if(options===undefined){options={strict:true,decodeBitStrings:true}}if(typeof options==="boolean"){options={strict:options,decodeBitStrings:true}}if(!("strict"in options)){options.strict=true}if(!("decodeBitStrings"in options)){options.decodeBitStrings=true}if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}return _fromDer(bytes,bytes.length(),0,options)};function _fromDer(bytes,remaining,depth,options){var start;_checkBufferLength(bytes,remaining,2);var b1=bytes.getByte();remaining--;var tagClass=b1&192;var type=b1&31;start=bytes.length();var length=_getValueLength(bytes,remaining);remaining-=start-bytes.length();if(length!==undefined&&length>remaining){if(options.strict){var error=new Error("Too few bytes to read ASN.1 value.");error.available=bytes.length();error.remaining=remaining;error.requested=length;throw error}length=remaining}var value;var bitStringContents;var constructed=(b1&32)===32;if(constructed){value=[];if(length===undefined){for(;;){_checkBufferLength(bytes,remaining,2);if(bytes.bytes(2)===String.fromCharCode(0,0)){bytes.getBytes(2);remaining-=2;break}start=bytes.length();value.push(_fromDer(bytes,remaining,depth+1,options));remaining-=start-bytes.length()}}else{while(length>0){start=bytes.length();value.push(_fromDer(bytes,length,depth+1,options));remaining-=start-bytes.length();length-=start-bytes.length()}}}if(value===undefined&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING){bitStringContents=bytes.bytes(length)}if(value===undefined&&options.decodeBitStrings&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING&&length>1){var savedRead=bytes.read;var savedRemaining=remaining;var unused=0;if(type===asn1.Type.BITSTRING){_checkBufferLength(bytes,remaining,1);unused=bytes.getByte();remaining--}if(unused===0){try{start=bytes.length();var subOptions={verbose:options.verbose,strict:true,decodeBitStrings:true};var composed=_fromDer(bytes,remaining,depth+1,subOptions);var used=start-bytes.length();remaining-=used;if(type==asn1.Type.BITSTRING){used++}var tc=composed.tagClass;if(used===length&&(tc===asn1.Class.UNIVERSAL||tc===asn1.Class.CONTEXT_SPECIFIC)){value=[composed]}}catch(ex){}}if(value===undefined){bytes.read=savedRead;remaining=savedRemaining}}if(value===undefined){if(length===undefined){if(options.strict){throw new Error("Non-constructed ASN.1 object of indefinite length.")}length=remaining}if(type===asn1.Type.BMPSTRING){value="";for(;length>0;length-=2){_checkBufferLength(bytes,remaining,2);value+=String.fromCharCode(bytes.getInt16());remaining-=2}}else{value=bytes.getBytes(length)}}var asn1Options=bitStringContents===undefined?null:{bitStringContents:bitStringContents};return asn1.create(tagClass,type,constructed,value,asn1Options)}asn1.toDer=function(obj){var bytes=forge.util.createBuffer();var b1=obj.tagClass|obj.type;var value=forge.util.createBuffer();var useBitStringContents=false;if("bitStringContents"in obj){useBitStringContents=true;if(obj.original){useBitStringContents=asn1.equals(obj,obj.original)}}if(useBitStringContents){value.putBytes(obj.bitStringContents)}else if(obj.composed){if(obj.constructed){b1|=32}else{value.putByte(0)}for(var i=0;i1&&(obj.value.charCodeAt(0)===0&&(obj.value.charCodeAt(1)&128)===0||obj.value.charCodeAt(0)===255&&(obj.value.charCodeAt(1)&128)===128)){value.putBytes(obj.value.substr(1))}else{value.putBytes(obj.value)}}}bytes.putByte(b1);if(value.length()<=127){bytes.putByte(value.length()&127)}else{var len=value.length();var lenBytes="";do{lenBytes+=String.fromCharCode(len&255);len=len>>>8}while(len>0);bytes.putByte(lenBytes.length|128);for(var i=lenBytes.length-1;i>=0;--i){bytes.putByte(lenBytes.charCodeAt(i))}}bytes.putBuffer(value);return bytes};asn1.oidToDer=function(oid){var values=oid.split(".");var bytes=forge.util.createBuffer();bytes.putByte(40*parseInt(values[0],10)+parseInt(values[1],10));var last,valueBytes,value,b;for(var i=2;i>>7;if(!last){b|=128}valueBytes.push(b);last=false}while(value>0);for(var n=valueBytes.length-1;n>=0;--n){bytes.putByte(valueBytes[n])}}return bytes};asn1.derToOid=function(bytes){var oid;if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}var b=bytes.getByte();oid=Math.floor(b/40)+"."+b%40;var value=0;while(bytes.length()>0){b=bytes.getByte();value=value<<7;if(b&128){value+=b&127}else{oid+="."+(value+b);value=0}}return oid};asn1.utcTimeToDate=function(utc){var date=new Date;var year=parseInt(utc.substr(0,2),10);year=year>=50?1900+year:2e3+year;var MM=parseInt(utc.substr(2,2),10)-1;var DD=parseInt(utc.substr(4,2),10);var hh=parseInt(utc.substr(6,2),10);var mm=parseInt(utc.substr(8,2),10);var ss=0;if(utc.length>11){var c=utc.charAt(10);var end=10;if(c!=="+"&&c!=="-"){ss=parseInt(utc.substr(10,2),10);end+=2}}date.setUTCFullYear(year,MM,DD);date.setUTCHours(hh,mm,ss,0);if(end){c=utc.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(utc.substr(end+1,2),10);var mmoffset=parseInt(utc.substr(end+4,2),10);var offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){date.setTime(+date-offset)}else{date.setTime(+date+offset)}}}return date};asn1.generalizedTimeToDate=function(gentime){var date=new Date;var YYYY=parseInt(gentime.substr(0,4),10);var MM=parseInt(gentime.substr(4,2),10)-1;var DD=parseInt(gentime.substr(6,2),10);var hh=parseInt(gentime.substr(8,2),10);var mm=parseInt(gentime.substr(10,2),10);var ss=parseInt(gentime.substr(12,2),10);var fff=0;var offset=0;var isUTC=false;if(gentime.charAt(gentime.length-1)==="Z"){isUTC=true}var end=gentime.length-5,c=gentime.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(gentime.substr(end+1,2),10);var mmoffset=parseInt(gentime.substr(end+4,2),10);offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){offset*=-1}isUTC=true}if(gentime.charAt(14)==="."){fff=parseFloat(gentime.substr(14),10)*1e3}if(isUTC){date.setUTCFullYear(YYYY,MM,DD);date.setUTCHours(hh,mm,ss,fff);date.setTime(+date+offset)}else{date.setFullYear(YYYY,MM,DD);date.setHours(hh,mm,ss,fff)}return date};asn1.dateToUtcTime=function(date){if(typeof date==="string"){return date}var rval="";var format=[];format.push((""+date.getUTCFullYear()).substr(2));format.push(""+(date.getUTCMonth()+1));format.push(""+date.getUTCDate());format.push(""+date.getUTCHours());format.push(""+date.getUTCMinutes());format.push(""+date.getUTCSeconds());for(var i=0;i=-128&&x<128){return rval.putSignedInt(x,8)}if(x>=-32768&&x<32768){return rval.putSignedInt(x,16)}if(x>=-8388608&&x<8388608){return rval.putSignedInt(x,24)}if(x>=-2147483648&&x<2147483648){return rval.putSignedInt(x,32)}var error=new Error("Integer too large; max is 32-bits.");error.integer=x;throw error};asn1.derToInteger=function(bytes){if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}var n=bytes.length()*8;if(n>32){throw new Error("Integer too large; max is 32-bits.")}return bytes.getSignedInt(n)};asn1.validate=function(obj,v,capture,errors){var rval=false;if((obj.tagClass===v.tagClass||typeof v.tagClass==="undefined")&&(obj.type===v.type||typeof v.type==="undefined")){if(obj.constructed===v.constructed||typeof v.constructed==="undefined"){rval=true;if(v.value&&forge.util.isArray(v.value)){var j=0;for(var i=0;rval&&i0){rval+="\n"}var indent="";for(var i=0;i1){rval+="0x"+forge.util.bytesToHex(obj.value.slice(1))}else{rval+="(none)"}if(obj.value.length>0){var unused=obj.value.charCodeAt(0);if(unused==1){rval+=" (1 unused bit shown)"}else if(unused>1){rval+=" ("+unused+" unused bits shown)"}}}else if(obj.type===asn1.Type.OCTETSTRING){if(!_nonLatinRegex.test(obj.value)){rval+="("+obj.value+") "}rval+="0x"+forge.util.bytesToHex(obj.value)}else if(obj.type===asn1.Type.UTF8){rval+=forge.util.decodeUtf8(obj.value)}else if(obj.type===asn1.Type.PRINTABLESTRING||obj.type===asn1.Type.IA5String){rval+=obj.value}else if(_nonLatinRegex.test(obj.value)){rval+="0x"+forge.util.bytesToHex(obj.value)}else if(obj.value.length===0){rval+="[null]"}else{rval+=obj.value}}return rval}},{"./forge":16,"./oids":27,"./util":48}],10:[function(require,module,exports){(function(Buffer){var api={};module.exports=api;var _reverseAlphabets={};api.encode=function(input,alphabet,maxline){if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}if(maxline!==undefined&&typeof maxline!=="number"){throw new TypeError('"maxline" must be a number.')}var output="";if(!(input instanceof Uint8Array)){output=_encodeWithByteBuffer(input,alphabet)}else{var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i0){digits.push(carry%base);carry=carry/base|0}}for(i=0;input[i]===0&&i=0;--i){output+=alphabet[digits[i]]}}if(maxline){var regex=new RegExp(".{1,"+maxline+"}","g");output=output.match(regex).join("\r\n")}return output};api.decode=function(input,alphabet){if(typeof input!=="string"){throw new TypeError('"input" must be a string.')}if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}var table=_reverseAlphabets[alphabet];if(!table){table=_reverseAlphabets[alphabet]=[];for(var i=0;i>=8}while(carry>0){bytes.push(carry&255);carry>>=8}}for(var k=0;input[k]===first&&k0){digits.push(carry%base);carry=carry/base|0}}var output="";for(i=0;input.at(i)===0&&i=0;--i){output+=alphabet[digits[i]]}return output}}).call(this,require("buffer").Buffer)},{buffer:6}],11:[function(require,module,exports){var forge=require("./forge");require("./util");module.exports=forge.cipher=forge.cipher||{};forge.cipher.algorithms=forge.cipher.algorithms||{};forge.cipher.createCipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:false})};forge.cipher.createDecipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:true})};forge.cipher.registerAlgorithm=function(name,algorithm){name=name.toUpperCase();forge.cipher.algorithms[name]=algorithm};forge.cipher.getAlgorithm=function(name){name=name.toUpperCase();if(name in forge.cipher.algorithms){return forge.cipher.algorithms[name]}return null};var BlockCipher=forge.cipher.BlockCipher=function(options){this.algorithm=options.algorithm;this.mode=this.algorithm.mode;this.blockSize=this.mode.blockSize;this._finish=false;this._input=null;this.output=null;this._op=options.decrypt?this.mode.decrypt:this.mode.encrypt;this._decrypt=options.decrypt;this.algorithm.initialize(options)};BlockCipher.prototype.start=function(options){options=options||{};var opts={};for(var key in options){opts[key]=options[key]}opts.decrypt=this._decrypt;this._finish=false;this._input=forge.util.createBuffer();this.output=options.output||forge.util.createBuffer();this.mode.start(opts)};BlockCipher.prototype.update=function(input){if(input){this._input.putBuffer(input)}while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish){}this._input.compact()};BlockCipher.prototype.finish=function(pad){if(pad&&(this.mode.name==="ECB"||this.mode.name==="CBC")){this.mode.pad=function(input){return pad(this.blockSize,input,false)};this.mode.unpad=function(output){return pad(this.blockSize,output,true)}}var options={};options.decrypt=this._decrypt;options.overflow=this._input.length()%this.blockSize;if(!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,options)){return false}}this._finish=true;this.update();if(this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,options)){return false}}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,options)){return false}}return true}},{"./forge":16,"./util":48}],12:[function(require,module,exports){var forge=require("./forge");require("./util");forge.cipher=forge.cipher||{};var modes=module.exports=forge.cipher.modes=forge.cipher.modes||{};modes.ecb=function(options){options=options||{};this.name="ECB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints)};modes.ecb.prototype.start=function(options){};modes.ecb.prototype.encrypt=function(input,output,finish){if(input.length()0)){return true}for(var i=0;i0)){return true}for(var i=0;i0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};modes.cbc=function(options){options=options||{};this.name="CBC";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints)};modes.cbc.prototype.start=function(options){if(options.iv===null){if(!this._prev){throw new Error("Invalid IV parameter.")}this._iv=this._prev.slice(0)}else if(!("iv"in options)){throw new Error("Invalid IV parameter.")}else{this._iv=transformIV(options.iv);this._prev=this._iv.slice(0)}};modes.cbc.prototype.encrypt=function(input,output,finish){if(input.length()0)){return true}for(var i=0;i0)){return true}for(var i=0;i0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};modes.cfb=function(options){options=options||{};this.name="CFB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.cfb.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.cfb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.cfb.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.ofb=function(options){options=options||{};this.name="OFB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.ofb.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.ofb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(input.length()===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.ofb.prototype.decrypt=modes.ofb.prototype.encrypt;modes.ctr=function(options){options=options||{};this.name="CTR";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.ctr.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.ctr.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0}inc32(this._inBlock)};modes.ctr.prototype.decrypt=modes.ctr.prototype.encrypt;modes.gcm=function(options){options=options||{};this.name="GCM";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0;this._R=3774873600};modes.gcm.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}var iv=forge.util.createBuffer(options.iv);this._cipherLength=0;var additionalData;if("additionalData"in options){additionalData=forge.util.createBuffer(options.additionalData)}else{additionalData=forge.util.createBuffer()}if("tagLength"in options){this._tagLength=options.tagLength}else{this._tagLength=128}this._tag=null;if(options.decrypt){this._tag=forge.util.createBuffer(options.tag).getBytes();if(this._tag.length!==this._tagLength/8){throw new Error("Authentication tag does not match tag length.")}}this._hashBlock=new Array(this._ints);this.tag=null;this._hashSubkey=new Array(this._ints);this.cipher.encrypt([0,0,0,0],this._hashSubkey);this.componentBits=4;this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var ivLength=iv.length();if(ivLength===12){this._j0=[iv.getInt32(),iv.getInt32(),iv.getInt32(),1]}else{this._j0=[0,0,0,0];while(iv.length()>0){this._j0=this.ghash(this._hashSubkey,this._j0,[iv.getInt32(),iv.getInt32(),iv.getInt32(),iv.getInt32()])}this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(from64To32(ivLength*8)))}this._inBlock=this._j0.slice(0);inc32(this._inBlock);this._partialBytes=0;additionalData=forge.util.createBuffer(additionalData);this._aDataLength=from64To32(additionalData.length()*8);var overflow=additionalData.length()%this.blockSize;if(overflow){additionalData.fillWithByte(0,this.blockSize-overflow)}this._s=[0,0,0,0];while(additionalData.length()>0){this._s=this.ghash(this._hashSubkey,this._s,[additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32()])}};modes.gcm.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){input.read-=this.blockSize;output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock);inc32(this._inBlock)};modes.gcm.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength0)){return true}this.cipher.encrypt(this._inBlock,this._outBlock);inc32(this._inBlock);this._hashBlock[0]=input.getInt32();this._hashBlock[1]=input.getInt32();this._hashBlock[2]=input.getInt32();this._hashBlock[3]=input.getInt32();this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--i){out[i]=x[i]>>>1|(x[i-1]&1)<<31}out[0]=x[0]>>>1;if(lsb){out[0]^=this._R}};modes.gcm.prototype.tableMultiply=function(x){var z=[0,0,0,0];for(var i=0;i<32;++i){var idx=i/8|0;var x_i=x[idx]>>>(7-i%8)*4&15;var ah=this._m[i][x_i];z[0]^=ah[0];z[1]^=ah[1];z[2]^=ah[2];z[3]^=ah[3]}return z};modes.gcm.prototype.ghash=function(h,y,x){y[0]^=x[0];y[1]^=x[1];y[2]^=x[2];y[3]^=x[3];return this.tableMultiply(y)};modes.gcm.prototype.generateHashTable=function(h,bits){var multiplier=8/bits;var perInt=4*multiplier;var size=16*multiplier;var m=new Array(size);for(var i=0;i>>1;var m=new Array(size);m[half]=mid.slice(0);var i=half>>>1;while(i>0){this.pow(m[2*i],m[i]=[]);i>>=1}i=2;while(i4){var tmp=iv;iv=forge.util.createBuffer();for(var i=0;i8?3:1;var keys=[];var shifts=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];var n=0,tmp;for(var j=0;j>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>2^right)&858993459;right^=tmp;left^=tmp<<2;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=left<<8|right>>>20&240;left=right<<24|right<<8&16711680|right>>>8&65280|right>>>24&240;right=tmp;for(var i=0;i>>26;right=right<<2|right>>>26}else{left=left<<1|left>>>27;right=right<<1|right>>>27}left&=-15;right&=-15;var lefttmp=pc2bytes0[left>>>28]|pc2bytes1[left>>>24&15]|pc2bytes2[left>>>20&15]|pc2bytes3[left>>>16&15]|pc2bytes4[left>>>12&15]|pc2bytes5[left>>>8&15]|pc2bytes6[left>>>4&15];var righttmp=pc2bytes7[right>>>28]|pc2bytes8[right>>>24&15]|pc2bytes9[right>>>20&15]|pc2bytes10[right>>>16&15]|pc2bytes11[right>>>12&15]|pc2bytes12[right>>>8&15]|pc2bytes13[right>>>4&15];tmp=(righttmp>>>16^lefttmp)&65535;keys[n++]=lefttmp^tmp;keys[n++]=righttmp^tmp<<16}}return keys}function _updateBlock(keys,input,output,decrypt){var iterations=keys.length===32?3:9;var looping;if(iterations===3){looping=decrypt?[30,-2,-2]:[0,32,2]}else{looping=decrypt?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2]}var tmp;var left=input[0];var right=input[1];tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;left=left<<1|left>>>31;right=right<<1|right>>>31;for(var j=0;j>>4|right<<28)^keys[i+1];tmp=left;left=right;right=tmp^(spfunction2[right1>>>24&63]|spfunction4[right1>>>16&63]|spfunction6[right1>>>8&63]|spfunction8[right1&63]|spfunction1[right2>>>24&63]|spfunction3[right2>>>16&63]|spfunction5[right2>>>8&63]|spfunction7[right2&63])}tmp=left;left=right;right=tmp}left=left>>>1|left<<31;right=right>>>1|right<<31;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;output[0]=left;output[1]=right}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="DES-"+mode;var cipher;if(options.decrypt){cipher=forge.cipher.createDecipher(algorithm,options.key)}else{cipher=forge.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options){var output=null;if(options instanceof forge.util.ByteBuffer){output=options;options={}}options=options||{};options.output=output;options.iv=iv;start.call(cipher,options)};return cipher}},{"./cipher":11,"./cipherModes":12,"./forge":16,"./util":48}],15:[function(require,module,exports){(function(Buffer){var forge=require("./forge");require("./jsbn");require("./random");require("./sha512");require("./util");if(typeof BigInteger==="undefined"){var BigInteger=forge.jsbn.BigInteger}var ByteBuffer=forge.util.ByteBuffer;var NativeBuffer=typeof Buffer==="undefined"?Uint8Array:Buffer;forge.pki=forge.pki||{};module.exports=forge.pki.ed25519=forge.ed25519=forge.ed25519||{};var ed25519=forge.ed25519;ed25519.constants={};ed25519.constants.PUBLIC_KEY_BYTE_LENGTH=32;ed25519.constants.PRIVATE_KEY_BYTE_LENGTH=64;ed25519.constants.SEED_BYTE_LENGTH=32;ed25519.constants.SIGN_BYTE_LENGTH=64;ed25519.constants.HASH_BYTE_LENGTH=64;ed25519.generateKeyPair=function(options){options=options||{};var seed=options.seed;if(seed===undefined){seed=forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH)}else if(typeof seed==="string"){if(seed.length!==ed25519.constants.SEED_BYTE_LENGTH){throw new TypeError('"seed" must be '+ed25519.constants.SEED_BYTE_LENGTH+" bytes in length.")}}else if(!(seed instanceof Uint8Array)){throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.')}seed=messageToNativeBuffer({message:seed,encoding:"binary"});var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);var sk=new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i){sk[i]=seed[i]}crypto_sign_keypair(pk,sk);return{publicKey:pk,privateKey:sk}};ed25519.publicKeyFromPrivateKey=function(options){options=options||{};var privateKey=messageToNativeBuffer({message:options.privateKey,encoding:"binary"});if(privateKey.length!==ed25519.constants.PRIVATE_KEY_BYTE_LENGTH){throw new TypeError('"options.privateKey" must have a byte length of '+ed25519.constants.PRIVATE_KEY_BYTE_LENGTH)}var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);for(var i=0;i=0};function messageToNativeBuffer(options){var message=options.message;if(message instanceof Uint8Array){return message}var encoding=options.encoding;if(message===undefined){if(options.md){message=options.md.digest().getBytes();encoding="binary"}else{throw new TypeError('"options.message" or "options.md" not specified.')}}if(typeof message==="string"&&!encoding){throw new TypeError('"options.encoding" must be "binary" or "utf8".')}if(typeof message==="string"){if(typeof Buffer!=="undefined"){return Buffer.from(message,encoding)}message=new ByteBuffer(message,encoding)}else if(!(message instanceof ByteBuffer)){throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge '+'ByteBuffer, or a string with "options.encoding" specifying its '+"encoding.")}var buffer=new NativeBuffer(message.length());for(var i=0;i=32;--i){carry=0;for(j=i-32,k=i-12;j>8;x[j]-=carry*256}x[j]+=carry;x[i]=0}carry=0;for(j=0;j<32;++j){x[j]+=carry-(x[31]>>4)*L[j];carry=x[j]>>8;x[j]&=255}for(j=0;j<32;++j){x[j]-=carry*L[j]}for(i=0;i<32;++i){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64);for(var i=0;i<64;++i){x[i]=r[i];r[i]=0}modL(r,x)}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h=gf(),t=gf();Z(a,p[1],p[0]);Z(t,q[1],q[0]);M(a,a,t);A(b,p[0],p[1]);A(t,q[0],q[1]);M(b,b,t);M(c,p[3],q[3]);M(c,c,D2);M(d,p[2],q[2]);A(d,d,d);Z(e,b,a);Z(f,d,c);A(g,d,c);A(h,b,a);M(p[0],e,f);M(p[1],h,g);M(p[2],g,f);M(p[3],e,h)}function cswap(p,q,b){for(var i=0;i<4;++i){sel25519(p[i],q[i],b)}}function pack(r,p){var tx=gf(),ty=gf(),zi=gf();inv25519(zi,p[2]);M(tx,p[0],zi);M(ty,p[1],zi);pack25519(r,ty);r[31]^=par25519(tx)<<7}function pack25519(o,n){var i,j,b;var m=gf(),t=gf();for(i=0;i<16;++i){t[i]=n[i]}car25519(t);car25519(t);car25519(t);for(j=0;j<2;++j){m[0]=t[0]-65517;for(i=1;i<15;++i){m[i]=t[i]-65535-(m[i-1]>>16&1);m[i-1]&=65535}m[15]=t[15]-32767-(m[14]>>16&1);b=m[15]>>16&1;m[14]&=65535;sel25519(t,m,1-b)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function unpackneg(r,p){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p);S(num,r[1]);M(den,num,D);Z(num,num,r[2]);A(den,r[2],den);S(den2,den);S(den4,den2);M(den6,den4,den2);M(t,den6,num);M(t,t,den);pow2523(t,t);M(t,t,num);M(t,t,den);M(t,t,den);M(r[0],t,den);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num)){M(r[0],r[0],I)}S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num)){return-1}if(par25519(r[0])===p[31]>>7){Z(r[0],gf0,r[0])}M(r[3],r[0],r[1]);return 0}function unpack25519(o,n){var i;for(i=0;i<16;++i){o[i]=n[2*i]+(n[2*i+1]<<8)}o[15]&=32767}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=250;a>=0;--a){S(c,c);if(a!==1){M(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function neq25519(a,b){var c=new NativeBuffer(32);var d=new NativeBuffer(32);pack25519(c,a);pack25519(d,b);return crypto_verify_32(c,0,d,0)}function crypto_verify_32(x,xi,y,yi){return vn(x,xi,y,yi,32)}function vn(x,xi,y,yi,n){var i,d=0;for(i=0;i>>8)-1}function par25519(a){var d=new NativeBuffer(32);pack25519(d,a);return d[0]&1}function scalarmult(p,q,s){var b,i;set25519(p[0],gf0);set25519(p[1],gf1);set25519(p[2],gf1);set25519(p[3],gf0);for(i=255;i>=0;--i){b=s[i/8|0]>>(i&7)&1;cswap(p,q,b);add(q,p);add(p,p);cswap(p,q,b)}}function scalarbase(p,s){var q=[gf(),gf(),gf(),gf()];set25519(q[0],X);set25519(q[1],Y);set25519(q[2],gf1);M(q[3],X,Y);scalarmult(p,q,s)}function set25519(r,a){var i;for(i=0;i<16;i++){r[i]=a[i]|0}}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=253;a>=0;--a){S(c,c);if(a!==2&&a!==4){M(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function car25519(o){var i,v,c=1;for(i=0;i<16;++i){v=o[i]+c+65535;c=Math.floor(v/65536);o[i]=v-c*65536}o[0]+=c-1+37*(c-1)}function sel25519(p,q,b){var t,c=~(b-1);for(var i=0;i<16;++i){t=c&(p[i]^q[i]);p[i]^=t;q[i]^=t}}function gf(init){var i,r=new Float64Array(16);if(init){for(i=0;i_md.blockLength){_md.start();_md.update(key.bytes());key=_md.digest()}_ipadding=forge.util.createBuffer();_opadding=forge.util.createBuffer();keylen=key.length();for(var i=0;i=0){var v=x*this.data[i++]+w.data[j]+c;c=Math.floor(v/67108864);w.data[j++]=v&67108863}return c}function am2(i,x,w,j,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this.data[i]&32767;var h=this.data[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&32767)<<15)+w.data[j]+(c&1073741823);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w.data[j++]=l&1073741823}return c}function am3(i,x,w,j,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this.data[i]&16383;var h=this.data[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&16383)<<14)+w.data[j]+c;c=(l>>28)+(m>>14)+xh*h;w.data[j++]=l&268435455}return c}if(typeof navigator==="undefined"){BigInteger.prototype.am=am3;dbits=28}else if(j_lm&&navigator.appName=="Microsoft Internet Explorer"){BigInteger.prototype.am=am2;dbits=30}else if(j_lm&&navigator.appName!="Netscape"){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<=0;--i)r.data[i]=this.data[i];r.t=this.t;r.s=this.s}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this.data[0]=x;else if(x<-1)this.data[0]=x+this.DV;else this.t=0}function nbv(i){var r=nbi();r.fromInt(i);return r}function bnpFromString(s,b){var k;if(b==16)k=4;else if(b==8)k=3;else if(b==256)k=8;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]&255:intAt(s,i);if(x<0){if(s.charAt(i)=="-")mi=true;continue}mi=false;if(sh==0)this.data[this.t++]=x;else if(sh+k>this.DB){this.data[this.t-1]|=(x&(1<>this.DB-sh}else this.data[this.t-1]|=x<=this.DB)sh-=this.DB}if(k==8&&(s[0]&128)!=0){this.s=-1;if(sh>0)this.data[this.t-1]|=(1<0&&this.data[this.t-1]==c)--this.t}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<0){if(p>p)>0){m=true;r=int2char(d)}while(i>=0){if(p>(p+=this.DB-k)}else{d=this.data[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"}function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}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.data[i]-a.data[i])!=0)return r;return 0}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}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r.data[i+n]=this.data[i];for(i=n-1;i>=0;--i)r.data[i]=0;r.t=this.t+n;r.s=this.s}function bnpDRShiftTo(n,r){for(var i=n;i=0;--i){r.data[i+ds+1]=this.data[i]>>cbs|c;c=(this.data[i]&bm)<=0;--i)r.data[i]=0;r.data[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp()}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;for(var i=ds+1;i>bs}if(bs>0)r.data[this.t-ds-1]|=(this.s&bm)<>=this.DB}if(a.t>=this.DB}c+=this.s}else{c+=this.s;while(i>=this.DB}c-=a.s}r.s=c<0?-1:0;if(c<-1)r.data[i++]=this.DV+c;else if(c>0)r.data[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r.data[i]=0;for(i=0;i=0)r.data[i]=0;for(i=0;i=x.DV){r.data[i+x.t]-=x.DV;r.data[i+x.t+1]=1}}if(r.t>0)r.data[r.t-1]+=x.am(i,x.data[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m,q,r){var pm=m.abs();if(pm.t<=0)return;var pt=this.abs();if(pt.t0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r)}else{pm.copyTo(y);pt.copyTo(r)}var ys=y.t;var y0=y.data[ys-1];if(y0==0)return;var yt=y0*(1<1?y.data[ys-2]>>this.F2:0);var d1=this.FV/yt,d2=(1<=0){r.data[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t=0){var qd=r.data[--i]==y0?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);if((r.data[i]+=y.am(0,qd,r,j,0,ys))0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r)}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}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;function bnpInvDigit(){if(this.t<1)return 0;var x=this.data[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<0)this.m.subTo(r,r);return r}function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x.data[x.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&x.DM;j=i+this.m.t;x.data[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x.data[j]>=x.DV){x.data[j]-=x.DV;x.data[++j]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(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;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,z){if(e>4294967295||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<0)z.mulTo(r2,g,r);else{var t=r;r=r2;r2=t}}return z.revert(r)}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)}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;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;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}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}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=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)}function bnpFromNumber(a,b,c){if("number"==typeof b){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=(1<0){if(p>p)!=(this.s&this.DM)>>p)r[k++]=d|this.s<=0){if(p<8){d=(this.data[i]&(1<>(p+=this.DB-8)}else{d=this.data[i]>>(p-=8)&255;if(p<=0){p+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k==0&&(this.s&128)!=(d&128))++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}function bnpBitwiseTo(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i=this.t)return this.s!=0;return(this.data[j]&1<>=this.DB}if(a.t>=this.DB}c+=this.s}else{c+=this.s;while(i>=this.DB}c+=a.s}r.s=c<0?-1:0;if(c>0)r.data[i++]=c;else if(c<-1)r.data[i++]=this.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=nbi();this.addTo(a,r);return r}function bnSubtract(a){var r=nbi();this.subTo(a,r);return r}function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r}function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q=nbi(),r=nbi();this.divRemTo(a,q,r);return new Array(q,r)}function bnpDMultiply(n){this.data[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w){if(n==0)return;while(this.t<=w)this.data[this.t++]=0;this.data[w]+=n;while(this.data[w]>=this.DV){this.data[w]-=this.DV;if(++w>=this.t)this.data[this.t++]=0;++this.data[w]}}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;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r.data[--i]=0;var j;for(j=r.t-this.t;i=0)r.data[i]=0;for(i=Math.max(n-this.t,0);i2*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}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)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(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;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);var g=new Array,n=3,k1=k-1,km=(1<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.data[j])-1;while(j>=0){if(i>=k1)w=e.data[j]>>i-k1&km;else{w=(e.data[j]&(1<0)w|=e.data[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){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.data[j]&1<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}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.data[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this.data[i])%n;return r}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];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x.data[0]<=lowprimes[lowprimes.length-1]){for(i=0;i=0);var y=a.modPow(r,this);if(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j=1;while(j++0){r=forge.util.fillString(String.fromCharCode(0),zeros)+r}var encapsulation=publicKey.encrypt(r,"NONE");var key=kdf.generate(r,keyLength);return{encapsulation:encapsulation,key:key}};kem.decrypt=function(privateKey,encapsulation,keyLength){var r=privateKey.decrypt(encapsulation,"NONE");return kdf.generate(r,keyLength)};return kem};forge.kem.kdf1=function(md,digestLength){_createKDF(this,md,0,digestLength||md.digestLength)};forge.kem.kdf2=function(md,digestLength){_createKDF(this,md,1,digestLength||md.digestLength)};function _createKDF(kdf,md,counterStart,digestLength){kdf.generate=function(x,length){var key=new forge.util.ByteBuffer;var k=Math.ceil(length/digestLength)+counterStart;var c=new forge.util.ByteBuffer;for(var i=counterStart;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var bits,carry=0;for(var i=md.fullMessageLength.length-1;i>=0;--i){bits=md.fullMessageLength[i]*8+carry;carry=bits/4294967296>>>0;finalBlock.putInt32Le(bits>>>0)}var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32Le(s2.h0);rval.putInt32Le(s2.h1);rval.putInt32Le(s2.h2);rval.putInt32Le(s2.h3);return rval};return md};var _padding=null;var _g=null;var _r=null;var _k=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_g=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9];_r=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];_k=new Array(64);for(var i=0;i<64;++i){_k[i]=Math.floor(Math.abs(Math.sin(i+1))*4294967296)}_initialized=true}function _update(s,w,bytes){var t,a,b,c,d,f,r,i;var len=bytes.length();while(len>=64){a=s.h0;b=s.h1;c=s.h2;d=s.h3;for(i=0;i<16;++i){w[i]=bytes.getInt32Le();f=d^b&(c^d);t=a+f+_k[i]+w[i];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<32;++i){f=c^d&(b^c);t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<48;++i){f=b^c^d;t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<64;++i){f=c^(b|~d);t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],25:[function(require,module,exports){var forge=require("./forge");require("./mgf1");module.exports=forge.mgf=forge.mgf||{};forge.mgf.mgf1=forge.mgf1},{"./forge":16,"./mgf1":26}],26:[function(require,module,exports){var forge=require("./forge");require("./util");forge.mgf=forge.mgf||{};var mgf1=module.exports=forge.mgf.mgf1=forge.mgf1=forge.mgf1||{};mgf1.create=function(md){var mgf={generate:function(seed,maskLen){var t=new forge.util.ByteBuffer;var len=Math.ceil(maskLen/md.digestLength);for(var i=0;i=0;l--){x=x>>8;x+=B.at(l)+chunk.at(l);chunk.setAt(l,x&255)}Inew.putBuffer(chunk)}I=Inew;result.putBuffer(buf)}result.truncate(result.length()-n);return result};pki.pbe.getCipher=function(oid,params,password){switch(oid){case pki.oids["pkcs5PBES2"]:return pki.pbe.getCipherForPBES2(oid,params,password);case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:return pki.pbe.getCipherForPKCS12PBE(oid,params,password);default:var error=new Error("Cannot read encrypted PBE data block. Unsupported OID.");error.oid=oid;error.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"];throw error}};pki.pbe.getCipherForPBES2=function(oid,params,password){var capture={};var errors=[];if(!asn1.validate(params,PBES2AlgorithmsValidator,capture,errors)){var error=new Error("Cannot read password-based-encryption algorithm "+"parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}oid=asn1.derToOid(capture.kdfOid);if(oid!==pki.oids["pkcs5PBKDF2"]){var error=new Error("Cannot read encrypted private key. "+"Unsupported key derivation function OID.");error.oid=oid;error.supportedOids=["pkcs5PBKDF2"];throw error}oid=asn1.derToOid(capture.encOid);if(oid!==pki.oids["aes128-CBC"]&&oid!==pki.oids["aes192-CBC"]&&oid!==pki.oids["aes256-CBC"]&&oid!==pki.oids["des-EDE3-CBC"]&&oid!==pki.oids["desCBC"]){var error=new Error("Cannot read encrypted private key. "+"Unsupported encryption scheme OID.");error.oid=oid;error.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"];throw error}var salt=capture.kdfSalt;var count=forge.util.createBuffer(capture.kdfIterationCount);count=count.getInt(count.length()<<3);var dkLen;var cipherFn;switch(pki.oids[oid]){case"aes128-CBC":dkLen=16;cipherFn=forge.aes.createDecryptionCipher;break;case"aes192-CBC":dkLen=24;cipherFn=forge.aes.createDecryptionCipher;break;case"aes256-CBC":dkLen=32;cipherFn=forge.aes.createDecryptionCipher;break;case"des-EDE3-CBC":dkLen=24;cipherFn=forge.des.createDecryptionCipher;break;case"desCBC":dkLen=8;cipherFn=forge.des.createDecryptionCipher;break}var md=prfOidToMessageDigest(capture.prfOid);var dk=forge.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=capture.encIv;var cipher=cipherFn(dk);cipher.start(iv);return cipher};pki.pbe.getCipherForPKCS12PBE=function(oid,params,password){var capture={};var errors=[];if(!asn1.validate(params,pkcs12PbeParamsValidator,capture,errors)){var error=new Error("Cannot read password-based-encryption algorithm "+"parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var salt=forge.util.createBuffer(capture.salt);var count=forge.util.createBuffer(capture.iterations);count=count.getInt(count.length()<<3);var dkLen,dIvLen,cipherFn;switch(oid){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:dkLen=24;dIvLen=8;cipherFn=forge.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:dkLen=5;dIvLen=8;cipherFn=function(key,iv){var cipher=forge.rc2.createDecryptionCipher(key,40);cipher.start(iv,null);return cipher};break;default:var error=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");error.oid=oid;throw error}var md=prfOidToMessageDigest(capture.prfOid);var key=pki.pbe.generatePkcs12Key(password,salt,1,count,dkLen,md);md.start();var iv=pki.pbe.generatePkcs12Key(password,salt,2,count,dIvLen,md);return cipherFn(key,iv)};pki.pbe.opensslDeriveBytes=function(password,salt,dkLen,md){if(typeof md==="undefined"||md===null){if(!("md5"in forge.md)){throw new Error('"md5" hash algorithm unavailable.')}md=forge.md.md5.create()}if(salt===null){salt=""}var digests=[hash(md,password+salt)];for(var length=16,i=1;length4||(!md||md==="sha1"))){if(typeof md!=="string"){md="sha1"}p=Buffer.from(p,"binary");s=Buffer.from(s,"binary");if(!callback){if(crypto.pbkdf2Sync.length===4){return crypto.pbkdf2Sync(p,s,c,dkLen).toString("binary")}return crypto.pbkdf2Sync(p,s,c,dkLen,md).toString("binary")}if(crypto.pbkdf2Sync.length===4){return crypto.pbkdf2(p,s,c,dkLen,function(err,key){if(err){return callback(err)}callback(null,key.toString("binary"))})}return crypto.pbkdf2(p,s,c,dkLen,md,function(err,key){if(err){return callback(err)}callback(null,key.toString("binary"))})}if(typeof md==="undefined"||md===null){md="sha1"}if(typeof md==="string"){if(!(md in forge.md.algorithms)){throw new Error("Unknown hash algorithm: "+md)}md=forge.md[md].create()}var hLen=md.digestLength;if(dkLen>4294967295*hLen){var err=new Error("Derived key is too long.");if(callback){return callback(err)}throw err}var len=Math.ceil(dkLen/hLen);var r=dkLen-(len-1)*hLen;var prf=forge.hmac.create();prf.start(md,p);var dk="";var xor,u_c,u_c1;if(!callback){for(var i=1;i<=len;++i){prf.start(null,null);prf.update(s);prf.update(forge.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();for(var j=2;j<=c;++j){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge.util.xorBytes(xor,u_c,hLen);u_c1=u_c}dk+=ilen){return callback(null,dk)}prf.start(null,null);prf.update(s);prf.update(forge.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();j=2;inner()}function inner(){if(j<=c){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge.util.xorBytes(xor,u_c,hLen);u_c1=u_c;++j;return forge.util.setImmediate(inner)}dk+=i65&&candidate!==-1){var insert=rval[candidate];if(insert===","){++candidate;rval=rval.substr(0,candidate)+"\r\n "+rval.substr(candidate)}else{rval=rval.substr(0,candidate)+"\r\n"+insert+rval.substr(candidate+1)}length=i-candidate-1;candidate=-1;++i}else if(rval[i]===" "||rval[i]==="\t"||rval[i]===","){candidate=i}}return rval}function ltrim(str){return str.replace(/^\s+/,"")}},{"./forge":16,"./util":48}],31:[function(require,module,exports){var forge=require("./forge");require("./util");require("./random");require("./sha1");var pkcs1=module.exports=forge.pkcs1=forge.pkcs1||{};pkcs1.encode_rsa_oaep=function(key,message,options){var label;var seed;var md;var mgf1Md;if(typeof options==="string"){label=options;seed=arguments[3]||undefined;md=arguments[4]||undefined}else if(options){label=options.label||undefined;seed=options.seed||undefined;md=options.md||undefined;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}if(!md){md=forge.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}var keyLength=Math.ceil(key.n.bitLength()/8);var maxLength=keyLength-2*md.digestLength-2;if(message.length>maxLength){var error=new Error("RSAES-OAEP input message length is too long.");error.length=message.length;error.maxLength=maxLength;throw error}if(!label){label=""}md.update(label,"raw");var lHash=md.digest();var PS="";var PS_length=maxLength-message.length;for(var i=0;i>24&255,i>>16&255,i>>8&255,i&255);hash.start();hash.update(seed+c);t+=hash.digest().getBytes()}return t.substring(0,maskLength)}},{"./forge":16,"./random":39,"./sha1":42,"./util":48}],32:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./hmac");require("./oids");require("./pkcs7asn1");require("./pbe");require("./random");require("./rsa");require("./sha1");require("./util");require("./x509");var asn1=forge.asn1;var pki=forge.pki;var p12=module.exports=forge.pkcs12=forge.pkcs12||{};var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"content"}]};var pfxValidator={name:"PFX",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},contentInfoValidator,{name:"PFX.macData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"macIterations"}]}]};var safeBagValidator={name:"SafeBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SafeBag.bagId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,optional:true,capture:"bagAttributes"}]};var attributeValidator={name:"Attribute",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Attribute.attrId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"oid"},{name:"Attribute.attrValues",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,capture:"values"}]};var certBagValidator={name:"CertBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertBag.certId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certId"},{name:"CertBag.certValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,value:[{name:"CertBag.certValue[0]",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.OCTETSTRING,constructed:false,capture:"cert"}]}]};function _getBagsByAttribute(safeContents,attrName,attrValue,bagType){var result=[];for(var i=0;i=0){result.push(bag)}}}return result}p12.pkcs12FromAsn1=function(obj,strict,password){if(typeof strict==="string"){password=strict;strict=true}else if(strict===undefined){strict=true}var capture={};var errors=[];if(!asn1.validate(obj,pfxValidator,capture,errors)){var error=new Error("Cannot read PKCS#12 PFX. "+"ASN.1 object is not an PKCS#12 PFX.");error.errors=error;throw error}var pfx={version:capture.version.charCodeAt(0),safeContents:[],getBags:function(filter){var rval={};var localKeyId;if("localKeyId"in filter){localKeyId=filter.localKeyId}else if("localKeyIdHex"in filter){localKeyId=forge.util.hexToBytes(filter.localKeyIdHex)}if(localKeyId===undefined&&!("friendlyName"in filter)&&"bagType"in filter){rval[filter.bagType]=_getBagsByAttribute(pfx.safeContents,null,null,filter.bagType)}if(localKeyId!==undefined){rval.localKeyId=_getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,filter.bagType)}if("friendlyName"in filter){rval.friendlyName=_getBagsByAttribute(pfx.safeContents,"friendlyName",filter.friendlyName,filter.bagType)}return rval},getBagsByFriendlyName:function(friendlyName,bagType){return _getBagsByAttribute(pfx.safeContents,"friendlyName",friendlyName,bagType)},getBagsByLocalKeyId:function(localKeyId,bagType){return _getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,bagType)}};if(capture.version.charCodeAt(0)!==3){var error=new Error("PKCS#12 PFX of version other than 3 not supported.");error.version=capture.version.charCodeAt(0);throw error}if(asn1.derToOid(capture.contentType)!==pki.oids.data){var error=new Error("Only PKCS#12 PFX in password integrity mode supported.");error.oid=asn1.derToOid(capture.contentType);throw error}var data=capture.content.value[0];if(data.tagClass!==asn1.Class.UNIVERSAL||data.type!==asn1.Type.OCTETSTRING){throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.")}data=_decodePkcs7Data(data);if(capture.mac){var md=null;var macKeyBytes=0;var macAlgorithm=asn1.derToOid(capture.macAlgorithm);switch(macAlgorithm){case pki.oids.sha1:md=forge.md.sha1.create();macKeyBytes=20;break;case pki.oids.sha256:md=forge.md.sha256.create();macKeyBytes=32;break;case pki.oids.sha384:md=forge.md.sha384.create();macKeyBytes=48;break;case pki.oids.sha512:md=forge.md.sha512.create();macKeyBytes=64;break;case pki.oids.md5:md=forge.md.md5.create();macKeyBytes=16;break}if(md===null){throw new Error("PKCS#12 uses unsupported MAC algorithm: "+macAlgorithm)}var macSalt=new forge.util.ByteBuffer(capture.macSalt);var macIterations="macIterations"in capture?parseInt(forge.util.bytesToHex(capture.macIterations),16):1;var macKey=p12.generateKey(password,macSalt,3,macIterations,macKeyBytes,md);var mac=forge.hmac.create();mac.start(md,macKey);mac.update(data.value);var macValue=mac.getMac();if(macValue.getBytes()!==capture.macDigest){throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}}_decodeAuthenticatedSafe(pfx,data.value,strict,password);return pfx};function _decodePkcs7Data(data){if(data.composed||data.constructed){var value=forge.util.createBuffer();for(var i=0;i0){bagAttrs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,attrs)}var contents=[];var chain=[];if(cert!==null){if(forge.util.isArray(cert)){chain=cert}else{chain=[cert]}}var certSafeBags=[];for(var i=0;i0){var certSafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,certSafeBags);var certCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certSafeContents).getBytes())])]);contents.push(certCI)}var keyBag=null;if(key!==null){var pkAsn1=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));if(password===null){keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.keyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pkAsn1]),bagAttrs])}else{keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pki.encryptPrivateKeyInfo(pkAsn1,password,options)]),bagAttrs])}var keySafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[keyBag]);var keyCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(keySafeContents).getBytes())])]);contents.push(keyCI)}var safe=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,contents);var macData;if(options.useMac){var sha1=forge.md.sha1.create();var macSalt=new forge.util.ByteBuffer(forge.random.getBytes(options.saltSize));var count=options.count;var key=p12.generateKey(password,macSalt,3,count,20);var mac=forge.hmac.create();mac.start(sha1,key);mac.update(asn1.toDer(safe).getBytes());var macValue=mac.getMac();macData=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.sha1).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macValue.getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macSalt.getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(count).getBytes())])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(3).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(safe).getBytes())])]),macData])};p12.generateKey=forge.pbe.generatePkcs12Key},{"./asn1":9,"./forge":16,"./hmac":17,"./oids":27,"./pbe":28,"./pkcs7asn1":34,"./random":39,"./rsa":41,"./sha1":42,"./util":48,"./x509":49}],33:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./asn1");require("./des");require("./oids");require("./pem");require("./pkcs7asn1");require("./random");require("./util");require("./x509");var asn1=forge.asn1;var p7=module.exports=forge.pkcs7=forge.pkcs7||{};p7.messageFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if(msg.type!=="PKCS7"){var error=new Error("Could not convert PKCS#7 message from PEM; PEM "+'header type is not "PKCS#7".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.")}var obj=asn1.fromDer(msg.body);return p7.messageFromAsn1(obj)};p7.messageToPem=function(msg,maxline){var pemObj={type:"PKCS7",body:asn1.toDer(msg.toAsn1()).getBytes()};return forge.pem.encode(pemObj,{maxline:maxline})};p7.messageFromAsn1=function(obj){var capture={};var errors=[];if(!asn1.validate(obj,p7.asn1.contentInfoValidator,capture,errors)){var error=new Error("Cannot read PKCS#7 message. "+"ASN.1 object is not an PKCS#7 ContentInfo.");error.errors=errors;throw error}var contentType=asn1.derToOid(capture.contentType);var msg;switch(contentType){case forge.pki.oids.envelopedData:msg=p7.createEnvelopedData();break;case forge.pki.oids.encryptedData:msg=p7.createEncryptedData();break;case forge.pki.oids.signedData:msg=p7.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+contentType+" is not (yet) supported.")}msg.fromAsn1(capture.content.value[0]);return msg};p7.createSignedData=function(){var msg=null;msg={type:forge.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.signedDataValidator);msg.certificates=[];msg.crls=[];msg.digestAlgorithmIdentifiers=[];msg.contentInfo=null;msg.signerInfos=[];if(msg.rawCapture.certificates){var certs=msg.rawCapture.certificates.value;for(var i=0;i0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,certs))}if(crls.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,crls))}signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.signerInfos));return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),signedData])},addSigner:function(signer){var issuer=signer.issuer;var serialNumber=signer.serialNumber;if(signer.certificate){var cert=signer.certificate;if(typeof cert==="string"){cert=forge.pki.certificateFromPem(cert)}issuer=cert.issuer.attributes;serialNumber=cert.serialNumber}var key=signer.key;if(!key){throw new Error("Could not add PKCS#7 signer; no private key specified.")}if(typeof key==="string"){key=forge.pki.privateKeyFromPem(key)}var digestAlgorithm=signer.digestAlgorithm||forge.pki.oids.sha1;switch(digestAlgorithm){case forge.pki.oids.sha1:case forge.pki.oids.sha256:case forge.pki.oids.sha384:case forge.pki.oids.sha512:case forge.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+digestAlgorithm)}var authenticatedAttributes=signer.authenticatedAttributes||[];if(authenticatedAttributes.length>0){var contentType=false;var messageDigest=false;for(var i=0;i0){var attrsAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[]);for(var i=0;i=jan_1_1950&&datebits){num=generateRandom(bits,rng)}if(num.isProbablePrime(mrTests)){return callback(null,num)}num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}while(maxBlockTime<0||+new Date-startbits){num=generateRandom(bits,rng)}var hex=num.toString(16);e.target.postMessage({hex:hex,workLoad:workLoad});num.dAddOffset(range,0)}}}function generateRandom(bits,rng){var num=new BigInteger(bits,rng);var bits1=bits-1;if(!num.testBit(bits1)){num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,num)}num.dAddOffset(31-num.mod(THIRTY).byteValue(),0);return num}function getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}})()},{"./forge":16,"./jsbn":19,"./random":39,"./util":48}],37:[function(require,module,exports){(function(process){var forge=require("./forge");require("./util");var _crypto=null;if(forge.util.isNodejs&&!forge.options.usePureJavaScript&&!process.versions["node-webkit"]){_crypto=require("crypto")}var prng=module.exports=forge.prng=forge.prng||{};prng.create=function(plugin){var ctx={plugin:plugin,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""};var md=plugin.md;var pools=new Array(32);for(var i=0;i<32;++i){pools[i]=md.create()}ctx.pools=pools;ctx.pool=0;ctx.generate=function(count,callback){if(!callback){return ctx.generateSync(count)}var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;var b=forge.util.createBuffer();ctx.key=null;generate();function generate(err){if(err){return callback(err)}if(b.length()>=count){return callback(null,b.getBytes(count))}if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){return forge.util.nextTick(function(){_reseed(generate)})}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed));forge.util.setImmediate(generate)}};ctx.generateSync=function(count){var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;ctx.key=null;var b=forge.util.createBuffer();while(b.length()1048575){ctx.key=null}if(ctx.key===null){_reseedSync()}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed))}return b.getBytes(count)};function _reseed(callback){if(ctx.pools[0].messageLength>=32){_seed();return callback()}var needed=32-ctx.pools[0].messageLength<<5;ctx.seedFile(needed,function(err,bytes){if(err){return callback(err)}ctx.collect(bytes);_seed();callback()})}function _reseedSync(){if(ctx.pools[0].messageLength>=32){return _seed()}var needed=32-ctx.pools[0].messageLength<<5;ctx.collect(ctx.seedFileSync(needed));_seed()}function _seed(){ctx.reseeds=ctx.reseeds===4294967295?0:ctx.reseeds+1;var md=ctx.plugin.md.create();md.update(ctx.keyBytes);var _2powK=1;for(var k=0;k<32;++k){if(ctx.reseeds%_2powK===0){md.update(ctx.pools[k].digest().getBytes());ctx.pools[k].start()}_2powK=_2powK<<1}ctx.keyBytes=md.digest().getBytes();md.start();md.update(ctx.keyBytes);var seedBytes=md.digest().getBytes();ctx.key=ctx.plugin.formatKey(ctx.keyBytes);ctx.seed=ctx.plugin.formatSeed(seedBytes);ctx.generated=0}function defaultSeedFile(needed){var getRandomValues=null;var globalScope=forge.util.globalScope;var _crypto=globalScope.crypto||globalScope.msCrypto;if(_crypto&&_crypto.getRandomValues){getRandomValues=function(arr){return _crypto.getRandomValues(arr)}}var b=forge.util.createBuffer();if(getRandomValues){while(b.length()>16);lo+=(hi&32767)<<16;lo+=hi>>15;lo=(lo&2147483647)+(lo>>31);seed=lo&4294967295;for(var i=0;i<3;++i){next=seed>>>(i<<3);next^=Math.floor(Math.random()*256);b.putByte(String.fromCharCode(next&255))}}}return b.getBytes(needed)}if(_crypto){ctx.seedFile=function(needed,callback){_crypto.randomBytes(needed,function(err,bytes){if(err){return callback(err)}callback(null,bytes.toString())})};ctx.seedFileSync=function(needed){return _crypto.randomBytes(needed).toString()}}else{ctx.seedFile=function(needed,callback){try{callback(null,defaultSeedFile(needed))}catch(e){callback(e)}};ctx.seedFileSync=defaultSeedFile}ctx.collect=function(bytes){var count=bytes.length;for(var i=0;i>x&255)}ctx.collect(bytes)};ctx.registerWorker=function(worker){if(worker===self){ctx.seedFile=function(needed,callback){function listener(e){var data=e.data;if(data.forge&&data.forge.prng){self.removeEventListener("message",listener);callback(data.forge.prng.err,data.forge.prng.bytes)}}self.addEventListener("message",listener);self.postMessage({forge:{prng:{needed:needed}}})}}else{var listener=function(e){var data=e.data;if(data.forge&&data.forge.prng){ctx.seedFile(data.forge.prng.needed,function(err,bytes){worker.postMessage({forge:{prng:{err:err,bytes:bytes}}})})}};worker.addEventListener("message",listener)}};return ctx}}).call(this,require("_process"))},{"./forge":16,"./util":48,_process:50,crypto:6}],38:[function(require,module,exports){var forge=require("./forge");require("./random");require("./util");var pss=module.exports=forge.pss=forge.pss||{};pss.create=function(options){if(arguments.length===3){options={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]}}var hash=options.md;var mgf=options.mgf;var hLen=hash.digestLength;var salt_=options.salt||null;if(typeof salt_==="string"){salt_=forge.util.createBuffer(salt_)}var sLen;if("saltLength"in options){sLen=options.saltLength}else if(salt_!==null){sLen=salt_.length()}else{throw new Error("Salt length not specified or specific salt not given.")}if(salt_!==null&&salt_.length()!==sLen){throw new Error("Given salt length does not match length of given salt.")}var prng=options.prng||forge.random;var pssobj={};pssobj.encode=function(md,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);var mHash=md.digest().getBytes();if(emLen>8*emLen-emBits&255;maskedDB=String.fromCharCode(maskedDB.charCodeAt(0)&~mask)+maskedDB.substr(1);return maskedDB+h+String.fromCharCode(188)};pssobj.verify=function(mHash,em,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);em=em.substr(-emLen);if(emLen>8*emLen-emBits&255;if((maskedDB.charCodeAt(0)&mask)!==0){throw new Error("Bits beyond keysize not zero as expected.")}var dbMask=mgf.generate(h,maskLen);var db="";for(i=0;i>16-bits};var ror=function(word,bits){return(word&65535)>>bits|word<<16-bits&65535};module.exports=forge.rc2=forge.rc2||{};forge.rc2.expandKey=function(key,effKeyBits){if(typeof key==="string"){key=forge.util.createBuffer(key)}effKeyBits=effKeyBits||128;var L=key;var T=key.length();var T1=effKeyBits;var T8=Math.ceil(T1/8);var TM=255>>(T1&7);var i;for(i=T;i<128;i++){L.putByte(piTable[L.at(i-1)+L.at(i-T)&255])}L.setAt(128-T8,piTable[L.at(128-T8)&TM]);for(i=127-T8;i>=0;i--){L.setAt(i,piTable[L.at(i+1)^L.at(i+T8)])}return L};var createCipher=function(key,bits,encrypt){var _finish=false,_input=null,_output=null,_iv=null;var mixRound,mashRound;var i,j,K=[];key=forge.rc2.expandKey(key,bits);for(i=0;i<64;i++){K.push(key.getInt16Le())}if(encrypt){mixRound=function(R){for(i=0;i<4;i++){R[i]+=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]);R[i]=rol(R[i],s[i]);j++}};mashRound=function(R){for(i=0;i<4;i++){R[i]+=K[R[(i+3)%4]&63]}}}else{mixRound=function(R){for(i=3;i>=0;i--){R[i]=ror(R[i],s[i]);R[i]-=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]);j--}};mashRound=function(R){for(i=3;i>=0;i--){R[i]-=K[R[(i+3)%4]&63]}}}var runPlan=function(plan){var R=[];for(i=0;i<4;i++){var val=_input.getInt16Le();if(_iv!==null){if(encrypt){val^=_iv.getInt16Le()}else{_iv.putInt16Le(val)}}R.push(val&65535)}j=encrypt?0:63;for(var ptr=0;ptr=8){runPlan([[5,mixRound],[1,mashRound],[6,mixRound],[1,mashRound],[5,mixRound]])}},finish:function(pad){var rval=true;if(encrypt){if(pad){rval=pad(8,_input,!encrypt)}else{var padding=_input.length()===8?8:8-_input.length();_input.fillWithByte(padding,padding)}}if(rval){_finish=true;cipher.update()}if(!encrypt){rval=_input.length()===0;if(rval){if(pad){rval=pad(8,_output,!encrypt)}else{var len=_output.length();var count=_output.at(len-1);if(count>len){rval=false}else{_output.truncate(count)}}}}return rval}};return cipher};forge.rc2.startEncrypting=function(key,iv,output){var cipher=forge.rc2.createEncryptionCipher(key,128);cipher.start(iv,output);return cipher};forge.rc2.createEncryptionCipher=function(key,bits){return createCipher(key,bits,true)};forge.rc2.startDecrypting=function(key,iv,output){var cipher=forge.rc2.createDecryptionCipher(key,128);cipher.start(iv,output);return cipher};forge.rc2.createDecryptionCipher=function(key,bits){return createCipher(key,bits,false)}},{"./forge":16,"./util":48}],41:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./jsbn");require("./oids");require("./pkcs1");require("./prime");require("./random");require("./util");if(typeof BigInteger==="undefined"){var BigInteger=forge.jsbn.BigInteger}var _crypto=forge.util.isNodejs?require("crypto"):null;var asn1=forge.asn1;var util=forge.util;forge.pki=forge.pki||{};module.exports=forge.pki.rsa=forge.rsa=forge.rsa||{};var pki=forge.pki;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};var rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPrivateKey.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyCoefficient"}]};var rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPublicKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyExponent"}]};var publicKeyValidator=forge.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"rsaPublicKey"}]}]};var emsaPkcs1v15encode=function(md){var oid;if(md.algorithm in pki.oids){oid=pki.oids[md.algorithm]}else{var error=new Error("Unknown message digest algorithm.");error.algorithm=md.algorithm;throw error}var oidBytes=asn1.oidToDer(oid).getBytes();var digestInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var digestAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,oidBytes));digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,""));var digest=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,md.digest().getBytes());digestInfo.value.push(digestAlgorithm);digestInfo.value.push(digest);return asn1.toDer(digestInfo).getBytes()};var _modPow=function(x,key,pub){if(pub){return x.modPow(key.e,key.n)}if(!key.p||!key.q){return x.modPow(key.d,key.n)}if(!key.dP){key.dP=key.d.mod(key.p.subtract(BigInteger.ONE))}if(!key.dQ){key.dQ=key.d.mod(key.q.subtract(BigInteger.ONE))}if(!key.qInv){key.qInv=key.q.modInverse(key.p)}var r;do{r=new BigInteger(forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength()/8)),16)}while(r.compareTo(key.n)>=0||!r.gcd(key.n).equals(BigInteger.ONE));x=x.multiply(r.modPow(key.e,key.n)).mod(key.n);var xp=x.mod(key.p).modPow(key.dP,key.p);var xq=x.mod(key.q).modPow(key.dQ,key.q);while(xp.compareTo(xq)<0){xp=xp.add(key.p)}var y=xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq);y=y.multiply(r.modInverse(key.n)).mod(key.n);return y};pki.rsa.encrypt=function(m,key,bt){var pub=bt;var eb;var k=Math.ceil(key.n.bitLength()/8);if(bt!==false&&bt!==true){pub=bt===2;eb=_encodePkcs1_v1_5(m,key,bt)}else{eb=forge.util.createBuffer();eb.putBytes(m)}var x=new BigInteger(eb.toHex(),16);var y=_modPow(x,key,pub);var yhex=y.toString(16);var ed=forge.util.createBuffer();var zeros=k-Math.ceil(yhex.length/2);while(zeros>0){ed.putByte(0);--zeros}ed.putBytes(forge.util.hexToBytes(yhex));return ed.getBytes()};pki.rsa.decrypt=function(ed,key,pub,ml){var k=Math.ceil(key.n.bitLength()/8);if(ed.length!==k){var error=new Error("Encrypted message length is invalid.");error.length=ed.length;error.expected=k;throw error}var y=new BigInteger(forge.util.createBuffer(ed).toHex(),16);if(y.compareTo(key.n)>=0){throw new Error("Encrypted message is invalid.")}var x=_modPow(y,key,pub);var xhex=x.toString(16);var eb=forge.util.createBuffer();var zeros=k-Math.ceil(xhex.length/2);while(zeros>0){eb.putByte(0);--zeros}eb.putBytes(forge.util.hexToBytes(xhex));if(ml!==false){return _decodePkcs1_v1_5(eb.getBytes(),key,pub)}return eb.getBytes()};pki.rsa.createKeyPairGenerationState=function(bits,e,options){if(typeof bits==="string"){bits=parseInt(bits,10)}bits=bits||2048;options=options||{};var prng=options.prng||forge.random;var rng={nextBytes:function(x){var b=prng.getBytesSync(x.length);for(var i=0;i>1,pBits:bits-(bits>>1),pqState:0,num:null,keys:null};rval.e.fromInt(rval.eInt)}else{throw new Error("Invalid key generation algorithm: "+algorithm)}return rval};pki.rsa.stepKeyPairGenerationState=function(state,n){if(!("algorithm"in state)){state.algorithm="PRIMEINC"}var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var deltaIdx=0;var op_or=function(x,y){return x|y};var t1=+new Date;var t2;var total=0;while(state.keys===null&&(n<=0||totalbits){state.pqState=0}else if(state.num.isProbablePrime(_getMillerRabinTests(state.num.bitLength()))){++state.pqState}else{state.num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}}else if(state.pqState===2){state.pqState=state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)===0?3:0}else if(state.pqState===3){state.pqState=0;if(state.p===null){state.p=state.num}else{state.q=state.num}if(state.p!==null&&state.q!==null){++state.state}state.num=null}}else if(state.state===1){if(state.p.compareTo(state.q)<0){state.num=state.p;state.p=state.q;state.q=state.num}++state.state}else if(state.state===2){state.p1=state.p.subtract(BigInteger.ONE);state.q1=state.q.subtract(BigInteger.ONE);state.phi=state.p1.multiply(state.q1);++state.state}else if(state.state===3){if(state.phi.gcd(state.e).compareTo(BigInteger.ONE)===0){++state.state}else{state.p=null;state.q=null;state.state=0}}else if(state.state===4){state.n=state.p.multiply(state.q);if(state.n.bitLength()===state.bits){++state.state}else{state.q=null;state.state=0}}else if(state.state===5){var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)}}t2=+new Date;total+=t2-t1;t1=t2}return state.keys!==null};pki.rsa.generateKeyPair=function(bits,e,options,callback){if(arguments.length===1){if(typeof bits==="object"){options=bits;bits=undefined}else if(typeof bits==="function"){callback=bits;bits=undefined}}else if(arguments.length===2){if(typeof bits==="number"){if(typeof e==="function"){callback=e;e=undefined}else if(typeof e!=="number"){options=e;e=undefined}}else{options=bits;callback=e;bits=undefined;e=undefined}}else if(arguments.length===3){if(typeof e==="number"){if(typeof options==="function"){callback=options;options=undefined}}else{callback=options;options=e;e=undefined}}options=options||{};if(bits===undefined){bits=options.bits||2048}if(e===undefined){e=options.e||65537}if(!forge.options.usePureJavaScript&&!options.prng&&bits>=256&&bits<=16384&&(e===65537||e===3)){if(callback){if(_detectNodeCrypto("generateKeyPair")){return _crypto.generateKeyPair("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(err,pub,priv){if(err){return callback(err)}callback(null,{privateKey:pki.privateKeyFromPem(priv),publicKey:pki.publicKeyFromPem(pub)})})}if(_detectSubtleCrypto("generateKey")&&_detectSubtleCrypto("exportKey")){return util.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},true,["sign","verify"]).then(function(pair){return util.globalScope.crypto.subtle.exportKey("pkcs8",pair.privateKey)}).then(undefined,function(err){callback(err)}).then(function(pkcs8){if(pkcs8){var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})}})}if(_detectSubtleMsCrypto("generateKey")&&_detectSubtleMsCrypto("exportKey")){var genOp=util.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},true,["sign","verify"]);genOp.oncomplete=function(e){var pair=e.target.result;var exportOp=util.globalScope.msCrypto.subtle.exportKey("pkcs8",pair.privateKey);exportOp.oncomplete=function(e){var pkcs8=e.target.result;var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})};exportOp.onerror=function(err){callback(err)}};genOp.onerror=function(err){callback(err)};return}}else{if(_detectNodeCrypto("generateKeyPairSync")){var keypair=_crypto.generateKeyPairSync("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:pki.privateKeyFromPem(keypair.privateKey),publicKey:pki.publicKeyFromPem(keypair.publicKey)}}}}var state=pki.rsa.createKeyPairGenerationState(bits,e,options);if(!callback){pki.rsa.stepKeyPairGenerationState(state,0);return state.keys}_generateKeyPair(state,options,callback)};pki.setRsaPublicKey=pki.rsa.setPublicKey=function(n,e){var key={n:n,e:e};key.encrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSAES-PKCS1-V1_5"}if(scheme==="RSAES-PKCS1-V1_5"){scheme={encode:function(m,key,pub){return _encodePkcs1_v1_5(m,key,2).getBytes()}}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={encode:function(m,key){return forge.pkcs1.encode_rsa_oaep(key,m,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={encode:function(e){return e}}}else if(typeof scheme==="string"){throw new Error('Unsupported encryption scheme: "'+scheme+'".')}var e=scheme.encode(data,key,true);return pki.rsa.encrypt(e,key,true)};key.verify=function(digest,signature,scheme){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSASSA-PKCS1-V1_5"}if(scheme==="RSASSA-PKCS1-V1_5"){scheme={verify:function(digest,d){d=_decodePkcs1_v1_5(d,key,true);var obj=asn1.fromDer(d);return digest===obj.value[1].value}}}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={verify:function(digest,d){d=_decodePkcs1_v1_5(d,key,true);return digest===d}}}var d=pki.rsa.decrypt(signature,key,true,false);return scheme.verify(digest,d,key.n.bitLength())};return key};pki.setRsaPrivateKey=pki.rsa.setPrivateKey=function(n,e,d,p,q,dP,dQ,qInv){var key={n:n,e:e,d:d,p:p,q:q,dP:dP,dQ:dQ,qInv:qInv};key.decrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSAES-PKCS1-V1_5"}var d=pki.rsa.decrypt(data,key,false,false);if(scheme==="RSAES-PKCS1-V1_5"){scheme={decode:_decodePkcs1_v1_5}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={decode:function(d,key){return forge.pkcs1.decode_rsa_oaep(key,d,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={decode:function(d){return d}}}else{throw new Error('Unsupported encryption scheme: "'+scheme+'".')}return scheme.decode(d,key,false)};key.sign=function(md,scheme){var bt=false;if(typeof scheme==="string"){scheme=scheme.toUpperCase()}if(scheme===undefined||scheme==="RSASSA-PKCS1-V1_5"){scheme={encode:emsaPkcs1v15encode};bt=1}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={encode:function(){return md}};bt=1}var d=scheme.encode(md,key.n.bitLength());return pki.rsa.encrypt(d,key,bt)};return key};pki.wrapRsaPrivateKey=function(rsaKey){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(rsaKey).getBytes())])};pki.privateKeyFromAsn1=function(obj){var capture={};var errors=[];if(asn1.validate(obj,privateKeyValidator,capture,errors)){obj=asn1.fromDer(forge.util.createBuffer(capture.privateKey))}capture={};errors=[];if(!asn1.validate(obj,rsaPrivateKeyValidator,capture,errors)){var error=new Error("Cannot read private key. "+"ASN.1 object does not contain an RSAPrivateKey.");error.errors=errors;throw error}var n,e,d,p,q,dP,dQ,qInv;n=forge.util.createBuffer(capture.privateKeyModulus).toHex();e=forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();d=forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();p=forge.util.createBuffer(capture.privateKeyPrime1).toHex();q=forge.util.createBuffer(capture.privateKeyPrime2).toHex();dP=forge.util.createBuffer(capture.privateKeyExponent1).toHex();dQ=forge.util.createBuffer(capture.privateKeyExponent2).toHex();qInv=forge.util.createBuffer(capture.privateKeyCoefficient).toHex();return pki.setRsaPrivateKey(new BigInteger(n,16),new BigInteger(e,16),new BigInteger(d,16),new BigInteger(p,16),new BigInteger(q,16),new BigInteger(dP,16),new BigInteger(dQ,16),new BigInteger(qInv,16))};pki.privateKeyToAsn1=pki.privateKeyToRSAPrivateKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.d)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.p)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.q)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dP)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dQ)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.qInv))])};pki.publicKeyFromAsn1=function(obj){var capture={};var errors=[];if(asn1.validate(obj,publicKeyValidator,capture,errors)){var oid=asn1.derToOid(capture.publicKeyOid);if(oid!==pki.oids.rsaEncryption){var error=new Error("Cannot read public key. Unknown OID.");error.oid=oid;throw error}obj=capture.rsaPublicKey}errors=[];if(!asn1.validate(obj,rsaPublicKeyValidator,capture,errors)){var error=new Error("Cannot read public key. "+"ASN.1 object does not contain an RSAPublicKey.");error.errors=errors;throw error}var n=forge.util.createBuffer(capture.publicKeyModulus).toHex();var e=forge.util.createBuffer(capture.publicKeyExponent).toHex();return pki.setRsaPublicKey(new BigInteger(n,16),new BigInteger(e,16))};pki.publicKeyToAsn1=pki.publicKeyToSubjectPublicKeyInfo=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,[pki.publicKeyToRSAPublicKey(key)])])};pki.publicKeyToRSAPublicKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e))])};function _encodePkcs1_v1_5(m,key,bt){var eb=forge.util.createBuffer();var k=Math.ceil(key.n.bitLength()/8);if(m.length>k-11){var error=new Error("Message is too long for PKCS#1 v1.5 padding.");error.length=m.length;error.max=k-11;throw error}eb.putByte(0);eb.putByte(bt);var padNum=k-3-m.length;var padByte;if(bt===0||bt===1){padByte=bt===0?0:255;for(var i=0;i0){var numZeros=0;var padBytes=forge.random.getBytes(padNum);for(var i=0;i1){if(eb.getByte()!==255){--eb.read;break}++padNum}}else if(bt===2){padNum=0;while(eb.length()>1){if(eb.getByte()===0){--eb.read;break}++padNum}}var zero=eb.getByte();if(zero!==0||padNum!==k-3-eb.length()){throw new Error("Encryption block is invalid.")}return eb.getBytes()}function _generateKeyPair(state,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var opts={algorithm:{name:options.algorithm||"PRIMEINC",options:{workers:options.workers||2,workLoad:options.workLoad||100,workerScript:options.workerScript}}};if("prng"in options){opts.prng=options.prng}generate();function generate(){getPrime(state.pBits,function(err,num){if(err){return callback(err)}state.p=num;if(state.q!==null){return finish(err,state.q)}getPrime(state.qBits,finish)})}function getPrime(bits,callback){forge.prime.generateProbablePrime(bits,opts,callback)}function finish(err,num){if(err){return callback(err)}state.q=num;if(state.p.compareTo(state.q)<0){var tmp=state.p;state.p=state.q;state.q=tmp}if(state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)!==0){state.p=null;generate();return}if(state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)!==0){state.q=null;getPrime(state.qBits,finish);return}state.p1=state.p.subtract(BigInteger.ONE);state.q1=state.q.subtract(BigInteger.ONE);state.phi=state.p1.multiply(state.q1);if(state.phi.gcd(state.e).compareTo(BigInteger.ONE)!==0){state.p=state.q=null;generate();return}state.n=state.p.multiply(state.q);if(state.n.bitLength()!==state.bits){state.q=null;getPrime(state.qBits,finish);return}var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)};callback(null,state.keys)}}function _bnToBytes(b){var hex=b.toString(16);if(hex[0]>="8"){hex="00"+hex}var bytes=forge.util.hexToBytes(hex);if(bytes.length>1&&(bytes.charCodeAt(0)===0&&(bytes.charCodeAt(1)&128)===0||bytes.charCodeAt(0)===255&&(bytes.charCodeAt(1)&128)===128)){return bytes.substr(1)}return bytes}function _getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}function _detectNodeCrypto(fn){return forge.util.isNodejs&&typeof _crypto[fn]==="function"}function _detectSubtleCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.crypto==="object"&&typeof util.globalScope.crypto.subtle==="object"&&typeof util.globalScope.crypto.subtle[fn]==="function"}function _detectSubtleMsCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.msCrypto==="object"&&typeof util.globalScope.msCrypto.subtle==="object"&&typeof util.globalScope.msCrypto.subtle[fn]==="function"}function _intToUint8Array(x){var bytes=forge.util.hexToBytes(x.toString(16));var buffer=new Uint8Array(bytes.length);for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32(s2.h0);rval.putInt32(s2.h1);rval.putInt32(s2.h2);rval.putInt32(s2.h3);rval.putInt32(s2.h4);return rval};return md};var _padding=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_initialized=true}function _update(s,w,bytes){var t,a,b,c,d,e,f,i;var len=bytes.length();while(len>=64){a=s.h0;b=s.h1;c=s.h2;d=s.h3;e=s.h4;for(i=0;i<16;++i){t=bytes.getInt32();w[i]=t;f=d^b&(c^d);t=(a<<5|a>>>27)+f+e+1518500249+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<20;++i){t=w[i-3]^w[i-8]^w[i-14]^w[i-16];t=t<<1|t>>>31;w[i]=t;f=d^b&(c^d);t=(a<<5|a>>>27)+f+e+1518500249+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<32;++i){t=w[i-3]^w[i-8]^w[i-14]^w[i-16];t=t<<1|t>>>31;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+1859775393+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<40;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+1859775393+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<60;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b&c|d&(b^c);t=(a<<5|a>>>27)+f+e+2400959708+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<80;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+3395469782+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;s.h4=s.h4+e|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],43:[function(require,module,exports){var forge=require("./forge");require("./md");require("./util");var sha256=module.exports=forge.sha256=forge.sha256||{};forge.md.sha256=forge.md.algorithms.sha256=sha256;sha256.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge.util.createBuffer();var _w=new Array(64);var md={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4,h5:_state.h5,h6:_state.h6,h7:_state.h7};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32(s2.h0);rval.putInt32(s2.h1);rval.putInt32(s2.h2);rval.putInt32(s2.h3);rval.putInt32(s2.h4);rval.putInt32(s2.h5);rval.putInt32(s2.h6);rval.putInt32(s2.h7);return rval};return md};var _padding=null;var _initialized=false;var _k=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];_initialized=true}function _update(s,w,bytes){var t1,t2,s0,s1,ch,maj,i,a,b,c,d,e,f,g,h;var len=bytes.length();while(len>=64){for(i=0;i<16;++i){w[i]=bytes.getInt32()}for(;i<64;++i){t1=w[i-2];t1=(t1>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10;t2=w[i-15];t2=(t2>>>7|t2<<25)^(t2>>>18|t2<<14)^t2>>>3;w[i]=t1+w[i-7]+t2+w[i-16]|0}a=s.h0;b=s.h1;c=s.h2;d=s.h3;e=s.h4;f=s.h5;g=s.h6;h=s.h7;for(i=0;i<64;++i){s1=(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7);ch=g^e&(f^g);s0=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10);maj=a&b|c&(a^b);t1=h+s1+ch+_k[i]+w[i];t2=s0+maj;h=g;g=f;f=e;e=d+t1>>>0;d=c;c=b;b=a;a=t1+t2>>>0}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;s.h4=s.h4+e|0;s.h5=s.h5+f|0;s.h6=s.h6+g|0;s.h7=s.h7+h|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],44:[function(require,module,exports){var forge=require("./forge");require("./md");require("./util");var sha512=module.exports=forge.sha512=forge.sha512||{};forge.md.sha512=forge.md.algorithms.sha512=sha512;var sha384=forge.sha384=forge.sha512.sha384=forge.sha512.sha384||{};sha384.create=function(){return sha512.create("SHA-384")};forge.md.sha384=forge.md.algorithms.sha384=sha384;forge.sha512.sha256=forge.sha512.sha256||{create:function(){return sha512.create("SHA-512/256")}};forge.md["sha512/256"]=forge.md.algorithms["sha512/256"]=forge.sha512.sha256;forge.sha512.sha224=forge.sha512.sha224||{create:function(){return sha512.create("SHA-512/224")}};forge.md["sha512/224"]=forge.md.algorithms["sha512/224"]=forge.sha512.sha224;sha512.create=function(algorithm){if(!_initialized){_init()}if(typeof algorithm==="undefined"){algorithm="SHA-512"}if(!(algorithm in _states)){throw new Error("Invalid SHA-512 algorithm: "+algorithm)}var _state=_states[algorithm];var _h=null;var _input=forge.util.createBuffer();var _w=new Array(80);for(var wi=0;wi<80;++wi){_w[wi]=new Array(2)}var digestLength=64;switch(algorithm){case"SHA-384":digestLength=48;break;case"SHA-512/256":digestLength=32;break;case"SHA-512/224":digestLength=28;break}var md={algorithm:algorithm.replace("-","").toLowerCase(),blockLength:128,digestLength:digestLength,messageLength:0,fullMessageLength:null,messageLengthSize:16};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength128=[];var int32s=md.messageLengthSize/4;for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_h,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var h=new Array(_h.length);for(var i=0;i<_h.length;++i){h[i]=_h[i].slice(0)}_update(h,_w,finalBlock);var rval=forge.util.createBuffer();var hlen;if(algorithm==="SHA-512"){hlen=h.length}else if(algorithm==="SHA-384"){hlen=h.length-2}else{hlen=h.length-4}for(var i=0;i=128){for(i=0;i<16;++i){w[i][0]=bytes.getInt32()>>>0;w[i][1]=bytes.getInt32()>>>0}for(;i<80;++i){w2=w[i-2];hi=w2[0];lo=w2[1];t1_hi=((hi>>>19|lo<<13)^(lo>>>29|hi<<3)^hi>>>6)>>>0;t1_lo=((hi<<13|lo>>>19)^(lo<<3|hi>>>29)^(hi<<26|lo>>>6))>>>0;w15=w[i-15];hi=w15[0];lo=w15[1];t2_hi=((hi>>>1|lo<<31)^(hi>>>8|lo<<24)^hi>>>7)>>>0;t2_lo=((hi<<31|lo>>>1)^(hi<<24|lo>>>8)^(hi<<25|lo>>>7))>>>0;w7=w[i-7];w16=w[i-16];lo=t1_lo+w7[1]+t2_lo+w16[1];w[i][0]=t1_hi+w7[0]+t2_hi+w16[0]+(lo/4294967296>>>0)>>>0;w[i][1]=lo>>>0}a_hi=s[0][0];a_lo=s[0][1];b_hi=s[1][0];b_lo=s[1][1];c_hi=s[2][0];c_lo=s[2][1];d_hi=s[3][0];d_lo=s[3][1];e_hi=s[4][0];e_lo=s[4][1];f_hi=s[5][0];f_lo=s[5][1];g_hi=s[6][0];g_lo=s[6][1];h_hi=s[7][0];h_lo=s[7][1];for(i=0;i<80;++i){s1_hi=((e_hi>>>14|e_lo<<18)^(e_hi>>>18|e_lo<<14)^(e_lo>>>9|e_hi<<23))>>>0;s1_lo=((e_hi<<18|e_lo>>>14)^(e_hi<<14|e_lo>>>18)^(e_lo<<23|e_hi>>>9))>>>0;ch_hi=(g_hi^e_hi&(f_hi^g_hi))>>>0;ch_lo=(g_lo^e_lo&(f_lo^g_lo))>>>0;s0_hi=((a_hi>>>28|a_lo<<4)^(a_lo>>>2|a_hi<<30)^(a_lo>>>7|a_hi<<25))>>>0;s0_lo=((a_hi<<4|a_lo>>>28)^(a_lo<<30|a_hi>>>2)^(a_lo<<25|a_hi>>>7))>>>0;maj_hi=(a_hi&b_hi|c_hi&(a_hi^b_hi))>>>0;maj_lo=(a_lo&b_lo|c_lo&(a_lo^b_lo))>>>0;lo=h_lo+s1_lo+ch_lo+_k[i][1]+w[i][1];t1_hi=h_hi+s1_hi+ch_hi+_k[i][0]+w[i][0]+(lo/4294967296>>>0)>>>0;t1_lo=lo>>>0;lo=s0_lo+maj_lo;t2_hi=s0_hi+maj_hi+(lo/4294967296>>>0)>>>0;t2_lo=lo>>>0;h_hi=g_hi;h_lo=g_lo;g_hi=f_hi;g_lo=f_lo;f_hi=e_hi;f_lo=e_lo;lo=d_lo+t1_lo;e_hi=d_hi+t1_hi+(lo/4294967296>>>0)>>>0;e_lo=lo>>>0;d_hi=c_hi;d_lo=c_lo;c_hi=b_hi;c_lo=b_lo;b_hi=a_hi;b_lo=a_lo;lo=t1_lo+t2_lo;a_hi=t1_hi+t2_hi+(lo/4294967296>>>0)>>>0;a_lo=lo>>>0}lo=s[0][1]+a_lo;s[0][0]=s[0][0]+a_hi+(lo/4294967296>>>0)>>>0;s[0][1]=lo>>>0;lo=s[1][1]+b_lo;s[1][0]=s[1][0]+b_hi+(lo/4294967296>>>0)>>>0;s[1][1]=lo>>>0;lo=s[2][1]+c_lo;s[2][0]=s[2][0]+c_hi+(lo/4294967296>>>0)>>>0;s[2][1]=lo>>>0;lo=s[3][1]+d_lo;s[3][0]=s[3][0]+d_hi+(lo/4294967296>>>0)>>>0;s[3][1]=lo>>>0;lo=s[4][1]+e_lo;s[4][0]=s[4][0]+e_hi+(lo/4294967296>>>0)>>>0;s[4][1]=lo>>>0;lo=s[5][1]+f_lo;s[5][0]=s[5][0]+f_hi+(lo/4294967296>>>0)>>>0;s[5][1]=lo>>>0;lo=s[6][1]+g_lo;s[6][0]=s[6][0]+g_hi+(lo/4294967296>>>0)>>>0;s[6][1]=lo>>>0;lo=s[7][1]+h_lo;s[7][0]=s[7][0]+h_hi+(lo/4294967296>>>0)>>>0;s[7][1]=lo>>>0;len-=128}}},{"./forge":16,"./md":23,"./util":48}],45:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./hmac");require("./md5");require("./sha1");require("./util");var ssh=module.exports=forge.ssh=forge.ssh||{};ssh.privateKeyToPutty=function(privateKey,passphrase,comment){comment=comment||"";passphrase=passphrase||"";var algorithm="ssh-rsa";var encryptionAlgorithm=passphrase===""?"none":"aes256-cbc";var ppk="PuTTY-User-Key-File-2: "+algorithm+"\r\n";ppk+="Encryption: "+encryptionAlgorithm+"\r\n";ppk+="Comment: "+comment+"\r\n";var pubbuffer=forge.util.createBuffer();_addStringToBuffer(pubbuffer,algorithm);_addBigIntegerToBuffer(pubbuffer,privateKey.e);_addBigIntegerToBuffer(pubbuffer,privateKey.n);var pub=forge.util.encode64(pubbuffer.bytes(),64);var length=Math.floor(pub.length/66)+1;ppk+="Public-Lines: "+length+"\r\n";ppk+=pub;var privbuffer=forge.util.createBuffer();_addBigIntegerToBuffer(privbuffer,privateKey.d);_addBigIntegerToBuffer(privbuffer,privateKey.p);_addBigIntegerToBuffer(privbuffer,privateKey.q);_addBigIntegerToBuffer(privbuffer,privateKey.qInv);var priv;if(!passphrase){priv=forge.util.encode64(privbuffer.bytes(),64)}else{var encLen=privbuffer.length()+16-1;encLen-=encLen%16;var padding=_sha1(privbuffer.bytes());padding.truncate(padding.length()-encLen+privbuffer.length());privbuffer.putBuffer(padding);var aeskey=forge.util.createBuffer();aeskey.putBuffer(_sha1("\0\0\0\0",passphrase));aeskey.putBuffer(_sha1("\0\0\0",passphrase));var cipher=forge.aes.createEncryptionCipher(aeskey.truncate(8),"CBC");cipher.start(forge.util.createBuffer().fillWithByte(0,16));cipher.update(privbuffer.copy());cipher.finish();var encrypted=cipher.output;encrypted.truncate(16);priv=forge.util.encode64(encrypted.bytes(),64)}length=Math.floor(priv.length/66)+1;ppk+="\r\nPrivate-Lines: "+length+"\r\n";ppk+=priv;var mackey=_sha1("putty-private-key-file-mac-key",passphrase);var macbuffer=forge.util.createBuffer();_addStringToBuffer(macbuffer,algorithm);_addStringToBuffer(macbuffer,encryptionAlgorithm);_addStringToBuffer(macbuffer,comment);macbuffer.putInt32(pubbuffer.length());macbuffer.putBuffer(pubbuffer);macbuffer.putInt32(privbuffer.length());macbuffer.putBuffer(privbuffer);var hmac=forge.hmac.create();hmac.start("sha1",mackey);hmac.update(macbuffer.bytes());ppk+="\r\nPrivate-MAC: "+hmac.digest().toHex()+"\r\n";return ppk};ssh.publicKeyToOpenSSH=function(key,comment){var type="ssh-rsa";comment=comment||"";var buffer=forge.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);return type+" "+forge.util.encode64(buffer.bytes())+" "+comment};ssh.privateKeyToOpenSSH=function(privateKey,passphrase){if(!passphrase){return forge.pki.privateKeyToPem(privateKey)}return forge.pki.encryptRsaPrivateKey(privateKey,passphrase,{legacy:true,algorithm:"aes128"})};ssh.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge.md.md5.create();var type="ssh-rsa";var buffer=forge.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);md.start();md.update(buffer.getBytes());var digest=md.digest();if(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};function _addBigIntegerToBuffer(buffer,val){var hexVal=val.toString(16);if(hexVal[0]>="8"){hexVal="00"+hexVal}var bytes=forge.util.hexToBytes(hexVal);buffer.putInt32(bytes.length);buffer.putBytes(bytes)}function _addStringToBuffer(buffer,val){buffer.putInt32(val.length);buffer.putString(val)}function _sha1(){var sha=forge.md.sha1.create();var num=arguments.length;for(var i=0;i=1){forge.log.verbose(cat,"[%s][%s] init",this.id,this.name,this)}};Task.prototype.debug=function(msg){msg=msg||"";forge.log.debug(cat,msg,"[%s][%s] task:",this.id,this.name,this,"subtasks:",this.subtasks.length,"queue:",sTaskQueues)};Task.prototype.next=function(name,subrun){if(typeof name==="function"){subrun=name;name=this.name}var subtask=new Task({run:subrun,name:name,parent:this});subtask.state=RUNNING;subtask.type=this.type;subtask.successCallback=this.successCallback||null;subtask.failureCallback=this.failureCallback||null;this.subtasks.push(subtask);return this};Task.prototype.parallel=function(name,subrun){if(forge.util.isArray(name)){subrun=name;name=this.name}return this.next(name,function(task){var ptask=task;ptask.block(subrun.length);var startParallelTask=function(pname,pi){forge.task.start({type:pname,run:function(task){subrun[pi](task)},success:function(task){ptask.unblock()},failure:function(task){ptask.unblock()}})};for(var i=0;i0){this.state=sStateTable[this.state][BLOCK]}};Task.prototype.unblock=function(n){n=typeof n==="undefined"?1:n;this.blocks-=n;if(this.blocks===0&&this.state!==DONE){this.state=RUNNING;runNext(this,0)}return this.blocks};Task.prototype.sleep=function(n){n=typeof n==="undefined"?0:n;this.state=sStateTable[this.state][SLEEP];var self=this;this.timeoutId=setTimeout(function(){self.timeoutId=null;self.state=RUNNING;runNext(self,0)},n)};Task.prototype.wait=function(cond){cond.wait(this)};Task.prototype.wakeup=function(){if(this.state===SLEEPING){cancelTimeout(this.timeoutId);this.timeoutId=null;this.state=RUNNING;runNext(this,0)}};Task.prototype.cancel=function(){this.state=sStateTable[this.state][CANCEL];this.permitsNeeded=0;if(this.timeoutId!==null){cancelTimeout(this.timeoutId);this.timeoutId=null}this.subtasks=[]};Task.prototype.fail=function(next){this.error=true;finish(this,true);if(next){next.error=this.error;next.swapTime=this.swapTime;next.userData=this.userData;runNext(next,0)}else{if(this.parent!==null){var parent=this.parent;while(parent.parent!==null){parent.error=this.error;parent.swapTime=this.swapTime;parent.userData=this.userData;parent=parent.parent}finish(parent,true)}if(this.failureCallback){this.failureCallback(this)}}};var start=function(task){task.error=false;task.state=sStateTable[task.state][START];setTimeout(function(){if(task.state===RUNNING){task.swapTime=+new Date;task.run(task);runNext(task,0)}},0)};var runNext=function(task,recurse){var swap=recurse>sMaxRecursions||+new Date-task.swapTime>sTimeSlice;var doNext=function(recurse){recurse++;if(task.state===RUNNING){if(swap){task.swapTime=+new Date}if(task.subtasks.length>0){var subtask=task.subtasks.shift();subtask.error=task.error;subtask.swapTime=task.swapTime;subtask.userData=task.userData;subtask.run(subtask);if(!subtask.error){runNext(subtask,recurse)}}else{finish(task);if(!task.error){if(task.parent!==null){task.parent.error=task.error;task.parent.swapTime=task.swapTime;task.parent.userData=task.userData;runNext(task.parent,recurse)}}}}};if(swap){setTimeout(doNext,0)}else{doNext(recurse)}};var finish=function(task,suppressCallbacks){task.state=DONE;delete sTasks[task.id];if(sVL>=1){forge.log.verbose(cat,"[%s][%s] finish",task.id,task.name,task)}if(task.parent===null){if(!(task.type in sTaskQueues)){forge.log.error(cat,"[%s][%s] task queue missing [%s]",task.id,task.name,task.type)}else if(sTaskQueues[task.type].length===0){forge.log.error(cat,"[%s][%s] task queue empty [%s]",task.id,task.name,task.type)}else if(sTaskQueues[task.type][0]!==task){forge.log.error(cat,"[%s][%s] task not first in queue [%s]",task.id,task.name,task.type)}else{sTaskQueues[task.type].shift();if(sTaskQueues[task.type].length===0){if(sVL>=1){forge.log.verbose(cat,"[%s][%s] delete queue [%s]",task.id,task.name,task.type)}delete sTaskQueues[task.type]}else{if(sVL>=1){forge.log.verbose(cat,"[%s][%s] queue start next [%s] remain:%s",task.id,task.name,task.type,sTaskQueues[task.type].length)}sTaskQueues[task.type][0].start()}}if(!suppressCallbacks){if(task.error&&task.failureCallback){task.failureCallback(task)}else if(!task.error&&task.successCallback){task.successCallback(task)}}}};module.exports=forge.task=forge.task||{};forge.task.start=function(options){var task=new Task({run:options.run,name:options.name||sNoTaskName});task.type=options.type;task.successCallback=options.success||null;task.failureCallback=options.failure||null;if(!(task.type in sTaskQueues)){if(sVL>=1){forge.log.verbose(cat,"[%s][%s] create queue [%s]",task.id,task.name,task.type)}sTaskQueues[task.type]=[task];start(task)}else{sTaskQueues[options.type].push(task)}};forge.task.cancel=function(type){if(type in sTaskQueues){sTaskQueues[type]=[sTaskQueues[type][0]]}};forge.task.createCondition=function(){var cond={tasks:{}};cond.wait=function(task){if(!(task.id in cond.tasks)){task.block();cond.tasks[task.id]=task}};cond.notify=function(){var tmp=cond.tasks;cond.tasks={};for(var id in tmp){tmp[id].unblock()}};return cond}},{"./debug":13,"./forge":16,"./log":21,"./util":48}],47:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./hmac");require("./md5");require("./pem");require("./pki");require("./random");require("./sha1");require("./util");var prf_TLS1=function(secret,label,seed,length){var rval=forge.util.createBuffer();var idx=secret.length>>1;var slen=idx+(secret.length&1);var s1=secret.substr(0,slen);var s2=secret.substr(idx,slen);var ai=forge.util.createBuffer();var hmac=forge.hmac.create();seed=label+seed;var md5itr=Math.ceil(length/16);var sha1itr=Math.ceil(length/20);hmac.start("MD5",s1);var md5bytes=forge.util.createBuffer();ai.putBytes(seed);for(var i=0;i0){tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.no_renegotiation}));tls.flush(c)}c.process()};tls.parseHelloMessage=function(c,record,length){var msg=null;var client=c.entity===tls.ConnectionEnd.client;if(length<38){c.error(c,{message:client?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}else{var b=record.fragment;var remaining=b.length();msg={version:{major:b.getByte(),minor:b.getByte()},random:forge.util.createBuffer(b.getBytes(32)),session_id:readVector(b,1),extensions:[]};if(client){msg.cipher_suite=b.getBytes(2);msg.compression_method=b.getByte()}else{msg.cipher_suites=readVector(b,2);msg.compression_methods=readVector(b,1)}remaining=length-(remaining-b.length());if(remaining>0){var exts=readVector(b,2);while(exts.length()>0){msg.extensions.push({type:[exts.getByte(),exts.getByte()],data:readVector(exts,2)})}if(!client){for(var i=0;i0){var snType=snl.getByte();if(snType!==0){break}c.session.extensions.server_name.serverNameList.push(readVector(snl,2).getBytes())}}}}}if(c.session.version){if(msg.version.major!==c.session.version.major||msg.version.minor!==c.session.version.minor){return c.error(c,{message:"TLS version change is disallowed during renegotiation.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}}if(client){c.session.cipherSuite=tls.getCipherSuite(msg.cipher_suite)}else{var tmp=forge.util.createBuffer(msg.cipher_suites.bytes());while(tmp.length()>0){c.session.cipherSuite=tls.getCipherSuite(tmp.getBytes(2));if(c.session.cipherSuite!==null){break}}}if(c.session.cipherSuite===null){return c.error(c,{message:"No cipher suites in common.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure},cipherSuite:forge.util.bytesToHex(msg.cipher_suite)})}if(client){c.session.compressionMethod=msg.compression_method}else{c.session.compressionMethod=tls.CompressionMethod.none}}return msg};tls.createSecurityParameters=function(c,msg){var client=c.entity===tls.ConnectionEnd.client;var msgRandom=msg.random.bytes();var cRandom=client?c.session.sp.client_random:msgRandom;var sRandom=client?msgRandom:tls.createRandom().getBytes();c.session.sp={entity:c.entity,prf_algorithm:tls.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:c.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:cRandom,server_random:sRandom}};tls.handleServerHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(c.fail){return}if(msg.version.minor<=c.version.minor){c.version.minor=msg.version.minor}else{return c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}c.session.version=c.version;var sessionId=msg.session_id.bytes();if(sessionId.length>0&&sessionId===c.session.id){c.expect=SCC;c.session.resuming=true;c.session.sp.server_random=msg.random.bytes()}else{c.expect=SCE;c.session.resuming=false;tls.createSecurityParameters(c,msg)}c.session.id=sessionId;c.process()};tls.handleClientHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(c.fail){return}var sessionId=msg.session_id.bytes();var session=null;if(c.sessionCache){session=c.sessionCache.getSession(sessionId);if(session===null){sessionId=""}else if(session.version.major!==msg.version.major||session.version.minor>msg.version.minor){session=null;sessionId=""}}if(sessionId.length===0){sessionId=forge.random.getBytes(32)}c.session.id=sessionId;c.session.clientHelloVersion=msg.version;c.session.sp={};if(session){c.version=c.session.version=session.version;c.session.sp=session.sp}else{var version;for(var i=1;i0){cert=readVector(msg.certificate_list,3);asn1=forge.asn1.fromDer(cert);cert=forge.pki.certificateFromAsn1(asn1,true);certs.push(cert)}}catch(ex){return c.error(c,{message:"Could not parse certificate list.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_certificate}})}var client=c.entity===tls.ConnectionEnd.client;if((client||c.verifyClient===true)&&certs.length===0){c.error(c,{message:client?"No server certificate provided.":"No client certificate provided.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}else if(certs.length===0){c.expect=client?SKE:CKE}else{if(client){c.session.serverCertificate=certs[0]}else{c.session.clientCertificate=certs[0]}if(tls.verifyCertificateChain(c,certs)){c.expect=client?SKE:CKE}}c.process()};tls.handleServerKeyExchange=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}})}c.expect=SCR;c.process()};tls.handleClientKeyExchange=function(c,record,length){if(length<48){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}})}var b=record.fragment;var msg={enc_pre_master_secret:readVector(b,2).getBytes()};var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.serverCertificate);privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}}if(privateKey===null){return c.error(c,{message:"No private key set.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}try{var sp=c.session.sp;sp.pre_master_secret=privateKey.decrypt(msg.enc_pre_master_secret);var version=c.session.clientHelloVersion;if(version.major!==sp.pre_master_secret.charCodeAt(0)||version.minor!==sp.pre_master_secret.charCodeAt(1)){throw new Error("TLS version rollback attack detected.")}}catch(ex){sp.pre_master_secret=forge.random.getBytes(48)}c.expect=CCC;if(c.session.clientCertificate!==null){c.expect=CCV}c.process()};tls.handleCertificateRequest=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid CertificateRequest. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var b=record.fragment;var msg={certificate_types:readVector(b,1),certificate_authorities:readVector(b,2)};c.session.certificateRequest=msg;c.expect=SHD;c.process()};tls.handleCertificateVerify=function(c,record,length){if(length<2){return c.error(c,{message:"Invalid CertificateVerify. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var msg={signature:readVector(b,2).getBytes()};var verify=forge.util.createBuffer();verify.putBuffer(c.session.md5.digest());verify.putBuffer(c.session.sha1.digest());verify=verify.getBytes();try{var cert=c.session.clientCertificate;if(!cert.publicKey.verify(verify,msg.signature,"NONE")){throw new Error("CertificateVerify signature does not match.")}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes)}catch(ex){return c.error(c,{message:"Bad signature in CertificateVerify.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure}})}c.expect=CCC;c.process()};tls.handleServerHelloDone=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid ServerHelloDone message. Invalid length.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.record_overflow}})}if(c.serverCertificate===null){var error={message:"No server certificate provided. Not enough security.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.insufficient_security}};var depth=0;var ret=c.verify(c,error.alert.description,depth,[]);if(ret!==true){if(ret||ret===0){if(typeof ret==="object"&&!forge.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}}else if(typeof ret==="number"){error.alert.description=ret}}return c.error(c,error)}}if(c.session.certificateRequest!==null){record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificate(c)});tls.queue(c,record)}record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientKeyExchange(c)});tls.queue(c,record);c.expect=SER;var callback=function(c,signature){if(c.session.certificateRequest!==null&&c.session.clientCertificate!==null){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificateVerify(c,signature)}))}tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()}));c.state.pending=tls.createConnectionState(c);c.state.current.write=c.state.pending.write;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}));c.expect=SCC;tls.flush(c);c.process()};if(c.session.certificateRequest===null||c.session.clientCertificate===null){return callback(c,null)}tls.getClientSignature(c,callback)};tls.handleChangeCipherSpec=function(c,record){if(record.fragment.getByte()!==1){return c.error(c,{message:"Invalid ChangeCipherSpec message received.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var client=c.entity===tls.ConnectionEnd.client;if(c.session.resuming&&client||!c.session.resuming&&!client){c.state.pending=tls.createConnectionState(c)}c.state.current.read=c.state.pending.read;if(!c.session.resuming&&client||c.session.resuming&&!client){c.state.pending=null}c.expect=client?SFI:CFI;c.process()};tls.handleFinished=function(c,record,length){var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var vd=record.fragment.getBytes();b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client;var label=client?"server finished":"client finished";var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;b=prf(sp.master_secret,label,b.getBytes(),vdl);if(b.getBytes()!==vd){return c.error(c,{message:"Invalid verify_data in Finished message.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decrypt_error}})}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes);if(c.session.resuming&&client||!c.session.resuming&&!client){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()}));c.state.current.write=c.state.pending.write;c.state.pending=null;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}))}c.expect=client?SAD:CAD;c.handshaking=false;++c.handshakes;c.peerCertificate=client?c.session.serverCertificate:c.session.clientCertificate;tls.flush(c);c.isConnected=true;c.connected(c);c.process()};tls.handleAlert=function(c,record){var b=record.fragment;var alert={level:b.getByte(),description:b.getByte()};var msg;switch(alert.description){case tls.Alert.Description.close_notify:msg="Connection closed.";break;case tls.Alert.Description.unexpected_message:msg="Unexpected message.";break;case tls.Alert.Description.bad_record_mac:msg="Bad record MAC.";break;case tls.Alert.Description.decryption_failed:msg="Decryption failed.";break;case tls.Alert.Description.record_overflow:msg="Record overflow.";break;case tls.Alert.Description.decompression_failure:msg="Decompression failed.";break;case tls.Alert.Description.handshake_failure:msg="Handshake failure.";break;case tls.Alert.Description.bad_certificate:msg="Bad certificate.";break;case tls.Alert.Description.unsupported_certificate:msg="Unsupported certificate.";break;case tls.Alert.Description.certificate_revoked:msg="Certificate revoked.";break;case tls.Alert.Description.certificate_expired:msg="Certificate expired.";break;case tls.Alert.Description.certificate_unknown:msg="Certificate unknown.";break;case tls.Alert.Description.illegal_parameter:msg="Illegal parameter.";break;case tls.Alert.Description.unknown_ca:msg="Unknown certificate authority.";break;case tls.Alert.Description.access_denied:msg="Access denied.";break;case tls.Alert.Description.decode_error:msg="Decode error.";break;case tls.Alert.Description.decrypt_error:msg="Decrypt error.";break;case tls.Alert.Description.export_restriction:msg="Export restriction.";break;case tls.Alert.Description.protocol_version:msg="Unsupported protocol version.";break;case tls.Alert.Description.insufficient_security:msg="Insufficient security.";break;case tls.Alert.Description.internal_error:msg="Internal error.";break;case tls.Alert.Description.user_canceled:msg="User canceled.";break;case tls.Alert.Description.no_renegotiation:msg="Renegotiation not supported.";break;default:msg="Unknown error.";break}if(alert.description===tls.Alert.Description.close_notify){return c.close()}c.error(c,{message:msg,send:false,origin:c.entity===tls.ConnectionEnd.client?"server":"client",alert:alert});c.process()};tls.handleHandshake=function(c,record){var b=record.fragment;var type=b.getByte();var length=b.getInt24();if(length>b.length()){c.fragmented=record;record.fragment=forge.util.createBuffer();b.read-=4;return c.process()}c.fragmented=null;b.read-=4;var bytes=b.bytes(length+4);b.read+=4;if(type in hsTable[c.entity][c.expect]){if(c.entity===tls.ConnectionEnd.server&&!c.open&&!c.fail){c.handshaking=true;c.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:forge.md.md5.create(),sha1:forge.md.sha1.create()}}if(type!==tls.HandshakeType.hello_request&&type!==tls.HandshakeType.certificate_verify&&type!==tls.HandshakeType.finished){c.session.md5.update(bytes);c.session.sha1.update(bytes)}hsTable[c.entity][c.expect][type](c,record,length)}else{tls.handleUnexpected(c,record)}};tls.handleApplicationData=function(c,record){c.data.putBuffer(record.fragment);c.dataReady(c);c.process()};tls.handleHeartbeat=function(c,record){var b=record.fragment;var type=b.getByte();var length=b.getInt16();var payload=b.getBytes(length);if(type===tls.HeartbeatMessageType.heartbeat_request){if(c.handshaking||length>payload.length){return c.process()}tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_response,payload)}));tls.flush(c)}else if(type===tls.HeartbeatMessageType.heartbeat_response){if(payload!==c.expectedHeartbeatPayload){return c.process()}if(c.heartbeatReceived){c.heartbeatReceived(c,forge.util.createBuffer(payload))}}c.process()};var SHE=0;var SCE=1;var SKE=2;var SCR=3;var SHD=4;var SCC=5;var SFI=6;var SAD=7;var SER=8;var CHE=0;var CCE=1;var CKE=2;var CCV=3;var CCC=4;var CFI=5;var CAD=6;var CER=7;var __=tls.handleUnexpected;var R0=tls.handleChangeCipherSpec;var R1=tls.handleAlert;var R2=tls.handleHandshake;var R3=tls.handleApplicationData;var R4=tls.handleHeartbeat;var ctTable=[];ctTable[tls.ConnectionEnd.client]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]];ctTable[tls.ConnectionEnd.server]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]];var H0=tls.handleHelloRequest;var H1=tls.handleServerHello;var H2=tls.handleCertificate;var H3=tls.handleServerKeyExchange;var H4=tls.handleCertificateRequest;var H5=tls.handleServerHelloDone;var H6=tls.handleFinished;var hsTable=[];hsTable[tls.ConnectionEnd.client]=[[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];var H7=tls.handleClientHello;var H8=tls.handleClientKeyExchange;var H9=tls.handleCertificateVerify;hsTable[tls.ConnectionEnd.server]=[[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];tls.generateKeys=function(c,sp){var prf=prf_TLS1;var random=sp.client_random+sp.server_random;if(!c.session.resuming){sp.master_secret=prf(sp.pre_master_secret,"master secret",random,48).bytes();sp.pre_master_secret=null}random=sp.server_random+sp.client_random;var length=2*sp.mac_key_length+2*sp.enc_key_length;var tls10=c.version.major===tls.Versions.TLS_1_0.major&&c.version.minor===tls.Versions.TLS_1_0.minor;if(tls10){length+=2*sp.fixed_iv_length}var km=prf(sp.master_secret,"key expansion",random,length);var rval={client_write_MAC_key:km.getBytes(sp.mac_key_length),server_write_MAC_key:km.getBytes(sp.mac_key_length),client_write_key:km.getBytes(sp.enc_key_length),server_write_key:km.getBytes(sp.enc_key_length)};if(tls10){rval.client_write_IV=km.getBytes(sp.fixed_iv_length);rval.server_write_IV=km.getBytes(sp.fixed_iv_length)}return rval};tls.createConnectionState=function(c){var client=c.entity===tls.ConnectionEnd.client;var createMode=function(){var mode={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(record){return true},compressionState:null,compressFunction:function(record){return true},updateSequenceNumber:function(){if(mode.sequenceNumber[1]===4294967295){mode.sequenceNumber[1]=0;++mode.sequenceNumber[0]}else{++mode.sequenceNumber[1]}}};return mode};var state={read:createMode(),write:createMode()};state.read.update=function(c,record){if(!state.read.cipherFunction(record,state.read)){c.error(c,{message:"Could not decrypt record or bad MAC.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_record_mac}})}else if(!state.read.compressFunction(c,record,state.read)){c.error(c,{message:"Could not decompress record.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decompression_failure}})}return!c.fail};state.write.update=function(c,record){if(!state.write.compressFunction(c,record,state.write)){c.error(c,{message:"Could not compress record.",send:false,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}else if(!state.write.cipherFunction(record,state.write)){c.error(c,{message:"Could not encrypt record.",send:false,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}return!c.fail};if(c.session){var sp=c.session.sp;c.session.cipherSuite.initSecurityParameters(sp);sp.keys=tls.generateKeys(c,sp);state.read.macKey=client?sp.keys.server_write_MAC_key:sp.keys.client_write_MAC_key;state.write.macKey=client?sp.keys.client_write_MAC_key:sp.keys.server_write_MAC_key;c.session.cipherSuite.initConnectionState(state,c,sp);switch(sp.compression_algorithm){case tls.CompressionMethod.none:break;case tls.CompressionMethod.deflate:state.read.compressFunction=inflate;state.write.compressFunction=deflate;break;default:throw new Error("Unsupported compression algorithm.")}}return state};tls.createRandom=function(){var d=new Date;var utc=+d+d.getTimezoneOffset()*6e4;var rval=forge.util.createBuffer();rval.putInt32(utc);rval.putBytes(forge.random.getBytes(28));return rval};tls.createRecord=function(c,options){if(!options.data){return null}var record={type:options.type,version:{major:c.version.major,minor:c.version.minor},length:options.data.length(),fragment:options.data};return record};tls.createAlert=function(c,alert){var b=forge.util.createBuffer();b.putByte(alert.level);b.putByte(alert.description);return tls.createRecord(c,{type:tls.ContentType.alert,data:b})};tls.createClientHello=function(c){c.session.clientHelloVersion={major:c.version.major,minor:c.version.minor};var cipherSuites=forge.util.createBuffer();for(var i=0;i0){extLength+=2}var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+cSuites+1+cMethods+extLength;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.client_hello);rval.putInt24(length);rval.putByte(c.version.major);rval.putByte(c.version.minor);rval.putBytes(c.session.sp.client_random);writeVector(rval,1,forge.util.createBuffer(sessionId));writeVector(rval,2,cipherSuites);writeVector(rval,1,compressionMethods);if(extLength>0){writeVector(rval,2,extensions)}return rval};tls.createServerHello=function(c){var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+1;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.server_hello);rval.putInt24(length);rval.putByte(c.version.major);rval.putByte(c.version.minor);rval.putBytes(c.session.sp.server_random);writeVector(rval,1,forge.util.createBuffer(sessionId));rval.putByte(c.session.cipherSuite.id[0]);rval.putByte(c.session.cipherSuite.id[1]);rval.putByte(c.session.compressionMethod);return rval};tls.createCertificate=function(c){var client=c.entity===tls.ConnectionEnd.client;var cert=null;if(c.getCertificate){var hint;if(client){hint=c.session.certificateRequest}else{hint=c.session.extensions.server_name.serverNameList}cert=c.getCertificate(c,hint)}var certList=forge.util.createBuffer();if(cert!==null){try{if(!forge.util.isArray(cert)){cert=[cert]}var asn1=null;for(var i=0;i0){rval.putByte(tls.HandshakeType.server_key_exchange);rval.putInt24(length)}return rval};tls.getClientSignature=function(c,callback){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());b=b.getBytes();c.getSignature=c.getSignature||function(c,b,callback){var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.clientCertificate);privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}}if(privateKey===null){c.error(c,{message:"No private key set.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}else{b=privateKey.sign(b,null)}callback(c,b)};c.getSignature(c,b,callback)};tls.createCertificateVerify=function(c,signature){var length=signature.length+2;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.certificate_verify);rval.putInt24(length);rval.putInt16(signature.length);rval.putBytes(signature);return rval};tls.createCertificateRequest=function(c){var certTypes=forge.util.createBuffer();certTypes.putByte(1);var cAs=forge.util.createBuffer();for(var key in c.caStore.certs){var cert=c.caStore.certs[key];var dn=forge.pki.distinguishedNameToAsn1(cert.subject);var byteBuffer=forge.asn1.toDer(dn);cAs.putInt16(byteBuffer.length());cAs.putBuffer(byteBuffer)}var length=1+certTypes.length()+2+cAs.length();var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.certificate_request);rval.putInt24(length);writeVector(rval,1,certTypes);writeVector(rval,2,cAs);return rval};tls.createServerHelloDone=function(c){var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.server_hello_done);rval.putInt24(0);return rval};tls.createChangeCipherSpec=function(){var rval=forge.util.createBuffer();rval.putByte(1);return rval};tls.createFinished=function(c){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client;var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;var label=client?"client finished":"server finished";b=prf(sp.master_secret,label,b.getBytes(),vdl);var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.finished);rval.putInt24(b.length());rval.putBuffer(b);return rval};tls.createHeartbeat=function(type,payload,payloadLength){if(typeof payloadLength==="undefined"){payloadLength=payload.length}var rval=forge.util.createBuffer();rval.putByte(type);rval.putInt16(payloadLength);rval.putBytes(payload);var plaintextLength=rval.length();var paddingLength=Math.max(16,plaintextLength-payloadLength-3);rval.putBytes(forge.random.getBytes(paddingLength));return rval};tls.queue=function(c,record){if(!record){return}if(record.fragment.length()===0){if(record.type===tls.ContentType.handshake||record.type===tls.ContentType.alert||record.type===tls.ContentType.change_cipher_spec){return}}if(record.type===tls.ContentType.handshake){var bytes=record.fragment.bytes();c.session.md5.update(bytes);c.session.sha1.update(bytes);bytes=null}var records;if(record.fragment.length()<=tls.MaxFragment){records=[record]}else{records=[];var data=record.fragment.bytes();while(data.length>tls.MaxFragment){records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data.slice(0,tls.MaxFragment))}));data=data.slice(tls.MaxFragment)}if(data.length>0){records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data)}))}}for(var i=0;i0){key=rval.order[0]}if(key!==null&&key in rval.cache){session=rval.cache[key];delete rval.cache[key];for(var i in rval.order){if(rval.order[i]===key){rval.order.splice(i,1);break}}}return session};rval.setSession=function(sessionId,session){if(rval.order.length===rval.capacity){var key=rval.order.shift();delete rval.cache[key]}var key=forge.util.bytesToHex(sessionId);rval.order.push(key);rval.cache[key]=session}}return rval};tls.createConnection=function(options){var caStore=null;if(options.caStore){if(forge.util.isArray(options.caStore)){caStore=forge.pki.createCaStore(options.caStore)}else{caStore=options.caStore}}else{caStore=forge.pki.createCaStore()}var cipherSuites=options.cipherSuites||null;if(cipherSuites===null){cipherSuites=[];for(var key in tls.CipherSuites){cipherSuites.push(tls.CipherSuites[key])}}var entity=options.server||false?tls.ConnectionEnd.server:tls.ConnectionEnd.client;var sessionCache=options.sessionCache?tls.createSessionCache(options.sessionCache):null;var c={version:{major:tls.Version.major,minor:tls.Version.minor},entity:entity,sessionId:options.sessionId,caStore:caStore,sessionCache:sessionCache,cipherSuites:cipherSuites,connected:options.connected,virtualHost:options.virtualHost||null,verifyClient:options.verifyClient||false,verify:options.verify||function(cn,vfd,dpth,cts){return vfd},verifyOptions:options.verifyOptions||{},getCertificate:options.getCertificate||null,getPrivateKey:options.getPrivateKey||null,getSignature:options.getSignature||null,input:forge.util.createBuffer(),tlsData:forge.util.createBuffer(),data:forge.util.createBuffer(),tlsDataReady:options.tlsDataReady,dataReady:options.dataReady,heartbeatReceived:options.heartbeatReceived,closed:options.closed,error:function(c,ex){ex.origin=ex.origin||(c.entity===tls.ConnectionEnd.client?"client":"server");if(ex.send){tls.queue(c,tls.createAlert(c,ex.alert));tls.flush(c)}var fatal=ex.fatal!==false;if(fatal){c.fail=true}options.error(c,ex);if(fatal){c.close(false)}},deflate:options.deflate||null,inflate:options.inflate||null};c.reset=function(clearFail){c.version={major:tls.Version.major,minor:tls.Version.minor};c.record=null;c.session=null;c.peerCertificate=null;c.state={pending:null,current:null};c.expect=c.entity===tls.ConnectionEnd.client?SHE:CHE;c.fragmented=null;c.records=[];c.open=false;c.handshakes=0;c.handshaking=false;c.isConnected=false;c.fail=!(clearFail||typeof clearFail==="undefined");c.input.clear();c.tlsData.clear();c.data.clear();c.state.current=tls.createConnectionState(c)};c.reset();var _update=function(c,record){var aligned=record.type-tls.ContentType.change_cipher_spec;var handlers=ctTable[c.entity][c.expect];if(aligned in handlers){handlers[aligned](c,record)}else{tls.handleUnexpected(c,record)}};var _readRecordHeader=function(c){var rval=0;var b=c.input;var len=b.length();if(len<5){rval=5-len}else{c.record={type:b.getByte(),version:{major:b.getByte(),minor:b.getByte()},length:b.getInt16(),fragment:forge.util.createBuffer(),ready:false};var compatibleVersion=c.record.version.major===c.version.major;if(compatibleVersion&&c.session&&c.session.version){compatibleVersion=c.record.version.minor===c.version.minor}if(!compatibleVersion){c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}}return rval};var _readRecord=function(c){var rval=0;var b=c.input;var len=b.length();if(len0){if(c.sessionCache){session=c.sessionCache.getSession(sessionId)}if(session===null){sessionId=""}}if(sessionId.length===0&&c.sessionCache){session=c.sessionCache.getSession();if(session!==null){sessionId=session.id}}c.session={id:sessionId,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:forge.md.md5.create(),sha1:forge.md.sha1.create()};if(session){c.version=session.version;c.session.sp=session.sp}c.session.sp.client_random=tls.createRandom().getBytes();c.open=true;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientHello(c)}));tls.flush(c)}};c.process=function(data){var rval=0;if(data){c.input.putBytes(data)}if(!c.fail){if(c.record!==null&&c.record.ready&&c.record.fragment.isEmpty()){c.record=null}if(c.record===null){rval=_readRecordHeader(c)}if(!c.fail&&c.record!==null&&!c.record.ready){rval=_readRecord(c)}if(!c.fail&&c.record!==null&&c.record.ready){_update(c,c.record)}}return rval};c.prepare=function(data){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.application_data,data:forge.util.createBuffer(data)}));return tls.flush(c)};c.prepareHeartbeatRequest=function(payload,payloadLength){if(payload instanceof forge.util.ByteBuffer){payload=payload.bytes()}if(typeof payloadLength==="undefined"){payloadLength=payload.length}c.expectedHeartbeatPayload=payload;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_request,payload,payloadLength)}));return tls.flush(c)};c.close=function(clearFail){if(!c.fail&&c.sessionCache&&c.session){var session={id:c.session.id,version:c.session.version,sp:c.session.sp};session.sp.keys=null;c.sessionCache.setSession(session.id,session)}if(c.open){c.open=false;c.input.clear();if(c.isConnected||c.handshaking){c.isConnected=c.handshaking=false;tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.close_notify}));tls.flush(c)}c.closed(c)}c.reset(clearFail)};return c};module.exports=forge.tls=forge.tls||{};for(var key in tls){if(typeof tls[key]!=="function"){forge.tls[key]=tls[key]}}forge.tls.prf_tls1=prf_TLS1;forge.tls.hmac_sha1=hmac_sha1;forge.tls.createSessionCache=tls.createSessionCache;forge.tls.createConnection=tls.createConnection},{"./asn1":9,"./forge":16,"./hmac":17,"./md5":24,"./pem":30,"./pki":35,"./random":39,"./sha1":42,"./util":48}],48:[function(require,module,exports){(function(process,global,Buffer,__argument0,__argument1,__argument2,__argument3,setImmediate){var forge=require("./forge");var baseN=require("./baseN");var util=module.exports=forge.util=forge.util||{};(function(){if(typeof process!=="undefined"&&process.nextTick&&!process.browser){util.nextTick=process.nextTick;if(typeof setImmediate==="function"){util.setImmediate=setImmediate}else{util.setImmediate=util.nextTick}return}if(typeof setImmediate==="function"){util.setImmediate=function(){return setImmediate.apply(undefined,arguments)};util.nextTick=function(callback){return setImmediate(callback)};return}util.setImmediate=function(callback){setTimeout(callback,0)};if(typeof window!=="undefined"&&typeof window.postMessage==="function"){var msg="forge.setImmediate";var callbacks=[];util.setImmediate=function(callback){callbacks.push(callback);if(callbacks.length===1){window.postMessage(msg,"*")}};function handler(event){if(event.source===window&&event.data===msg){event.stopPropagation();var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}}window.addEventListener("message",handler,true)}if(typeof MutationObserver!=="undefined"){var now=Date.now();var attr=true;var div=document.createElement("div");var callbacks=[];new MutationObserver(function(){var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}).observe(div,{attributes:true});var oldSetImmediate=util.setImmediate;util.setImmediate=function(callback){if(Date.now()-now>15){now=Date.now();oldSetImmediate(callback)}else{callbacks.push(callback);if(callbacks.length===1){div.setAttribute("a",attr=!attr)}}}}util.nextTick=util.setImmediate})();util.isNodejs=typeof process!=="undefined"&&process.versions&&process.versions.node;util.globalScope=function(){if(util.isNodejs){return global}return typeof self==="undefined"?window:self}();util.isArray=Array.isArray||function(x){return Object.prototype.toString.call(x)==="[object Array]"};util.isArrayBuffer=function(x){return typeof ArrayBuffer!=="undefined"&&x instanceof ArrayBuffer};util.isArrayBufferView=function(x){return x&&util.isArrayBuffer(x.buffer)&&x.byteLength!==undefined};function _checkBitsParam(n){if(!(n===8||n===16||n===24||n===32)){throw new Error("Only 8, 16, 24, or 32 bits supported: "+n)}}util.ByteBuffer=ByteStringBuffer;function ByteStringBuffer(b){this.data="";this.read=0;if(typeof b==="string"){this.data=b}else if(util.isArrayBuffer(b)||util.isArrayBufferView(b)){if(typeof Buffer!=="undefined"&&b instanceof Buffer){this.data=b.toString("binary")}else{var arr=new Uint8Array(b);try{this.data=String.fromCharCode.apply(null,arr)}catch(e){for(var i=0;i_MAX_CONSTRUCTED_STRING_LENGTH){this.data.substr(0,1);this._constructedStringLength=0}};util.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};util.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};util.ByteStringBuffer.prototype.putByte=function(b){return this.putBytes(String.fromCharCode(b))};util.ByteStringBuffer.prototype.fillWithByte=function(b,n){b=String.fromCharCode(b);var d=this.data;while(n>0){if(n&1){d+=b}n>>>=1;if(n>0){b+=b}}this.data=d;this._optimizeConstructedString(n);return this};util.ByteStringBuffer.prototype.putBytes=function(bytes){this.data+=bytes;this._optimizeConstructedString(bytes.length);return this};util.ByteStringBuffer.prototype.putString=function(str){return this.putBytes(util.encodeUtf8(str))};util.ByteStringBuffer.prototype.putInt16=function(i){return this.putBytes(String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt24=function(i){return this.putBytes(String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt32=function(i){return this.putBytes(String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt16Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255))};util.ByteStringBuffer.prototype.putInt24Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255))};util.ByteStringBuffer.prototype.putInt32Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>24&255))};util.ByteStringBuffer.prototype.putInt=function(i,n){_checkBitsParam(n);var bytes="";do{n-=8;bytes+=String.fromCharCode(i>>n&255)}while(n>0);return this.putBytes(bytes)};util.ByteStringBuffer.prototype.putSignedInt=function(i,n){if(i<0){i+=2<0);return rval};util.ByteStringBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<=max){x-=max<<1}return x};util.ByteStringBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.ByteStringBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.ByteStringBuffer.prototype.at=function(i){return this.data.charCodeAt(this.read+i)};util.ByteStringBuffer.prototype.setAt=function(i,b){this.data=this.data.substr(0,this.read+i)+String.fromCharCode(b)+this.data.substr(this.read+i+1);return this};util.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};util.ByteStringBuffer.prototype.copy=function(){var c=util.createBuffer(this.data);c.read=this.read;return c};util.ByteStringBuffer.prototype.compact=function(){if(this.read>0){this.data=this.data.slice(this.read);this.read=0}return this};util.ByteStringBuffer.prototype.clear=function(){this.data="";this.read=0;return this};util.ByteStringBuffer.prototype.truncate=function(count){var len=Math.max(0,this.length()-count);this.data=this.data.substr(this.read,len);this.read=0;return this};util.ByteStringBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i=amount){return this}growSize=Math.max(growSize||this.growSize,amount);var src=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);var dst=new Uint8Array(this.length()+growSize);dst.set(src);this.data=new DataView(dst.buffer);return this};util.DataBuffer.prototype.putByte=function(b){this.accommodate(1);this.data.setUint8(this.write++,b);return this};util.DataBuffer.prototype.fillWithByte=function(b,n){this.accommodate(n);for(var i=0;i>8&65535);this.data.setInt8(this.write,i>>16&255);this.write+=3;return this};util.DataBuffer.prototype.putInt32=function(i){this.accommodate(4);this.data.setInt32(this.write,i);this.write+=4;return this};util.DataBuffer.prototype.putInt16Le=function(i){this.accommodate(2);this.data.setInt16(this.write,i,true);this.write+=2;return this};util.DataBuffer.prototype.putInt24Le=function(i){this.accommodate(3);this.data.setInt8(this.write,i>>16&255);this.data.setInt16(this.write,i>>8&65535,true);this.write+=3;return this};util.DataBuffer.prototype.putInt32Le=function(i){this.accommodate(4);this.data.setInt32(this.write,i,true);this.write+=4;return this};util.DataBuffer.prototype.putInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);do{n-=8;this.data.setInt8(this.write++,i>>n&255)}while(n>0);return this};util.DataBuffer.prototype.putSignedInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);if(i<0){i+=2<0);return rval};util.DataBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<=max){x-=max<<1}return x};util.DataBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.DataBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.DataBuffer.prototype.at=function(i){return this.data.getUint8(this.read+i)};util.DataBuffer.prototype.setAt=function(i,b){this.data.setUint8(i,b);return this};util.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};util.DataBuffer.prototype.copy=function(){return new util.DataBuffer(this)};util.DataBuffer.prototype.compact=function(){if(this.read>0){var src=new Uint8Array(this.data.buffer,this.read);var dst=new Uint8Array(src.byteLength);dst.set(src);this.data=new DataView(dst);this.write-=this.read;this.read=0}return this};util.DataBuffer.prototype.clear=function(){this.data=new DataView(new ArrayBuffer(0));this.read=this.write=0;return this};util.DataBuffer.prototype.truncate=function(count){this.write=Math.max(0,this.length()-count);this.read=Math.min(this.read,this.write);return this};util.DataBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i0){if(n&1){s+=c}n>>>=1;if(n>0){c+=c}}return s};util.xorBytes=function(s1,s2,n){var s3="";var b="";var t="";var i=0;var c=0;for(;n>0;--n,++i){b=s1.charCodeAt(i)^s2.charCodeAt(i);if(c>=10){s3+=t;t="";c=0}t+=String.fromCharCode(b);++c}s3+=t;return s3};util.hexToBytes=function(hex){var rval="";var i=0;if(hex.length&1==1){i=1;rval+=String.fromCharCode(parseInt(hex[0],16))}for(;i>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var _base64Idx=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,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,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];var _base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util.encode64=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.decode64=function(input){input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");var output="";var enc1,enc2,enc3,enc4;var i=0;while(i>4);if(enc3!==64){output+=String.fromCharCode((enc2&15)<<4|enc3>>2);if(enc4!==64){output+=String.fromCharCode((enc3&3)<<6|enc4)}}}return output};util.encodeUtf8=function(str){return unescape(encodeURIComponent(str))};util.decodeUtf8=function(str){return decodeURIComponent(escape(str))};util.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}};util.binary.raw.encode=function(bytes){return String.fromCharCode.apply(null,bytes)};util.binary.raw.decode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j=offset;for(var i=0;i>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.binary.base64.decode=function(input,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(input.length/4)*3)}input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");offset=offset||0;var enc1,enc2,enc3,enc4;var i=0,j=offset;while(i>4;if(enc3!==64){out[j++]=(enc2&15)<<4|enc3>>2;if(enc4!==64){out[j++]=(enc3&3)<<6|enc4}}}return output?j-offset:out.subarray(0,j)};util.binary.base58.encode=function(input,maxline){return util.binary.baseN.encode(input,_base58,maxline)};util.binary.base58.decode=function(input,maxline){return util.binary.baseN.decode(input,_base58,maxline)};util.text={utf8:{},utf16:{}};util.text.utf8.encode=function(str,output,offset){str=util.encodeUtf8(str);var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j=offset;for(var i=0;i0){key=kvpairs[i].substring(0,pos);val=kvpairs[i].substring(pos+1)}else{key=kvpairs[i];val=null}if(!(key in rval)){rval[key]=[]}if(!(key in Object.prototype)&&val!==null){rval[key].push(unescape(val))}}return rval};var rval;if(typeof query==="undefined"){if(_queryVariables===null){if(typeof window!=="undefined"&&window.location&&window.location.search){_queryVariables=parse(window.location.search.substring(1))}else{_queryVariables={}}}rval=_queryVariables}else{rval=parse(query)}return rval};util.parseFragment=function(fragment){var fp=fragment;var fq="";var pos=fragment.indexOf("?");if(pos>0){fp=fragment.substring(0,pos);fq=fragment.substring(pos+1)}var path=fp.split("/");if(path.length>0&&path[0]===""){path.shift()}var query=fq===""?{}:util.getQueryVariables(fq);return{pathString:fp,queryString:fq,path:path,query:query}};util.makeRequest=function(reqString){var frag=util.parseFragment(reqString);var req={path:frag.pathString,query:frag.queryString,getPath:function(i){return typeof i==="undefined"?frag.path:frag.path[i]},getQuery:function(k,i){var rval;if(typeof k==="undefined"){rval=frag.query}else{rval=frag.query[k];if(rval&&typeof i!=="undefined"){rval=rval[i]}}return rval},getQueryLast:function(k,_default){var rval;var vals=req.getQuery(k);if(vals){rval=vals[vals.length-1]}else{rval=_default}return rval}};return req};util.makeLink=function(path,query,fragment){path=jQuery.isArray(path)?path.join("/"):path;var qstr=jQuery.param(query||{});fragment=fragment||"";return path+(qstr.length>0?"?"+qstr:"")+(fragment.length>0?"#"+fragment:"")};util.setPath=function(object,keys,value){if(typeof object==="object"&&object!==null){var i=0;var len=keys.length;while(i0){parts.push(part)}last=re.lastIndex;var code=match[0][1];switch(code){case"s":case"o":if(argi")}break;case"%":parts.push("%");break;default:parts.push("<%"+code+"?>")}}parts.push(format.substring(last));return parts.join("")};util.formatNumber=function(number,decimals,dec_point,thousands_sep){var n=number,c=isNaN(decimals=Math.abs(decimals))?2:decimals;var d=dec_point===undefined?",":dec_point;var t=thousands_sep===undefined?".":thousands_sep,s=n<0?"-":"";var i=parseInt(n=Math.abs(+n||0).toFixed(c),10)+"";var j=i.length>3?i.length%3:0;return s+(j?i.substr(0,j)+t:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"")};util.formatSize=function(size){if(size>=1073741824){size=util.formatNumber(size/1073741824,2,".","")+" GiB"}else if(size>=1048576){size=util.formatNumber(size/1048576,2,".","")+" MiB"}else if(size>=1024){size=util.formatNumber(size/1024,0)+" KiB"}else{size=util.formatNumber(size,0)+" bytes"}return size};util.bytesFromIP=function(ip){if(ip.indexOf(".")!==-1){return util.bytesFromIPv4(ip)}if(ip.indexOf(":")!==-1){return util.bytesFromIPv6(ip)}return null};util.bytesFromIPv4=function(ip){ip=ip.split(".");if(ip.length!==4){return null}var b=util.createBuffer();for(var i=0;izeroGroups[zeroMaxGroup].end-zeroGroups[zeroMaxGroup].start){zeroMaxGroup=zeroGroups.length-1}}}ip.push(hex)}if(zeroGroups.length>0){var group=zeroGroups[zeroMaxGroup];if(group.end-group.start>0){ip.splice(group.start,group.end-group.start+1,"");if(group.start===0){ip.unshift("")}if(group.end===7){ip.push("")}}}return ip.join(":")};util.estimateCores=function(options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};if("cores"in util&&!options.update){return callback(null,util.cores)}if(typeof navigator!=="undefined"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0){util.cores=navigator.hardwareConcurrency;return callback(null,util.cores)}if(typeof Worker==="undefined"){util.cores=1;return callback(null,util.cores)}if(typeof Blob==="undefined"){util.cores=2;return callback(null,util.cores)}var blobUrl=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){var st=Date.now();var et=st+4;while(Date.now()r2.st&&r1.str1.st&&r2.st2){throw new Error("Cannot read notBefore/notAfter validity times; more "+"than two times were provided in the certificate.")}if(validity.length<2){throw new Error("Cannot read notBefore/notAfter validity times; they "+"were not provided as either UTCTime or GeneralizedTime.")}cert.validity.notBefore=validity[0];cert.validity.notAfter=validity[1];cert.tbsCertificate=capture.tbsCertificate;if(computeHash){cert.md=null;if(cert.signatureOid in oids){var oid=oids[cert.signatureOid];switch(oid){case"sha1WithRSAEncryption":cert.md=forge.md.sha1.create();break;case"md5WithRSAEncryption":cert.md=forge.md.md5.create();break;case"sha256WithRSAEncryption":cert.md=forge.md.sha256.create();break;case"sha384WithRSAEncryption":cert.md=forge.md.sha384.create();break;case"sha512WithRSAEncryption":cert.md=forge.md.sha512.create();break;case"RSASSA-PSS":cert.md=forge.md.sha256.create();break}}if(cert.md===null){var error=new Error("Could not compute certificate digest. "+"Unknown signature OID.");error.signatureOid=cert.signatureOid;throw error}var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes())}var imd=forge.md.sha1.create();cert.issuer.getField=function(sn){return _getAttribute(cert.issuer,sn)};cert.issuer.addField=function(attr){_fillMissingFields([attr]);cert.issuer.attributes.push(attr)};cert.issuer.attributes=pki.RDNAttributesAsArray(capture.certIssuer,imd);if(capture.certIssuerUniqueId){cert.issuer.uniqueId=capture.certIssuerUniqueId}cert.issuer.hash=imd.digest().toHex();var smd=forge.md.sha1.create();cert.subject.getField=function(sn){return _getAttribute(cert.subject,sn)};cert.subject.addField=function(attr){_fillMissingFields([attr]);cert.subject.attributes.push(attr)};cert.subject.attributes=pki.RDNAttributesAsArray(capture.certSubject,smd);if(capture.certSubjectUniqueId){cert.subject.uniqueId=capture.certSubjectUniqueId}cert.subject.hash=smd.digest().toHex();if(capture.certExtensions){cert.extensions=pki.certificateExtensionsFromAsn1(capture.certExtensions)}else{cert.extensions=[]}cert.publicKey=pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);return cert};pki.certificateExtensionsFromAsn1=function(exts){var rval=[];for(var i=0;i1){b2=ev.value.charCodeAt(1);b3=ev.value.length>2?ev.value.charCodeAt(2):0}e.digitalSignature=(b2&128)===128;e.nonRepudiation=(b2&64)===64;e.keyEncipherment=(b2&32)===32;e.dataEncipherment=(b2&16)===16;e.keyAgreement=(b2&8)===8;e.keyCertSign=(b2&4)===4;e.cRLSign=(b2&2)===2;e.encipherOnly=(b2&1)===1;e.decipherOnly=(b3&128)===128}else if(e.name==="basicConstraints"){var ev=asn1.fromDer(e.value);if(ev.value.length>0&&ev.value[0].type===asn1.Type.BOOLEAN){e.cA=ev.value[0].value.charCodeAt(0)!==0}else{e.cA=false}var value=null;if(ev.value.length>0&&ev.value[0].type===asn1.Type.INTEGER){value=ev.value[0].value}else if(ev.value.length>1){value=ev.value[1].value}if(value!==null){e.pathLenConstraint=asn1.derToInteger(value)}}else if(e.name==="extKeyUsage"){var ev=asn1.fromDer(e.value);for(var vi=0;vi1){b2=ev.value.charCodeAt(1)}e.client=(b2&128)===128;e.server=(b2&64)===64;e.email=(b2&32)===32;e.objsign=(b2&16)===16;e.reserved=(b2&8)===8;e.sslCA=(b2&4)===4;e.emailCA=(b2&2)===2;e.objCA=(b2&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];var gn;var ev=asn1.fromDer(e.value);for(var n=0;n128){throw new Error('Invalid "nsComment" content.')}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.IA5STRING,false,e.comment)}else if(e.name==="subjectKeyIdentifier"&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex();e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ski.getBytes())}else if(e.name==="authorityKeyIdentifier"&&options.cert){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=e.keyIdentifier===true?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,false,keyIdentifier))}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,true,[_dnToAsn1(e.authorityCertIssuer===true?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,authorityCertIssuer))}if(e.serialNumber){var serialNumber=forge.util.hexToBytes(e.serialNumber===true?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,false,serialNumber))}}else if(e.name==="cRLDistributionPoints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;var subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);var altName;for(var n=0;n=jan_1_1950&&date0){tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions))}return tbs};pki.getCertificationRequestInfo=function(csr){var cri=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(csr.version).getBytes()),_dnToAsn1(csr.subject),pki.publicKeyToAsn1(csr.publicKey),_CRIAttributesToAsn1(csr)]);return cri};pki.distinguishedNameToAsn1=function(dn){return _dnToAsn1(dn)};pki.certificateToAsn1=function(cert){var tbsCertificate=cert.tbsCertificate||pki.getTBSCertificate(cert);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[tbsCertificate,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.signatureOid).getBytes()),_signatureParametersToAsn1(cert.signatureOid,cert.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.signature)])};pki.certificateExtensionsToAsn1=function(exts){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,3,true,[]);var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);rval.value.push(seq);for(var i=0;icert.validity.notAfter){error={message:"Certificate is not valid yet or has expired.",error:pki.certificateError.certificate_expired,notBefore:cert.validity.notBefore,notAfter:cert.validity.notAfter,now:validityCheckDate}}}if(error===null){parent=chain[0]||caStore.getIssuer(cert);if(parent===null){if(cert.isIssuer(cert)){selfSigned=true;parent=cert}}if(parent){var parents=parent;if(!forge.util.isArray(parents)){parents=[parents]}var verified=false;while(!verified&&parents.length>0){parent=parents.shift();try{verified=parent.verify(cert)}catch(ex){}}if(!verified){error={message:"Certificate signature is invalid.",error:pki.certificateError.bad_certificate}}}if(error===null&&(!parent||selfSigned)&&!caStore.hasCertificate(cert)){error={message:"Certificate is not trusted.",error:pki.certificateError.unknown_ca}}}if(error===null&&parent&&!cert.isIssuer(parent)){error={message:"Certificate issuer is invalid.",error:pki.certificateError.bad_certificate}}if(error===null){var se={keyUsage:true,basicConstraints:true};for(var i=0;error===null&&ibcExt.pathLenConstraint){error={message:"Certificate basicConstraints pathLenConstraint violated.",error:pki.certificateError.bad_certificate}}}}var vfd=error===null?true:error.error;var ret=options.verify?options.verify(vfd,depth,certs):vfd;if(ret===true){error=null}else{if(vfd===true){error={message:"The application rejected the certificate.",error:pki.certificateError.bad_certificate}}if(ret||ret===0){if(typeof ret==="object"&&!forge.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.error){error.error=ret.error}}else if(typeof ret==="string"){error.error=ret}}throw error}first=false;++depth}while(chain.length>0);return true}},{"./aes":7,"./asn1":9,"./des":14,"./forge":16,"./md":23,"./mgf":25,"./oids":27,"./pem":30,"./pss":38,"./rsa":41,"./util":48}],50:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}});return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":50,timers:51}],52:[function(require,module,exports){module.exports={name:"hybrid-crypto-js",version:"0.2.3",description:"Hybrid (RSA+AES) encryption and decryption toolkit for JavaScript",main:"lib/index.js",scripts:{prepublish:"npm run build",webpack:"browserify lib/webpack.js -o web/hybrid-crypto.js",uglify:"uglifyjs web/hybrid-crypto.js -o web/hybrid-crypto.min.js",flow:"flow",babel:"babel src/ -d lib/",build:"npm run babel && npm run webpack && npm run uglify",test:"npm run babel && mocha -R spec"},repository:{type:"git",url:"https://github.com/juhoen/hybrid-crypto-js.git"},keywords:["rsa","aes","rsa+aes","react","node","react-native"],author:"Juho Enala ",license:"MIT",bugs:{url:"https://github.com/juhoen/hybrid-crypto-js/issues"},homepage:"https://github.com/juhoen/hybrid-crypto-js",dependencies:{"node-forge":"^0.8.5"},devDependencies:{"@babel/cli":"^7.5.5","@babel/core":"^7.5.5","@babel/preset-env":"^7.5.5","@babel/preset-flow":"^7.0.0","babel-core":"^6.26.0","babel-preset-env":"1.6.0","babel-preset-es2015":"^6.24.1",babelify:"^8.0.0",browserify:"^16.5.0",chai:"^4.1.2","flow-bin":"^0.107.0",mocha:"^4.0.1",prettier:"^1.18.2","uglify-js":"^3.2.1"},browserslist:"> 0.25%, not dead"}},{}]},{},[5]); \ No newline at end of file +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,Crypt);this.options=_objectSpread({md:DEFAULT_MESSAGE_DIGEST,aesKeySize:DEFAULT_AES_KEY_SIZE,aesIvSize:DEFAULT_AES_IV_SIZE,aesStandard:AES_STANDARD,rsaStandard:RSA_STANDARD,entropy:undefined},options);if(this.options.entropy){this._entropy(this.options.entropy)}}_createClass(Crypt,[{key:"_getMessageDigest",value:function _getMessageDigest(messageDigest){switch(messageDigest){case"sha1":return forge.md.sha1.create();case"sha256":return forge.md.sha256.create();case"sha384":return forge.md.sha384.create();case"sha512":return forge.md.sha512.create();case"md5":return forge.md.md5.create();default:console.warn('Message digest "'.concat(this.options.md,'" not found. Using default message digest "sha1" instead'));return forge.md.sha1.create()}}},{key:"_parseSignature",value:function _parseSignature(_signature){try{return JSON.parse(_signature)}catch(e){return{signature:_signature,md:"sha1",v:helpers.version()}}}},{key:"fingerprint",value:function fingerprint(publicKey){return pki.getPublicKeyFingerprint(publicKey,{encoding:"hex",delimiter:":"})}},{key:"signature",value:function signature(privateKey,message){var checkSum=this._getMessageDigest(this.options.md);checkSum.update(message,"utf8");if(typeof privateKey==="string")privateKey=pki.privateKeyFromPem(privateKey);var signature=privateKey.sign(checkSum);var signature64=forge.util.encode64(signature);return JSON.stringify({signature:signature64,md:this.options.md})}},{key:"verify",value:function verify(publicKey,_signature,decrypted){if(!_signature)return false;var _this$_parseSignature=this._parseSignature(_signature),signature=_this$_parseSignature.signature,md=_this$_parseSignature.md;var checkSum=this._getMessageDigest(md);checkSum.update(decrypted,"utf8");signature=forge.util.decode64(signature);if(typeof publicKey==="string")publicKey=pki.publicKeyFromPem(publicKey);return publicKey.verify(checkSum.digest().getBytes(),signature)}},{key:"encrypt",value:function encrypt(publicKeys,message,signature){var _this=this;publicKeys=helpers.toArray(publicKeys);publicKeys=publicKeys.map(function(key){return typeof key==="string"?pki.publicKeyFromPem(key):key});var iv=forge.random.getBytesSync(this.options.aesIvSize);var key=forge.random.getBytesSync(this.options.aesKeySize/8);var encryptedKeys={};publicKeys.forEach(function(publicKey){var encryptedKey=publicKey.encrypt(key,_this.options.rsaStandard);var fingerprint=_this.fingerprint(publicKey);encryptedKeys[fingerprint]=forge.util.encode64(encryptedKey)});var buffer=forge.util.createBuffer(message,"utf8");var cipher=forge.cipher.createCipher(this.options.aesStandard,key);cipher.start({iv:iv});cipher.update(buffer);cipher.finish();var payload={};payload.v=helpers.version();payload.iv=forge.util.encode64(iv);payload.keys=encryptedKeys;payload.cipher=forge.util.encode64(cipher.output.data);payload.signature=signature;payload.tag=cipher.mode.tag&&forge.util.encode64(cipher.mode.tag.getBytes());return JSON.stringify(payload)}},{key:"decrypt",value:function decrypt(privateKey,encrypted){this._validate(encrypted);var payload=JSON.parse(encrypted);if(typeof privateKey==="string")privateKey=pki.privateKeyFromPem(privateKey);var fingerprint=this.fingerprint(privateKey);var encryptedKey=payload.keys[fingerprint];if(!encryptedKey)throw"RSA fingerprint doesn't match with any of the encrypted message's fingerprints";var keyBytes=forge.util.decode64(encryptedKey);var iv=forge.util.decode64(payload.iv);var cipher=forge.util.decode64(payload.cipher);var tag=payload.tag&&forge.util.decode64(payload.tag);var key=privateKey.decrypt(keyBytes,this.options.rsaStandard);var buffer=forge.util.createBuffer(cipher);var decipher=forge.cipher.createDecipher(this.options.aesStandard,key);decipher.start({iv:iv,tag:tag});decipher.update(buffer);decipher.finish();var bytes=decipher.output.getBytes();var decrypted=forge.util.decodeUtf8(bytes);var output={};output.message=decrypted;output.signature=payload.signature;return output}},{key:"_validate",value:function _validate(encrypted){var p=JSON.parse(encrypted);if(!(p.hasOwnProperty("v")&&p.hasOwnProperty("iv")&&p.hasOwnProperty("keys")&&p.hasOwnProperty("cipher")))throw"Encrypted message is not valid"}},{key:"_entropy",value:function _entropy(input){var inputString=String(input);var bytes=forge.util.encodeUtf8(inputString);forge.random.collect(bytes)}}]);return Crypt}();module.exports=Crypt},{"./constants":1,"./helpers":3,"node-forge":18}],3:[function(require,module,exports){"use strict";var pkg=require("../package.json");module.exports={version:function version(){return"".concat(pkg.name,"_").concat(pkg.version)},toArray:function toArray(obj){return Array.isArray(obj)?obj:[obj]}}},{"../package.json":52}],4:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,RSA);this.options=_objectSpread({keySize:4096,entropy:undefined},options);if(this.options.entropy){this._entropy(this.options.entropy)}}_createClass(RSA,[{key:"generateKeyPair",value:function generateKeyPair(callback,keySize){pki.rsa.generateKeyPair({bits:keySize||this.options.keySize,workers:-1},function(err,keyPair){keyPair.publicKey=pki.publicKeyToPem(keyPair.publicKey);keyPair.privateKey=pki.privateKeyToPem(keyPair.privateKey);callback(keyPair)})}},{key:"generateKeyPairAsync",value:function generateKeyPairAsync(keySize){var _this=this;return new Promise(function(resolve){_this.generateKeyPair(resolve,keySize)})}},{key:"_entropy",value:function _entropy(input){var inputString=String(input);var bytes=forge.util.encodeUtf8(inputString);forge.random.collect(bytes)}}]);return RSA}();module.exports=RSA},{"node-forge":18}],5:[function(require,module,exports){"use strict";var _crypt=_interopRequireDefault(require("./crypt"));var _rsa=_interopRequireDefault(require("./rsa"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}window.Crypt=_crypt.default;window.RSA=_rsa.default},{"./crypt":2,"./rsa":4}],6:[function(require,module,exports){},{}],7:[function(require,module,exports){var forge=require("./forge");require("./cipher");require("./cipherModes");require("./util");module.exports=forge.aes=forge.aes||{};forge.aes.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:false,mode:mode});cipher.start(iv);return cipher};forge.aes.createEncryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:false,mode:mode})};forge.aes.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:true,mode:mode});cipher.start(iv);return cipher};forge.aes.createDecryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:true,mode:mode})};forge.aes.Algorithm=function(name,mode){if(!init){initialize()}var self=this;self.name=name;self.mode=new mode({blockSize:16,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,true)}}});self._init=false};forge.aes.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=options.key;var tmp;if(typeof key==="string"&&(key.length===16||key.length===24||key.length===32)){key=forge.util.createBuffer(key)}else if(forge.util.isArray(key)&&(key.length===16||key.length===24||key.length===32)){tmp=key;key=forge.util.createBuffer();for(var i=0;i>>2;for(var i=0;i>8^sx&255^99;sbox[e]=sx;isbox[sx]=e;sx2=xtime[sx];e2=xtime[e];e4=xtime[e2];e8=xtime[e4];me=sx2<<24^sx<<16^sx<<8^(sx^sx2);ime=(e2^e4^e8)<<24^(e^e8)<<16^(e^e4^e8)<<8^(e^e2^e8);for(var n=0;n<4;++n){mix[n][e]=me;imix[n][sx]=ime;me=me<<24|me>>>8;ime=ime<<24|ime>>>8}if(e===0){e=ei=1}else{e=e2^xtime[xtime[xtime[e2^e8]]];ei^=xtime[xtime[ei]]}}}function _expandKey(key,decrypt){var w=key.slice(0);var temp,iNk=1;var Nk=w.length;var Nr1=Nk+6+1;var end=Nb*Nr1;for(var i=Nk;i>>16&255]<<24^sbox[temp>>>8&255]<<16^sbox[temp&255]<<8^sbox[temp>>>24]^rcon[iNk]<<24;iNk++}else if(Nk>6&&i%Nk===4){temp=sbox[temp>>>24]<<24^sbox[temp>>>16&255]<<16^sbox[temp>>>8&255]<<8^sbox[temp&255]}w[i]=w[i-Nk]^temp}if(decrypt){var tmp;var m0=imix[0];var m1=imix[1];var m2=imix[2];var m3=imix[3];var wnew=w.slice(0);end=w.length;for(var i=0,wi=end-Nb;i>>24]]^m1[sbox[tmp>>>16&255]]^m2[sbox[tmp>>>8&255]]^m3[sbox[tmp&255]]}}}w=wnew}return w}function _updateBlock(w,input,output,decrypt){var Nr=w.length/4-1;var m0,m1,m2,m3,sub;if(decrypt){m0=imix[0];m1=imix[1];m2=imix[2];m3=imix[3];sub=isbox}else{m0=mix[0];m1=mix[1];m2=mix[2];m3=mix[3];sub=sbox}var a,b,c,d,a2,b2,c2;a=input[0]^w[0];b=input[decrypt?3:1]^w[1];c=input[2]^w[2];d=input[decrypt?1:3]^w[3];var i=3;for(var round=1;round>>24]^m1[b>>>16&255]^m2[c>>>8&255]^m3[d&255]^w[++i];b2=m0[b>>>24]^m1[c>>>16&255]^m2[d>>>8&255]^m3[a&255]^w[++i];c2=m0[c>>>24]^m1[d>>>16&255]^m2[a>>>8&255]^m3[b&255]^w[++i];d=m0[d>>>24]^m1[a>>>16&255]^m2[b>>>8&255]^m3[c&255]^w[++i];a=a2;b=b2;c=c2}output[0]=sub[a>>>24]<<24^sub[b>>>16&255]<<16^sub[c>>>8&255]<<8^sub[d&255]^w[++i];output[decrypt?3:1]=sub[b>>>24]<<24^sub[c>>>16&255]<<16^sub[d>>>8&255]<<8^sub[a&255]^w[++i];output[2]=sub[c>>>24]<<24^sub[d>>>16&255]<<16^sub[a>>>8&255]<<8^sub[b&255]^w[++i];output[decrypt?1:3]=sub[d>>>24]<<24^sub[a>>>16&255]<<16^sub[b>>>8&255]<<8^sub[c&255]^w[++i]}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="AES-"+mode;var cipher;if(options.decrypt){cipher=forge.cipher.createDecipher(algorithm,options.key)}else{cipher=forge.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options){var output=null;if(options instanceof forge.util.ByteBuffer){output=options;options={}}options=options||{};options.output=output;options.iv=iv;start.call(cipher,options)};return cipher}},{"./cipher":11,"./cipherModes":12,"./forge":16,"./util":48}],8:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./tls");var tls=module.exports=forge.tls;tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"]={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes;sp.cipher_type=tls.CipherType.block;sp.enc_key_length=16;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState:initConnectionState};tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"]={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes;sp.cipher_type=tls.CipherType.block;sp.enc_key_length=32;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState:initConnectionState};function initConnectionState(state,c,sp){var client=c.entity===forge.tls.ConnectionEnd.client;state.read.cipherState={init:false,cipher:forge.cipher.createDecipher("AES-CBC",client?sp.keys.server_write_key:sp.keys.client_write_key),iv:client?sp.keys.server_write_IV:sp.keys.client_write_IV};state.write.cipherState={init:false,cipher:forge.cipher.createCipher("AES-CBC",client?sp.keys.client_write_key:sp.keys.server_write_key),iv:client?sp.keys.client_write_IV:sp.keys.server_write_IV};state.read.cipherFunction=decrypt_aes_cbc_sha1;state.write.cipherFunction=encrypt_aes_cbc_sha1;state.read.macLength=state.write.macLength=sp.mac_length;state.read.macFunction=state.write.macFunction=tls.hmac_sha1}function encrypt_aes_cbc_sha1(record,s){var rval=false;var mac=s.macFunction(s.macKey,s.sequenceNumber,record);record.fragment.putBytes(mac);s.updateSequenceNumber();var iv;if(record.version.minor===tls.Versions.TLS_1_0.minor){iv=s.cipherState.init?null:s.cipherState.iv}else{iv=forge.random.getBytesSync(16)}s.cipherState.init=true;var cipher=s.cipherState.cipher;cipher.start({iv:iv});if(record.version.minor>=tls.Versions.TLS_1_1.minor){cipher.output.putBytes(iv)}cipher.update(record.fragment);if(cipher.finish(encrypt_aes_cbc_sha1_padding)){record.fragment=cipher.output;record.length=record.fragment.length();rval=true}return rval}function encrypt_aes_cbc_sha1_padding(blockSize,input,decrypt){if(!decrypt){var padding=blockSize-input.length()%blockSize;input.fillWithByte(padding-1,padding)}return true}function decrypt_aes_cbc_sha1_padding(blockSize,output,decrypt){var rval=true;if(decrypt){var len=output.length();var paddingLength=output.last();for(var i=len-1-paddingLength;i=macLen){record.fragment=cipher.output.getBytes(len-macLen);mac=cipher.output.getBytes(macLen)}else{record.fragment=cipher.output.getBytes()}record.fragment=forge.util.createBuffer(record.fragment);record.length=record.fragment.length();var mac2=s.macFunction(s.macKey,s.sequenceNumber,record);s.updateSequenceNumber();rval=compareMacs(s.macKey,mac,mac2)&&rval;return rval}function compareMacs(key,mac1,mac2){var hmac=forge.hmac.create();hmac.start("SHA1",key);hmac.update(mac1);mac1=hmac.digest().getBytes();hmac.start(null,null);hmac.update(mac2);mac2=hmac.digest().getBytes();return mac1===mac2}},{"./aes":7,"./forge":16,"./tls":47}],9:[function(require,module,exports){var forge=require("./forge");require("./util");require("./oids");var asn1=module.exports=forge.asn1=forge.asn1||{};asn1.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};asn1.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};asn1.create=function(tagClass,type,constructed,value,options){if(forge.util.isArray(value)){var tmp=[];for(var i=0;iremaining){var error=new Error("Too few bytes to parse DER.");error.available=bytes.length();error.remaining=remaining;error.requested=n;throw error}}var _getValueLength=function(bytes,remaining){var b2=bytes.getByte();remaining--;if(b2===128){return undefined}var length;var longForm=b2&128;if(!longForm){length=b2}else{var longFormBytes=b2&127;_checkBufferLength(bytes,remaining,longFormBytes);length=bytes.getInt(longFormBytes<<3)}if(length<0){throw new Error("Negative length: "+length)}return length};asn1.fromDer=function(bytes,options){if(options===undefined){options={strict:true,decodeBitStrings:true}}if(typeof options==="boolean"){options={strict:options,decodeBitStrings:true}}if(!("strict"in options)){options.strict=true}if(!("decodeBitStrings"in options)){options.decodeBitStrings=true}if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}return _fromDer(bytes,bytes.length(),0,options)};function _fromDer(bytes,remaining,depth,options){var start;_checkBufferLength(bytes,remaining,2);var b1=bytes.getByte();remaining--;var tagClass=b1&192;var type=b1&31;start=bytes.length();var length=_getValueLength(bytes,remaining);remaining-=start-bytes.length();if(length!==undefined&&length>remaining){if(options.strict){var error=new Error("Too few bytes to read ASN.1 value.");error.available=bytes.length();error.remaining=remaining;error.requested=length;throw error}length=remaining}var value;var bitStringContents;var constructed=(b1&32)===32;if(constructed){value=[];if(length===undefined){for(;;){_checkBufferLength(bytes,remaining,2);if(bytes.bytes(2)===String.fromCharCode(0,0)){bytes.getBytes(2);remaining-=2;break}start=bytes.length();value.push(_fromDer(bytes,remaining,depth+1,options));remaining-=start-bytes.length()}}else{while(length>0){start=bytes.length();value.push(_fromDer(bytes,length,depth+1,options));remaining-=start-bytes.length();length-=start-bytes.length()}}}if(value===undefined&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING){bitStringContents=bytes.bytes(length)}if(value===undefined&&options.decodeBitStrings&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING&&length>1){var savedRead=bytes.read;var savedRemaining=remaining;var unused=0;if(type===asn1.Type.BITSTRING){_checkBufferLength(bytes,remaining,1);unused=bytes.getByte();remaining--}if(unused===0){try{start=bytes.length();var subOptions={verbose:options.verbose,strict:true,decodeBitStrings:true};var composed=_fromDer(bytes,remaining,depth+1,subOptions);var used=start-bytes.length();remaining-=used;if(type==asn1.Type.BITSTRING){used++}var tc=composed.tagClass;if(used===length&&(tc===asn1.Class.UNIVERSAL||tc===asn1.Class.CONTEXT_SPECIFIC)){value=[composed]}}catch(ex){}}if(value===undefined){bytes.read=savedRead;remaining=savedRemaining}}if(value===undefined){if(length===undefined){if(options.strict){throw new Error("Non-constructed ASN.1 object of indefinite length.")}length=remaining}if(type===asn1.Type.BMPSTRING){value="";for(;length>0;length-=2){_checkBufferLength(bytes,remaining,2);value+=String.fromCharCode(bytes.getInt16());remaining-=2}}else{value=bytes.getBytes(length)}}var asn1Options=bitStringContents===undefined?null:{bitStringContents:bitStringContents};return asn1.create(tagClass,type,constructed,value,asn1Options)}asn1.toDer=function(obj){var bytes=forge.util.createBuffer();var b1=obj.tagClass|obj.type;var value=forge.util.createBuffer();var useBitStringContents=false;if("bitStringContents"in obj){useBitStringContents=true;if(obj.original){useBitStringContents=asn1.equals(obj,obj.original)}}if(useBitStringContents){value.putBytes(obj.bitStringContents)}else if(obj.composed){if(obj.constructed){b1|=32}else{value.putByte(0)}for(var i=0;i1&&(obj.value.charCodeAt(0)===0&&(obj.value.charCodeAt(1)&128)===0||obj.value.charCodeAt(0)===255&&(obj.value.charCodeAt(1)&128)===128)){value.putBytes(obj.value.substr(1))}else{value.putBytes(obj.value)}}}bytes.putByte(b1);if(value.length()<=127){bytes.putByte(value.length()&127)}else{var len=value.length();var lenBytes="";do{lenBytes+=String.fromCharCode(len&255);len=len>>>8}while(len>0);bytes.putByte(lenBytes.length|128);for(var i=lenBytes.length-1;i>=0;--i){bytes.putByte(lenBytes.charCodeAt(i))}}bytes.putBuffer(value);return bytes};asn1.oidToDer=function(oid){var values=oid.split(".");var bytes=forge.util.createBuffer();bytes.putByte(40*parseInt(values[0],10)+parseInt(values[1],10));var last,valueBytes,value,b;for(var i=2;i>>7;if(!last){b|=128}valueBytes.push(b);last=false}while(value>0);for(var n=valueBytes.length-1;n>=0;--n){bytes.putByte(valueBytes[n])}}return bytes};asn1.derToOid=function(bytes){var oid;if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}var b=bytes.getByte();oid=Math.floor(b/40)+"."+b%40;var value=0;while(bytes.length()>0){b=bytes.getByte();value=value<<7;if(b&128){value+=b&127}else{oid+="."+(value+b);value=0}}return oid};asn1.utcTimeToDate=function(utc){var date=new Date;var year=parseInt(utc.substr(0,2),10);year=year>=50?1900+year:2e3+year;var MM=parseInt(utc.substr(2,2),10)-1;var DD=parseInt(utc.substr(4,2),10);var hh=parseInt(utc.substr(6,2),10);var mm=parseInt(utc.substr(8,2),10);var ss=0;if(utc.length>11){var c=utc.charAt(10);var end=10;if(c!=="+"&&c!=="-"){ss=parseInt(utc.substr(10,2),10);end+=2}}date.setUTCFullYear(year,MM,DD);date.setUTCHours(hh,mm,ss,0);if(end){c=utc.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(utc.substr(end+1,2),10);var mmoffset=parseInt(utc.substr(end+4,2),10);var offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){date.setTime(+date-offset)}else{date.setTime(+date+offset)}}}return date};asn1.generalizedTimeToDate=function(gentime){var date=new Date;var YYYY=parseInt(gentime.substr(0,4),10);var MM=parseInt(gentime.substr(4,2),10)-1;var DD=parseInt(gentime.substr(6,2),10);var hh=parseInt(gentime.substr(8,2),10);var mm=parseInt(gentime.substr(10,2),10);var ss=parseInt(gentime.substr(12,2),10);var fff=0;var offset=0;var isUTC=false;if(gentime.charAt(gentime.length-1)==="Z"){isUTC=true}var end=gentime.length-5,c=gentime.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(gentime.substr(end+1,2),10);var mmoffset=parseInt(gentime.substr(end+4,2),10);offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){offset*=-1}isUTC=true}if(gentime.charAt(14)==="."){fff=parseFloat(gentime.substr(14),10)*1e3}if(isUTC){date.setUTCFullYear(YYYY,MM,DD);date.setUTCHours(hh,mm,ss,fff);date.setTime(+date+offset)}else{date.setFullYear(YYYY,MM,DD);date.setHours(hh,mm,ss,fff)}return date};asn1.dateToUtcTime=function(date){if(typeof date==="string"){return date}var rval="";var format=[];format.push((""+date.getUTCFullYear()).substr(2));format.push(""+(date.getUTCMonth()+1));format.push(""+date.getUTCDate());format.push(""+date.getUTCHours());format.push(""+date.getUTCMinutes());format.push(""+date.getUTCSeconds());for(var i=0;i=-128&&x<128){return rval.putSignedInt(x,8)}if(x>=-32768&&x<32768){return rval.putSignedInt(x,16)}if(x>=-8388608&&x<8388608){return rval.putSignedInt(x,24)}if(x>=-2147483648&&x<2147483648){return rval.putSignedInt(x,32)}var error=new Error("Integer too large; max is 32-bits.");error.integer=x;throw error};asn1.derToInteger=function(bytes){if(typeof bytes==="string"){bytes=forge.util.createBuffer(bytes)}var n=bytes.length()*8;if(n>32){throw new Error("Integer too large; max is 32-bits.")}return bytes.getSignedInt(n)};asn1.validate=function(obj,v,capture,errors){var rval=false;if((obj.tagClass===v.tagClass||typeof v.tagClass==="undefined")&&(obj.type===v.type||typeof v.type==="undefined")){if(obj.constructed===v.constructed||typeof v.constructed==="undefined"){rval=true;if(v.value&&forge.util.isArray(v.value)){var j=0;for(var i=0;rval&&i0){rval+="\n"}var indent="";for(var i=0;i1){rval+="0x"+forge.util.bytesToHex(obj.value.slice(1))}else{rval+="(none)"}if(obj.value.length>0){var unused=obj.value.charCodeAt(0);if(unused==1){rval+=" (1 unused bit shown)"}else if(unused>1){rval+=" ("+unused+" unused bits shown)"}}}else if(obj.type===asn1.Type.OCTETSTRING){if(!_nonLatinRegex.test(obj.value)){rval+="("+obj.value+") "}rval+="0x"+forge.util.bytesToHex(obj.value)}else if(obj.type===asn1.Type.UTF8){rval+=forge.util.decodeUtf8(obj.value)}else if(obj.type===asn1.Type.PRINTABLESTRING||obj.type===asn1.Type.IA5String){rval+=obj.value}else if(_nonLatinRegex.test(obj.value)){rval+="0x"+forge.util.bytesToHex(obj.value)}else if(obj.value.length===0){rval+="[null]"}else{rval+=obj.value}}return rval}},{"./forge":16,"./oids":27,"./util":48}],10:[function(require,module,exports){(function(Buffer){var api={};module.exports=api;var _reverseAlphabets={};api.encode=function(input,alphabet,maxline){if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}if(maxline!==undefined&&typeof maxline!=="number"){throw new TypeError('"maxline" must be a number.')}var output="";if(!(input instanceof Uint8Array)){output=_encodeWithByteBuffer(input,alphabet)}else{var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i0){digits.push(carry%base);carry=carry/base|0}}for(i=0;input[i]===0&&i=0;--i){output+=alphabet[digits[i]]}}if(maxline){var regex=new RegExp(".{1,"+maxline+"}","g");output=output.match(regex).join("\r\n")}return output};api.decode=function(input,alphabet){if(typeof input!=="string"){throw new TypeError('"input" must be a string.')}if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}var table=_reverseAlphabets[alphabet];if(!table){table=_reverseAlphabets[alphabet]=[];for(var i=0;i>=8}while(carry>0){bytes.push(carry&255);carry>>=8}}for(var k=0;input[k]===first&&k0){digits.push(carry%base);carry=carry/base|0}}var output="";for(i=0;input.at(i)===0&&i=0;--i){output+=alphabet[digits[i]]}return output}}).call(this,require("buffer").Buffer)},{buffer:6}],11:[function(require,module,exports){var forge=require("./forge");require("./util");module.exports=forge.cipher=forge.cipher||{};forge.cipher.algorithms=forge.cipher.algorithms||{};forge.cipher.createCipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:false})};forge.cipher.createDecipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:true})};forge.cipher.registerAlgorithm=function(name,algorithm){name=name.toUpperCase();forge.cipher.algorithms[name]=algorithm};forge.cipher.getAlgorithm=function(name){name=name.toUpperCase();if(name in forge.cipher.algorithms){return forge.cipher.algorithms[name]}return null};var BlockCipher=forge.cipher.BlockCipher=function(options){this.algorithm=options.algorithm;this.mode=this.algorithm.mode;this.blockSize=this.mode.blockSize;this._finish=false;this._input=null;this.output=null;this._op=options.decrypt?this.mode.decrypt:this.mode.encrypt;this._decrypt=options.decrypt;this.algorithm.initialize(options)};BlockCipher.prototype.start=function(options){options=options||{};var opts={};for(var key in options){opts[key]=options[key]}opts.decrypt=this._decrypt;this._finish=false;this._input=forge.util.createBuffer();this.output=options.output||forge.util.createBuffer();this.mode.start(opts)};BlockCipher.prototype.update=function(input){if(input){this._input.putBuffer(input)}while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish){}this._input.compact()};BlockCipher.prototype.finish=function(pad){if(pad&&(this.mode.name==="ECB"||this.mode.name==="CBC")){this.mode.pad=function(input){return pad(this.blockSize,input,false)};this.mode.unpad=function(output){return pad(this.blockSize,output,true)}}var options={};options.decrypt=this._decrypt;options.overflow=this._input.length()%this.blockSize;if(!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,options)){return false}}this._finish=true;this.update();if(this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,options)){return false}}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,options)){return false}}return true}},{"./forge":16,"./util":48}],12:[function(require,module,exports){var forge=require("./forge");require("./util");forge.cipher=forge.cipher||{};var modes=module.exports=forge.cipher.modes=forge.cipher.modes||{};modes.ecb=function(options){options=options||{};this.name="ECB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints)};modes.ecb.prototype.start=function(options){};modes.ecb.prototype.encrypt=function(input,output,finish){if(input.length()0)){return true}for(var i=0;i0)){return true}for(var i=0;i0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};modes.cbc=function(options){options=options||{};this.name="CBC";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints)};modes.cbc.prototype.start=function(options){if(options.iv===null){if(!this._prev){throw new Error("Invalid IV parameter.")}this._iv=this._prev.slice(0)}else if(!("iv"in options)){throw new Error("Invalid IV parameter.")}else{this._iv=transformIV(options.iv);this._prev=this._iv.slice(0)}};modes.cbc.prototype.encrypt=function(input,output,finish){if(input.length()0)){return true}for(var i=0;i0)){return true}for(var i=0;i0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};modes.cfb=function(options){options=options||{};this.name="CFB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.cfb.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.cfb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.cfb.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.ofb=function(options){options=options||{};this.name="OFB";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.ofb.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.ofb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(input.length()===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}else{for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.ofb.prototype.decrypt=modes.ofb.prototype.encrypt;modes.ctr=function(options){options=options||{};this.name="CTR";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=null;this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0};modes.ctr.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}this._iv=transformIV(options.iv);this._inBlock=this._iv.slice(0);this._partialBytes=0};modes.ctr.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){input.read-=this.blockSize}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0}inc32(this._inBlock)};modes.ctr.prototype.decrypt=modes.ctr.prototype.encrypt;modes.gcm=function(options){options=options||{};this.name="GCM";this.cipher=options.cipher;this.blockSize=options.blockSize||16;this._ints=this.blockSize/4;this._inBlock=new Array(this._ints);this._outBlock=new Array(this._ints);this._partialOutput=forge.util.createBuffer();this._partialBytes=0;this._R=3774873600};modes.gcm.prototype.start=function(options){if(!("iv"in options)){throw new Error("Invalid IV parameter.")}var iv=forge.util.createBuffer(options.iv);this._cipherLength=0;var additionalData;if("additionalData"in options){additionalData=forge.util.createBuffer(options.additionalData)}else{additionalData=forge.util.createBuffer()}if("tagLength"in options){this._tagLength=options.tagLength}else{this._tagLength=128}this._tag=null;if(options.decrypt){this._tag=forge.util.createBuffer(options.tag).getBytes();if(this._tag.length!==this._tagLength/8){throw new Error("Authentication tag does not match tag length.")}}this._hashBlock=new Array(this._ints);this.tag=null;this._hashSubkey=new Array(this._ints);this.cipher.encrypt([0,0,0,0],this._hashSubkey);this.componentBits=4;this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var ivLength=iv.length();if(ivLength===12){this._j0=[iv.getInt32(),iv.getInt32(),iv.getInt32(),1]}else{this._j0=[0,0,0,0];while(iv.length()>0){this._j0=this.ghash(this._hashSubkey,this._j0,[iv.getInt32(),iv.getInt32(),iv.getInt32(),iv.getInt32()])}this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(from64To32(ivLength*8)))}this._inBlock=this._j0.slice(0);inc32(this._inBlock);this._partialBytes=0;additionalData=forge.util.createBuffer(additionalData);this._aDataLength=from64To32(additionalData.length()*8);var overflow=additionalData.length()%this.blockSize;if(overflow){additionalData.fillWithByte(0,this.blockSize-overflow)}this._s=[0,0,0,0];while(additionalData.length()>0){this._s=this.ghash(this._hashSubkey,this._s,[additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32()])}};modes.gcm.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){input.read-=this.blockSize;output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock);inc32(this._inBlock)};modes.gcm.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength0)){return true}this.cipher.encrypt(this._inBlock,this._outBlock);inc32(this._inBlock);this._hashBlock[0]=input.getInt32();this._hashBlock[1]=input.getInt32();this._hashBlock[2]=input.getInt32();this._hashBlock[3]=input.getInt32();this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--i){out[i]=x[i]>>>1|(x[i-1]&1)<<31}out[0]=x[0]>>>1;if(lsb){out[0]^=this._R}};modes.gcm.prototype.tableMultiply=function(x){var z=[0,0,0,0];for(var i=0;i<32;++i){var idx=i/8|0;var x_i=x[idx]>>>(7-i%8)*4&15;var ah=this._m[i][x_i];z[0]^=ah[0];z[1]^=ah[1];z[2]^=ah[2];z[3]^=ah[3]}return z};modes.gcm.prototype.ghash=function(h,y,x){y[0]^=x[0];y[1]^=x[1];y[2]^=x[2];y[3]^=x[3];return this.tableMultiply(y)};modes.gcm.prototype.generateHashTable=function(h,bits){var multiplier=8/bits;var perInt=4*multiplier;var size=16*multiplier;var m=new Array(size);for(var i=0;i>>1;var m=new Array(size);m[half]=mid.slice(0);var i=half>>>1;while(i>0){this.pow(m[2*i],m[i]=[]);i>>=1}i=2;while(i4){var tmp=iv;iv=forge.util.createBuffer();for(var i=0;i8?3:1;var keys=[];var shifts=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];var n=0,tmp;for(var j=0;j>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>2^right)&858993459;right^=tmp;left^=tmp<<2;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=left<<8|right>>>20&240;left=right<<24|right<<8&16711680|right>>>8&65280|right>>>24&240;right=tmp;for(var i=0;i>>26;right=right<<2|right>>>26}else{left=left<<1|left>>>27;right=right<<1|right>>>27}left&=-15;right&=-15;var lefttmp=pc2bytes0[left>>>28]|pc2bytes1[left>>>24&15]|pc2bytes2[left>>>20&15]|pc2bytes3[left>>>16&15]|pc2bytes4[left>>>12&15]|pc2bytes5[left>>>8&15]|pc2bytes6[left>>>4&15];var righttmp=pc2bytes7[right>>>28]|pc2bytes8[right>>>24&15]|pc2bytes9[right>>>20&15]|pc2bytes10[right>>>16&15]|pc2bytes11[right>>>12&15]|pc2bytes12[right>>>8&15]|pc2bytes13[right>>>4&15];tmp=(righttmp>>>16^lefttmp)&65535;keys[n++]=lefttmp^tmp;keys[n++]=righttmp^tmp<<16}}return keys}function _updateBlock(keys,input,output,decrypt){var iterations=keys.length===32?3:9;var looping;if(iterations===3){looping=decrypt?[30,-2,-2]:[0,32,2]}else{looping=decrypt?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2]}var tmp;var left=input[0];var right=input[1];tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;left=left<<1|left>>>31;right=right<<1|right>>>31;for(var j=0;j>>4|right<<28)^keys[i+1];tmp=left;left=right;right=tmp^(spfunction2[right1>>>24&63]|spfunction4[right1>>>16&63]|spfunction6[right1>>>8&63]|spfunction8[right1&63]|spfunction1[right2>>>24&63]|spfunction3[right2>>>16&63]|spfunction5[right2>>>8&63]|spfunction7[right2&63])}tmp=left;left=right;right=tmp}left=left>>>1|left<<31;right=right>>>1|right<<31;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;output[0]=left;output[1]=right}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="DES-"+mode;var cipher;if(options.decrypt){cipher=forge.cipher.createDecipher(algorithm,options.key)}else{cipher=forge.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options){var output=null;if(options instanceof forge.util.ByteBuffer){output=options;options={}}options=options||{};options.output=output;options.iv=iv;start.call(cipher,options)};return cipher}},{"./cipher":11,"./cipherModes":12,"./forge":16,"./util":48}],15:[function(require,module,exports){(function(Buffer){var forge=require("./forge");require("./jsbn");require("./random");require("./sha512");require("./util");if(typeof BigInteger==="undefined"){var BigInteger=forge.jsbn.BigInteger}var ByteBuffer=forge.util.ByteBuffer;var NativeBuffer=typeof Buffer==="undefined"?Uint8Array:Buffer;forge.pki=forge.pki||{};module.exports=forge.pki.ed25519=forge.ed25519=forge.ed25519||{};var ed25519=forge.ed25519;ed25519.constants={};ed25519.constants.PUBLIC_KEY_BYTE_LENGTH=32;ed25519.constants.PRIVATE_KEY_BYTE_LENGTH=64;ed25519.constants.SEED_BYTE_LENGTH=32;ed25519.constants.SIGN_BYTE_LENGTH=64;ed25519.constants.HASH_BYTE_LENGTH=64;ed25519.generateKeyPair=function(options){options=options||{};var seed=options.seed;if(seed===undefined){seed=forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH)}else if(typeof seed==="string"){if(seed.length!==ed25519.constants.SEED_BYTE_LENGTH){throw new TypeError('"seed" must be '+ed25519.constants.SEED_BYTE_LENGTH+" bytes in length.")}}else if(!(seed instanceof Uint8Array)){throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.')}seed=messageToNativeBuffer({message:seed,encoding:"binary"});var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);var sk=new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i){sk[i]=seed[i]}crypto_sign_keypair(pk,sk);return{publicKey:pk,privateKey:sk}};ed25519.publicKeyFromPrivateKey=function(options){options=options||{};var privateKey=messageToNativeBuffer({message:options.privateKey,encoding:"binary"});if(privateKey.length!==ed25519.constants.PRIVATE_KEY_BYTE_LENGTH){throw new TypeError('"options.privateKey" must have a byte length of '+ed25519.constants.PRIVATE_KEY_BYTE_LENGTH)}var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);for(var i=0;i=0};function messageToNativeBuffer(options){var message=options.message;if(message instanceof Uint8Array){return message}var encoding=options.encoding;if(message===undefined){if(options.md){message=options.md.digest().getBytes();encoding="binary"}else{throw new TypeError('"options.message" or "options.md" not specified.')}}if(typeof message==="string"&&!encoding){throw new TypeError('"options.encoding" must be "binary" or "utf8".')}if(typeof message==="string"){if(typeof Buffer!=="undefined"){return Buffer.from(message,encoding)}message=new ByteBuffer(message,encoding)}else if(!(message instanceof ByteBuffer)){throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge '+'ByteBuffer, or a string with "options.encoding" specifying its '+"encoding.")}var buffer=new NativeBuffer(message.length());for(var i=0;i=32;--i){carry=0;for(j=i-32,k=i-12;j>8;x[j]-=carry*256}x[j]+=carry;x[i]=0}carry=0;for(j=0;j<32;++j){x[j]+=carry-(x[31]>>4)*L[j];carry=x[j]>>8;x[j]&=255}for(j=0;j<32;++j){x[j]-=carry*L[j]}for(i=0;i<32;++i){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64);for(var i=0;i<64;++i){x[i]=r[i];r[i]=0}modL(r,x)}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h=gf(),t=gf();Z(a,p[1],p[0]);Z(t,q[1],q[0]);M(a,a,t);A(b,p[0],p[1]);A(t,q[0],q[1]);M(b,b,t);M(c,p[3],q[3]);M(c,c,D2);M(d,p[2],q[2]);A(d,d,d);Z(e,b,a);Z(f,d,c);A(g,d,c);A(h,b,a);M(p[0],e,f);M(p[1],h,g);M(p[2],g,f);M(p[3],e,h)}function cswap(p,q,b){for(var i=0;i<4;++i){sel25519(p[i],q[i],b)}}function pack(r,p){var tx=gf(),ty=gf(),zi=gf();inv25519(zi,p[2]);M(tx,p[0],zi);M(ty,p[1],zi);pack25519(r,ty);r[31]^=par25519(tx)<<7}function pack25519(o,n){var i,j,b;var m=gf(),t=gf();for(i=0;i<16;++i){t[i]=n[i]}car25519(t);car25519(t);car25519(t);for(j=0;j<2;++j){m[0]=t[0]-65517;for(i=1;i<15;++i){m[i]=t[i]-65535-(m[i-1]>>16&1);m[i-1]&=65535}m[15]=t[15]-32767-(m[14]>>16&1);b=m[15]>>16&1;m[14]&=65535;sel25519(t,m,1-b)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function unpackneg(r,p){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p);S(num,r[1]);M(den,num,D);Z(num,num,r[2]);A(den,r[2],den);S(den2,den);S(den4,den2);M(den6,den4,den2);M(t,den6,num);M(t,t,den);pow2523(t,t);M(t,t,num);M(t,t,den);M(t,t,den);M(r[0],t,den);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num)){M(r[0],r[0],I)}S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num)){return-1}if(par25519(r[0])===p[31]>>7){Z(r[0],gf0,r[0])}M(r[3],r[0],r[1]);return 0}function unpack25519(o,n){var i;for(i=0;i<16;++i){o[i]=n[2*i]+(n[2*i+1]<<8)}o[15]&=32767}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=250;a>=0;--a){S(c,c);if(a!==1){M(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function neq25519(a,b){var c=new NativeBuffer(32);var d=new NativeBuffer(32);pack25519(c,a);pack25519(d,b);return crypto_verify_32(c,0,d,0)}function crypto_verify_32(x,xi,y,yi){return vn(x,xi,y,yi,32)}function vn(x,xi,y,yi,n){var i,d=0;for(i=0;i>>8)-1}function par25519(a){var d=new NativeBuffer(32);pack25519(d,a);return d[0]&1}function scalarmult(p,q,s){var b,i;set25519(p[0],gf0);set25519(p[1],gf1);set25519(p[2],gf1);set25519(p[3],gf0);for(i=255;i>=0;--i){b=s[i/8|0]>>(i&7)&1;cswap(p,q,b);add(q,p);add(p,p);cswap(p,q,b)}}function scalarbase(p,s){var q=[gf(),gf(),gf(),gf()];set25519(q[0],X);set25519(q[1],Y);set25519(q[2],gf1);M(q[3],X,Y);scalarmult(p,q,s)}function set25519(r,a){var i;for(i=0;i<16;i++){r[i]=a[i]|0}}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=253;a>=0;--a){S(c,c);if(a!==2&&a!==4){M(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function car25519(o){var i,v,c=1;for(i=0;i<16;++i){v=o[i]+c+65535;c=Math.floor(v/65536);o[i]=v-c*65536}o[0]+=c-1+37*(c-1)}function sel25519(p,q,b){var t,c=~(b-1);for(var i=0;i<16;++i){t=c&(p[i]^q[i]);p[i]^=t;q[i]^=t}}function gf(init){var i,r=new Float64Array(16);if(init){for(i=0;i_md.blockLength){_md.start();_md.update(key.bytes());key=_md.digest()}_ipadding=forge.util.createBuffer();_opadding=forge.util.createBuffer();keylen=key.length();for(var i=0;i=0){var v=x*this.data[i++]+w.data[j]+c;c=Math.floor(v/67108864);w.data[j++]=v&67108863}return c}function am2(i,x,w,j,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this.data[i]&32767;var h=this.data[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&32767)<<15)+w.data[j]+(c&1073741823);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w.data[j++]=l&1073741823}return c}function am3(i,x,w,j,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this.data[i]&16383;var h=this.data[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&16383)<<14)+w.data[j]+c;c=(l>>28)+(m>>14)+xh*h;w.data[j++]=l&268435455}return c}if(typeof navigator==="undefined"){BigInteger.prototype.am=am3;dbits=28}else if(j_lm&&navigator.appName=="Microsoft Internet Explorer"){BigInteger.prototype.am=am2;dbits=30}else if(j_lm&&navigator.appName!="Netscape"){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<=0;--i)r.data[i]=this.data[i];r.t=this.t;r.s=this.s}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this.data[0]=x;else if(x<-1)this.data[0]=x+this.DV;else this.t=0}function nbv(i){var r=nbi();r.fromInt(i);return r}function bnpFromString(s,b){var k;if(b==16)k=4;else if(b==8)k=3;else if(b==256)k=8;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]&255:intAt(s,i);if(x<0){if(s.charAt(i)=="-")mi=true;continue}mi=false;if(sh==0)this.data[this.t++]=x;else if(sh+k>this.DB){this.data[this.t-1]|=(x&(1<>this.DB-sh}else this.data[this.t-1]|=x<=this.DB)sh-=this.DB}if(k==8&&(s[0]&128)!=0){this.s=-1;if(sh>0)this.data[this.t-1]|=(1<0&&this.data[this.t-1]==c)--this.t}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<0){if(p>p)>0){m=true;r=int2char(d)}while(i>=0){if(p>(p+=this.DB-k)}else{d=this.data[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"}function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}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.data[i]-a.data[i])!=0)return r;return 0}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}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r.data[i+n]=this.data[i];for(i=n-1;i>=0;--i)r.data[i]=0;r.t=this.t+n;r.s=this.s}function bnpDRShiftTo(n,r){for(var i=n;i=0;--i){r.data[i+ds+1]=this.data[i]>>cbs|c;c=(this.data[i]&bm)<=0;--i)r.data[i]=0;r.data[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp()}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;for(var i=ds+1;i>bs}if(bs>0)r.data[this.t-ds-1]|=(this.s&bm)<>=this.DB}if(a.t>=this.DB}c+=this.s}else{c+=this.s;while(i>=this.DB}c-=a.s}r.s=c<0?-1:0;if(c<-1)r.data[i++]=this.DV+c;else if(c>0)r.data[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r.data[i]=0;for(i=0;i=0)r.data[i]=0;for(i=0;i=x.DV){r.data[i+x.t]-=x.DV;r.data[i+x.t+1]=1}}if(r.t>0)r.data[r.t-1]+=x.am(i,x.data[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m,q,r){var pm=m.abs();if(pm.t<=0)return;var pt=this.abs();if(pt.t0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r)}else{pm.copyTo(y);pt.copyTo(r)}var ys=y.t;var y0=y.data[ys-1];if(y0==0)return;var yt=y0*(1<1?y.data[ys-2]>>this.F2:0);var d1=this.FV/yt,d2=(1<=0){r.data[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t=0){var qd=r.data[--i]==y0?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);if((r.data[i]+=y.am(0,qd,r,j,0,ys))0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r)}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}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;function bnpInvDigit(){if(this.t<1)return 0;var x=this.data[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<0)this.m.subTo(r,r);return r}function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x.data[x.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&x.DM;j=i+this.m.t;x.data[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x.data[j]>=x.DV){x.data[j]-=x.DV;x.data[++j]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(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;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,z){if(e>4294967295||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<0)z.mulTo(r2,g,r);else{var t=r;r=r2;r2=t}}return z.revert(r)}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)}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;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;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}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}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=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)}function bnpFromNumber(a,b,c){if("number"==typeof b){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=(1<0){if(p>p)!=(this.s&this.DM)>>p)r[k++]=d|this.s<=0){if(p<8){d=(this.data[i]&(1<>(p+=this.DB-8)}else{d=this.data[i]>>(p-=8)&255;if(p<=0){p+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k==0&&(this.s&128)!=(d&128))++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}function bnpBitwiseTo(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i=this.t)return this.s!=0;return(this.data[j]&1<>=this.DB}if(a.t>=this.DB}c+=this.s}else{c+=this.s;while(i>=this.DB}c+=a.s}r.s=c<0?-1:0;if(c>0)r.data[i++]=c;else if(c<-1)r.data[i++]=this.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=nbi();this.addTo(a,r);return r}function bnSubtract(a){var r=nbi();this.subTo(a,r);return r}function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r}function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q=nbi(),r=nbi();this.divRemTo(a,q,r);return new Array(q,r)}function bnpDMultiply(n){this.data[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w){if(n==0)return;while(this.t<=w)this.data[this.t++]=0;this.data[w]+=n;while(this.data[w]>=this.DV){this.data[w]-=this.DV;if(++w>=this.t)this.data[this.t++]=0;++this.data[w]}}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;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r.data[--i]=0;var j;for(j=r.t-this.t;i=0)r.data[i]=0;for(i=Math.max(n-this.t,0);i2*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}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)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(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;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);var g=new Array,n=3,k1=k-1,km=(1<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.data[j])-1;while(j>=0){if(i>=k1)w=e.data[j]>>i-k1&km;else{w=(e.data[j]&(1<0)w|=e.data[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){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.data[j]&1<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}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.data[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this.data[i])%n;return r}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];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x.data[0]<=lowprimes[lowprimes.length-1]){for(i=0;i=0);var y=a.modPow(r,this);if(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j=1;while(j++0){r=forge.util.fillString(String.fromCharCode(0),zeros)+r}var encapsulation=publicKey.encrypt(r,"NONE");var key=kdf.generate(r,keyLength);return{encapsulation:encapsulation,key:key}};kem.decrypt=function(privateKey,encapsulation,keyLength){var r=privateKey.decrypt(encapsulation,"NONE");return kdf.generate(r,keyLength)};return kem};forge.kem.kdf1=function(md,digestLength){_createKDF(this,md,0,digestLength||md.digestLength)};forge.kem.kdf2=function(md,digestLength){_createKDF(this,md,1,digestLength||md.digestLength)};function _createKDF(kdf,md,counterStart,digestLength){kdf.generate=function(x,length){var key=new forge.util.ByteBuffer;var k=Math.ceil(length/digestLength)+counterStart;var c=new forge.util.ByteBuffer;for(var i=counterStart;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var bits,carry=0;for(var i=md.fullMessageLength.length-1;i>=0;--i){bits=md.fullMessageLength[i]*8+carry;carry=bits/4294967296>>>0;finalBlock.putInt32Le(bits>>>0)}var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32Le(s2.h0);rval.putInt32Le(s2.h1);rval.putInt32Le(s2.h2);rval.putInt32Le(s2.h3);return rval};return md};var _padding=null;var _g=null;var _r=null;var _k=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_g=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9];_r=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];_k=new Array(64);for(var i=0;i<64;++i){_k[i]=Math.floor(Math.abs(Math.sin(i+1))*4294967296)}_initialized=true}function _update(s,w,bytes){var t,a,b,c,d,f,r,i;var len=bytes.length();while(len>=64){a=s.h0;b=s.h1;c=s.h2;d=s.h3;for(i=0;i<16;++i){w[i]=bytes.getInt32Le();f=d^b&(c^d);t=a+f+_k[i]+w[i];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<32;++i){f=c^d&(b^c);t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<48;++i){f=b^c^d;t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}for(;i<64;++i){f=c^(b|~d);t=a+f+_k[i]+w[_g[i]];r=_r[i];a=d;d=c;c=b;b+=t<>>32-r}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],25:[function(require,module,exports){var forge=require("./forge");require("./mgf1");module.exports=forge.mgf=forge.mgf||{};forge.mgf.mgf1=forge.mgf1},{"./forge":16,"./mgf1":26}],26:[function(require,module,exports){var forge=require("./forge");require("./util");forge.mgf=forge.mgf||{};var mgf1=module.exports=forge.mgf.mgf1=forge.mgf1=forge.mgf1||{};mgf1.create=function(md){var mgf={generate:function(seed,maskLen){var t=new forge.util.ByteBuffer;var len=Math.ceil(maskLen/md.digestLength);for(var i=0;i=0;l--){x=x>>8;x+=B.at(l)+chunk.at(l);chunk.setAt(l,x&255)}Inew.putBuffer(chunk)}I=Inew;result.putBuffer(buf)}result.truncate(result.length()-n);return result};pki.pbe.getCipher=function(oid,params,password){switch(oid){case pki.oids["pkcs5PBES2"]:return pki.pbe.getCipherForPBES2(oid,params,password);case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:return pki.pbe.getCipherForPKCS12PBE(oid,params,password);default:var error=new Error("Cannot read encrypted PBE data block. Unsupported OID.");error.oid=oid;error.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"];throw error}};pki.pbe.getCipherForPBES2=function(oid,params,password){var capture={};var errors=[];if(!asn1.validate(params,PBES2AlgorithmsValidator,capture,errors)){var error=new Error("Cannot read password-based-encryption algorithm "+"parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}oid=asn1.derToOid(capture.kdfOid);if(oid!==pki.oids["pkcs5PBKDF2"]){var error=new Error("Cannot read encrypted private key. "+"Unsupported key derivation function OID.");error.oid=oid;error.supportedOids=["pkcs5PBKDF2"];throw error}oid=asn1.derToOid(capture.encOid);if(oid!==pki.oids["aes128-CBC"]&&oid!==pki.oids["aes192-CBC"]&&oid!==pki.oids["aes256-CBC"]&&oid!==pki.oids["des-EDE3-CBC"]&&oid!==pki.oids["desCBC"]){var error=new Error("Cannot read encrypted private key. "+"Unsupported encryption scheme OID.");error.oid=oid;error.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"];throw error}var salt=capture.kdfSalt;var count=forge.util.createBuffer(capture.kdfIterationCount);count=count.getInt(count.length()<<3);var dkLen;var cipherFn;switch(pki.oids[oid]){case"aes128-CBC":dkLen=16;cipherFn=forge.aes.createDecryptionCipher;break;case"aes192-CBC":dkLen=24;cipherFn=forge.aes.createDecryptionCipher;break;case"aes256-CBC":dkLen=32;cipherFn=forge.aes.createDecryptionCipher;break;case"des-EDE3-CBC":dkLen=24;cipherFn=forge.des.createDecryptionCipher;break;case"desCBC":dkLen=8;cipherFn=forge.des.createDecryptionCipher;break}var md=prfOidToMessageDigest(capture.prfOid);var dk=forge.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=capture.encIv;var cipher=cipherFn(dk);cipher.start(iv);return cipher};pki.pbe.getCipherForPKCS12PBE=function(oid,params,password){var capture={};var errors=[];if(!asn1.validate(params,pkcs12PbeParamsValidator,capture,errors)){var error=new Error("Cannot read password-based-encryption algorithm "+"parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var salt=forge.util.createBuffer(capture.salt);var count=forge.util.createBuffer(capture.iterations);count=count.getInt(count.length()<<3);var dkLen,dIvLen,cipherFn;switch(oid){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:dkLen=24;dIvLen=8;cipherFn=forge.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:dkLen=5;dIvLen=8;cipherFn=function(key,iv){var cipher=forge.rc2.createDecryptionCipher(key,40);cipher.start(iv,null);return cipher};break;default:var error=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");error.oid=oid;throw error}var md=prfOidToMessageDigest(capture.prfOid);var key=pki.pbe.generatePkcs12Key(password,salt,1,count,dkLen,md);md.start();var iv=pki.pbe.generatePkcs12Key(password,salt,2,count,dIvLen,md);return cipherFn(key,iv)};pki.pbe.opensslDeriveBytes=function(password,salt,dkLen,md){if(typeof md==="undefined"||md===null){if(!("md5"in forge.md)){throw new Error('"md5" hash algorithm unavailable.')}md=forge.md.md5.create()}if(salt===null){salt=""}var digests=[hash(md,password+salt)];for(var length=16,i=1;length4||(!md||md==="sha1"))){if(typeof md!=="string"){md="sha1"}p=Buffer.from(p,"binary");s=Buffer.from(s,"binary");if(!callback){if(crypto.pbkdf2Sync.length===4){return crypto.pbkdf2Sync(p,s,c,dkLen).toString("binary")}return crypto.pbkdf2Sync(p,s,c,dkLen,md).toString("binary")}if(crypto.pbkdf2Sync.length===4){return crypto.pbkdf2(p,s,c,dkLen,function(err,key){if(err){return callback(err)}callback(null,key.toString("binary"))})}return crypto.pbkdf2(p,s,c,dkLen,md,function(err,key){if(err){return callback(err)}callback(null,key.toString("binary"))})}if(typeof md==="undefined"||md===null){md="sha1"}if(typeof md==="string"){if(!(md in forge.md.algorithms)){throw new Error("Unknown hash algorithm: "+md)}md=forge.md[md].create()}var hLen=md.digestLength;if(dkLen>4294967295*hLen){var err=new Error("Derived key is too long.");if(callback){return callback(err)}throw err}var len=Math.ceil(dkLen/hLen);var r=dkLen-(len-1)*hLen;var prf=forge.hmac.create();prf.start(md,p);var dk="";var xor,u_c,u_c1;if(!callback){for(var i=1;i<=len;++i){prf.start(null,null);prf.update(s);prf.update(forge.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();for(var j=2;j<=c;++j){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge.util.xorBytes(xor,u_c,hLen);u_c1=u_c}dk+=ilen){return callback(null,dk)}prf.start(null,null);prf.update(s);prf.update(forge.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();j=2;inner()}function inner(){if(j<=c){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge.util.xorBytes(xor,u_c,hLen);u_c1=u_c;++j;return forge.util.setImmediate(inner)}dk+=i65&&candidate!==-1){var insert=rval[candidate];if(insert===","){++candidate;rval=rval.substr(0,candidate)+"\r\n "+rval.substr(candidate)}else{rval=rval.substr(0,candidate)+"\r\n"+insert+rval.substr(candidate+1)}length=i-candidate-1;candidate=-1;++i}else if(rval[i]===" "||rval[i]==="\t"||rval[i]===","){candidate=i}}return rval}function ltrim(str){return str.replace(/^\s+/,"")}},{"./forge":16,"./util":48}],31:[function(require,module,exports){var forge=require("./forge");require("./util");require("./random");require("./sha1");var pkcs1=module.exports=forge.pkcs1=forge.pkcs1||{};pkcs1.encode_rsa_oaep=function(key,message,options){var label;var seed;var md;var mgf1Md;if(typeof options==="string"){label=options;seed=arguments[3]||undefined;md=arguments[4]||undefined}else if(options){label=options.label||undefined;seed=options.seed||undefined;md=options.md||undefined;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}if(!md){md=forge.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}var keyLength=Math.ceil(key.n.bitLength()/8);var maxLength=keyLength-2*md.digestLength-2;if(message.length>maxLength){var error=new Error("RSAES-OAEP input message length is too long.");error.length=message.length;error.maxLength=maxLength;throw error}if(!label){label=""}md.update(label,"raw");var lHash=md.digest();var PS="";var PS_length=maxLength-message.length;for(var i=0;i>24&255,i>>16&255,i>>8&255,i&255);hash.start();hash.update(seed+c);t+=hash.digest().getBytes()}return t.substring(0,maskLength)}},{"./forge":16,"./random":39,"./sha1":42,"./util":48}],32:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./hmac");require("./oids");require("./pkcs7asn1");require("./pbe");require("./random");require("./rsa");require("./sha1");require("./util");require("./x509");var asn1=forge.asn1;var pki=forge.pki;var p12=module.exports=forge.pkcs12=forge.pkcs12||{};var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"content"}]};var pfxValidator={name:"PFX",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},contentInfoValidator,{name:"PFX.macData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"macIterations"}]}]};var safeBagValidator={name:"SafeBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SafeBag.bagId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,optional:true,capture:"bagAttributes"}]};var attributeValidator={name:"Attribute",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Attribute.attrId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"oid"},{name:"Attribute.attrValues",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,capture:"values"}]};var certBagValidator={name:"CertBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertBag.certId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certId"},{name:"CertBag.certValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,value:[{name:"CertBag.certValue[0]",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.OCTETSTRING,constructed:false,capture:"cert"}]}]};function _getBagsByAttribute(safeContents,attrName,attrValue,bagType){var result=[];for(var i=0;i=0){result.push(bag)}}}return result}p12.pkcs12FromAsn1=function(obj,strict,password){if(typeof strict==="string"){password=strict;strict=true}else if(strict===undefined){strict=true}var capture={};var errors=[];if(!asn1.validate(obj,pfxValidator,capture,errors)){var error=new Error("Cannot read PKCS#12 PFX. "+"ASN.1 object is not an PKCS#12 PFX.");error.errors=error;throw error}var pfx={version:capture.version.charCodeAt(0),safeContents:[],getBags:function(filter){var rval={};var localKeyId;if("localKeyId"in filter){localKeyId=filter.localKeyId}else if("localKeyIdHex"in filter){localKeyId=forge.util.hexToBytes(filter.localKeyIdHex)}if(localKeyId===undefined&&!("friendlyName"in filter)&&"bagType"in filter){rval[filter.bagType]=_getBagsByAttribute(pfx.safeContents,null,null,filter.bagType)}if(localKeyId!==undefined){rval.localKeyId=_getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,filter.bagType)}if("friendlyName"in filter){rval.friendlyName=_getBagsByAttribute(pfx.safeContents,"friendlyName",filter.friendlyName,filter.bagType)}return rval},getBagsByFriendlyName:function(friendlyName,bagType){return _getBagsByAttribute(pfx.safeContents,"friendlyName",friendlyName,bagType)},getBagsByLocalKeyId:function(localKeyId,bagType){return _getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,bagType)}};if(capture.version.charCodeAt(0)!==3){var error=new Error("PKCS#12 PFX of version other than 3 not supported.");error.version=capture.version.charCodeAt(0);throw error}if(asn1.derToOid(capture.contentType)!==pki.oids.data){var error=new Error("Only PKCS#12 PFX in password integrity mode supported.");error.oid=asn1.derToOid(capture.contentType);throw error}var data=capture.content.value[0];if(data.tagClass!==asn1.Class.UNIVERSAL||data.type!==asn1.Type.OCTETSTRING){throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.")}data=_decodePkcs7Data(data);if(capture.mac){var md=null;var macKeyBytes=0;var macAlgorithm=asn1.derToOid(capture.macAlgorithm);switch(macAlgorithm){case pki.oids.sha1:md=forge.md.sha1.create();macKeyBytes=20;break;case pki.oids.sha256:md=forge.md.sha256.create();macKeyBytes=32;break;case pki.oids.sha384:md=forge.md.sha384.create();macKeyBytes=48;break;case pki.oids.sha512:md=forge.md.sha512.create();macKeyBytes=64;break;case pki.oids.md5:md=forge.md.md5.create();macKeyBytes=16;break}if(md===null){throw new Error("PKCS#12 uses unsupported MAC algorithm: "+macAlgorithm)}var macSalt=new forge.util.ByteBuffer(capture.macSalt);var macIterations="macIterations"in capture?parseInt(forge.util.bytesToHex(capture.macIterations),16):1;var macKey=p12.generateKey(password,macSalt,3,macIterations,macKeyBytes,md);var mac=forge.hmac.create();mac.start(md,macKey);mac.update(data.value);var macValue=mac.getMac();if(macValue.getBytes()!==capture.macDigest){throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}}_decodeAuthenticatedSafe(pfx,data.value,strict,password);return pfx};function _decodePkcs7Data(data){if(data.composed||data.constructed){var value=forge.util.createBuffer();for(var i=0;i0){bagAttrs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,attrs)}var contents=[];var chain=[];if(cert!==null){if(forge.util.isArray(cert)){chain=cert}else{chain=[cert]}}var certSafeBags=[];for(var i=0;i0){var certSafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,certSafeBags);var certCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certSafeContents).getBytes())])]);contents.push(certCI)}var keyBag=null;if(key!==null){var pkAsn1=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));if(password===null){keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.keyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pkAsn1]),bagAttrs])}else{keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pki.encryptPrivateKeyInfo(pkAsn1,password,options)]),bagAttrs])}var keySafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[keyBag]);var keyCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(keySafeContents).getBytes())])]);contents.push(keyCI)}var safe=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,contents);var macData;if(options.useMac){var sha1=forge.md.sha1.create();var macSalt=new forge.util.ByteBuffer(forge.random.getBytes(options.saltSize));var count=options.count;var key=p12.generateKey(password,macSalt,3,count,20);var mac=forge.hmac.create();mac.start(sha1,key);mac.update(asn1.toDer(safe).getBytes());var macValue=mac.getMac();macData=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.sha1).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macValue.getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macSalt.getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(count).getBytes())])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(3).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(safe).getBytes())])]),macData])};p12.generateKey=forge.pbe.generatePkcs12Key},{"./asn1":9,"./forge":16,"./hmac":17,"./oids":27,"./pbe":28,"./pkcs7asn1":34,"./random":39,"./rsa":41,"./sha1":42,"./util":48,"./x509":49}],33:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./asn1");require("./des");require("./oids");require("./pem");require("./pkcs7asn1");require("./random");require("./util");require("./x509");var asn1=forge.asn1;var p7=module.exports=forge.pkcs7=forge.pkcs7||{};p7.messageFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if(msg.type!=="PKCS7"){var error=new Error("Could not convert PKCS#7 message from PEM; PEM "+'header type is not "PKCS#7".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.")}var obj=asn1.fromDer(msg.body);return p7.messageFromAsn1(obj)};p7.messageToPem=function(msg,maxline){var pemObj={type:"PKCS7",body:asn1.toDer(msg.toAsn1()).getBytes()};return forge.pem.encode(pemObj,{maxline:maxline})};p7.messageFromAsn1=function(obj){var capture={};var errors=[];if(!asn1.validate(obj,p7.asn1.contentInfoValidator,capture,errors)){var error=new Error("Cannot read PKCS#7 message. "+"ASN.1 object is not an PKCS#7 ContentInfo.");error.errors=errors;throw error}var contentType=asn1.derToOid(capture.contentType);var msg;switch(contentType){case forge.pki.oids.envelopedData:msg=p7.createEnvelopedData();break;case forge.pki.oids.encryptedData:msg=p7.createEncryptedData();break;case forge.pki.oids.signedData:msg=p7.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+contentType+" is not (yet) supported.")}msg.fromAsn1(capture.content.value[0]);return msg};p7.createSignedData=function(){var msg=null;msg={type:forge.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.signedDataValidator);msg.certificates=[];msg.crls=[];msg.digestAlgorithmIdentifiers=[];msg.contentInfo=null;msg.signerInfos=[];if(msg.rawCapture.certificates){var certs=msg.rawCapture.certificates.value;for(var i=0;i0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,certs))}if(crls.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,crls))}signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.signerInfos));return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),signedData])},addSigner:function(signer){var issuer=signer.issuer;var serialNumber=signer.serialNumber;if(signer.certificate){var cert=signer.certificate;if(typeof cert==="string"){cert=forge.pki.certificateFromPem(cert)}issuer=cert.issuer.attributes;serialNumber=cert.serialNumber}var key=signer.key;if(!key){throw new Error("Could not add PKCS#7 signer; no private key specified.")}if(typeof key==="string"){key=forge.pki.privateKeyFromPem(key)}var digestAlgorithm=signer.digestAlgorithm||forge.pki.oids.sha1;switch(digestAlgorithm){case forge.pki.oids.sha1:case forge.pki.oids.sha256:case forge.pki.oids.sha384:case forge.pki.oids.sha512:case forge.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+digestAlgorithm)}var authenticatedAttributes=signer.authenticatedAttributes||[];if(authenticatedAttributes.length>0){var contentType=false;var messageDigest=false;for(var i=0;i0){var attrsAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[]);for(var i=0;i=jan_1_1950&&datebits){num=generateRandom(bits,rng)}if(num.isProbablePrime(mrTests)){return callback(null,num)}num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}while(maxBlockTime<0||+new Date-startbits){num=generateRandom(bits,rng)}var hex=num.toString(16);e.target.postMessage({hex:hex,workLoad:workLoad});num.dAddOffset(range,0)}}}function generateRandom(bits,rng){var num=new BigInteger(bits,rng);var bits1=bits-1;if(!num.testBit(bits1)){num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,num)}num.dAddOffset(31-num.mod(THIRTY).byteValue(),0);return num}function getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}})()},{"./forge":16,"./jsbn":19,"./random":39,"./util":48}],37:[function(require,module,exports){(function(process){var forge=require("./forge");require("./util");var _crypto=null;if(forge.util.isNodejs&&!forge.options.usePureJavaScript&&!process.versions["node-webkit"]){_crypto=require("crypto")}var prng=module.exports=forge.prng=forge.prng||{};prng.create=function(plugin){var ctx={plugin:plugin,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""};var md=plugin.md;var pools=new Array(32);for(var i=0;i<32;++i){pools[i]=md.create()}ctx.pools=pools;ctx.pool=0;ctx.generate=function(count,callback){if(!callback){return ctx.generateSync(count)}var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;var b=forge.util.createBuffer();ctx.key=null;generate();function generate(err){if(err){return callback(err)}if(b.length()>=count){return callback(null,b.getBytes(count))}if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){return forge.util.nextTick(function(){_reseed(generate)})}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed));forge.util.setImmediate(generate)}};ctx.generateSync=function(count){var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;ctx.key=null;var b=forge.util.createBuffer();while(b.length()1048575){ctx.key=null}if(ctx.key===null){_reseedSync()}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed))}return b.getBytes(count)};function _reseed(callback){if(ctx.pools[0].messageLength>=32){_seed();return callback()}var needed=32-ctx.pools[0].messageLength<<5;ctx.seedFile(needed,function(err,bytes){if(err){return callback(err)}ctx.collect(bytes);_seed();callback()})}function _reseedSync(){if(ctx.pools[0].messageLength>=32){return _seed()}var needed=32-ctx.pools[0].messageLength<<5;ctx.collect(ctx.seedFileSync(needed));_seed()}function _seed(){ctx.reseeds=ctx.reseeds===4294967295?0:ctx.reseeds+1;var md=ctx.plugin.md.create();md.update(ctx.keyBytes);var _2powK=1;for(var k=0;k<32;++k){if(ctx.reseeds%_2powK===0){md.update(ctx.pools[k].digest().getBytes());ctx.pools[k].start()}_2powK=_2powK<<1}ctx.keyBytes=md.digest().getBytes();md.start();md.update(ctx.keyBytes);var seedBytes=md.digest().getBytes();ctx.key=ctx.plugin.formatKey(ctx.keyBytes);ctx.seed=ctx.plugin.formatSeed(seedBytes);ctx.generated=0}function defaultSeedFile(needed){var getRandomValues=null;var globalScope=forge.util.globalScope;var _crypto=globalScope.crypto||globalScope.msCrypto;if(_crypto&&_crypto.getRandomValues){getRandomValues=function(arr){return _crypto.getRandomValues(arr)}}var b=forge.util.createBuffer();if(getRandomValues){while(b.length()>16);lo+=(hi&32767)<<16;lo+=hi>>15;lo=(lo&2147483647)+(lo>>31);seed=lo&4294967295;for(var i=0;i<3;++i){next=seed>>>(i<<3);next^=Math.floor(Math.random()*256);b.putByte(String.fromCharCode(next&255))}}}return b.getBytes(needed)}if(_crypto){ctx.seedFile=function(needed,callback){_crypto.randomBytes(needed,function(err,bytes){if(err){return callback(err)}callback(null,bytes.toString())})};ctx.seedFileSync=function(needed){return _crypto.randomBytes(needed).toString()}}else{ctx.seedFile=function(needed,callback){try{callback(null,defaultSeedFile(needed))}catch(e){callback(e)}};ctx.seedFileSync=defaultSeedFile}ctx.collect=function(bytes){var count=bytes.length;for(var i=0;i>x&255)}ctx.collect(bytes)};ctx.registerWorker=function(worker){if(worker===self){ctx.seedFile=function(needed,callback){function listener(e){var data=e.data;if(data.forge&&data.forge.prng){self.removeEventListener("message",listener);callback(data.forge.prng.err,data.forge.prng.bytes)}}self.addEventListener("message",listener);self.postMessage({forge:{prng:{needed:needed}}})}}else{var listener=function(e){var data=e.data;if(data.forge&&data.forge.prng){ctx.seedFile(data.forge.prng.needed,function(err,bytes){worker.postMessage({forge:{prng:{err:err,bytes:bytes}}})})}};worker.addEventListener("message",listener)}};return ctx}}).call(this,require("_process"))},{"./forge":16,"./util":48,_process:50,crypto:6}],38:[function(require,module,exports){var forge=require("./forge");require("./random");require("./util");var pss=module.exports=forge.pss=forge.pss||{};pss.create=function(options){if(arguments.length===3){options={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]}}var hash=options.md;var mgf=options.mgf;var hLen=hash.digestLength;var salt_=options.salt||null;if(typeof salt_==="string"){salt_=forge.util.createBuffer(salt_)}var sLen;if("saltLength"in options){sLen=options.saltLength}else if(salt_!==null){sLen=salt_.length()}else{throw new Error("Salt length not specified or specific salt not given.")}if(salt_!==null&&salt_.length()!==sLen){throw new Error("Given salt length does not match length of given salt.")}var prng=options.prng||forge.random;var pssobj={};pssobj.encode=function(md,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);var mHash=md.digest().getBytes();if(emLen>8*emLen-emBits&255;maskedDB=String.fromCharCode(maskedDB.charCodeAt(0)&~mask)+maskedDB.substr(1);return maskedDB+h+String.fromCharCode(188)};pssobj.verify=function(mHash,em,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);em=em.substr(-emLen);if(emLen>8*emLen-emBits&255;if((maskedDB.charCodeAt(0)&mask)!==0){throw new Error("Bits beyond keysize not zero as expected.")}var dbMask=mgf.generate(h,maskLen);var db="";for(i=0;i>16-bits};var ror=function(word,bits){return(word&65535)>>bits|word<<16-bits&65535};module.exports=forge.rc2=forge.rc2||{};forge.rc2.expandKey=function(key,effKeyBits){if(typeof key==="string"){key=forge.util.createBuffer(key)}effKeyBits=effKeyBits||128;var L=key;var T=key.length();var T1=effKeyBits;var T8=Math.ceil(T1/8);var TM=255>>(T1&7);var i;for(i=T;i<128;i++){L.putByte(piTable[L.at(i-1)+L.at(i-T)&255])}L.setAt(128-T8,piTable[L.at(128-T8)&TM]);for(i=127-T8;i>=0;i--){L.setAt(i,piTable[L.at(i+1)^L.at(i+T8)])}return L};var createCipher=function(key,bits,encrypt){var _finish=false,_input=null,_output=null,_iv=null;var mixRound,mashRound;var i,j,K=[];key=forge.rc2.expandKey(key,bits);for(i=0;i<64;i++){K.push(key.getInt16Le())}if(encrypt){mixRound=function(R){for(i=0;i<4;i++){R[i]+=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]);R[i]=rol(R[i],s[i]);j++}};mashRound=function(R){for(i=0;i<4;i++){R[i]+=K[R[(i+3)%4]&63]}}}else{mixRound=function(R){for(i=3;i>=0;i--){R[i]=ror(R[i],s[i]);R[i]-=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]);j--}};mashRound=function(R){for(i=3;i>=0;i--){R[i]-=K[R[(i+3)%4]&63]}}}var runPlan=function(plan){var R=[];for(i=0;i<4;i++){var val=_input.getInt16Le();if(_iv!==null){if(encrypt){val^=_iv.getInt16Le()}else{_iv.putInt16Le(val)}}R.push(val&65535)}j=encrypt?0:63;for(var ptr=0;ptr=8){runPlan([[5,mixRound],[1,mashRound],[6,mixRound],[1,mashRound],[5,mixRound]])}},finish:function(pad){var rval=true;if(encrypt){if(pad){rval=pad(8,_input,!encrypt)}else{var padding=_input.length()===8?8:8-_input.length();_input.fillWithByte(padding,padding)}}if(rval){_finish=true;cipher.update()}if(!encrypt){rval=_input.length()===0;if(rval){if(pad){rval=pad(8,_output,!encrypt)}else{var len=_output.length();var count=_output.at(len-1);if(count>len){rval=false}else{_output.truncate(count)}}}}return rval}};return cipher};forge.rc2.startEncrypting=function(key,iv,output){var cipher=forge.rc2.createEncryptionCipher(key,128);cipher.start(iv,output);return cipher};forge.rc2.createEncryptionCipher=function(key,bits){return createCipher(key,bits,true)};forge.rc2.startDecrypting=function(key,iv,output){var cipher=forge.rc2.createDecryptionCipher(key,128);cipher.start(iv,output);return cipher};forge.rc2.createDecryptionCipher=function(key,bits){return createCipher(key,bits,false)}},{"./forge":16,"./util":48}],41:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./jsbn");require("./oids");require("./pkcs1");require("./prime");require("./random");require("./util");if(typeof BigInteger==="undefined"){var BigInteger=forge.jsbn.BigInteger}var _crypto=forge.util.isNodejs?require("crypto"):null;var asn1=forge.asn1;var util=forge.util;forge.pki=forge.pki||{};module.exports=forge.pki.rsa=forge.rsa=forge.rsa||{};var pki=forge.pki;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};var rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPrivateKey.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyCoefficient"}]};var rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPublicKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyExponent"}]};var publicKeyValidator=forge.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"rsaPublicKey"}]}]};var emsaPkcs1v15encode=function(md){var oid;if(md.algorithm in pki.oids){oid=pki.oids[md.algorithm]}else{var error=new Error("Unknown message digest algorithm.");error.algorithm=md.algorithm;throw error}var oidBytes=asn1.oidToDer(oid).getBytes();var digestInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var digestAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,oidBytes));digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,""));var digest=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,md.digest().getBytes());digestInfo.value.push(digestAlgorithm);digestInfo.value.push(digest);return asn1.toDer(digestInfo).getBytes()};var _modPow=function(x,key,pub){if(pub){return x.modPow(key.e,key.n)}if(!key.p||!key.q){return x.modPow(key.d,key.n)}if(!key.dP){key.dP=key.d.mod(key.p.subtract(BigInteger.ONE))}if(!key.dQ){key.dQ=key.d.mod(key.q.subtract(BigInteger.ONE))}if(!key.qInv){key.qInv=key.q.modInverse(key.p)}var r;do{r=new BigInteger(forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength()/8)),16)}while(r.compareTo(key.n)>=0||!r.gcd(key.n).equals(BigInteger.ONE));x=x.multiply(r.modPow(key.e,key.n)).mod(key.n);var xp=x.mod(key.p).modPow(key.dP,key.p);var xq=x.mod(key.q).modPow(key.dQ,key.q);while(xp.compareTo(xq)<0){xp=xp.add(key.p)}var y=xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq);y=y.multiply(r.modInverse(key.n)).mod(key.n);return y};pki.rsa.encrypt=function(m,key,bt){var pub=bt;var eb;var k=Math.ceil(key.n.bitLength()/8);if(bt!==false&&bt!==true){pub=bt===2;eb=_encodePkcs1_v1_5(m,key,bt)}else{eb=forge.util.createBuffer();eb.putBytes(m)}var x=new BigInteger(eb.toHex(),16);var y=_modPow(x,key,pub);var yhex=y.toString(16);var ed=forge.util.createBuffer();var zeros=k-Math.ceil(yhex.length/2);while(zeros>0){ed.putByte(0);--zeros}ed.putBytes(forge.util.hexToBytes(yhex));return ed.getBytes()};pki.rsa.decrypt=function(ed,key,pub,ml){var k=Math.ceil(key.n.bitLength()/8);if(ed.length!==k){var error=new Error("Encrypted message length is invalid.");error.length=ed.length;error.expected=k;throw error}var y=new BigInteger(forge.util.createBuffer(ed).toHex(),16);if(y.compareTo(key.n)>=0){throw new Error("Encrypted message is invalid.")}var x=_modPow(y,key,pub);var xhex=x.toString(16);var eb=forge.util.createBuffer();var zeros=k-Math.ceil(xhex.length/2);while(zeros>0){eb.putByte(0);--zeros}eb.putBytes(forge.util.hexToBytes(xhex));if(ml!==false){return _decodePkcs1_v1_5(eb.getBytes(),key,pub)}return eb.getBytes()};pki.rsa.createKeyPairGenerationState=function(bits,e,options){if(typeof bits==="string"){bits=parseInt(bits,10)}bits=bits||2048;options=options||{};var prng=options.prng||forge.random;var rng={nextBytes:function(x){var b=prng.getBytesSync(x.length);for(var i=0;i>1,pBits:bits-(bits>>1),pqState:0,num:null,keys:null};rval.e.fromInt(rval.eInt)}else{throw new Error("Invalid key generation algorithm: "+algorithm)}return rval};pki.rsa.stepKeyPairGenerationState=function(state,n){if(!("algorithm"in state)){state.algorithm="PRIMEINC"}var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var deltaIdx=0;var op_or=function(x,y){return x|y};var t1=+new Date;var t2;var total=0;while(state.keys===null&&(n<=0||totalbits){state.pqState=0}else if(state.num.isProbablePrime(_getMillerRabinTests(state.num.bitLength()))){++state.pqState}else{state.num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}}else if(state.pqState===2){state.pqState=state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)===0?3:0}else if(state.pqState===3){state.pqState=0;if(state.p===null){state.p=state.num}else{state.q=state.num}if(state.p!==null&&state.q!==null){++state.state}state.num=null}}else if(state.state===1){if(state.p.compareTo(state.q)<0){state.num=state.p;state.p=state.q;state.q=state.num}++state.state}else if(state.state===2){state.p1=state.p.subtract(BigInteger.ONE);state.q1=state.q.subtract(BigInteger.ONE);state.phi=state.p1.multiply(state.q1);++state.state}else if(state.state===3){if(state.phi.gcd(state.e).compareTo(BigInteger.ONE)===0){++state.state}else{state.p=null;state.q=null;state.state=0}}else if(state.state===4){state.n=state.p.multiply(state.q);if(state.n.bitLength()===state.bits){++state.state}else{state.q=null;state.state=0}}else if(state.state===5){var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)}}t2=+new Date;total+=t2-t1;t1=t2}return state.keys!==null};pki.rsa.generateKeyPair=function(bits,e,options,callback){if(arguments.length===1){if(typeof bits==="object"){options=bits;bits=undefined}else if(typeof bits==="function"){callback=bits;bits=undefined}}else if(arguments.length===2){if(typeof bits==="number"){if(typeof e==="function"){callback=e;e=undefined}else if(typeof e!=="number"){options=e;e=undefined}}else{options=bits;callback=e;bits=undefined;e=undefined}}else if(arguments.length===3){if(typeof e==="number"){if(typeof options==="function"){callback=options;options=undefined}}else{callback=options;options=e;e=undefined}}options=options||{};if(bits===undefined){bits=options.bits||2048}if(e===undefined){e=options.e||65537}if(!forge.options.usePureJavaScript&&!options.prng&&bits>=256&&bits<=16384&&(e===65537||e===3)){if(callback){if(_detectNodeCrypto("generateKeyPair")){return _crypto.generateKeyPair("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(err,pub,priv){if(err){return callback(err)}callback(null,{privateKey:pki.privateKeyFromPem(priv),publicKey:pki.publicKeyFromPem(pub)})})}if(_detectSubtleCrypto("generateKey")&&_detectSubtleCrypto("exportKey")){return util.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},true,["sign","verify"]).then(function(pair){return util.globalScope.crypto.subtle.exportKey("pkcs8",pair.privateKey)}).then(undefined,function(err){callback(err)}).then(function(pkcs8){if(pkcs8){var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})}})}if(_detectSubtleMsCrypto("generateKey")&&_detectSubtleMsCrypto("exportKey")){var genOp=util.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},true,["sign","verify"]);genOp.oncomplete=function(e){var pair=e.target.result;var exportOp=util.globalScope.msCrypto.subtle.exportKey("pkcs8",pair.privateKey);exportOp.oncomplete=function(e){var pkcs8=e.target.result;var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})};exportOp.onerror=function(err){callback(err)}};genOp.onerror=function(err){callback(err)};return}}else{if(_detectNodeCrypto("generateKeyPairSync")){var keypair=_crypto.generateKeyPairSync("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:pki.privateKeyFromPem(keypair.privateKey),publicKey:pki.publicKeyFromPem(keypair.publicKey)}}}}var state=pki.rsa.createKeyPairGenerationState(bits,e,options);if(!callback){pki.rsa.stepKeyPairGenerationState(state,0);return state.keys}_generateKeyPair(state,options,callback)};pki.setRsaPublicKey=pki.rsa.setPublicKey=function(n,e){var key={n:n,e:e};key.encrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSAES-PKCS1-V1_5"}if(scheme==="RSAES-PKCS1-V1_5"){scheme={encode:function(m,key,pub){return _encodePkcs1_v1_5(m,key,2).getBytes()}}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={encode:function(m,key){return forge.pkcs1.encode_rsa_oaep(key,m,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={encode:function(e){return e}}}else if(typeof scheme==="string"){throw new Error('Unsupported encryption scheme: "'+scheme+'".')}var e=scheme.encode(data,key,true);return pki.rsa.encrypt(e,key,true)};key.verify=function(digest,signature,scheme){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSASSA-PKCS1-V1_5"}if(scheme==="RSASSA-PKCS1-V1_5"){scheme={verify:function(digest,d){d=_decodePkcs1_v1_5(d,key,true);var obj=asn1.fromDer(d);return digest===obj.value[1].value}}}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={verify:function(digest,d){d=_decodePkcs1_v1_5(d,key,true);return digest===d}}}var d=pki.rsa.decrypt(signature,key,true,false);return scheme.verify(digest,d,key.n.bitLength())};return key};pki.setRsaPrivateKey=pki.rsa.setPrivateKey=function(n,e,d,p,q,dP,dQ,qInv){var key={n:n,e:e,d:d,p:p,q:q,dP:dP,dQ:dQ,qInv:qInv};key.decrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===undefined){scheme="RSAES-PKCS1-V1_5"}var d=pki.rsa.decrypt(data,key,false,false);if(scheme==="RSAES-PKCS1-V1_5"){scheme={decode:_decodePkcs1_v1_5}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={decode:function(d,key){return forge.pkcs1.decode_rsa_oaep(key,d,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={decode:function(d){return d}}}else{throw new Error('Unsupported encryption scheme: "'+scheme+'".')}return scheme.decode(d,key,false)};key.sign=function(md,scheme){var bt=false;if(typeof scheme==="string"){scheme=scheme.toUpperCase()}if(scheme===undefined||scheme==="RSASSA-PKCS1-V1_5"){scheme={encode:emsaPkcs1v15encode};bt=1}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={encode:function(){return md}};bt=1}var d=scheme.encode(md,key.n.bitLength());return pki.rsa.encrypt(d,key,bt)};return key};pki.wrapRsaPrivateKey=function(rsaKey){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(rsaKey).getBytes())])};pki.privateKeyFromAsn1=function(obj){var capture={};var errors=[];if(asn1.validate(obj,privateKeyValidator,capture,errors)){obj=asn1.fromDer(forge.util.createBuffer(capture.privateKey))}capture={};errors=[];if(!asn1.validate(obj,rsaPrivateKeyValidator,capture,errors)){var error=new Error("Cannot read private key. "+"ASN.1 object does not contain an RSAPrivateKey.");error.errors=errors;throw error}var n,e,d,p,q,dP,dQ,qInv;n=forge.util.createBuffer(capture.privateKeyModulus).toHex();e=forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();d=forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();p=forge.util.createBuffer(capture.privateKeyPrime1).toHex();q=forge.util.createBuffer(capture.privateKeyPrime2).toHex();dP=forge.util.createBuffer(capture.privateKeyExponent1).toHex();dQ=forge.util.createBuffer(capture.privateKeyExponent2).toHex();qInv=forge.util.createBuffer(capture.privateKeyCoefficient).toHex();return pki.setRsaPrivateKey(new BigInteger(n,16),new BigInteger(e,16),new BigInteger(d,16),new BigInteger(p,16),new BigInteger(q,16),new BigInteger(dP,16),new BigInteger(dQ,16),new BigInteger(qInv,16))};pki.privateKeyToAsn1=pki.privateKeyToRSAPrivateKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.d)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.p)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.q)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dP)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dQ)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.qInv))])};pki.publicKeyFromAsn1=function(obj){var capture={};var errors=[];if(asn1.validate(obj,publicKeyValidator,capture,errors)){var oid=asn1.derToOid(capture.publicKeyOid);if(oid!==pki.oids.rsaEncryption){var error=new Error("Cannot read public key. Unknown OID.");error.oid=oid;throw error}obj=capture.rsaPublicKey}errors=[];if(!asn1.validate(obj,rsaPublicKeyValidator,capture,errors)){var error=new Error("Cannot read public key. "+"ASN.1 object does not contain an RSAPublicKey.");error.errors=errors;throw error}var n=forge.util.createBuffer(capture.publicKeyModulus).toHex();var e=forge.util.createBuffer(capture.publicKeyExponent).toHex();return pki.setRsaPublicKey(new BigInteger(n,16),new BigInteger(e,16))};pki.publicKeyToAsn1=pki.publicKeyToSubjectPublicKeyInfo=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,[pki.publicKeyToRSAPublicKey(key)])])};pki.publicKeyToRSAPublicKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e))])};function _encodePkcs1_v1_5(m,key,bt){var eb=forge.util.createBuffer();var k=Math.ceil(key.n.bitLength()/8);if(m.length>k-11){var error=new Error("Message is too long for PKCS#1 v1.5 padding.");error.length=m.length;error.max=k-11;throw error}eb.putByte(0);eb.putByte(bt);var padNum=k-3-m.length;var padByte;if(bt===0||bt===1){padByte=bt===0?0:255;for(var i=0;i0){var numZeros=0;var padBytes=forge.random.getBytes(padNum);for(var i=0;i1){if(eb.getByte()!==255){--eb.read;break}++padNum}}else if(bt===2){padNum=0;while(eb.length()>1){if(eb.getByte()===0){--eb.read;break}++padNum}}var zero=eb.getByte();if(zero!==0||padNum!==k-3-eb.length()){throw new Error("Encryption block is invalid.")}return eb.getBytes()}function _generateKeyPair(state,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var opts={algorithm:{name:options.algorithm||"PRIMEINC",options:{workers:options.workers||2,workLoad:options.workLoad||100,workerScript:options.workerScript}}};if("prng"in options){opts.prng=options.prng}generate();function generate(){getPrime(state.pBits,function(err,num){if(err){return callback(err)}state.p=num;if(state.q!==null){return finish(err,state.q)}getPrime(state.qBits,finish)})}function getPrime(bits,callback){forge.prime.generateProbablePrime(bits,opts,callback)}function finish(err,num){if(err){return callback(err)}state.q=num;if(state.p.compareTo(state.q)<0){var tmp=state.p;state.p=state.q;state.q=tmp}if(state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)!==0){state.p=null;generate();return}if(state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)!==0){state.q=null;getPrime(state.qBits,finish);return}state.p1=state.p.subtract(BigInteger.ONE);state.q1=state.q.subtract(BigInteger.ONE);state.phi=state.p1.multiply(state.q1);if(state.phi.gcd(state.e).compareTo(BigInteger.ONE)!==0){state.p=state.q=null;generate();return}state.n=state.p.multiply(state.q);if(state.n.bitLength()!==state.bits){state.q=null;getPrime(state.qBits,finish);return}var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)};callback(null,state.keys)}}function _bnToBytes(b){var hex=b.toString(16);if(hex[0]>="8"){hex="00"+hex}var bytes=forge.util.hexToBytes(hex);if(bytes.length>1&&(bytes.charCodeAt(0)===0&&(bytes.charCodeAt(1)&128)===0||bytes.charCodeAt(0)===255&&(bytes.charCodeAt(1)&128)===128)){return bytes.substr(1)}return bytes}function _getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}function _detectNodeCrypto(fn){return forge.util.isNodejs&&typeof _crypto[fn]==="function"}function _detectSubtleCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.crypto==="object"&&typeof util.globalScope.crypto.subtle==="object"&&typeof util.globalScope.crypto.subtle[fn]==="function"}function _detectSubtleMsCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.msCrypto==="object"&&typeof util.globalScope.msCrypto.subtle==="object"&&typeof util.globalScope.msCrypto.subtle[fn]==="function"}function _intToUint8Array(x){var bytes=forge.util.hexToBytes(x.toString(16));var buffer=new Uint8Array(bytes.length);for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32(s2.h0);rval.putInt32(s2.h1);rval.putInt32(s2.h2);rval.putInt32(s2.h3);rval.putInt32(s2.h4);return rval};return md};var _padding=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_initialized=true}function _update(s,w,bytes){var t,a,b,c,d,e,f,i;var len=bytes.length();while(len>=64){a=s.h0;b=s.h1;c=s.h2;d=s.h3;e=s.h4;for(i=0;i<16;++i){t=bytes.getInt32();w[i]=t;f=d^b&(c^d);t=(a<<5|a>>>27)+f+e+1518500249+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<20;++i){t=w[i-3]^w[i-8]^w[i-14]^w[i-16];t=t<<1|t>>>31;w[i]=t;f=d^b&(c^d);t=(a<<5|a>>>27)+f+e+1518500249+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<32;++i){t=w[i-3]^w[i-8]^w[i-14]^w[i-16];t=t<<1|t>>>31;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+1859775393+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<40;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+1859775393+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<60;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b&c|d&(b^c);t=(a<<5|a>>>27)+f+e+2400959708+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}for(;i<80;++i){t=w[i-6]^w[i-16]^w[i-28]^w[i-32];t=t<<2|t>>>30;w[i]=t;f=b^c^d;t=(a<<5|a>>>27)+f+e+3395469782+t;e=d;d=c;c=(b<<30|b>>>2)>>>0;b=a;a=t}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;s.h4=s.h4+e|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],43:[function(require,module,exports){var forge=require("./forge");require("./md");require("./util");var sha256=module.exports=forge.sha256=forge.sha256||{};forge.md.sha256=forge.md.algorithms.sha256=sha256;sha256.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge.util.createBuffer();var _w=new Array(64);var md={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4,h5:_state.h5,h6:_state.h6,h7:_state.h7};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();rval.putInt32(s2.h0);rval.putInt32(s2.h1);rval.putInt32(s2.h2);rval.putInt32(s2.h3);rval.putInt32(s2.h4);rval.putInt32(s2.h5);rval.putInt32(s2.h6);rval.putInt32(s2.h7);return rval};return md};var _padding=null;var _initialized=false;var _k=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge.util.fillString(String.fromCharCode(0),64);_k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];_initialized=true}function _update(s,w,bytes){var t1,t2,s0,s1,ch,maj,i,a,b,c,d,e,f,g,h;var len=bytes.length();while(len>=64){for(i=0;i<16;++i){w[i]=bytes.getInt32()}for(;i<64;++i){t1=w[i-2];t1=(t1>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10;t2=w[i-15];t2=(t2>>>7|t2<<25)^(t2>>>18|t2<<14)^t2>>>3;w[i]=t1+w[i-7]+t2+w[i-16]|0}a=s.h0;b=s.h1;c=s.h2;d=s.h3;e=s.h4;f=s.h5;g=s.h6;h=s.h7;for(i=0;i<64;++i){s1=(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7);ch=g^e&(f^g);s0=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10);maj=a&b|c&(a^b);t1=h+s1+ch+_k[i]+w[i];t2=s0+maj;h=g;g=f;f=e;e=d+t1>>>0;d=c;c=b;b=a;a=t1+t2>>>0}s.h0=s.h0+a|0;s.h1=s.h1+b|0;s.h2=s.h2+c|0;s.h3=s.h3+d|0;s.h4=s.h4+e|0;s.h5=s.h5+f|0;s.h6=s.h6+g|0;s.h7=s.h7+h|0;len-=64}}},{"./forge":16,"./md":23,"./util":48}],44:[function(require,module,exports){var forge=require("./forge");require("./md");require("./util");var sha512=module.exports=forge.sha512=forge.sha512||{};forge.md.sha512=forge.md.algorithms.sha512=sha512;var sha384=forge.sha384=forge.sha512.sha384=forge.sha512.sha384||{};sha384.create=function(){return sha512.create("SHA-384")};forge.md.sha384=forge.md.algorithms.sha384=sha384;forge.sha512.sha256=forge.sha512.sha256||{create:function(){return sha512.create("SHA-512/256")}};forge.md["sha512/256"]=forge.md.algorithms["sha512/256"]=forge.sha512.sha256;forge.sha512.sha224=forge.sha512.sha224||{create:function(){return sha512.create("SHA-512/224")}};forge.md["sha512/224"]=forge.md.algorithms["sha512/224"]=forge.sha512.sha224;sha512.create=function(algorithm){if(!_initialized){_init()}if(typeof algorithm==="undefined"){algorithm="SHA-512"}if(!(algorithm in _states)){throw new Error("Invalid SHA-512 algorithm: "+algorithm)}var _state=_states[algorithm];var _h=null;var _input=forge.util.createBuffer();var _w=new Array(80);for(var wi=0;wi<80;++wi){_w[wi]=new Array(2)}var digestLength=64;switch(algorithm){case"SHA-384":digestLength=48;break;case"SHA-512/256":digestLength=32;break;case"SHA-512/224":digestLength=28;break}var md={algorithm:algorithm.replace("-","").toLowerCase(),blockLength:128,digestLength:digestLength,messageLength:0,fullMessageLength:null,messageLengthSize:16};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength128=[];var int32s=md.messageLengthSize/4;for(var i=0;i>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i){md.fullMessageLength[i]+=len[1];len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0);md.fullMessageLength[i]=md.fullMessageLength[i]>>>0;len[0]=len[1]/4294967296>>>0}_input.putBytes(msg);_update(_h,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var h=new Array(_h.length);for(var i=0;i<_h.length;++i){h[i]=_h[i].slice(0)}_update(h,_w,finalBlock);var rval=forge.util.createBuffer();var hlen;if(algorithm==="SHA-512"){hlen=h.length}else if(algorithm==="SHA-384"){hlen=h.length-2}else{hlen=h.length-4}for(var i=0;i=128){for(i=0;i<16;++i){w[i][0]=bytes.getInt32()>>>0;w[i][1]=bytes.getInt32()>>>0}for(;i<80;++i){w2=w[i-2];hi=w2[0];lo=w2[1];t1_hi=((hi>>>19|lo<<13)^(lo>>>29|hi<<3)^hi>>>6)>>>0;t1_lo=((hi<<13|lo>>>19)^(lo<<3|hi>>>29)^(hi<<26|lo>>>6))>>>0;w15=w[i-15];hi=w15[0];lo=w15[1];t2_hi=((hi>>>1|lo<<31)^(hi>>>8|lo<<24)^hi>>>7)>>>0;t2_lo=((hi<<31|lo>>>1)^(hi<<24|lo>>>8)^(hi<<25|lo>>>7))>>>0;w7=w[i-7];w16=w[i-16];lo=t1_lo+w7[1]+t2_lo+w16[1];w[i][0]=t1_hi+w7[0]+t2_hi+w16[0]+(lo/4294967296>>>0)>>>0;w[i][1]=lo>>>0}a_hi=s[0][0];a_lo=s[0][1];b_hi=s[1][0];b_lo=s[1][1];c_hi=s[2][0];c_lo=s[2][1];d_hi=s[3][0];d_lo=s[3][1];e_hi=s[4][0];e_lo=s[4][1];f_hi=s[5][0];f_lo=s[5][1];g_hi=s[6][0];g_lo=s[6][1];h_hi=s[7][0];h_lo=s[7][1];for(i=0;i<80;++i){s1_hi=((e_hi>>>14|e_lo<<18)^(e_hi>>>18|e_lo<<14)^(e_lo>>>9|e_hi<<23))>>>0;s1_lo=((e_hi<<18|e_lo>>>14)^(e_hi<<14|e_lo>>>18)^(e_lo<<23|e_hi>>>9))>>>0;ch_hi=(g_hi^e_hi&(f_hi^g_hi))>>>0;ch_lo=(g_lo^e_lo&(f_lo^g_lo))>>>0;s0_hi=((a_hi>>>28|a_lo<<4)^(a_lo>>>2|a_hi<<30)^(a_lo>>>7|a_hi<<25))>>>0;s0_lo=((a_hi<<4|a_lo>>>28)^(a_lo<<30|a_hi>>>2)^(a_lo<<25|a_hi>>>7))>>>0;maj_hi=(a_hi&b_hi|c_hi&(a_hi^b_hi))>>>0;maj_lo=(a_lo&b_lo|c_lo&(a_lo^b_lo))>>>0;lo=h_lo+s1_lo+ch_lo+_k[i][1]+w[i][1];t1_hi=h_hi+s1_hi+ch_hi+_k[i][0]+w[i][0]+(lo/4294967296>>>0)>>>0;t1_lo=lo>>>0;lo=s0_lo+maj_lo;t2_hi=s0_hi+maj_hi+(lo/4294967296>>>0)>>>0;t2_lo=lo>>>0;h_hi=g_hi;h_lo=g_lo;g_hi=f_hi;g_lo=f_lo;f_hi=e_hi;f_lo=e_lo;lo=d_lo+t1_lo;e_hi=d_hi+t1_hi+(lo/4294967296>>>0)>>>0;e_lo=lo>>>0;d_hi=c_hi;d_lo=c_lo;c_hi=b_hi;c_lo=b_lo;b_hi=a_hi;b_lo=a_lo;lo=t1_lo+t2_lo;a_hi=t1_hi+t2_hi+(lo/4294967296>>>0)>>>0;a_lo=lo>>>0}lo=s[0][1]+a_lo;s[0][0]=s[0][0]+a_hi+(lo/4294967296>>>0)>>>0;s[0][1]=lo>>>0;lo=s[1][1]+b_lo;s[1][0]=s[1][0]+b_hi+(lo/4294967296>>>0)>>>0;s[1][1]=lo>>>0;lo=s[2][1]+c_lo;s[2][0]=s[2][0]+c_hi+(lo/4294967296>>>0)>>>0;s[2][1]=lo>>>0;lo=s[3][1]+d_lo;s[3][0]=s[3][0]+d_hi+(lo/4294967296>>>0)>>>0;s[3][1]=lo>>>0;lo=s[4][1]+e_lo;s[4][0]=s[4][0]+e_hi+(lo/4294967296>>>0)>>>0;s[4][1]=lo>>>0;lo=s[5][1]+f_lo;s[5][0]=s[5][0]+f_hi+(lo/4294967296>>>0)>>>0;s[5][1]=lo>>>0;lo=s[6][1]+g_lo;s[6][0]=s[6][0]+g_hi+(lo/4294967296>>>0)>>>0;s[6][1]=lo>>>0;lo=s[7][1]+h_lo;s[7][0]=s[7][0]+h_hi+(lo/4294967296>>>0)>>>0;s[7][1]=lo>>>0;len-=128}}},{"./forge":16,"./md":23,"./util":48}],45:[function(require,module,exports){var forge=require("./forge");require("./aes");require("./hmac");require("./md5");require("./sha1");require("./util");var ssh=module.exports=forge.ssh=forge.ssh||{};ssh.privateKeyToPutty=function(privateKey,passphrase,comment){comment=comment||"";passphrase=passphrase||"";var algorithm="ssh-rsa";var encryptionAlgorithm=passphrase===""?"none":"aes256-cbc";var ppk="PuTTY-User-Key-File-2: "+algorithm+"\r\n";ppk+="Encryption: "+encryptionAlgorithm+"\r\n";ppk+="Comment: "+comment+"\r\n";var pubbuffer=forge.util.createBuffer();_addStringToBuffer(pubbuffer,algorithm);_addBigIntegerToBuffer(pubbuffer,privateKey.e);_addBigIntegerToBuffer(pubbuffer,privateKey.n);var pub=forge.util.encode64(pubbuffer.bytes(),64);var length=Math.floor(pub.length/66)+1;ppk+="Public-Lines: "+length+"\r\n";ppk+=pub;var privbuffer=forge.util.createBuffer();_addBigIntegerToBuffer(privbuffer,privateKey.d);_addBigIntegerToBuffer(privbuffer,privateKey.p);_addBigIntegerToBuffer(privbuffer,privateKey.q);_addBigIntegerToBuffer(privbuffer,privateKey.qInv);var priv;if(!passphrase){priv=forge.util.encode64(privbuffer.bytes(),64)}else{var encLen=privbuffer.length()+16-1;encLen-=encLen%16;var padding=_sha1(privbuffer.bytes());padding.truncate(padding.length()-encLen+privbuffer.length());privbuffer.putBuffer(padding);var aeskey=forge.util.createBuffer();aeskey.putBuffer(_sha1("\0\0\0\0",passphrase));aeskey.putBuffer(_sha1("\0\0\0",passphrase));var cipher=forge.aes.createEncryptionCipher(aeskey.truncate(8),"CBC");cipher.start(forge.util.createBuffer().fillWithByte(0,16));cipher.update(privbuffer.copy());cipher.finish();var encrypted=cipher.output;encrypted.truncate(16);priv=forge.util.encode64(encrypted.bytes(),64)}length=Math.floor(priv.length/66)+1;ppk+="\r\nPrivate-Lines: "+length+"\r\n";ppk+=priv;var mackey=_sha1("putty-private-key-file-mac-key",passphrase);var macbuffer=forge.util.createBuffer();_addStringToBuffer(macbuffer,algorithm);_addStringToBuffer(macbuffer,encryptionAlgorithm);_addStringToBuffer(macbuffer,comment);macbuffer.putInt32(pubbuffer.length());macbuffer.putBuffer(pubbuffer);macbuffer.putInt32(privbuffer.length());macbuffer.putBuffer(privbuffer);var hmac=forge.hmac.create();hmac.start("sha1",mackey);hmac.update(macbuffer.bytes());ppk+="\r\nPrivate-MAC: "+hmac.digest().toHex()+"\r\n";return ppk};ssh.publicKeyToOpenSSH=function(key,comment){var type="ssh-rsa";comment=comment||"";var buffer=forge.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);return type+" "+forge.util.encode64(buffer.bytes())+" "+comment};ssh.privateKeyToOpenSSH=function(privateKey,passphrase){if(!passphrase){return forge.pki.privateKeyToPem(privateKey)}return forge.pki.encryptRsaPrivateKey(privateKey,passphrase,{legacy:true,algorithm:"aes128"})};ssh.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge.md.md5.create();var type="ssh-rsa";var buffer=forge.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);md.start();md.update(buffer.getBytes());var digest=md.digest();if(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};function _addBigIntegerToBuffer(buffer,val){var hexVal=val.toString(16);if(hexVal[0]>="8"){hexVal="00"+hexVal}var bytes=forge.util.hexToBytes(hexVal);buffer.putInt32(bytes.length);buffer.putBytes(bytes)}function _addStringToBuffer(buffer,val){buffer.putInt32(val.length);buffer.putString(val)}function _sha1(){var sha=forge.md.sha1.create();var num=arguments.length;for(var i=0;i=1){forge.log.verbose(cat,"[%s][%s] init",this.id,this.name,this)}};Task.prototype.debug=function(msg){msg=msg||"";forge.log.debug(cat,msg,"[%s][%s] task:",this.id,this.name,this,"subtasks:",this.subtasks.length,"queue:",sTaskQueues)};Task.prototype.next=function(name,subrun){if(typeof name==="function"){subrun=name;name=this.name}var subtask=new Task({run:subrun,name:name,parent:this});subtask.state=RUNNING;subtask.type=this.type;subtask.successCallback=this.successCallback||null;subtask.failureCallback=this.failureCallback||null;this.subtasks.push(subtask);return this};Task.prototype.parallel=function(name,subrun){if(forge.util.isArray(name)){subrun=name;name=this.name}return this.next(name,function(task){var ptask=task;ptask.block(subrun.length);var startParallelTask=function(pname,pi){forge.task.start({type:pname,run:function(task){subrun[pi](task)},success:function(task){ptask.unblock()},failure:function(task){ptask.unblock()}})};for(var i=0;i0){this.state=sStateTable[this.state][BLOCK]}};Task.prototype.unblock=function(n){n=typeof n==="undefined"?1:n;this.blocks-=n;if(this.blocks===0&&this.state!==DONE){this.state=RUNNING;runNext(this,0)}return this.blocks};Task.prototype.sleep=function(n){n=typeof n==="undefined"?0:n;this.state=sStateTable[this.state][SLEEP];var self=this;this.timeoutId=setTimeout(function(){self.timeoutId=null;self.state=RUNNING;runNext(self,0)},n)};Task.prototype.wait=function(cond){cond.wait(this)};Task.prototype.wakeup=function(){if(this.state===SLEEPING){cancelTimeout(this.timeoutId);this.timeoutId=null;this.state=RUNNING;runNext(this,0)}};Task.prototype.cancel=function(){this.state=sStateTable[this.state][CANCEL];this.permitsNeeded=0;if(this.timeoutId!==null){cancelTimeout(this.timeoutId);this.timeoutId=null}this.subtasks=[]};Task.prototype.fail=function(next){this.error=true;finish(this,true);if(next){next.error=this.error;next.swapTime=this.swapTime;next.userData=this.userData;runNext(next,0)}else{if(this.parent!==null){var parent=this.parent;while(parent.parent!==null){parent.error=this.error;parent.swapTime=this.swapTime;parent.userData=this.userData;parent=parent.parent}finish(parent,true)}if(this.failureCallback){this.failureCallback(this)}}};var start=function(task){task.error=false;task.state=sStateTable[task.state][START];setTimeout(function(){if(task.state===RUNNING){task.swapTime=+new Date;task.run(task);runNext(task,0)}},0)};var runNext=function(task,recurse){var swap=recurse>sMaxRecursions||+new Date-task.swapTime>sTimeSlice;var doNext=function(recurse){recurse++;if(task.state===RUNNING){if(swap){task.swapTime=+new Date}if(task.subtasks.length>0){var subtask=task.subtasks.shift();subtask.error=task.error;subtask.swapTime=task.swapTime;subtask.userData=task.userData;subtask.run(subtask);if(!subtask.error){runNext(subtask,recurse)}}else{finish(task);if(!task.error){if(task.parent!==null){task.parent.error=task.error;task.parent.swapTime=task.swapTime;task.parent.userData=task.userData;runNext(task.parent,recurse)}}}}};if(swap){setTimeout(doNext,0)}else{doNext(recurse)}};var finish=function(task,suppressCallbacks){task.state=DONE;delete sTasks[task.id];if(sVL>=1){forge.log.verbose(cat,"[%s][%s] finish",task.id,task.name,task)}if(task.parent===null){if(!(task.type in sTaskQueues)){forge.log.error(cat,"[%s][%s] task queue missing [%s]",task.id,task.name,task.type)}else if(sTaskQueues[task.type].length===0){forge.log.error(cat,"[%s][%s] task queue empty [%s]",task.id,task.name,task.type)}else if(sTaskQueues[task.type][0]!==task){forge.log.error(cat,"[%s][%s] task not first in queue [%s]",task.id,task.name,task.type)}else{sTaskQueues[task.type].shift();if(sTaskQueues[task.type].length===0){if(sVL>=1){forge.log.verbose(cat,"[%s][%s] delete queue [%s]",task.id,task.name,task.type)}delete sTaskQueues[task.type]}else{if(sVL>=1){forge.log.verbose(cat,"[%s][%s] queue start next [%s] remain:%s",task.id,task.name,task.type,sTaskQueues[task.type].length)}sTaskQueues[task.type][0].start()}}if(!suppressCallbacks){if(task.error&&task.failureCallback){task.failureCallback(task)}else if(!task.error&&task.successCallback){task.successCallback(task)}}}};module.exports=forge.task=forge.task||{};forge.task.start=function(options){var task=new Task({run:options.run,name:options.name||sNoTaskName});task.type=options.type;task.successCallback=options.success||null;task.failureCallback=options.failure||null;if(!(task.type in sTaskQueues)){if(sVL>=1){forge.log.verbose(cat,"[%s][%s] create queue [%s]",task.id,task.name,task.type)}sTaskQueues[task.type]=[task];start(task)}else{sTaskQueues[options.type].push(task)}};forge.task.cancel=function(type){if(type in sTaskQueues){sTaskQueues[type]=[sTaskQueues[type][0]]}};forge.task.createCondition=function(){var cond={tasks:{}};cond.wait=function(task){if(!(task.id in cond.tasks)){task.block();cond.tasks[task.id]=task}};cond.notify=function(){var tmp=cond.tasks;cond.tasks={};for(var id in tmp){tmp[id].unblock()}};return cond}},{"./debug":13,"./forge":16,"./log":21,"./util":48}],47:[function(require,module,exports){var forge=require("./forge");require("./asn1");require("./hmac");require("./md5");require("./pem");require("./pki");require("./random");require("./sha1");require("./util");var prf_TLS1=function(secret,label,seed,length){var rval=forge.util.createBuffer();var idx=secret.length>>1;var slen=idx+(secret.length&1);var s1=secret.substr(0,slen);var s2=secret.substr(idx,slen);var ai=forge.util.createBuffer();var hmac=forge.hmac.create();seed=label+seed;var md5itr=Math.ceil(length/16);var sha1itr=Math.ceil(length/20);hmac.start("MD5",s1);var md5bytes=forge.util.createBuffer();ai.putBytes(seed);for(var i=0;i0){tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.no_renegotiation}));tls.flush(c)}c.process()};tls.parseHelloMessage=function(c,record,length){var msg=null;var client=c.entity===tls.ConnectionEnd.client;if(length<38){c.error(c,{message:client?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}else{var b=record.fragment;var remaining=b.length();msg={version:{major:b.getByte(),minor:b.getByte()},random:forge.util.createBuffer(b.getBytes(32)),session_id:readVector(b,1),extensions:[]};if(client){msg.cipher_suite=b.getBytes(2);msg.compression_method=b.getByte()}else{msg.cipher_suites=readVector(b,2);msg.compression_methods=readVector(b,1)}remaining=length-(remaining-b.length());if(remaining>0){var exts=readVector(b,2);while(exts.length()>0){msg.extensions.push({type:[exts.getByte(),exts.getByte()],data:readVector(exts,2)})}if(!client){for(var i=0;i0){var snType=snl.getByte();if(snType!==0){break}c.session.extensions.server_name.serverNameList.push(readVector(snl,2).getBytes())}}}}}if(c.session.version){if(msg.version.major!==c.session.version.major||msg.version.minor!==c.session.version.minor){return c.error(c,{message:"TLS version change is disallowed during renegotiation.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}}if(client){c.session.cipherSuite=tls.getCipherSuite(msg.cipher_suite)}else{var tmp=forge.util.createBuffer(msg.cipher_suites.bytes());while(tmp.length()>0){c.session.cipherSuite=tls.getCipherSuite(tmp.getBytes(2));if(c.session.cipherSuite!==null){break}}}if(c.session.cipherSuite===null){return c.error(c,{message:"No cipher suites in common.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure},cipherSuite:forge.util.bytesToHex(msg.cipher_suite)})}if(client){c.session.compressionMethod=msg.compression_method}else{c.session.compressionMethod=tls.CompressionMethod.none}}return msg};tls.createSecurityParameters=function(c,msg){var client=c.entity===tls.ConnectionEnd.client;var msgRandom=msg.random.bytes();var cRandom=client?c.session.sp.client_random:msgRandom;var sRandom=client?msgRandom:tls.createRandom().getBytes();c.session.sp={entity:c.entity,prf_algorithm:tls.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:c.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:cRandom,server_random:sRandom}};tls.handleServerHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(c.fail){return}if(msg.version.minor<=c.version.minor){c.version.minor=msg.version.minor}else{return c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}c.session.version=c.version;var sessionId=msg.session_id.bytes();if(sessionId.length>0&&sessionId===c.session.id){c.expect=SCC;c.session.resuming=true;c.session.sp.server_random=msg.random.bytes()}else{c.expect=SCE;c.session.resuming=false;tls.createSecurityParameters(c,msg)}c.session.id=sessionId;c.process()};tls.handleClientHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(c.fail){return}var sessionId=msg.session_id.bytes();var session=null;if(c.sessionCache){session=c.sessionCache.getSession(sessionId);if(session===null){sessionId=""}else if(session.version.major!==msg.version.major||session.version.minor>msg.version.minor){session=null;sessionId=""}}if(sessionId.length===0){sessionId=forge.random.getBytes(32)}c.session.id=sessionId;c.session.clientHelloVersion=msg.version;c.session.sp={};if(session){c.version=c.session.version=session.version;c.session.sp=session.sp}else{var version;for(var i=1;i0){cert=readVector(msg.certificate_list,3);asn1=forge.asn1.fromDer(cert);cert=forge.pki.certificateFromAsn1(asn1,true);certs.push(cert)}}catch(ex){return c.error(c,{message:"Could not parse certificate list.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_certificate}})}var client=c.entity===tls.ConnectionEnd.client;if((client||c.verifyClient===true)&&certs.length===0){c.error(c,{message:client?"No server certificate provided.":"No client certificate provided.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}else if(certs.length===0){c.expect=client?SKE:CKE}else{if(client){c.session.serverCertificate=certs[0]}else{c.session.clientCertificate=certs[0]}if(tls.verifyCertificateChain(c,certs)){c.expect=client?SKE:CKE}}c.process()};tls.handleServerKeyExchange=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}})}c.expect=SCR;c.process()};tls.handleClientKeyExchange=function(c,record,length){if(length<48){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}})}var b=record.fragment;var msg={enc_pre_master_secret:readVector(b,2).getBytes()};var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.serverCertificate);privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}}if(privateKey===null){return c.error(c,{message:"No private key set.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}try{var sp=c.session.sp;sp.pre_master_secret=privateKey.decrypt(msg.enc_pre_master_secret);var version=c.session.clientHelloVersion;if(version.major!==sp.pre_master_secret.charCodeAt(0)||version.minor!==sp.pre_master_secret.charCodeAt(1)){throw new Error("TLS version rollback attack detected.")}}catch(ex){sp.pre_master_secret=forge.random.getBytes(48)}c.expect=CCC;if(c.session.clientCertificate!==null){c.expect=CCV}c.process()};tls.handleCertificateRequest=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid CertificateRequest. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var b=record.fragment;var msg={certificate_types:readVector(b,1),certificate_authorities:readVector(b,2)};c.session.certificateRequest=msg;c.expect=SHD;c.process()};tls.handleCertificateVerify=function(c,record,length){if(length<2){return c.error(c,{message:"Invalid CertificateVerify. Message too short.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var msg={signature:readVector(b,2).getBytes()};var verify=forge.util.createBuffer();verify.putBuffer(c.session.md5.digest());verify.putBuffer(c.session.sha1.digest());verify=verify.getBytes();try{var cert=c.session.clientCertificate;if(!cert.publicKey.verify(verify,msg.signature,"NONE")){throw new Error("CertificateVerify signature does not match.")}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes)}catch(ex){return c.error(c,{message:"Bad signature in CertificateVerify.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure}})}c.expect=CCC;c.process()};tls.handleServerHelloDone=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid ServerHelloDone message. Invalid length.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.record_overflow}})}if(c.serverCertificate===null){var error={message:"No server certificate provided. Not enough security.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.insufficient_security}};var depth=0;var ret=c.verify(c,error.alert.description,depth,[]);if(ret!==true){if(ret||ret===0){if(typeof ret==="object"&&!forge.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}}else if(typeof ret==="number"){error.alert.description=ret}}return c.error(c,error)}}if(c.session.certificateRequest!==null){record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificate(c)});tls.queue(c,record)}record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientKeyExchange(c)});tls.queue(c,record);c.expect=SER;var callback=function(c,signature){if(c.session.certificateRequest!==null&&c.session.clientCertificate!==null){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificateVerify(c,signature)}))}tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()}));c.state.pending=tls.createConnectionState(c);c.state.current.write=c.state.pending.write;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}));c.expect=SCC;tls.flush(c);c.process()};if(c.session.certificateRequest===null||c.session.clientCertificate===null){return callback(c,null)}tls.getClientSignature(c,callback)};tls.handleChangeCipherSpec=function(c,record){if(record.fragment.getByte()!==1){return c.error(c,{message:"Invalid ChangeCipherSpec message received.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}})}var client=c.entity===tls.ConnectionEnd.client;if(c.session.resuming&&client||!c.session.resuming&&!client){c.state.pending=tls.createConnectionState(c)}c.state.current.read=c.state.pending.read;if(!c.session.resuming&&client||c.session.resuming&&!client){c.state.pending=null}c.expect=client?SFI:CFI;c.process()};tls.handleFinished=function(c,record,length){var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var vd=record.fragment.getBytes();b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client;var label=client?"server finished":"client finished";var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;b=prf(sp.master_secret,label,b.getBytes(),vdl);if(b.getBytes()!==vd){return c.error(c,{message:"Invalid verify_data in Finished message.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decrypt_error}})}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes);if(c.session.resuming&&client||!c.session.resuming&&!client){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()}));c.state.current.write=c.state.pending.write;c.state.pending=null;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}))}c.expect=client?SAD:CAD;c.handshaking=false;++c.handshakes;c.peerCertificate=client?c.session.serverCertificate:c.session.clientCertificate;tls.flush(c);c.isConnected=true;c.connected(c);c.process()};tls.handleAlert=function(c,record){var b=record.fragment;var alert={level:b.getByte(),description:b.getByte()};var msg;switch(alert.description){case tls.Alert.Description.close_notify:msg="Connection closed.";break;case tls.Alert.Description.unexpected_message:msg="Unexpected message.";break;case tls.Alert.Description.bad_record_mac:msg="Bad record MAC.";break;case tls.Alert.Description.decryption_failed:msg="Decryption failed.";break;case tls.Alert.Description.record_overflow:msg="Record overflow.";break;case tls.Alert.Description.decompression_failure:msg="Decompression failed.";break;case tls.Alert.Description.handshake_failure:msg="Handshake failure.";break;case tls.Alert.Description.bad_certificate:msg="Bad certificate.";break;case tls.Alert.Description.unsupported_certificate:msg="Unsupported certificate.";break;case tls.Alert.Description.certificate_revoked:msg="Certificate revoked.";break;case tls.Alert.Description.certificate_expired:msg="Certificate expired.";break;case tls.Alert.Description.certificate_unknown:msg="Certificate unknown.";break;case tls.Alert.Description.illegal_parameter:msg="Illegal parameter.";break;case tls.Alert.Description.unknown_ca:msg="Unknown certificate authority.";break;case tls.Alert.Description.access_denied:msg="Access denied.";break;case tls.Alert.Description.decode_error:msg="Decode error.";break;case tls.Alert.Description.decrypt_error:msg="Decrypt error.";break;case tls.Alert.Description.export_restriction:msg="Export restriction.";break;case tls.Alert.Description.protocol_version:msg="Unsupported protocol version.";break;case tls.Alert.Description.insufficient_security:msg="Insufficient security.";break;case tls.Alert.Description.internal_error:msg="Internal error.";break;case tls.Alert.Description.user_canceled:msg="User canceled.";break;case tls.Alert.Description.no_renegotiation:msg="Renegotiation not supported.";break;default:msg="Unknown error.";break}if(alert.description===tls.Alert.Description.close_notify){return c.close()}c.error(c,{message:msg,send:false,origin:c.entity===tls.ConnectionEnd.client?"server":"client",alert:alert});c.process()};tls.handleHandshake=function(c,record){var b=record.fragment;var type=b.getByte();var length=b.getInt24();if(length>b.length()){c.fragmented=record;record.fragment=forge.util.createBuffer();b.read-=4;return c.process()}c.fragmented=null;b.read-=4;var bytes=b.bytes(length+4);b.read+=4;if(type in hsTable[c.entity][c.expect]){if(c.entity===tls.ConnectionEnd.server&&!c.open&&!c.fail){c.handshaking=true;c.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:forge.md.md5.create(),sha1:forge.md.sha1.create()}}if(type!==tls.HandshakeType.hello_request&&type!==tls.HandshakeType.certificate_verify&&type!==tls.HandshakeType.finished){c.session.md5.update(bytes);c.session.sha1.update(bytes)}hsTable[c.entity][c.expect][type](c,record,length)}else{tls.handleUnexpected(c,record)}};tls.handleApplicationData=function(c,record){c.data.putBuffer(record.fragment);c.dataReady(c);c.process()};tls.handleHeartbeat=function(c,record){var b=record.fragment;var type=b.getByte();var length=b.getInt16();var payload=b.getBytes(length);if(type===tls.HeartbeatMessageType.heartbeat_request){if(c.handshaking||length>payload.length){return c.process()}tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_response,payload)}));tls.flush(c)}else if(type===tls.HeartbeatMessageType.heartbeat_response){if(payload!==c.expectedHeartbeatPayload){return c.process()}if(c.heartbeatReceived){c.heartbeatReceived(c,forge.util.createBuffer(payload))}}c.process()};var SHE=0;var SCE=1;var SKE=2;var SCR=3;var SHD=4;var SCC=5;var SFI=6;var SAD=7;var SER=8;var CHE=0;var CCE=1;var CKE=2;var CCV=3;var CCC=4;var CFI=5;var CAD=6;var CER=7;var __=tls.handleUnexpected;var R0=tls.handleChangeCipherSpec;var R1=tls.handleAlert;var R2=tls.handleHandshake;var R3=tls.handleApplicationData;var R4=tls.handleHeartbeat;var ctTable=[];ctTable[tls.ConnectionEnd.client]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]];ctTable[tls.ConnectionEnd.server]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]];var H0=tls.handleHelloRequest;var H1=tls.handleServerHello;var H2=tls.handleCertificate;var H3=tls.handleServerKeyExchange;var H4=tls.handleCertificateRequest;var H5=tls.handleServerHelloDone;var H6=tls.handleFinished;var hsTable=[];hsTable[tls.ConnectionEnd.client]=[[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];var H7=tls.handleClientHello;var H8=tls.handleClientKeyExchange;var H9=tls.handleCertificateVerify;hsTable[tls.ConnectionEnd.server]=[[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];tls.generateKeys=function(c,sp){var prf=prf_TLS1;var random=sp.client_random+sp.server_random;if(!c.session.resuming){sp.master_secret=prf(sp.pre_master_secret,"master secret",random,48).bytes();sp.pre_master_secret=null}random=sp.server_random+sp.client_random;var length=2*sp.mac_key_length+2*sp.enc_key_length;var tls10=c.version.major===tls.Versions.TLS_1_0.major&&c.version.minor===tls.Versions.TLS_1_0.minor;if(tls10){length+=2*sp.fixed_iv_length}var km=prf(sp.master_secret,"key expansion",random,length);var rval={client_write_MAC_key:km.getBytes(sp.mac_key_length),server_write_MAC_key:km.getBytes(sp.mac_key_length),client_write_key:km.getBytes(sp.enc_key_length),server_write_key:km.getBytes(sp.enc_key_length)};if(tls10){rval.client_write_IV=km.getBytes(sp.fixed_iv_length);rval.server_write_IV=km.getBytes(sp.fixed_iv_length)}return rval};tls.createConnectionState=function(c){var client=c.entity===tls.ConnectionEnd.client;var createMode=function(){var mode={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(record){return true},compressionState:null,compressFunction:function(record){return true},updateSequenceNumber:function(){if(mode.sequenceNumber[1]===4294967295){mode.sequenceNumber[1]=0;++mode.sequenceNumber[0]}else{++mode.sequenceNumber[1]}}};return mode};var state={read:createMode(),write:createMode()};state.read.update=function(c,record){if(!state.read.cipherFunction(record,state.read)){c.error(c,{message:"Could not decrypt record or bad MAC.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_record_mac}})}else if(!state.read.compressFunction(c,record,state.read)){c.error(c,{message:"Could not decompress record.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decompression_failure}})}return!c.fail};state.write.update=function(c,record){if(!state.write.compressFunction(c,record,state.write)){c.error(c,{message:"Could not compress record.",send:false,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}else if(!state.write.cipherFunction(record,state.write)){c.error(c,{message:"Could not encrypt record.",send:false,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}return!c.fail};if(c.session){var sp=c.session.sp;c.session.cipherSuite.initSecurityParameters(sp);sp.keys=tls.generateKeys(c,sp);state.read.macKey=client?sp.keys.server_write_MAC_key:sp.keys.client_write_MAC_key;state.write.macKey=client?sp.keys.client_write_MAC_key:sp.keys.server_write_MAC_key;c.session.cipherSuite.initConnectionState(state,c,sp);switch(sp.compression_algorithm){case tls.CompressionMethod.none:break;case tls.CompressionMethod.deflate:state.read.compressFunction=inflate;state.write.compressFunction=deflate;break;default:throw new Error("Unsupported compression algorithm.")}}return state};tls.createRandom=function(){var d=new Date;var utc=+d+d.getTimezoneOffset()*6e4;var rval=forge.util.createBuffer();rval.putInt32(utc);rval.putBytes(forge.random.getBytes(28));return rval};tls.createRecord=function(c,options){if(!options.data){return null}var record={type:options.type,version:{major:c.version.major,minor:c.version.minor},length:options.data.length(),fragment:options.data};return record};tls.createAlert=function(c,alert){var b=forge.util.createBuffer();b.putByte(alert.level);b.putByte(alert.description);return tls.createRecord(c,{type:tls.ContentType.alert,data:b})};tls.createClientHello=function(c){c.session.clientHelloVersion={major:c.version.major,minor:c.version.minor};var cipherSuites=forge.util.createBuffer();for(var i=0;i0){extLength+=2}var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+cSuites+1+cMethods+extLength;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.client_hello);rval.putInt24(length);rval.putByte(c.version.major);rval.putByte(c.version.minor);rval.putBytes(c.session.sp.client_random);writeVector(rval,1,forge.util.createBuffer(sessionId));writeVector(rval,2,cipherSuites);writeVector(rval,1,compressionMethods);if(extLength>0){writeVector(rval,2,extensions)}return rval};tls.createServerHello=function(c){var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+1;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.server_hello);rval.putInt24(length);rval.putByte(c.version.major);rval.putByte(c.version.minor);rval.putBytes(c.session.sp.server_random);writeVector(rval,1,forge.util.createBuffer(sessionId));rval.putByte(c.session.cipherSuite.id[0]);rval.putByte(c.session.cipherSuite.id[1]);rval.putByte(c.session.compressionMethod);return rval};tls.createCertificate=function(c){var client=c.entity===tls.ConnectionEnd.client;var cert=null;if(c.getCertificate){var hint;if(client){hint=c.session.certificateRequest}else{hint=c.session.extensions.server_name.serverNameList}cert=c.getCertificate(c,hint)}var certList=forge.util.createBuffer();if(cert!==null){try{if(!forge.util.isArray(cert)){cert=[cert]}var asn1=null;for(var i=0;i0){rval.putByte(tls.HandshakeType.server_key_exchange);rval.putInt24(length)}return rval};tls.getClientSignature=function(c,callback){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());b=b.getBytes();c.getSignature=c.getSignature||function(c,b,callback){var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.clientCertificate);privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}}if(privateKey===null){c.error(c,{message:"No private key set.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}else{b=privateKey.sign(b,null)}callback(c,b)};c.getSignature(c,b,callback)};tls.createCertificateVerify=function(c,signature){var length=signature.length+2;var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.certificate_verify);rval.putInt24(length);rval.putInt16(signature.length);rval.putBytes(signature);return rval};tls.createCertificateRequest=function(c){var certTypes=forge.util.createBuffer();certTypes.putByte(1);var cAs=forge.util.createBuffer();for(var key in c.caStore.certs){var cert=c.caStore.certs[key];var dn=forge.pki.distinguishedNameToAsn1(cert.subject);var byteBuffer=forge.asn1.toDer(dn);cAs.putInt16(byteBuffer.length());cAs.putBuffer(byteBuffer)}var length=1+certTypes.length()+2+cAs.length();var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.certificate_request);rval.putInt24(length);writeVector(rval,1,certTypes);writeVector(rval,2,cAs);return rval};tls.createServerHelloDone=function(c){var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.server_hello_done);rval.putInt24(0);return rval};tls.createChangeCipherSpec=function(){var rval=forge.util.createBuffer();rval.putByte(1);return rval};tls.createFinished=function(c){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest());b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client;var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;var label=client?"client finished":"server finished";b=prf(sp.master_secret,label,b.getBytes(),vdl);var rval=forge.util.createBuffer();rval.putByte(tls.HandshakeType.finished);rval.putInt24(b.length());rval.putBuffer(b);return rval};tls.createHeartbeat=function(type,payload,payloadLength){if(typeof payloadLength==="undefined"){payloadLength=payload.length}var rval=forge.util.createBuffer();rval.putByte(type);rval.putInt16(payloadLength);rval.putBytes(payload);var plaintextLength=rval.length();var paddingLength=Math.max(16,plaintextLength-payloadLength-3);rval.putBytes(forge.random.getBytes(paddingLength));return rval};tls.queue=function(c,record){if(!record){return}if(record.fragment.length()===0){if(record.type===tls.ContentType.handshake||record.type===tls.ContentType.alert||record.type===tls.ContentType.change_cipher_spec){return}}if(record.type===tls.ContentType.handshake){var bytes=record.fragment.bytes();c.session.md5.update(bytes);c.session.sha1.update(bytes);bytes=null}var records;if(record.fragment.length()<=tls.MaxFragment){records=[record]}else{records=[];var data=record.fragment.bytes();while(data.length>tls.MaxFragment){records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data.slice(0,tls.MaxFragment))}));data=data.slice(tls.MaxFragment)}if(data.length>0){records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data)}))}}for(var i=0;i0){key=rval.order[0]}if(key!==null&&key in rval.cache){session=rval.cache[key];delete rval.cache[key];for(var i in rval.order){if(rval.order[i]===key){rval.order.splice(i,1);break}}}return session};rval.setSession=function(sessionId,session){if(rval.order.length===rval.capacity){var key=rval.order.shift();delete rval.cache[key]}var key=forge.util.bytesToHex(sessionId);rval.order.push(key);rval.cache[key]=session}}return rval};tls.createConnection=function(options){var caStore=null;if(options.caStore){if(forge.util.isArray(options.caStore)){caStore=forge.pki.createCaStore(options.caStore)}else{caStore=options.caStore}}else{caStore=forge.pki.createCaStore()}var cipherSuites=options.cipherSuites||null;if(cipherSuites===null){cipherSuites=[];for(var key in tls.CipherSuites){cipherSuites.push(tls.CipherSuites[key])}}var entity=options.server||false?tls.ConnectionEnd.server:tls.ConnectionEnd.client;var sessionCache=options.sessionCache?tls.createSessionCache(options.sessionCache):null;var c={version:{major:tls.Version.major,minor:tls.Version.minor},entity:entity,sessionId:options.sessionId,caStore:caStore,sessionCache:sessionCache,cipherSuites:cipherSuites,connected:options.connected,virtualHost:options.virtualHost||null,verifyClient:options.verifyClient||false,verify:options.verify||function(cn,vfd,dpth,cts){return vfd},verifyOptions:options.verifyOptions||{},getCertificate:options.getCertificate||null,getPrivateKey:options.getPrivateKey||null,getSignature:options.getSignature||null,input:forge.util.createBuffer(),tlsData:forge.util.createBuffer(),data:forge.util.createBuffer(),tlsDataReady:options.tlsDataReady,dataReady:options.dataReady,heartbeatReceived:options.heartbeatReceived,closed:options.closed,error:function(c,ex){ex.origin=ex.origin||(c.entity===tls.ConnectionEnd.client?"client":"server");if(ex.send){tls.queue(c,tls.createAlert(c,ex.alert));tls.flush(c)}var fatal=ex.fatal!==false;if(fatal){c.fail=true}options.error(c,ex);if(fatal){c.close(false)}},deflate:options.deflate||null,inflate:options.inflate||null};c.reset=function(clearFail){c.version={major:tls.Version.major,minor:tls.Version.minor};c.record=null;c.session=null;c.peerCertificate=null;c.state={pending:null,current:null};c.expect=c.entity===tls.ConnectionEnd.client?SHE:CHE;c.fragmented=null;c.records=[];c.open=false;c.handshakes=0;c.handshaking=false;c.isConnected=false;c.fail=!(clearFail||typeof clearFail==="undefined");c.input.clear();c.tlsData.clear();c.data.clear();c.state.current=tls.createConnectionState(c)};c.reset();var _update=function(c,record){var aligned=record.type-tls.ContentType.change_cipher_spec;var handlers=ctTable[c.entity][c.expect];if(aligned in handlers){handlers[aligned](c,record)}else{tls.handleUnexpected(c,record)}};var _readRecordHeader=function(c){var rval=0;var b=c.input;var len=b.length();if(len<5){rval=5-len}else{c.record={type:b.getByte(),version:{major:b.getByte(),minor:b.getByte()},length:b.getInt16(),fragment:forge.util.createBuffer(),ready:false};var compatibleVersion=c.record.version.major===c.version.major;if(compatibleVersion&&c.session&&c.session.version){compatibleVersion=c.record.version.minor===c.version.minor}if(!compatibleVersion){c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}}return rval};var _readRecord=function(c){var rval=0;var b=c.input;var len=b.length();if(len0){if(c.sessionCache){session=c.sessionCache.getSession(sessionId)}if(session===null){sessionId=""}}if(sessionId.length===0&&c.sessionCache){session=c.sessionCache.getSession();if(session!==null){sessionId=session.id}}c.session={id:sessionId,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:forge.md.md5.create(),sha1:forge.md.sha1.create()};if(session){c.version=session.version;c.session.sp=session.sp}c.session.sp.client_random=tls.createRandom().getBytes();c.open=true;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientHello(c)}));tls.flush(c)}};c.process=function(data){var rval=0;if(data){c.input.putBytes(data)}if(!c.fail){if(c.record!==null&&c.record.ready&&c.record.fragment.isEmpty()){c.record=null}if(c.record===null){rval=_readRecordHeader(c)}if(!c.fail&&c.record!==null&&!c.record.ready){rval=_readRecord(c)}if(!c.fail&&c.record!==null&&c.record.ready){_update(c,c.record)}}return rval};c.prepare=function(data){tls.queue(c,tls.createRecord(c,{type:tls.ContentType.application_data,data:forge.util.createBuffer(data)}));return tls.flush(c)};c.prepareHeartbeatRequest=function(payload,payloadLength){if(payload instanceof forge.util.ByteBuffer){payload=payload.bytes()}if(typeof payloadLength==="undefined"){payloadLength=payload.length}c.expectedHeartbeatPayload=payload;tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_request,payload,payloadLength)}));return tls.flush(c)};c.close=function(clearFail){if(!c.fail&&c.sessionCache&&c.session){var session={id:c.session.id,version:c.session.version,sp:c.session.sp};session.sp.keys=null;c.sessionCache.setSession(session.id,session)}if(c.open){c.open=false;c.input.clear();if(c.isConnected||c.handshaking){c.isConnected=c.handshaking=false;tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.close_notify}));tls.flush(c)}c.closed(c)}c.reset(clearFail)};return c};module.exports=forge.tls=forge.tls||{};for(var key in tls){if(typeof tls[key]!=="function"){forge.tls[key]=tls[key]}}forge.tls.prf_tls1=prf_TLS1;forge.tls.hmac_sha1=hmac_sha1;forge.tls.createSessionCache=tls.createSessionCache;forge.tls.createConnection=tls.createConnection},{"./asn1":9,"./forge":16,"./hmac":17,"./md5":24,"./pem":30,"./pki":35,"./random":39,"./sha1":42,"./util":48}],48:[function(require,module,exports){(function(process,global,Buffer,__argument0,__argument1,__argument2,__argument3,setImmediate){var forge=require("./forge");var baseN=require("./baseN");var util=module.exports=forge.util=forge.util||{};(function(){if(typeof process!=="undefined"&&process.nextTick&&!process.browser){util.nextTick=process.nextTick;if(typeof setImmediate==="function"){util.setImmediate=setImmediate}else{util.setImmediate=util.nextTick}return}if(typeof setImmediate==="function"){util.setImmediate=function(){return setImmediate.apply(undefined,arguments)};util.nextTick=function(callback){return setImmediate(callback)};return}util.setImmediate=function(callback){setTimeout(callback,0)};if(typeof window!=="undefined"&&typeof window.postMessage==="function"){var msg="forge.setImmediate";var callbacks=[];util.setImmediate=function(callback){callbacks.push(callback);if(callbacks.length===1){window.postMessage(msg,"*")}};function handler(event){if(event.source===window&&event.data===msg){event.stopPropagation();var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}}window.addEventListener("message",handler,true)}if(typeof MutationObserver!=="undefined"){var now=Date.now();var attr=true;var div=document.createElement("div");var callbacks=[];new MutationObserver(function(){var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}).observe(div,{attributes:true});var oldSetImmediate=util.setImmediate;util.setImmediate=function(callback){if(Date.now()-now>15){now=Date.now();oldSetImmediate(callback)}else{callbacks.push(callback);if(callbacks.length===1){div.setAttribute("a",attr=!attr)}}}}util.nextTick=util.setImmediate})();util.isNodejs=typeof process!=="undefined"&&process.versions&&process.versions.node;util.globalScope=function(){if(util.isNodejs){return global}return typeof self==="undefined"?window:self}();util.isArray=Array.isArray||function(x){return Object.prototype.toString.call(x)==="[object Array]"};util.isArrayBuffer=function(x){return typeof ArrayBuffer!=="undefined"&&x instanceof ArrayBuffer};util.isArrayBufferView=function(x){return x&&util.isArrayBuffer(x.buffer)&&x.byteLength!==undefined};function _checkBitsParam(n){if(!(n===8||n===16||n===24||n===32)){throw new Error("Only 8, 16, 24, or 32 bits supported: "+n)}}util.ByteBuffer=ByteStringBuffer;function ByteStringBuffer(b){this.data="";this.read=0;if(typeof b==="string"){this.data=b}else if(util.isArrayBuffer(b)||util.isArrayBufferView(b)){if(typeof Buffer!=="undefined"&&b instanceof Buffer){this.data=b.toString("binary")}else{var arr=new Uint8Array(b);try{this.data=String.fromCharCode.apply(null,arr)}catch(e){for(var i=0;i_MAX_CONSTRUCTED_STRING_LENGTH){this.data.substr(0,1);this._constructedStringLength=0}};util.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};util.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};util.ByteStringBuffer.prototype.putByte=function(b){return this.putBytes(String.fromCharCode(b))};util.ByteStringBuffer.prototype.fillWithByte=function(b,n){b=String.fromCharCode(b);var d=this.data;while(n>0){if(n&1){d+=b}n>>>=1;if(n>0){b+=b}}this.data=d;this._optimizeConstructedString(n);return this};util.ByteStringBuffer.prototype.putBytes=function(bytes){this.data+=bytes;this._optimizeConstructedString(bytes.length);return this};util.ByteStringBuffer.prototype.putString=function(str){return this.putBytes(util.encodeUtf8(str))};util.ByteStringBuffer.prototype.putInt16=function(i){return this.putBytes(String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt24=function(i){return this.putBytes(String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt32=function(i){return this.putBytes(String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt16Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255))};util.ByteStringBuffer.prototype.putInt24Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255))};util.ByteStringBuffer.prototype.putInt32Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>24&255))};util.ByteStringBuffer.prototype.putInt=function(i,n){_checkBitsParam(n);var bytes="";do{n-=8;bytes+=String.fromCharCode(i>>n&255)}while(n>0);return this.putBytes(bytes)};util.ByteStringBuffer.prototype.putSignedInt=function(i,n){if(i<0){i+=2<0);return rval};util.ByteStringBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<=max){x-=max<<1}return x};util.ByteStringBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.ByteStringBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.ByteStringBuffer.prototype.at=function(i){return this.data.charCodeAt(this.read+i)};util.ByteStringBuffer.prototype.setAt=function(i,b){this.data=this.data.substr(0,this.read+i)+String.fromCharCode(b)+this.data.substr(this.read+i+1);return this};util.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};util.ByteStringBuffer.prototype.copy=function(){var c=util.createBuffer(this.data);c.read=this.read;return c};util.ByteStringBuffer.prototype.compact=function(){if(this.read>0){this.data=this.data.slice(this.read);this.read=0}return this};util.ByteStringBuffer.prototype.clear=function(){this.data="";this.read=0;return this};util.ByteStringBuffer.prototype.truncate=function(count){var len=Math.max(0,this.length()-count);this.data=this.data.substr(this.read,len);this.read=0;return this};util.ByteStringBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i=amount){return this}growSize=Math.max(growSize||this.growSize,amount);var src=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);var dst=new Uint8Array(this.length()+growSize);dst.set(src);this.data=new DataView(dst.buffer);return this};util.DataBuffer.prototype.putByte=function(b){this.accommodate(1);this.data.setUint8(this.write++,b);return this};util.DataBuffer.prototype.fillWithByte=function(b,n){this.accommodate(n);for(var i=0;i>8&65535);this.data.setInt8(this.write,i>>16&255);this.write+=3;return this};util.DataBuffer.prototype.putInt32=function(i){this.accommodate(4);this.data.setInt32(this.write,i);this.write+=4;return this};util.DataBuffer.prototype.putInt16Le=function(i){this.accommodate(2);this.data.setInt16(this.write,i,true);this.write+=2;return this};util.DataBuffer.prototype.putInt24Le=function(i){this.accommodate(3);this.data.setInt8(this.write,i>>16&255);this.data.setInt16(this.write,i>>8&65535,true);this.write+=3;return this};util.DataBuffer.prototype.putInt32Le=function(i){this.accommodate(4);this.data.setInt32(this.write,i,true);this.write+=4;return this};util.DataBuffer.prototype.putInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);do{n-=8;this.data.setInt8(this.write++,i>>n&255)}while(n>0);return this};util.DataBuffer.prototype.putSignedInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);if(i<0){i+=2<0);return rval};util.DataBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<=max){x-=max<<1}return x};util.DataBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.DataBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.DataBuffer.prototype.at=function(i){return this.data.getUint8(this.read+i)};util.DataBuffer.prototype.setAt=function(i,b){this.data.setUint8(i,b);return this};util.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};util.DataBuffer.prototype.copy=function(){return new util.DataBuffer(this)};util.DataBuffer.prototype.compact=function(){if(this.read>0){var src=new Uint8Array(this.data.buffer,this.read);var dst=new Uint8Array(src.byteLength);dst.set(src);this.data=new DataView(dst);this.write-=this.read;this.read=0}return this};util.DataBuffer.prototype.clear=function(){this.data=new DataView(new ArrayBuffer(0));this.read=this.write=0;return this};util.DataBuffer.prototype.truncate=function(count){this.write=Math.max(0,this.length()-count);this.read=Math.min(this.read,this.write);return this};util.DataBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i0){if(n&1){s+=c}n>>>=1;if(n>0){c+=c}}return s};util.xorBytes=function(s1,s2,n){var s3="";var b="";var t="";var i=0;var c=0;for(;n>0;--n,++i){b=s1.charCodeAt(i)^s2.charCodeAt(i);if(c>=10){s3+=t;t="";c=0}t+=String.fromCharCode(b);++c}s3+=t;return s3};util.hexToBytes=function(hex){var rval="";var i=0;if(hex.length&1==1){i=1;rval+=String.fromCharCode(parseInt(hex[0],16))}for(;i>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var _base64Idx=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,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,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];var _base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util.encode64=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.decode64=function(input){input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");var output="";var enc1,enc2,enc3,enc4;var i=0;while(i>4);if(enc3!==64){output+=String.fromCharCode((enc2&15)<<4|enc3>>2);if(enc4!==64){output+=String.fromCharCode((enc3&3)<<6|enc4)}}}return output};util.encodeUtf8=function(str){return unescape(encodeURIComponent(str))};util.decodeUtf8=function(str){return decodeURIComponent(escape(str))};util.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}};util.binary.raw.encode=function(bytes){return String.fromCharCode.apply(null,bytes)};util.binary.raw.decode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j=offset;for(var i=0;i>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.binary.base64.decode=function(input,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(input.length/4)*3)}input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");offset=offset||0;var enc1,enc2,enc3,enc4;var i=0,j=offset;while(i>4;if(enc3!==64){out[j++]=(enc2&15)<<4|enc3>>2;if(enc4!==64){out[j++]=(enc3&3)<<6|enc4}}}return output?j-offset:out.subarray(0,j)};util.binary.base58.encode=function(input,maxline){return util.binary.baseN.encode(input,_base58,maxline)};util.binary.base58.decode=function(input,maxline){return util.binary.baseN.decode(input,_base58,maxline)};util.text={utf8:{},utf16:{}};util.text.utf8.encode=function(str,output,offset){str=util.encodeUtf8(str);var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j=offset;for(var i=0;i0){key=kvpairs[i].substring(0,pos);val=kvpairs[i].substring(pos+1)}else{key=kvpairs[i];val=null}if(!(key in rval)){rval[key]=[]}if(!(key in Object.prototype)&&val!==null){rval[key].push(unescape(val))}}return rval};var rval;if(typeof query==="undefined"){if(_queryVariables===null){if(typeof window!=="undefined"&&window.location&&window.location.search){_queryVariables=parse(window.location.search.substring(1))}else{_queryVariables={}}}rval=_queryVariables}else{rval=parse(query)}return rval};util.parseFragment=function(fragment){var fp=fragment;var fq="";var pos=fragment.indexOf("?");if(pos>0){fp=fragment.substring(0,pos);fq=fragment.substring(pos+1)}var path=fp.split("/");if(path.length>0&&path[0]===""){path.shift()}var query=fq===""?{}:util.getQueryVariables(fq);return{pathString:fp,queryString:fq,path:path,query:query}};util.makeRequest=function(reqString){var frag=util.parseFragment(reqString);var req={path:frag.pathString,query:frag.queryString,getPath:function(i){return typeof i==="undefined"?frag.path:frag.path[i]},getQuery:function(k,i){var rval;if(typeof k==="undefined"){rval=frag.query}else{rval=frag.query[k];if(rval&&typeof i!=="undefined"){rval=rval[i]}}return rval},getQueryLast:function(k,_default){var rval;var vals=req.getQuery(k);if(vals){rval=vals[vals.length-1]}else{rval=_default}return rval}};return req};util.makeLink=function(path,query,fragment){path=jQuery.isArray(path)?path.join("/"):path;var qstr=jQuery.param(query||{});fragment=fragment||"";return path+(qstr.length>0?"?"+qstr:"")+(fragment.length>0?"#"+fragment:"")};util.setPath=function(object,keys,value){if(typeof object==="object"&&object!==null){var i=0;var len=keys.length;while(i0){parts.push(part)}last=re.lastIndex;var code=match[0][1];switch(code){case"s":case"o":if(argi")}break;case"%":parts.push("%");break;default:parts.push("<%"+code+"?>")}}parts.push(format.substring(last));return parts.join("")};util.formatNumber=function(number,decimals,dec_point,thousands_sep){var n=number,c=isNaN(decimals=Math.abs(decimals))?2:decimals;var d=dec_point===undefined?",":dec_point;var t=thousands_sep===undefined?".":thousands_sep,s=n<0?"-":"";var i=parseInt(n=Math.abs(+n||0).toFixed(c),10)+"";var j=i.length>3?i.length%3:0;return s+(j?i.substr(0,j)+t:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"")};util.formatSize=function(size){if(size>=1073741824){size=util.formatNumber(size/1073741824,2,".","")+" GiB"}else if(size>=1048576){size=util.formatNumber(size/1048576,2,".","")+" MiB"}else if(size>=1024){size=util.formatNumber(size/1024,0)+" KiB"}else{size=util.formatNumber(size,0)+" bytes"}return size};util.bytesFromIP=function(ip){if(ip.indexOf(".")!==-1){return util.bytesFromIPv4(ip)}if(ip.indexOf(":")!==-1){return util.bytesFromIPv6(ip)}return null};util.bytesFromIPv4=function(ip){ip=ip.split(".");if(ip.length!==4){return null}var b=util.createBuffer();for(var i=0;izeroGroups[zeroMaxGroup].end-zeroGroups[zeroMaxGroup].start){zeroMaxGroup=zeroGroups.length-1}}}ip.push(hex)}if(zeroGroups.length>0){var group=zeroGroups[zeroMaxGroup];if(group.end-group.start>0){ip.splice(group.start,group.end-group.start+1,"");if(group.start===0){ip.unshift("")}if(group.end===7){ip.push("")}}}return ip.join(":")};util.estimateCores=function(options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};if("cores"in util&&!options.update){return callback(null,util.cores)}if(typeof navigator!=="undefined"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0){util.cores=navigator.hardwareConcurrency;return callback(null,util.cores)}if(typeof Worker==="undefined"){util.cores=1;return callback(null,util.cores)}if(typeof Blob==="undefined"){util.cores=2;return callback(null,util.cores)}var blobUrl=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){var st=Date.now();var et=st+4;while(Date.now()r2.st&&r1.str1.st&&r2.st2){throw new Error("Cannot read notBefore/notAfter validity times; more "+"than two times were provided in the certificate.")}if(validity.length<2){throw new Error("Cannot read notBefore/notAfter validity times; they "+"were not provided as either UTCTime or GeneralizedTime.")}cert.validity.notBefore=validity[0];cert.validity.notAfter=validity[1];cert.tbsCertificate=capture.tbsCertificate;if(computeHash){cert.md=null;if(cert.signatureOid in oids){var oid=oids[cert.signatureOid];switch(oid){case"sha1WithRSAEncryption":cert.md=forge.md.sha1.create();break;case"md5WithRSAEncryption":cert.md=forge.md.md5.create();break;case"sha256WithRSAEncryption":cert.md=forge.md.sha256.create();break;case"sha384WithRSAEncryption":cert.md=forge.md.sha384.create();break;case"sha512WithRSAEncryption":cert.md=forge.md.sha512.create();break;case"RSASSA-PSS":cert.md=forge.md.sha256.create();break}}if(cert.md===null){var error=new Error("Could not compute certificate digest. "+"Unknown signature OID.");error.signatureOid=cert.signatureOid;throw error}var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes())}var imd=forge.md.sha1.create();cert.issuer.getField=function(sn){return _getAttribute(cert.issuer,sn)};cert.issuer.addField=function(attr){_fillMissingFields([attr]);cert.issuer.attributes.push(attr)};cert.issuer.attributes=pki.RDNAttributesAsArray(capture.certIssuer,imd);if(capture.certIssuerUniqueId){cert.issuer.uniqueId=capture.certIssuerUniqueId}cert.issuer.hash=imd.digest().toHex();var smd=forge.md.sha1.create();cert.subject.getField=function(sn){return _getAttribute(cert.subject,sn)};cert.subject.addField=function(attr){_fillMissingFields([attr]);cert.subject.attributes.push(attr)};cert.subject.attributes=pki.RDNAttributesAsArray(capture.certSubject,smd);if(capture.certSubjectUniqueId){cert.subject.uniqueId=capture.certSubjectUniqueId}cert.subject.hash=smd.digest().toHex();if(capture.certExtensions){cert.extensions=pki.certificateExtensionsFromAsn1(capture.certExtensions)}else{cert.extensions=[]}cert.publicKey=pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);return cert};pki.certificateExtensionsFromAsn1=function(exts){var rval=[];for(var i=0;i1){b2=ev.value.charCodeAt(1);b3=ev.value.length>2?ev.value.charCodeAt(2):0}e.digitalSignature=(b2&128)===128;e.nonRepudiation=(b2&64)===64;e.keyEncipherment=(b2&32)===32;e.dataEncipherment=(b2&16)===16;e.keyAgreement=(b2&8)===8;e.keyCertSign=(b2&4)===4;e.cRLSign=(b2&2)===2;e.encipherOnly=(b2&1)===1;e.decipherOnly=(b3&128)===128}else if(e.name==="basicConstraints"){var ev=asn1.fromDer(e.value);if(ev.value.length>0&&ev.value[0].type===asn1.Type.BOOLEAN){e.cA=ev.value[0].value.charCodeAt(0)!==0}else{e.cA=false}var value=null;if(ev.value.length>0&&ev.value[0].type===asn1.Type.INTEGER){value=ev.value[0].value}else if(ev.value.length>1){value=ev.value[1].value}if(value!==null){e.pathLenConstraint=asn1.derToInteger(value)}}else if(e.name==="extKeyUsage"){var ev=asn1.fromDer(e.value);for(var vi=0;vi1){b2=ev.value.charCodeAt(1)}e.client=(b2&128)===128;e.server=(b2&64)===64;e.email=(b2&32)===32;e.objsign=(b2&16)===16;e.reserved=(b2&8)===8;e.sslCA=(b2&4)===4;e.emailCA=(b2&2)===2;e.objCA=(b2&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];var gn;var ev=asn1.fromDer(e.value);for(var n=0;n128){throw new Error('Invalid "nsComment" content.')}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.IA5STRING,false,e.comment)}else if(e.name==="subjectKeyIdentifier"&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex();e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ski.getBytes())}else if(e.name==="authorityKeyIdentifier"&&options.cert){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=e.keyIdentifier===true?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,false,keyIdentifier))}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,true,[_dnToAsn1(e.authorityCertIssuer===true?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,authorityCertIssuer))}if(e.serialNumber){var serialNumber=forge.util.hexToBytes(e.serialNumber===true?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,false,serialNumber))}}else if(e.name==="cRLDistributionPoints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;var subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);var altName;for(var n=0;n=jan_1_1950&&date0){tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions))}return tbs};pki.getCertificationRequestInfo=function(csr){var cri=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(csr.version).getBytes()),_dnToAsn1(csr.subject),pki.publicKeyToAsn1(csr.publicKey),_CRIAttributesToAsn1(csr)]);return cri};pki.distinguishedNameToAsn1=function(dn){return _dnToAsn1(dn)};pki.certificateToAsn1=function(cert){var tbsCertificate=cert.tbsCertificate||pki.getTBSCertificate(cert);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[tbsCertificate,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.signatureOid).getBytes()),_signatureParametersToAsn1(cert.signatureOid,cert.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.signature)])};pki.certificateExtensionsToAsn1=function(exts){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,3,true,[]);var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);rval.value.push(seq);for(var i=0;icert.validity.notAfter){error={message:"Certificate is not valid yet or has expired.",error:pki.certificateError.certificate_expired,notBefore:cert.validity.notBefore,notAfter:cert.validity.notAfter,now:validityCheckDate}}}if(error===null){parent=chain[0]||caStore.getIssuer(cert);if(parent===null){if(cert.isIssuer(cert)){selfSigned=true;parent=cert}}if(parent){var parents=parent;if(!forge.util.isArray(parents)){parents=[parents]}var verified=false;while(!verified&&parents.length>0){parent=parents.shift();try{verified=parent.verify(cert)}catch(ex){}}if(!verified){error={message:"Certificate signature is invalid.",error:pki.certificateError.bad_certificate}}}if(error===null&&(!parent||selfSigned)&&!caStore.hasCertificate(cert)){error={message:"Certificate is not trusted.",error:pki.certificateError.unknown_ca}}}if(error===null&&parent&&!cert.isIssuer(parent)){error={message:"Certificate issuer is invalid.",error:pki.certificateError.bad_certificate}}if(error===null){var se={keyUsage:true,basicConstraints:true};for(var i=0;error===null&&ibcExt.pathLenConstraint){error={message:"Certificate basicConstraints pathLenConstraint violated.",error:pki.certificateError.bad_certificate}}}}var vfd=error===null?true:error.error;var ret=options.verify?options.verify(vfd,depth,certs):vfd;if(ret===true){error=null}else{if(vfd===true){error={message:"The application rejected the certificate.",error:pki.certificateError.bad_certificate}}if(ret||ret===0){if(typeof ret==="object"&&!forge.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.error){error.error=ret.error}}else if(typeof ret==="string"){error.error=ret}}throw error}first=false;++depth}while(chain.length>0);return true}},{"./aes":7,"./asn1":9,"./des":14,"./forge":16,"./md":23,"./mgf":25,"./oids":27,"./pem":30,"./pss":38,"./rsa":41,"./util":48}],50:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}});return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":50,timers:51}],52:[function(require,module,exports){module.exports={name:"hybrid-crypto-js",version:"0.2.4",description:"Hybrid (RSA+AES) encryption and decryption toolkit for JavaScript",main:"lib/index.js",scripts:{prepublish:"npm run build",webpack:"browserify lib/webpack.js -o web/hybrid-crypto.js",uglify:"uglifyjs web/hybrid-crypto.js -o web/hybrid-crypto.min.js",flow:"flow",babel:"babel src/ -d lib/",build:"npm run babel && npm run webpack && npm run uglify",test:"npm run babel && mocha -R spec"},repository:{type:"git",url:"https://github.com/juhoen/hybrid-crypto-js.git"},keywords:["rsa","aes","rsa+aes","react","node","react-native"],author:"Juho Enala ",license:"MIT",bugs:{url:"https://github.com/juhoen/hybrid-crypto-js/issues"},homepage:"https://github.com/juhoen/hybrid-crypto-js",dependencies:{"node-forge":"^0.8.5"},devDependencies:{"@babel/cli":"^7.5.5","@babel/core":"^7.5.5","@babel/preset-env":"^7.5.5","@babel/preset-flow":"^7.0.0","babel-core":"^6.26.0","babel-preset-env":"1.6.0","babel-preset-es2015":"^6.24.1",babelify:"^8.0.0",browserify:"^16.5.0",chai:"^4.1.2","flow-bin":"^0.107.0",mocha:"^4.0.1",prettier:"^1.18.2","uglify-js":"^3.2.1"},browserslist:"> 0.25%, not dead"}},{}]},{},[5]); \ No newline at end of file