mirror of
https://github.com/moparisthebest/mail
synced 2024-11-15 13:45:08 -05:00
1108 lines
32 KiB
JavaScript
1108 lines
32 KiB
JavaScript
|
/**
|
||
|
* Javascript implementation of a basic RSA algorithms.
|
||
|
*
|
||
|
* @author Dave Longley
|
||
|
*
|
||
|
* Copyright (c) 2010-2013 Digital Bazaar, Inc.
|
||
|
*/
|
||
|
(function() {
|
||
|
function initModule(forge) {
|
||
|
/* ########## Begin module implementation ########## */
|
||
|
|
||
|
var _nodejs = (typeof module === 'object' && module.exports);
|
||
|
|
||
|
if(typeof BigInteger === 'undefined') {
|
||
|
BigInteger = forge.jsbn.BigInteger;
|
||
|
}
|
||
|
|
||
|
// shortcut for asn.1 API
|
||
|
var asn1 = forge.asn1;
|
||
|
|
||
|
/*
|
||
|
* RSA encryption and decryption, see RFC 2313.
|
||
|
*/
|
||
|
forge.pki = forge.pki || {};
|
||
|
forge.pki.rsa = forge.rsa = forge.rsa || {};
|
||
|
var pki = forge.pki;
|
||
|
|
||
|
// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
|
||
|
var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
|
||
|
|
||
|
/**
|
||
|
* Wrap digest in DigestInfo object.
|
||
|
*
|
||
|
* This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.
|
||
|
*
|
||
|
* DigestInfo ::= SEQUENCE {
|
||
|
* digestAlgorithm DigestAlgorithmIdentifier,
|
||
|
* digest Digest
|
||
|
* }
|
||
|
*
|
||
|
* DigestAlgorithmIdentifier ::= AlgorithmIdentifier
|
||
|
* Digest ::= OCTET STRING
|
||
|
*
|
||
|
* @param md the message digest object with the hash to sign.
|
||
|
* @return the encoded message (ready for RSA encrytion)
|
||
|
*/
|
||
|
var emsaPkcs1v15encode = function(md) {
|
||
|
// get the oid for the algorithm
|
||
|
var oid;
|
||
|
if(md.algorithm in forge.pki.oids) {
|
||
|
oid = forge.pki.oids[md.algorithm];
|
||
|
}
|
||
|
else {
|
||
|
throw {
|
||
|
message: 'Unknown message digest algorithm.',
|
||
|
algorithm: md.algorithm
|
||
|
};
|
||
|
}
|
||
|
var oidBytes = asn1.oidToDer(oid).getBytes();
|
||
|
|
||
|
// create the digest info
|
||
|
var digestInfo = asn1.create(
|
||
|
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
|
||
|
var digestAlgorithm = asn1.create(
|
||
|
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
|
||
|
digestAlgorithm.value.push(asn1.create(
|
||
|
asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));
|
||
|
digestAlgorithm.value.push(asn1.create(
|
||
|
asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));
|
||
|
var digest = asn1.create(
|
||
|
asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,
|
||
|
false, md.digest().getBytes());
|
||
|
digestInfo.value.push(digestAlgorithm);
|
||
|
digestInfo.value.push(digest);
|
||
|
|
||
|
// encode digest info
|
||
|
return asn1.toDer(digestInfo).getBytes();
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Performs x^c mod n (RSA encryption or decryption operation).
|
||
|
*
|
||
|
* @param x the number to raise and mod.
|
||
|
* @param key the key to use.
|
||
|
* @param pub true if the key is public, false if private.
|
||
|
*
|
||
|
* @return the result of x^c mod n.
|
||
|
*/
|
||
|
var _modPow = function(x, key, pub) {
|
||
|
var y;
|
||
|
|
||
|
if(pub) {
|
||
|
y = x.modPow(key.e, key.n);
|
||
|
}
|
||
|
else {
|
||
|
// pre-compute dP, dQ, and qInv if necessary
|
||
|
if(!key.dP) {
|
||
|
key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
|
||
|
}
|
||
|
if(!key.dQ) {
|
||
|
key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
|
||
|
}
|
||
|
if(!key.qInv) {
|
||
|
key.qInv = key.q.modInverse(key.p);
|
||
|
}
|
||
|
|
||
|
/* Chinese remainder theorem (CRT) states:
|
||
|
|
||
|
Suppose n1, n2, ..., nk are positive integers which are pairwise
|
||
|
coprime (n1 and n2 have no common factors other than 1). For any
|
||
|
integers x1, x2, ..., xk there exists an integer x solving the
|
||
|
system of simultaneous congruences (where ~= means modularly
|
||
|
congruent so a ~= b mod n means a mod n = b mod n):
|
||
|
|
||
|
x ~= x1 mod n1
|
||
|
x ~= x2 mod n2
|
||
|
...
|
||
|
x ~= xk mod nk
|
||
|
|
||
|
This system of congruences has a single simultaneous solution x
|
||
|
between 0 and n - 1. Furthermore, each xk solution and x itself
|
||
|
is congruent modulo the product n = n1*n2*...*nk.
|
||
|
So x1 mod n = x2 mod n = xk mod n = x mod n.
|
||
|
|
||
|
The single simultaneous solution x can be solved with the following
|
||
|
equation:
|
||
|
|
||
|
x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.
|
||
|
|
||
|
Where x is less than n, xi = x mod ni.
|
||
|
|
||
|
For RSA we are only concerned with k = 2. The modulus n = pq, where
|
||
|
p and q are coprime. The RSA decryption algorithm is:
|
||
|
|
||
|
y = x^d mod n
|
||
|
|
||
|
Given the above:
|
||
|
|
||
|
x1 = x^d mod p
|
||
|
r1 = n/p = q
|
||
|
s1 = q^-1 mod p
|
||
|
x2 = x^d mod q
|
||
|
r2 = n/q = p
|
||
|
s2 = p^-1 mod q
|
||
|
|
||
|
So y = (x1r1s1 + x2r2s2) mod n
|
||
|
= ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n
|
||
|
|
||
|
According to Fermat's Little Theorem, if the modulus P is prime,
|
||
|
for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.
|
||
|
Since A is not divisible by P it follows that if:
|
||
|
N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:
|
||
|
|
||
|
A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort
|
||
|
to calculate). In order to calculate x^d mod p more quickly the
|
||
|
exponent d mod (p - 1) is stored in the RSA private key (the same
|
||
|
is done for x^d mod q). These values are referred to as dP and dQ
|
||
|
respectively. Therefore we now have:
|
||
|
|
||
|
y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n
|
||
|
|
||
|
Since we'll be reducing x^dP by modulo p (same for q) we can also
|
||
|
reduce x by p (and q respectively) before hand. Therefore, let
|
||
|
|
||
|
xp = ((x mod p)^dP mod p), and
|
||
|
xq = ((x mod q)^dQ mod q), yielding:
|
||
|
|
||
|
y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n
|
||
|
|
||
|
This can be further reduced to a simple algorithm that only
|
||
|
requires 1 inverse (the q inverse is used) to be used and stored.
|
||
|
The algorithm is called Garner's algorithm. If qInv is the
|
||
|
inverse of q, we simply calculate:
|
||
|
|
||
|
y = (qInv*(xp - xq) mod p) * q + xq
|
||
|
|
||
|
However, there are two further complications. First, we need to
|
||
|
ensure that xp > xq to prevent signed BigIntegers from being used
|
||
|
so we add p until this is true (since we will be mod'ing with
|
||
|
p anyway). Then, there is a known timing attack on algorithms
|
||
|
using the CRT. To mitigate this risk, "cryptographic blinding"
|
||
|
should be used (*Not yet implemented*). This requires simply
|
||
|
generating a random number r between 0 and n-1 and its inverse
|
||
|
and multiplying x by r^e before calculating y and then multiplying
|
||
|
y by r^-1 afterwards.
|
||
|
*/
|
||
|
|
||
|
// TODO: do cryptographic blinding
|
||
|
|
||
|
// calculate xp and xq
|
||
|
var xp = x.mod(key.p).modPow(key.dP, key.p);
|
||
|
var xq = x.mod(key.q).modPow(key.dQ, key.q);
|
||
|
|
||
|
// xp must be larger than xq to avoid signed bit usage
|
||
|
while(xp.compareTo(xq) < 0) {
|
||
|
xp = xp.add(key.p);
|
||
|
}
|
||
|
|
||
|
// do last step
|
||
|
y = xp.subtract(xq)
|
||
|
.multiply(key.qInv).mod(key.p)
|
||
|
.multiply(key.q).add(xq);
|
||
|
}
|
||
|
|
||
|
return y;
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Performs RSA encryption.
|
||
|
*
|
||
|
* The parameter bt controls whether to put padding bytes before the
|
||
|
* message passed in. Set bt to either true or false to disable padding
|
||
|
* completely (in order to handle e.g. EMSA-PSS encoding seperately before),
|
||
|
* signaling whether the encryption operation is a public key operation
|
||
|
* (i.e. encrypting data) or not, i.e. private key operation (data signing).
|
||
|
*
|
||
|
* For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01
|
||
|
* (for signing) or 0x02 (for encryption). The key operation mode (private
|
||
|
* or public) is derived from this flag in that case).
|
||
|
*
|
||
|
* @param m the message to encrypt as a byte string.
|
||
|
* @param key the RSA key to use.
|
||
|
* @param bt for PKCS#1 v1.5 padding, the block type to use
|
||
|
* (0x01 for private key, 0x02 for public),
|
||
|
* to disable padding: true = public key, false = private key
|
||
|
* @return the encrypted bytes as a string.
|
||
|
*/
|
||
|
pki.rsa.encrypt = function(m, key, bt) {
|
||
|
var pub = bt;
|
||
|
var eb = forge.util.createBuffer();
|
||
|
|
||
|
// get the length of the modulus in bytes
|
||
|
var k = Math.ceil(key.n.bitLength() / 8);
|
||
|
|
||
|
if(bt !== false && bt !== true) {
|
||
|
/* use PKCS#1 v1.5 padding */
|
||
|
if(m.length > (k - 11)) {
|
||
|
throw {
|
||
|
message: 'Message is too long to encrypt.',
|
||
|
length: m.length,
|
||
|
max: (k - 11)
|
||
|
};
|
||
|
}
|
||
|
|
||
|
/* A block type BT, a padding string PS, and the data D shall be
|
||
|
formatted into an octet string EB, the encryption block:
|
||
|
|
||
|
EB = 00 || BT || PS || 00 || D
|
||
|
|
||
|
The block type BT shall be a single octet indicating the structure of
|
||
|
the encryption block. For this version of the document it shall have
|
||
|
value 00, 01, or 02. For a private-key operation, the block type
|
||
|
shall be 00 or 01. For a public-key operation, it shall be 02.
|
||
|
|
||
|
The padding string PS shall consist of k-3-||D|| octets. For block
|
||
|
type 00, the octets shall have value 00; for block type 01, they
|
||
|
shall have value FF; and for block type 02, they shall be
|
||
|
pseudorandomly generated and nonzero. This makes the length of the
|
||
|
encryption block EB equal to k. */
|
||
|
|
||
|
// build the encryption block
|
||
|
eb.putByte(0x00);
|
||
|
eb.putByte(bt);
|
||
|
|
||
|
// create the padding, get key type
|
||
|
var padNum = k - 3 - m.length;
|
||
|
var padByte;
|
||
|
if(bt === 0x00 || bt === 0x01) {
|
||
|
pub = false;
|
||
|
padByte = (bt === 0x00) ? 0x00 : 0xFF;
|
||
|
for(var i = 0; i < padNum; ++i) {
|
||
|
eb.putByte(padByte);
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
pub = true;
|
||
|
for(var i = 0; i < padNum; ++i) {
|
||
|
padByte = Math.floor(Math.random() * 255) + 1;
|
||
|
eb.putByte(padByte);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// zero followed by message
|
||
|
eb.putByte(0x00);
|
||
|
}
|
||
|
|
||
|
eb.putBytes(m);
|
||
|
|
||
|
// load encryption block as big integer 'x'
|
||
|
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
|
||
|
var x = new BigInteger(eb.toHex(), 16);
|
||
|
|
||
|
// do RSA encryption
|
||
|
var y = _modPow(x, key, pub);
|
||
|
|
||
|
// convert y into the encrypted data byte string, if y is shorter in
|
||
|
// bytes than k, then prepend zero bytes to fill up ed
|
||
|
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
|
||
|
var yhex = y.toString(16);
|
||
|
var ed = forge.util.createBuffer();
|
||
|
var zeros = k - Math.ceil(yhex.length / 2);
|
||
|
while(zeros > 0) {
|
||
|
ed.putByte(0x00);
|
||
|
--zeros;
|
||
|
}
|
||
|
ed.putBytes(forge.util.hexToBytes(yhex));
|
||
|
return ed.getBytes();
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Performs RSA decryption.
|
||
|
*
|
||
|
* The parameter ml controls whether to apply PKCS#1 v1.5 padding
|
||
|
* or not. Set ml = false to disable padding removal completely
|
||
|
* (in order to handle e.g. EMSA-PSS later on) and simply pass back
|
||
|
* the RSA encryption block.
|
||
|
*
|
||
|
* @param ed the encrypted data to decrypt in as a byte string.
|
||
|
* @param key the RSA key to use.
|
||
|
* @param pub true for a public key operation, false for private.
|
||
|
* @param ml the message length, if known. false to disable padding.
|
||
|
*
|
||
|
* @return the decrypted message as a byte string.
|
||
|
*/
|
||
|
pki.rsa.decrypt = function(ed, key, pub, ml) {
|
||
|
// get the length of the modulus in bytes
|
||
|
var k = Math.ceil(key.n.bitLength() / 8);
|
||
|
|
||
|
// error if the length of the encrypted data ED is not k
|
||
|
if(ed.length != k) {
|
||
|
throw {
|
||
|
message: 'Encrypted message length is invalid.',
|
||
|
length: ed.length,
|
||
|
expected: k
|
||
|
};
|
||
|
}
|
||
|
|
||
|
// convert encrypted data into a big integer
|
||
|
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
|
||
|
var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
|
||
|
|
||
|
// do RSA decryption
|
||
|
var x = _modPow(y, key, pub);
|
||
|
|
||
|
// create the encryption block, if x is shorter in bytes than k, then
|
||
|
// prepend zero bytes to fill up eb
|
||
|
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
|
||
|
var xhex = x.toString(16);
|
||
|
var eb = forge.util.createBuffer();
|
||
|
var zeros = k - Math.ceil(xhex.length / 2);
|
||
|
while(zeros > 0) {
|
||
|
eb.putByte(0x00);
|
||
|
--zeros;
|
||
|
}
|
||
|
eb.putBytes(forge.util.hexToBytes(xhex));
|
||
|
|
||
|
if(ml !== false) {
|
||
|
/* It is an error if any of the following conditions occurs:
|
||
|
|
||
|
1. The encryption block EB cannot be parsed unambiguously.
|
||
|
2. The padding string PS consists of fewer than eight octets
|
||
|
or is inconsisent with the block type BT.
|
||
|
3. The decryption process is a public-key operation and the block
|
||
|
type BT is not 00 or 01, or the decryption process is a
|
||
|
private-key operation and the block type is not 02.
|
||
|
*/
|
||
|
|
||
|
// parse the encryption block
|
||
|
var first = eb.getByte();
|
||
|
var bt = eb.getByte();
|
||
|
if(first !== 0x00 ||
|
||
|
(pub && bt !== 0x00 && bt !== 0x01) ||
|
||
|
(!pub && bt != 0x02) ||
|
||
|
(pub && bt === 0x00 && typeof(ml) === 'undefined')) {
|
||
|
throw {
|
||
|
message: 'Encryption block is invalid.'
|
||
|
};
|
||
|
}
|
||
|
|
||
|
var padNum = 0;
|
||
|
if(bt === 0x00) {
|
||
|
// check all padding bytes for 0x00
|
||
|
padNum = k - 3 - ml;
|
||
|
for(var i = 0; i < padNum; ++i) {
|
||
|
if(eb.getByte() !== 0x00) {
|
||
|
throw {
|
||
|
message: 'Encryption block is invalid.'
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
else if(bt === 0x01) {
|
||
|
// find the first byte that isn't 0xFF, should be after all padding
|
||
|
padNum = 0;
|
||
|
while(eb.length() > 1) {
|
||
|
if(eb.getByte() !== 0xFF) {
|
||
|
--eb.read;
|
||
|
break;
|
||
|
}
|
||
|
++padNum;
|
||
|
}
|
||
|
}
|
||
|
else if(bt === 0x02) {
|
||
|
// look for 0x00 byte
|
||
|
padNum = 0;
|
||
|
while(eb.length() > 1) {
|
||
|
if(eb.getByte() === 0x00) {
|
||
|
--eb.read;
|
||
|
break;
|
||
|
}
|
||
|
++padNum;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// zero must be 0x00 and padNum must be (k - 3 - message length)
|
||
|
var zero = eb.getByte();
|
||
|
if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {
|
||
|
throw {
|
||
|
message: 'Encryption block is invalid.'
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// return message
|
||
|
return eb.getBytes();
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Creates an RSA key-pair generation state object. It is used to allow
|
||
|
* key-generation to be performed in steps. It also allows for a UI to
|
||
|
* display progress updates.
|
||
|
*
|
||
|
* @param bits the size for the private key in bits, defaults to 1024.
|
||
|
* @param e the public exponent to use, defaults to 65537 (0x10001).
|
||
|
*
|
||
|
* @return the state object to use to generate the key-pair.
|
||
|
*/
|
||
|
pki.rsa.createKeyPairGenerationState = function(bits, e) {
|
||
|
// set default bits
|
||
|
if(typeof(bits) === 'string') {
|
||
|
bits = parseInt(bits, 10);
|
||
|
}
|
||
|
bits = bits || 1024;
|
||
|
|
||
|
// create prng with api that matches BigInteger secure random
|
||
|
var rng = {
|
||
|
// x is an array to fill with bytes
|
||
|
nextBytes: function(x) {
|
||
|
var b = forge.random.getBytes(x.length);
|
||
|
for(var i = 0; i < x.length; ++i) {
|
||
|
x[i] = b.charCodeAt(i);
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var rval = {
|
||
|
state: 0,
|
||
|
bits: bits,
|
||
|
rng: rng,
|
||
|
eInt: e || 65537,
|
||
|
e: new BigInteger(null),
|
||
|
p: null,
|
||
|
q: null,
|
||
|
qBits: bits >> 1,
|
||
|
pBits: bits - (bits >> 1),
|
||
|
pqState: 0,
|
||
|
num: null,
|
||
|
keys: null
|
||
|
};
|
||
|
rval.e.fromInt(rval.eInt);
|
||
|
|
||
|
return rval;
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Attempts to runs the key-generation algorithm for at most n seconds
|
||
|
* (approximately) using the given state. When key-generation has completed,
|
||
|
* the keys will be stored in state.keys.
|
||
|
*
|
||
|
* To use this function to update a UI while generating a key or to prevent
|
||
|
* causing browser lockups/warnings, set "n" to a value other than 0. A
|
||
|
* simple pattern for generating a key and showing a progress indicator is:
|
||
|
*
|
||
|
* var state = pki.rsa.createKeyPairGenerationState(2048);
|
||
|
* var step = function() {
|
||
|
* // step key-generation, run algorithm for 100 ms, repeat
|
||
|
* if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {
|
||
|
* setTimeout(step, 1);
|
||
|
* }
|
||
|
* // key-generation complete
|
||
|
* else {
|
||
|
* // TODO: turn off progress indicator here
|
||
|
* // TODO: use the generated key-pair in "state.keys"
|
||
|
* }
|
||
|
* };
|
||
|
* // TODO: turn on progress indicator here
|
||
|
* setTimeout(step, 0);
|
||
|
*
|
||
|
* @param state the state to use.
|
||
|
* @param n the maximum number of milliseconds to run the algorithm for, 0
|
||
|
* to run the algorithm to completion.
|
||
|
*
|
||
|
* @return true if the key-generation completed, false if not.
|
||
|
*/
|
||
|
pki.rsa.stepKeyPairGenerationState = function(state, n) {
|
||
|
// do key generation (based on Tom Wu's rsa.js, see jsbn.js license)
|
||
|
// with some minor optimizations and designed to run in steps
|
||
|
|
||
|
// local state vars
|
||
|
var THIRTY = new BigInteger(null);
|
||
|
THIRTY.fromInt(30);
|
||
|
var deltaIdx = 0;
|
||
|
var op_or = function(x,y) { return x|y; };
|
||
|
|
||
|
// keep stepping until time limit is reached or done
|
||
|
var t1 = +new Date();
|
||
|
var t2;
|
||
|
var total = 0;
|
||
|
while(state.keys === null && (n <= 0 || total < n)) {
|
||
|
// generate p or q
|
||
|
if(state.state === 0) {
|
||
|
/* Note: All primes are of the form:
|
||
|
|
||
|
30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i
|
||
|
|
||
|
When we generate a random number, we always align it at 30k + 1. Each
|
||
|
time the number is determined not to be prime we add to get to the
|
||
|
next 'i', eg: if the number was at 30k + 1 we add 6. */
|
||
|
var bits = (state.p === null) ? state.pBits : state.qBits;
|
||
|
var bits1 = bits - 1;
|
||
|
|
||
|
// get a random number
|
||
|
if(state.pqState === 0) {
|
||
|
state.num = new BigInteger(bits, state.rng);
|
||
|
// force MSB set
|
||
|
if(!state.num.testBit(bits1)) {
|
||
|
state.num.bitwiseTo(
|
||
|
BigInteger.ONE.shiftLeft(bits1), op_or, state.num);
|
||
|
}
|
||
|
// align number on 30k+1 boundary
|
||
|
state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
|
||
|
deltaIdx = 0;
|
||
|
|
||
|
++state.pqState;
|
||
|
}
|
||
|
// try to make the number a prime
|
||
|
else if(state.pqState === 1) {
|
||
|
// overflow, try again
|
||
|
if(state.num.bitLength() > bits) {
|
||
|
state.pqState = 0;
|
||
|
}
|
||
|
// do primality test
|
||
|
else if(state.num.isProbablePrime(1)) {
|
||
|
++state.pqState;
|
||
|
}
|
||
|
else {
|
||
|
// get next potential prime
|
||
|
state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
|
||
|
}
|
||
|
}
|
||
|
// ensure number is coprime with e
|
||
|
else if(state.pqState === 2) {
|
||
|
state.pqState =
|
||
|
(state.num.subtract(BigInteger.ONE).gcd(state.e)
|
||
|
.compareTo(BigInteger.ONE) === 0) ? 3 : 0;
|
||
|
}
|
||
|
// ensure number is a probable prime
|
||
|
else if(state.pqState === 3) {
|
||
|
state.pqState = 0;
|
||
|
if(state.num.isProbablePrime(10)) {
|
||
|
if(state.p === null) {
|
||
|
state.p = state.num;
|
||
|
}
|
||
|
else {
|
||
|
state.q = state.num;
|
||
|
}
|
||
|
|
||
|
// advance state if both p and q are ready
|
||
|
if(state.p !== null && state.q !== null) {
|
||
|
++state.state;
|
||
|
}
|
||
|
}
|
||
|
state.num = null;
|
||
|
}
|
||
|
}
|
||
|
// ensure p is larger than q (swap them if not)
|
||
|
else if(state.state === 1) {
|
||
|
if(state.p.compareTo(state.q) < 0) {
|
||
|
state.num = state.p;
|
||
|
state.p = state.q;
|
||
|
state.q = state.num;
|
||
|
}
|
||
|
++state.state;
|
||
|
}
|
||
|
// compute phi: (p - 1)(q - 1) (Euler's totient function)
|
||
|
else if(state.state === 2) {
|
||
|
state.p1 = state.p.subtract(BigInteger.ONE);
|
||
|
state.q1 = state.q.subtract(BigInteger.ONE);
|
||
|
state.phi = state.p1.multiply(state.q1);
|
||
|
++state.state;
|
||
|
}
|
||
|
// ensure e and phi are coprime
|
||
|
else if(state.state === 3) {
|
||
|
if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {
|
||
|
// phi and e are coprime, advance
|
||
|
++state.state;
|
||
|
}
|
||
|
else {
|
||
|
// phi and e aren't coprime, so generate a new p and q
|
||
|
state.p = null;
|
||
|
state.q = null;
|
||
|
state.state = 0;
|
||
|
}
|
||
|
}
|
||
|
// create n, ensure n is has the right number of bits
|
||
|
else if(state.state === 4) {
|
||
|
state.n = state.p.multiply(state.q);
|
||
|
|
||
|
// ensure n is right number of bits
|
||
|
if(state.n.bitLength() === state.bits) {
|
||
|
// success, advance
|
||
|
++state.state;
|
||
|
}
|
||
|
else {
|
||
|
// failed, get new q
|
||
|
state.q = null;
|
||
|
state.state = 0;
|
||
|
}
|
||
|
}
|
||
|
// set keys
|
||
|
else if(state.state === 5) {
|
||
|
var d = state.e.modInverse(state.phi);
|
||
|
state.keys = {
|
||
|
privateKey: forge.pki.rsa.setPrivateKey(
|
||
|
state.n, state.e, d, state.p, state.q,
|
||
|
d.mod(state.p1), d.mod(state.q1),
|
||
|
state.q.modInverse(state.p)),
|
||
|
publicKey: forge.pki.rsa.setPublicKey(state.n, state.e)
|
||
|
};
|
||
|
}
|
||
|
|
||
|
// update timing
|
||
|
t2 = +new Date();
|
||
|
total += t2 - t1;
|
||
|
t1 = t2;
|
||
|
}
|
||
|
|
||
|
return state.keys !== null;
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Generates an RSA public-private key pair in a single call.
|
||
|
*
|
||
|
* To generate a key-pair in steps (to allow for progress updates and to
|
||
|
* prevent blocking or warnings in slow browsers) then use the key-pair
|
||
|
* generation state functions.
|
||
|
*
|
||
|
* To generate a key-pair asynchronously (either through web-workers, if
|
||
|
* available, or by breaking up the work on the main thread), pass a
|
||
|
* callback function.
|
||
|
*
|
||
|
* @param [bits] the size for the private key in bits, defaults to 1024.
|
||
|
* @param [e] the public exponent to use, defaults to 65537.
|
||
|
* @param [options] options for key-pair generation, if given then 'bits'
|
||
|
* and 'e' must *not* be given:
|
||
|
* bits the size for the private key in bits, (default: 1024).
|
||
|
* e the public exponent to use, (default: 65537 (0x10001)).
|
||
|
* workerScript the worker script URL.
|
||
|
* workers the number of web workers (if supported) to use,
|
||
|
* (default: 2).
|
||
|
* workLoad the size of the work load, ie: number of possible prime
|
||
|
* numbers for each web worker to check per work assignment,
|
||
|
* (default: 100).
|
||
|
* e the public exponent to use, defaults to 65537.
|
||
|
* @param [callback(err, keypair)] called once the operation completes.
|
||
|
*
|
||
|
* @return an object with privateKey and publicKey properties.
|
||
|
*/
|
||
|
pki.rsa.generateKeyPair = function(bits, e, options, callback) {
|
||
|
// (bits), (options), (callback)
|
||
|
if(arguments.length === 1) {
|
||
|
if(typeof bits === 'object') {
|
||
|
options = bits;
|
||
|
bits = undefined;
|
||
|
}
|
||
|
else if(typeof bits === 'function') {
|
||
|
callback = bits;
|
||
|
bits = undefined;
|
||
|
}
|
||
|
}
|
||
|
// (bits, options), (bits, callback), (options, callback)
|
||
|
else if(arguments.length === 2) {
|
||
|
if(typeof bits === 'number') {
|
||
|
if(typeof e === 'function') {
|
||
|
callback = e;
|
||
|
}
|
||
|
else {
|
||
|
options = e;
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
options = bits;
|
||
|
callback = e;
|
||
|
bits = undefined;
|
||
|
}
|
||
|
e = undefined;
|
||
|
}
|
||
|
// (bits, e, options), (bits, e, callback), (bits, options, callback)
|
||
|
else if(arguments.length === 3) {
|
||
|
if(typeof e === 'number') {
|
||
|
if(typeof options === 'function') {
|
||
|
callback = options;
|
||
|
options = undefined;
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
callback = options;
|
||
|
options = e;
|
||
|
e = undefined;
|
||
|
}
|
||
|
}
|
||
|
options = options || {};
|
||
|
if(bits === undefined) {
|
||
|
bits = options.bits || 1024;
|
||
|
}
|
||
|
if(e === undefined) {
|
||
|
e = options.e || 0x10001;
|
||
|
}
|
||
|
var state = pki.rsa.createKeyPairGenerationState(bits, e);
|
||
|
if(!callback) {
|
||
|
pki.rsa.stepKeyPairGenerationState(state, 0);
|
||
|
return state.keys;
|
||
|
}
|
||
|
_generateKeyPair(state, options, callback);
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Sets an RSA public key from BigIntegers modulus and exponent.
|
||
|
*
|
||
|
* @param n the modulus.
|
||
|
* @param e the exponent.
|
||
|
*
|
||
|
* @return the public key.
|
||
|
*/
|
||
|
pki.rsa.setPublicKey = function(n, e) {
|
||
|
var key = {
|
||
|
n: n,
|
||
|
e: e
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Encrypts the given data with this public key.
|
||
|
*
|
||
|
* @param data the byte string to encrypt.
|
||
|
*
|
||
|
* @return the encrypted byte string.
|
||
|
*/
|
||
|
key.encrypt = function(data) {
|
||
|
return pki.rsa.encrypt(data, key, 0x02);
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Verifies the given signature against the given digest.
|
||
|
*
|
||
|
* PKCS#1 supports multiple (currently two) signature schemes:
|
||
|
* RSASSA-PKCS1-v1_5 and RSASSA-PSS.
|
||
|
*
|
||
|
* By default this implementation uses the "old scheme", i.e.
|
||
|
* RSASSA-PKCS1-v1_5, in which case once RSA-decrypted, the
|
||
|
* signature is an OCTET STRING that holds a DigestInfo.
|
||
|
*
|
||
|
* DigestInfo ::= SEQUENCE {
|
||
|
* digestAlgorithm DigestAlgorithmIdentifier,
|
||
|
* digest Digest
|
||
|
* }
|
||
|
* DigestAlgorithmIdentifier ::= AlgorithmIdentifier
|
||
|
* Digest ::= OCTET STRING
|
||
|
*
|
||
|
* To perform PSS signature verification, provide an instance
|
||
|
* of Forge PSS object as scheme parameter.
|
||
|
*
|
||
|
* @param digest the message digest hash to compare against the signature.
|
||
|
* @param signature the signature to verify.
|
||
|
* @param scheme signature scheme to use, undefined for PKCS#1 v1.5
|
||
|
* padding style.
|
||
|
* @return true if the signature was verified, false if not.
|
||
|
*/
|
||
|
key.verify = function(digest, signature, scheme) {
|
||
|
// do rsa decryption
|
||
|
var ml = scheme === undefined ? undefined : false;
|
||
|
var d = pki.rsa.decrypt(signature, key, true, ml);
|
||
|
|
||
|
if(scheme === undefined) {
|
||
|
// d is ASN.1 BER-encoded DigestInfo
|
||
|
var obj = asn1.fromDer(d);
|
||
|
|
||
|
// compare the given digest to the decrypted one
|
||
|
return digest === obj.value[1].value;
|
||
|
}
|
||
|
else {
|
||
|
return scheme.verify(digest, d, key.n.bitLength());
|
||
|
}
|
||
|
};
|
||
|
|
||
|
return key;
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Sets an RSA private key from BigIntegers modulus, exponent, primes,
|
||
|
* prime exponents, and modular multiplicative inverse.
|
||
|
*
|
||
|
* @param n the modulus.
|
||
|
* @param e the public exponent.
|
||
|
* @param d the private exponent ((inverse of e) mod n).
|
||
|
* @param p the first prime.
|
||
|
* @param q the second prime.
|
||
|
* @param dP exponent1 (d mod (p-1)).
|
||
|
* @param dQ exponent2 (d mod (q-1)).
|
||
|
* @param qInv ((inverse of q) mod p)
|
||
|
*
|
||
|
* @return the private key.
|
||
|
*/
|
||
|
pki.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) {
|
||
|
var key = {
|
||
|
n: n,
|
||
|
e: e,
|
||
|
d: d,
|
||
|
p: p,
|
||
|
q: q,
|
||
|
dP: dP,
|
||
|
dQ: dQ,
|
||
|
qInv: qInv
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Decrypts the given data with this private key.
|
||
|
*
|
||
|
* @param data the byte string to decrypt.
|
||
|
*
|
||
|
* @return the decrypted byte string.
|
||
|
*/
|
||
|
key.decrypt = function(data) {
|
||
|
return pki.rsa.decrypt(data, key, false);
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Signs the given digest, producing a signature.
|
||
|
*
|
||
|
* PKCS#1 supports multiple (currently two) signature schemes:
|
||
|
* RSASSA-PKCS1-v1_5 and RSASSA-PSS.
|
||
|
*
|
||
|
* By default this implementation uses the "old scheme", i.e.
|
||
|
* RSASSA-PKCS1-v1_5. In order to generate a PSS signature, provide
|
||
|
* an instance of Forge PSS object as scheme parameter.
|
||
|
*
|
||
|
* @param md the message digest object with the hash to sign.
|
||
|
* @param scheme signature scheme to use, undefined for PKCS#1 v1.5
|
||
|
* padding style.
|
||
|
* @return the signature as a byte string.
|
||
|
*/
|
||
|
key.sign = function(md, scheme) {
|
||
|
var bt = false; /* private key operation */
|
||
|
|
||
|
if(scheme === undefined) {
|
||
|
scheme = { encode: emsaPkcs1v15encode };
|
||
|
bt = 0x01;
|
||
|
}
|
||
|
|
||
|
var d = scheme.encode(md, key.n.bitLength());
|
||
|
return pki.rsa.encrypt(d, key, bt);
|
||
|
};
|
||
|
|
||
|
return key;
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Runs the key-generation algorithm asynchronously, either in the background
|
||
|
* via Web Workers, or using the main thread and setImmediate.
|
||
|
*
|
||
|
* @param state the key-pair generation state.
|
||
|
* @param [options] options for key-pair generation:
|
||
|
* workerScript the worker script URL.
|
||
|
* workers the number of web workers (if supported) to use,
|
||
|
* (default: 2).
|
||
|
* workLoad the size of the work load, ie: number of possible prime
|
||
|
* numbers for each web worker to check per work assignment,
|
||
|
* (default: 100).
|
||
|
* @param callback(err, keypair) called once the operation completes.
|
||
|
*/
|
||
|
function _generateKeyPair(state, options, callback) {
|
||
|
if(typeof options === 'function') {
|
||
|
callback = options;
|
||
|
options = {};
|
||
|
}
|
||
|
|
||
|
// web workers unavailable, use setImmediate
|
||
|
if(typeof(Worker) === 'undefined') {
|
||
|
function step() {
|
||
|
// 10 ms gives 5ms of leeway for other calculations before dropping
|
||
|
// below 60fps (1000/60 == 16.67), but in reality, the number will
|
||
|
// likely be higher due to an 'atomic' big int modPow
|
||
|
if(forge.pki.rsa.stepKeyPairGenerationState(state, 10)) {
|
||
|
return callback(null, state.keys);
|
||
|
}
|
||
|
forge.util.setImmediate(step);
|
||
|
}
|
||
|
return step();
|
||
|
}
|
||
|
|
||
|
// use web workers to generate keys
|
||
|
var numWorkers = options.workers || 2;
|
||
|
var workLoad = options.workLoad || 100;
|
||
|
var range = workLoad * 30/8;
|
||
|
var workerScript = options.workerScript || 'forge/prime.worker.js';
|
||
|
var THIRTY = new BigInteger(null);
|
||
|
THIRTY.fromInt(30);
|
||
|
var op_or = function(x,y) { return x|y; };
|
||
|
generate();
|
||
|
|
||
|
function generate() {
|
||
|
// find p and then q (done in series to simplify setting worker number)
|
||
|
getPrime(state.pBits, function(err, num) {
|
||
|
if(err) {
|
||
|
return callback(err);
|
||
|
}
|
||
|
state.p = num;
|
||
|
getPrime(state.qBits, finish);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// implement prime number generation using web workers
|
||
|
function getPrime(bits, callback) {
|
||
|
// TODO: consider optimizing by starting workers outside getPrime() ...
|
||
|
// note that in order to clean up they will have to be made internally
|
||
|
// asynchronous which may actually be slower
|
||
|
|
||
|
// start workers immediately
|
||
|
var workers = [];
|
||
|
for(var i = 0; i < numWorkers; ++i) {
|
||
|
// FIXME: fix path or use blob URLs
|
||
|
workers[i] = new Worker(workerScript);
|
||
|
}
|
||
|
var running = numWorkers;
|
||
|
|
||
|
// initialize random number
|
||
|
var num = generateRandom();
|
||
|
|
||
|
// listen for requests from workers and assign ranges to find prime
|
||
|
for(var i = 0; i < numWorkers; ++i) {
|
||
|
workers[i].addEventListener('message', workerMessage);
|
||
|
}
|
||
|
|
||
|
/* Note: The distribution of random numbers is unknown. Therefore, each
|
||
|
web worker is continuously allocated a range of numbers to check for a
|
||
|
random number until one is found.
|
||
|
|
||
|
Every 30 numbers will be checked just 8 times, because prime numbers
|
||
|
have the form:
|
||
|
|
||
|
30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)
|
||
|
|
||
|
Therefore, if we want a web worker to run N checks before asking for
|
||
|
a new range of numbers, each range must contain N*30/8 numbers.
|
||
|
|
||
|
For 100 checks (workLoad), this is a range of 375. */
|
||
|
|
||
|
function generateRandom() {
|
||
|
var bits1 = bits - 1;
|
||
|
var num = new BigInteger(bits, state.rng);
|
||
|
// force MSB set
|
||
|
if(!num.testBit(bits1)) {
|
||
|
num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
|
||
|
}
|
||
|
// align number on 30k+1 boundary
|
||
|
num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
|
||
|
return num;
|
||
|
}
|
||
|
|
||
|
var found = false;
|
||
|
function workerMessage(e) {
|
||
|
// ignore message, prime already found
|
||
|
if(found) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
--running;
|
||
|
var data = e.data;
|
||
|
if(data.found) {
|
||
|
// terminate all workers
|
||
|
for(var i = 0; i < workers.length; ++i) {
|
||
|
workers[i].terminate();
|
||
|
}
|
||
|
found = true;
|
||
|
return callback(null, new BigInteger(data.prime, 16));
|
||
|
}
|
||
|
|
||
|
// overflow, regenerate prime
|
||
|
if(num.bitLength() > bits) {
|
||
|
num = generateRandom();
|
||
|
}
|
||
|
|
||
|
// assign new range to check
|
||
|
var hex = num.toString(16);
|
||
|
|
||
|
// start prime search
|
||
|
e.target.postMessage({
|
||
|
e: state.eInt,
|
||
|
hex: hex,
|
||
|
workLoad: workLoad
|
||
|
});
|
||
|
|
||
|
num.dAddOffset(range, 0);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function finish(err, num) {
|
||
|
// set q
|
||
|
state.q = num;
|
||
|
|
||
|
// ensure p is larger than q (swap them if not)
|
||
|
if(state.p.compareTo(state.q) < 0) {
|
||
|
var tmp = state.p;
|
||
|
state.p = state.q;
|
||
|
state.q = tmp;
|
||
|
}
|
||
|
|
||
|
// compute phi: (p - 1)(q - 1) (Euler's totient function)
|
||
|
state.p1 = state.p.subtract(BigInteger.ONE);
|
||
|
state.q1 = state.q.subtract(BigInteger.ONE);
|
||
|
state.phi = state.p1.multiply(state.q1);
|
||
|
|
||
|
// ensure e and phi are coprime
|
||
|
if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {
|
||
|
// phi and e aren't coprime, so generate a new p and q
|
||
|
state.p = state.q = null;
|
||
|
generate();
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// create n, ensure n is has the right number of bits
|
||
|
state.n = state.p.multiply(state.q);
|
||
|
if(state.n.bitLength() !== state.bits) {
|
||
|
// failed, get new q
|
||
|
state.q = null;
|
||
|
getPrime(state.qBits, finish);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// set keys
|
||
|
var d = state.e.modInverse(state.phi);
|
||
|
state.keys = {
|
||
|
privateKey: forge.pki.rsa.setPrivateKey(
|
||
|
state.n, state.e, d, state.p, state.q,
|
||
|
d.mod(state.p1), d.mod(state.q1),
|
||
|
state.q.modInverse(state.p)),
|
||
|
publicKey: forge.pki.rsa.setPublicKey(state.n, state.e)
|
||
|
};
|
||
|
|
||
|
callback(null, state.keys);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
} // end module implementation
|
||
|
|
||
|
/* ########## Begin module wrapper ########## */
|
||
|
var name = 'rsa';
|
||
|
var deps = ['./asn1', './oids', './random', './util', './jsbn'];
|
||
|
var nodeDefine = null;
|
||
|
if(typeof define !== 'function') {
|
||
|
// NodeJS -> AMD
|
||
|
if(typeof module === 'object' && module.exports) {
|
||
|
nodeDefine = function(ids, factory) {
|
||
|
factory(require, module);
|
||
|
};
|
||
|
}
|
||
|
// <script>
|
||
|
else {
|
||
|
if(typeof forge === 'undefined') {
|
||
|
forge = {};
|
||
|
}
|
||
|
initModule(forge);
|
||
|
}
|
||
|
}
|
||
|
// AMD
|
||
|
if(nodeDefine || typeof define === 'function') {
|
||
|
// define module AMD style
|
||
|
(nodeDefine || define)(['require', 'module'].concat(deps),
|
||
|
function(require, module) {
|
||
|
module.exports = function(forge) {
|
||
|
var mods = deps.map(function(dep) {
|
||
|
return require(dep);
|
||
|
}).concat(initModule);
|
||
|
// handle circular dependencies
|
||
|
forge = forge || {};
|
||
|
forge.defined = forge.defined || {};
|
||
|
if(forge.defined[name]) {
|
||
|
return forge[name];
|
||
|
}
|
||
|
forge.defined[name] = true;
|
||
|
for(var i = 0; i < mods.length; ++i) {
|
||
|
mods[i](forge);
|
||
|
}
|
||
|
return forge[name];
|
||
|
};
|
||
|
});
|
||
|
}
|
||
|
})();
|