Professional Documents
Culture Documents
base.$el = $(el);
base.el = el;
base.$el.data("jCryption", base);
base.$el.data("key", null);
base.init = function() {
base.options = $.extend({}, $.jCryption.defaultOptions, options);
$submitElement.bind(base.options.submitEvent, function() {
$(this).attr("disabled", true);
if (base.options.beforeEncryption()) {
base.authenticate(
function(AESEncryptionKey) {
var toEncrypt = base.$el.serialize();
if ($submitElement.is(":submit")) {
toEncrypt = toEncrypt + "&" + $submitElement.attr("name") + "=" +
$submitElement.val();
}
$encryptedElement.val($.jCryption.encrypt(toEncrypt,
AESEncryptionKey));
$(base.$el).find(base.options.formFieldSelector)
.attr("disabled", true).end()
.append($encryptedElement).submit();
},
function() {
// Authentication with AES Failed ... sending form without
protection
confirm("Authentication with Server failed, are you sure you want
to submit this form unencrypted?", function() {
$(base.$el).submit();
});
}
);
}
return false;
});
};
base.init();
/**
* Creates a random string(key) for use in the AES algorithm
*/
base.getKey = function() {
if (base.$el.data("key") !== null) {
return base.$el.data("key");
}
var key;
/**
* Authenticate with the server (One way)
* @param {function} success The function to call if the operation was
successfull
* @param {function} failure The function to call if an error has occurred
*/
base.authenticate = function(success, failure) {
var key = base.getKey();
$.jCryption.authenticate(key, base.options.getKeysURL,
base.options.handshakeURL, success, failure);
};
};
/**
* Authenticates with the server
* @param {string} AESEncryptionKey The AES key
* @param {string} publicKeyURL The public key URL
* @param {string} handshakeURL The handshake URL
* @param {function} success The function to call if the operation was successfull
* @param {function} failure The function to call if an error has occurred
*/
$.jCryption.authenticate = function(AESEncryptionKey, publicKeyURL, handshakeURL,
success, failure) {
$.jCryption.getPublicKey(publicKeyURL, function() {
$.jCryption.encryptKey(AESEncryptionKey, function(encryptedKey) {
$.jCryption.handshake(handshakeURL, encryptedKey, function(response) {
if ($.jCryption.challenge(response.challenge, AESEncryptionKey)) {
success.call(this, AESEncryptionKey);
} else {
failure.call(this);
}
});
});
});
};
/**
* Gets the RSA keys from the specified url, and saves it into a RSA keypair
* @param {string} url The url to contact
* @param {function} callback The function to call when the operation has finshed
*/
$.jCryption.getPublicKey = function(url, callback) {
$.getJSON(url, function(data) {
$.jCryption.crypt.setKey(data.publickey);
if($.isFunction(callback)) {
callback.call(this);
}
});
};
/**
* Decrypts data using AES 256
* @param {string} data The data to decrypt(Ciphertext)
* @param {string} secret The AES secret
* @returns {string} The result of the decryption(Plaintext)
*/
$.jCryption.decrypt = function(data, secret) {
return $.jCryption.hex2string(CryptoJS.AES.decrypt(data, secret) + "");
};
/**
* Encrypts data using AES 256
* @param {string} data The data to encrypt(Plaintext)
* @param {string} secret The AES secret
* @returns {string} The result of the encryption(Ciphertext)
*/
$.jCryption.encrypt = function(data, secret) {
return CryptoJS.AES.encrypt(data, secret) + "";
};
/**
* Makes sure that the challenge the client sent, is correct
* @param {string} challenge The challenge string
* @param {string} secret The AES secret
*/
$.jCryption.challenge = function(challenge, secret) {
var decrypt = $.jCryption.decrypt(challenge, secret);
if (decrypt == secret) {
return true;
}
return false;
};
/**
* Converts a hex into a string
* @param {hex} string representing a hex number
* @returns {string} ASCII sting of input hex
*/
$.jCryption.hex2string = function(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return str;
};
/**
* Executes a handshake with the server
* @param {string} url The url to connect to
* @param {string} ecrypted The encrypted AES secret
* @param {function} callback The function to call when the handshaking has
finished
*/
$.jCryption.handshake = function(url, ecrypted, callback) {
$.ajax({
url: url,
dataType: "json",
type: "POST",
data: {
key: ecrypted
},
success: function(response) {
callback.call(this, response);
}
});
};
/**
* Encrypts the AES secret using RSA
* @param {string} secret The AES secret
* @param {function} callback The function to call when the encryption has
finished
*/
$.jCryption.encryptKey = function(secret, callback) {
var encryptedString = $.jCryption.crypt.encrypt(secret);
if($.isFunction(callback)) {
callback(encryptedString);
} else {
return encryptedString;
}
};
$.jCryption.defaultOptions = {
submitElement: false,
submitEvent: "click",
getKeysURL: "jcryption.php?getPublicKey=true",
handshakeURL: "jcryption.php?handshake=true",
beforeEncryption: function() { return true },
postVariable: "jCryption",
formFieldSelector: ":input"
};
$.fn.jCryption = function(options) {
return this.each(function(){
(new $.jCryption(this, options));
});
};
})(jQuery);
// (public) Constructor
function BigInteger(a,b,c) {
if(a != null)
if("number" == typeof a) this.fromNumber(a,b,c);
else if(b == null && "string" != typeof a) this.fromString(a,256);
else this.fromString(a,b);
}
// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
function am1(i,x,w,j,c,n) {
while(--n >= 0) {
var v = x*this[i++]+w[j]+c;
c = Math.floor(v/0x4000000);
w[j++] = v&0x3ffffff;
}
return c;
}
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
function am2(i,x,w,j,c,n) {
var xl = x&0x7fff, xh = x>>15;
while(--n >= 0) {
var l = this[i]&0x7fff;
var h = this[i++]>>15;
var m = xh*l+h*xl;
l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
w[j++] = l&0x3fffffff;
}
return c;
}
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
function am3(i,x,w,j,c,n) {
var xl = x&0x3fff, xh = x>>14;
while(--n >= 0) {
var l = this[i]&0x3fff;
var h = this[i++]>>14;
var m = xh*l+h*xl;
l = xl*l+((m&0x3fff)<<14)+w[j]+c;
c = (l>>28)+(m>>14)+xh*h;
w[j++] = l&0xfffffff;
}
return c;
}
if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
BigInteger.prototype.am = am2;
dbits = 30;
}
else if(j_lm && (navigator.appName != "Netscape")) {
BigInteger.prototype.am = am1;
dbits = 26;
}
else { // Mozilla/Netscape seems to prefer am3
BigInteger.prototype.am = am3;
dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = ((1<<dbits)-1);
BigInteger.prototype.DV = (1<<dbits);
// Digit conversions
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr,vv;
rr = "0".charCodeAt(0);
for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
// (public) -this
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
// (public) |this|
function bnAbs() { return (this.s<0)?this.negate():this; }
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
// Montgomery reduction
function Montgomery(m) {
this.m = m;
this.mp = m.invDigit();
this.mpl = this.mp&0x7fff;
this.mph = this.mp>>15;
this.um = (1<<(m.DB-15))-1;
this.mt2 = 2*m.t;
}
// xR mod m
function montConvert(x) {
var r = nbi();
x.abs().dlShiftTo(this.m.t,r);
r.divRemTo(this.m,null,r);
if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
return r;
}
// x/R mod m
function montRevert(x) {
var r = nbi();
x.copyTo(r);
this.reduce(r);
return r;
}
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
function bnpExp(e,z) {
if(e > 0xffffffff || e < 1) return BigInteger.ONE;
var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
g.copyTo(r);
while(--i >= 0) {
z.sqrTo(r,r2);
if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
else { var t = r; r = r2; r2 = t; }
}
return z.revert(r);
}
// (public) this^e % m, 0 <= e < 2^32
function bnModPowInt(e,m) {
var z;
if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
return this.exp(e,z);
}
// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
// Copyright (c) 2005-2009 Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
// (public)
function bnClone() { var r = nbi(); this.copyTo(r); return r; }
// (public) this | a
function op_or(x,y) { return x|y; }
function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
// (public) this ^ a
function op_xor(x,y) { return x^y; }
function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
// (public) ~this
function bnNot() {
var r = nbi();
for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
r.t = this.t;
r.s = ~this.s;
return r;
}
// (protected) r = this + a
function bnpAddTo(a,r) {
var i = 0, c = 0, m = Math.min(a.t,this.t);
while(i < m) {
c += this[i]+a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
if(a.t < this.t) {
c += a.s;
while(i < this.t) {
c += this[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c += this.s;
}
else {
c += this.s;
while(i < a.t) {
c += a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c += a.s;
}
r.s = (c<0)?-1:0;
if(c > 0) r[i++] = c;
else if(c < -1) r[i++] = this.DV+c;
r.t = i;
r.clamp();
}
// (public) this + a
function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
// (public) this - a
function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
// (public) this * a
function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
// (public) this^2
function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
// (public) this / a
function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
// (public) this % a
function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
// (public) [this/a,this%a]
function bnDivideAndRemainder(a) {
var q = nbi(), r = nbi();
this.divRemTo(a,q,r);
return new Array(q,r);
}
// A "null" reducer
function NullExp() {}
function nNop(x) { return x; }
function nMulTo(x,y,r) { x.multiplyTo(y,r); }
function nSqrTo(x,r) { x.squareTo(r); }
NullExp.prototype.convert = nNop;
NullExp.prototype.revert = nNop;
NullExp.prototype.mulTo = nMulTo;
NullExp.prototype.sqrTo = nSqrTo;
// (public) this^e
function bnPow(e) { return this.exp(e,new NullExp()); }
// r = x^2 mod m; x != r
function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
Barrett.prototype.convert = barrettConvert;
Barrett.prototype.revert = barrettRevert;
Barrett.prototype.reduce = barrettReduce;
Barrett.prototype.mulTo = barrettMulTo;
Barrett.prototype.sqrTo = barrettSqrTo;
// precomputation
var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
g[1] = z.convert(this);
if(k > 1) {
var g2 = nbi();
z.sqrTo(g[1],g2);
while(n <= km) {
g[n] = nbi();
z.mulTo(g2,g[n-2],g[n]);
n += 2;
}
}
n = k;
while((w&1) == 0) { w >>= 1; --n; }
if((i -= n) < 0) { i += this.DB; --j; }
if(is1) { // ret == 1, don't bother squaring or multiplying it
g[w].copyTo(r);
is1 = false;
}
else {
while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
z.mulTo(r2,g[w],r);
}
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,22
7,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,3
49,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,
467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607
,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,74
3,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,8
83,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
var lplim = (1<<26)/lowprimes[lowprimes.length-1];
// protected
BigInteger.prototype.chunkSize = bnpChunkSize;
BigInteger.prototype.toRadix = bnpToRadix;
BigInteger.prototype.fromRadix = bnpFromRadix;
BigInteger.prototype.fromNumber = bnpFromNumber;
BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
BigInteger.prototype.changeBit = bnpChangeBit;
BigInteger.prototype.addTo = bnpAddTo;
BigInteger.prototype.dMultiply = bnpDMultiply;
BigInteger.prototype.dAddOffset = bnpDAddOffset;
BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
BigInteger.prototype.modInt = bnpModInt;
BigInteger.prototype.millerRabin = bnpMillerRabin;
// public
BigInteger.prototype.clone = bnClone;
BigInteger.prototype.intValue = bnIntValue;
BigInteger.prototype.byteValue = bnByteValue;
BigInteger.prototype.shortValue = bnShortValue;
BigInteger.prototype.signum = bnSigNum;
BigInteger.prototype.toByteArray = bnToByteArray;
BigInteger.prototype.equals = bnEquals;
BigInteger.prototype.min = bnMin;
BigInteger.prototype.max = bnMax;
BigInteger.prototype.and = bnAnd;
BigInteger.prototype.or = bnOr;
BigInteger.prototype.xor = bnXor;
BigInteger.prototype.andNot = bnAndNot;
BigInteger.prototype.not = bnNot;
BigInteger.prototype.shiftLeft = bnShiftLeft;
BigInteger.prototype.shiftRight = bnShiftRight;
BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
BigInteger.prototype.bitCount = bnBitCount;
BigInteger.prototype.testBit = bnTestBit;
BigInteger.prototype.setBit = bnSetBit;
BigInteger.prototype.clearBit = bnClearBit;
BigInteger.prototype.flipBit = bnFlipBit;
BigInteger.prototype.add = bnAdd;
BigInteger.prototype.subtract = bnSubtract;
BigInteger.prototype.multiply = bnMultiply;
BigInteger.prototype.divide = bnDivide;
BigInteger.prototype.remainder = bnRemainder;
BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
BigInteger.prototype.modPow = bnModPow;
BigInteger.prototype.modInverse = bnModInverse;
BigInteger.prototype.pow = bnPow;
BigInteger.prototype.gcd = bnGCD;
BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
// JSBN-specific extension
BigInteger.prototype.square = bnSquare;
function Arcfour() {
this.i = 0;
this.j = 0;
this.S = new Array();
}
// Initialize arcfour context from key, an array of ints, each from [0..255]
function ARC4init(key) {
var i, j, t;
for(i = 0; i < 256; ++i)
this.S[i] = i;
j = 0;
for(i = 0; i < 256; ++i) {
j = (j + this.S[i] + key[i % key.length]) & 255;
t = this.S[i];
this.S[i] = this.S[j];
this.S[j] = t;
}
this.i = 0;
this.j = 0;
}
function ARC4next() {
var t;
this.i = (this.i + 1) & 255;
this.j = (this.j + this.S[this.i]) & 255;
t = this.S[this.i];
this.S[this.i] = this.S[this.j];
this.S[this.j] = t;
return this.S[(t + this.S[this.i]) & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
var rng_state;
var rng_pool;
var rng_pptr;
function rng_get_byte() {
if(rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next();
}
function rng_get_bytes(ba) {
var i;
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
function SecureRandom() {}
SecureRandom.prototype.nextBytes = rng_get_bytes;
// Depends on jsbn.js and rng.js
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
console.error("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
// Depends on rsa.js and jsbn2.js
// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
function pkcs1unpad2(d,n) {
var b = d.toByteArray();
var i = 0;
while(i < b.length && b[i] == 0) ++i;
if(b.length-i != n-1 || b[i] != 2)
return null;
++i;
while(b[i] != 0)
if(++i >= b.length) return null;
var ret = "";
while(++i < b.length) {
var c = b[i] & 255;
if(c < 128) { // utf-8 decode
ret += String.fromCharCode(c);
}
else if((c > 191) && (c < 224)) {
ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
++i;
}
else {
ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2]
& 63));
i += 2;
}
}
return ret;
}
// Set the private key fields N, e, d and CRT params from hex strings
function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
this.d = parseBigInt(D,16);
this.p = parseBigInt(P,16);
this.q = parseBigInt(Q,16);
this.dmp1 = parseBigInt(DP,16);
this.dmq1 = parseBigInt(DQ,16);
this.coeff = parseBigInt(C,16);
}
else
console.error("Invalid RSA private key");
}
// Generate a new random private key B bits long, using public expt E
function RSAGenerate(B,E) {
var rng = new SecureRandom();
var qs = B>>1;
this.e = parseInt(E,16);
var ee = new BigInteger(E,16);
for(;;) {
for(;;) {
this.p = new BigInteger(B-qs,1,rng);
if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 &&
this.p.isProbablePrime(10)) break;
}
for(;;) {
this.q = new BigInteger(qs,1,rng);
if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 &&
this.q.isProbablePrime(10)) break;
}
if(this.p.compareTo(this.q) <= 0) {
var t = this.p;
this.p = this.q;
this.q = t;
}
var p1 = this.p.subtract(BigInteger.ONE);
var q1 = this.q.subtract(BigInteger.ONE);
var phi = p1.multiply(q1);
if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
this.n = this.p.multiply(this.q);
this.d = ee.modInverse(phi);
this.dmp1 = this.d.mod(p1);
this.dmq1 = this.d.mod(q1);
this.coeff = this.q.modInverse(this.p);
break;
}
}
}
while(xp.compareTo(xq) < 0)
xp = xp.add(this.p);
return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
}
// protected
RSAKey.prototype.doPrivate = RSADoPrivate;
// public
RSAKey.prototype.setPrivate = RSASetPrivate;
RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
RSAKey.prototype.generate = RSAGenerate;
RSAKey.prototype.decrypt = RSADecrypt;
//RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
// Copyright (c) 2011 Kevin M Burns Jr.
// All Rights Reserved.
// See "LICENSE" for details.
//
// Extension to jsbn which adds facilities for asynchronous RSA key generation
// Primarily created to avoid execution timeout on mobile devices
//
// http://www-cs-students.stanford.edu/~tjw/jsbn/
//
// ---
(function(){
// Generate a new random private key B bits long, using public expt E
var RSAGenerateAsync = function (B, E, callback) {
//var rng = new SeededRandom();
var rng = new SecureRandom();
var qs = B >> 1;
this.e = parseInt(E, 16);
var ee = new BigInteger(E, 16);
var rsa = this;
// These functions have non-descript names because they were originally for(;;)
loops.
// I don't know about cryptography to give them better names than loop1-4.
var loop1 = function() {
var loop4 = function() {
if (rsa.p.compareTo(rsa.q) <= 0) {
var t = rsa.p;
rsa.p = rsa.q;
rsa.q = t;
}
var p1 = rsa.p.subtract(BigInteger.ONE);
var q1 = rsa.q.subtract(BigInteger.ONE);
var phi = p1.multiply(q1);
if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
rsa.n = rsa.p.multiply(rsa.q);
rsa.d = ee.modInverse(phi);
rsa.dmp1 = rsa.d.mod(p1);
rsa.dmq1 = rsa.d.mod(q1);
rsa.coeff = rsa.q.modInverse(rsa.p);
setTimeout(function(){callback()},0); // escape
} else {
setTimeout(loop1,0);
}
};
var loop3 = function() {
rsa.q = nbi();
rsa.q.fromNumberAsync(qs, 1, rng, function(){
rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r){
if (r.compareTo(BigInteger.ONE) == 0 &&
rsa.q.isProbablePrime(10)) {
setTimeout(loop4,0);
} else {
setTimeout(loop3,0);
}
});
});
};
var loop2 = function() {
rsa.p = nbi();
rsa.p.fromNumberAsync(B - qs, 1, rng, function(){
rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r){
if (r.compareTo(BigInteger.ONE) == 0 &&
rsa.p.isProbablePrime(10)) {
setTimeout(loop3,0);
} else {
setTimeout(loop2,0);
}
});
});
};
setTimeout(loop2,0);
};
setTimeout(loop1,0);
};
RSAKey.prototype.generateAsync = RSAGenerateAsync;
})();var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad="=";
function hex2b64(h) {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1 == h.length) {
c = parseInt(h.substring(i,i+1),16);
ret += b64map.charAt(c << 2);
}
else if(i+2 == h.length) {
c = parseInt(h.substring(i,i+2),16);
ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
}
while((ret.length & 3) > 0) ret += b64pad;
return ret;
}
JSX.env.parseUA = function(agent) {
nav = navigator,
o = {
ie: 0,
opera: 0,
gecko: 0,
webkit: 0,
chrome: 0,
mobile: null,
air: 0,
ipad: 0,
iphone: 0,
ipod: 0,
ios: null,
android: 0,
webos: 0,
caja: nav && nav.cajaVersion,
secure: false,
os: null
},
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh/i).test(ua)) {
o.os = 'macintosh';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
if (/ Mobile\//.test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);
if (m) {
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
o.mobile = 'Android';
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
}
m = ua.match(/Chrome\/([^\s]*)/);
if (m && m[1]) {
o.chrome = numberify(m[1]); // Chrome
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) {
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
}
}
}
}
}
}
return o;
};
JSX.env.ua = JSX.env.parseUA();
JSX.isFunction = function(o) {
return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING;
};
fname = ADD[i];
f = s[fname];
if (overrides) {
for (i in overrides) {
if (L.hasOwnProperty(overrides, i)) {
subc.prototype[i]=overrides[i];
}
}
L._IEEnumFix(subc.prototype, overrides);
}
};
/*
* asn1.js - ASN.1 DER encoder classes
*
* Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
*
* This software is licensed under the terms of the MIT License.
* http://kjur.github.com/jsrsasign/license
*
* The above copyright and license notice shall be
* included in all copies or substantial portions of the Software.
*/
/**
* @fileOverview
* @name asn1-1.0.js
* @author Kenji Urushima kenji.urushima@gmail.com
* @version 1.0.2 (2013-May-30)
* @since 2.1
* @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
/**
* kjur's class library name space
* <p>
* This name space provides following name spaces:
* <ul>
* <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
* <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
* <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style
MessageDigest/Signature
* class and utilities</li>
* </ul>
* </p>
* NOTE: Please ignore method summary and document of this namespace. This caused
by a bug of jsdoc2.
* @name KJUR
* @namespace kjur's class library name space
*/
if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
/**
* kjur's ASN.1 class library name space
* <p>
* This is ITU-T X.690 ASN.1 DER encoder class library and
* class structure and methods is very similar to
* org.bouncycastle.asn1 package of
* well known BouncyCaslte Cryptography Library.
*
* <h4>PROVIDING ASN.1 PRIMITIVES</h4>
* Here are ASN.1 DER primitive classes.
* <ul>
* <li>{@link KJUR.asn1.DERBoolean}</li>
* <li>{@link KJUR.asn1.DERInteger}</li>
* <li>{@link KJUR.asn1.DERBitString}</li>
* <li>{@link KJUR.asn1.DEROctetString}</li>
* <li>{@link KJUR.asn1.DERNull}</li>
* <li>{@link KJUR.asn1.DERObjectIdentifier}</li>
* <li>{@link KJUR.asn1.DERUTF8String}</li>
* <li>{@link KJUR.asn1.DERNumericString}</li>
* <li>{@link KJUR.asn1.DERPrintableString}</li>
* <li>{@link KJUR.asn1.DERTeletexString}</li>
* <li>{@link KJUR.asn1.DERIA5String}</li>
* <li>{@link KJUR.asn1.DERUTCTime}</li>
* <li>{@link KJUR.asn1.DERGeneralizedTime}</li>
* <li>{@link KJUR.asn1.DERSequence}</li>
* <li>{@link KJUR.asn1.DERSet}</li>
* </ul>
*
* <h4>OTHER ASN.1 CLASSES</h4>
* <ul>
* <li>{@link KJUR.asn1.ASN1Object}</li>
* <li>{@link KJUR.asn1.DERAbstractString}</li>
* <li>{@link KJUR.asn1.DERAbstractTime}</li>
* <li>{@link KJUR.asn1.DERAbstractStructured}</li>
* <li>{@link KJUR.asn1.DERTaggedObject}</li>
* </ul>
* </p>
* NOTE: Please ignore method summary and document of this namespace. This caused
by a bug of jsdoc2.
* @name KJUR.asn1
* @namespace
*/
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
/**
* ASN1 utilities class
* @name KJUR.asn1.ASN1Util
* @classs ASN1 utilities class
* @since asn1 1.0.2
*/
KJUR.asn1.ASN1Util = new function() {
this.integerToByteHex = function(i) {
var h = i.toString(16);
if ((h.length % 2) == 1) h = '0' + h;
return h;
};
this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
var h = bigIntegerValue.toString(16);
if (h.substr(0, 1) != '-') {
if (h.length % 2 == 1) {
h = '0' + h;
} else {
if (! h.match(/^[0-7]/)) {
h = '00' + h;
}
}
} else {
var hPos = h.substr(1);
var xorLen = hPos.length;
if (xorLen % 2 == 1) {
xorLen += 1;
} else {
if (! h.match(/^[0-7]/)) {
xorLen += 2;
}
}
var hMask = '';
for (var i = 0; i < xorLen; i++) {
hMask += 'f';
}
var biMask = new BigInteger(hMask, 16);
var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
h = biNeg.toString(16).replace(/^-/, '');
}
return h;
};
/**
* get PEM string from hexadecimal data and header string
* @name getPEMStringFromHex
* @memberOf KJUR.asn1.ASN1Util
* @function
* @param {String} dataHex hexadecimal string of PEM body
* @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
* @return {String} PEM formatted string of input data
* @description
* @example
* var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE
KEY');
* // value of pem will be:
* -----BEGIN PRIVATE KEY-----
* YWFh
* -----END PRIVATE KEY-----
*/
this.getPEMStringFromHex = function(dataHex, pemHeader) {
var dataWA = CryptoJS.enc.Hex.parse(dataHex);
var dataB64 = CryptoJS.enc.Base64.stringify(dataWA);
var pemBody = dataB64.replace(/(.{64})/g, "$1\r\n");
pemBody = pemBody.replace(/\r\n$/, '');
return "-----BEGIN " + pemHeader + "-----\r\n" +
pemBody +
"\r\n-----END " + pemHeader + "-----\r\n";
};
};
// ********************************************************************
// Abstract ASN.1 Classes
// ********************************************************************
// ********************************************************************
/**
* base class for ASN.1 DER encoder object
* @name KJUR.asn1.ASN1Object
* @class base class for ASN.1 DER encoder object
* @property {Boolean} isModified flag whether internal data was changed
* @property {String} hTLV hexadecimal string of ASN.1 TLV
* @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
* @property {String} hL hexadecimal string of ASN.1 TLV length(L)
* @property {String} hV hexadecimal string of ASN.1 TLV value(V)
* @description
*/
KJUR.asn1.ASN1Object = function() {
var isModified = true;
var hTLV = null;
var hT = '00'
var hL = '00';
var hV = '';
/**
* get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
* @name getLengthHexFromValue
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV length(L)
*/
this.getLengthHexFromValue = function() {
if (typeof this.hV == "undefined" || this.hV == null) {
throw "this.hV is null or undefined.";
}
if (this.hV.length % 2 == 1) {
throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
}
var n = this.hV.length / 2;
var hN = n.toString(16);
if (hN.length % 2 == 1) {
hN = "0" + hN;
}
if (n < 128) {
return hN;
} else {
var hNlen = hN.length / 2;
if (hNlen > 15) {
throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
}
var head = 128 + hNlen;
return head.toString(16) + hN;
}
};
/**
* get hexadecimal string of ASN.1 TLV bytes
* @name getEncodedHex
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV
*/
this.getEncodedHex = function() {
if (this.hTLV == null || this.isModified) {
this.hV = this.getFreshValueHex();
this.hL = this.getLengthHexFromValue();
this.hTLV = this.hT + this.hL + this.hV;
this.isModified = false;
//console.error("first time: " + this.hTLV);
}
return this.hTLV;
};
/**
* get hexadecimal string of ASN.1 TLV value(V) bytes
* @name getValueHex
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
*/
this.getValueHex = function() {
this.getEncodedHex();
return this.hV;
}
this.getFreshValueHex = function() {
return '';
};
};
/**
* get string value of this string object
* @name getString
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @return {String} string value of this string object
*/
this.getString = function() {
return this.s;
};
/**
* set value by a string
* @name setString
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @param {String} newS value by a string to set
*/
this.setString = function(newS) {
this.hTLV = null;
this.isModified = true;
this.s = newS;
this.hV = stohex(this.s);
};
/**
* set value by a hexadecimal string
* @name setStringHex
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @param {String} newHexString value by a hexadecimal string to set
*/
this.setStringHex = function(newHexString) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = newHexString;
};
this.getFreshValueHex = function() {
return this.hV;
};
/**
* set value by a string
* @name setString
* @memberOf KJUR.asn1.DERAbstractTime
* @function
* @param {String} newS value by a string to set such like "130430235959Z"
*/
this.setString = function(newS) {
this.hTLV = null;
this.isModified = true;
this.s = newS;
this.hV = stohex(this.s);
};
/**
* set value by a Date object
* @name setByDateValue
* @memberOf KJUR.asn1.DERAbstractTime
* @function
* @param {Integer} year year of date (ex. 2013)
* @param {Integer} month month of date between 1 and 12 (ex. 12)
* @param {Integer} day day of month
* @param {Integer} hour hours of date
* @param {Integer} min minutes of date
* @param {Integer} sec seconds of date
*/
this.setByDateValue = function(year, month, day, hour, min, sec) {
var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
this.setByDate(dateObject);
};
this.getFreshValueHex = function() {
return this.hV;
};
};
JSX.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
// == END DERAbstractTime ==================================================
/**
* set value by array of ASN1Object
* @name setByASN1ObjectArray
* @memberOf KJUR.asn1.DERAbstractStructured
* @function
* @param {array} asn1ObjectArray array of ASN1Object to set
*/
this.setByASN1ObjectArray = function(asn1ObjectArray) {
this.hTLV = null;
this.isModified = true;
this.asn1Array = asn1ObjectArray;
};
/**
* append an ASN1Object to internal array
* @name appendASN1Object
* @memberOf KJUR.asn1.DERAbstractStructured
* @function
* @param {ASN1Object} asn1Object to add
*/
this.appendASN1Object = function(asn1Object) {
this.hTLV = null;
this.isModified = true;
this.asn1Array.push(asn1Object);
};
// ********************************************************************
// ASN.1 Object Classes
// ********************************************************************
// ********************************************************************
/**
* class for ASN.1 DER Boolean
* @name KJUR.asn1.DERBoolean
* @class class for ASN.1 DER Boolean
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERBoolean = function() {
KJUR.asn1.DERBoolean.superclass.constructor.call(this);
this.hT = "01";
this.hTLV = "0101ff";
};
JSX.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER Integer
* @name KJUR.asn1.DERInteger
* @class class for ASN.1 DER Integer
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>int - specify initial ASN.1 value(V) by integer value</li>
* <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERInteger = function(params) {
KJUR.asn1.DERInteger.superclass.constructor.call(this);
this.hT = "02";
/**
* set value by Tom Wu's BigInteger object
* @name setByBigInteger
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {BigInteger} bigIntegerValue to set
*/
this.setByBigInteger = function(bigIntegerValue) {
this.hTLV = null;
this.isModified = true;
this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
};
/**
* set value by integer value
* @name setByInteger
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {Integer} integer value to set
*/
this.setByInteger = function(intValue) {
var bi = new BigInteger(String(intValue), 10);
this.setByBigInteger(bi);
};
/**
* set value by integer value
* @name setValueHex
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {String} hexadecimal string of integer value
* @description
* <br/>
* NOTE: Value shall be represented by minimum octet length of
* two's complement representation.
*/
this.setValueHex = function(newHexString) {
this.hV = newHexString;
};
this.getFreshValueHex = function() {
return this.hV;
};
// ********************************************************************
/**
* class for ASN.1 DER encoded BitString primitive
* @name KJUR.asn1.DERBitString
* @class class for ASN.1 DER encoded BitString primitive
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>bin - specify binary string (ex. '10111')</li>
* <li>array - specify array of boolean (ex. [true,false,true,true])</li>
* <li>hex - specify hexadecimal string of ASN.1 value(V) including unused
bits</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERBitString = function(params) {
KJUR.asn1.DERBitString.superclass.constructor.call(this);
this.hT = "03";
/**
* set ASN.1 value(V) by a hexadecimal string including unused bits
* @name setHexValueIncludingUnusedBits
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {String} newHexStringIncludingUnusedBits
*/
this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits)
{
this.hTLV = null;
this.isModified = true;
this.hV = newHexStringIncludingUnusedBits;
};
/**
* set ASN.1 value(V) by unused bit and hexadecimal string of value
* @name setUnusedBitsAndHexValue
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {Integer} unusedBits
* @param {String} hValue
*/
this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
if (unusedBits < 0 || 7 < unusedBits) {
throw "unused bits shall be from 0 to 7: u = " + unusedBits;
}
var hUnusedBits = "0" + unusedBits;
this.hTLV = null;
this.isModified = true;
this.hV = hUnusedBits + hValue;
};
/**
* set ASN.1 DER BitString by binary string
* @name setByBinaryString
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {String} binaryString binary value string (i.e. '10111')
* @description
* Its unused bits will be calculated automatically by length of
* 'binaryValue'. <br/>
* NOTE: Trailing zeros '0' will be ignored.
*/
this.setByBinaryString = function(binaryString) {
binaryString = binaryString.replace(/0+$/, '');
var unusedBits = 8 - binaryString.length % 8;
if (unusedBits == 8) unusedBits = 0;
for (var i = 0; i <= unusedBits; i++) {
binaryString += '0';
}
var h = '';
for (var i = 0; i < binaryString.length - 1; i += 8) {
var b = binaryString.substr(i, 8);
var x = parseInt(b, 2).toString(16);
if (x.length == 1) x = '0' + x;
h += x;
}
this.hTLV = null;
this.isModified = true;
this.hV = '0' + unusedBits + h;
};
/**
* set ASN.1 TLV value(V) by an array of boolean
* @name setByBooleanArray
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {array} booleanArray array of boolean (ex. [true, false, true])
* @description
* NOTE: Trailing falses will be ignored.
*/
this.setByBooleanArray = function(booleanArray) {
var s = '';
for (var i = 0; i < booleanArray.length; i++) {
if (booleanArray[i] == true) {
s += '1';
} else {
s += '0';
}
}
this.setByBinaryString(s);
};
/**
* generate an array of false with specified length
* @name newFalseArray
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {Integer} nLength length of array to generate
* @return {array} array of boolean faluse
* @description
* This static method may be useful to initialize boolean array.
*/
this.newFalseArray = function(nLength) {
var a = new Array(nLength);
for (var i = 0; i < nLength; i++) {
a[i] = false;
}
return a;
};
this.getFreshValueHex = function() {
return this.hV;
};
// ********************************************************************
/**
* class for ASN.1 DER OctetString
* @name KJUR.asn1.DEROctetString
* @class class for ASN.1 DER OctetString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DEROctetString = function(params) {
KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
this.hT = "04";
};
JSX.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER Null
* @name KJUR.asn1.DERNull
* @class class for ASN.1 DER Null
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERNull = function() {
KJUR.asn1.DERNull.superclass.constructor.call(this);
this.hT = "05";
this.hTLV = "0500";
};
JSX.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER ObjectIdentifier
* @name KJUR.asn1.DERObjectIdentifier
* @class class for ASN.1 DER ObjectIdentifier
* @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERObjectIdentifier = function(params) {
var itox = function(i) {
var h = i.toString(16);
if (h.length == 1) h = '0' + h;
return h;
};
var roidtox = function(roid) {
var h = '';
var bi = new BigInteger(roid, 10);
var b = bi.toString(2);
var padLen = 7 - b.length % 7;
if (padLen == 7) padLen = 0;
var bPad = '';
for (var i = 0; i < padLen; i++) bPad += '0';
b = bPad + b;
for (var i = 0; i < b.length - 1; i += 7) {
var b8 = b.substr(i, 7);
if (i != b.length - 7) b8 = '1' + b8;
h += itox(parseInt(b8, 2));
}
return h;
}
KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
this.hT = "06";
/**
* set value by a hexadecimal string
* @name setValueHex
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} newHexString hexadecimal value of OID bytes
*/
this.setValueHex = function(newHexString) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = newHexString;
};
/**
* set value by a OID string
* @name setValueOidString
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} oidString OID string (ex. 2.5.4.13)
*/
this.setValueOidString = function(oidString) {
if (! oidString.match(/^[0-9.]+$/)) {
throw "malformed oid string: " + oidString;
}
var h = '';
var a = oidString.split('.');
var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
h += itox(i0);
a.splice(0, 2);
for (var i = 0; i < a.length; i++) {
h += roidtox(a[i]);
}
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = h;
};
/**
* set value by a OID name
* @name setValueName
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} oidName OID name (ex. 'serverAuth')
* @since 1.0.1
* @description
* OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
* Otherwise raise error.
*/
this.setValueName = function(oidName) {
if (typeof KJUR.asn1.x509.OID.name2oidList[oidName] != "undefined") {
var oid = KJUR.asn1.x509.OID.name2oidList[oidName];
this.setValueOidString(oid);
} else {
throw "DERObjectIdentifier oidName undefined: " + oidName;
}
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params['oid'] != "undefined") {
this.setValueOidString(params['oid']);
} else if (typeof params['hex'] != "undefined") {
this.setValueHex(params['hex']);
} else if (typeof params['name'] != "undefined") {
this.setValueName(params['name']);
}
}
};
JSX.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER UTF8String
* @name KJUR.asn1.DERUTF8String
* @class class for ASN.1 DER UTF8String
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERUTF8String = function(params) {
KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
this.hT = "0c";
};
JSX.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER NumericString
* @name KJUR.asn1.DERNumericString
* @class class for ASN.1 DER NumericString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERNumericString = function(params) {
KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
this.hT = "12";
};
JSX.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER PrintableString
* @name KJUR.asn1.DERPrintableString
* @class class for ASN.1 DER PrintableString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERPrintableString = function(params) {
KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
this.hT = "13";
};
JSX.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER TeletexString
* @name KJUR.asn1.DERTeletexString
* @class class for ASN.1 DER TeletexString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERTeletexString = function(params) {
KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
this.hT = "14";
};
JSX.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER IA5String
* @name KJUR.asn1.DERIA5String
* @class class for ASN.1 DER IA5String
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERIA5String = function(params) {
KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
this.hT = "16";
};
JSX.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER UTCTime
* @name KJUR.asn1.DERUTCTime
* @class class for ASN.1 DER UTCTime
* @param {Array} params associative array of parameters (ex. {'str':
'130430235959Z'})
* @extends KJUR.asn1.DERAbstractTime
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* <li>date - specify Date object.</li>
* </ul>
* NOTE: 'params' can be omitted.
* <h4>EXAMPLES</h4>
* @example
* var d1 = new KJUR.asn1.DERUTCTime();
* d1.setString('130430125959Z');
*
* var d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
*
* var d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0,
0, 0))});
*/
KJUR.asn1.DERUTCTime = function(params) {
KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
this.hT = "17";
/**
* set value by a Date object
* @name setByDate
* @memberOf KJUR.asn1.DERUTCTime
* @function
* @param {Date} dateObject Date object to set ASN.1 value(V)
*/
this.setByDate = function(dateObject) {
this.hTLV = null;
this.isModified = true;
this.date = dateObject;
this.s = this.formatDate(this.date, 'utc');
this.hV = stohex(this.s);
};
// ********************************************************************
/**
* class for ASN.1 DER GeneralizedTime
* @name KJUR.asn1.DERGeneralizedTime
* @class class for ASN.1 DER GeneralizedTime
* @param {Array} params associative array of parameters (ex. {'str':
'20130430235959Z'})
* @extends KJUR.asn1.DERAbstractTime
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* <li>date - specify Date object.</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERGeneralizedTime = function(params) {
KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
this.hT = "18";
/**
* set value by a Date object
* @name setByDate
* @memberOf KJUR.asn1.DERGeneralizedTime
* @function
* @param {Date} dateObject Date object to set ASN.1 value(V)
* @example
* When you specify UTC time, use 'Date.UTC' method like this:<br/>
* var o = new DERUTCTime();
* var date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31
23:59:59
* o.setByDate(date);
*/
this.setByDate = function(dateObject) {
this.hTLV = null;
this.isModified = true;
this.date = dateObject;
this.s = this.formatDate(this.date, 'gen');
this.hV = stohex(this.s);
};
// ********************************************************************
/**
* class for ASN.1 DER Sequence
* @name KJUR.asn1.DERSequence
* @class class for ASN.1 DER Sequence
* @extends KJUR.asn1.DERAbstractStructured
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>array - specify array of ASN1Object to set elements of content</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERSequence = function(params) {
KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
this.hT = "30";
this.getFreshValueHex = function() {
var h = '';
for (var i = 0; i < this.asn1Array.length; i++) {
var asn1Obj = this.asn1Array[i];
h += asn1Obj.getEncodedHex();
}
this.hV = h;
return this.hV;
};
};
JSX.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
// ********************************************************************
/**
* class for ASN.1 DER Set
* @name KJUR.asn1.DERSet
* @class class for ASN.1 DER Set
* @extends KJUR.asn1.DERAbstractStructured
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>array - specify array of ASN1Object to set elements of content</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERSet = function(params) {
KJUR.asn1.DERSet.superclass.constructor.call(this, params);
this.hT = "31";
this.getFreshValueHex = function() {
var a = new Array();
for (var i = 0; i < this.asn1Array.length; i++) {
var asn1Obj = this.asn1Array[i];
a.push(asn1Obj.getEncodedHex());
}
a.sort();
this.hV = a.join('');
return this.hV;
};
};
JSX.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
// ********************************************************************
/**
* class for ASN.1 DER TaggedObject
* @name KJUR.asn1.DERTaggedObject
* @class class for ASN.1 DER TaggedObject
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
* For example, if you find '[1]' tag in a ASN.1 dump,
* 'tagNoHex' will be 'a1'.
* <br/>
* As for optional argument 'params' for constructor, you can specify *ANY* of
* following properties:
* <ul>
* <li>explicit - specify true if this is explicit tag otherwise false
* (default is 'true').</li>
* <li>tag - specify tag (default is 'a0' which means [0])</li>
* <li>obj - specify ASN1Object which is tagged</li>
* </ul>
* @example
* d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
* d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
* hex = d2.getEncodedHex();
*/
KJUR.asn1.DERTaggedObject = function(params) {
KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
this.hT = "a0";
this.hV = '';
this.isExplicit = true;
this.asn1Object = null;
/**
* set value by an ASN1Object
* @name setString
* @memberOf KJUR.asn1.DERTaggedObject
* @function
* @param {Boolean} isExplicitFlag flag for explicit/implicit tag
* @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
* @param {ASN1Object} asn1Object ASN.1 to encapsulate
*/
this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
this.hT = tagNoHex;
this.isExplicit = isExplicitFlag;
this.asn1Object = asn1Object;
if (this.isExplicit) {
this.hV = this.asn1Object.getEncodedHex();
this.hTLV = null;
this.isModified = true;
} else {
this.hV = null;
this.hTLV = asn1Object.getEncodedHex();
this.hTLV = this.hTLV.replace(/^../, tagNoHex);
this.isModified = false;
}
};
this.getFreshValueHex = function() {
return this.hV;
};
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true,
regexdash: false */
(function (undefined) {
"use strict";
Hex.decode = function(a) {
var i;
if (decoder === undefined) {
var hex = "0123456789ABCDEF",
ignore = " \f\n\r\t\u00A0\u2028\u2029";
decoder = [];
for (i = 0; i < 16; ++i)
decoder[hex.charAt(i)] = i;
hex = hex.toLowerCase();
for (i = 10; i < 16; ++i)
decoder[hex.charAt(i)] = i;
for (i = 0; i < ignore.length; ++i)
decoder[ignore.charAt(i)] = -1;
}
var out = [],
bits = 0,
char_count = 0;
for (i = 0; i < a.length; ++i) {
var c = a.charAt(i);
if (c == '=')
break;
c = decoder[c];
if (c == -1)
continue;
if (c === undefined)
throw 'Illegal character at offset ' + i;
bits |= c;
if (++char_count >= 2) {
out[out.length] = bits;
bits = 0;
char_count = 0;
} else {
bits <<= 4;
}
}
if (char_count)
throw "Hex encoding incomplete: 4 bits missing";
return out;
};
// export globals
window.Hex = Hex;
})();// Base64 JavaScript decoder
// Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true,
regexdash: false */
(function (undefined) {
"use strict";
// export globals
window.Base64 = Base64;
})();// ASN.1 JavaScript decoder
// Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true,
regexdash: false */
/*global oids */
(function (undefined) {
"use strict";
return str;
};
Stream.prototype.reTime = /^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|
3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|
1[0-2])([0-5]\d)?)?$/;
Stream.prototype.parseTime = function (start, end) {
var s = this.parseStringISO(start, end),
m = this.reTime.exec(s);
if (!m)
return "Unrecognized time: " + s;
s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
if (m[5]) {
s += ":" + m[5];
if (m[6]) {
s += ":" + m[6];
if (m[7])
s += "." + m[7];
}
}
if (m[8]) {
s += " UTC";
if (m[8] != 'Z') {
s += m[8];
if (m[9])
s += ":" + m[9];
}
}
return s;
};
Stream.prototype.parseInteger = function (start, end) {
//TODO support negative numbers
var len = end - start;
if (len > 4) {
len <<= 3;
var s = this.get(start);
if (s === 0)
len -= 8;
else
while (s < 128) {
s <<= 1;
--len;
}
return "(" + len + " bit)";
}
var n = 0;
for (var i = start; i < end; ++i)
n = (n << 8) | this.get(i);
return n;
};
Stream.prototype.parseBitString = function (start, end) {
var unusedBit = this.get(start),
lenBit = ((end - start - 1) << 3) - unusedBit,
s = "(" + lenBit + " bit)";
if (lenBit <= 20) {
var skip = unusedBit;
s += " ";
for (var i = end - 1; i > start; --i) {
var b = this.get(i);
for (var j = skip; j < 8; ++j)
s += (b >> j) & 1 ? "1" : "0";
skip = 0;
}
}
return s;
};
Stream.prototype.parseOctetString = function (start, end) {
var len = end - start,
s = "(" + len + " byte) ";
if (len > hardLimit)
end = start + hardLimit;
for (var i = start; i < end; ++i)
s += this.hexByte(this.get(i)); //TODO: also try Latin1?
if (len > hardLimit)
s += ellipsis;
return s;
};
Stream.prototype.parseOID = function (start, end) {
var s = '',
n = 0,
bits = 0;
for (var i = start; i < end; ++i) {
var v = this.get(i);
n = (n << 7) | (v & 0x7F);
bits += 7;
if (!(v & 0x80)) { // finished
if (s === '') {
var m = n < 80 ? n < 40 ? 0 : 1 : 2;
s = m + "." + (n - m * 40);
} else
s += "." + ((bits >= 31) ? "bigint" : n);
n = bits = 0;
}
}
return s;
};
// export globals
window.ASN1 = ASN1;
})();/**
* Retrieve the hexadecimal value (as a string) of the current ASN.1 element
* @returns {string}
* @public
*/
ASN1.prototype.getHexStringValue = function(){
var hexString = this.toHexString();
var offset = this.header * 2;
var length = this.length * 2;
return hexString.substr(offset,length);
};
/**
* Method to parse a pem encoded string containing both a public or private key.
* The method will translate the pem encoded string in a der encoded string and
* will parse private key and public key parameters. This method accepts public key
* in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
* @todo Check how many rsa formats use the same format of pkcs #1. The format is
defined as:
* PublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* PublicKey BIT STRING
* }
* Where AlgorithmIdentifier is:
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
* parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
* }
* and PublicKey is a SEQUENCE encapsulated in a BIT STRING
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER -- e
* }
* it's possible to examine the structure of the keys obtained from openssl using
* an asn.1 dumper as the one used here to parse the components:
http://lapo.it/asn1js/
* @argument {string} pem the pem encoded string, can include the BEGIN/END
header/footer
* @private
*/
RSAKey.prototype.parseKey = function(pem) {
try{
var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
var asn1 = ASN1.decode(der);
if (asn1.sub.length === 9){
// the data is a Private key
//in order
//Algorithm version, n, e, d, p, q, dmp1, dmq1, coeff
//Alg version, modulus, public exponent, private exponent, prime 1,
prime 2, exponent 1, exponent 2, coefficient
var modulus = asn1.sub[1].getHexStringValue(); //bigint
this.n = parseBigInt(modulus, 16);
}else{
return false;
}
return true;
}catch(ex){
return false;
}
};
/**
* Translate rsa parameters in a hex encoded string representing the rsa key.
* The translation follow the ASN.1 notation :
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* }
* @returns {string} DER Encoded String representing the rsa private key
* @private
*/
RSAKey.prototype.getPrivateBaseKey = function() {
//Algorithm version, n, e, d, p, q, dmp1, dmq1, coeff
//Alg version, modulus, public exponent, private exponent, prime 1, prime 2,
exponent 1, exponent 2, coefficient
var options = {
'array' : [
new KJUR.asn1.DERInteger({'int' : 0}),
new KJUR.asn1.DERInteger({'bigint' : this.n}),
new KJUR.asn1.DERInteger({'int' : this.e}),
new KJUR.asn1.DERInteger({'bigint' : this.d}),
new KJUR.asn1.DERInteger({'bigint' : this.p}),
new KJUR.asn1.DERInteger({'bigint' : this.q}),
new KJUR.asn1.DERInteger({'bigint' : this.dmp1}),
new KJUR.asn1.DERInteger({'bigint' : this.dmq1}),
new KJUR.asn1.DERInteger({'bigint' : this.coeff})
]
};
var seq = new KJUR.asn1.DERSequence(options);
return seq.getEncodedHex();
};
/**
* base64 (pem) encoded version of the DER encoded representation
* @returns {string} pem encoded representation without header and footer
* @public
*/
RSAKey.prototype.getPrivateBaseKeyB64 = function (){
return hex2b64(this.getPrivateBaseKey());
};
/**
* Translate rsa parameters in a hex encoded string representing the rsa public
key.
* The representation follow the ASN.1 notation :
* PublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* PublicKey BIT STRING
* }
* Where AlgorithmIdentifier is:
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
* parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
* }
* and PublicKey is a SEQUENCE encapsulated in a BIT STRING
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER -- e
* }
* @returns {string} DER Encoded String representing the rsa public key
* @private
*/
RSAKey.prototype.getPublicBaseKey = function() {
var options = {
'array' : [
new KJUR.asn1.DERObjectIdentifier({'oid':'1.2.840.113549.1.1.1'}),
//RSA Encryption pkcs #1 oid
new KJUR.asn1.DERNull()
]
};
var first_sequence = new KJUR.asn1.DERSequence(options);
options = {
'array' : [
new KJUR.asn1.DERInteger({'bigint' : this.n}),
new KJUR.asn1.DERInteger({'int' : this.e})
]
};
var second_sequence = new KJUR.asn1.DERSequence(options);
options = {
'hex' : '00'+second_sequence.getEncodedHex()
};
var bit_string = new KJUR.asn1.DERBitString(options);
options = {
'array' : [
first_sequence,
bit_string
]
};
var seq = new KJUR.asn1.DERSequence(options);
return seq.getEncodedHex();
};
/**
* base64 (pem) encoded version of the DER encoded representation
* @returns {string} pem encoded representation without header and footer
* @public
*/
RSAKey.prototype.getPublicBaseKeyB64 = function (){
return hex2b64(this.getPublicBaseKey());
};
/**
* wrap the string in block of width chars. The default value for rsa keys is 64
* characters.
* @param {string} str the pem encoded string without header and footer
* @param {Number} [width=64] - the length the string has to be wrapped at
* @returns {string}
* @private
*/
RSAKey.prototype.wordwrap = function(str, width) {
width = width || 64;
if (!str)
return str;
var regex = '(.{1,' + width + '})( +|$\n?)|(.{1,' + width + '})';
return str.match(RegExp(regex, 'g')).join('\n');
};
/**
* Retrieve the pem encoded private key
* @returns {string} the pem encoded private key with header/footer
* @public
*/
RSAKey.prototype.getPrivateKey = function() {
var key = "-----BEGIN RSA PRIVATE KEY-----\n";
key += this.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
key += "-----END RSA PRIVATE KEY-----";
return key;
};
/**
* Retrieve the pem encoded public key
* @returns {string} the pem encoded public key with header/footer
* @public
*/
RSAKey.prototype.getPublicKey = function() {
var key = "-----BEGIN PUBLIC KEY-----\n";
key += this.wordwrap(this.getPublicBaseKeyB64()) + "\n";
key += "-----END PUBLIC KEY-----";
return key;
};
/**
* Check if the object contains the necessary parameters to populate the rsa
modulus
* and public exponent parameters.
* @param {Object} [obj={}] - An object that may contain the two public key
* parameters
* @returns {boolean} true if the object contains both the modulus and the public
exponent
* properties (n and e)
* @todo check for types of n and e. N should be a parseable bigInt object, E
should
* be a parseable integer number
* @private
*/
RSAKey.prototype.hasPublicKeyProperty = function(obj){
obj = obj || {};
return obj.hasOwnProperty('n') &&
obj.hasOwnProperty('e');
};
/**
* Check if the object contains ALL the parameters of an RSA key.
* @param {Object} [obj={}] - An object that may contain nine rsa key
* parameters
* @returns {boolean} true if the object contains all the parameters needed
* @todo check for types of the parameters all the parameters but the public
exponent
* should be parseable bigint objects, the public exponent should be a parseable
integer number
* @private
*/
RSAKey.prototype.hasPrivateKeyProperty = function(obj){
obj = obj || {};
return obj.hasOwnProperty('n') &&
obj.hasOwnProperty('e') &&
obj.hasOwnProperty('d') &&
obj.hasOwnProperty('p') &&
obj.hasOwnProperty('q') &&
obj.hasOwnProperty('dmp1') &&
obj.hasOwnProperty('dmq1') &&
obj.hasOwnProperty('coeff');
};
/**
* Parse the properties of obj in the current rsa object. Obj should AT LEAST
* include the modulus and public exponent (n, e) parameters.
* @param {Object} obj - the object containing rsa parameters
* @private
*/
RSAKey.prototype.parsePropertiesFrom = function(obj){
this.n = obj.n;
this.e = obj.e;
if (obj.hasOwnProperty('d')){
this.d = obj.d;
this.p = obj.p;
this.q = obj.q;
this.dmp1 = obj.dmp1;
this.dmq1 = obj.dmq1;
this.coeff = obj.coeff;
}
};
/**
* Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
* This object is just a decorator for parsing the key parameter
* @param {string|Object} key - The key in string format, or an object containing
* the parameters needed to build a RSAKey object.
* @constructor
*/
var JSEncryptRSAKey = function(key) {
// Call the super constructor.
RSAKey.call(this);
// If a key key was provided.
if (key) {
// If this is a string...
if (typeof key === 'string') {
this.parseKey(key);
}else if (this.hasPrivateKeyProperty(key)||this.hasPublicKeyProperty(key))
{
// Set the values for the key.
this.parsePropertiesFrom(key);
}
}
};
/**
*
* @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
* possible parameters are:
* - default_key_size {number} default: 1024 the key size in bit
* - default_public_exponent {string} default: '010001' the hexadecimal
representation of the public exponent
* - log {boolean} default: false whether log warn/error or not
* @constructor
*/
var JSEncrypt = function(options) {
options = options || {};
this.default_key_size = parseInt(options.default_key_size) || 1024;
this.default_public_exponent = options.default_public_exponent ||
'010001'; //65537 default openssl public exponent for rsa key type
this.log = options.log || false;
// The private and public key.
this.key = null;
};
/**
* Method to set the rsa key parameter (one method is enough to set both the public
* and the private key, since the private key contains the public key paramenters)
* Log a warning if logs are enabled
* @param {Object|string} key the pem encoded string or an object (with or without
header/footer)
* @public
*/
JSEncrypt.prototype.setKey = function(key){
if (this.log && this.key)
console.warn('A key was already set, overriding existing.');
this.key = new JSEncryptRSAKey(key);
};
/**
* Proxy method for setKey, for api compatibility
* @see setKey
* @public
*/
JSEncrypt.prototype.setPrivateKey = function(privkey) {
// Create the key.
this.setKey(privkey);
};
/**
* Proxy method for setKey, for api compatibility
* @see setKey
* @public
*/
JSEncrypt.prototype.setPublicKey = function(pubkey) {
// Sets the public key.
this.setKey(pubkey);
};
/**
* Proxy method for RSAKey object's decrypt, decrypt the string using the private
* components of the rsa key object. Note that if the object was not set will be
created
* on the fly (by the getKey method) using the parameters passed in the JSEncrypt
constructor
* @param {string} string base64 encoded crypted string to decrypt
* @return {string} the decrypted string
* @public
*/
JSEncrypt.prototype.decrypt = function(string) {
// Return the decrypted string.
try{
return this.getKey().decrypt(b64tohex(string));
}catch(ex){
return false;
}
};
/**
* Proxy method for RSAKey object's encrypt, encrypt the string using the public
* components of the rsa key object. Note that if the object was not set will be
created
* on the fly (by the getKey method) using the parameters passed in the JSEncrypt
constructor
* @param {string} string the string to encrypt
* @return {string} the encrypted string encoded in base64
* @public
*/
JSEncrypt.prototype.encrypt = function(string) {
// Return the encrypted string.
try{
return hex2b64(this.getKey().encrypt(string));
}catch(ex){
return false;
}
};
/**
* Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
* will be created and returned
* @param {callback} [cb] the callback to be called if we want the key to be
generated
* in an async fashion
* @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
* @public
*/
JSEncrypt.prototype.getKey = function(cb){
// Only create new if it does not exist.
if (!this.key) {
// Get a new private key.
this.key = new JSEncryptRSAKey();
if (cb && {}.toString.call(cb) === '[object Function]'){
this.key.generateAsync(this.default_key_size,
this.default_public_exponent,cb);
return;
}
// Generate the key.
this.key.generate(this.default_key_size, this.default_public_exponent);
}
return this.key;
};
/**
* Returns the pem encoded representation of the private key
* If the key doesn't exists a new key will be created
* @returns {string} pem encoded representation of the private key WITH header and
footer
* @public
*/
JSEncrypt.prototype.getPrivateKey = function() {
// Return the private representation of this key.
return this.getKey().getPrivateKey();
};
/**
* Returns the pem encoded representation of the private key
* If the key doesn't exists a new key will be created
* @returns {string} pem encoded representation of the private key WITHOUT header
and footer
* @public
*/
JSEncrypt.prototype.getPrivateKeyB64 = function() {
// Return the private representation of this key.
return this.getKey().getPrivateBaseKeyB64();
};
/**
* Returns the pem encoded representation of the public key
* If the key doesn't exists a new key will be created
* @returns {string} pem encoded representation of the public key WITH header and
footer
* @public
*/
JSEncrypt.prototype.getPublicKey = function() {
// Return the private representation of this key.
return this.getKey().getPublicKey();
};
/**
* Returns the pem encoded representation of the public key
* If the key doesn't exists a new key will be created
* @returns {string} pem encoded representation of the public key WITHOUT header
and footer
* @public
*/
JSEncrypt.prototype.getPublicKeyB64 = function() {
// Return the private representation of this key.
return this.getKey().getPublicBaseKeyB64();
};
exports.JSEncrypt = JSEncrypt;
})(JSEncryptExports);
var JSEncrypt = JSEncryptExports.JSEncrypt;
// Important call
$.jCryption.crypt = new JSEncrypt();
/* http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js */
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
var CryptoJS=CryptoJS||function(u,p){var d={},l=d.lib={},s=function()
{},t=l.Base={extend:function(a){s.prototype=this;var c=new
s;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.
$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return
c},create:function(){var a=this.extend();a.init.apply(a,arguments);return
a},init:function(){},mixIn:function(a){for(var c in
a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=
a.toString)},clone:function(){return this.init.prototype.extend(this)}},
r=l.WordArray=t.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=p?
c:4*a.length},toString:function(a){return(a||v).stringify(this)},concat:function(a)
{var c=this.words,e=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j
%4)for(var k=0;k<a;k++)c[j+k>>>2]|=(e[k>>>2]>>>24-8*(k%4)&255)<<24-8*((j+k)%4);else
if(65535<e.length)for(k=0;k<a;k+=4)c[j+k>>>2]=e[k>>>2];else
c.push.apply(c,e);this.sigBytes+=a;return this},clamp:function(){var
a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
32-8*(c%4);a.length=u.ceil(c/4)},clone:function(){var
a=t.clone.call(this);a.words=this.words.slice(0);return a},random:function(a)
{for(var c=[],e=0;e<a;e+=4)c.push(4294967296*u.random()|0);return new
r.init(c,a)}}),w=d.enc={},v=w.Hex={stringify:function(a){var
c=a.words;a=a.sigBytes;for(var e=[],j=0;j<a;j++){var k=c[j>>>2]>>>24-8*(j
%4)&255;e.push((k>>>4).toString(16));e.push((k&15).toString(16))}return
e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j<c;j+=2)e[j>>>3]|
=parseInt(a.substr(j,
2),16)<<24-4*(j%8);return new r.init(e,c/2)}},b=w.Latin1={stringify:function(a){var
c=a.words;a=a.sigBytes;for(var e=[],j=0;j<a;j+
+)e.push(String.fromCharCode(c[j>>>2]>>>24-8*(j%4)&255));return
e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j<c;j++)e[j>>>2]|
=(a.charCodeAt(j)&255)<<24-8*(j%4);return new
r.init(e,c)}},x=w.Utf8={stringify:function(a){try{return
decodeURIComponent(escape(b.stringify(a)))}catch(c){throw Error("Malformed UTF-8
data");}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}},
q=l.BufferedBlockAlgorithm=t.extend({reset:function(){this._data=new
r.init;this._nDataBytes=0},_append:function(a){"string"==typeof
a&&(a=x.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:funct
ion(a){var c=this._data,e=c.words,j=c.sigBytes,k=this.blockSize,b=j/(4*k),b=a?
u.ceil(b):u.max((b|0)-this._minBufferSize,0);a=b*k;j=u.min(4*a,j);if(a){for(var
q=0;q<a;q+=k)this._doProcessBlock(e,q);q=e.splice(0,a);c.sigBytes-=j}return new
r.init(q,j)},clone:function(){var a=t.clone.call(this);
a._data=this._data.clone();return
a},_minBufferSize:0});l.Hasher=q.extend({cfg:t.extend(),init:function(a)
{this.cfg=this.cfg.extend(a);this.reset()},reset:function()
{q.reset.call(this);this._doReset()},update:function(a)
{this._append(a);this._process();return this},finalize:function(a)
{a&&this._append(a);return
this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,e)
{return(new a.init(e)).finalize(b)}},_createHmacHelper:function(a){return
function(b,e){return(new n.HMAC.init(a,
e)).finalize(b)}}});var n=d.algo={};return d}(Math);
(function(){var u=CryptoJS,p=u.lib.WordArray;u.enc.Base64={stringify:function(d)
{var l=d.words,p=d.sigBytes,t=this._map;d.clamp();d=[];for(var r=0;r<p;r+=3)for(var
w=(l[r>>>2]>>>24-8*(r%4)&255)<<16|(l[r+1>>>2]>>>24-8*((r+1)%4)&255)<<8|
l[r+2>>>2]>>>24-8*((r+2)%4)&255,v=0;4>v&&r+0.75*v<p;v++)d.push(t.charAt(w>>>6*(3-
v)&63));if(l=t.charAt(64))for(;d.length%4;)d.push(l);return
d.join("")},parse:function(d){var
l=d.length,s=this._map,t=s.charAt(64);t&&(t=d.indexOf(t),-1!=t&&(l=t));for(var
t=[],r=0,w=0;w<
l;w++)if(w%4){var v=s.indexOf(d.charAt(w-1))<<2*(w%4),b=s.indexOf(d.charAt(w))>>>6-
2*(w%4);t[r>>>2]|=(v|b)<<24-8*(r%4);r++}return
p.create(t,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
+/="}})();
(function(u){function p(b,n,a,c,e,j,k){b=b+(n&a|~n&c)+e+k;return(b<<j|b>>>32-j)
+n}function d(b,n,a,c,e,j,k){b=b+(n&c|a&~c)+e+k;return(b<<j|b>>>32-j)+n}function
l(b,n,a,c,e,j,k){b=b+(n^a^c)+e+k;return(b<<j|b>>>32-j)+n}function s(b,n,a,c,e,j,k)
{b=b+(a^(n|~c))+e+k;return(b<<j|b>>>32-j)+n}for(var
t=CryptoJS,r=t.lib,w=r.WordArray,v=r.Hasher,r=t.algo,b=[],x=0;64>x;x+
+)b[x]=4294967296*u.abs(u.sin(x+1))|0;r=r.MD5=v.extend({_doReset:function()
{this._hash=new w.init([1732584193,4023233417,2562383102,271733878])},
_doProcessBlock:function(q,n){for(var a=0;16>a;a++){var c=n+a,e=q[c];q[c]=(e<<8|
e>>>24)&16711935|(e<<24|e>>>8)&4278255360}var
a=this._hash.words,c=q[n+0],e=q[n+1],j=q[n+2],k=q[n+3],z=q[n+4],r=q[n+5],t=q[n+6],w
=q[n+7],v=q[n+8],A=q[n+9],B=q[n+10],C=q[n+11],u=q[n+12],D=q[n+13],E=q[n+14],x=q[n+1
5],f=a[0],m=a[1],g=a[2],h=a[3],f=p(f,m,g,h,c,7,b[0]),h=p(h,f,m,g,e,12,b[1]),g=p(g,h
,f,m,j,17,b[2]),m=p(m,g,h,f,k,22,b[3]),f=p(f,m,g,h,z,7,b[4]),h=p(h,f,m,g,r,12,b[5])
,g=p(g,h,f,m,t,17,b[6]),m=p(m,g,h,f,w,22,b[7]),
f=p(f,m,g,h,v,7,b[8]),h=p(h,f,m,g,A,12,b[9]),g=p(g,h,f,m,B,17,b[10]),m=p(m,g,h,f,C,
22,b[11]),f=p(f,m,g,h,u,7,b[12]),h=p(h,f,m,g,D,12,b[13]),g=p(g,h,f,m,E,17,b[14]),m=
p(m,g,h,f,x,22,b[15]),f=d(f,m,g,h,e,5,b[16]),h=d(h,f,m,g,t,9,b[17]),g=d(g,h,f,m,C,1
4,b[18]),m=d(m,g,h,f,c,20,b[19]),f=d(f,m,g,h,r,5,b[20]),h=d(h,f,m,g,B,9,b[21]),g=d(
g,h,f,m,x,14,b[22]),m=d(m,g,h,f,z,20,b[23]),f=d(f,m,g,h,A,5,b[24]),h=d(h,f,m,g,E,9,
b[25]),g=d(g,h,f,m,k,14,b[26]),m=d(m,g,h,f,v,20,b[27]),f=d(f,m,g,h,D,5,b[28]),h=d(h
,f,
m,g,j,9,b[29]),g=d(g,h,f,m,w,14,b[30]),m=d(m,g,h,f,u,20,b[31]),f=l(f,m,g,h,r,4,b[32
]),h=l(h,f,m,g,v,11,b[33]),g=l(g,h,f,m,C,16,b[34]),m=l(m,g,h,f,E,23,b[35]),f=l(f,m,
g,h,e,4,b[36]),h=l(h,f,m,g,z,11,b[37]),g=l(g,h,f,m,w,16,b[38]),m=l(m,g,h,f,B,23,b[3
9]),f=l(f,m,g,h,D,4,b[40]),h=l(h,f,m,g,c,11,b[41]),g=l(g,h,f,m,k,16,b[42]),m=l(m,g,
h,f,t,23,b[43]),f=l(f,m,g,h,A,4,b[44]),h=l(h,f,m,g,u,11,b[45]),g=l(g,h,f,m,x,16,b[4
6]),m=l(m,g,h,f,j,23,b[47]),f=s(f,m,g,h,c,6,b[48]),h=s(h,f,m,g,w,10,b[49]),g=s(g,h,
f,m,
E,15,b[50]),m=s(m,g,h,f,r,21,b[51]),f=s(f,m,g,h,u,6,b[52]),h=s(h,f,m,g,k,10,b[53]),
g=s(g,h,f,m,B,15,b[54]),m=s(m,g,h,f,e,21,b[55]),f=s(f,m,g,h,v,6,b[56]),h=s(h,f,m,g,
x,10,b[57]),g=s(g,h,f,m,t,15,b[58]),m=s(m,g,h,f,D,21,b[59]),f=s(f,m,g,h,z,6,b[60]),
h=s(h,f,m,g,C,10,b[61]),g=s(g,h,f,m,j,15,b[62]),m=s(m,g,h,f,A,21,b[63]);a[0]=a[0]+f
|0;a[1]=a[1]+m|0;a[2]=a[2]+g|0;a[3]=a[3]+h|0},_doFinalize:function(){var
b=this._data,n=b.words,a=8*this._nDataBytes,c=8*b.sigBytes;n[c>>>5]|=128<<24-c
%32;var e=u.floor(a/
4294967296);n[(c+64>>>9<<4)+15]=(e<<8|e>>>24)&16711935|(e<<24|
e>>>8)&4278255360;n[(c+64>>>9<<4)+14]=(a<<8|a>>>24)&16711935|(a<<24|
a>>>8)&4278255360;b.sigBytes=4*(n.length+1);this._process();b=this._hash;n=b.words;
for(a=0;4>a;a++)c=n[a],n[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return
b},clone:function(){var b=v.clone.call(this);b._hash=this._hash.clone();return
b}});t.MD5=v._createHelper(r);t.HmacMD5=v._createHmacHelper(r)})(Math);
(function(){var
u=CryptoJS,p=u.lib,d=p.Base,l=p.WordArray,p=u.algo,s=p.EvpKDF=d.extend({cfg:d.exten
d({keySize:4,hasher:p.MD5,iterations:1}),init:function(d)
{this.cfg=this.cfg.extend(d)},compute:function(d,r){for(var
p=this.cfg,s=p.hasher.create(),b=l.create(),u=b.words,q=p.keySize,p=p.iterations;u.
length<q;){n&&s.update(n);var n=s.update(d).finalize(r);s.reset();for(var
a=1;a<p;a++)n=s.finalize(n),s.reset();b.concat(n)}b.sigBytes=4*q;return
b}});u.EvpKDF=function(d,l,p){return s.create(p).compute(d,
l)}})();
CryptoJS.lib.Cipher||function(u){var
p=CryptoJS,d=p.lib,l=d.Base,s=d.WordArray,t=d.BufferedBlockAlgorithm,r=p.enc.Base64
,w=p.algo.EvpKDF,v=d.Cipher=t.extend({cfg:l.extend(),createEncryptor:function(e,a)
{return this.create(this._ENC_XFORM_MODE,e,a)},createDecryptor:function(e,a){return
this.create(this._DEC_XFORM_MODE,e,a)},init:function(e,a,b)
{this.cfg=this.cfg.extend(b);this._xformMode=e;this._key=a;this.reset()},reset:func
tion(){t.reset.call(this);this._doReset()},process:function(e)
{this._append(e);return this._process()},
finalize:function(e){e&&this._append(e);return
this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createH
elper:function(e){return{encrypt:function(b,k,d){return("string"==typeof k?
c:a).encrypt(e,b,k,d)},decrypt:function(b,k,d){return("string"==typeof k?
c:a).decrypt(e,b,k,d)}}}});d.StreamCipher=v.extend({_doFinalize:function(){return
this._process(!0)},blockSize:1});var b=p.mode={},x=function(e,a,b){var
c=this._iv;c?this._iv=u:c=this._prevBlock;for(var d=0;d<b;d++)e[a+d]^=
c[d]},q=(d.BlockCipherMode=l.extend({createEncryptor:function(e,a){return
this.Encryptor.create(e,a)},createDecryptor:function(e,a){return
this.Decryptor.create(e,a)},init:function(e,a)
{this._cipher=e;this._iv=a}})).extend();q.Encryptor=q.extend({processBlock:function
(e,a){var
b=this._cipher,c=b.blockSize;x.call(this,e,a,c);b.encryptBlock(e,a);this._prevBlock
=e.slice(a,a+c)}});q.Decryptor=q.extend({processBlock:function(e,a){var
b=this._cipher,c=b.blockSize,d=e.slice(a,a+c);b.decryptBlock(e,a);x.call(this,
e,a,c);this._prevBlock=d}});b=b.CBC=q;q=(p.pad={}).Pkcs7={pad:function(a,b){for(var
c=4*b,c=c-a.sigBytes%c,d=c<<24|c<<16|c<<8|
c,l=[],n=0;n<c;n+=4)l.push(d);c=s.create(l,c);a.concat(c)},unpad:function(a)
{a.sigBytes-=a.words[a.sigBytes-
1>>>2]&255}};d.BlockCipher=v.extend({cfg:v.cfg.extend({mode:b,padding:q}),reset:fun
ction(){v.reset.call(this);var
a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var
c=a.createEncryptor;else
c=a.createDecryptor,this._minBufferSize=1;this._mode=c.call(a,
this,b&&b.words)},_doProcessBlock:function(a,b)
{this._mode.processBlock(a,b)},_doFinalize:function(){var
a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE)
{a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!
0),a.unpad(b);return b},blockSize:4});var
n=d.CipherParams=l.extend({init:function(a){this.mixIn(a)},toString:function(a)
{return(a||
this.formatter).stringify(this)}}),b=(p.format={}).OpenSSL={stringify:function(a)
{var b=a.ciphertext;a=a.salt;return(a?s.create([1398893684,
1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var
b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var
c=s.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return
n.create({ciphertext:a,salt:c})}},a=d.SerializableCipher=l.extend({cfg:l.extend({fo
rmat:b}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var
l=a.createEncryptor(c,d);b=l.finalize(b);l=l.cfg;return
n.create({ciphertext:b,key:c,iv:l.iv,algorithm:a,mode:l.mode,padding:l.padding,bloc
kSize:a.blockSize,formatter:d.format})},
decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return
a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b)
{return"string"==typeof a?
b.parse(a,this):a}}),p=(p.kdf={}).OpenSSL={execute:function(a,b,c,d){d||
(d=s.random(8));a=w.create({keySize:b+c}).compute(a,d);c=s.create(a.words.slice(b),
4*c);a.sigBytes=4*b;return
n.create({key:a,iv:c,salt:d})}},c=d.PasswordBasedCipher=a.extend({cfg:a.cfg.extend(
{kdf:p}),encrypt:function(b,c,d,l){l=this.cfg.extend(l);d=l.kdf.execute(d,
b.keySize,b.ivSize);l.iv=d.iv;b=a.encrypt.call(this,b,c,d.key,l);b.mixIn(d);return
b},decrypt:function(b,c,d,l)
{l=this.cfg.extend(l);c=this._parse(c,l.format);d=l.kdf.execute(d,b.keySize,b.ivSiz
e,c.salt);l.iv=d.iv;return a.decrypt.call(this,b,c,d.key,l)}})}();
(function(){for(var
u=CryptoJS,p=u.lib.BlockCipher,d=u.algo,l=[],s=[],t=[],r=[],w=[],v=[],b=[],x=[],q=[
],n=[],a=[],c=0;256>c;c++)a[c]=128>c?c<<1:c<<1^283;for(var e=0,j=0,c=0;256>c;c++)
{var k=j^j<<1^j<<2^j<<3^j<<4,k=k>>>8^k&255^99;l[e]=k;s[k]=e;var
z=a[e],F=a[z],G=a[F],y=257*a[k]^16843008*k;t[e]=y<<24|y>>>8;r[e]=y<<16|
y>>>16;w[e]=y<<8|y>>>24;v[e]=y;y=16843009*G^65537*F^257*z^16843008*e;b[k]=y<<24|
y>>>8;x[k]=y<<16|y>>>16;q[k]=y<<8|y>>>24;n[k]=y;e?
(e=z^a[a[a[G^z]]],j^=a[a[j]]):e=j=1}var H=[0,1,2,4,8,
16,32,64,128,27,54],d=d.AES=p.extend({_doReset:function(){for(var
a=this._key,c=a.words,d=a.sigBytes/4,a=4*((this._nRounds=d+6)+1),e=this._keySchedul
e=[],j=0;j<a;j++)if(j<d)e[j]=c[j];else{var k=e[j-1];j%d?6<d&&4==j
%d&&(k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255]):(k=k<<8|
k>>>24,k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255],k^=H[j/d|
0]<<24);e[j]=e[j-d]^k}c=this._invKeySchedule=[];for(d=0;d<a;d++)j=a-d,k=d%4?
e[j]:e[j-4],c[d]=4>d||4>=j?k:b[l[k>>>24]]^x[l[k>>>16&255]]^q[l[k>>>
8&255]]^n[l[k&255]]},encryptBlock:function(a,b)
{this._doCryptBlock(a,b,this._keySchedule,t,r,w,v,l)},decryptBlock:function(a,c)
{var
d=a[c+1];a[c+1]=a[c+3];a[c+3]=d;this._doCryptBlock(a,c,this._invKeySchedule,b,x,q,n
,s);d=a[c+1];a[c+1]=a[c+3];a[c+3]=d},_doCryptBlock:function(a,b,c,d,e,j,l,f)
{for(var
m=this._nRounds,g=a[b]^c[0],h=a[b+1]^c[1],k=a[b+2]^c[2],n=a[b+3]^c[3],p=4,r=1;r<m;r
++)var q=d[g>>>24]^e[h>>>16&255]^j[k>>>8&255]^l[n&255]^c[p+
+],s=d[h>>>24]^e[k>>>16&255]^j[n>>>8&255]^l[g&255]^c[p++],t=
d[k>>>24]^e[n>>>16&255]^j[g>>>8&255]^l[h&255]^c[p+
+],n=d[n>>>24]^e[g>>>16&255]^j[h>>>8&255]^l[k&255]^c[p+
+],g=q,h=s,k=t;q=(f[g>>>24]<<24|f[h>>>16&255]<<16|f[k>>>8&255]<<8|f[n&255])^c[p+
+];s=(f[h>>>24]<<24|f[k>>>16&255]<<16|f[n>>>8&255]<<8|f[g&255])^c[p+
+];t=(f[k>>>24]<<24|f[n>>>16&255]<<16|f[g>>>8&255]<<8|f[h&255])^c[p+
+];n=(f[n>>>24]<<24|f[g>>>16&255]<<16|f[h>>>8&255]<<8|f[k&255])^c[p+
+];a[b]=q;a[b+1]=s;a[b+2]=t;a[b+3]=n},keySize:8});u.AES=p._createHelper(d)})();