diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fa52d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git +node_modules + +# Users Environment Variables +.lock-wscript + + +######## Webstorm/Idea directories +.idea + diff --git a/README.md b/README.md index ec69581..9dff08e 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ var EncryptionResult = cryptico.encrypt(PlainText, MattsPublicKeyString, SamsRSA The public key associated with the signature can be used by Matt to make sure that it was sent by Sam, but there are a lot of characters to examine in the key - it would be easy to make a mistake. Instead, the public key string associated with the signature can be processed like this: ```javascript -var PublicKeyID = cryptico.publicKeyID(EncryptionResult.publickey); +var PublicKeyID = cryptico.publicKeyID(EncryptionResult.cipher); ``` and `PublicKeyID` would look something like this: @@ -193,4 +193,4 @@ plaintext, the public key of the sender, and the signature: signature This concatenated block is then encrypted with CBC AES and concatenated with the -encrypted AES key to form the complete encrypted message. \ No newline at end of file +encrypted AES key to form the complete encrypted message. diff --git a/build b/build deleted file mode 100755 index 651533b..0000000 --- a/build +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env sh - -cat ./src/jsbn.js ./src/random.js ./src/hash.js ./src/rsa.js ./src/aes.js ./src/api.js > ./lib/cryptico.js \ No newline at end of file diff --git a/dist/cryptico.amd.js b/dist/cryptico.amd.js new file mode 100644 index 0000000..fd418ea --- /dev/null +++ b/dist/cryptico.amd.js @@ -0,0 +1,4852 @@ +/* cryptico-js v1.0.4 - - https://github.com/tracker1/cryptico-js */ + +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o> 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; +} + +BigInteger.prototype.am = am; +dbits = 30; + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1 << dbits) - 1); +BigInteger.prototype.DV = (1 << dbits); + +var BI_FP = 52; +BigInteger.prototype.FV = Math.pow(2, BI_FP); +BigInteger.prototype.F1 = BI_FP - dbits; +BigInteger.prototype.F2 = 2 * dbits - BI_FP; + +// Digit conversions +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; +var BI_RC = new Array(); +var rr, vv; +rr = "0".charCodeAt(0); +for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; +rr = "a".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; +rr = "A".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + +function int2char(n) { + return BI_RM.charAt(n); +} + +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; +} + +// (protected) copy this to r + +function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV + +function bnpFromInt(x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + DV; + else this.t = 0; +} + +// return bigint initialized to value + +function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; +} + +// (protected) set from string and radix + +function bnpFromString(s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; // byte array + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = (k == 8) ? s[i] & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if (sh == 0) this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } + else this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 0x80) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); +} + +// (protected) clamp off excess high words + +function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c)--this.t; +} + +// (public) return string representation in given radix + +function bnToString(b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 64) k = 6; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, + d, m = false, + r = "", + i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } + else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : "0"; +} + +// (public) -this + +function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; +} + +// (public) |this| + +function bnAbs() { + return (this.s < 0) ? this.negate() : this; +} + +// (public) return + if this > a, - if this < a, 0 if equal + +function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return r; + while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x + +function nbits(x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; +} + +// (public) return the number of bits in "this" + +function bnBitLength() { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); +} + +// (protected) r = this << n*DB + +function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; +} + +// (protected) r = this >> n*DB + +function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; +} + +// (protected) r = this << n + +function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n + +function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); +} + +// (protected) r = this - a + +function bnpSubTo(a, r) { + var i = 0, + c = 0, + m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. + +function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); +} + +// (protected) r = this^2, r != this (HAC 14.16) + +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. + +function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), + ts = this.s, + ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } + else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) r.subTo(t, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r); +} + +// (public) this mod a + +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; +} + +// Modular reduction using "classic" algorithm + +function Classic(m) { + this.m = m; +} + +function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} + +function cRevert(x) { + return x; +} + +function cReduce(x) { + x.divRemTo(this.m, null, x); +} + +function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. + +function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; +} + +// Montgomery reduction + +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; +} + +// xR mod m + +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; +} + +// x/R mod m + +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) + +function montReduce(x) { + while (x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); +} + +// r = "x^2/R mod m"; x != r + +function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +// r = "xy/R mod m"; x,y != r + +function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even + +function bnpIsEven() { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; +} + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + +function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 + +function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + + +function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; +} + +// (public) return value as integer + +function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } + else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; +} + +// (public) return value as byte + +function bnByteValue() { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; +} + +// (public) return value as short (assumes DB>=16) + +function bnShortValue() { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; +} + +// (protected) return x s.t. r^x < DV + +function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); +} + +// (public) 0 if this == 0, 1 if this > 0 + +function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; +} + +// (protected) convert to radix string + +function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), + y = nbi(), + z = nbi(), + r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; +} + +// (protected) convert from radix string + +function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); +} + +// (protected) alternate constructor + +function bnpFromNumber(a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= ((1 << t) - 1); + else x[0] = 0; + this.fromString(x, 256); + } +} + +// (public) convert to bigendian byte array + +function bnToByteArray() { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8, + d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } + else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) d |= -256; + if (k == 0 && (this.s & 0x80) != (d & 0x80))++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; +} + +function bnEquals(a) { + return (this.compareTo(a) == 0); +} + +function bnMin(a) { + return (this.compareTo(a) < 0) ? this : a; +} + +function bnMax(a) { + return (this.compareTo(a) > 0) ? this : a; +} + +// (protected) r = this op a (bitwise) + +function bnpBitwiseTo(a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } + else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); +} + +// (public) this & a + +function op_and(x, y) { + return x & y; +} + +function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; +} + +// (public) this | a + +function op_or(x, y) { + return x | y; +} + +function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; +} + +// (public) this ^ a + +function op_xor(x, y) { + return x ^ y; +} + +function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; +} + +// (public) this & ~a + +function op_andnot(x, y) { + return x & ~y; +} + +function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; +} + +// (public) ~this + +function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; +} + +// (public) this << n + +function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; +} + +// (public) this >> n + +function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; +} + +// return index of lowest 1-bit in x, x < 2^31 + +function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0)++r; + return r; +} + +// (public) returns index of lowest 1-bit (or -1 if none) + +function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; +} + +// return number of 1 bits in x + +function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; +} + +// (public) return number of set bits + +function bnBitCount() { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; +} + +// (public) true iff nth bit is set + +function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return (this.s != 0); + return ((this[j] & (1 << (n % this.DB))) != 0); +} + +// (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); +} + +// (public) this + a + +function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; +} + +// (public) this - a + +function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; +} + +// (public) this * a + +function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; +} + +// (public) this^2 + +function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; +} + +// (public) this / a + +function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; +} + +// (public) this % a + +function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; +} + +// (public) [this/a,this%a] + +function bnDivideAndRemainder(a) { + var q = nbi(), + r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); +} + +// (protected) this *= n, this >= 0, 1 < n < DV + +function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); +} + +// (protected) this += n << w words, this >= 0 + +function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; + } +} + +// A "null" reducer + +function NullExp() {} + +function nNop(x) { + return x; +} + +function nMulTo(x, y, r) { + x.multiplyTo(y, r); +} + +function nSqrTo(x, r) { + x.squareTo(r); +} + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +// (public) this^e + +function bnPow(e) { + return this.exp(e, new NullExp()); +} + +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. + +function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); +} + +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. + +function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); +} + +// Barrett modular reduction + +function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; +} + +function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } +} + +function barrettRevert(x) { + return x; +} + +// x = x mod m (HAC 14.42) + +function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); +} + +// r = x^2 mod m; x != r + +function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +// r = x*y mod m; x,y != r + +function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +// (public) this^e % m (HAC 14.85) + +function bnModPow(e, m) { + var i = e.bitLength(), + k, r = nbv(1), + z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) z = new Classic(m); + else if (m.isEven()) z = new Barrett(m); + else z = new Montgomery(m); + + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + + var j = e.t - 1, + w, is1 = true, + r2 = nbi(), + t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km; + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); + } + + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); +} + +// (public) gcd(this,a) (HAC 14.54) + +function bnGCD(a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; +} + +// (protected) this % n, n < 2^26 + +function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) if (d == 0) r = this[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; +} + +// (public) 1/this % m (HAC 14.61) + +function bnModInverse(m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), + v = this.clone(); + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } + else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } + else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } + else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; +} + +var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + +// (public) test primality with certainty >= 1-.5^t + +function bnIsProbablePrime(t) { + var i, x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); +} + +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) + +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; +} + +// protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +// public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +// JSBN-specific extension +BigInteger.prototype.square = bnSquare; +// seedrandom.js version 2.0. +// Author: David Bau 4/2/2011 +// +// Defines a method Math.seedrandom() that, when called, substitutes +// an explicitly seeded RC4-based algorithm for Math.random(). Also +// supports automatic seeding from local or network sources of entropy. +// +// Usage: +// +// +// +// Math.seedrandom('yipee'); Sets Math.random to a function that is +// initialized using the given explicit seed. +// +// Math.seedrandom(); Sets Math.random to a function that is +// seeded using the current time, dom state, +// and other accumulated local entropy. +// The generated seed string is returned. +// +// Math.seedrandom('yowza', true); +// Seeds using the given explicit seed mixed +// together with accumulated entropy. +// +// +// Seeds using physical random bits downloaded +// from random.org. +// +// Seeds using urandom bits from call.jsonlib.com, +// which is faster than random.org. +// +// Examples: +// +// Math.seedrandom("hello"); // Use "hello" as the seed. +// document.write(Math.random()); // Always 0.5463663768140734 +// document.write(Math.random()); // Always 0.43973793770592234 +// var rng1 = Math.random; // Remember the current prng. +// +// var autoseed = Math.seedrandom(); // New prng with an automatic seed. +// document.write(Math.random()); // Pretty much unpredictable. +// +// Math.random = rng1; // Continue "hello" prng sequence. +// document.write(Math.random()); // Always 0.554769432473455 +// +// Math.seedrandom(autoseed); // Restart at the previous seed. +// document.write(Math.random()); // Repeat the 'unpredictable' value. +// +// Notes: +// +// Each time seedrandom('arg') is called, entropy from the passed seed +// is accumulated in a pool to help generate future seeds for the +// zero-argument form of Math.seedrandom, so entropy can be injected over +// time by calling seedrandom with explicit data repeatedly. +// +// On speed - This javascript implementation of Math.random() is about +// 3-10x slower than the built-in Math.random() because it is not native +// code, but this is typically fast enough anyway. Seeding is more expensive, +// especially if you use auto-seeding. Some details (timings on Chrome 4): +// +// Our Math.random() - avg less than 0.002 milliseconds per call +// seedrandom('explicit') - avg less than 0.5 milliseconds per call +// seedrandom('explicit', true) - avg less than 2 milliseconds per call +// seedrandom() - avg about 38 milliseconds per call +// +// LICENSE (BSD): +// +// Copyright 2010 David Bau, all rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. Neither the name of this module nor the names of its contributors may +// be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/** + * All code is in an anonymous closure to keep the global namespace clean. + * + * @param {number=} overflow + * @param {number=} startdenom + */ +(function (pool, math, width, chunks, significance, overflow, startdenom) +{ + + + // + // seedrandom() + // This is the seedrandom function described above. + // + math['seedrandom'] = function seedrandom(seed, use_entropy) + { + var key = []; + var arc4; + + // Flatten the seed string or build one from local entropy if needed. + seed = mixkey(flatten( + use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool], 3), key); + + // Use the seed to initialize an ARC4 generator. + arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(arc4.S, pool); + + // Override Math.random + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + math['random'] = function random() + { // Closure to return a random double: + var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 + var d = startdenom; // and denominator d = 2 ^ 48. + var x = 0; // and no 'extra last byte'. + while (n < significance) + { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) + { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + // Return the seed that was used + return seed; + }; + + // + // ARC4 + // + // An ARC4 implementation. The constructor takes a key in the form of + // an array of at most (width) integers that should be 0 <= x < (width). + // + // The g(count) method returns a pseudorandom integer that concatenates + // the next (count) outputs from ARC4. Its return value is a number x + // that is in the range 0 <= x < (width ^ count). + // + /** @constructor */ + + function ARC4(key) + { + var t, u, me = this, + keylen = key.length; + var i = 0, + j = me.i = me.j = me.m = 0; + me.S = []; + me.c = []; + + // The empty key [] is treated as [0]. + if (!keylen) + { + key = [keylen++]; + } + + // Set up S using the standard key scheduling algorithm. + while (i < width) + { + me.S[i] = i++; + } + for (i = 0; i < width; i++) + { + t = me.S[i]; + j = lowbits(j + t + key[i % keylen]); + u = me.S[j]; + me.S[i] = u; + me.S[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + me.g = function getnext(count) + { + var s = me.S; + var i = lowbits(me.i + 1); + var t = s[i]; + var j = lowbits(me.j + t); + var u = s[j]; + s[i] = u; + s[j] = t; + var r = s[lowbits(t + u)]; + while (--count) + { + i = lowbits(i + 1); + t = s[i]; + j = lowbits(j + t); + u = s[j]; + s[i] = u; + s[j] = t; + r = r * width + s[lowbits(t + u)]; + } + me.i = i; + me.j = j; + return r; + }; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + me.g(width); + } + + // + // flatten() + // Converts an object tree to nested arrays of strings. + // + /** @param {Object=} result + * @param {string=} prop + * @param {string=} typ */ + + function flatten(obj, depth, result, prop, typ) + { + result = []; + typ = typeof (obj); + if (depth && typ == 'object') + { + for (prop in obj) + { + if (prop.indexOf('S') < 5) + { // Avoid FF3 bug (local/sessionStorage) + try + { + result.push(flatten(obj[prop], depth - 1)); + } + catch (e) + {} + } + } + } + return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); + } + + // + // mixkey() + // Mixes a string seed into a key that is an array of integers, and + // returns a shortened string seed that is equivalent to the result key. + // + /** @param {number=} smear + * @param {number=} j */ + + function mixkey(seed, key, smear, j) + { + seed += ''; // Ensure the seed is a string + smear = 0; + for (j = 0; j < seed.length; j++) + { + key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); + } + seed = ''; + for (j in key) + { + seed += String.fromCharCode(key[j]); + } + return seed; + } + + // + // lowbits() + // A quick "n mod width" for width a power of 2. + // + + + function lowbits(n) + { + return n & (width - 1); + } + + // + // The following constants are related to IEEE 754 limits. + // + startdenom = math.pow(width, chunks); + significance = math.pow(2, significance); + overflow = significance * 2; + + // + // When seedrandom.js is loaded, we immediately mix a few bits + // from the built-in RNG into the entropy pool. Because we do + // not want to intefere with determinstic PRNG state later, + // seedrandom will not call math.random on its own again after + // initialization. + // + mixkey(math.random(), pool); + + // End anonymous scope, and pass initial values. +})([], // pool: entropy pool starts empty +Math, // math: package containing random, pow, and seedrandom +256, // width: each RC4 output is 0 <= x < 256 +6, // chunks: at least six RC4 outputs for each double +52 // significance: there are 52 significant digits in a double +); + + +// This is not really a random number generator object, and two SeededRandom +// objects will conflict with one another, but it's good enough for generating +// the rsa key. +function SeededRandom(){} + +function SRnextBytes(ba) +{ + var i; + for(i = 0; i < ba.length; i++) + { + ba[i] = Math.floor(Math.random() * 256); + } +} + +SeededRandom.prototype.nextBytes = SRnextBytes; + +// prng4.js - uses Arcfour as a PRNG + +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; + +// Plug in your RNG constructor here +function prng_newstate() { + return new Arcfour(); +} + +// Pool size must be a multiple of 4 and greater than 32. +// An array of bytes the size of the pool will be passed to init() +var rng_psize = 256; + +// Random number generator - requires a PRNG backend, e.g. prng4.js + +// For best results, put code like +// +// in your main HTML document. + +var rng_state; +var rng_pool; +var rng_pptr; + +// Mix in a 32-bit integer into the pool +function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; +} + +// Mix in the current time (w/milliseconds) into the pool +function rng_seed_time() { + rng_seed_int(new Date().getTime()); +} + +// Initialize the pool with junk if needed. +if(rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + while(rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + //rng_seed_int(window.screenX); + //rng_seed_int(window.screenY); +} + +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; +/** +* +* Secure Hash Algorithm (SHA256) +* http://www.webtoolkit.info/ +* +* Original code by Angel Marin, Paul Johnston. +* +**/ + +var crypto = require('crypto'); + +function SHA256(s){ + return crypto.createHash('sha256').update(s, 'utf8').digest('hex'); +} + +var sha256 = {} +sha256.hex = function(s) +{ + return SHA256(s); +} + +/** +* +* Secure Hash Algorithm (SHA1) +* http://www.webtoolkit.info/ +* +**/ + +function SHA1 (msg) { + return crypto.createHash('sha1').update(msg, 'utf8').digest('hex'); +} + +var sha1 = {} +sha1.hex = function(s) +{ + return SHA1(s); +} + +/** +* +* MD5 (Message-Digest Algorithm) +* http://www.webtoolkit.info/ +* +**/ + +var MD5 = function (string) { + return crypto.createHash('md5').update(string, 'utf8').digest('hex'); +} +// Depends on jsbn.js and rng.js +// Version 1.1: support utf-8 encoding in pkcs1pad2 +// convert a (hex) string to a bignum object + + +function parseBigInt(str, r) +{ + return new BigInteger(str, r); +} + +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 + //alert("Message too long for RSA (n=" + n + ", l=" + s.length + ")"); + //return null; + throw "Message too long for RSA (n=" + n + ", l=" + s.length + ")"; + } + 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); +} + +// "empty" RSA key constructor + + +function RSAKey() +{ + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; +} +// Set the public key fields N and e from hex strings + + +function RSASetPublic(N, E) +{ + if (N != null && E != null && N.length > 0 && E.length > 0) + { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + } + else alert("Invalid RSA public key"); +} + +// Perform raw public operation on "x": return x^e (mod n) + + +function RSADoPublic(x) +{ + return x.modPowInt(this.e, this.n); +} + +// Return the PKCS#1 RSA encryption of "text" as an even-length hex string + + +function RSAEncrypt(text) +{ + var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); + if (m == null) return null; + var c = this.doPublic(m); + if (c == null) return null; + var h = c.toString(16); + if ((h.length & 1) == 0) return h; + else return "0" + h; +} + +function RSAToJSON() +{ + return { + coeff: this.coeff.toString(16), + d: this.d.toString(16), + dmp1: this.dmp1.toString(16), + dmq1: this.dmq1.toString(16), + e: this.e.toString(16), + n: this.n.toString(16), + p: this.p.toString(16), + q: this.q.toString(16) + } +} + +function RSAParse(rsaString) { + var json = JSON.parse(rsaString); + var rsa = new RSAKey(); + + rsa.setPrivateEx(json.n, json.e, json.d, json.p, json.q, json.dmp1, json.dmq1, json.coeff); + + return rsa; +} + +// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string +//function RSAEncryptB64(text) { +// var h = this.encrypt(text); +// if(h) return hex2b64(h); else return null; +//} +// protected +RSAKey.prototype.doPublic = RSADoPublic; + +// public +RSAKey.prototype.setPublic = RSASetPublic; +RSAKey.prototype.encrypt = RSAEncrypt; +RSAKey.prototype.toJSON = RSAToJSON; +RSAKey.parse = RSAParse; + +// Version 1.1: support utf-8 decoding in pkcs1unpad2 +// 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, and d from hex strings +function RSASetPrivate(N, E, D) +{ + 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); + } + else alert("Invalid RSA private key"); +} + +// 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 throw new 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 SeededRandom(); + 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; + } + } +} + +// Perform raw private operation on "x": return x^d (mod n) +function RSADoPrivate(x) +{ + if (this.p == null || this.q == null) return x.modPow(this.d, this.n); + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + 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); +} + +// Return the PKCS#1 RSA decryption of "ctext". +// "ctext" is an even-length hex string and the output is a plain string. +function RSADecrypt(ctext) +{ + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if (m == null) return null; + return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); +} + +// protected +RSAKey.prototype.doPrivate = RSADoPrivate; + +// public +RSAKey.prototype.setPrivate = RSASetPrivate; +RSAKey.prototype.setPrivateEx = RSASetPrivateEx; +RSAKey.prototype.generate = RSAGenerate; +RSAKey.prototype.decrypt = RSADecrypt; + + +// +// rsa-sign.js - adding signing functions to RSAKey class. +// +// +// version: 1.0 (2010-Jun-03) +// +// Copyright (c) 2010 Kenji Urushima (kenji.urushima@gmail.com) +// +// This software is licensed under the terms of the MIT License. +// http://www.opensource.org/licenses/mit-license.php +// +// The above copyright and license notice shall be +// included in all copies or substantial portions of the Software. +// +// Depends on: +// function sha1.hex(s) of sha1.js +// jsbn.js +// jsbn2.js +// rsa.js +// rsa2.js +// +// keysize / pmstrlen +// 512 / 128 +// 1024 / 256 +// 2048 / 512 +// 4096 / 1024 +// As for _RSASGIN_DIHEAD values for each hash algorithm, see PKCS#1 v2.1 spec (p38). +var _RSASIGN_DIHEAD = []; +_RSASIGN_DIHEAD['sha1'] = "3021300906052b0e03021a05000414"; +_RSASIGN_DIHEAD['sha256'] = "3031300d060960864801650304020105000420"; +//_RSASIGN_DIHEAD['md2'] = "3020300c06082a864886f70d020205000410"; +//_RSASIGN_DIHEAD['md5'] = "3020300c06082a864886f70d020505000410"; +//_RSASIGN_DIHEAD['sha384'] = "3041300d060960864801650304020205000430"; +//_RSASIGN_DIHEAD['sha512'] = "3051300d060960864801650304020305000440"; +var _RSASIGN_HASHHEXFUNC = []; +_RSASIGN_HASHHEXFUNC['sha1'] = sha1.hex; +_RSASIGN_HASHHEXFUNC['sha256'] = sha256.hex; + +// ======================================================================== +// Signature Generation +// ======================================================================== + +function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) +{ + var pmStrLen = keySize / 4; + var hashFunc = _RSASIGN_HASHHEXFUNC[hashAlg]; + var sHashHex = hashFunc(s); + + var sHead = "0001"; + var sTail = "00" + _RSASIGN_DIHEAD[hashAlg] + sHashHex; + var sMid = ""; + var fLen = pmStrLen - sHead.length - sTail.length; + for (var i = 0; i < fLen; i += 2) + { + sMid += "ff"; + } + var sPaddedMessageHex = sHead + sMid + sTail; + return sPaddedMessageHex; +} + +function _rsasign_signString(s, hashAlg) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), hashAlg); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +function _rsasign_signStringWithSHA1(s) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), 'sha1'); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +function _rsasign_signStringWithSHA256(s) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), 'sha256'); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +// ======================================================================== +// Signature Verification +// ======================================================================== + +function _rsasign_getDecryptSignatureBI(biSig, hN, hE) +{ + var rsa = new RSAKey(); + rsa.setPublic(hN, hE); + var biDecryptedSig = rsa.doPublic(biSig); + return biDecryptedSig; +} + +function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) +{ + var biDecryptedSig = _rsasign_getDecryptSignatureBI(biSig, hN, hE); + var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, ''); + return hDigestInfo; +} + +function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) +{ + for (var algName in _RSASIGN_DIHEAD) + { + var head = _RSASIGN_DIHEAD[algName]; + var len = head.length; + if (hDigestInfo.substring(0, len) == head) + { + var a = [algName, hDigestInfo.substring(len)]; + return a; + } + } + return []; +} + +function _rsasign_verifySignatureWithArgs(sMsg, biSig, hN, hE) +{ + var hDigestInfo = _rsasign_getHexDigestInfoFromSig(biSig, hN, hE); + var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo); + if (digestInfoAry.length == 0) return false; + var algName = digestInfoAry[0]; + var diHashValue = digestInfoAry[1]; + var ff = _RSASIGN_HASHHEXFUNC[algName]; + var msgHashValue = ff(sMsg); + return (diHashValue == msgHashValue); +} + +function _rsasign_verifyHexSignatureForMessage(hSig, sMsg) +{ + var biSig = parseBigInt(hSig, 16); + var result = _rsasign_verifySignatureWithArgs(sMsg, biSig, this.n.toString(16), this.e.toString(16)); + return result; +} + +function _rsasign_verifyString(sMsg, hSig) +{ + hSig = hSig.replace(/[ \n]+/g, ""); + var biSig = parseBigInt(hSig, 16); + var biDecryptedSig = this.doPublic(biSig); + var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, ''); + var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo); + + if (digestInfoAry.length == 0) return false; + var algName = digestInfoAry[0]; + var diHashValue = digestInfoAry[1]; + var ff = _RSASIGN_HASHHEXFUNC[algName]; + var msgHashValue = ff(sMsg); + return (diHashValue == msgHashValue); +} + +RSAKey.prototype.signString = _rsasign_signString; +RSAKey.prototype.signStringWithSHA1 = _rsasign_signStringWithSHA1; +RSAKey.prototype.signStringWithSHA256 = _rsasign_signStringWithSHA256; + +RSAKey.prototype.verifyString = _rsasign_verifyString; +RSAKey.prototype.verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMessage; + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* + * jsaes version 0.1 - Copyright 2006 B. Poettering + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA + */ + + // later modifications by wwwtyro@github + +var aes = (function () { + + var my = {}; + + my.Sbox = new Array(99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22); + + my.ShiftRowTab = new Array(0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11); + + my.Init = function () { + my.Sbox_Inv = new Array(256); + for (var i = 0; i < 256; i++) + my.Sbox_Inv[my.Sbox[i]] = i; + + my.ShiftRowTab_Inv = new Array(16); + for (var i = 0; i < 16; i++) + my.ShiftRowTab_Inv[my.ShiftRowTab[i]] = i; + + my.xtime = new Array(256); + for (var i = 0; i < 128; i++) { + my.xtime[i] = i << 1; + my.xtime[128 + i] = (i << 1) ^ 0x1b; + } + } + + my.Done = function () { + delete my.Sbox_Inv; + delete my.ShiftRowTab_Inv; + delete my.xtime; + } + + my.ExpandKey = function (key) { + var kl = key.length, + ks, Rcon = 1; + switch (kl) { + case 16: + ks = 16 * (10 + 1); + break; + case 24: + ks = 16 * (12 + 1); + break; + case 32: + ks = 16 * (14 + 1); + break; + default: + alert("my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!"); + } + for (var i = kl; i < ks; i += 4) { + var temp = key.slice(i - 4, i); + if (i % kl == 0) { + temp = new Array(my.Sbox[temp[1]] ^ Rcon, my.Sbox[temp[2]], my.Sbox[temp[3]], my.Sbox[temp[0]]); + if ((Rcon <<= 1) >= 256) Rcon ^= 0x11b; + } + else if ((kl > 24) && (i % kl == 16)) temp = new Array(my.Sbox[temp[0]], my.Sbox[temp[1]], my.Sbox[temp[2]], my.Sbox[temp[3]]); + for (var j = 0; j < 4; j++) + key[i + j] = key[i + j - kl] ^ temp[j]; + } + } + + my.Encrypt = function (block, key) { + var l = key.length; + my.AddRoundKey(block, key.slice(0, 16)); + for (var i = 16; i < l - 16; i += 16) { + my.SubBytes(block, my.Sbox); + my.ShiftRows(block, my.ShiftRowTab); + my.MixColumns(block); + my.AddRoundKey(block, key.slice(i, i + 16)); + } + my.SubBytes(block, my.Sbox); + my.ShiftRows(block, my.ShiftRowTab); + my.AddRoundKey(block, key.slice(i, l)); + } + + my.Decrypt = function (block, key) { + var l = key.length; + my.AddRoundKey(block, key.slice(l - 16, l)); + my.ShiftRows(block, my.ShiftRowTab_Inv); + my.SubBytes(block, my.Sbox_Inv); + for (var i = l - 32; i >= 16; i -= 16) { + my.AddRoundKey(block, key.slice(i, i + 16)); + my.MixColumns_Inv(block); + my.ShiftRows(block, my.ShiftRowTab_Inv); + my.SubBytes(block, my.Sbox_Inv); + } + my.AddRoundKey(block, key.slice(0, 16)); + } + + my.SubBytes = function (state, sbox) { + for (var i = 0; i < 16; i++) + state[i] = sbox[state[i]]; + } + + my.AddRoundKey = function (state, rkey) { + for (var i = 0; i < 16; i++) + state[i] ^= rkey[i]; + } + + my.ShiftRows = function (state, shifttab) { + var h = new Array().concat(state); + for (var i = 0; i < 16; i++) + state[i] = h[shifttab[i]]; + } + + my.MixColumns = function (state) { + for (var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], + s1 = state[i + 1]; + var s2 = state[i + 2], + s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + state[i + 0] ^= h ^ my.xtime[s0 ^ s1]; + state[i + 1] ^= h ^ my.xtime[s1 ^ s2]; + state[i + 2] ^= h ^ my.xtime[s2 ^ s3]; + state[i + 3] ^= h ^ my.xtime[s3 ^ s0]; + } + } + + my.MixColumns_Inv = function (state) { + for (var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], + s1 = state[i + 1]; + var s2 = state[i + 2], + s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + var xh = my.xtime[h]; + var h1 = my.xtime[my.xtime[xh ^ s0 ^ s2]] ^ h; + var h2 = my.xtime[my.xtime[xh ^ s1 ^ s3]] ^ h; + state[i + 0] ^= h1 ^ my.xtime[s0 ^ s1]; + state[i + 1] ^= h2 ^ my.xtime[s1 ^ s2]; + state[i + 2] ^= h1 ^ my.xtime[s2 ^ s3]; + state[i + 3] ^= h2 ^ my.xtime[s3 ^ s0]; + } + } + + return my; + +}()); +var cryptico = (function() { + + var my = {}; + + aes.Init(); + + var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + my.b256to64 = function(t) { + var a, c, n; + var r = '', l = 0, s = 0; + var tl = t.length; + for (n = 0; n < tl; n++) + { + c = t.charCodeAt(n); + if (s == 0) + { + r += base64Chars.charAt((c >> 2) & 63); + a = (c & 3) << 4; + } + else if (s == 1) + { + r += base64Chars.charAt((a | (c >> 4) & 15)); + a = (c & 15) << 2; + } + else if (s == 2) + { + r += base64Chars.charAt(a | ((c >> 6) & 3)); + l += 1; + r += base64Chars.charAt(c & 63); + } + l += 1; + s += 1; + if (s == 3) s = 0; + } + if (s > 0) + { + r += base64Chars.charAt(a); + l += 1; + r += '='; + l += 1; + } + if (s == 1) + { + r += '='; + } + return r; + } + + my.b64to256 = function(t) + { + var c, n; + var r = '', s = 0, a = 0; + var tl = t.length; + for (n = 0; n < tl; n++) + { + c = base64Chars.indexOf(t.charAt(n)); + if (c >= 0) + { + if (s) r += String.fromCharCode(a | (c >> (6 - s)) & 255); + s = (s + 2) & 7; + a = (c << s) & 255; + } + } + return r; + } + + my.b16to64 = function(h) { + var i; + var c; + var ret = ""; + if(h.length % 2 == 1) + { + h = "0" + h; + } + for (i = 0; i + 3 <= h.length; i += 3) + { + c = parseInt(h.substring(i, i + 3), 16); + ret += base64Chars.charAt(c >> 6) + base64Chars.charAt(c & 63); + } + if (i + 1 == h.length) + { + c = parseInt(h.substring(i, i + 1), 16); + ret += base64Chars.charAt(c << 2); + } + else if (i + 2 == h.length) + { + c = parseInt(h.substring(i, i + 2), 16); + ret += base64Chars.charAt(c >> 2) + base64Chars.charAt((c & 3) << 4); + } + while ((ret.length & 3) > 0) ret += "="; + return ret; + } + + my.b64to16 = function(s) { + var ret = ""; + var i; + var k = 0; + var slop; + for (i = 0; i < s.length; ++i) + { + if (s.charAt(i) == "=") break; + v = base64Chars.indexOf(s.charAt(i)); + if (v < 0) continue; + if (k == 0) + { + ret += int2char(v >> 2); + slop = v & 3; + k = 1; + } + else if (k == 1) + { + ret += int2char((slop << 2) | (v >> 4)); + slop = v & 0xf; + k = 2; + } + else if (k == 2) + { + ret += int2char(slop); + ret += int2char(v >> 2); + slop = v & 3; + k = 3; + } + else + { + ret += int2char((slop << 2) | (v >> 4)); + ret += int2char(v & 0xf); + k = 0; + } + } + if (k == 1) ret += int2char(slop << 2); + return ret; + } + + // Converts a string to a byte array. + my.string2bytes = function(string) + { + var bytes = new Array(); + for(var i = 0; i < string.length; i++) + { + bytes.push(string.charCodeAt(i)); + } + return bytes; + } + + // Converts a byte array to a string. + my.bytes2string = function(bytes) + { + var string = ""; + for(var i = 0; i < bytes.length; i++) + { + string += String.fromCharCode(bytes[i]); + } + return string; + } + + // Returns a XOR b, where a and b are 16-byte byte arrays. + my.blockXOR = function(a, b) + { + var xor = new Array(16); + for(var i = 0; i < 16; i++) + { + xor[i] = a[i] ^ b[i]; + } + return xor; + } + + // Returns a 16-byte initialization vector. + my.blockIV = function() + { + var r = new SecureRandom(); + var IV = new Array(16); + r.nextBytes(IV); + return IV; + } + + // Returns a copy of bytes with zeros appended to the end + // so that the (length of bytes) % 16 == 0. + my.pad16 = function(bytes) + { + var newBytes = bytes.slice(0); + var padding = (16 - (bytes.length % 16)) % 16; + for(i = bytes.length; i < bytes.length + padding; i++) + { + newBytes.push(0); + } + return newBytes; + } + + // Removes trailing zeros from a byte array. + my.depad = function(bytes) + { + var newBytes = bytes.slice(0); + while(newBytes[newBytes.length - 1] == 0) + { + newBytes = newBytes.slice(0, newBytes.length - 1); + } + return newBytes; + } + + // AES CBC Encryption. + my.encryptAESCBC = function(plaintext, key) + { + var exkey = key.slice(0); + aes.ExpandKey(exkey); + var blocks = my.string2bytes(plaintext); + blocks = my.pad16(blocks); + var encryptedBlocks = my.blockIV(); + for(var i = 0; i < blocks.length/16; i++) + { + var tempBlock = blocks.slice(i * 16, i * 16 + 16); + var prevBlock = encryptedBlocks.slice((i) * 16, (i) * 16 + 16); + tempBlock = my.blockXOR(prevBlock, tempBlock); + aes.Encrypt(tempBlock, exkey); + encryptedBlocks = encryptedBlocks.concat(tempBlock); + } + var ciphertext = my.bytes2string(encryptedBlocks); + return my.b256to64(ciphertext) + } + + // AES CBC Decryption. + my.decryptAESCBC = function(encryptedText, key) + { + var exkey = key.slice(0); + aes.ExpandKey(exkey); + var encryptedText = my.b64to256(encryptedText); + var encryptedBlocks = my.string2bytes(encryptedText); + var decryptedBlocks = new Array(); + for(var i = 1; i < encryptedBlocks.length/16; i++) + { + var tempBlock = encryptedBlocks.slice(i * 16, i * 16 + 16); + var prevBlock = encryptedBlocks.slice((i-1) * 16, (i-1) * 16 + 16); + aes.Decrypt(tempBlock, exkey); + tempBlock = my.blockXOR(prevBlock, tempBlock); + decryptedBlocks = decryptedBlocks.concat(tempBlock); + } + decryptedBlocks = my.depad(decryptedBlocks); + return my.bytes2string(decryptedBlocks); + } + + // Wraps a string to 60 characters. + my.wrap60 = function(string) + { + var outstr = ""; + for(var i = 0; i < string.length; i++) { + if(i % 60 == 0 && i != 0) outstr += "\n"; + outstr += string[i]; } + return outstr; + } + + // Generate a random key for the AES-encrypted message. + my.generateAESKey = function() + { + var key = new Array(32); + var r = new SecureRandom(); + r.nextBytes(key); + return key; + } + + // Generates an RSA key from a passphrase. + my.generateRSAKey = function(passphrase, bitlength) + { + Math.seedrandom(sha256.hex(passphrase)); + var rsa = new RSAKey(); + rsa.generate(bitlength, "03"); + return rsa; + } + + // Returns the ascii-armored version of the public key. + my.publicKeyString = function(rsakey) + { + pubkey = my.b16to64(rsakey.n.toString(16)); + return pubkey; + } + + // Returns an MD5 sum of a publicKeyString for easier identification. + my.publicKeyID = function(publicKeyString) + { + return MD5(publicKeyString); + } + + my.publicKeyFromString = function(string) + { + var N = my.b64to16(string.split("|")[0]); + var E = "03"; + var rsa = new RSAKey(); + rsa.setPublic(N, E); + return rsa + } + + my.encrypt = function(plaintext, publickeystring, signingkey) + { + var cipherblock = ""; + var aeskey = my.generateAESKey(); + try + { + var publickey = my.publicKeyFromString(publickeystring); + cipherblock += my.b16to64(publickey.encrypt(my.bytes2string(aeskey))) + "?"; + } + catch(err) + { + return {status: "Invalid public key"}; + } + if(signingkey) + { + signString = cryptico.b16to64(signingkey.signString(plaintext, "sha256")); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += cryptico.publicKeyString(signingkey); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += signString; + } + cipherblock += my.encryptAESCBC(plaintext, aeskey); + return {status: "success", cipher: cipherblock}; + } + + my.decrypt = function(ciphertext, key) + { + var cipherblock = ciphertext.split("?"); + var aeskey = key.decrypt(my.b64to16(cipherblock[0])); + if(aeskey == null) + { + return {status: "failure"}; + } + aeskey = my.string2bytes(aeskey); + var plaintext = my.decryptAESCBC(cipherblock[1], aeskey).split("::52cee64bb3a38f6403386519a39ac91c::"); + if(plaintext.length == 3) + { + var publickey = my.publicKeyFromString(plaintext[1]); + var signature = my.b64to16(plaintext[2]); + if(publickey.verifyString(plaintext[0], signature)) + { + return {status: "success", + plaintext: plaintext[0], + signature: "verified", + publicKeyString: my.publicKeyString(publickey)}; + } + else + { + return {status: "success", + plaintext: plaintext[0], + signature: "forged", + publicKeyString: my.publicKeyString(publickey)}; + } + } + else + { + return {status: "success", plaintext: plaintext[0], signature: "unsigned"}; + } + } + + return my; + +}()); + + +module.exports = cryptico; +module.exports.RSAKey = RSAKey; + +if (typeof window !== 'undefined') { + window.cryptico = module.exports; +} + +},{"crypto":6}],2:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = Buffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 + +/** + * If `Buffer._useTypedArrays`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (compatible down to IE6) + */ +Buffer._useTypedArrays = (function () { + // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, + // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding + // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support + // because we need to be able to add all the node Buffer API methods. This is an issue + // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return 42 === arr.foo() && + typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` + } catch (e) { + return false + } +})() + +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (subject, encoding, noZero) { + if (!(this instanceof Buffer)) + return new Buffer(subject, encoding, noZero) + + var type = typeof subject + + // Workaround: node's base64 implementation allows for non-padded strings + // while base64-js does not. + if (encoding === 'base64' && type === 'string') { + subject = stringtrim(subject) + while (subject.length % 4 !== 0) { + subject = subject + '=' + } + } + + // Find the length + var length + if (type === 'number') + length = coerce(subject) + else if (type === 'string') + length = Buffer.byteLength(subject, encoding) + else if (type === 'object') + length = coerce(subject.length) // assume that object is array-like + else + throw new Error('First argument needs to be a number, array or string.') + + var buf + if (Buffer._useTypedArrays) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + buf = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + buf = this + buf.length = length + buf._isBuffer = true + } + + var i + if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + buf._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + for (i = 0; i < length; i++) { + if (Buffer.isBuffer(subject)) + buf[i] = subject.readUInt8(i) + else + buf[i] = subject[i] + } + } else if (type === 'string') { + buf.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { + for (i = 0; i < length; i++) { + buf[i] = 0 + } + } + + return buf +} + +// STATIC METHODS +// ============== + +Buffer.isEncoding = function (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.isBuffer = function (b) { + return !!(b !== null && b !== undefined && b._isBuffer) +} + +Buffer.byteLength = function (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'hex': + ret = str.length / 2 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'base64': + ret = base64ToBytes(str).length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.concat = function (list, totalLength) { + assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + + 'list should be an Array.') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (typeof totalLength !== 'number') { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length + } + } + + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +// BUFFER INSTANCE METHODS +// ======================= + +function _hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + assert(strLen % 2 === 0, 'Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16) + assert(!isNaN(byte), 'Invalid hex string') + buf[offset + i] = byte + } + Buffer._charsWritten = i * 2 + return i +} + +function _utf8Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf8ToBytes(string), buf, offset, length) + return charsWritten +} + +function _asciiWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} + +function _binaryWrite (buf, string, offset, length) { + return _asciiWrite(buf, string, offset, length) +} + +function _base64Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +function _utf16leWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf16leToBytes(string), buf, offset, length) + return charsWritten +} + +Buffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap + } + + offset = Number(offset) || 0 + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() + + var ret + switch (encoding) { + case 'hex': + ret = _hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = _utf8Write(this, string, offset, length) + break + case 'ascii': + ret = _asciiWrite(this, string, offset, length) + break + case 'binary': + ret = _binaryWrite(this, string, offset, length) + break + case 'base64': + ret = _base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leWrite(this, string, offset, length) + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.prototype.toString = function (encoding, start, end) { + var self = this + + encoding = String(encoding || 'utf8').toLowerCase() + start = Number(start) || 0 + end = (end !== undefined) + ? Number(end) + : end = self.length + + // Fastpath empty strings + if (end === start) + return '' + + var ret + switch (encoding) { + case 'hex': + ret = _hexSlice(self, start, end) + break + case 'utf8': + case 'utf-8': + ret = _utf8Slice(self, start, end) + break + case 'ascii': + ret = _asciiSlice(self, start, end) + break + case 'binary': + ret = _binarySlice(self, start, end) + break + case 'base64': + ret = _base64Slice(self, start, end) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leSlice(self, start, end) + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.prototype.toJSON = function () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this + + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (!target_start) target_start = 0 + + // Copy 0 bytes; we're done + if (end === start) return + if (target.length === 0 || source.length === 0) return + + // Fatal error conditions + assert(end >= start, 'sourceEnd < sourceStart') + assert(target_start >= 0 && target_start < target.length, + 'targetStart out of bounds') + assert(start >= 0 && start < source.length, 'sourceStart out of bounds') + assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start + + var len = end - start + + if (len < 100 || !Buffer._useTypedArrays) { + for (var i = 0; i < len; i++) + target[i + target_start] = this[i + start] + } else { + target._set(this.subarray(start, start + len), target_start) + } +} + +function _base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function _utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +function _asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) + ret += String.fromCharCode(buf[i]) + return ret +} + +function _binarySlice (buf, start, end) { + return _asciiSlice(buf, start, end) +} + +function _hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function _utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) + } + return res +} + +Buffer.prototype.slice = function (start, end) { + var len = this.length + start = clamp(start, len, 0) + end = clamp(end, len, len) + + if (Buffer._useTypedArrays) { + return Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + var newBuf = new Buffer(sliceLen, undefined, true) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + return newBuf + } +} + +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +Buffer.prototype.readUInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') + } + + if (offset >= this.length) + return + + return this[offset] +} + +function _readUInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val + if (littleEndian) { + val = buf[offset] + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + } else { + val = buf[offset] << 8 + if (offset + 1 < len) + val |= buf[offset + 1] + } + return val +} + +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + return _readUInt16(this, offset, true, noAssert) +} + +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + return _readUInt16(this, offset, false, noAssert) +} + +function _readUInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val + if (littleEndian) { + if (offset + 2 < len) + val = buf[offset + 2] << 16 + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + val |= buf[offset] + if (offset + 3 < len) + val = val + (buf[offset + 3] << 24 >>> 0) + } else { + if (offset + 1 < len) + val = buf[offset + 1] << 16 + if (offset + 2 < len) + val |= buf[offset + 2] << 8 + if (offset + 3 < len) + val |= buf[offset + 3] + val = val + (buf[offset] << 24 >>> 0) + } + return val +} + +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + return _readUInt32(this, offset, true, noAssert) +} + +Buffer.prototype.readUInt32BE = function (offset, noAssert) { + return _readUInt32(this, offset, false, noAssert) +} + +Buffer.prototype.readInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, + 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') + } + + if (offset >= this.length) + return + + var neg = this[offset] & 0x80 + if (neg) + return (0xff - this[offset] + 1) * -1 + else + return this[offset] +} + +function _readInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val = _readUInt16(buf, offset, littleEndian, true) + var neg = val & 0x8000 + if (neg) + return (0xffff - val + 1) * -1 + else + return val +} + +Buffer.prototype.readInt16LE = function (offset, noAssert) { + return _readInt16(this, offset, true, noAssert) +} + +Buffer.prototype.readInt16BE = function (offset, noAssert) { + return _readInt16(this, offset, false, noAssert) +} + +function _readInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val = _readUInt32(buf, offset, littleEndian, true) + var neg = val & 0x80000000 + if (neg) + return (0xffffffff - val + 1) * -1 + else + return val +} + +Buffer.prototype.readInt32LE = function (offset, noAssert) { + return _readInt32(this, offset, true, noAssert) +} + +Buffer.prototype.readInt32BE = function (offset, noAssert) { + return _readInt32(this, offset, false, noAssert) +} + +function _readFloat (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + return ieee754.read(buf, offset, littleEndian, 23, 4) +} + +Buffer.prototype.readFloatLE = function (offset, noAssert) { + return _readFloat(this, offset, true, noAssert) +} + +Buffer.prototype.readFloatBE = function (offset, noAssert) { + return _readFloat(this, offset, false, noAssert) +} + +function _readDouble (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') + } + + return ieee754.read(buf, offset, littleEndian, 52, 8) +} + +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + return _readDouble(this, offset, true, noAssert) +} + +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + return _readDouble(this, offset, false, noAssert) +} + +Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'trying to write beyond buffer length') + verifuint(value, 0xff) + } + + if (offset >= this.length) return + + this[offset] = value +} + +function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffff) + } + + var len = buf.length + if (offset >= len) + return + + for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { + buf[offset + i] = + (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, false, noAssert) +} + +function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffffffff) + } + + var len = buf.length + if (offset >= len) + return + + for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { + buf[offset + i] = + (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, false, noAssert) +} + +Buffer.prototype.writeInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7f, -0x80) + } + + if (offset >= this.length) + return + + if (value >= 0) + this.writeUInt8(value, offset, noAssert) + else + this.writeUInt8(0xff + value + 1, offset, noAssert) +} + +function _writeInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fff, -0x8000) + } + + var len = buf.length + if (offset >= len) + return + + if (value >= 0) + _writeUInt16(buf, value, offset, littleEndian, noAssert) + else + _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) +} + +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, false, noAssert) +} + +function _writeInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fffffff, -0x80000000) + } + + var len = buf.length + if (offset >= len) + return + + if (value >= 0) + _writeUInt32(buf, value, offset, littleEndian, noAssert) + else + _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) +} + +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, false, noAssert) +} + +function _writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + + var len = buf.length + if (offset >= len) + return + + ieee754.write(buf, value, offset, littleEndian, 23, 4) +} + +Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, false, noAssert) +} + +function _writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 7 < buf.length, + 'Trying to write beyond buffer length') + verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + + var len = buf.length + if (offset >= len) + return + + ieee754.write(buf, value, offset, littleEndian, 52, 8) +} + +Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, false, noAssert) +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (typeof value === 'string') { + value = value.charCodeAt(0) + } + + assert(typeof value === 'number' && !isNaN(value), 'value is not a number') + assert(end >= start, 'end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + assert(start >= 0 && start < this.length, 'start out of bounds') + assert(end >= 0 && end <= this.length, 'end out of bounds') + + for (var i = start; i < end; i++) { + this[i] = value + } +} + +Buffer.prototype.inspect = function () { + var out = [] + var len = this.length + for (var i = 0; i < len; i++) { + out[i] = toHex(this[i]) + if (i === exports.INSPECT_MAX_BYTES) { + out[i + 1] = '...' + break + } + } + return '' +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer._useTypedArrays) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) + buf[i] = this[i] + return buf.buffer + } + } else { + throw new Error('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function (arr) { + arr._isBuffer = true + + // save reference to original Uint8Array get/set methods before overwriting + arr._get = arr.get + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +// slice(start, end) +function clamp (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index; // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} + +function coerce (length) { + // Coerce length to a number (possibly NaN), round up + // in case it's fractional (e.g. 123.456) then do a + // double negate to coerce a NaN to 0. Easy, right? + length = ~~Math.ceil(+length) + return length < 0 ? 0 : length +} + +function isArray (subject) { + return (Array.isArray || function (subject) { + return Object.prototype.toString.call(subject) === '[object Array]' + })(subject) +} + +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + var b = str.charCodeAt(i) + if (b <= 0x7F) + byteArray.push(str.charCodeAt(i)) + else { + var start = i + if (b >= 0xD800 && b <= 0xDFFF) i++ + var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') + for (var j = 0; j < h.length; j++) + byteArray.push(parseInt(h[j], 16)) + } + } + return byteArray +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(str) +} + +function blitBuffer (src, dst, offset, length) { + var pos + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) + break + dst[i + offset] = src[i] + } + return i +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +/* + * We have to make sure that the value is a valid integer. This means that it + * is non-negative. It has no fractional component and that it does not + * exceed the maximum allowed value. + */ +function verifuint (value, max) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value >= 0, 'specified a negative value for writing an unsigned value') + assert(value <= max, 'value is larger than maximum value for type') + assert(Math.floor(value) === value, 'value has a fractional component') +} + +function verifsint (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') + assert(Math.floor(value) === value, 'value has a fractional component') +} + +function verifIEEE754 (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') +} + +function assert (test, message) { + if (!test) throw new Error(message || 'Failed assertion') +} + +},{"base64-js":3,"ieee754":4}],3:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],4:[function(require,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +},{}],5:[function(require,module,exports){ +var Buffer = require('buffer').Buffer; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} + +module.exports = { hash: hash }; + +},{"buffer":2}],6:[function(require,module,exports){ +var Buffer = require('buffer').Buffer +var sha = require('./sha') +var sha256 = require('./sha256') +var rng = require('./rng') +var md5 = require('./md5') + +var algorithms = { + sha1: sha, + sha256: sha256, + md5: md5 +} + +var blocksize = 64 +var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0) +function hmac(fn, key, data) { + if(!Buffer.isBuffer(key)) key = new Buffer(key) + if(!Buffer.isBuffer(data)) data = new Buffer(data) + + if(key.length > blocksize) { + key = fn(key) + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) + } + + var ipad = new Buffer(blocksize), opad = new Buffer(blocksize) + for(var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var hash = fn(Buffer.concat([ipad, data])) + return fn(Buffer.concat([opad, hash])) +} + +function hash(alg, key) { + alg = alg || 'sha1' + var fn = algorithms[alg] + var bufs = [] + var length = 0 + if(!fn) error('algorithm:', alg, 'is not yet supported') + return { + update: function (data) { + if(!Buffer.isBuffer(data)) data = new Buffer(data) + + bufs.push(data) + length += data.length + return this + }, + digest: function (enc) { + var buf = Buffer.concat(bufs) + var r = key ? hmac(fn, key, buf) : fn(buf) + bufs = null + return enc ? r.toString(enc) : r + } + } +} + +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) +} + +exports.createHash = function (alg) { return hash(alg) } +exports.createHmac = function (alg, key) { return hash(alg, key) } +exports.randomBytes = function(size, callback) { + if (callback && callback.call) { + try { + callback.call(this, undefined, new Buffer(rng(size))) + } catch (err) { callback(err) } + } else { + return new Buffer(rng(size)) + } +} + +function each(a, f) { + for(var i in a) + f(a[i], i) +} + +// the least I can do is make error messages for the rest of the node.js/crypto api. +each(['createCredentials' +, 'createCipher' +, 'createCipheriv' +, 'createDecipher' +, 'createDecipheriv' +, 'createSign' +, 'createVerify' +, 'createDiffieHellman' +, 'pbkdf2'], function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') + } +}) + +},{"./md5":7,"./rng":8,"./sha":9,"./sha256":10,"buffer":2}],7:[function(require,module,exports){ +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Perform a simple self-test to see if the VM is working + */ +function md5_vm_test() +{ + return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; +} + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; + +},{"./helpers":5}],8:[function(require,module,exports){ +// Original code adapted from Robert Kieffer. +// details at https://github.com/broofa/node-uuid +(function() { + var _global = this; + + var mathRNG, whatwgRNG; + + // NOTE: Math.random() does not guarantee "cryptographic quality" + mathRNG = function(size) { + var bytes = new Array(size); + var r; + + for (var i = 0, r; i < size; i++) { + if ((i & 0x03) == 0) r = Math.random() * 0x100000000; + bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return bytes; + } + + if (_global.crypto && crypto.getRandomValues) { + whatwgRNG = function(size) { + var bytes = new Uint8Array(size); + crypto.getRandomValues(bytes); + return bytes; + } + } + + module.exports = whatwgRNG || mathRNG; + +}()) + +},{}],9:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var helpers = require('./helpers'); + +/* + * Calculate the SHA-1 of an array of big-endian words, and a bit length + */ +function core_sha1(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << (24 - len % 32); + x[((len + 64 >> 9) << 4) + 15] = len; + + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; + + for(var j = 0; j < 80; j++) + { + if(j < 16) w[j] = x[i + j]; + else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); + var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), + safe_add(safe_add(e, w[j]), sha1_kt(j))); + e = d; + d = c; + c = rol(b, 30); + b = a; + a = t; + } + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + e = safe_add(e, olde); + } + return Array(a, b, c, d, e); + +} + +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) +{ + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} + +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function sha1(buf) { + return helpers.hash(buf, core_sha1, 20, true); +}; + +},{"./helpers":5}],10:[function(require,module,exports){ + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var helpers = require('./helpers'); + +var safe_add = function(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +}; + +var S = function(X, n) { + return (X >>> n) | (X << (32 - n)); +}; + +var R = function(X, n) { + return (X >>> n); +}; + +var Ch = function(x, y, z) { + return ((x & y) ^ ((~x) & z)); +}; + +var Maj = function(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +}; + +var Sigma0256 = function(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); +}; + +var Sigma1256 = function(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); +}; + +var Gamma0256 = function(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); +}; + +var Gamma1256 = function(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); +}; + +var core_sha256 = function(m, l) { + var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + for (var i = 0; i < m.length; i += 16) { + a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; + for (var j = 0; j < 64; j++) { + if (j < 16) { + W[j] = m[j + i]; + } else { + W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + } + T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); + T2 = safe_add(Sigma0256(a), Maj(a, b, c)); + h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); + } + HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); + HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); + } + return HASH; +}; + +module.exports = function sha256(buf) { + return helpers.hash(buf, core_sha256, 32, true); +}; + +},{"./helpers":5}]},{},[1]) \ No newline at end of file diff --git a/dist/cryptico.amd.min.js b/dist/cryptico.amd.min.js new file mode 100644 index 0000000..a5fb3d2 --- /dev/null +++ b/dist/cryptico.amd.min.js @@ -0,0 +1,4 @@ +/* cryptico-js v1.0.4 - - https://github.com/tracker1/cryptico-js */ + +!function t(r,n,e){function i(s,a){if(!n[s]){if(!r[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var h=n[s]={exports:{}};r[s][0].call(h.exports,function(t){var n=r[s][1][t];return i(n?n:t)},h,h.exports,t,r,n,e)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s>15;--o>=0;){var u=32767&this[t],h=this[t++]>>15,f=a*u+h*s;u=s*u+((32767&f)<<15)+n[e]+(1073741823&i),i=(u>>>30)+(f>>>15)+a*h+(i>>>30),n[e++]=1073741823&u}return i}function s(t){return Kn.charAt(t)}function a(t,r){var n=jn[t.charCodeAt(r)];return null==n?-1:n}function u(t){for(var r=this.t-1;r>=0;--r)t[r]=this[r];t.t=this.t,t.s=this.s}function h(t){this.t=1,this.s=0>t?-1:0,t>0?this[0]=t:-1>t?this[0]=t+DV:this.t=0}function f(t){var r=e();return r.fromInt(t),r}function c(t,r){var e;if(16==r)e=4;else if(8==r)e=3;else if(256==r)e=8;else if(2==r)e=1;else if(32==r)e=5;else{if(4!=r)return this.fromRadix(t,r),void 0;e=2}this.t=0,this.s=0;for(var i=t.length,o=!1,s=0;--i>=0;){var u=8==e?255&t[i]:a(t,i);0>u?"-"==t.charAt(i)&&(o=!0):(o=!1,0==s?this[this.t++]=u:s+e>this.DB?(this[this.t-1]|=(u&(1<>this.DB-s):this[this.t-1]|=u<=this.DB&&(s-=this.DB))}8==e&&0!=(128&t[0])&&(this.s=-1,s>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==t;)--this.t}function p(t){if(this.s<0)return"-"+this.negate().toString(t);var r;if(16==t)r=4;else if(8==t)r=3;else if(2==t)r=1;else if(32==t)r=5;else if(64==t)r=6;else{if(4!=t)return this.toRadix(t);r=2}var n,e=(1<0)for(u>u)>0&&(i=!0,o=s(n));a>=0;)r>u?(n=(this[a]&(1<>(u+=this.DB-r)):(n=this[a]>>(u-=r)&e,0>=u&&(u+=this.DB,--a)),n>0&&(i=!0),i&&(o+=s(n));return i?o:"0"}function d(){var t=e();return n.ZERO.subTo(this,t),t}function g(){return this.s<0?this.negate():this}function y(t){var r=this.s-t.s;if(0!=r)return r;var n=this.t;if(r=n-t.t,0!=r)return r;for(;--n>=0;)if(0!=(r=this[n]-t[n]))return r;return 0}function m(t){var r,n=1;return 0!=(r=t>>>16)&&(t=r,n+=16),0!=(r=t>>8)&&(t=r,n+=8),0!=(r=t>>4)&&(t=r,n+=4),0!=(r=t>>2)&&(t=r,n+=2),0!=(r=t>>1)&&(t=r,n+=1),n}function b(){return this.t<=0?0:this.DB*(this.t-1)+m(this[this.t-1]^this.s&this.DM)}function w(t,r){var n;for(n=this.t-1;n>=0;--n)r[n+t]=this[n];for(n=t-1;n>=0;--n)r[n]=0;r.t=this.t+t,r.s=this.s}function S(t,r){for(var n=t;n=0;--n)r[n+s+1]=this[n]>>i|a,a=(this[n]&o)<=0;--n)r[n]=0;r[s]=a,r.t=this.t+s+1,r.s=this.s,r.clamp()}function E(t,r){r.s=this.s;var n=Math.floor(t/this.DB);if(n>=this.t)return r.t=0,void 0;var e=t%this.DB,i=this.DB-e,o=(1<>e;for(var s=n+1;s>e;e>0&&(r[this.t-n-1]|=(this.s&o)<n;)e+=this[n]-t[n],r[n++]=e&this.DM,e>>=this.DB;if(t.t>=this.DB;e+=this.s}else{for(e+=this.s;n>=this.DB;e-=t.s}r.s=0>e?-1:0,-1>e?r[n++]=this.DV+e:e>0&&(r[n++]=e),r.t=n,r.clamp()}function B(t,r){var e=this.abs(),i=t.abs(),o=e.t;for(r.t=o+i.t;--o>=0;)r[o]=0;for(o=0;o=0;)t[n]=0;for(n=0;n=r.DV&&(t[n+r.t]-=r.DV,t[n+r.t+1]=1)}t.t>0&&(t[t.t-1]+=r.am(n,r[n],t,2*n,0,1)),t.s=0,t.clamp()}function x(t,r,i){var o=t.abs();if(!(o.t<=0)){var s=this.abs();if(s.t0?(o.lShiftTo(f,a),s.lShiftTo(f,i)):(o.copyTo(a),s.copyTo(i));var c=a.t,l=a[c-1];if(0!=l){var p=l*(1<1?a[c-2]>>this.F2:0),v=this.FV/p,d=(1<=0&&(i[i.t++]=1,i.subTo(w,i)),n.ONE.dlShiftTo(c,w),w.subTo(a,a);a.t=0;){var S=i[--y]==l?this.DM:Math.floor(i[y]*v+(i[y-1]+g)*d);if((i[y]+=a.am(0,S,i,b,0,c))0&&i.rShiftTo(f,i),0>u&&n.ZERO.subTo(i,i)}}}function D(t){var r=e();return this.abs().divRemTo(t,null,r),this.s<0&&r.compareTo(n.ZERO)>0&&t.subTo(r,r),r}function M(t){this.m=t}function L(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function C(t){return t}function R(t){t.divRemTo(this.m,null,t)}function q(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function U(t,r){t.squareTo(r),this.reduce(r)}function O(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var r=3&t;return r=r*(2-(15&t)*r)&15,r=r*(2-(255&t)*r)&255,r=r*(2-((65535&t)*r&65535))&65535,r=r*(2-t*r%this.DV)%this.DV,r>0?this.DV-r:-r}function N(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(r,r),r}function _(t){var r=e();return t.copyTo(r),this.reduce(r),r}function P(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var r=0;r>15)*this.mpl&this.um)<<15)&t.DM;for(n=r+this.m.t,t[n]+=this.m.am(0,e,t,r,0,this.m.t);t[n]>=t.DV;)t[n]-=t.DV,t[++n]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function F(t,r){t.squareTo(r),this.reduce(r)}function V(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function K(){return 0==(this.t>0?1&this[0]:this.s)}function j(t,r){if(t>4294967295||1>t)return n.ONE;var i=e(),o=e(),s=r.convert(this),a=m(t)-1;for(s.copyTo(i);--a>=0;)if(r.sqrTo(i,o),(t&1<0)r.mulTo(o,s,i);else{var u=i;i=o,o=u}return r.revert(i)}function Z(t,r){var n;return n=256>t||r.isEven()?new M(r):new N(r),this.exp(t,n)}function H(){var t=e();return this.copyTo(t),t}function W(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function J(){return 0==this.t?this.s:this[0]<<16>>16}function X(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function Y(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function G(t){if(null==t&&(t=10),0==this.signum()||2>t||t>36)return"0";var r=this.chunkSize(t),n=Math.pow(t,r),i=f(n),o=e(),s=e(),a="";for(this.divRemTo(i,o,s);o.signum()>0;)a=(n+s.intValue()).toString(t).substr(1)+a,o.divRemTo(i,o,s);return s.intValue().toString(t)+a}function Q(t,r){this.fromInt(0),null==r&&(r=10);for(var e=this.chunkSize(r),i=Math.pow(r,e),o=!1,s=0,u=0,h=0;hf?"-"==t.charAt(h)&&0==this.signum()&&(o=!0):(u=r*u+f,++s>=e&&(this.dMultiply(i),this.dAddOffset(u,0),s=0,u=0))}s>0&&(this.dMultiply(Math.pow(r,s)),this.dAddOffset(u,0)),o&&n.ZERO.subTo(this,this)}function $(t,r,e){if("number"==typeof r)if(2>t)this.fromInt(1);else for(this.fromNumber(t,e),this.testBit(t-1)||this.bitwiseTo(n.ONE.shiftLeft(t-1),ar,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(n.ONE.shiftLeft(t-1),this);else{var i=new Array,o=7&t;i.length=(t>>3)+1,r.nextBytes(i),o>0?i[0]&=(1<0)for(e>e)!=(this.s&this.DM)>>e&&(r[i++]=n|this.s<=0;)8>e?(n=(this[t]&(1<>(e+=this.DB-8)):(n=this[t]>>(e-=8)&255,0>=e&&(e+=this.DB,--t)),0!=(128&n)&&(n|=-256),0==i&&(128&this.s)!=(128&n)&&++i,(i>0||n!=this.s)&&(r[i++]=n);return r}function rr(t){return 0==this.compareTo(t)}function nr(t){return this.compareTo(t)<0?this:t}function er(t){return this.compareTo(t)>0?this:t}function ir(t,r,n){var e,i,o=Math.min(t.t,this.t);for(e=0;o>e;++e)n[e]=r(this[e],t[e]);if(t.tt?this.rShiftTo(-t,r):this.lShiftTo(t,r),r}function dr(t){var r=e();return 0>t?this.lShiftTo(-t,r):this.rShiftTo(t,r),r}function gr(t){if(0==t)return-1;var r=0;return 0==(65535&t)&&(t>>=16,r+=16),0==(255&t)&&(t>>=8,r+=8),0==(15&t)&&(t>>=4,r+=4),0==(3&t)&&(t>>=2,r+=2),0==(1&t)&&++r,r}function yr(){for(var t=0;t=this.t?0!=this.s:0!=(this[r]&1<n;)e+=this[n]+t[n],r[n++]=e&this.DM,e>>=this.DB;if(t.t>=this.DB;e+=this.s}else{for(e+=this.s;n>=this.DB;e+=t.s}r.s=0>e?-1:0,e>0?r[n++]=e:-1>e&&(r[n++]=this.DV+e),r.t=n,r.clamp()}function Ir(t){var r=e();return this.addTo(t,r),r}function xr(t){var r=e();return this.subTo(t,r),r}function Dr(t){var r=e();return this.multiplyTo(t,r),r}function Mr(){var t=e();return this.squareTo(t),t}function Lr(t){var r=e();return this.divRemTo(t,r,null),r}function Cr(t){var r=e();return this.divRemTo(t,null,r),r}function Rr(t){var r=e(),n=e();return this.divRemTo(t,r,n),new Array(r,n)}function qr(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function Ur(t,r){if(0!=t){for(;this.t<=r;)this[this.t++]=0;for(this[r]+=t;this[r]>=this.DV;)this[r]-=this.DV,++r>=this.t&&(this[this.t++]=0),++this[r]}}function Or(){}function Nr(t){return t}function kr(t,r,n){t.multiplyTo(r,n)}function _r(t,r){t.squareTo(r)}function Pr(t){return this.exp(t,new Or)}function Fr(t,r,n){var e=Math.min(this.t+t.t,r);for(n.s=0,n.t=e;e>0;)n[--e]=0;var i;for(i=n.t-this.t;i>e;++e)n[e+this.t]=this.am(0,t[e],n,e,0,this.t);for(i=Math.min(t.t,r);i>e;++e)this.am(0,t[e],n,e,0,r-e);n.clamp()}function Vr(t,r,n){--r;var e=n.t=this.t+t.t-r;for(n.s=0;--e>=0;)n[e]=0;for(e=Math.max(r-this.t,0);e2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var r=e();return t.copyTo(r),this.reduce(r),r}function Zr(t){return t}function Hr(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function Wr(t,r){t.squareTo(r),this.reduce(r)}function zr(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function Jr(t,r){var n,i,o=t.bitLength(),s=f(1);if(0>=o)return s;n=18>o?1:48>o?3:144>o?4:768>o?5:6,i=8>o?new M(r):r.isEven()?new Kr(r):new N(r);var a=new Array,u=3,h=n-1,c=(1<1){var l=e();for(i.sqrTo(a[1],l);c>=u;)a[u]=e(),i.mulTo(l,a[u-2],a[u]),u+=2}var p,v,d=t.t-1,g=!0,y=e();for(o=m(t[d])-1;d>=0;){for(o>=h?p=t[d]>>o-h&c:(p=(t[d]&(1<0&&(p|=t[d-1]>>this.DB+o-h)),u=n;0==(1&p);)p>>=1,--u;if((o-=u)<0&&(o+=this.DB,--d),g)a[p].copyTo(s),g=!1;else{for(;u>1;)i.sqrTo(s,y),i.sqrTo(y,s),u-=2;u>0?i.sqrTo(s,y):(v=s,s=y,y=v),i.mulTo(y,a[p],s)}for(;d>=0&&0==(t[d]&1<o)return r;for(o>i&&(o=i),o>0&&(r.rShiftTo(o,r),n.rShiftTo(o,n));r.signum()>0;)(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),r.compareTo(n)>=0?(r.subTo(n,r),r.rShiftTo(1,r)):(n.subTo(r,n),n.rShiftTo(1,n));return o>0&&n.lShiftTo(o,n),n}function Yr(t){if(0>=t)return 0;var r=this.DV%t,n=this.s<0?t-1:0;if(this.t>0)if(0==r)n=this[0]%t;else for(var e=this.t-1;e>=0;--e)n=(r*n+this[e])%t;return n}function Gr(t){var r=t.isEven();if(this.isEven()&&r||0==t.signum())return n.ZERO;for(var e=t.clone(),i=this.clone(),o=f(1),s=f(0),a=f(0),u=f(1);0!=e.signum();){for(;e.isEven();)e.rShiftTo(1,e),r?(o.isEven()&&s.isEven()||(o.addTo(this,o),s.subTo(t,s)),o.rShiftTo(1,o)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;i.isEven();)i.rShiftTo(1,i),r?(a.isEven()&&u.isEven()||(a.addTo(this,a),u.subTo(t,u)),a.rShiftTo(1,a)):u.isEven()||u.subTo(t,u),u.rShiftTo(1,u);e.compareTo(i)>=0?(e.subTo(i,e),r&&o.subTo(a,o),s.subTo(u,s)):(i.subTo(e,i),r&&a.subTo(o,a),u.subTo(s,u))}return 0!=i.compareTo(n.ONE)?n.ZERO:u.compareTo(t)>=0?u.subtract(t):u.signum()<0?(u.addTo(t,u),u.signum()<0?u.add(t):u):u}function Qr(t){var r,n=this.abs();if(1==n.t&&n[0]<=Zn[Zn.length-1]){for(r=0;re;)e*=Zn[i++];for(e=n.modInt(e);i>r;)if(e%Zn[r++]==0)return!1}return n.millerRabin(t)}function $r(t){var r=this.subtract(n.ONE),i=r.getLowestSetBit();if(0>=i)return!1;var o=r.shiftRight(i);t=t+1>>1,t>Zn.length&&(t=Zn.length);for(var s=e(),a=0;t>a;++a){s.fromInt(Zn[Math.floor(Math.random()*Zn.length)]);var u=s.modPow(o,this);if(0!=u.compareTo(n.ONE)&&0!=u.compareTo(r)){for(var h=1;h++r;++r)this.S[r]=r;for(n=0,r=0;256>r;++r)n=n+this.S[r]+t[r%t.length]&255,e=this.S[r],this.S[r]=this.S[n],this.S[n]=e;this.i=0,this.j=0}function on(){var t;return 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,this.S[t+this.S[this.i]&255]}function sn(){return new nn}function an(t){zn[Jn++]^=255&t,zn[Jn++]^=t>>8&255,zn[Jn++]^=t>>16&255,zn[Jn++]^=t>>24&255,Jn>=Xn&&(Jn-=Xn)}function un(){an((new Date).getTime())}function hn(){if(null==Wn){for(un(),Wn=sn(),Wn.init(zn),Jn=0;Jn=0&&r>0;){var o=t.charCodeAt(i--);128>o?e[--r]=o:o>127&&2048>o?(e[--r]=63&o|128,e[--r]=o>>6|192):(e[--r]=63&o|128,e[--r]=o>>6&63|128,e[--r]=o>>12|224)}e[--r]=0;for(var s=new cn,a=new Array;r>2;){for(a[0]=0;0==a[0];)s.nextBytes(a);e[--r]=a[0]}return e[--r]=2,e[--r]=0,new n(e)}function gn(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function yn(t,r){null!=t&&null!=r&&t.length>0&&r.length>0?(this.n=vn(t,16),this.e=parseInt(r,16)):alert("Invalid RSA public key")}function mn(t){return t.modPowInt(this.e,this.n)}function bn(t){var r=dn(t,this.n.bitLength()+7>>3);if(null==r)return null;var n=this.doPublic(r);if(null==n)return null;var e=n.toString(16);return 0==(1&e.length)?e:"0"+e}function wn(){return{coeff:this.coeff.toString(16),d:this.d.toString(16),dmp1:this.dmp1.toString(16),dmq1:this.dmq1.toString(16),e:this.e.toString(16),n:this.n.toString(16),p:this.p.toString(16),q:this.q.toString(16)}}function Sn(t){var r=JSON.parse(t),n=new gn;return n.setPrivateEx(r.n,r.e,r.d,r.p,r.q,r.dmp1,r.dmq1,r.coeff),n}function Tn(t,r){for(var n=t.toByteArray(),e=0;e=n.length)return null;for(var i="";++eo?i+=String.fromCharCode(o):o>191&&224>o?(i+=String.fromCharCode((31&o)<<6|63&n[e+1]),++e):(i+=String.fromCharCode((15&o)<<12|(63&n[e+1])<<6|63&n[e+2]),e+=2)}return i}function En(t,r,n){null!=t&&null!=r&&t.length>0&&r.length>0?(this.n=vn(t,16),this.e=parseInt(r,16),this.d=vn(n,16)):alert("Invalid RSA private key")}function An(t,r,n,e,i,o,s,a){if(!(null!=t&&null!=r&&t.length>0&&r.length>0))throw new Error("Invalid RSA private key");this.n=vn(t,16),this.e=parseInt(r,16),this.d=vn(n,16),this.p=vn(e,16),this.q=vn(i,16),this.dmp1=vn(o,16),this.dmq1=vn(s,16),this.coeff=vn(a,16)}function Bn(t,r){var e=new tn,i=t>>1;this.e=parseInt(r,16);for(var o=new n(r,16);;){for(;this.p=new n(t-i,1,e),0!=this.p.subtract(n.ONE).gcd(o).compareTo(n.ONE)||!this.p.isProbablePrime(10););for(;this.q=new n(i,1,e),0!=this.q.subtract(n.ONE).gcd(o).compareTo(n.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var s=this.p;this.p=this.q,this.q=s}var a=this.p.subtract(n.ONE),u=this.q.subtract(n.ONE),h=a.multiply(u);if(0==h.gcd(o).compareTo(n.ONE)){this.n=this.p.multiply(this.q),this.d=o.modInverse(h),this.dmp1=this.d.mod(a),this.dmq1=this.d.mod(u),this.coeff=this.q.modInverse(this.p);break}}}function In(t){if(null==this.p||null==this.q)return t.modPow(this.d,this.n);for(var r=t.mod(this.p).modPow(this.dmp1,this.p),n=t.mod(this.q).modPow(this.dmq1,this.q);r.compareTo(n)<0;)r=r.add(this.p);return r.subtract(n).multiply(this.coeff).mod(this.p).multiply(this.q).add(n)}function xn(t){var r=vn(t,16),n=this.doPrivate(r);return null==n?null:Tn(n,this.n.bitLength()+7>>3)}function Dn(t,r,n){for(var e=r/4,i=ne[n],o=i(t),s="0001",a="00"+re[n]+o,u="",h=e-s.length-a.length,f=0;h>f;f+=2)u+="ff";var c=s+u+a;return c}function Mn(t,r){var n=Dn(t,this.n.bitLength(),r),e=vn(n,16),i=this.doPrivate(e),o=i.toString(16);return o}function Ln(t){var r=Dn(t,this.n.bitLength(),"sha1"),n=vn(r,16),e=this.doPrivate(n),i=e.toString(16);return i}function Cn(t){var r=Dn(t,this.n.bitLength(),"sha256"),n=vn(r,16),e=this.doPrivate(n),i=e.toString(16);return i}function Rn(t,r,n){var e=new gn;e.setPublic(r,n);var i=e.doPublic(t);return i}function qn(t,r,n){var e=Rn(t,r,n),i=e.toString(16).replace(/^1f+00/,"");return i}function Un(t){for(var r in re){var n=re[r],e=n.length;if(t.substring(0,e)==n){var i=[r,t.substring(e)];return i}}return[]}function On(t,r,n,e){var i=qn(r,n,e),o=Un(i);if(0==o.length)return!1;var s=o[0],a=o[1],u=ne[s],h=u(t);return a==h}function Nn(t,r){var n=vn(t,16),e=On(r,n,this.n.toString(16),this.e.toString(16));return e}function kn(t,r){r=r.replace(/[ \n]+/g,"");var n=vn(r,16),e=this.doPublic(n),i=e.toString(16).replace(/^1f+00/,""),o=Un(i);if(0==o.length)return!1;var s=o[0],a=o[1],u=ne[s],h=u(t);return a==h}var _n;n.prototype.am=o,_n=30,n.prototype.DB=_n,n.prototype.DM=(1<<_n)-1,n.prototype.DV=1<<_n;var Pn=52;n.prototype.FV=Math.pow(2,Pn),n.prototype.F1=Pn-_n,n.prototype.F2=2*_n-Pn;var Fn,Vn,Kn="0123456789abcdefghijklmnopqrstuvwxyz",jn=new Array;for(Fn="0".charCodeAt(0),Vn=0;9>=Vn;++Vn)jn[Fn++]=Vn;for(Fn="a".charCodeAt(0),Vn=10;36>Vn;++Vn)jn[Fn++]=Vn;for(Fn="A".charCodeAt(0),Vn=10;36>Vn;++Vn)jn[Fn++]=Vn;M.prototype.convert=L,M.prototype.revert=C,M.prototype.reduce=R,M.prototype.mulTo=q,M.prototype.sqrTo=U,N.prototype.convert=k,N.prototype.revert=_,N.prototype.reduce=P,N.prototype.mulTo=V,N.prototype.sqrTo=F,n.prototype.copyTo=u,n.prototype.fromInt=h,n.prototype.fromString=c,n.prototype.clamp=l,n.prototype.dlShiftTo=w,n.prototype.drShiftTo=S,n.prototype.lShiftTo=T,n.prototype.rShiftTo=E,n.prototype.subTo=A,n.prototype.multiplyTo=B,n.prototype.squareTo=I,n.prototype.divRemTo=x,n.prototype.invDigit=O,n.prototype.isEven=K,n.prototype.exp=j,n.prototype.toString=p,n.prototype.negate=d,n.prototype.abs=g,n.prototype.compareTo=y,n.prototype.bitLength=b,n.prototype.mod=D,n.prototype.modPowInt=Z,n.ZERO=f(0),n.ONE=f(1),Or.prototype.convert=Nr,Or.prototype.revert=Nr,Or.prototype.mulTo=kr,Or.prototype.sqrTo=_r,Kr.prototype.convert=jr,Kr.prototype.revert=Zr,Kr.prototype.reduce=Hr,Kr.prototype.mulTo=zr,Kr.prototype.sqrTo=Wr;var Zn=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],Hn=(1<<26)/Zn[Zn.length-1];n.prototype.chunkSize=X,n.prototype.toRadix=G,n.prototype.fromRadix=Q,n.prototype.fromNumber=$,n.prototype.bitwiseTo=ir,n.prototype.changeBit=Sr,n.prototype.addTo=Br,n.prototype.dMultiply=qr,n.prototype.dAddOffset=Ur,n.prototype.multiplyLowerTo=Fr,n.prototype.multiplyUpperTo=Vr,n.prototype.modInt=Yr,n.prototype.millerRabin=$r,n.prototype.clone=H,n.prototype.intValue=W,n.prototype.byteValue=z,n.prototype.shortValue=J,n.prototype.signum=Y,n.prototype.toByteArray=tr,n.prototype.equals=rr,n.prototype.min=nr,n.prototype.max=er,n.prototype.and=sr,n.prototype.or=ur,n.prototype.xor=fr,n.prototype.andNot=lr,n.prototype.not=pr,n.prototype.shiftLeft=vr,n.prototype.shiftRight=dr,n.prototype.getLowestSetBit=yr,n.prototype.bitCount=br,n.prototype.testBit=wr,n.prototype.setBit=Tr,n.prototype.clearBit=Er,n.prototype.flipBit=Ar,n.prototype.add=Ir,n.prototype.subtract=xr,n.prototype.multiply=Dr,n.prototype.divide=Lr,n.prototype.remainder=Cr,n.prototype.divideAndRemainder=Rr,n.prototype.modPow=Jr,n.prototype.modInverse=Gr,n.prototype.pow=Pr,n.prototype.gcd=Xr,n.prototype.isProbablePrime=Qr,n.prototype.square=Mr,function(t,r,n,e,i,o,s){function a(t){var r,e,i=this,o=t.length,s=0,a=i.i=i.j=i.m=0;for(i.S=[],i.c=[],o||(t=[o++]);n>s;)i.S[s]=s++;for(s=0;n>s;s++)r=i.S[s],a=f(a+r+t[s%o]),e=i.S[a],i.S[s]=e,i.S[a]=r;i.g=function(t){var r=i.S,e=f(i.i+1),o=r[e],s=f(i.j+o),a=r[s];r[e]=a,r[s]=o;for(var u=r[f(o+a)];--t;)e=f(e+1),o=r[e],s=f(s+o),a=r[s],r[e]=a,r[s]=o,u=u*n+r[f(o+a)];return i.i=e,i.j=s,u},i.g(n)}function u(t,r,n,e,i){if(n=[],i=typeof t,r&&"object"==i)for(e in t)if(e.indexOf("S")<5)try{n.push(u(t[e],r-1))}catch(o){}return n.length?n:t+("string"!=i?"\x00":"")}function h(t,r,n,e){for(t+="",n=0,e=0;et;)t=(t+a)*n,r*=n,a=l.g(1);for(;t>=o;)t/=2,r/=2,a>>>=1;return(t+a)/r},f},s=r.pow(n,e),i=r.pow(2,i),o=2*i,h(r.random(),t)}([],Math,256,6,52),tn.prototype.nextBytes=rn,nn.prototype.init=en,nn.prototype.next=on;var Wn,zn,Jn,Xn=256;if(null==zn){zn=new Array,Jn=0;for(var Yn;Xn>Jn;)Yn=Math.floor(65536*Math.random()),zn[Jn++]=Yn>>>8,zn[Jn++]=255&Yn;Jn=0,un()}cn.prototype.nextBytes=fn;var Gn=t("crypto"),Qn={};Qn.hex=function(t){return ln(t)};var $n={};$n.hex=function(t){return pn(t)};var te=function(t){return Gn.createHash("md5").update(t,"utf8").digest("hex")};gn.prototype.doPublic=mn,gn.prototype.setPublic=yn,gn.prototype.encrypt=bn,gn.prototype.toJSON=wn,gn.parse=Sn,gn.prototype.doPrivate=In,gn.prototype.setPrivate=En,gn.prototype.setPrivateEx=An,gn.prototype.generate=Bn,gn.prototype.decrypt=xn;var re=[];re.sha1="3021300906052b0e03021a05000414",re.sha256="3031300d060960864801650304020105000420";var ne=[];ne.sha1=$n.hex,ne.sha256=Qn.hex,gn.prototype.signString=Mn,gn.prototype.signStringWithSHA1=Ln,gn.prototype.signStringWithSHA256=Cn,gn.prototype.verifyString=kn,gn.prototype.verifyHexSignatureForMessage=Nn;var ee=function(){var t={};return t.Sbox=new Array(99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22),t.ShiftRowTab=new Array(0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11),t.Init=function(){t.Sbox_Inv=new Array(256);for(var r=0;256>r;r++)t.Sbox_Inv[t.Sbox[r]]=r;t.ShiftRowTab_Inv=new Array(16);for(var r=0;16>r;r++)t.ShiftRowTab_Inv[t.ShiftRowTab[r]]=r;t.xtime=new Array(256);for(var r=0;128>r;r++)t.xtime[r]=r<<1,t.xtime[128+r]=r<<1^27},t.Done=function(){delete t.Sbox_Inv,delete t.ShiftRowTab_Inv,delete t.xtime},t.ExpandKey=function(r){var n,e=r.length,i=1;switch(e){case 16:n=176;break;case 24:n=208;break;case 32:n=240;break;default:alert("my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!")}for(var o=e;n>o;o+=4){var s=r.slice(o-4,o);o%e==0?(s=new Array(t.Sbox[s[1]]^i,t.Sbox[s[2]],t.Sbox[s[3]],t.Sbox[s[0]]),(i<<=1)>=256&&(i^=283)):e>24&&o%e==16&&(s=new Array(t.Sbox[s[0]],t.Sbox[s[1]],t.Sbox[s[2]],t.Sbox[s[3]]));for(var a=0;4>a;a++)r[o+a]=r[o+a-e]^s[a]}},t.Encrypt=function(r,n){var e=n.length;t.AddRoundKey(r,n.slice(0,16));for(var i=16;e-16>i;i+=16)t.SubBytes(r,t.Sbox),t.ShiftRows(r,t.ShiftRowTab),t.MixColumns(r),t.AddRoundKey(r,n.slice(i,i+16));t.SubBytes(r,t.Sbox),t.ShiftRows(r,t.ShiftRowTab),t.AddRoundKey(r,n.slice(i,e))},t.Decrypt=function(r,n){var e=n.length;t.AddRoundKey(r,n.slice(e-16,e)),t.ShiftRows(r,t.ShiftRowTab_Inv),t.SubBytes(r,t.Sbox_Inv);for(var i=e-32;i>=16;i-=16)t.AddRoundKey(r,n.slice(i,i+16)),t.MixColumns_Inv(r),t.ShiftRows(r,t.ShiftRowTab_Inv),t.SubBytes(r,t.Sbox_Inv);t.AddRoundKey(r,n.slice(0,16))},t.SubBytes=function(t,r){for(var n=0;16>n;n++)t[n]=r[t[n]]},t.AddRoundKey=function(t,r){for(var n=0;16>n;n++)t[n]^=r[n]},t.ShiftRows=function(t,r){for(var n=(new Array).concat(t),e=0;16>e;e++)t[e]=n[r[e]]},t.MixColumns=function(r){for(var n=0;16>n;n+=4){var e=r[n+0],i=r[n+1],o=r[n+2],s=r[n+3],a=e^i^o^s;r[n+0]^=a^t.xtime[e^i],r[n+1]^=a^t.xtime[i^o],r[n+2]^=a^t.xtime[o^s],r[n+3]^=a^t.xtime[s^e]}},t.MixColumns_Inv=function(r){for(var n=0;16>n;n+=4){var e=r[n+0],i=r[n+1],o=r[n+2],s=r[n+3],a=e^i^o^s,u=t.xtime[a],h=t.xtime[t.xtime[u^e^o]]^a,f=t.xtime[t.xtime[u^i^s]]^a;r[n+0]^=h^t.xtime[e^i],r[n+1]^=f^t.xtime[i^o],r[n+2]^=h^t.xtime[o^s],r[n+3]^=f^t.xtime[s^e]}},t}(),ie=function(){var t={};ee.Init();var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";return t.b256to64=function(t){var n,e,i,o="",s=0,a=0,u=t.length;for(i=0;u>i;i++)e=t.charCodeAt(i),0==a?(o+=r.charAt(e>>2&63),n=(3&e)<<4):1==a?(o+=r.charAt(n|e>>4&15),n=(15&e)<<2):2==a&&(o+=r.charAt(n|e>>6&3),s+=1,o+=r.charAt(63&e)),s+=1,a+=1,3==a&&(a=0);return a>0&&(o+=r.charAt(n),s+=1,o+="=",s+=1),1==a&&(o+="="),o},t.b64to256=function(t){var n,e,i="",o=0,s=0,a=t.length;for(e=0;a>e;e++)n=r.indexOf(t.charAt(e)),n>=0&&(o&&(i+=String.fromCharCode(s|n>>6-o&255)),o=o+2&7,s=n<>6)+r.charAt(63&e);for(n+1==t.length?(e=parseInt(t.substring(n,n+1),16),i+=r.charAt(e<<2)):n+2==t.length&&(e=parseInt(t.substring(n,n+2),16),i+=r.charAt(e>>2)+r.charAt((3&e)<<4));(3&i.length)>0;)i+="=";return i},t.b64to16=function(t){var n,e,i="",o=0;for(n=0;nv||(0==o?(i+=s(v>>2),e=3&v,o=1):1==o?(i+=s(e<<2|v>>4),e=15&v,o=2):2==o?(i+=s(e),i+=s(v>>2),e=3&v,o=3):(i+=s(e<<2|v>>4),i+=s(15&v),o=0));return 1==o&&(i+=s(e<<2)),i},t.string2bytes=function(t){for(var r=new Array,n=0;ne;e++)n[e]=t[e]^r[e];return n},t.blockIV=function(){var t=new cn,r=new Array(16);return t.nextBytes(r),r},t.pad16=function(t){var r=t.slice(0),n=(16-t.length%16)%16;for(i=t.length;ia;a++)s[a]=e.isBuffer(t)?t.readUInt8(a):t[a];else if("string"===i)s.write(t,0,r);else if("number"===i&&!e._useTypedArrays&&!n)for(a=0;o>a;a++)s[a]=0;return s}function i(t,r,n,i){n=Number(n)||0;var o=t.length-n;i?(i=Number(i),i>o&&(i=o)):i=o;var s=r.length;j(s%2===0,"Invalid hex string"),i>s/2&&(i=s/2);for(var a=0;i>a;a++){var u=parseInt(r.substr(2*a,2),16);j(!isNaN(u),"Invalid hex string"),t[n+a]=u}return e._charsWritten=2*a,a}function o(t,r,n,i){var o=e._charsWritten=_(U(r),t,n,i);return o}function s(t,r,n,i){var o=e._charsWritten=_(O(r),t,n,i);return o}function a(t,r,n,e){return s(t,r,n,e)}function u(t,r,n,i){var o=e._charsWritten=_(k(r),t,n,i);return o}function h(t,r,n,i){var o=e._charsWritten=_(N(r),t,n,i);return o}function f(t,r,n){return 0===r&&n===t.length?Z.fromByteArray(t):Z.fromByteArray(t.slice(r,n))}function c(t,r,n){var e="",i="";n=Math.min(t.length,n);for(var o=r;n>o;o++)t[o]<=127?(e+=P(i)+String.fromCharCode(t[o]),i=""):i+="%"+t[o].toString(16);return e+P(i)}function l(t,r,n){var e="";n=Math.min(t.length,n);for(var i=r;n>i;i++)e+=String.fromCharCode(t[i]);return e}function p(t,r,n){return l(t,r,n)}function v(t,r,n){var e=t.length;(!r||0>r)&&(r=0),(!n||0>n||n>e)&&(n=e);for(var i="",o=r;n>o;o++)i+=q(t[o]);return i}function d(t,r,n){for(var e=t.slice(r,n),i="",o=0;o=i)){var o;return n?(o=t[r],i>r+1&&(o|=t[r+1]<<8)):(o=t[r]<<8,i>r+1&&(o|=t[r+1])),o}}function y(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+3=i)){var o;return n?(i>r+2&&(o=t[r+2]<<16),i>r+1&&(o|=t[r+1]<<8),o|=t[r],i>r+3&&(o+=t[r+3]<<24>>>0)):(i>r+1&&(o=t[r+1]<<16),i>r+2&&(o|=t[r+2]<<8),i>r+3&&(o|=t[r+3]),o+=t[r]<<24>>>0),o}}function m(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+1=i)){var o=g(t,r,n,!0),s=32768&o;return s?-1*(65535-o+1):o}}function b(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+3=i)){var o=y(t,r,n,!0),s=2147483648&o;return s?-1*(4294967295-o+1):o}}function w(t,r,n,e){return e||(j("boolean"==typeof n,"missing or invalid endian"),j(r+3=o))for(var s=0,a=Math.min(o-n,2);a>s;s++)t[n+s]=(r&255<<8*(e?s:1-s))>>>8*(e?s:1-s)}function E(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o))for(var s=0,a=Math.min(o-n,4);a>s;s++)t[n+s]=r>>>8*(e?s:3-s)&255}function A(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+1=o||(r>=0?T(t,r,n,e,i):T(t,65535+r+1,n,e,i))}function B(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||(r>=0?E(t,r,n,e,i):E(t,4294967295+r+1,n,e,i))}function I(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||H.write(t,r,n,e,23,4)}function x(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+7=o||H.write(t,r,n,e,52,8)}function D(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function M(t,r,n){return"number"!=typeof t?n:(t=~~t,t>=r?r:t>=0?t:(t+=r,t>=0?t:0))}function L(t){return t=~~Math.ceil(+t),0>t?0:t}function C(t){return(Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)})(t)}function R(t){return C(t)||e.isBuffer(t)||t&&"object"==typeof t&&"number"==typeof t.length}function q(t){return 16>t?"0"+t.toString(16):t.toString(16)}function U(t){for(var r=[],n=0;n=e)r.push(t.charCodeAt(n));else{var i=n;e>=55296&&57343>=e&&n++;for(var o=encodeURIComponent(t.slice(i,n+1)).substr(1).split("%"),s=0;s>8,e=r%256,i.push(e),i.push(n);return i}function k(t){return Z.toByteArray(t)}function _(t,r,n,e){for(var i=0;e>i&&!(i+n>=r.length||i>=t.length);i++)r[i+n]=t[i];return i}function P(t){try{return decodeURIComponent(t)}catch(r){return String.fromCharCode(65533)}}function F(t,r){j("number"==typeof t,"cannot write a non-number as a number"),j(t>=0,"specified a negative value for writing an unsigned value"),j(r>=t,"value is larger than maximum value for type"),j(Math.floor(t)===t,"value has a fractional component")}function V(t,r,n){j("number"==typeof t,"cannot write a non-number as a number"),j(r>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value"),j(Math.floor(t)===t,"value has a fractional component")}function K(t,r,n){j("number"==typeof t,"cannot write a non-number as a number"),j(r>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value")}function j(t,r){if(!t)throw new Error(r||"Failed assertion")}var Z=t("base64-js"),H=t("ieee754");n.Buffer=e,n.SlowBuffer=e,n.INSPECT_MAX_BYTES=50,e.poolSize=8192,e._useTypedArrays=function(){try{var t=new ArrayBuffer(0),r=new Uint8Array(t);return r.foo=function(){return 42},42===r.foo()&&"function"==typeof r.subarray}catch(n){return!1}}(),e.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},e.isBuffer=function(t){return!(null===t||void 0===t||!t._isBuffer)},e.byteLength=function(t,r){var n;switch(t+="",r||"utf8"){case"hex":n=t.length/2;break;case"utf8":case"utf-8":n=U(t).length;break;case"ascii":case"binary":case"raw":n=t.length;break;case"base64":n=k(t).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*t.length;break;default:throw new Error("Unknown encoding")}return n},e.concat=function(t,r){if(j(C(t),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===t.length)return new e(0);if(1===t.length)return t[0];var n;if("number"!=typeof r)for(r=0,n=0;nc&&(n=c)):n=c,e=String(e||"utf8").toLowerCase();var l;switch(e){case"hex":l=i(this,t,r,n);break;case"utf8":case"utf-8":l=o(this,t,r,n);break;case"ascii":l=s(this,t,r,n);break;case"binary":l=a(this,t,r,n);break;case"base64":l=u(this,t,r,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":l=h(this,t,r,n);break;default:throw new Error("Unknown encoding")}return l},e.prototype.toString=function(t,r,n){var e=this;if(t=String(t||"utf8").toLowerCase(),r=Number(r)||0,n=void 0!==n?Number(n):n=e.length,n===r)return"";var i;switch(t){case"hex":i=v(e,r,n);break;case"utf8":case"utf-8":i=c(e,r,n);break;case"ascii":i=l(e,r,n);break;case"binary":i=p(e,r,n);break;case"base64":i=f(e,r,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=d(e,r,n);break;default:throw new Error("Unknown encoding")}return i},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},e.prototype.copy=function(t,r,n,i){var o=this;if(n||(n=0),i||0===i||(i=this.length),r||(r=0),i!==n&&0!==t.length&&0!==o.length){j(i>=n,"sourceEnd < sourceStart"),j(r>=0&&r=0&&n=0&&i<=o.length,"sourceEnd out of bounds"),i>this.length&&(i=this.length),t.length-rs||!e._useTypedArrays)for(var a=0;s>a;a++)t[a+r]=this[a+n];else t._set(this.subarray(n,n+s),r)}},e.prototype.slice=function(t,r){var n=this.length;if(t=M(t,n,0),r=M(r,n,n),e._useTypedArrays)return e._augment(this.subarray(t,r));for(var i=r-t,o=new e(i,void 0,!0),s=0;i>s;s++)o[s]=this[s+t];return o},e.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},e.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},e.prototype.readUInt8=function(t,r){return r||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length?void 0:this[t]},e.prototype.readUInt16LE=function(t,r){return g(this,t,!0,r)},e.prototype.readUInt16BE=function(t,r){return g(this,t,!1,r)},e.prototype.readUInt32LE=function(t,r){return y(this,t,!0,r)},e.prototype.readUInt32BE=function(t,r){return y(this,t,!1,r)},e.prototype.readInt8=function(t,r){if(r||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length)){var n=128&this[t];return n?-1*(255-this[t]+1):this[t]}},e.prototype.readInt16LE=function(t,r){return m(this,t,!0,r)},e.prototype.readInt16BE=function(t,r){return m(this,t,!1,r)},e.prototype.readInt32LE=function(t,r){return b(this,t,!0,r)},e.prototype.readInt32BE=function(t,r){return b(this,t,!1,r)},e.prototype.readFloatLE=function(t,r){return w(this,t,!0,r)},e.prototype.readFloatBE=function(t,r){return w(this,t,!1,r)},e.prototype.readDoubleLE=function(t,r){return S(this,t,!0,r)},e.prototype.readDoubleBE=function(t,r){return S(this,t,!1,r)},e.prototype.writeUInt8=function(t,r,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==r&&null!==r,"missing offset"),j(r=this.length||(this[r]=t)},e.prototype.writeUInt16LE=function(t,r,n){T(this,t,r,!0,n)},e.prototype.writeUInt16BE=function(t,r,n){T(this,t,r,!1,n)},e.prototype.writeUInt32LE=function(t,r,n){E(this,t,r,!0,n)},e.prototype.writeUInt32BE=function(t,r,n){E(this,t,r,!1,n)},e.prototype.writeInt8=function(t,r,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==r&&null!==r,"missing offset"),j(r=this.length||(t>=0?this.writeUInt8(t,r,n):this.writeUInt8(255+t+1,r,n))},e.prototype.writeInt16LE=function(t,r,n){A(this,t,r,!0,n)},e.prototype.writeInt16BE=function(t,r,n){A(this,t,r,!1,n)},e.prototype.writeInt32LE=function(t,r,n){B(this,t,r,!0,n)},e.prototype.writeInt32BE=function(t,r,n){B(this,t,r,!1,n)},e.prototype.writeFloatLE=function(t,r,n){I(this,t,r,!0,n)},e.prototype.writeFloatBE=function(t,r,n){I(this,t,r,!1,n)},e.prototype.writeDoubleLE=function(t,r,n){x(this,t,r,!0,n)},e.prototype.writeDoubleBE=function(t,r,n){x(this,t,r,!1,n)},e.prototype.fill=function(t,r,n){if(t||(t=0),r||(r=0),n||(n=this.length),"string"==typeof t&&(t=t.charCodeAt(0)),j("number"==typeof t&&!isNaN(t),"value is not a number"),j(n>=r,"end < start"),n!==r&&0!==this.length){j(r>=0&&r=0&&n<=this.length,"end out of bounds");for(var e=r;n>e;e++)this[e]=t}},e.prototype.inspect=function(){for(var t=[],r=this.length,e=0;r>e;e++)if(t[e]=q(this[e]),e===n.INSPECT_MAX_BYTES){t[e+1]="...";break}return""},e.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(e._useTypedArrays)return new e(this).buffer;for(var t=new Uint8Array(this.length),r=0,n=t.length;n>r;r+=1)t[r]=this[r];return t.buffer}throw new Error("Buffer.toArrayBuffer not supported in this browser")};var W=e.prototype;e._augment=function(t){return t._isBuffer=!0,t._get=t.get,t._set=t.set,t.get=W.get,t.set=W.set,t.write=W.write,t.toString=W.toString,t.toLocaleString=W.toString,t.toJSON=W.toJSON,t.copy=W.copy,t.slice=W.slice,t.readUInt8=W.readUInt8,t.readUInt16LE=W.readUInt16LE,t.readUInt16BE=W.readUInt16BE,t.readUInt32LE=W.readUInt32LE,t.readUInt32BE=W.readUInt32BE,t.readInt8=W.readInt8,t.readInt16LE=W.readInt16LE,t.readInt16BE=W.readInt16BE,t.readInt32LE=W.readInt32LE,t.readInt32BE=W.readInt32BE,t.readFloatLE=W.readFloatLE,t.readFloatBE=W.readFloatBE,t.readDoubleLE=W.readDoubleLE,t.readDoubleBE=W.readDoubleBE,t.writeUInt8=W.writeUInt8,t.writeUInt16LE=W.writeUInt16LE,t.writeUInt16BE=W.writeUInt16BE,t.writeUInt32LE=W.writeUInt32LE,t.writeUInt32BE=W.writeUInt32BE,t.writeInt8=W.writeInt8,t.writeInt16LE=W.writeInt16LE,t.writeInt16BE=W.writeInt16BE,t.writeInt32LE=W.writeInt32LE,t.writeInt32BE=W.writeInt32BE,t.writeFloatLE=W.writeFloatLE,t.writeFloatBE=W.writeFloatBE,t.writeDoubleLE=W.writeDoubleLE,t.writeDoubleBE=W.writeDoubleBE,t.fill=W.fill,t.inspect=W.inspect,t.toArrayBuffer=W.toArrayBuffer,t}},{"base64-js":3,ieee754:4}],3:[function(t,r,n){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(t){"use strict";function r(t){var r=t.charCodeAt(0);return r===s||r===c?62:r===a||r===l?63:u>r?-1:u+10>r?r-u+26+26:f+26>r?r-f:h+26>r?r-h+26:void 0}function n(t){function n(t){h[c++]=t}var e,i,s,a,u,h;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;u="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-u),s=u>0?t.length-4:t.length;var c=0;for(e=0,i=0;s>e;e+=4,i+=3)a=r(t.charAt(e))<<18|r(t.charAt(e+1))<<12|r(t.charAt(e+2))<<6|r(t.charAt(e+3)),n((16711680&a)>>16),n((65280&a)>>8),n(255&a);return 2===u?(a=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&a)):1===u&&(a=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(a>>8&255),n(255&a)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,a=t.length%3,u="";for(i=0,s=t.length-a;s>i;i+=3)o=(t[i]<<16)+(t[i+1]<<8)+t[i+2],u+=n(o);switch(a){case 1:o=t[t.length-1],u+=r(o>>2),u+=r(o<<4&63),u+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],u+=r(o>>10),u+=r(o>>4&63),u+=r(o<<2&63),u+="="}return u}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),a="/".charCodeAt(0),u="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}("undefined"==typeof n?this.base64js={}:n)},{}],4:[function(t,r,n){n.read=function(t,r,n,e,i){var o,s,a=8*i-e-1,u=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===u)return s?0/0:1/0*(p?-1:1);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},n.write=function(t,r,n,e,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,v=e?1:-1,d=0>r||0===r&&0>1/r?1:0;for(r=Math.abs(r),isNaN(r)||1/0===r?(a=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-s))<1&&(s--,u*=2),r+=s+c>=1?l/u:l*Math.pow(2,1-c),r*u>=2&&(s++,u/=2),s+c>=f?(a=0,s=f):s+c>=1?(a=(r*u-1)*Math.pow(2,i),s+=c):(a=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&a,p+=v,a/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=v,s/=256,h-=8);t[n+p-v]|=128*d}},{}],5:[function(t,r){function n(t,r){if(t.length%s!==0){var n=t.length+(s-t.length%s);t=o.concat([t,a],n)}for(var e=[],i=r?t.readInt32BE:t.readInt32LE,u=0;up?r=t(r):r.lengtho;o++)e[o]=54^r[o],i[o]=92^r[o];var s=t(a.concat([e,n]));return t(a.concat([i,s]))}function i(t,r){t=t||"sha1";var n=l[t],i=[],s=0;return n||o("algorithm:",t,"is not yet supported"),{update:function(t){return a.isBuffer(t)||(t=new a(t)),i.push(t),s+=t.length,this},digest:function(t){var o=a.concat(i),s=r?e(n,r,o):n(o);return i=null,t?s.toString(t):s}}}function o(){var t=[].slice.call(arguments).join(" ");throw new Error([t,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}function s(t,r){for(var n in t)r(t[n],n)}var a=t("buffer").Buffer,u=t("./sha"),h=t("./sha256"),f=t("./rng"),c=t("./md5"),l={sha1:u,sha256:h,md5:c},p=64,v=new a(p);v.fill(0),n.createHash=function(t){return i(t)},n.createHmac=function(t,r){return i(t,r)},n.randomBytes=function(t,r){if(!r||!r.call)return new a(f(t));try{r.call(this,void 0,new a(f(t)))}catch(n){r(n)}},s(["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],function(t){n[t]=function(){o("sorry,",t,"is not implemented yet")}})},{"./md5":7,"./rng":8,"./sha":9,"./sha256":10,buffer:2}],7:[function(t,r){function n(t,r){t[r>>5]|=128<>>9<<4)+14]=r;for(var n=1732584193,e=-271733879,h=-1732584194,f=271733878,c=0;c>16)+(r>>16)+(n>>16);return e<<16|65535&n}function h(t,r){return t<>>32-r}var f=t("./helpers");r.exports=function(t){return f.hash(t,n,16)}},{"./helpers":5}],8:[function(t,r){!function(){var t,n,e=this;t=function(t){for(var r,r,n=new Array(t),e=0;t>e;e++)0==(3&e)&&(r=4294967296*Math.random()),n[e]=r>>>((3&e)<<3)&255;return n},e.crypto&&crypto.getRandomValues&&(n=function(t){var r=new Uint8Array(t);return crypto.getRandomValues(r),r}),r.exports=n||t}()},{}],9:[function(t,r){function n(t,r){t[r>>5]|=128<<24-r%32,t[(r+64>>9<<4)+15]=r;for(var n=Array(80),a=1732584193,u=-271733879,h=-1732584194,f=271733878,c=-1009589776,l=0;lm;m++){n[m]=16>m?t[l+m]:s(n[m-3]^n[m-8]^n[m-14]^n[m-16],1);var b=o(o(s(a,5),e(m,u,h,f)),o(o(c,n[m]),i(m)));c=f,f=h,h=s(u,30),u=a,a=b}a=o(a,p),u=o(u,v),h=o(h,d),f=o(f,g),c=o(c,y)}return Array(a,u,h,f,c)}function e(t,r,n,e){return 20>t?r&n|~r&e:40>t?r^n^e:60>t?r&n|r&e|n&e:r^n^e}function i(t){return 20>t?1518500249:40>t?1859775393:60>t?-1894007588:-899497514}function o(t,r){var n=(65535&t)+(65535&r),e=(t>>16)+(r>>16)+(n>>16);return e<<16|65535&n}function s(t,r){return t<>>32-r}var a=t("./helpers");r.exports=function(t){return a.hash(t,n,20,!0)}},{"./helpers":5}],10:[function(t,r){var n=t("./helpers"),e=function(t,r){var n=(65535&t)+(65535&r),e=(t>>16)+(r>>16)+(n>>16);return e<<16|65535&n},i=function(t,r){return t>>>r|t<<32-r},o=function(t,r){return t>>>r},s=function(t,r,n){return t&r^~t&n},a=function(t,r,n){return t&r^t&n^r&n},u=function(t){return i(t,2)^i(t,13)^i(t,22)},h=function(t){return i(t,6)^i(t,11)^i(t,25)},f=function(t){return i(t,7)^i(t,18)^o(t,3)},c=function(t){return i(t,17)^i(t,19)^o(t,10)},l=function(t,r){var n,i,o,l,p,v,d,g,y,m,b,w,S=new Array(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),T=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),E=new Array(64);t[r>>5]|=128<<24-r%32,t[(r+64>>9<<4)+15]=r;for(var y=0;ym;m++)E[m]=16>m?t[m+y]:e(e(e(c(E[m-2]),E[m-7]),f(E[m-15])),E[m-16]),b=e(e(e(e(g,h(p)),s(p,v,d)),S[m]),E[m]),w=e(u(n),a(n,i,o)),g=d,d=v,v=p,p=e(l,b),l=o,o=i,i=n,n=e(b,w);T[0]=e(n,T[0]),T[1]=e(i,T[1]),T[2]=e(o,T[2]),T[3]=e(l,T[3]),T[4]=e(p,T[4]),T[5]=e(v,T[5]),T[6]=e(d,T[6]),T[7]=e(g,T[7])}return T};r.exports=function(t){return n.hash(t,l,32,!0)}},{"./helpers":5}]},{},[1]); \ No newline at end of file diff --git a/dist/cryptico.browser.js b/dist/cryptico.browser.js new file mode 100644 index 0000000..f37ea8c --- /dev/null +++ b/dist/cryptico.browser.js @@ -0,0 +1,4854 @@ +/* cryptico-js v1.0.4 - - https://github.com/tracker1/cryptico-js */ + +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.cryptico=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o> 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; +} + +BigInteger.prototype.am = am; +dbits = 30; + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1 << dbits) - 1); +BigInteger.prototype.DV = (1 << dbits); + +var BI_FP = 52; +BigInteger.prototype.FV = Math.pow(2, BI_FP); +BigInteger.prototype.F1 = BI_FP - dbits; +BigInteger.prototype.F2 = 2 * dbits - BI_FP; + +// Digit conversions +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; +var BI_RC = new Array(); +var rr, vv; +rr = "0".charCodeAt(0); +for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; +rr = "a".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; +rr = "A".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + +function int2char(n) { + return BI_RM.charAt(n); +} + +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; +} + +// (protected) copy this to r + +function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV + +function bnpFromInt(x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + DV; + else this.t = 0; +} + +// return bigint initialized to value + +function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; +} + +// (protected) set from string and radix + +function bnpFromString(s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; // byte array + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = (k == 8) ? s[i] & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if (sh == 0) this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } + else this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 0x80) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); +} + +// (protected) clamp off excess high words + +function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c)--this.t; +} + +// (public) return string representation in given radix + +function bnToString(b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 64) k = 6; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, + d, m = false, + r = "", + i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } + else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : "0"; +} + +// (public) -this + +function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; +} + +// (public) |this| + +function bnAbs() { + return (this.s < 0) ? this.negate() : this; +} + +// (public) return + if this > a, - if this < a, 0 if equal + +function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return r; + while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x + +function nbits(x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; +} + +// (public) return the number of bits in "this" + +function bnBitLength() { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); +} + +// (protected) r = this << n*DB + +function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; +} + +// (protected) r = this >> n*DB + +function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; +} + +// (protected) r = this << n + +function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n + +function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); +} + +// (protected) r = this - a + +function bnpSubTo(a, r) { + var i = 0, + c = 0, + m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. + +function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); +} + +// (protected) r = this^2, r != this (HAC 14.16) + +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. + +function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), + ts = this.s, + ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } + else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) r.subTo(t, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r); +} + +// (public) this mod a + +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; +} + +// Modular reduction using "classic" algorithm + +function Classic(m) { + this.m = m; +} + +function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} + +function cRevert(x) { + return x; +} + +function cReduce(x) { + x.divRemTo(this.m, null, x); +} + +function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. + +function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; +} + +// Montgomery reduction + +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; +} + +// xR mod m + +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; +} + +// x/R mod m + +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) + +function montReduce(x) { + while (x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); +} + +// r = "x^2/R mod m"; x != r + +function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +// r = "xy/R mod m"; x,y != r + +function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even + +function bnpIsEven() { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; +} + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + +function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 + +function bnModPowInt(e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); +} + +// protected +BigInteger.prototype.copyTo = bnpCopyTo; +BigInteger.prototype.fromInt = bnpFromInt; +BigInteger.prototype.fromString = bnpFromString; +BigInteger.prototype.clamp = bnpClamp; +BigInteger.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger.prototype.drShiftTo = bnpDRShiftTo; +BigInteger.prototype.lShiftTo = bnpLShiftTo; +BigInteger.prototype.rShiftTo = bnpRShiftTo; +BigInteger.prototype.subTo = bnpSubTo; +BigInteger.prototype.multiplyTo = bnpMultiplyTo; +BigInteger.prototype.squareTo = bnpSquareTo; +BigInteger.prototype.divRemTo = bnpDivRemTo; +BigInteger.prototype.invDigit = bnpInvDigit; +BigInteger.prototype.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// public +BigInteger.prototype.toString = bnToString; +BigInteger.prototype.negate = bnNegate; +BigInteger.prototype.abs = bnAbs; +BigInteger.prototype.compareTo = bnCompareTo; +BigInteger.prototype.bitLength = bnBitLength; +BigInteger.prototype.mod = bnMod; +BigInteger.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + + +function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; +} + +// (public) return value as integer + +function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } + else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; +} + +// (public) return value as byte + +function bnByteValue() { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; +} + +// (public) return value as short (assumes DB>=16) + +function bnShortValue() { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; +} + +// (protected) return x s.t. r^x < DV + +function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); +} + +// (public) 0 if this == 0, 1 if this > 0 + +function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; +} + +// (protected) convert to radix string + +function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), + y = nbi(), + z = nbi(), + r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; +} + +// (protected) convert from radix string + +function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); +} + +// (protected) alternate constructor + +function bnpFromNumber(a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= ((1 << t) - 1); + else x[0] = 0; + this.fromString(x, 256); + } +} + +// (public) convert to bigendian byte array + +function bnToByteArray() { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8, + d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } + else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) d |= -256; + if (k == 0 && (this.s & 0x80) != (d & 0x80))++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; +} + +function bnEquals(a) { + return (this.compareTo(a) == 0); +} + +function bnMin(a) { + return (this.compareTo(a) < 0) ? this : a; +} + +function bnMax(a) { + return (this.compareTo(a) > 0) ? this : a; +} + +// (protected) r = this op a (bitwise) + +function bnpBitwiseTo(a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } + else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); +} + +// (public) this & a + +function op_and(x, y) { + return x & y; +} + +function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; +} + +// (public) this | a + +function op_or(x, y) { + return x | y; +} + +function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; +} + +// (public) this ^ a + +function op_xor(x, y) { + return x ^ y; +} + +function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; +} + +// (public) this & ~a + +function op_andnot(x, y) { + return x & ~y; +} + +function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; +} + +// (public) ~this + +function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; +} + +// (public) this << n + +function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; +} + +// (public) this >> n + +function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; +} + +// return index of lowest 1-bit in x, x < 2^31 + +function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0)++r; + return r; +} + +// (public) returns index of lowest 1-bit (or -1 if none) + +function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; +} + +// return number of 1 bits in x + +function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; +} + +// (public) return number of set bits + +function bnBitCount() { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; +} + +// (public) true iff nth bit is set + +function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return (this.s != 0); + return ((this[j] & (1 << (n % this.DB))) != 0); +} + +// (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); +} + +// (public) this + a + +function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; +} + +// (public) this - a + +function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; +} + +// (public) this * a + +function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; +} + +// (public) this^2 + +function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; +} + +// (public) this / a + +function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; +} + +// (public) this % a + +function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; +} + +// (public) [this/a,this%a] + +function bnDivideAndRemainder(a) { + var q = nbi(), + r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); +} + +// (protected) this *= n, this >= 0, 1 < n < DV + +function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); +} + +// (protected) this += n << w words, this >= 0 + +function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; + } +} + +// A "null" reducer + +function NullExp() {} + +function nNop(x) { + return x; +} + +function nMulTo(x, y, r) { + x.multiplyTo(y, r); +} + +function nSqrTo(x, r) { + x.squareTo(r); +} + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +// (public) this^e + +function bnPow(e) { + return this.exp(e, new NullExp()); +} + +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. + +function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); +} + +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. + +function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); +} + +// Barrett modular reduction + +function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; +} + +function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } +} + +function barrettRevert(x) { + return x; +} + +// x = x mod m (HAC 14.42) + +function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); +} + +// r = x^2 mod m; x != r + +function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); +} + +// r = x*y mod m; x,y != r + +function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); +} + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +// (public) this^e % m (HAC 14.85) + +function bnModPow(e, m) { + var i = e.bitLength(), + k, r = nbv(1), + z; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) z = new Classic(m); + else if (m.isEven()) z = new Barrett(m); + else z = new Montgomery(m); + + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1; + g[1] = z.convert(this); + if (k > 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + + var j = e.t - 1, + w, is1 = true, + r2 = nbi(), + t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km; + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); + } + + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); +} + +// (public) gcd(this,a) (HAC 14.54) + +function bnGCD(a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; +} + +// (protected) this % n, n < 2^26 + +function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) if (d == 0) r = this[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; +} + +// (public) 1/this % m (HAC 14.61) + +function bnModInverse(m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), + v = this.clone(); + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } + else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } + else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } + else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; +} + +var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + +// (public) test primality with certainty >= 1-.5^t + +function bnIsProbablePrime(t) { + var i, x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); +} + +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) + +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; +} + +// protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +// public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +// JSBN-specific extension +BigInteger.prototype.square = bnSquare; +// seedrandom.js version 2.0. +// Author: David Bau 4/2/2011 +// +// Defines a method Math.seedrandom() that, when called, substitutes +// an explicitly seeded RC4-based algorithm for Math.random(). Also +// supports automatic seeding from local or network sources of entropy. +// +// Usage: +// +// +// +// Math.seedrandom('yipee'); Sets Math.random to a function that is +// initialized using the given explicit seed. +// +// Math.seedrandom(); Sets Math.random to a function that is +// seeded using the current time, dom state, +// and other accumulated local entropy. +// The generated seed string is returned. +// +// Math.seedrandom('yowza', true); +// Seeds using the given explicit seed mixed +// together with accumulated entropy. +// +// +// Seeds using physical random bits downloaded +// from random.org. +// +// Seeds using urandom bits from call.jsonlib.com, +// which is faster than random.org. +// +// Examples: +// +// Math.seedrandom("hello"); // Use "hello" as the seed. +// document.write(Math.random()); // Always 0.5463663768140734 +// document.write(Math.random()); // Always 0.43973793770592234 +// var rng1 = Math.random; // Remember the current prng. +// +// var autoseed = Math.seedrandom(); // New prng with an automatic seed. +// document.write(Math.random()); // Pretty much unpredictable. +// +// Math.random = rng1; // Continue "hello" prng sequence. +// document.write(Math.random()); // Always 0.554769432473455 +// +// Math.seedrandom(autoseed); // Restart at the previous seed. +// document.write(Math.random()); // Repeat the 'unpredictable' value. +// +// Notes: +// +// Each time seedrandom('arg') is called, entropy from the passed seed +// is accumulated in a pool to help generate future seeds for the +// zero-argument form of Math.seedrandom, so entropy can be injected over +// time by calling seedrandom with explicit data repeatedly. +// +// On speed - This javascript implementation of Math.random() is about +// 3-10x slower than the built-in Math.random() because it is not native +// code, but this is typically fast enough anyway. Seeding is more expensive, +// especially if you use auto-seeding. Some details (timings on Chrome 4): +// +// Our Math.random() - avg less than 0.002 milliseconds per call +// seedrandom('explicit') - avg less than 0.5 milliseconds per call +// seedrandom('explicit', true) - avg less than 2 milliseconds per call +// seedrandom() - avg about 38 milliseconds per call +// +// LICENSE (BSD): +// +// Copyright 2010 David Bau, all rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. Neither the name of this module nor the names of its contributors may +// be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/** + * All code is in an anonymous closure to keep the global namespace clean. + * + * @param {number=} overflow + * @param {number=} startdenom + */ +(function (pool, math, width, chunks, significance, overflow, startdenom) +{ + + + // + // seedrandom() + // This is the seedrandom function described above. + // + math['seedrandom'] = function seedrandom(seed, use_entropy) + { + var key = []; + var arc4; + + // Flatten the seed string or build one from local entropy if needed. + seed = mixkey(flatten( + use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool], 3), key); + + // Use the seed to initialize an ARC4 generator. + arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(arc4.S, pool); + + // Override Math.random + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + math['random'] = function random() + { // Closure to return a random double: + var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 + var d = startdenom; // and denominator d = 2 ^ 48. + var x = 0; // and no 'extra last byte'. + while (n < significance) + { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) + { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + // Return the seed that was used + return seed; + }; + + // + // ARC4 + // + // An ARC4 implementation. The constructor takes a key in the form of + // an array of at most (width) integers that should be 0 <= x < (width). + // + // The g(count) method returns a pseudorandom integer that concatenates + // the next (count) outputs from ARC4. Its return value is a number x + // that is in the range 0 <= x < (width ^ count). + // + /** @constructor */ + + function ARC4(key) + { + var t, u, me = this, + keylen = key.length; + var i = 0, + j = me.i = me.j = me.m = 0; + me.S = []; + me.c = []; + + // The empty key [] is treated as [0]. + if (!keylen) + { + key = [keylen++]; + } + + // Set up S using the standard key scheduling algorithm. + while (i < width) + { + me.S[i] = i++; + } + for (i = 0; i < width; i++) + { + t = me.S[i]; + j = lowbits(j + t + key[i % keylen]); + u = me.S[j]; + me.S[i] = u; + me.S[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + me.g = function getnext(count) + { + var s = me.S; + var i = lowbits(me.i + 1); + var t = s[i]; + var j = lowbits(me.j + t); + var u = s[j]; + s[i] = u; + s[j] = t; + var r = s[lowbits(t + u)]; + while (--count) + { + i = lowbits(i + 1); + t = s[i]; + j = lowbits(j + t); + u = s[j]; + s[i] = u; + s[j] = t; + r = r * width + s[lowbits(t + u)]; + } + me.i = i; + me.j = j; + return r; + }; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + me.g(width); + } + + // + // flatten() + // Converts an object tree to nested arrays of strings. + // + /** @param {Object=} result + * @param {string=} prop + * @param {string=} typ */ + + function flatten(obj, depth, result, prop, typ) + { + result = []; + typ = typeof (obj); + if (depth && typ == 'object') + { + for (prop in obj) + { + if (prop.indexOf('S') < 5) + { // Avoid FF3 bug (local/sessionStorage) + try + { + result.push(flatten(obj[prop], depth - 1)); + } + catch (e) + {} + } + } + } + return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); + } + + // + // mixkey() + // Mixes a string seed into a key that is an array of integers, and + // returns a shortened string seed that is equivalent to the result key. + // + /** @param {number=} smear + * @param {number=} j */ + + function mixkey(seed, key, smear, j) + { + seed += ''; // Ensure the seed is a string + smear = 0; + for (j = 0; j < seed.length; j++) + { + key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); + } + seed = ''; + for (j in key) + { + seed += String.fromCharCode(key[j]); + } + return seed; + } + + // + // lowbits() + // A quick "n mod width" for width a power of 2. + // + + + function lowbits(n) + { + return n & (width - 1); + } + + // + // The following constants are related to IEEE 754 limits. + // + startdenom = math.pow(width, chunks); + significance = math.pow(2, significance); + overflow = significance * 2; + + // + // When seedrandom.js is loaded, we immediately mix a few bits + // from the built-in RNG into the entropy pool. Because we do + // not want to intefere with determinstic PRNG state later, + // seedrandom will not call math.random on its own again after + // initialization. + // + mixkey(math.random(), pool); + + // End anonymous scope, and pass initial values. +})([], // pool: entropy pool starts empty +Math, // math: package containing random, pow, and seedrandom +256, // width: each RC4 output is 0 <= x < 256 +6, // chunks: at least six RC4 outputs for each double +52 // significance: there are 52 significant digits in a double +); + + +// This is not really a random number generator object, and two SeededRandom +// objects will conflict with one another, but it's good enough for generating +// the rsa key. +function SeededRandom(){} + +function SRnextBytes(ba) +{ + var i; + for(i = 0; i < ba.length; i++) + { + ba[i] = Math.floor(Math.random() * 256); + } +} + +SeededRandom.prototype.nextBytes = SRnextBytes; + +// prng4.js - uses Arcfour as a PRNG + +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; + +// Plug in your RNG constructor here +function prng_newstate() { + return new Arcfour(); +} + +// Pool size must be a multiple of 4 and greater than 32. +// An array of bytes the size of the pool will be passed to init() +var rng_psize = 256; + +// Random number generator - requires a PRNG backend, e.g. prng4.js + +// For best results, put code like +// +// in your main HTML document. + +var rng_state; +var rng_pool; +var rng_pptr; + +// Mix in a 32-bit integer into the pool +function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; +} + +// Mix in the current time (w/milliseconds) into the pool +function rng_seed_time() { + rng_seed_int(new Date().getTime()); +} + +// Initialize the pool with junk if needed. +if(rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + while(rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + //rng_seed_int(window.screenX); + //rng_seed_int(window.screenY); +} + +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; +/** +* +* Secure Hash Algorithm (SHA256) +* http://www.webtoolkit.info/ +* +* Original code by Angel Marin, Paul Johnston. +* +**/ + +var crypto = _dereq_('crypto'); + +function SHA256(s){ + return crypto.createHash('sha256').update(s, 'utf8').digest('hex'); +} + +var sha256 = {} +sha256.hex = function(s) +{ + return SHA256(s); +} + +/** +* +* Secure Hash Algorithm (SHA1) +* http://www.webtoolkit.info/ +* +**/ + +function SHA1 (msg) { + return crypto.createHash('sha1').update(msg, 'utf8').digest('hex'); +} + +var sha1 = {} +sha1.hex = function(s) +{ + return SHA1(s); +} + +/** +* +* MD5 (Message-Digest Algorithm) +* http://www.webtoolkit.info/ +* +**/ + +var MD5 = function (string) { + return crypto.createHash('md5').update(string, 'utf8').digest('hex'); +} +// Depends on jsbn.js and rng.js +// Version 1.1: support utf-8 encoding in pkcs1pad2 +// convert a (hex) string to a bignum object + + +function parseBigInt(str, r) +{ + return new BigInteger(str, r); +} + +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 + //alert("Message too long for RSA (n=" + n + ", l=" + s.length + ")"); + //return null; + throw "Message too long for RSA (n=" + n + ", l=" + s.length + ")"; + } + 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); +} + +// "empty" RSA key constructor + + +function RSAKey() +{ + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; +} +// Set the public key fields N and e from hex strings + + +function RSASetPublic(N, E) +{ + if (N != null && E != null && N.length > 0 && E.length > 0) + { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + } + else alert("Invalid RSA public key"); +} + +// Perform raw public operation on "x": return x^e (mod n) + + +function RSADoPublic(x) +{ + return x.modPowInt(this.e, this.n); +} + +// Return the PKCS#1 RSA encryption of "text" as an even-length hex string + + +function RSAEncrypt(text) +{ + var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); + if (m == null) return null; + var c = this.doPublic(m); + if (c == null) return null; + var h = c.toString(16); + if ((h.length & 1) == 0) return h; + else return "0" + h; +} + +function RSAToJSON() +{ + return { + coeff: this.coeff.toString(16), + d: this.d.toString(16), + dmp1: this.dmp1.toString(16), + dmq1: this.dmq1.toString(16), + e: this.e.toString(16), + n: this.n.toString(16), + p: this.p.toString(16), + q: this.q.toString(16) + } +} + +function RSAParse(rsaString) { + var json = JSON.parse(rsaString); + var rsa = new RSAKey(); + + rsa.setPrivateEx(json.n, json.e, json.d, json.p, json.q, json.dmp1, json.dmq1, json.coeff); + + return rsa; +} + +// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string +//function RSAEncryptB64(text) { +// var h = this.encrypt(text); +// if(h) return hex2b64(h); else return null; +//} +// protected +RSAKey.prototype.doPublic = RSADoPublic; + +// public +RSAKey.prototype.setPublic = RSASetPublic; +RSAKey.prototype.encrypt = RSAEncrypt; +RSAKey.prototype.toJSON = RSAToJSON; +RSAKey.parse = RSAParse; + +// Version 1.1: support utf-8 decoding in pkcs1unpad2 +// 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, and d from hex strings +function RSASetPrivate(N, E, D) +{ + 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); + } + else alert("Invalid RSA private key"); +} + +// 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 throw new 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 SeededRandom(); + 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; + } + } +} + +// Perform raw private operation on "x": return x^d (mod n) +function RSADoPrivate(x) +{ + if (this.p == null || this.q == null) return x.modPow(this.d, this.n); + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + 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); +} + +// Return the PKCS#1 RSA decryption of "ctext". +// "ctext" is an even-length hex string and the output is a plain string. +function RSADecrypt(ctext) +{ + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if (m == null) return null; + return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); +} + +// protected +RSAKey.prototype.doPrivate = RSADoPrivate; + +// public +RSAKey.prototype.setPrivate = RSASetPrivate; +RSAKey.prototype.setPrivateEx = RSASetPrivateEx; +RSAKey.prototype.generate = RSAGenerate; +RSAKey.prototype.decrypt = RSADecrypt; + + +// +// rsa-sign.js - adding signing functions to RSAKey class. +// +// +// version: 1.0 (2010-Jun-03) +// +// Copyright (c) 2010 Kenji Urushima (kenji.urushima@gmail.com) +// +// This software is licensed under the terms of the MIT License. +// http://www.opensource.org/licenses/mit-license.php +// +// The above copyright and license notice shall be +// included in all copies or substantial portions of the Software. +// +// Depends on: +// function sha1.hex(s) of sha1.js +// jsbn.js +// jsbn2.js +// rsa.js +// rsa2.js +// +// keysize / pmstrlen +// 512 / 128 +// 1024 / 256 +// 2048 / 512 +// 4096 / 1024 +// As for _RSASGIN_DIHEAD values for each hash algorithm, see PKCS#1 v2.1 spec (p38). +var _RSASIGN_DIHEAD = []; +_RSASIGN_DIHEAD['sha1'] = "3021300906052b0e03021a05000414"; +_RSASIGN_DIHEAD['sha256'] = "3031300d060960864801650304020105000420"; +//_RSASIGN_DIHEAD['md2'] = "3020300c06082a864886f70d020205000410"; +//_RSASIGN_DIHEAD['md5'] = "3020300c06082a864886f70d020505000410"; +//_RSASIGN_DIHEAD['sha384'] = "3041300d060960864801650304020205000430"; +//_RSASIGN_DIHEAD['sha512'] = "3051300d060960864801650304020305000440"; +var _RSASIGN_HASHHEXFUNC = []; +_RSASIGN_HASHHEXFUNC['sha1'] = sha1.hex; +_RSASIGN_HASHHEXFUNC['sha256'] = sha256.hex; + +// ======================================================================== +// Signature Generation +// ======================================================================== + +function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) +{ + var pmStrLen = keySize / 4; + var hashFunc = _RSASIGN_HASHHEXFUNC[hashAlg]; + var sHashHex = hashFunc(s); + + var sHead = "0001"; + var sTail = "00" + _RSASIGN_DIHEAD[hashAlg] + sHashHex; + var sMid = ""; + var fLen = pmStrLen - sHead.length - sTail.length; + for (var i = 0; i < fLen; i += 2) + { + sMid += "ff"; + } + var sPaddedMessageHex = sHead + sMid + sTail; + return sPaddedMessageHex; +} + +function _rsasign_signString(s, hashAlg) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), hashAlg); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +function _rsasign_signStringWithSHA1(s) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), 'sha1'); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +function _rsasign_signStringWithSHA256(s) +{ + var hPM = _rsasign_getHexPaddedDigestInfoForString(s, this.n.bitLength(), 'sha256'); + var biPaddedMessage = parseBigInt(hPM, 16); + var biSign = this.doPrivate(biPaddedMessage); + var hexSign = biSign.toString(16); + return hexSign; +} + +// ======================================================================== +// Signature Verification +// ======================================================================== + +function _rsasign_getDecryptSignatureBI(biSig, hN, hE) +{ + var rsa = new RSAKey(); + rsa.setPublic(hN, hE); + var biDecryptedSig = rsa.doPublic(biSig); + return biDecryptedSig; +} + +function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) +{ + var biDecryptedSig = _rsasign_getDecryptSignatureBI(biSig, hN, hE); + var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, ''); + return hDigestInfo; +} + +function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) +{ + for (var algName in _RSASIGN_DIHEAD) + { + var head = _RSASIGN_DIHEAD[algName]; + var len = head.length; + if (hDigestInfo.substring(0, len) == head) + { + var a = [algName, hDigestInfo.substring(len)]; + return a; + } + } + return []; +} + +function _rsasign_verifySignatureWithArgs(sMsg, biSig, hN, hE) +{ + var hDigestInfo = _rsasign_getHexDigestInfoFromSig(biSig, hN, hE); + var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo); + if (digestInfoAry.length == 0) return false; + var algName = digestInfoAry[0]; + var diHashValue = digestInfoAry[1]; + var ff = _RSASIGN_HASHHEXFUNC[algName]; + var msgHashValue = ff(sMsg); + return (diHashValue == msgHashValue); +} + +function _rsasign_verifyHexSignatureForMessage(hSig, sMsg) +{ + var biSig = parseBigInt(hSig, 16); + var result = _rsasign_verifySignatureWithArgs(sMsg, biSig, this.n.toString(16), this.e.toString(16)); + return result; +} + +function _rsasign_verifyString(sMsg, hSig) +{ + hSig = hSig.replace(/[ \n]+/g, ""); + var biSig = parseBigInt(hSig, 16); + var biDecryptedSig = this.doPublic(biSig); + var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, ''); + var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo); + + if (digestInfoAry.length == 0) return false; + var algName = digestInfoAry[0]; + var diHashValue = digestInfoAry[1]; + var ff = _RSASIGN_HASHHEXFUNC[algName]; + var msgHashValue = ff(sMsg); + return (diHashValue == msgHashValue); +} + +RSAKey.prototype.signString = _rsasign_signString; +RSAKey.prototype.signStringWithSHA1 = _rsasign_signStringWithSHA1; +RSAKey.prototype.signStringWithSHA256 = _rsasign_signStringWithSHA256; + +RSAKey.prototype.verifyString = _rsasign_verifyString; +RSAKey.prototype.verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMessage; + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* + * jsaes version 0.1 - Copyright 2006 B. Poettering + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA + */ + + // later modifications by wwwtyro@github + +var aes = (function () { + + var my = {}; + + my.Sbox = new Array(99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22); + + my.ShiftRowTab = new Array(0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11); + + my.Init = function () { + my.Sbox_Inv = new Array(256); + for (var i = 0; i < 256; i++) + my.Sbox_Inv[my.Sbox[i]] = i; + + my.ShiftRowTab_Inv = new Array(16); + for (var i = 0; i < 16; i++) + my.ShiftRowTab_Inv[my.ShiftRowTab[i]] = i; + + my.xtime = new Array(256); + for (var i = 0; i < 128; i++) { + my.xtime[i] = i << 1; + my.xtime[128 + i] = (i << 1) ^ 0x1b; + } + } + + my.Done = function () { + delete my.Sbox_Inv; + delete my.ShiftRowTab_Inv; + delete my.xtime; + } + + my.ExpandKey = function (key) { + var kl = key.length, + ks, Rcon = 1; + switch (kl) { + case 16: + ks = 16 * (10 + 1); + break; + case 24: + ks = 16 * (12 + 1); + break; + case 32: + ks = 16 * (14 + 1); + break; + default: + alert("my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!"); + } + for (var i = kl; i < ks; i += 4) { + var temp = key.slice(i - 4, i); + if (i % kl == 0) { + temp = new Array(my.Sbox[temp[1]] ^ Rcon, my.Sbox[temp[2]], my.Sbox[temp[3]], my.Sbox[temp[0]]); + if ((Rcon <<= 1) >= 256) Rcon ^= 0x11b; + } + else if ((kl > 24) && (i % kl == 16)) temp = new Array(my.Sbox[temp[0]], my.Sbox[temp[1]], my.Sbox[temp[2]], my.Sbox[temp[3]]); + for (var j = 0; j < 4; j++) + key[i + j] = key[i + j - kl] ^ temp[j]; + } + } + + my.Encrypt = function (block, key) { + var l = key.length; + my.AddRoundKey(block, key.slice(0, 16)); + for (var i = 16; i < l - 16; i += 16) { + my.SubBytes(block, my.Sbox); + my.ShiftRows(block, my.ShiftRowTab); + my.MixColumns(block); + my.AddRoundKey(block, key.slice(i, i + 16)); + } + my.SubBytes(block, my.Sbox); + my.ShiftRows(block, my.ShiftRowTab); + my.AddRoundKey(block, key.slice(i, l)); + } + + my.Decrypt = function (block, key) { + var l = key.length; + my.AddRoundKey(block, key.slice(l - 16, l)); + my.ShiftRows(block, my.ShiftRowTab_Inv); + my.SubBytes(block, my.Sbox_Inv); + for (var i = l - 32; i >= 16; i -= 16) { + my.AddRoundKey(block, key.slice(i, i + 16)); + my.MixColumns_Inv(block); + my.ShiftRows(block, my.ShiftRowTab_Inv); + my.SubBytes(block, my.Sbox_Inv); + } + my.AddRoundKey(block, key.slice(0, 16)); + } + + my.SubBytes = function (state, sbox) { + for (var i = 0; i < 16; i++) + state[i] = sbox[state[i]]; + } + + my.AddRoundKey = function (state, rkey) { + for (var i = 0; i < 16; i++) + state[i] ^= rkey[i]; + } + + my.ShiftRows = function (state, shifttab) { + var h = new Array().concat(state); + for (var i = 0; i < 16; i++) + state[i] = h[shifttab[i]]; + } + + my.MixColumns = function (state) { + for (var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], + s1 = state[i + 1]; + var s2 = state[i + 2], + s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + state[i + 0] ^= h ^ my.xtime[s0 ^ s1]; + state[i + 1] ^= h ^ my.xtime[s1 ^ s2]; + state[i + 2] ^= h ^ my.xtime[s2 ^ s3]; + state[i + 3] ^= h ^ my.xtime[s3 ^ s0]; + } + } + + my.MixColumns_Inv = function (state) { + for (var i = 0; i < 16; i += 4) { + var s0 = state[i + 0], + s1 = state[i + 1]; + var s2 = state[i + 2], + s3 = state[i + 3]; + var h = s0 ^ s1 ^ s2 ^ s3; + var xh = my.xtime[h]; + var h1 = my.xtime[my.xtime[xh ^ s0 ^ s2]] ^ h; + var h2 = my.xtime[my.xtime[xh ^ s1 ^ s3]] ^ h; + state[i + 0] ^= h1 ^ my.xtime[s0 ^ s1]; + state[i + 1] ^= h2 ^ my.xtime[s1 ^ s2]; + state[i + 2] ^= h1 ^ my.xtime[s2 ^ s3]; + state[i + 3] ^= h2 ^ my.xtime[s3 ^ s0]; + } + } + + return my; + +}()); +var cryptico = (function() { + + var my = {}; + + aes.Init(); + + var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + my.b256to64 = function(t) { + var a, c, n; + var r = '', l = 0, s = 0; + var tl = t.length; + for (n = 0; n < tl; n++) + { + c = t.charCodeAt(n); + if (s == 0) + { + r += base64Chars.charAt((c >> 2) & 63); + a = (c & 3) << 4; + } + else if (s == 1) + { + r += base64Chars.charAt((a | (c >> 4) & 15)); + a = (c & 15) << 2; + } + else if (s == 2) + { + r += base64Chars.charAt(a | ((c >> 6) & 3)); + l += 1; + r += base64Chars.charAt(c & 63); + } + l += 1; + s += 1; + if (s == 3) s = 0; + } + if (s > 0) + { + r += base64Chars.charAt(a); + l += 1; + r += '='; + l += 1; + } + if (s == 1) + { + r += '='; + } + return r; + } + + my.b64to256 = function(t) + { + var c, n; + var r = '', s = 0, a = 0; + var tl = t.length; + for (n = 0; n < tl; n++) + { + c = base64Chars.indexOf(t.charAt(n)); + if (c >= 0) + { + if (s) r += String.fromCharCode(a | (c >> (6 - s)) & 255); + s = (s + 2) & 7; + a = (c << s) & 255; + } + } + return r; + } + + my.b16to64 = function(h) { + var i; + var c; + var ret = ""; + if(h.length % 2 == 1) + { + h = "0" + h; + } + for (i = 0; i + 3 <= h.length; i += 3) + { + c = parseInt(h.substring(i, i + 3), 16); + ret += base64Chars.charAt(c >> 6) + base64Chars.charAt(c & 63); + } + if (i + 1 == h.length) + { + c = parseInt(h.substring(i, i + 1), 16); + ret += base64Chars.charAt(c << 2); + } + else if (i + 2 == h.length) + { + c = parseInt(h.substring(i, i + 2), 16); + ret += base64Chars.charAt(c >> 2) + base64Chars.charAt((c & 3) << 4); + } + while ((ret.length & 3) > 0) ret += "="; + return ret; + } + + my.b64to16 = function(s) { + var ret = ""; + var i; + var k = 0; + var slop; + for (i = 0; i < s.length; ++i) + { + if (s.charAt(i) == "=") break; + v = base64Chars.indexOf(s.charAt(i)); + if (v < 0) continue; + if (k == 0) + { + ret += int2char(v >> 2); + slop = v & 3; + k = 1; + } + else if (k == 1) + { + ret += int2char((slop << 2) | (v >> 4)); + slop = v & 0xf; + k = 2; + } + else if (k == 2) + { + ret += int2char(slop); + ret += int2char(v >> 2); + slop = v & 3; + k = 3; + } + else + { + ret += int2char((slop << 2) | (v >> 4)); + ret += int2char(v & 0xf); + k = 0; + } + } + if (k == 1) ret += int2char(slop << 2); + return ret; + } + + // Converts a string to a byte array. + my.string2bytes = function(string) + { + var bytes = new Array(); + for(var i = 0; i < string.length; i++) + { + bytes.push(string.charCodeAt(i)); + } + return bytes; + } + + // Converts a byte array to a string. + my.bytes2string = function(bytes) + { + var string = ""; + for(var i = 0; i < bytes.length; i++) + { + string += String.fromCharCode(bytes[i]); + } + return string; + } + + // Returns a XOR b, where a and b are 16-byte byte arrays. + my.blockXOR = function(a, b) + { + var xor = new Array(16); + for(var i = 0; i < 16; i++) + { + xor[i] = a[i] ^ b[i]; + } + return xor; + } + + // Returns a 16-byte initialization vector. + my.blockIV = function() + { + var r = new SecureRandom(); + var IV = new Array(16); + r.nextBytes(IV); + return IV; + } + + // Returns a copy of bytes with zeros appended to the end + // so that the (length of bytes) % 16 == 0. + my.pad16 = function(bytes) + { + var newBytes = bytes.slice(0); + var padding = (16 - (bytes.length % 16)) % 16; + for(i = bytes.length; i < bytes.length + padding; i++) + { + newBytes.push(0); + } + return newBytes; + } + + // Removes trailing zeros from a byte array. + my.depad = function(bytes) + { + var newBytes = bytes.slice(0); + while(newBytes[newBytes.length - 1] == 0) + { + newBytes = newBytes.slice(0, newBytes.length - 1); + } + return newBytes; + } + + // AES CBC Encryption. + my.encryptAESCBC = function(plaintext, key) + { + var exkey = key.slice(0); + aes.ExpandKey(exkey); + var blocks = my.string2bytes(plaintext); + blocks = my.pad16(blocks); + var encryptedBlocks = my.blockIV(); + for(var i = 0; i < blocks.length/16; i++) + { + var tempBlock = blocks.slice(i * 16, i * 16 + 16); + var prevBlock = encryptedBlocks.slice((i) * 16, (i) * 16 + 16); + tempBlock = my.blockXOR(prevBlock, tempBlock); + aes.Encrypt(tempBlock, exkey); + encryptedBlocks = encryptedBlocks.concat(tempBlock); + } + var ciphertext = my.bytes2string(encryptedBlocks); + return my.b256to64(ciphertext) + } + + // AES CBC Decryption. + my.decryptAESCBC = function(encryptedText, key) + { + var exkey = key.slice(0); + aes.ExpandKey(exkey); + var encryptedText = my.b64to256(encryptedText); + var encryptedBlocks = my.string2bytes(encryptedText); + var decryptedBlocks = new Array(); + for(var i = 1; i < encryptedBlocks.length/16; i++) + { + var tempBlock = encryptedBlocks.slice(i * 16, i * 16 + 16); + var prevBlock = encryptedBlocks.slice((i-1) * 16, (i-1) * 16 + 16); + aes.Decrypt(tempBlock, exkey); + tempBlock = my.blockXOR(prevBlock, tempBlock); + decryptedBlocks = decryptedBlocks.concat(tempBlock); + } + decryptedBlocks = my.depad(decryptedBlocks); + return my.bytes2string(decryptedBlocks); + } + + // Wraps a string to 60 characters. + my.wrap60 = function(string) + { + var outstr = ""; + for(var i = 0; i < string.length; i++) { + if(i % 60 == 0 && i != 0) outstr += "\n"; + outstr += string[i]; } + return outstr; + } + + // Generate a random key for the AES-encrypted message. + my.generateAESKey = function() + { + var key = new Array(32); + var r = new SecureRandom(); + r.nextBytes(key); + return key; + } + + // Generates an RSA key from a passphrase. + my.generateRSAKey = function(passphrase, bitlength) + { + Math.seedrandom(sha256.hex(passphrase)); + var rsa = new RSAKey(); + rsa.generate(bitlength, "03"); + return rsa; + } + + // Returns the ascii-armored version of the public key. + my.publicKeyString = function(rsakey) + { + pubkey = my.b16to64(rsakey.n.toString(16)); + return pubkey; + } + + // Returns an MD5 sum of a publicKeyString for easier identification. + my.publicKeyID = function(publicKeyString) + { + return MD5(publicKeyString); + } + + my.publicKeyFromString = function(string) + { + var N = my.b64to16(string.split("|")[0]); + var E = "03"; + var rsa = new RSAKey(); + rsa.setPublic(N, E); + return rsa + } + + my.encrypt = function(plaintext, publickeystring, signingkey) + { + var cipherblock = ""; + var aeskey = my.generateAESKey(); + try + { + var publickey = my.publicKeyFromString(publickeystring); + cipherblock += my.b16to64(publickey.encrypt(my.bytes2string(aeskey))) + "?"; + } + catch(err) + { + return {status: "Invalid public key"}; + } + if(signingkey) + { + signString = cryptico.b16to64(signingkey.signString(plaintext, "sha256")); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += cryptico.publicKeyString(signingkey); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += signString; + } + cipherblock += my.encryptAESCBC(plaintext, aeskey); + return {status: "success", cipher: cipherblock}; + } + + my.decrypt = function(ciphertext, key) + { + var cipherblock = ciphertext.split("?"); + var aeskey = key.decrypt(my.b64to16(cipherblock[0])); + if(aeskey == null) + { + return {status: "failure"}; + } + aeskey = my.string2bytes(aeskey); + var plaintext = my.decryptAESCBC(cipherblock[1], aeskey).split("::52cee64bb3a38f6403386519a39ac91c::"); + if(plaintext.length == 3) + { + var publickey = my.publicKeyFromString(plaintext[1]); + var signature = my.b64to16(plaintext[2]); + if(publickey.verifyString(plaintext[0], signature)) + { + return {status: "success", + plaintext: plaintext[0], + signature: "verified", + publicKeyString: my.publicKeyString(publickey)}; + } + else + { + return {status: "success", + plaintext: plaintext[0], + signature: "forged", + publicKeyString: my.publicKeyString(publickey)}; + } + } + else + { + return {status: "success", plaintext: plaintext[0], signature: "unsigned"}; + } + } + + return my; + +}()); + + +module.exports = cryptico; +module.exports.RSAKey = RSAKey; + +if (typeof window !== 'undefined') { + window.cryptico = module.exports; +} + +},{"crypto":6}],2:[function(_dereq_,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var base64 = _dereq_('base64-js') +var ieee754 = _dereq_('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = Buffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 + +/** + * If `Buffer._useTypedArrays`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (compatible down to IE6) + */ +Buffer._useTypedArrays = (function () { + // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, + // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding + // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support + // because we need to be able to add all the node Buffer API methods. This is an issue + // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return 42 === arr.foo() && + typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` + } catch (e) { + return false + } +})() + +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (subject, encoding, noZero) { + if (!(this instanceof Buffer)) + return new Buffer(subject, encoding, noZero) + + var type = typeof subject + + // Workaround: node's base64 implementation allows for non-padded strings + // while base64-js does not. + if (encoding === 'base64' && type === 'string') { + subject = stringtrim(subject) + while (subject.length % 4 !== 0) { + subject = subject + '=' + } + } + + // Find the length + var length + if (type === 'number') + length = coerce(subject) + else if (type === 'string') + length = Buffer.byteLength(subject, encoding) + else if (type === 'object') + length = coerce(subject.length) // assume that object is array-like + else + throw new Error('First argument needs to be a number, array or string.') + + var buf + if (Buffer._useTypedArrays) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + buf = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + buf = this + buf.length = length + buf._isBuffer = true + } + + var i + if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + buf._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + for (i = 0; i < length; i++) { + if (Buffer.isBuffer(subject)) + buf[i] = subject.readUInt8(i) + else + buf[i] = subject[i] + } + } else if (type === 'string') { + buf.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { + for (i = 0; i < length; i++) { + buf[i] = 0 + } + } + + return buf +} + +// STATIC METHODS +// ============== + +Buffer.isEncoding = function (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.isBuffer = function (b) { + return !!(b !== null && b !== undefined && b._isBuffer) +} + +Buffer.byteLength = function (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'hex': + ret = str.length / 2 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'base64': + ret = base64ToBytes(str).length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.concat = function (list, totalLength) { + assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + + 'list should be an Array.') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (typeof totalLength !== 'number') { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length + } + } + + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +// BUFFER INSTANCE METHODS +// ======================= + +function _hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + assert(strLen % 2 === 0, 'Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16) + assert(!isNaN(byte), 'Invalid hex string') + buf[offset + i] = byte + } + Buffer._charsWritten = i * 2 + return i +} + +function _utf8Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf8ToBytes(string), buf, offset, length) + return charsWritten +} + +function _asciiWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} + +function _binaryWrite (buf, string, offset, length) { + return _asciiWrite(buf, string, offset, length) +} + +function _base64Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +function _utf16leWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf16leToBytes(string), buf, offset, length) + return charsWritten +} + +Buffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap + } + + offset = Number(offset) || 0 + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() + + var ret + switch (encoding) { + case 'hex': + ret = _hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = _utf8Write(this, string, offset, length) + break + case 'ascii': + ret = _asciiWrite(this, string, offset, length) + break + case 'binary': + ret = _binaryWrite(this, string, offset, length) + break + case 'base64': + ret = _base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leWrite(this, string, offset, length) + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.prototype.toString = function (encoding, start, end) { + var self = this + + encoding = String(encoding || 'utf8').toLowerCase() + start = Number(start) || 0 + end = (end !== undefined) + ? Number(end) + : end = self.length + + // Fastpath empty strings + if (end === start) + return '' + + var ret + switch (encoding) { + case 'hex': + ret = _hexSlice(self, start, end) + break + case 'utf8': + case 'utf-8': + ret = _utf8Slice(self, start, end) + break + case 'ascii': + ret = _asciiSlice(self, start, end) + break + case 'binary': + ret = _binarySlice(self, start, end) + break + case 'base64': + ret = _base64Slice(self, start, end) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leSlice(self, start, end) + break + default: + throw new Error('Unknown encoding') + } + return ret +} + +Buffer.prototype.toJSON = function () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this + + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (!target_start) target_start = 0 + + // Copy 0 bytes; we're done + if (end === start) return + if (target.length === 0 || source.length === 0) return + + // Fatal error conditions + assert(end >= start, 'sourceEnd < sourceStart') + assert(target_start >= 0 && target_start < target.length, + 'targetStart out of bounds') + assert(start >= 0 && start < source.length, 'sourceStart out of bounds') + assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start + + var len = end - start + + if (len < 100 || !Buffer._useTypedArrays) { + for (var i = 0; i < len; i++) + target[i + target_start] = this[i + start] + } else { + target._set(this.subarray(start, start + len), target_start) + } +} + +function _base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function _utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +function _asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) + ret += String.fromCharCode(buf[i]) + return ret +} + +function _binarySlice (buf, start, end) { + return _asciiSlice(buf, start, end) +} + +function _hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function _utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) + } + return res +} + +Buffer.prototype.slice = function (start, end) { + var len = this.length + start = clamp(start, len, 0) + end = clamp(end, len, len) + + if (Buffer._useTypedArrays) { + return Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + var newBuf = new Buffer(sliceLen, undefined, true) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + return newBuf + } +} + +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +Buffer.prototype.readUInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') + } + + if (offset >= this.length) + return + + return this[offset] +} + +function _readUInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val + if (littleEndian) { + val = buf[offset] + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + } else { + val = buf[offset] << 8 + if (offset + 1 < len) + val |= buf[offset + 1] + } + return val +} + +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + return _readUInt16(this, offset, true, noAssert) +} + +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + return _readUInt16(this, offset, false, noAssert) +} + +function _readUInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val + if (littleEndian) { + if (offset + 2 < len) + val = buf[offset + 2] << 16 + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + val |= buf[offset] + if (offset + 3 < len) + val = val + (buf[offset + 3] << 24 >>> 0) + } else { + if (offset + 1 < len) + val = buf[offset + 1] << 16 + if (offset + 2 < len) + val |= buf[offset + 2] << 8 + if (offset + 3 < len) + val |= buf[offset + 3] + val = val + (buf[offset] << 24 >>> 0) + } + return val +} + +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + return _readUInt32(this, offset, true, noAssert) +} + +Buffer.prototype.readUInt32BE = function (offset, noAssert) { + return _readUInt32(this, offset, false, noAssert) +} + +Buffer.prototype.readInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, + 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') + } + + if (offset >= this.length) + return + + var neg = this[offset] & 0x80 + if (neg) + return (0xff - this[offset] + 1) * -1 + else + return this[offset] +} + +function _readInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val = _readUInt16(buf, offset, littleEndian, true) + var neg = val & 0x8000 + if (neg) + return (0xffff - val + 1) * -1 + else + return val +} + +Buffer.prototype.readInt16LE = function (offset, noAssert) { + return _readInt16(this, offset, true, noAssert) +} + +Buffer.prototype.readInt16BE = function (offset, noAssert) { + return _readInt16(this, offset, false, noAssert) +} + +function _readInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + var len = buf.length + if (offset >= len) + return + + var val = _readUInt32(buf, offset, littleEndian, true) + var neg = val & 0x80000000 + if (neg) + return (0xffffffff - val + 1) * -1 + else + return val +} + +Buffer.prototype.readInt32LE = function (offset, noAssert) { + return _readInt32(this, offset, true, noAssert) +} + +Buffer.prototype.readInt32BE = function (offset, noAssert) { + return _readInt32(this, offset, false, noAssert) +} + +function _readFloat (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } + + return ieee754.read(buf, offset, littleEndian, 23, 4) +} + +Buffer.prototype.readFloatLE = function (offset, noAssert) { + return _readFloat(this, offset, true, noAssert) +} + +Buffer.prototype.readFloatBE = function (offset, noAssert) { + return _readFloat(this, offset, false, noAssert) +} + +function _readDouble (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') + } + + return ieee754.read(buf, offset, littleEndian, 52, 8) +} + +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + return _readDouble(this, offset, true, noAssert) +} + +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + return _readDouble(this, offset, false, noAssert) +} + +Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'trying to write beyond buffer length') + verifuint(value, 0xff) + } + + if (offset >= this.length) return + + this[offset] = value +} + +function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffff) + } + + var len = buf.length + if (offset >= len) + return + + for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { + buf[offset + i] = + (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, false, noAssert) +} + +function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffffffff) + } + + var len = buf.length + if (offset >= len) + return + + for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { + buf[offset + i] = + (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, false, noAssert) +} + +Buffer.prototype.writeInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7f, -0x80) + } + + if (offset >= this.length) + return + + if (value >= 0) + this.writeUInt8(value, offset, noAssert) + else + this.writeUInt8(0xff + value + 1, offset, noAssert) +} + +function _writeInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fff, -0x8000) + } + + var len = buf.length + if (offset >= len) + return + + if (value >= 0) + _writeUInt16(buf, value, offset, littleEndian, noAssert) + else + _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) +} + +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, false, noAssert) +} + +function _writeInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fffffff, -0x80000000) + } + + var len = buf.length + if (offset >= len) + return + + if (value >= 0) + _writeUInt32(buf, value, offset, littleEndian, noAssert) + else + _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) +} + +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, false, noAssert) +} + +function _writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + + var len = buf.length + if (offset >= len) + return + + ieee754.write(buf, value, offset, littleEndian, 23, 4) +} + +Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, false, noAssert) +} + +function _writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 7 < buf.length, + 'Trying to write beyond buffer length') + verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + + var len = buf.length + if (offset >= len) + return + + ieee754.write(buf, value, offset, littleEndian, 52, 8) +} + +Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, false, noAssert) +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (typeof value === 'string') { + value = value.charCodeAt(0) + } + + assert(typeof value === 'number' && !isNaN(value), 'value is not a number') + assert(end >= start, 'end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + assert(start >= 0 && start < this.length, 'start out of bounds') + assert(end >= 0 && end <= this.length, 'end out of bounds') + + for (var i = start; i < end; i++) { + this[i] = value + } +} + +Buffer.prototype.inspect = function () { + var out = [] + var len = this.length + for (var i = 0; i < len; i++) { + out[i] = toHex(this[i]) + if (i === exports.INSPECT_MAX_BYTES) { + out[i + 1] = '...' + break + } + } + return '' +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer._useTypedArrays) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) + buf[i] = this[i] + return buf.buffer + } + } else { + throw new Error('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function (arr) { + arr._isBuffer = true + + // save reference to original Uint8Array get/set methods before overwriting + arr._get = arr.get + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +// slice(start, end) +function clamp (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index; // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} + +function coerce (length) { + // Coerce length to a number (possibly NaN), round up + // in case it's fractional (e.g. 123.456) then do a + // double negate to coerce a NaN to 0. Easy, right? + length = ~~Math.ceil(+length) + return length < 0 ? 0 : length +} + +function isArray (subject) { + return (Array.isArray || function (subject) { + return Object.prototype.toString.call(subject) === '[object Array]' + })(subject) +} + +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + var b = str.charCodeAt(i) + if (b <= 0x7F) + byteArray.push(str.charCodeAt(i)) + else { + var start = i + if (b >= 0xD800 && b <= 0xDFFF) i++ + var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') + for (var j = 0; j < h.length; j++) + byteArray.push(parseInt(h[j], 16)) + } + } + return byteArray +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(str) +} + +function blitBuffer (src, dst, offset, length) { + var pos + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) + break + dst[i + offset] = src[i] + } + return i +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +/* + * We have to make sure that the value is a valid integer. This means that it + * is non-negative. It has no fractional component and that it does not + * exceed the maximum allowed value. + */ +function verifuint (value, max) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value >= 0, 'specified a negative value for writing an unsigned value') + assert(value <= max, 'value is larger than maximum value for type') + assert(Math.floor(value) === value, 'value has a fractional component') +} + +function verifsint (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') + assert(Math.floor(value) === value, 'value has a fractional component') +} + +function verifIEEE754 (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') +} + +function assert (test, message) { + if (!test) throw new Error(message || 'Failed assertion') +} + +},{"base64-js":3,"ieee754":4}],3:[function(_dereq_,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],4:[function(_dereq_,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +},{}],5:[function(_dereq_,module,exports){ +var Buffer = _dereq_('buffer').Buffer; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} + +module.exports = { hash: hash }; + +},{"buffer":2}],6:[function(_dereq_,module,exports){ +var Buffer = _dereq_('buffer').Buffer +var sha = _dereq_('./sha') +var sha256 = _dereq_('./sha256') +var rng = _dereq_('./rng') +var md5 = _dereq_('./md5') + +var algorithms = { + sha1: sha, + sha256: sha256, + md5: md5 +} + +var blocksize = 64 +var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0) +function hmac(fn, key, data) { + if(!Buffer.isBuffer(key)) key = new Buffer(key) + if(!Buffer.isBuffer(data)) data = new Buffer(data) + + if(key.length > blocksize) { + key = fn(key) + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) + } + + var ipad = new Buffer(blocksize), opad = new Buffer(blocksize) + for(var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var hash = fn(Buffer.concat([ipad, data])) + return fn(Buffer.concat([opad, hash])) +} + +function hash(alg, key) { + alg = alg || 'sha1' + var fn = algorithms[alg] + var bufs = [] + var length = 0 + if(!fn) error('algorithm:', alg, 'is not yet supported') + return { + update: function (data) { + if(!Buffer.isBuffer(data)) data = new Buffer(data) + + bufs.push(data) + length += data.length + return this + }, + digest: function (enc) { + var buf = Buffer.concat(bufs) + var r = key ? hmac(fn, key, buf) : fn(buf) + bufs = null + return enc ? r.toString(enc) : r + } + } +} + +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) +} + +exports.createHash = function (alg) { return hash(alg) } +exports.createHmac = function (alg, key) { return hash(alg, key) } +exports.randomBytes = function(size, callback) { + if (callback && callback.call) { + try { + callback.call(this, undefined, new Buffer(rng(size))) + } catch (err) { callback(err) } + } else { + return new Buffer(rng(size)) + } +} + +function each(a, f) { + for(var i in a) + f(a[i], i) +} + +// the least I can do is make error messages for the rest of the node.js/crypto api. +each(['createCredentials' +, 'createCipher' +, 'createCipheriv' +, 'createDecipher' +, 'createDecipheriv' +, 'createSign' +, 'createVerify' +, 'createDiffieHellman' +, 'pbkdf2'], function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') + } +}) + +},{"./md5":7,"./rng":8,"./sha":9,"./sha256":10,"buffer":2}],7:[function(_dereq_,module,exports){ +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = _dereq_('./helpers'); + +/* + * Perform a simple self-test to see if the VM is working + */ +function md5_vm_test() +{ + return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; +} + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; + +},{"./helpers":5}],8:[function(_dereq_,module,exports){ +// Original code adapted from Robert Kieffer. +// details at https://github.com/broofa/node-uuid +(function() { + var _global = this; + + var mathRNG, whatwgRNG; + + // NOTE: Math.random() does not guarantee "cryptographic quality" + mathRNG = function(size) { + var bytes = new Array(size); + var r; + + for (var i = 0, r; i < size; i++) { + if ((i & 0x03) == 0) r = Math.random() * 0x100000000; + bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return bytes; + } + + if (_global.crypto && crypto.getRandomValues) { + whatwgRNG = function(size) { + var bytes = new Uint8Array(size); + crypto.getRandomValues(bytes); + return bytes; + } + } + + module.exports = whatwgRNG || mathRNG; + +}()) + +},{}],9:[function(_dereq_,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var helpers = _dereq_('./helpers'); + +/* + * Calculate the SHA-1 of an array of big-endian words, and a bit length + */ +function core_sha1(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << (24 - len % 32); + x[((len + 64 >> 9) << 4) + 15] = len; + + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; + + for(var j = 0; j < 80; j++) + { + if(j < 16) w[j] = x[i + j]; + else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); + var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), + safe_add(safe_add(e, w[j]), sha1_kt(j))); + e = d; + d = c; + c = rol(b, 30); + b = a; + a = t; + } + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + e = safe_add(e, olde); + } + return Array(a, b, c, d, e); + +} + +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) +{ + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} + +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function sha1(buf) { + return helpers.hash(buf, core_sha1, 20, true); +}; + +},{"./helpers":5}],10:[function(_dereq_,module,exports){ + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var helpers = _dereq_('./helpers'); + +var safe_add = function(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +}; + +var S = function(X, n) { + return (X >>> n) | (X << (32 - n)); +}; + +var R = function(X, n) { + return (X >>> n); +}; + +var Ch = function(x, y, z) { + return ((x & y) ^ ((~x) & z)); +}; + +var Maj = function(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +}; + +var Sigma0256 = function(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); +}; + +var Sigma1256 = function(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); +}; + +var Gamma0256 = function(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); +}; + +var Gamma1256 = function(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); +}; + +var core_sha256 = function(m, l) { + var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + for (var i = 0; i < m.length; i += 16) { + a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; + for (var j = 0; j < 64; j++) { + if (j < 16) { + W[j] = m[j + i]; + } else { + W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + } + T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); + T2 = safe_add(Sigma0256(a), Maj(a, b, c)); + h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); + } + HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); + HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); + } + return HASH; +}; + +module.exports = function sha256(buf) { + return helpers.hash(buf, core_sha256, 32, true); +}; + +},{"./helpers":5}]},{},[1]) +(1) +}); \ No newline at end of file diff --git a/dist/cryptico.browser.min.js b/dist/cryptico.browser.min.js new file mode 100644 index 0000000..b17ddb8 --- /dev/null +++ b/dist/cryptico.browser.min.js @@ -0,0 +1,4 @@ +/* cryptico-js v1.0.4 - - https://github.com/tracker1/cryptico-js */ + +!function(t){if("object"==typeof exports)module.exports=t();else if("function"==typeof define&&define.amd)define(t);else{var r;"undefined"!=typeof window?r=window:"undefined"!=typeof global?r=global:"undefined"!=typeof self&&(r=self),r.cryptico=t()}}(function(){return function t(r,n,e){function i(s,u){if(!n[s]){if(!r[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var h=n[s]={exports:{}};r[s][0].call(h.exports,function(t){var n=r[s][1][t];return i(n?n:t)},h,h.exports,t,r,n,e)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s>15;--o>=0;){var a=32767&this[t],h=this[t++]>>15,f=u*a+h*s;a=s*a+((32767&f)<<15)+n[e]+(1073741823&i),i=(a>>>30)+(f>>>15)+u*h+(i>>>30),n[e++]=1073741823&a}return i}function s(t){return Kn.charAt(t)}function u(t,r){var n=jn[t.charCodeAt(r)];return null==n?-1:n}function a(t){for(var r=this.t-1;r>=0;--r)t[r]=this[r];t.t=this.t,t.s=this.s}function h(t){this.t=1,this.s=0>t?-1:0,t>0?this[0]=t:-1>t?this[0]=t+DV:this.t=0}function f(t){var r=e();return r.fromInt(t),r}function c(t,r){var e;if(16==r)e=4;else if(8==r)e=3;else if(256==r)e=8;else if(2==r)e=1;else if(32==r)e=5;else{if(4!=r)return this.fromRadix(t,r),void 0;e=2}this.t=0,this.s=0;for(var i=t.length,o=!1,s=0;--i>=0;){var a=8==e?255&t[i]:u(t,i);0>a?"-"==t.charAt(i)&&(o=!0):(o=!1,0==s?this[this.t++]=a:s+e>this.DB?(this[this.t-1]|=(a&(1<>this.DB-s):this[this.t-1]|=a<=this.DB&&(s-=this.DB))}8==e&&0!=(128&t[0])&&(this.s=-1,s>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==t;)--this.t}function p(t){if(this.s<0)return"-"+this.negate().toString(t);var r;if(16==t)r=4;else if(8==t)r=3;else if(2==t)r=1;else if(32==t)r=5;else if(64==t)r=6;else{if(4!=t)return this.toRadix(t);r=2}var n,e=(1<0)for(a>a)>0&&(i=!0,o=s(n));u>=0;)r>a?(n=(this[u]&(1<>(a+=this.DB-r)):(n=this[u]>>(a-=r)&e,0>=a&&(a+=this.DB,--u)),n>0&&(i=!0),i&&(o+=s(n));return i?o:"0"}function d(){var t=e();return n.ZERO.subTo(this,t),t}function y(){return this.s<0?this.negate():this}function g(t){var r=this.s-t.s;if(0!=r)return r;var n=this.t;if(r=n-t.t,0!=r)return r;for(;--n>=0;)if(0!=(r=this[n]-t[n]))return r;return 0}function m(t){var r,n=1;return 0!=(r=t>>>16)&&(t=r,n+=16),0!=(r=t>>8)&&(t=r,n+=8),0!=(r=t>>4)&&(t=r,n+=4),0!=(r=t>>2)&&(t=r,n+=2),0!=(r=t>>1)&&(t=r,n+=1),n}function b(){return this.t<=0?0:this.DB*(this.t-1)+m(this[this.t-1]^this.s&this.DM)}function w(t,r){var n;for(n=this.t-1;n>=0;--n)r[n+t]=this[n];for(n=t-1;n>=0;--n)r[n]=0;r.t=this.t+t,r.s=this.s}function S(t,r){for(var n=t;n=0;--n)r[n+s+1]=this[n]>>i|u,u=(this[n]&o)<=0;--n)r[n]=0;r[s]=u,r.t=this.t+s+1,r.s=this.s,r.clamp()}function E(t,r){r.s=this.s;var n=Math.floor(t/this.DB);if(n>=this.t)return r.t=0,void 0;var e=t%this.DB,i=this.DB-e,o=(1<>e;for(var s=n+1;s>e;e>0&&(r[this.t-n-1]|=(this.s&o)<n;)e+=this[n]-t[n],r[n++]=e&this.DM,e>>=this.DB;if(t.t>=this.DB;e+=this.s}else{for(e+=this.s;n>=this.DB;e-=t.s}r.s=0>e?-1:0,-1>e?r[n++]=this.DV+e:e>0&&(r[n++]=e),r.t=n,r.clamp()}function B(t,r){var e=this.abs(),i=t.abs(),o=e.t;for(r.t=o+i.t;--o>=0;)r[o]=0;for(o=0;o=0;)t[n]=0;for(n=0;n=r.DV&&(t[n+r.t]-=r.DV,t[n+r.t+1]=1)}t.t>0&&(t[t.t-1]+=r.am(n,r[n],t,2*n,0,1)),t.s=0,t.clamp()}function x(t,r,i){var o=t.abs();if(!(o.t<=0)){var s=this.abs();if(s.t0?(o.lShiftTo(f,u),s.lShiftTo(f,i)):(o.copyTo(u),s.copyTo(i));var c=u.t,l=u[c-1];if(0!=l){var p=l*(1<1?u[c-2]>>this.F2:0),d=this.FV/p,v=(1<=0&&(i[i.t++]=1,i.subTo(w,i)),n.ONE.dlShiftTo(c,w),w.subTo(u,u);u.t=0;){var S=i[--g]==l?this.DM:Math.floor(i[g]*d+(i[g-1]+y)*v);if((i[g]+=u.am(0,S,i,b,0,c))0&&i.rShiftTo(f,i),0>a&&n.ZERO.subTo(i,i)}}}function D(t){var r=e();return this.abs().divRemTo(t,null,r),this.s<0&&r.compareTo(n.ZERO)>0&&t.subTo(r,r),r}function M(t){this.m=t}function L(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function C(t){return t}function R(t){t.divRemTo(this.m,null,t)}function q(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function U(t,r){t.squareTo(r),this.reduce(r)}function O(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var r=3&t;return r=r*(2-(15&t)*r)&15,r=r*(2-(255&t)*r)&255,r=r*(2-((65535&t)*r&65535))&65535,r=r*(2-t*r%this.DV)%this.DV,r>0?this.DV-r:-r}function N(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(r,r),r}function _(t){var r=e();return t.copyTo(r),this.reduce(r),r}function P(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var r=0;r>15)*this.mpl&this.um)<<15)&t.DM;for(n=r+this.m.t,t[n]+=this.m.am(0,e,t,r,0,this.m.t);t[n]>=t.DV;)t[n]-=t.DV,t[++n]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function F(t,r){t.squareTo(r),this.reduce(r)}function V(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function K(){return 0==(this.t>0?1&this[0]:this.s)}function j(t,r){if(t>4294967295||1>t)return n.ONE;var i=e(),o=e(),s=r.convert(this),u=m(t)-1;for(s.copyTo(i);--u>=0;)if(r.sqrTo(i,o),(t&1<0)r.mulTo(o,s,i);else{var a=i;i=o,o=a}return r.revert(i)}function Z(t,r){var n;return n=256>t||r.isEven()?new M(r):new N(r),this.exp(t,n)}function H(){var t=e();return this.copyTo(t),t}function W(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function J(){return 0==this.t?this.s:this[0]<<16>>16}function X(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function Y(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function G(t){if(null==t&&(t=10),0==this.signum()||2>t||t>36)return"0";var r=this.chunkSize(t),n=Math.pow(t,r),i=f(n),o=e(),s=e(),u="";for(this.divRemTo(i,o,s);o.signum()>0;)u=(n+s.intValue()).toString(t).substr(1)+u,o.divRemTo(i,o,s);return s.intValue().toString(t)+u}function Q(t,r){this.fromInt(0),null==r&&(r=10);for(var e=this.chunkSize(r),i=Math.pow(r,e),o=!1,s=0,a=0,h=0;hf?"-"==t.charAt(h)&&0==this.signum()&&(o=!0):(a=r*a+f,++s>=e&&(this.dMultiply(i),this.dAddOffset(a,0),s=0,a=0))}s>0&&(this.dMultiply(Math.pow(r,s)),this.dAddOffset(a,0)),o&&n.ZERO.subTo(this,this)}function $(t,r,e){if("number"==typeof r)if(2>t)this.fromInt(1);else for(this.fromNumber(t,e),this.testBit(t-1)||this.bitwiseTo(n.ONE.shiftLeft(t-1),ur,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(n.ONE.shiftLeft(t-1),this);else{var i=new Array,o=7&t;i.length=(t>>3)+1,r.nextBytes(i),o>0?i[0]&=(1<0)for(e>e)!=(this.s&this.DM)>>e&&(r[i++]=n|this.s<=0;)8>e?(n=(this[t]&(1<>(e+=this.DB-8)):(n=this[t]>>(e-=8)&255,0>=e&&(e+=this.DB,--t)),0!=(128&n)&&(n|=-256),0==i&&(128&this.s)!=(128&n)&&++i,(i>0||n!=this.s)&&(r[i++]=n);return r}function rr(t){return 0==this.compareTo(t)}function nr(t){return this.compareTo(t)<0?this:t}function er(t){return this.compareTo(t)>0?this:t}function ir(t,r,n){var e,i,o=Math.min(t.t,this.t);for(e=0;o>e;++e)n[e]=r(this[e],t[e]);if(t.tt?this.rShiftTo(-t,r):this.lShiftTo(t,r),r}function vr(t){var r=e();return 0>t?this.lShiftTo(-t,r):this.rShiftTo(t,r),r}function yr(t){if(0==t)return-1;var r=0;return 0==(65535&t)&&(t>>=16,r+=16),0==(255&t)&&(t>>=8,r+=8),0==(15&t)&&(t>>=4,r+=4),0==(3&t)&&(t>>=2,r+=2),0==(1&t)&&++r,r}function gr(){for(var t=0;t=this.t?0!=this.s:0!=(this[r]&1<n;)e+=this[n]+t[n],r[n++]=e&this.DM,e>>=this.DB;if(t.t>=this.DB;e+=this.s}else{for(e+=this.s;n>=this.DB;e+=t.s}r.s=0>e?-1:0,e>0?r[n++]=e:-1>e&&(r[n++]=this.DV+e),r.t=n,r.clamp()}function Ir(t){var r=e();return this.addTo(t,r),r}function xr(t){var r=e();return this.subTo(t,r),r}function Dr(t){var r=e();return this.multiplyTo(t,r),r}function Mr(){var t=e();return this.squareTo(t),t}function Lr(t){var r=e();return this.divRemTo(t,r,null),r}function Cr(t){var r=e();return this.divRemTo(t,null,r),r}function Rr(t){var r=e(),n=e();return this.divRemTo(t,r,n),new Array(r,n)}function qr(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function Ur(t,r){if(0!=t){for(;this.t<=r;)this[this.t++]=0;for(this[r]+=t;this[r]>=this.DV;)this[r]-=this.DV,++r>=this.t&&(this[this.t++]=0),++this[r]}}function Or(){}function Nr(t){return t}function kr(t,r,n){t.multiplyTo(r,n)}function _r(t,r){t.squareTo(r)}function Pr(t){return this.exp(t,new Or)}function Fr(t,r,n){var e=Math.min(this.t+t.t,r);for(n.s=0,n.t=e;e>0;)n[--e]=0;var i;for(i=n.t-this.t;i>e;++e)n[e+this.t]=this.am(0,t[e],n,e,0,this.t);for(i=Math.min(t.t,r);i>e;++e)this.am(0,t[e],n,e,0,r-e);n.clamp()}function Vr(t,r,n){--r;var e=n.t=this.t+t.t-r;for(n.s=0;--e>=0;)n[e]=0;for(e=Math.max(r-this.t,0);e2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var r=e();return t.copyTo(r),this.reduce(r),r}function Zr(t){return t}function Hr(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function Wr(t,r){t.squareTo(r),this.reduce(r)}function zr(t,r,n){t.multiplyTo(r,n),this.reduce(n)}function Jr(t,r){var n,i,o=t.bitLength(),s=f(1);if(0>=o)return s;n=18>o?1:48>o?3:144>o?4:768>o?5:6,i=8>o?new M(r):r.isEven()?new Kr(r):new N(r);var u=new Array,a=3,h=n-1,c=(1<1){var l=e();for(i.sqrTo(u[1],l);c>=a;)u[a]=e(),i.mulTo(l,u[a-2],u[a]),a+=2}var p,d,v=t.t-1,y=!0,g=e();for(o=m(t[v])-1;v>=0;){for(o>=h?p=t[v]>>o-h&c:(p=(t[v]&(1<0&&(p|=t[v-1]>>this.DB+o-h)),a=n;0==(1&p);)p>>=1,--a;if((o-=a)<0&&(o+=this.DB,--v),y)u[p].copyTo(s),y=!1;else{for(;a>1;)i.sqrTo(s,g),i.sqrTo(g,s),a-=2;a>0?i.sqrTo(s,g):(d=s,s=g,g=d),i.mulTo(g,u[p],s)}for(;v>=0&&0==(t[v]&1<o)return r;for(o>i&&(o=i),o>0&&(r.rShiftTo(o,r),n.rShiftTo(o,n));r.signum()>0;)(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),r.compareTo(n)>=0?(r.subTo(n,r),r.rShiftTo(1,r)):(n.subTo(r,n),n.rShiftTo(1,n));return o>0&&n.lShiftTo(o,n),n}function Yr(t){if(0>=t)return 0;var r=this.DV%t,n=this.s<0?t-1:0;if(this.t>0)if(0==r)n=this[0]%t;else for(var e=this.t-1;e>=0;--e)n=(r*n+this[e])%t;return n}function Gr(t){var r=t.isEven();if(this.isEven()&&r||0==t.signum())return n.ZERO;for(var e=t.clone(),i=this.clone(),o=f(1),s=f(0),u=f(0),a=f(1);0!=e.signum();){for(;e.isEven();)e.rShiftTo(1,e),r?(o.isEven()&&s.isEven()||(o.addTo(this,o),s.subTo(t,s)),o.rShiftTo(1,o)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;i.isEven();)i.rShiftTo(1,i),r?(u.isEven()&&a.isEven()||(u.addTo(this,u),a.subTo(t,a)),u.rShiftTo(1,u)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);e.compareTo(i)>=0?(e.subTo(i,e),r&&o.subTo(u,o),s.subTo(a,s)):(i.subTo(e,i),r&&u.subTo(o,u),a.subTo(s,a))}return 0!=i.compareTo(n.ONE)?n.ZERO:a.compareTo(t)>=0?a.subtract(t):a.signum()<0?(a.addTo(t,a),a.signum()<0?a.add(t):a):a}function Qr(t){var r,n=this.abs();if(1==n.t&&n[0]<=Zn[Zn.length-1]){for(r=0;re;)e*=Zn[i++];for(e=n.modInt(e);i>r;)if(e%Zn[r++]==0)return!1}return n.millerRabin(t)}function $r(t){var r=this.subtract(n.ONE),i=r.getLowestSetBit();if(0>=i)return!1;var o=r.shiftRight(i);t=t+1>>1,t>Zn.length&&(t=Zn.length);for(var s=e(),u=0;t>u;++u){s.fromInt(Zn[Math.floor(Math.random()*Zn.length)]);var a=s.modPow(o,this);if(0!=a.compareTo(n.ONE)&&0!=a.compareTo(r)){for(var h=1;h++r;++r)this.S[r]=r;for(n=0,r=0;256>r;++r)n=n+this.S[r]+t[r%t.length]&255,e=this.S[r],this.S[r]=this.S[n],this.S[n]=e;this.i=0,this.j=0}function on(){var t;return 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,this.S[t+this.S[this.i]&255]}function sn(){return new nn}function un(t){zn[Jn++]^=255&t,zn[Jn++]^=t>>8&255,zn[Jn++]^=t>>16&255,zn[Jn++]^=t>>24&255,Jn>=Xn&&(Jn-=Xn)}function an(){un((new Date).getTime())}function hn(){if(null==Wn){for(an(),Wn=sn(),Wn.init(zn),Jn=0;Jn=0&&r>0;){var o=t.charCodeAt(i--);128>o?e[--r]=o:o>127&&2048>o?(e[--r]=63&o|128,e[--r]=o>>6|192):(e[--r]=63&o|128,e[--r]=o>>6&63|128,e[--r]=o>>12|224)}e[--r]=0;for(var s=new cn,u=new Array;r>2;){for(u[0]=0;0==u[0];)s.nextBytes(u);e[--r]=u[0]}return e[--r]=2,e[--r]=0,new n(e)}function yn(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function gn(t,r){null!=t&&null!=r&&t.length>0&&r.length>0?(this.n=dn(t,16),this.e=parseInt(r,16)):alert("Invalid RSA public key")}function mn(t){return t.modPowInt(this.e,this.n)}function bn(t){var r=vn(t,this.n.bitLength()+7>>3);if(null==r)return null;var n=this.doPublic(r);if(null==n)return null;var e=n.toString(16);return 0==(1&e.length)?e:"0"+e}function wn(){return{coeff:this.coeff.toString(16),d:this.d.toString(16),dmp1:this.dmp1.toString(16),dmq1:this.dmq1.toString(16),e:this.e.toString(16),n:this.n.toString(16),p:this.p.toString(16),q:this.q.toString(16)}}function Sn(t){var r=JSON.parse(t),n=new yn;return n.setPrivateEx(r.n,r.e,r.d,r.p,r.q,r.dmp1,r.dmq1,r.coeff),n}function Tn(t,r){for(var n=t.toByteArray(),e=0;e=n.length)return null;for(var i="";++eo?i+=String.fromCharCode(o):o>191&&224>o?(i+=String.fromCharCode((31&o)<<6|63&n[e+1]),++e):(i+=String.fromCharCode((15&o)<<12|(63&n[e+1])<<6|63&n[e+2]),e+=2)}return i}function En(t,r,n){null!=t&&null!=r&&t.length>0&&r.length>0?(this.n=dn(t,16),this.e=parseInt(r,16),this.d=dn(n,16)):alert("Invalid RSA private key")}function An(t,r,n,e,i,o,s,u){if(!(null!=t&&null!=r&&t.length>0&&r.length>0))throw new Error("Invalid RSA private key");this.n=dn(t,16),this.e=parseInt(r,16),this.d=dn(n,16),this.p=dn(e,16),this.q=dn(i,16),this.dmp1=dn(o,16),this.dmq1=dn(s,16),this.coeff=dn(u,16)}function Bn(t,r){var e=new tn,i=t>>1;this.e=parseInt(r,16);for(var o=new n(r,16);;){for(;this.p=new n(t-i,1,e),0!=this.p.subtract(n.ONE).gcd(o).compareTo(n.ONE)||!this.p.isProbablePrime(10););for(;this.q=new n(i,1,e),0!=this.q.subtract(n.ONE).gcd(o).compareTo(n.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var s=this.p;this.p=this.q,this.q=s}var u=this.p.subtract(n.ONE),a=this.q.subtract(n.ONE),h=u.multiply(a);if(0==h.gcd(o).compareTo(n.ONE)){this.n=this.p.multiply(this.q),this.d=o.modInverse(h),this.dmp1=this.d.mod(u),this.dmq1=this.d.mod(a),this.coeff=this.q.modInverse(this.p);break}}}function In(t){if(null==this.p||null==this.q)return t.modPow(this.d,this.n);for(var r=t.mod(this.p).modPow(this.dmp1,this.p),n=t.mod(this.q).modPow(this.dmq1,this.q);r.compareTo(n)<0;)r=r.add(this.p);return r.subtract(n).multiply(this.coeff).mod(this.p).multiply(this.q).add(n)}function xn(t){var r=dn(t,16),n=this.doPrivate(r);return null==n?null:Tn(n,this.n.bitLength()+7>>3)}function Dn(t,r,n){for(var e=r/4,i=ne[n],o=i(t),s="0001",u="00"+re[n]+o,a="",h=e-s.length-u.length,f=0;h>f;f+=2)a+="ff";var c=s+a+u;return c}function Mn(t,r){var n=Dn(t,this.n.bitLength(),r),e=dn(n,16),i=this.doPrivate(e),o=i.toString(16);return o}function Ln(t){var r=Dn(t,this.n.bitLength(),"sha1"),n=dn(r,16),e=this.doPrivate(n),i=e.toString(16);return i}function Cn(t){var r=Dn(t,this.n.bitLength(),"sha256"),n=dn(r,16),e=this.doPrivate(n),i=e.toString(16);return i}function Rn(t,r,n){var e=new yn;e.setPublic(r,n);var i=e.doPublic(t);return i}function qn(t,r,n){var e=Rn(t,r,n),i=e.toString(16).replace(/^1f+00/,"");return i}function Un(t){for(var r in re){var n=re[r],e=n.length;if(t.substring(0,e)==n){var i=[r,t.substring(e)];return i}}return[]}function On(t,r,n,e){var i=qn(r,n,e),o=Un(i);if(0==o.length)return!1;var s=o[0],u=o[1],a=ne[s],h=a(t);return u==h}function Nn(t,r){var n=dn(t,16),e=On(r,n,this.n.toString(16),this.e.toString(16));return e}function kn(t,r){r=r.replace(/[ \n]+/g,"");var n=dn(r,16),e=this.doPublic(n),i=e.toString(16).replace(/^1f+00/,""),o=Un(i);if(0==o.length)return!1;var s=o[0],u=o[1],a=ne[s],h=a(t);return u==h}var _n;n.prototype.am=o,_n=30,n.prototype.DB=_n,n.prototype.DM=(1<<_n)-1,n.prototype.DV=1<<_n;var Pn=52;n.prototype.FV=Math.pow(2,Pn),n.prototype.F1=Pn-_n,n.prototype.F2=2*_n-Pn;var Fn,Vn,Kn="0123456789abcdefghijklmnopqrstuvwxyz",jn=new Array;for(Fn="0".charCodeAt(0),Vn=0;9>=Vn;++Vn)jn[Fn++]=Vn;for(Fn="a".charCodeAt(0),Vn=10;36>Vn;++Vn)jn[Fn++]=Vn;for(Fn="A".charCodeAt(0),Vn=10;36>Vn;++Vn)jn[Fn++]=Vn;M.prototype.convert=L,M.prototype.revert=C,M.prototype.reduce=R,M.prototype.mulTo=q,M.prototype.sqrTo=U,N.prototype.convert=k,N.prototype.revert=_,N.prototype.reduce=P,N.prototype.mulTo=V,N.prototype.sqrTo=F,n.prototype.copyTo=a,n.prototype.fromInt=h,n.prototype.fromString=c,n.prototype.clamp=l,n.prototype.dlShiftTo=w,n.prototype.drShiftTo=S,n.prototype.lShiftTo=T,n.prototype.rShiftTo=E,n.prototype.subTo=A,n.prototype.multiplyTo=B,n.prototype.squareTo=I,n.prototype.divRemTo=x,n.prototype.invDigit=O,n.prototype.isEven=K,n.prototype.exp=j,n.prototype.toString=p,n.prototype.negate=d,n.prototype.abs=y,n.prototype.compareTo=g,n.prototype.bitLength=b,n.prototype.mod=D,n.prototype.modPowInt=Z,n.ZERO=f(0),n.ONE=f(1),Or.prototype.convert=Nr,Or.prototype.revert=Nr,Or.prototype.mulTo=kr,Or.prototype.sqrTo=_r,Kr.prototype.convert=jr,Kr.prototype.revert=Zr,Kr.prototype.reduce=Hr,Kr.prototype.mulTo=zr,Kr.prototype.sqrTo=Wr;var Zn=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],Hn=(1<<26)/Zn[Zn.length-1];n.prototype.chunkSize=X,n.prototype.toRadix=G,n.prototype.fromRadix=Q,n.prototype.fromNumber=$,n.prototype.bitwiseTo=ir,n.prototype.changeBit=Sr,n.prototype.addTo=Br,n.prototype.dMultiply=qr,n.prototype.dAddOffset=Ur,n.prototype.multiplyLowerTo=Fr,n.prototype.multiplyUpperTo=Vr,n.prototype.modInt=Yr,n.prototype.millerRabin=$r,n.prototype.clone=H,n.prototype.intValue=W,n.prototype.byteValue=z,n.prototype.shortValue=J,n.prototype.signum=Y,n.prototype.toByteArray=tr,n.prototype.equals=rr,n.prototype.min=nr,n.prototype.max=er,n.prototype.and=sr,n.prototype.or=ar,n.prototype.xor=fr,n.prototype.andNot=lr,n.prototype.not=pr,n.prototype.shiftLeft=dr,n.prototype.shiftRight=vr,n.prototype.getLowestSetBit=gr,n.prototype.bitCount=br,n.prototype.testBit=wr,n.prototype.setBit=Tr,n.prototype.clearBit=Er,n.prototype.flipBit=Ar,n.prototype.add=Ir,n.prototype.subtract=xr,n.prototype.multiply=Dr,n.prototype.divide=Lr,n.prototype.remainder=Cr,n.prototype.divideAndRemainder=Rr,n.prototype.modPow=Jr,n.prototype.modInverse=Gr,n.prototype.pow=Pr,n.prototype.gcd=Xr,n.prototype.isProbablePrime=Qr,n.prototype.square=Mr,function(t,r,n,e,i,o,s){function u(t){var r,e,i=this,o=t.length,s=0,u=i.i=i.j=i.m=0;for(i.S=[],i.c=[],o||(t=[o++]);n>s;)i.S[s]=s++;for(s=0;n>s;s++)r=i.S[s],u=f(u+r+t[s%o]),e=i.S[u],i.S[s]=e,i.S[u]=r;i.g=function(t){var r=i.S,e=f(i.i+1),o=r[e],s=f(i.j+o),u=r[s];r[e]=u,r[s]=o;for(var a=r[f(o+u)];--t;)e=f(e+1),o=r[e],s=f(s+o),u=r[s],r[e]=u,r[s]=o,a=a*n+r[f(o+u)];return i.i=e,i.j=s,a},i.g(n)}function a(t,r,n,e,i){if(n=[],i=typeof t,r&&"object"==i)for(e in t)if(e.indexOf("S")<5)try{n.push(a(t[e],r-1))}catch(o){}return n.length?n:t+("string"!=i?"\x00":"")}function h(t,r,n,e){for(t+="",n=0,e=0;et;)t=(t+u)*n,r*=n,u=l.g(1);for(;t>=o;)t/=2,r/=2,u>>>=1;return(t+u)/r},f},s=r.pow(n,e),i=r.pow(2,i),o=2*i,h(r.random(),t)}([],Math,256,6,52),tn.prototype.nextBytes=rn,nn.prototype.init=en,nn.prototype.next=on;var Wn,zn,Jn,Xn=256;if(null==zn){zn=new Array,Jn=0;for(var Yn;Xn>Jn;)Yn=Math.floor(65536*Math.random()),zn[Jn++]=Yn>>>8,zn[Jn++]=255&Yn;Jn=0,an()}cn.prototype.nextBytes=fn;var Gn=t("crypto"),Qn={};Qn.hex=function(t){return ln(t)};var $n={};$n.hex=function(t){return pn(t)};var te=function(t){return Gn.createHash("md5").update(t,"utf8").digest("hex")};yn.prototype.doPublic=mn,yn.prototype.setPublic=gn,yn.prototype.encrypt=bn,yn.prototype.toJSON=wn,yn.parse=Sn,yn.prototype.doPrivate=In,yn.prototype.setPrivate=En,yn.prototype.setPrivateEx=An,yn.prototype.generate=Bn,yn.prototype.decrypt=xn;var re=[];re.sha1="3021300906052b0e03021a05000414",re.sha256="3031300d060960864801650304020105000420";var ne=[];ne.sha1=$n.hex,ne.sha256=Qn.hex,yn.prototype.signString=Mn,yn.prototype.signStringWithSHA1=Ln,yn.prototype.signStringWithSHA256=Cn,yn.prototype.verifyString=kn,yn.prototype.verifyHexSignatureForMessage=Nn;var ee=function(){var t={};return t.Sbox=new Array(99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22),t.ShiftRowTab=new Array(0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11),t.Init=function(){t.Sbox_Inv=new Array(256);for(var r=0;256>r;r++)t.Sbox_Inv[t.Sbox[r]]=r;t.ShiftRowTab_Inv=new Array(16);for(var r=0;16>r;r++)t.ShiftRowTab_Inv[t.ShiftRowTab[r]]=r;t.xtime=new Array(256);for(var r=0;128>r;r++)t.xtime[r]=r<<1,t.xtime[128+r]=r<<1^27},t.Done=function(){delete t.Sbox_Inv,delete t.ShiftRowTab_Inv,delete t.xtime},t.ExpandKey=function(r){var n,e=r.length,i=1;switch(e){case 16:n=176;break;case 24:n=208;break;case 32:n=240;break;default:alert("my.ExpandKey: Only key lengths of 16, 24 or 32 bytes allowed!")}for(var o=e;n>o;o+=4){var s=r.slice(o-4,o);o%e==0?(s=new Array(t.Sbox[s[1]]^i,t.Sbox[s[2]],t.Sbox[s[3]],t.Sbox[s[0]]),(i<<=1)>=256&&(i^=283)):e>24&&o%e==16&&(s=new Array(t.Sbox[s[0]],t.Sbox[s[1]],t.Sbox[s[2]],t.Sbox[s[3]]));for(var u=0;4>u;u++)r[o+u]=r[o+u-e]^s[u]}},t.Encrypt=function(r,n){var e=n.length;t.AddRoundKey(r,n.slice(0,16));for(var i=16;e-16>i;i+=16)t.SubBytes(r,t.Sbox),t.ShiftRows(r,t.ShiftRowTab),t.MixColumns(r),t.AddRoundKey(r,n.slice(i,i+16));t.SubBytes(r,t.Sbox),t.ShiftRows(r,t.ShiftRowTab),t.AddRoundKey(r,n.slice(i,e))},t.Decrypt=function(r,n){var e=n.length;t.AddRoundKey(r,n.slice(e-16,e)),t.ShiftRows(r,t.ShiftRowTab_Inv),t.SubBytes(r,t.Sbox_Inv);for(var i=e-32;i>=16;i-=16)t.AddRoundKey(r,n.slice(i,i+16)),t.MixColumns_Inv(r),t.ShiftRows(r,t.ShiftRowTab_Inv),t.SubBytes(r,t.Sbox_Inv);t.AddRoundKey(r,n.slice(0,16))},t.SubBytes=function(t,r){for(var n=0;16>n;n++)t[n]=r[t[n]]},t.AddRoundKey=function(t,r){for(var n=0;16>n;n++)t[n]^=r[n]},t.ShiftRows=function(t,r){for(var n=(new Array).concat(t),e=0;16>e;e++)t[e]=n[r[e]]},t.MixColumns=function(r){for(var n=0;16>n;n+=4){var e=r[n+0],i=r[n+1],o=r[n+2],s=r[n+3],u=e^i^o^s;r[n+0]^=u^t.xtime[e^i],r[n+1]^=u^t.xtime[i^o],r[n+2]^=u^t.xtime[o^s],r[n+3]^=u^t.xtime[s^e]}},t.MixColumns_Inv=function(r){for(var n=0;16>n;n+=4){var e=r[n+0],i=r[n+1],o=r[n+2],s=r[n+3],u=e^i^o^s,a=t.xtime[u],h=t.xtime[t.xtime[a^e^o]]^u,f=t.xtime[t.xtime[a^i^s]]^u;r[n+0]^=h^t.xtime[e^i],r[n+1]^=f^t.xtime[i^o],r[n+2]^=h^t.xtime[o^s],r[n+3]^=f^t.xtime[s^e]}},t}(),ie=function(){var t={};ee.Init();var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";return t.b256to64=function(t){var n,e,i,o="",s=0,u=0,a=t.length;for(i=0;a>i;i++)e=t.charCodeAt(i),0==u?(o+=r.charAt(e>>2&63),n=(3&e)<<4):1==u?(o+=r.charAt(n|e>>4&15),n=(15&e)<<2):2==u&&(o+=r.charAt(n|e>>6&3),s+=1,o+=r.charAt(63&e)),s+=1,u+=1,3==u&&(u=0);return u>0&&(o+=r.charAt(n),s+=1,o+="=",s+=1),1==u&&(o+="="),o},t.b64to256=function(t){var n,e,i="",o=0,s=0,u=t.length;for(e=0;u>e;e++)n=r.indexOf(t.charAt(e)),n>=0&&(o&&(i+=String.fromCharCode(s|n>>6-o&255)),o=o+2&7,s=n<>6)+r.charAt(63&e);for(n+1==t.length?(e=parseInt(t.substring(n,n+1),16),i+=r.charAt(e<<2)):n+2==t.length&&(e=parseInt(t.substring(n,n+2),16),i+=r.charAt(e>>2)+r.charAt((3&e)<<4));(3&i.length)>0;)i+="=";return i},t.b64to16=function(t){var n,e,i="",o=0;for(n=0;nv||(0==o?(i+=s(v>>2),e=3&v,o=1):1==o?(i+=s(e<<2|v>>4),e=15&v,o=2):2==o?(i+=s(e),i+=s(v>>2),e=3&v,o=3):(i+=s(e<<2|v>>4),i+=s(15&v),o=0));return 1==o&&(i+=s(e<<2)),i},t.string2bytes=function(t){for(var r=new Array,n=0;ne;e++)n[e]=t[e]^r[e];return n},t.blockIV=function(){var t=new cn,r=new Array(16);return t.nextBytes(r),r},t.pad16=function(t){var r=t.slice(0),n=(16-t.length%16)%16;for(i=t.length;iu;u++)s[u]=e.isBuffer(t)?t.readUInt8(u):t[u];else if("string"===i)s.write(t,0,r);else if("number"===i&&!e._useTypedArrays&&!n)for(u=0;o>u;u++)s[u]=0;return s}function i(t,r,n,i){n=Number(n)||0;var o=t.length-n;i?(i=Number(i),i>o&&(i=o)):i=o;var s=r.length;j(s%2===0,"Invalid hex string"),i>s/2&&(i=s/2);for(var u=0;i>u;u++){var a=parseInt(r.substr(2*u,2),16);j(!isNaN(a),"Invalid hex string"),t[n+u]=a}return e._charsWritten=2*u,u}function o(t,r,n,i){var o=e._charsWritten=_(U(r),t,n,i);return o}function s(t,r,n,i){var o=e._charsWritten=_(O(r),t,n,i);return o}function u(t,r,n,e){return s(t,r,n,e)}function a(t,r,n,i){var o=e._charsWritten=_(k(r),t,n,i);return o}function h(t,r,n,i){var o=e._charsWritten=_(N(r),t,n,i);return o}function f(t,r,n){return 0===r&&n===t.length?Z.fromByteArray(t):Z.fromByteArray(t.slice(r,n))}function c(t,r,n){var e="",i="";n=Math.min(t.length,n);for(var o=r;n>o;o++)t[o]<=127?(e+=P(i)+String.fromCharCode(t[o]),i=""):i+="%"+t[o].toString(16);return e+P(i)}function l(t,r,n){var e="";n=Math.min(t.length,n);for(var i=r;n>i;i++)e+=String.fromCharCode(t[i]);return e}function p(t,r,n){return l(t,r,n)}function d(t,r,n){var e=t.length;(!r||0>r)&&(r=0),(!n||0>n||n>e)&&(n=e);for(var i="",o=r;n>o;o++)i+=q(t[o]);return i}function v(t,r,n){for(var e=t.slice(r,n),i="",o=0;o=i)){var o;return n?(o=t[r],i>r+1&&(o|=t[r+1]<<8)):(o=t[r]<<8,i>r+1&&(o|=t[r+1])),o}}function g(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+3=i)){var o;return n?(i>r+2&&(o=t[r+2]<<16),i>r+1&&(o|=t[r+1]<<8),o|=t[r],i>r+3&&(o+=t[r+3]<<24>>>0)):(i>r+1&&(o=t[r+1]<<16),i>r+2&&(o|=t[r+2]<<8),i>r+3&&(o|=t[r+3]),o+=t[r]<<24>>>0),o}}function m(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+1=i)){var o=y(t,r,n,!0),s=32768&o;return s?-1*(65535-o+1):o}}function b(t,r,n,e){e||(j("boolean"==typeof n,"missing or invalid endian"),j(void 0!==r&&null!==r,"missing offset"),j(r+3=i)){var o=g(t,r,n,!0),s=2147483648&o;return s?-1*(4294967295-o+1):o}}function w(t,r,n,e){return e||(j("boolean"==typeof n,"missing or invalid endian"),j(r+3=o))for(var s=0,u=Math.min(o-n,2);u>s;s++)t[n+s]=(r&255<<8*(e?s:1-s))>>>8*(e?s:1-s)}function E(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o))for(var s=0,u=Math.min(o-n,4);u>s;s++)t[n+s]=r>>>8*(e?s:3-s)&255}function A(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+1=o||(r>=0?T(t,r,n,e,i):T(t,65535+r+1,n,e,i))}function B(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||(r>=0?E(t,r,n,e,i):E(t,4294967295+r+1,n,e,i))}function I(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+3=o||H.write(t,r,n,e,23,4)}function x(t,r,n,e,i){i||(j(void 0!==r&&null!==r,"missing value"),j("boolean"==typeof e,"missing or invalid endian"),j(void 0!==n&&null!==n,"missing offset"),j(n+7=o||H.write(t,r,n,e,52,8)}function D(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function M(t,r,n){return"number"!=typeof t?n:(t=~~t,t>=r?r:t>=0?t:(t+=r,t>=0?t:0))}function L(t){return t=~~Math.ceil(+t),0>t?0:t}function C(t){return(Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)})(t)}function R(t){return C(t)||e.isBuffer(t)||t&&"object"==typeof t&&"number"==typeof t.length}function q(t){return 16>t?"0"+t.toString(16):t.toString(16)}function U(t){for(var r=[],n=0;n=e)r.push(t.charCodeAt(n));else{var i=n;e>=55296&&57343>=e&&n++;for(var o=encodeURIComponent(t.slice(i,n+1)).substr(1).split("%"),s=0;s>8,e=r%256,i.push(e),i.push(n);return i}function k(t){return Z.toByteArray(t)}function _(t,r,n,e){for(var i=0;e>i&&!(i+n>=r.length||i>=t.length);i++)r[i+n]=t[i];return i}function P(t){try{return decodeURIComponent(t)}catch(r){return String.fromCharCode(65533)}}function F(t,r){j("number"==typeof t,"cannot write a non-number as a number"),j(t>=0,"specified a negative value for writing an unsigned value"),j(r>=t,"value is larger than maximum value for type"),j(Math.floor(t)===t,"value has a fractional component")}function V(t,r,n){j("number"==typeof t,"cannot write a non-number as a number"),j(r>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value"),j(Math.floor(t)===t,"value has a fractional component")}function K(t,r,n){j("number"==typeof t,"cannot write a non-number as a number"),j(r>=t,"value larger than maximum allowed value"),j(t>=n,"value smaller than minimum allowed value")}function j(t,r){if(!t)throw new Error(r||"Failed assertion")}var Z=t("base64-js"),H=t("ieee754");n.Buffer=e,n.SlowBuffer=e,n.INSPECT_MAX_BYTES=50,e.poolSize=8192,e._useTypedArrays=function(){try{var t=new ArrayBuffer(0),r=new Uint8Array(t);return r.foo=function(){return 42},42===r.foo()&&"function"==typeof r.subarray}catch(n){return!1}}(),e.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},e.isBuffer=function(t){return!(null===t||void 0===t||!t._isBuffer)},e.byteLength=function(t,r){var n;switch(t+="",r||"utf8"){case"hex":n=t.length/2;break;case"utf8":case"utf-8":n=U(t).length;break;case"ascii":case"binary":case"raw":n=t.length;break;case"base64":n=k(t).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*t.length;break;default:throw new Error("Unknown encoding")}return n},e.concat=function(t,r){if(j(C(t),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===t.length)return new e(0);if(1===t.length)return t[0];var n;if("number"!=typeof r)for(r=0,n=0;nc&&(n=c)):n=c,e=String(e||"utf8").toLowerCase();var l;switch(e){case"hex":l=i(this,t,r,n);break;case"utf8":case"utf-8":l=o(this,t,r,n);break;case"ascii":l=s(this,t,r,n);break;case"binary":l=u(this,t,r,n);break;case"base64":l=a(this,t,r,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":l=h(this,t,r,n);break;default:throw new Error("Unknown encoding")}return l},e.prototype.toString=function(t,r,n){var e=this;if(t=String(t||"utf8").toLowerCase(),r=Number(r)||0,n=void 0!==n?Number(n):n=e.length,n===r)return"";var i;switch(t){case"hex":i=d(e,r,n);break;case"utf8":case"utf-8":i=c(e,r,n);break;case"ascii":i=l(e,r,n);break;case"binary":i=p(e,r,n);break;case"base64":i=f(e,r,n);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=v(e,r,n);break;default:throw new Error("Unknown encoding")}return i},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},e.prototype.copy=function(t,r,n,i){var o=this;if(n||(n=0),i||0===i||(i=this.length),r||(r=0),i!==n&&0!==t.length&&0!==o.length){j(i>=n,"sourceEnd < sourceStart"),j(r>=0&&r=0&&n=0&&i<=o.length,"sourceEnd out of bounds"),i>this.length&&(i=this.length),t.length-rs||!e._useTypedArrays)for(var u=0;s>u;u++)t[u+r]=this[u+n];else t._set(this.subarray(n,n+s),r)}},e.prototype.slice=function(t,r){var n=this.length;if(t=M(t,n,0),r=M(r,n,n),e._useTypedArrays)return e._augment(this.subarray(t,r));for(var i=r-t,o=new e(i,void 0,!0),s=0;i>s;s++)o[s]=this[s+t];return o},e.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},e.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},e.prototype.readUInt8=function(t,r){return r||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length?void 0:this[t]},e.prototype.readUInt16LE=function(t,r){return y(this,t,!0,r)},e.prototype.readUInt16BE=function(t,r){return y(this,t,!1,r)},e.prototype.readUInt32LE=function(t,r){return g(this,t,!0,r)},e.prototype.readUInt32BE=function(t,r){return g(this,t,!1,r)},e.prototype.readInt8=function(t,r){if(r||(j(void 0!==t&&null!==t,"missing offset"),j(t=this.length)){var n=128&this[t];return n?-1*(255-this[t]+1):this[t]}},e.prototype.readInt16LE=function(t,r){return m(this,t,!0,r)},e.prototype.readInt16BE=function(t,r){return m(this,t,!1,r)},e.prototype.readInt32LE=function(t,r){return b(this,t,!0,r)},e.prototype.readInt32BE=function(t,r){return b(this,t,!1,r)},e.prototype.readFloatLE=function(t,r){return w(this,t,!0,r)},e.prototype.readFloatBE=function(t,r){return w(this,t,!1,r)},e.prototype.readDoubleLE=function(t,r){return S(this,t,!0,r)},e.prototype.readDoubleBE=function(t,r){return S(this,t,!1,r)},e.prototype.writeUInt8=function(t,r,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==r&&null!==r,"missing offset"),j(r=this.length||(this[r]=t)},e.prototype.writeUInt16LE=function(t,r,n){T(this,t,r,!0,n)},e.prototype.writeUInt16BE=function(t,r,n){T(this,t,r,!1,n)},e.prototype.writeUInt32LE=function(t,r,n){E(this,t,r,!0,n)},e.prototype.writeUInt32BE=function(t,r,n){E(this,t,r,!1,n)},e.prototype.writeInt8=function(t,r,n){n||(j(void 0!==t&&null!==t,"missing value"),j(void 0!==r&&null!==r,"missing offset"),j(r=this.length||(t>=0?this.writeUInt8(t,r,n):this.writeUInt8(255+t+1,r,n))},e.prototype.writeInt16LE=function(t,r,n){A(this,t,r,!0,n)},e.prototype.writeInt16BE=function(t,r,n){A(this,t,r,!1,n)},e.prototype.writeInt32LE=function(t,r,n){B(this,t,r,!0,n)},e.prototype.writeInt32BE=function(t,r,n){B(this,t,r,!1,n)},e.prototype.writeFloatLE=function(t,r,n){I(this,t,r,!0,n)},e.prototype.writeFloatBE=function(t,r,n){I(this,t,r,!1,n)},e.prototype.writeDoubleLE=function(t,r,n){x(this,t,r,!0,n)},e.prototype.writeDoubleBE=function(t,r,n){x(this,t,r,!1,n)},e.prototype.fill=function(t,r,n){if(t||(t=0),r||(r=0),n||(n=this.length),"string"==typeof t&&(t=t.charCodeAt(0)),j("number"==typeof t&&!isNaN(t),"value is not a number"),j(n>=r,"end < start"),n!==r&&0!==this.length){j(r>=0&&r=0&&n<=this.length,"end out of bounds");for(var e=r;n>e;e++)this[e]=t}},e.prototype.inspect=function(){for(var t=[],r=this.length,e=0;r>e;e++)if(t[e]=q(this[e]),e===n.INSPECT_MAX_BYTES){t[e+1]="...";break}return""},e.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(e._useTypedArrays)return new e(this).buffer;for(var t=new Uint8Array(this.length),r=0,n=t.length;n>r;r+=1)t[r]=this[r];return t.buffer}throw new Error("Buffer.toArrayBuffer not supported in this browser")};var W=e.prototype;e._augment=function(t){return t._isBuffer=!0,t._get=t.get,t._set=t.set,t.get=W.get,t.set=W.set,t.write=W.write,t.toString=W.toString,t.toLocaleString=W.toString,t.toJSON=W.toJSON,t.copy=W.copy,t.slice=W.slice,t.readUInt8=W.readUInt8,t.readUInt16LE=W.readUInt16LE,t.readUInt16BE=W.readUInt16BE,t.readUInt32LE=W.readUInt32LE,t.readUInt32BE=W.readUInt32BE,t.readInt8=W.readInt8,t.readInt16LE=W.readInt16LE,t.readInt16BE=W.readInt16BE,t.readInt32LE=W.readInt32LE,t.readInt32BE=W.readInt32BE,t.readFloatLE=W.readFloatLE,t.readFloatBE=W.readFloatBE,t.readDoubleLE=W.readDoubleLE,t.readDoubleBE=W.readDoubleBE,t.writeUInt8=W.writeUInt8,t.writeUInt16LE=W.writeUInt16LE,t.writeUInt16BE=W.writeUInt16BE,t.writeUInt32LE=W.writeUInt32LE,t.writeUInt32BE=W.writeUInt32BE,t.writeInt8=W.writeInt8,t.writeInt16LE=W.writeInt16LE,t.writeInt16BE=W.writeInt16BE,t.writeInt32LE=W.writeInt32LE,t.writeInt32BE=W.writeInt32BE,t.writeFloatLE=W.writeFloatLE,t.writeFloatBE=W.writeFloatBE,t.writeDoubleLE=W.writeDoubleLE,t.writeDoubleBE=W.writeDoubleBE,t.fill=W.fill,t.inspect=W.inspect,t.toArrayBuffer=W.toArrayBuffer,t}},{"base64-js":3,ieee754:4}],3:[function(t,r,n){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(t){"use strict";function r(t){var r=t.charCodeAt(0);return r===s||r===c?62:r===u||r===l?63:a>r?-1:a+10>r?r-a+26+26:f+26>r?r-f:h+26>r?r-h+26:void 0}function n(t){function n(t){h[c++]=t}var e,i,s,u,a,h;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-a),s=a>0?t.length-4:t.length;var c=0;for(e=0,i=0;s>e;e+=4,i+=3)u=r(t.charAt(e))<<18|r(t.charAt(e+1))<<12|r(t.charAt(e+2))<<6|r(t.charAt(e+3)),n((16711680&u)>>16),n((65280&u)>>8),n(255&u);return 2===a?(u=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&u)):1===a&&(u=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(u>>8&255),n(255&u)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,u=t.length%3,a="";for(i=0,s=t.length-u;s>i;i+=3)o=(t[i]<<16)+(t[i+1]<<8)+t[i+2],a+=n(o);switch(u){case 1:o=t[t.length-1],a+=r(o>>2),a+=r(o<<4&63),a+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],a+=r(o>>10),a+=r(o>>4&63),a+=r(o<<2&63),a+="="}return a}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),u="/".charCodeAt(0),a="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}("undefined"==typeof n?this.base64js={}:n)},{}],4:[function(t,r,n){n.read=function(t,r,n,e,i){var o,s,u=8*i-e-1,a=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?0/0:1/0*(p?-1:1);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},n.write=function(t,r,n,e,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,d=e?1:-1,v=0>r||0===r&&0>1/r?1:0;for(r=Math.abs(r),isNaN(r)||1/0===r?(u=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-s))<1&&(s--,a*=2),r+=s+c>=1?l/a:l*Math.pow(2,1-c),r*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(r*a-1)*Math.pow(2,i),s+=c):(u=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=d,s/=256,h-=8);t[n+p-d]|=128*v}},{}],5:[function(t,r){function n(t,r){if(t.length%s!==0){var n=t.length+(s-t.length%s);t=o.concat([t,u],n)}for(var e=[],i=r?t.readInt32BE:t.readInt32LE,a=0;ap?r=t(r):r.lengtho;o++)e[o]=54^r[o],i[o]=92^r[o];var s=t(u.concat([e,n]));return t(u.concat([i,s]))}function i(t,r){t=t||"sha1";var n=l[t],i=[],s=0;return n||o("algorithm:",t,"is not yet supported"),{update:function(t){return u.isBuffer(t)||(t=new u(t)),i.push(t),s+=t.length,this},digest:function(t){var o=u.concat(i),s=r?e(n,r,o):n(o);return i=null,t?s.toString(t):s}}}function o(){var t=[].slice.call(arguments).join(" ");throw new Error([t,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}function s(t,r){for(var n in t)r(t[n],n)}var u=t("buffer").Buffer,a=t("./sha"),h=t("./sha256"),f=t("./rng"),c=t("./md5"),l={sha1:a,sha256:h,md5:c},p=64,d=new u(p);d.fill(0),n.createHash=function(t){return i(t)},n.createHmac=function(t,r){return i(t,r)},n.randomBytes=function(t,r){if(!r||!r.call)return new u(f(t));try{r.call(this,void 0,new u(f(t)))}catch(n){r(n)}},s(["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],function(t){n[t]=function(){o("sorry,",t,"is not implemented yet")}})},{"./md5":7,"./rng":8,"./sha":9,"./sha256":10,buffer:2}],7:[function(t,r){function n(t,r){t[r>>5]|=128<>>9<<4)+14]=r;for(var n=1732584193,e=-271733879,h=-1732584194,f=271733878,c=0;c>16)+(r>>16)+(n>>16);return e<<16|65535&n}function h(t,r){return t<>>32-r}var f=t("./helpers");r.exports=function(t){return f.hash(t,n,16)}},{"./helpers":5}],8:[function(t,r){!function(){var t,n,e=this;t=function(t){for(var r,r,n=new Array(t),e=0;t>e;e++)0==(3&e)&&(r=4294967296*Math.random()),n[e]=r>>>((3&e)<<3)&255;return n},e.crypto&&crypto.getRandomValues&&(n=function(t){var r=new Uint8Array(t);return crypto.getRandomValues(r),r}),r.exports=n||t}()},{}],9:[function(t,r){function n(t,r){t[r>>5]|=128<<24-r%32,t[(r+64>>9<<4)+15]=r;for(var n=Array(80),u=1732584193,a=-271733879,h=-1732584194,f=271733878,c=-1009589776,l=0;lm;m++){n[m]=16>m?t[l+m]:s(n[m-3]^n[m-8]^n[m-14]^n[m-16],1);var b=o(o(s(u,5),e(m,a,h,f)),o(o(c,n[m]),i(m)));c=f,f=h,h=s(a,30),a=u,u=b}u=o(u,p),a=o(a,d),h=o(h,v),f=o(f,y),c=o(c,g)}return Array(u,a,h,f,c)}function e(t,r,n,e){return 20>t?r&n|~r&e:40>t?r^n^e:60>t?r&n|r&e|n&e:r^n^e}function i(t){return 20>t?1518500249:40>t?1859775393:60>t?-1894007588:-899497514}function o(t,r){var n=(65535&t)+(65535&r),e=(t>>16)+(r>>16)+(n>>16);return e<<16|65535&n}function s(t,r){return t<>>32-r}var u=t("./helpers");r.exports=function(t){return u.hash(t,n,20,!0)}},{"./helpers":5}],10:[function(t,r){var n=t("./helpers"),e=function(t,r){var n=(65535&t)+(65535&r),e=(t>>16)+(r>>16)+(n>>16);return e<<16|65535&n},i=function(t,r){return t>>>r|t<<32-r},o=function(t,r){return t>>>r},s=function(t,r,n){return t&r^~t&n},u=function(t,r,n){return t&r^t&n^r&n},a=function(t){return i(t,2)^i(t,13)^i(t,22)},h=function(t){return i(t,6)^i(t,11)^i(t,25)},f=function(t){return i(t,7)^i(t,18)^o(t,3)},c=function(t){return i(t,17)^i(t,19)^o(t,10)},l=function(t,r){var n,i,o,l,p,d,v,y,g,m,b,w,S=new Array(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),T=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),E=new Array(64);t[r>>5]|=128<<24-r%32,t[(r+64>>9<<4)+15]=r;for(var g=0;gm;m++)E[m]=16>m?t[m+g]:e(e(e(c(E[m-2]),E[m-7]),f(E[m-15])),E[m-16]),b=e(e(e(e(y,h(p)),s(p,d,v)),S[m]),E[m]),w=e(a(n),u(n,i,o)),y=v,v=d,d=p,p=e(l,b),l=o,o=i,i=n,n=e(b,w);T[0]=e(n,T[0]),T[1]=e(i,T[1]),T[2]=e(o,T[2]),T[3]=e(l,T[3]),T[4]=e(p,T[4]),T[5]=e(d,T[5]),T[6]=e(v,T[6]),T[7]=e(y,T[7])}return T};r.exports=function(t){return n.hash(t,l,32,!0)}},{"./helpers":5}]},{},[1])(1)}); \ No newline at end of file diff --git a/dist/test.html b/dist/test.html new file mode 100644 index 0000000..8086632 --- /dev/null +++ b/dist/test.html @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..fc448e6 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,59 @@ +'use strict'; + +var pkg = require('./package.json') + ,gulp = require('gulp') + ,concat = require('gulp-concat') + ,header = require('gulp-header') + ,uglify = require('gulp-uglify') + ,rename = require('gulp-rename') + ,browserify = require('gulp-browserify') + ; + + +gulp.task('lib',function(){ + gulp + .src([ + 'src/jsbn.js' + ,'src/random.js' + ,'src/hash.js' + ,'src/rsa.js' + ,'src/aes.js' + ,'src/api.js' + ,'src/exports.js' + ]) + .pipe(concat('cryptico.js')) + .pipe(header('/* cryptico-js v${pkg.version} - ${file.name} - https://github.com/tracker1/cryptico-js */\n\n', {pkg:pkg})) + .pipe(gulp.dest('lib/')) + ; +}); + + +gulp.task('browser',['lib'],function(){ + return gulp + .src('lib/cryptico.js') + .pipe(browserify({standalone:'cryptico'})) + .pipe(header('/* cryptico-js v${pkg.version} - ${file.name} - https://github.com/tracker1/cryptico-js */\n\n', {pkg:pkg})) + .pipe(rename('cryptico.browser.js')) + .pipe(gulp.dest('dist/')) + .pipe(uglify()) + .pipe(rename('cryptico.browser.min.js')) + .pipe(header('/* cryptico-js v${pkg.version} - ${file.name} - https://github.com/tracker1/cryptico-js */\n\n', {pkg:pkg})) + .pipe(gulp.dest('dist/')) +}); + + +gulp.task('amd',['lib'],function(){ + return gulp + .src('lib/cryptico.js') + .pipe(browserify()) + .pipe(header('/* cryptico-js v${pkg.version} - ${file.name} - https://github.com/tracker1/cryptico-js */\n\n', {pkg:pkg})) + .pipe(rename('cryptico.amd.js')) + .pipe(gulp.dest('dist/')) + .pipe(uglify()) + .pipe(rename('cryptico.amd.min.js')) + .pipe(header('/* cryptico-js v${pkg.version} - ${file.name} - https://github.com/tracker1/cryptico-js */\n\n', {pkg:pkg})) + .pipe(gulp.dest('dist/')) +}); + + +gulp.task('default',['lib','browser','amd']); diff --git a/lib/cryptico.js b/lib/cryptico.js index 930cc16..b158cfb 100644 --- a/lib/cryptico.js +++ b/lib/cryptico.js @@ -1,3 +1,5 @@ +/* cryptico-js v1.0.4 - - https://github.com/tracker1/cryptico-js */ + // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. @@ -1515,7 +1517,8 @@ BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension -BigInteger.prototype.square = bnSquare;// seedrandom.js version 2.0. +BigInteger.prototype.square = bnSquare; +// seedrandom.js version 2.0. // Author: David Bau 4/2/2011 // // Defines a method Math.seedrandom() that, when called, substitutes @@ -1949,7 +1952,8 @@ function rng_get_bytes(ba) { function SecureRandom() {} -SecureRandom.prototype.nextBytes = rng_get_bytes;/** +SecureRandom.prototype.nextBytes = rng_get_bytes; +/** * * Secure Hash Algorithm (SHA256) * http://www.webtoolkit.info/ @@ -1996,7 +2000,8 @@ sha1.hex = function(s) var MD5 = function (string) { return crypto.createHash('md5').update(string, 'utf8').digest('hex'); -}// Depends on jsbn.js and rng.js +} +// Depends on jsbn.js and rng.js // Version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object @@ -2129,7 +2134,7 @@ function RSAToJSON() e: this.e.toString(16), n: this.n.toString(16), p: this.p.toString(16), - q: this.q.toString(16), + q: this.q.toString(16) } } @@ -2216,7 +2221,7 @@ function RSASetPrivateEx(N, E, D, P, Q, DP, DQ, C) this.dmq1 = parseBigInt(DQ, 16); this.coeff = parseBigInt(C, 16); } - else alert("Invalid RSA private key"); + else throw new Error("Invalid RSA private key"); } // Generate a new random private key B bits long, using public expt E @@ -2347,7 +2352,7 @@ function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) { sMid += "ff"; } - sPaddedMessageHex = sHead + sMid + sTail; + var sPaddedMessageHex = sHead + sMid + sTail; return sPaddedMessageHex; } @@ -2478,6 +2483,7 @@ RSAKey.prototype.verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMe + /* @@ -2636,7 +2642,8 @@ var aes = (function () { return my; -}());var cryptico = module.exports = (function() { +}()); +var cryptico = (function() { var my = {}; @@ -2990,4 +2997,10 @@ var aes = (function () { }()); -module.exports.RSAKey = RSAKey; \ No newline at end of file + +module.exports = cryptico; +module.exports.RSAKey = RSAKey; + +if (typeof window !== 'undefined') { + window.cryptico = module.exports; +} diff --git a/package.json b/package.json index b7550a9..c02e92e 100644 --- a/package.json +++ b/package.json @@ -1,25 +1,53 @@ { - "name": "cryptico", - "version": "1.0.2", - "author": "Rye Terrell ", - "contributors": [ - { - "name": "Roberto Aguilar", - "email": "roberto@baremetal.io" - }, - { - "name": "PhpMyCoder" - } - ], - "main": "./lib/cryptico.js", - "repository": { - "type": "git", - "url": "https://github.com/phpmycoder/cryptico-node.git" - }, - "keywords": [ - "cryptography", - "public-key", - "private-key", - "RSA" - ] -} \ No newline at end of file + "name": "cryptico-js", + "version": "2.0.0-alpha0", + "description": "Encryption/Decryption Library (AES/RSA, based on Cryptico)", + "main": "./lib/cryptico.js", + "scripts": { + "postinstall": "npm dedupe", + "start": "gulp", + "build": "gulp", + "publish-major": "npm run build && git commit -am pre-publish-build && npm version major && npm publish && git push origin master && git push origin master --tags", + "publish-minor": "npm run build && git commit -am pre-publish-build && npm version minor && npm publish && git push origin master && git push origin master --tags", + "publish-patch": "npm run build && git commit -am pre-publish-build && npm version patch && npm publish && git push origin master && git push origin master --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/tracker1/cryptico-js.git" + }, + "author": "Michael J. Ryan ", + "license": "ISC", + "contributors": [ + { + "name": "Rye Terrell", + "email": "ryeterrell@ryeterrell.net" + }, + { + "name": "Roberto Aguilar", + "email": "roberto@baremetal.io" + }, + { + "name": "PhpMyCoder" + } + ], + "keywords": [ + "encryption", + "cryptography", + "public-key", + "private-key", + "AES", + "RSA" + ], + "bugs": { + "url": "https://github.com/tracker1/cryptico-js/issues" + }, + "homepage": "https://github.com/tracker1/cryptico-js", + "devDependencies": { + "gulp": "^3.8.6", + "gulp-browserify": "^0.5.0", + "gulp-concat": "^2.3.4", + "gulp-header": "^1.0.5", + "gulp-rename": "^1.2.0", + "gulp-uglify": "^0.3.1" + } +} diff --git a/src/api.js b/src/api.js index de9e0af..26b9a24 100644 --- a/src/api.js +++ b/src/api.js @@ -1,4 +1,4 @@ -var cryptico = module.exports = (function() { +var cryptico = (function() { var my = {}; @@ -133,25 +133,65 @@ var cryptico = module.exports = (function() { } // Converts a string to a byte array. - my.string2bytes = function(string) + my.string2bytes = function(str) { - var bytes = new Array(); - for(var i = 0; i < string.length; i++) - { - bytes.push(string.charCodeAt(i)); + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } } - return bytes; + return utf8; } // Converts a byte array to a string. - my.bytes2string = function(bytes) + my.bytes2string = function(data) { - var string = ""; - for(var i = 0; i < bytes.length; i++) - { - string += String.fromCharCode(bytes[i]); - } - return string; + var str = '', + i; + + for (i = 0; i < data.length; i++) { + var value = data[i]; + + if (value < 0x80) { + str += String.fromCharCode(value); + } else if (value > 0xBF && value < 0xE0) { + str += String.fromCharCode((value & 0x1F) << 6 | data[i + 1] & 0x3F); + i += 1; + } else if (value > 0xDF && value < 0xF0) { + str += String.fromCharCode((value & 0x0F) << 12 | (data[i + 1] & 0x3F) << 6 | data[i + 2] & 0x3F); + i += 2; + } else { + // surrogate pair + var charCode = ((value & 0x07) << 18 | (data[i + 1] & 0x3F) << 12 | (data[i + 2] & 0x3F) << 6 | data[i + 3] & 0x3F) - 0x010000; + + str += String.fromCharCode(charCode >> 10 | 0xD800, charCode & 0x03FF | 0xDC00); + i += 3; + } + } + + return str; } // Returns a XOR b, where a and b are 16-byte byte arrays. @@ -288,68 +328,88 @@ var cryptico = module.exports = (function() { return rsa } - my.encrypt = function(plaintext, publickeystring, signingkey) - { + my.encrypt = function(plaintext, publickeystring, signingkey) { var cipherblock = ""; var aeskey = my.generateAESKey(); - try - { - var publickey = my.publicKeyFromString(publickeystring); - cipherblock += my.b16to64(publickey.encrypt(my.bytes2string(aeskey))) + "?"; - } - catch(err) - { - return {status: "Invalid public key"}; + try { + var publickey = my.publicKeyFromString(publickeystring); + cipherblock += my.b16to64(publickey.encrypt(my.bytes2string(aeskey))) + "?"; + } catch (err) { + return { + status: "Invalid public key" + }; } - if(signingkey) - { - signString = cryptico.b16to64(signingkey.signString(plaintext, "sha256")); - plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; - plaintext += cryptico.publicKeyString(signingkey); - plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; - plaintext += signString; + if (signingkey) { + plaintext += my.sign(plaintext, signingkey); } - cipherblock += my.encryptAESCBC(plaintext, aeskey); - return {status: "success", cipher: cipherblock}; - } - - my.decrypt = function(ciphertext, key) - { + cipherblock += my.encryptAESCBC(plaintext, aeskey); + return { + status: "success", + cipher: cipherblock + }; + } + my.decrypt = function(ciphertext, key) { var cipherblock = ciphertext.split("?"); var aeskey = key.decrypt(my.b64to16(cipherblock[0])); - if(aeskey == null) - { - return {status: "failure"}; + if (aeskey == null) { + return { + status: "failure" + }; } aeskey = my.string2bytes(aeskey); - var plaintext = my.decryptAESCBC(cipherblock[1], aeskey).split("::52cee64bb3a38f6403386519a39ac91c::"); - if(plaintext.length == 3) - { - var publickey = my.publicKeyFromString(plaintext[1]); - var signature = my.b64to16(plaintext[2]); - if(publickey.verifyString(plaintext[0], signature)) - { - return {status: "success", - plaintext: plaintext[0], - signature: "verified", - publicKeyString: my.publicKeyString(publickey)}; - } - else - { - return {status: "success", - plaintext: plaintext[0], - signature: "forged", - publicKeyString: my.publicKeyString(publickey)}; - } + var plaintext = my.decryptAESCBC(cipherblock[1], aeskey); + if (plaintext.indexOf("::52cee64bb3a38f6403386519a39ac91c::") != -1) { + return my._confirm(plaintext); + } else { + return { + status: "success", + plaintext: plaintext[0], + signature: "unsigned" + }; } - else - { - return {status: "success", plaintext: plaintext[0], signature: "unsigned"}; + } + + my.sign = function(plaintext, signingkey) { + var signString = cryptico.b16to64(signingkey.signString(plaintext, "sha256")); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += cryptico.publicKeyString(signingkey); + plaintext += "::52cee64bb3a38f6403386519a39ac91c::"; + plaintext += signString; + return plaintext; + } + + my.verify = function(plaintext) { + var result = my._confirm(plaintext); + return (result.status === "success" && result.signature === "verified"); + } + + my._confirm = function(plaintext) { + plaintext = plaintext.split("::52cee64bb3a38f6403386519a39ac91c::"); + if (plaintext.length == 3) { + var publickey = my.publicKeyFromString(plaintext[1]); + var signature = my.b64to16(plaintext[2]); + if (publickey.verifyString(plaintext[0], signature)) { + return { + status: "success", + plaintext: plaintext[0], + signature: "verified", + publicKeyString: my.publicKeyString(publickey) + }; + } else { + return { + status: "success", + plaintext: plaintext[0], + signature: "forged", + publicKeyString: my.publicKeyString(publickey) + }; + } + } else { + return { + status: "failure" + }; } - } + } return my; }()); - -module.exports.RSAKey = RSAKey; \ No newline at end of file diff --git a/src/exports.js b/src/exports.js new file mode 100644 index 0000000..e8b92c5 --- /dev/null +++ b/src/exports.js @@ -0,0 +1,7 @@ + +module.exports = cryptico; +module.exports.RSAKey = RSAKey; + +if (typeof window !== 'undefined') { + window.cryptico = module.exports; +} diff --git a/src/rsa.js b/src/rsa.js index f1c255d..5a0216d 100644 --- a/src/rsa.js +++ b/src/rsa.js @@ -131,7 +131,7 @@ function RSAToJSON() e: this.e.toString(16), n: this.n.toString(16), p: this.p.toString(16), - q: this.q.toString(16), + q: this.q.toString(16) } } @@ -218,7 +218,7 @@ function RSASetPrivateEx(N, E, D, P, Q, DP, DQ, C) this.dmq1 = parseBigInt(DQ, 16); this.coeff = parseBigInt(C, 16); } - else alert("Invalid RSA private key"); + else throw new Error("Invalid RSA private key"); } // Generate a new random private key B bits long, using public expt E @@ -349,7 +349,7 @@ function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) { sMid += "ff"; } - sPaddedMessageHex = sHead + sMid + sTail; + var sPaddedMessageHex = sHead + sMid + sTail; return sPaddedMessageHex; } @@ -456,29 +456,28 @@ RSAKey.prototype.signStringWithSHA256 = _rsasign_signStringWithSHA256; RSAKey.prototype.verifyString = _rsasign_verifyString; RSAKey.prototype.verifyHexSignatureForMessage = _rsasign_verifyHexSignatureForMessage; +// instance serializer, JSON.stringify(object_with_RSAKey) will serialize as expected. +RSAKey.prototype.toJSON = function() { + return JSON.stringify({ + type: 'RSAKey', + coeff: this.coeff.toString(16), + d: this.d.toString(16), + dmp1: this.dmp1.toString(16), + dmq1: this.dmq1.toString(16), + e: this.e.toString(16), + n: this.n.toString(16), + p: this.p.toString(16), + q: this.q.toString(16) + }) +} - - - - - - - - - - - - - - - - - - - - - - - - - +// global deserializer method +RSAKey.fromJSON = function(key) { + let json = typeof key === 'string' ? JSON.parse(key) : key; + if (!(json && json.type === 'RSAKey')) { + return null; + } + let rsa = new RSAKey(); + rsa.setPrivateEx(json.n, json.e, json.d, json.p, json.q, json.dmp1, json.dmq1, json.coeff); + return rsa; +} \ No newline at end of file