function NodeRSA(key, format, options) {
if (!(this instanceof NodeRSA)) {
return new NodeRSA(key, format, options);
}
if (_.isObject(format)) {
options = format;
format = undefined;
}
this.$options = {
signingScheme: DEFAULT_SIGNING_SCHEME,
signingSchemeOptions: {
hash: 'sha256',
saltLength: null
},
encryptionScheme: DEFAULT_ENCRYPTION_SCHEME,
encryptionSchemeOptions: {
hash: 'sha1',
label: null
},
environment: utils.detectEnvironment(),
rsaUtils: this
};
this.keyPair = new rsa.Key();
this.$cache = {};
if (Buffer.isBuffer(key) || _.isString(key)) {
this.importKey(key, format);
} else if (_.isObject(key)) {
this.generateKeyPair(key.b, key.e);
}
this.setOptions(options);
}n/a
function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}n/a
autoImport = function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
return false;
}...
isPublicImport: function (format) {
return module.exports[format] && typeof module.exports[format].publicImport === 'function';
},
detectAndImport: function (key, data, format) {
if (format === undefined) {
for (var scheme in module.exports) {
if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
return true;
}
}
} else if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
...privateExport = function (key, options) {
return {
n: key.n.toBuffer(),
e: key.e,
d: key.d.toBuffer(),
p: key.p.toBuffer(),
q: key.q.toBuffer(),
dmp1: key.dmp1.toBuffer(),
dmq1: key.dmq1.toBuffer(),
coeff: key.coeff.toBuffer()
};
}...
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
if (!key.isPrivate()) {
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
...privateImport = function (key, data, options) {
if (data.n && data.e && data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) {
key.setPrivate(
data.n,
data.e,
data.d,
data.p,
data.q,
data.dmp1,
data.dmq1,
data.coeff
);
} else {
throw Error("Invalid key data");
}
}...
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
...publicExport = function (key, options) {
return {
n: key.n.toBuffer(),
e: key.e
};
}...
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
}
};
...publicImport = function (key, data, options) {
if (data.n && data.e) {
key.setPublic(
data.n,
data.e
);
} else {
throw Error("Invalid key data");
}
}...
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
return false;
}
};
...getEngine = function (keyPair, options) {
var engine = require('./js.js');
if (options.environment === 'node') {
if (typeof crypt.publicEncrypt === 'function' && typeof crypt.privateDecrypt === 'function') {
if (typeof crypt.privateEncrypt === 'function' && typeof crypt.publicDecrypt === 'function') {
engine = require('./io.js');
} else {
engine = require('./node12.js');
}
}
}
return engine(keyPair, options);
}...
if (signingSchemeProvider === encryptionSchemeProvider) {
this.signingScheme = this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options);
} else {
this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options);
this.signingScheme = signingSchemeProvider.makeScheme(this, options);
}
this.encryptEngine = encryptEngines.getEngine(this, options);
};
/**
* Generate a new random private key B bits long, using public expt E
* @param B
* @param E
*/
...detectAndExport = function (key, format) {
if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
if (!key.isPrivate()) {
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
}...
* @param [format] {string}
*/
NodeRSA.prototype.exportKey = function (format) {
format = format || DEFAULT_EXPORT_FORMAT;
format = EXPORT_FORMAT_ALIASES[format] || format;
if (!this.$cache[format]) {
this.$cache[format] = formats.detectAndExport(this.keyPair, format);
}
return this.$cache[format];
};
/**
* Check if key pair contains private key
...detectAndImport = function (key, data, format) {
if (format === undefined) {
for (var scheme in module.exports) {
if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
return true;
}
}
} else if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
module.exports[fmt.scheme].privateImport(key, data, fmt.keyOpt);
} else {
module.exports[fmt.scheme].publicImport(key, data, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
return false;
}...
throw Error("Empty key given");
}
if (format) {
format = EXPORT_FORMAT_ALIASES[format] || format;
}
if (!formats.detectAndImport(this.keyPair, keyData, format) && format ===
undefined) {
throw Error("Key format must be specified");
}
this.$cache = {};
};
/**
...isPrivateExport = function (format) {
return module.exports[format] && typeof module.exports[format].privateExport === 'function';
}n/a
isPrivateImport = function (format) {
return module.exports[format] && typeof module.exports[format].privateImport === 'function';
}n/a
isPublicExport = function (format) {
return module.exports[format] && typeof module.exports[format].publicExport === 'function';
}n/a
isPublicImport = function (format) {
return module.exports[format] && typeof module.exports[format].publicImport === 'function';
}n/a
function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}n/a
function int2char(n) {
return BI_RM.charAt(n);
}n/a
function bnAbs() {
return (this.s < 0) ? this.negate() : this;
}...
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);
...function bnAdd(a) {
var r = nbi();
this.addTo(a, r);
return r;
}...
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) {
...function bnpAddTo(a, r) {
var i = 0, c = 0, m = Math.min(a.t, this.t);
while (i < m) {
c += this[i] + a[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
if (a.t < this.t) {
c += a.s;
while (i < this.t) {
c += this[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
c += this.s;
}
else {
c += this.s;
while (i < a.t) {
c += a[i];
r[i++] = c & this.DM;
c >>= this.DB;
}
c += a.s;
}
r.s = (c < 0) ? -1 : 0;
if (c > 0) r[i++] = c;
else if (c < -1) r[i++] = this.DV + c;
r.t = i;
r.clamp();
}...
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);
...function am3(i, x, w, j, c, n) {
var xl = x & 0x3fff, xh = x >> 14;
while (--n >= 0) {
var l = this[i] & 0x3fff;
var h = this[i++] >> 14;
var m = xh * l + h * xl;
l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
c = (l >> 28) + (m >> 14) + xh * h;
w[j++] = l & 0xfffffff;
}
return c;
}...
// (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) {
...function bnAnd(a) {
var r = nbi();
this.bitwiseTo(a, op_and, r);
return r;
}n/a
function bnAndNot(a) {
var r = nbi();
this.bitwiseTo(a, op_andnot, r);
return r;
}n/a
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;
}n/a
function bnBitLength() {
if (this.t <= 0) return 0;
return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
}...
else {
this.fromNumber(a);
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 = crypt.randomBytes((a >> 3) + 1)
var t = a & 7;
...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();
}...
function bnpFromNumber(a, b) {
if ("number" == typeof b) {
// new BigInteger(int,int,RNG)
if (a < 2) this.fromInt(1);
else {
this.fromNumber(a);
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 {
...function bnByteValue() {
return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
}n/a
function bnpChangeBit(n, op) {
var r = BigInteger.ONE.shiftLeft(n);
this.bitwiseTo(r, op, r);
return r;
}...
var r = BigInteger.ONE.shiftLeft(n);
this.bitwiseTo(r, op, r);
return r;
}
//(public) this | (1<<n)
function bnSetBit(n) {
return this.changeBit(n, op_or);
}
//(public) this & ~(1<<n)
function bnClearBit(n) {
return this.changeBit(n, op_andnot);
}
...function bnpChunkSize(r) {
return Math.floor(Math.LN2 * this.DB / Math.log(r));
}...
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);
}
...function bnpClamp() {
var c = this.s & this.DM;
while (this.t > 0 && this[this.t - 1] == c) --this.t;
}...
sh += k;
if (sh >= this.DB) sh -= this.DB;
}
if ((!unsigned) && k == 8 && (data[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);
}
function bnpFromByteArray(a, unsigned) {
this.fromString(a, 256, unsigned)
}
...function bnClearBit(n) {
return this.changeBit(n, op_andnot);
}n/a
function bnClone() {
var r = nbi();
this.copyTo(r);
return r;
}...
}
}
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();
...function bnCompareTo(a) {
var r = this.s - a.s;
if (r != 0) return r;
var i = this.t;
r = i - a.t;
if (r != 0) return (this.s < 0) ? -r : r;
while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r;
return 0;
}...
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) {
...function bnpCopyTo(r) {
for (var i = this.t - 1; i >= 0; --i) r[i] = this[i];
r.t = this.t;
r.s = this.s;
}...
// 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);
...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];
}
}...
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);
...function bnpDMultiply(n) {
this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
++this.t;
this.clamp();
}...
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));
...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);
}...
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 bnDivide(a) {
var r = nbi();
this.divRemTo(a, r, null);
return 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 {
...function bnDivideAndRemainder(a) {
var q = nbi(), r = nbi();
this.divRemTo(a, q, r);
return new Array(q, r);
}n/a
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;
}...
}
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;
...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;
}...
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);
}
...function bnEquals(a) {
return (this.compareTo(a) == 0);
}n/a
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);
}...
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);
}
// Copyright (c) 2005-2009 Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
// Extended JavaScript BN functions, required for RSA private ops.
...function bnFlipBit(n) {
return this.changeBit(n, op_xor);
}n/a
function bnpFromBuffer(a) {
this.fromString(a, 256, true)
}...
// (public) Constructor
function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}
...function bnpFromByteArray(a, unsigned) {
this.fromString(a, 256, unsigned)
}...
function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}
// return new, unset BigInteger
...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;
}...
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(data, radix, unsigned) {
var k;
switch (radix) {
...function bnpFromNumber(a, b) {
if ("number" == typeof b) {
// new BigInteger(int,int,RNG)
if (a < 2) this.fromInt(1);
else {
this.fromNumber(a);
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 = crypt.randomBytes((a >> 3) + 1)
var t = a & 7;
if (t > 0)
x[0] &= ((1 << t) - 1);
else
x[0] = 0;
this.fromByteArray(x);
}
}...
var canary = 0xdeadbeefcafe;
var j_lm = ((canary & 0xffffff) == 0xefcafe);
// (public) Constructor
function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
...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);
}...
case 32:
k = 5;
break;
case 256:
k = 8;
break;
default:
this.fromRadix(data, radix);
return;
}
this.t = 0;
this.s = 0;
var i = data.length;
...function bnpFromString(data, radix, unsigned) {
var k;
switch (radix) {
case 2:
k = 1;
break;
case 4:
k = 2;
break;
case 8:
k = 3;
break;
case 16:
k = 4;
break;
case 32:
k = 5;
break;
case 256:
k = 8;
break;
default:
this.fromRadix(data, radix);
return;
}
this.t = 0;
this.s = 0;
var i = data.length;
var mi = false;
var sh = 0;
while (--i >= 0) {
var x = (k == 8) ? data[i] & 0xff : intAt(data, i);
if (x < 0) {
if (data.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 ((!unsigned) && k == 8 && (data[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);
}...
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}
// return new, unset BigInteger
function nbi() {
return new BigInteger(null);
...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;
}...
RSAKey.prototype.generate = function (B, E) {
var qs = B >> 1;
this.e = parseInt(E, 16);
var ee = new BigInteger(E, 16);
while (true) {
while (true) {
this.p = new BigInteger(B - qs, 1);
if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0
x26;& this.p.isProbablePrime(10))
break;
}
while (true) {
this.q = new BigInteger(qs, 1);
if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0 && this.q.isProbablePrime(10))
break;
}
...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;
}...
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) {
...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];
}...
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) {
...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;
}...
// 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 bnpIsEven() {
return ((this.t > 0) ? (this[0] & 1) : this.s) === 0;
}...
}
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);
}
// Copyright (c) 2005-2009 Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
...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);
}...
// new BigInteger(int,int,RNG)
if (a < 2) this.fromInt(1);
else {
this.fromNumber(a);
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 = crypt.randomBytes((a >> 3) + 1)
...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();
}...
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;
...function bnMax(a) {
return (this.compareTo(a) > 0) ? this : a;
}...
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;
...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;
}...
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;
...function bnMin(a) {
return (this.compareTo(a) < 0) ? this : a;
}...
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;
...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 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;
}...
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) {
...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 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);
if (this.n.bitLength() < B) {
continue;
}
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;
}
}
this.$$recalculateCache();
...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);
}...
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;
...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);
}...
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;
}
...function bnMultiply(a) {
var r = nbi();
this.multiplyTo(a, r);
return r;
}...
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);
if (this.n.bitLength() < B) {
continue;
}
this.d = ee.modInverse(phi);
this.dmp1 = this.d.mod(p1);
...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();
}...
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) {
...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);
}...
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);
}
...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);
}...
//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 bnNegate() {
var r = nbi();
BigInteger.ZERO.subTo(this, r);
return r;
}...
function bnpClamp() {
var c = this.s & this.DM;
while (this.t > 0 && this[this.t - 1] == c) --this.t;
}
// (public) return string representation in given radix
function bnToString(b) {
if (this.s < 0) return "-" + this.negate().toString(b);
var k;
if (b == 16) k = 4;
else if (b == 8) k = 3;
else if (b == 2) k = 1;
else if (b == 32) k = 5;
else if (b == 4) k = 2;
else return this.toRadix(b);
...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;
}n/a
function bnOr(a) {
var r = nbi();
this.bitwiseTo(a, op_or, r);
return r;
}n/a
function bnPow(e) {
return this.exp(e, new NullExp());
}...
var size = 0;
if ((size = buffer.length - offset) > 0) {
if (size >= 4) {
return buffer.readUInt32BE(offset);
} else {
var res = 0;
for (var i = offset + size, d = 0; i > offset; i--, d += 2) {
res += buffer[i - 1] * Math.pow(16, d);
}
return res;
}
} else {
return NaN;
}
};
...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();
}...
}
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);
...function bnRemainder(a) {
var r = nbi();
this.divRemTo(a, null, r);
return r;
}n/a
function bnSetBit(n) {
return this.changeBit(n, op_or);
}n/a
function bnShiftLeft(n) {
var r = nbi();
if (n < 0) this.rShiftTo(-n, r); else this.lShiftTo(n, r);
return r;
}...
function bnpFromNumber(a, b) {
if ("number" == typeof b) {
// new BigInteger(int,int,RNG)
if (a < 2) this.fromInt(1);
else {
this.fromNumber(a);
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 {
...function bnShiftRight(n) {
var r = nbi();
if (n < 0) this.lShiftTo(-n, r); else this.rShiftTo(n, r);
return r;
}...
}
//(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);
...function bnShortValue() {
return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
}n/a
function bnSigNum() {
if (this.s < 0) return -1;
else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
else 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);
...function bnSquare() {
var r = nbi();
this.squareTo(r);
return r;
}n/a
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();
}...
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;
...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();
}...
if (sh >= this.DB) sh -= this.DB;
}
if ((!unsigned) && k == 8 && (data[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);
}
function bnpFromByteArray(a, unsigned) {
this.fromString(a, 256, unsigned)
}
function bnpFromBuffer(a) {
...function bnSubtract(a) {
var r = nbi();
this.subTo(a, r);
return r;
}...
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];
...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) alternate constructor
function bnpFromNumber(a, b) {
if ("number" == typeof b) {
// new BigInteger(int,int,RNG)
if (a < 2) this.fromInt(1);
else {
this.fromNumber(a);
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);
}
}
...function bnToBuffer(trimOrSize) {
var res = new Buffer(this.toByteArray());
if (trimOrSize === true && res[0] === 0) {
res = res.slice(1);
} else if (_.isNumber(trimOrSize)) {
if (res.length > trimOrSize) {
for (var i = 0; i < res.length - trimOrSize; i++) {
if (res[i] !== 0) {
return null;
}
}
return res.slice(res.length - trimOrSize);
} else if (res.length < trimOrSize) {
var padded = new Buffer(trimOrSize);
padded.fill(0, 0, trimOrSize - res.length);
res.copy(padded, trimOrSize - res.length);
return padded;
}
}
return res;
}...
/* Type 1: zeros padding for private key encrypt */
m = new BigInteger(pkcs1Scheme.encPad(buffer, {type: 1}));
c = keyPair.$doPrivate(m);
} else {
m = new BigInteger(keyPair.encryptionScheme.encPad(buffer));
c = keyPair.$doPublic(m);
}
return c.toBuffer(keyPair.encryptedDataLength);
},
decrypt: function (buffer, usePublic) {
var m, c = new BigInteger(buffer);
if (usePublic) {
m = keyPair.$doPublic(c);
...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;
}...
/**
* return Buffer object
* @param trim {boolean} slice buffer if first element == 0
* @returns {Buffer}
*/
function bnToBuffer(trimOrSize) {
var res = new Buffer(this.toByteArray());
if (trimOrSize === true && res[0] === 0) {
res = res.slice(1);
} else if (_.isNumber(trimOrSize)) {
if (res.length > trimOrSize) {
for (var i = 0; i < res.length - trimOrSize; i++) {
if (res[i] !== 0) {
return null;
...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;
}...
if (this.s < 0) return "-" + this.negate().toString(b);
var k;
if (b == 16) k = 4;
else if (b == 8) k = 3;
else if (b == 2) k = 1;
else if (b == 32) k = 5;
else if (b == 4) k = 2;
else return this.toRadix(b);
var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
var p = this.DB - (i * this.DB) % k;
if (i-- > 0) {
if (p < this.DB && (d = this[i] >> p) > 0) {
m = true;
r = int2char(d);
}
...function bnToString(b) {
if (this.s < 0) return "-" + this.negate().toString(b);
var k;
if (b == 16) k = 4;
else if (b == 8) k = 3;
else if (b == 2) k = 1;
else if (b == 32) k = 5;
else if (b == 4) k = 2;
else return this.toRadix(b);
var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
var p = this.DB - (i * this.DB) % k;
if (i-- > 0) {
if (p < this.DB && (d = this[i] >> p) > 0) {
m = true;
r = int2char(d);
}
while (i >= 0) {
if (p < k) {
d = (this[i] & ((1 << p) - 1)) << (k - p);
d |= this[--i] >> (p += this.DB - k);
}
else {
d = (this[i] >> (p -= k)) & km;
if (p <= 0) {
p += this.DB;
--i;
}
}
if (d > 0) m = true;
if (m) r += int2char(d);
}
}
return m ? r : "0";
}...
bits = bits || 2048;
exp = exp || 65537;
if (bits % 8 !== 0) {
throw Error('Key size must be a multiple of 8.');
}
this.keyPair.generate(bits, exp.toString(16));
this.$cache = {};
return this;
};
/**
* Importing key
* @param keyData {string|buffer|Object}
...function bnXor(a) {
var r = nbi();
this.bitwiseTo(a, op_xor, r);
return r;
}n/a
eme_oaep_mgf1 = function (seed, maskLength, hashFunction) {
hashFunction = hashFunction || DEFAULT_HASH_FUNCTION;
var hLen = module.exports.digestLength[hashFunction];
var count = Math.ceil(maskLength / hLen);
var T = new Buffer(hLen * count);
var c = new Buffer(4);
for (var i = 0; i < count; ++i) {
var hash = crypt.createHash(hashFunction);
hash.update(seed);
c.writeUInt32BE(i, 0);
hash.update(c);
hash.digest().copy(T, i * hLen);
}
return T.slice(0, maskLength);
}n/a
makeScheme = function (key, options) {
function Scheme(key, options) {
this.key = key;
this.options = options;
}
Scheme.prototype.maxMessageLength = function () {
return this.key.encryptedDataLength - 2 * module.exports.digestLength[this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION
] - 2;
};
/**
* Pad input
* alg: PKCS1_OAEP
*
* https://tools.ietf.org/html/rfc3447#section-7.1.1
*/
Scheme.prototype.encPad = function (buffer) {
var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1;
var label = this.options.encryptionSchemeOptions.label || new Buffer(0);
var emLen = this.key.encryptedDataLength;
var hLen = module.exports.digestLength[hash];
// Make sure we can put message into an encoded message of emLen bytes
if (buffer.length > emLen - 2 * hLen - 2) {
throw new Error("Message is too long to encode into an encoded message with a length of " + emLen + " bytes, increase
" +
"emLen to fix this error (minimum value for given parameters and options: " + (emLen - 2 * hLen - 2) + ")");
}
var lHash = crypt.createHash(hash);
lHash.update(label);
lHash = lHash.digest();
var PS = new Buffer(emLen - buffer.length - 2 * hLen - 1); // Padding "String"
PS.fill(0); // Fill the buffer with octets of 0
PS[PS.length - 1] = 1;
var DB = Buffer.concat([lHash, PS, buffer]);
var seed = crypt.randomBytes(hLen);
// mask = dbMask
var mask = mgf(seed, DB.length, hash);
// XOR DB and dbMask together.
for (var i = 0; i < DB.length; i++) {
DB[i] ^= mask[i];
}
// DB = maskedDB
// mask = seedMask
mask = mgf(DB, hLen, hash);
// XOR seed and seedMask together.
for (i = 0; i < seed.length; i++) {
seed[i] ^= mask[i];
}
// seed = maskedSeed
var em = new Buffer(1 + seed.length + DB.length);
em[0] = 0;
seed.copy(em, 1);
DB.copy(em, 1 + seed.length);
return em;
};
/**
* Unpad input
* alg: PKCS1_OAEP
*
* Note: This method works within the buffer given and modifies the values. It also returns a slice of the EM as the return
Message.
* If the implementation requires that the EM parameter be unmodified then the implementation should pass in a clone of the
EM buffer.
*
* https://tools.ietf.org/html/rfc3447#section-7.1.2
*/
Scheme.prototype.encUnPad = function (buffer) {
var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1;
var label = this.options.encryptionSchemeOptions.label || new Buffer(0);
var hLen = module.exports.digestLength[hash];
// Check to see if buffer is a properly encoded OAEP message
if (buffer.length < 2 * hLen + 2) {
throw new Error("Error decoding message, the supplied message is not long enough to be a valid OAEP encoded message");
}
var seed = buffer.slice(1, hLen + 1); // seed = maskedSeed
var DB = buffer.slice(1 + hLen); // DB = maskedDB
var mask = mgf(DB, hLen, hash); // seedMask
// XOR maskedSeed and seedMask together to get the original seed.
for (var i = 0; i < seed.length; i++) {
seed[i] ^= mask[i];
}
mask = mgf(seed, DB.length, hash); // dbMask
// XOR DB and dbMask together to get the original data block.
for (i = 0; i < DB.length; i++) {
DB[i] ^= mask[i];
}
var lHash = crypt.createHash(hash);
lHash.update(label);
lHash = lHash.digest();
var lHashEM = DB.slice(0, hLen);
if (lHashEM.toString("hex") != lHash.toString("hex")) {
throw new Error("Error decod ......
var crypto = require('crypto');
var constants = require('constants');
var schemes = require('../schemes/schemes.js');
module.exports = function (keyPair, options) {
var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options);
return {
encrypt: function (buffer, usePrivate) {
if (usePrivate) {
var padding = constants.RSA_PKCS1_PADDING;
if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) {
padding = options.encryptionSchemeOptions.padding;
...autoImport = function (key, data) {
if (/^\s*-----BEGIN RSA PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PRIVATE KEY-----\s*$/g.test(data)) {
module.exports.privateImport(key, data);
return true;
}
if (/^\s*-----BEGIN RSA PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PUBLIC KEY-----\s*$/g.test(data)) {
module.exports.publicImport(key, data);
return true;
}
return false;
}...
isPublicImport: function (format) {
return module.exports[format] && typeof module.exports[format].publicImport === 'function';
},
detectAndImport: function (key, data, format) {
if (format === undefined) {
for (var scheme in module.exports) {
if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
return true;
}
}
} else if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
...privateExport = function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var d = key.d.toBuffer();
var p = key.p.toBuffer();
var q = key.q.toBuffer();
var dmp1 = key.dmp1.toBuffer();
var dmq1 = key.dmq1.toBuffer();
var coeff = key.coeff.toBuffer();
var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.writeInt(0);
writer.writeBuffer(n, 2);
writer.writeInt(key.e);
writer.writeBuffer(d, 2);
writer.writeBuffer(p, 2);
writer.writeBuffer(q, 2);
writer.writeBuffer(dmp1, 2);
writer.writeBuffer(dmq1, 2);
writer.writeBuffer(coeff, 2);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return '-----BEGIN RSA PRIVATE KEY-----\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n-----END RSA PRIVATE
KEY-----';
}
}...
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
if (!key.isPrivate()) {
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
...privateImport = function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = data.replace('-----BEGIN RSA PRIVATE KEY-----', '')
.replace('-----END RSA PRIVATE KEY-----', '')
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = new Buffer(pem, 'base64');
} else {
throw Error('Unsupported key format');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
reader.readString(2, true); // just zero
key.setPrivate(
reader.readString(2, true), // modulus
reader.readString(2, true), // publicExponent
reader.readString(2, true), // privateExponent
reader.readString(2, true), // prime1
reader.readString(2, true), // prime2
reader.readString(2, true), // exponent1 -- d mod (p1)
reader.readString(2, true), // exponent2 -- d mod (q-1)
reader.readString(2, true) // coefficient -- (inverse of q) mod p
);
}...
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
...publicExport = function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var length = n.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.startSequence();
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.endSequence();
if (options.type === 'der') {
return bodyWriter.buffer;
} else {
return '-----BEGIN RSA PUBLIC KEY-----\n' + utils.linebrk(bodyWriter.buffer.toString('base64'), 64) + '\n-----END RSA PUBLIC
KEY-----';
}
}...
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
}
};
...publicImport = function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = data.replace('-----BEGIN RSA PUBLIC KEY-----', '')
.replace('-----END RSA PUBLIC KEY-----', '')
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = new Buffer(pem, 'base64');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var body = new ber.Reader(buffer);
body.readSequence();
key.setPublic(
body.readString(0x02, true), // modulus
body.readString(0x02, true) // publicExponent
);
}...
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
return false;
}
};
...autoImport = function (key, data) {
if (/^\s*-----BEGIN PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PRIVATE KEY-----\s*$/g.test(data)) {
module.exports.privateImport(key, data);
return true;
}
if (/^\s*-----BEGIN PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PUBLIC KEY-----\s*$/g.test(data)) {
module.exports.publicImport(key, data);
return true;
}
return false;
}...
isPublicImport: function (format) {
return module.exports[format] && typeof module.exports[format].publicImport === 'function';
},
detectAndImport: function (key, data, format) {
if (format === undefined) {
for (var scheme in module.exports) {
if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
return true;
}
}
} else if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
...privateExport = function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var d = key.d.toBuffer();
var p = key.p.toBuffer();
var q = key.q.toBuffer();
var dmp1 = key.dmp1.toBuffer();
var dmq1 = key.dmq1.toBuffer();
var coeff = key.coeff.toBuffer();
var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.startSequence();
bodyWriter.writeInt(0);
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.writeBuffer(d, 2);
bodyWriter.writeBuffer(p, 2);
bodyWriter.writeBuffer(q, 2);
bodyWriter.writeBuffer(dmp1, 2);
bodyWriter.writeBuffer(dmq1, 2);
bodyWriter.writeBuffer(coeff, 2);
bodyWriter.endSequence();
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.writeInt(0);
writer.startSequence();
writer.writeOID(PUBLIC_RSA_OID);
writer.writeNull();
writer.endSequence();
writer.writeBuffer(bodyWriter.buffer, 4);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return '-----BEGIN PRIVATE KEY-----\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n-----END PRIVATE KEY-----';
}
}...
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
if (!key.isPrivate()) {
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
...privateImport = function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = data.replace('-----BEGIN PRIVATE KEY-----', '')
.replace('-----END PRIVATE KEY-----', '')
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = new Buffer(pem, 'base64');
} else {
throw Error('Unsupported key format');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
reader.readInt(0);
var header = new ber.Reader(reader.readString(0x30, true));
if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) {
throw Error('Invalid Public key format');
}
var body = new ber.Reader(reader.readString(0x04, true));
body.readSequence();
body.readString(2, true); // just zero
key.setPrivate(
body.readString(2, true), // modulus
body.readString(2, true), // publicExponent
body.readString(2, true), // privateExponent
body.readString(2, true), // prime1
body.readString(2, true), // prime2
body.readString(2, true), // exponent1 -- d mod (p1)
body.readString(2, true), // exponent2 -- d mod (q-1)
body.readString(2, true) // coefficient -- (inverse of q) mod p
);
}...
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
...publicExport = function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var length = n.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.writeByte(0);
bodyWriter.startSequence();
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.endSequence();
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.startSequence();
writer.writeOID(PUBLIC_RSA_OID);
writer.writeNull();
writer.endSequence();
writer.writeBuffer(bodyWriter.buffer, 3);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return '-----BEGIN PUBLIC KEY-----\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n-----END PUBLIC KEY-----';
}
}...
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
}
};
...publicImport = function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = data.replace('-----BEGIN PUBLIC KEY-----', '')
.replace('-----END PUBLIC KEY-----', '')
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = new Buffer(pem, 'base64');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
var header = new ber.Reader(reader.readString(0x30, true));
if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) {
throw Error('Invalid Public key format');
}
var body = new ber.Reader(reader.readString(0x03, true));
body.readByte();
body.readSequence();
key.setPublic(
body.readString(0x02, true), // modulus
body.readString(0x02, true) // publicExponent
);
}...
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff
) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
return false;
}
};
...makeScheme = function (key, options) {
var OAEP = require('./schemes').pkcs1_oaep;
/**
* @param key
* @param options
* options [Object] An object that contains the following keys that specify certain options for encoding.
* └>signingSchemeOptions
* ├>hash [String] Hash function to use when encoding and generating masks. Must be a string accepted by node's crypto
.createHash function. (default = "sha1")
* ├>mgf [function] The mask generation function to use when encoding. (default = mgf1SHA1)
* └>sLen [uint] The length of the salt to generate. (default = 20)
* @constructor
*/
function Scheme(key, options) {
this.key = key;
this.options = options;
}
Scheme.prototype.sign = function (buffer) {
var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION);
mHash.update(buffer);
var encoded = this.emsa_pss_encode(mHash.digest(), this.key.keySize - 1);
return this.key.$doPrivate(new BigInteger(encoded)).toBuffer(this.key.encryptedDataLength);
};
Scheme.prototype.verify = function (buffer, signature, signature_encoding) {
if (signature_encoding) {
signature = new Buffer(signature, signature_encoding);
}
signature = new BigInteger(signature);
var emLen = Math.ceil((this.key.keySize - 1) / 8);
var m = this.key.$doPublic(signature).toBuffer(emLen);
var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION);
mHash.update(buffer);
return this.emsa_pss_verify(mHash.digest(), m, this.key.keySize - 1);
};
/*
* https://tools.ietf.org/html/rfc3447#section-9.1.1
*
* mHash [Buffer] Hashed message to encode
* emBits [uint] Maximum length of output in bits. Must be at least 8hLen + 8sLen + 9 (hLen = Hash digest length in bytes |
sLen = length of salt in bytes)
* @returns {Buffer} The encoded message
*/
Scheme.prototype.emsa_pss_encode = function (mHash, emBits) {
var hash = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.signingSchemeOptions.mgf || OAEP.eme_oaep_mgf1;
var sLen = this.options.signingSchemeOptions.saltLength || DEFAULT_SALT_LENGTH;
var hLen = OAEP.digestLength[hash];
var emLen = Math.ceil(emBits / 8);
if (emLen < hLen + sLen + 2) {
throw new Error("Output length passed to emBits(" + emBits + ") is too small for the options " +
"specified(" + hash + ", " + sLen + "). To fix this issue increase the value of emBits. (minimum size: " +
(8 * hLen + 8 * sLen + 9) + ")"
);
}
var salt = crypt.randomBytes(sLen);
var Mapostrophe = new Buffer(8 + hLen + sLen);
Mapostrophe.fill(0, 0, 8);
mHash.copy(Mapostrophe, 8);
salt.copy(Mapostrophe, 8 + mHash.length);
var H = crypt.createHash(hash);
H.update(Mapostrophe);
H = H.digest();
var PS = new Buffer(emLen - salt.length - hLen - 2);
PS.fill(0);
var DB = new Buffer(PS.length + 1 + salt.length);
PS.copy(DB);
DB[PS.length] = 0x01;
salt.copy(DB, PS.length + 1);
var dbMask = mgf(H, DB.length, hash);
// XOR DB and dbMask together
var maskedDB = new Buffer(DB.length);
for (var i = 0; i < dbMask.length; i++) {
maskedDB[i] = DB[i] ^ dbMask[i];
}
var bits = 8 * emLen - emBits;
var mask = 255 ^ (255 >> 8 - bits << 8 - bits);
maskedDB[0] = maskedDB[0] & mask;
var EM = new Buffer(maskedDB.length + H.length + 1);
maskedDB.copy(EM, 0);
H.copy(EM, maskedDB.length);
EM[EM.length - 1] = 0xbc;
return EM;
};
/*
* https://tools.ietf.org/html/rfc3447#section-9.1.2
*
* mHash [Buffer] Hashed message
* EM [Buffer] Signature
* emBits [uint] Length of EM in bits. ......
var crypto = require('crypto');
var constants = require('constants');
var schemes = require('../schemes/schemes.js');
module.exports = function (keyPair, options) {
var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options);
return {
encrypt: function (buffer, usePrivate) {
if (usePrivate) {
var padding = constants.RSA_PKCS1_PADDING;
if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) {
padding = options.encryptionSchemeOptions.padding;
...function BigInteger(a, b) {
if (a != null) {
if ("number" == typeof a) {
this.fromNumber(a, b);
} else if (Buffer.isBuffer(a)) {
this.fromBuffer(a);
} else if (b == null && "string" != typeof a) {
this.fromByteArray(a);
} else {
this.fromString(a, b);
}
}
}n/a
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;
}...
encryptionSchemeOptions: {
hash: 'sha1',
label: null
},
environment: utils.detectEnvironment(),
rsaUtils: this
};
this.keyPair = new rsa.Key();
this.$cache = {};
if (Buffer.isBuffer(key) || _.isString(key)) {
this.importKey(key, format);
} else if (_.isObject(key)) {
this.generateKeyPair(key.b, key.e);
}
...isEncryption = function (scheme) {
return module.exports[scheme] && module.exports[scheme].isEncryption;
}...
this.$options.encryptionScheme = options.encryptionScheme.toLowerCase();
this.$options.encryptionSchemeOptions = {};
} else if (_.isObject(options.encryptionScheme)) {
this.$options.encryptionScheme = options.encryptionScheme.scheme || DEFAULT_ENCRYPTION_SCHEME;
this.$options.encryptionSchemeOptions = _.omit(options.encryptionScheme, 'scheme');
}
if (!schemes.isEncryption(this.$options.encryptionScheme)) {
throw Error('Unsupported encryption scheme');
}
if (this.$options.encryptionSchemeOptions.hash &&
SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.encryptionSchemeOptions.hash) === -1) {
throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment');
}
...isSignature = function (scheme) {
return module.exports[scheme] && module.exports[scheme].isSignature;
}...
this.$options.signingScheme = signingScheme[0];
}
} else if (_.isObject(options.signingScheme)) {
this.$options.signingScheme = options.signingScheme.scheme || DEFAULT_SIGNING_SCHEME;
this.$options.signingSchemeOptions = _.omit(options.signingScheme, 'scheme');
}
if (!schemes.isSignature(this.$options.signingScheme)) {
throw Error('Unsupported signing scheme');
}
if (this.$options.signingSchemeOptions.hash &&
SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.signingSchemeOptions.hash) === -1) {
throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment');
}
...detectEnvironment = function () {
if (process && process.title === 'browser' || (typeof(window) !== 'undefined' && window)) {
return 'browser';
}
return 'node';
}...
saltLength: null
},
encryptionScheme: DEFAULT_ENCRYPTION_SCHEME,
encryptionSchemeOptions: {
hash: 'sha1',
label: null
},
environment: utils.detectEnvironment(),
rsaUtils: this
};
this.keyPair = new rsa.Key();
this.$cache = {};
if (Buffer.isBuffer(key) || _.isString(key)) {
this.importKey(key, format);
...get32IntFromBuffer = function (buffer, offset) {
offset = offset || 0;
var size = 0;
if ((size = buffer.length - offset) > 0) {
if (size >= 4) {
return buffer.readUInt32BE(offset);
} else {
var res = 0;
for (var i = offset + size, d = 0; i > offset; i--, d += 2) {
res += buffer[i - 1] * Math.pow(16, d);
}
return res;
}
} else {
return NaN;
}
}...
* @param DP
* @param DQ
* @param C
*/
RSAKey.prototype.setPrivate = function (N, E, D, P, Q, DP, DQ, C) {
if (N && E && D && N.length > 0 && (_.isNumber(E) || E.length > 0) &
;& D.length > 0) {
this.n = new BigInteger(N);
this.e = _.isNumber(E) ? E : utils.get32IntFromBuffer(E, 0);
this.d = new BigInteger(D);
if (P && Q && DP && DQ && C) {
this.p = new BigInteger(P);
this.q = new BigInteger(Q);
this.dmp1 = new BigInteger(DP);
this.dmq1 = new BigInteger(DQ);
...linebrk = function (str, maxLen) {
var res = '';
var i = 0;
while (i + maxLen < str.length) {
res += str.substring(i, i + maxLen) + "\n";
i += maxLen;
}
return res + str.substring(i, str.length);
}...
writer.writeBuffer(dmq1, 2);
writer.writeBuffer(coeff, 2);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return '-----BEGIN RSA PRIVATE KEY-----\n' + utils.linebrk(writer.buffer
.toString('base64'), 64) + '\n-----END RSA PRIVATE KEY-----';
}
},
privateImport: function (key, data, options) {
options = options || {};
var buffer;
...