12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949 |
- var forge = require('./forge');
- require('./asn1');
- require('./jsbn');
- require('./oids');
- require('./pkcs1');
- require('./prime');
- require('./random');
- require('./util');
- if(typeof BigInteger === 'undefined') {
- var BigInteger = forge.jsbn.BigInteger;
- }
- var _crypto = forge.util.isNodejs ? require('crypto') : null;
- var asn1 = forge.asn1;
- var util = forge.util;
- forge.pki = forge.pki || {};
- module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};
- var pki = forge.pki;
- var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
- var privateKeyValidator = {
-
- name: 'PrivateKeyInfo',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
-
- name: 'PrivateKeyInfo.version',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyVersion'
- }, {
-
- name: 'PrivateKeyInfo.privateKeyAlgorithm',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: 'AlgorithmIdentifier.algorithm',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: 'privateKeyOid'
- }]
- }, {
-
- name: 'PrivateKeyInfo',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: 'privateKey'
- }]
- };
- var rsaPrivateKeyValidator = {
-
- name: 'RSAPrivateKey',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
-
- name: 'RSAPrivateKey.version',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyVersion'
- }, {
-
- name: 'RSAPrivateKey.modulus',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyModulus'
- }, {
-
- name: 'RSAPrivateKey.publicExponent',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyPublicExponent'
- }, {
-
- name: 'RSAPrivateKey.privateExponent',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyPrivateExponent'
- }, {
-
- name: 'RSAPrivateKey.prime1',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyPrime1'
- }, {
-
- name: 'RSAPrivateKey.prime2',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyPrime2'
- }, {
-
- name: 'RSAPrivateKey.exponent1',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyExponent1'
- }, {
-
- name: 'RSAPrivateKey.exponent2',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyExponent2'
- }, {
-
- name: 'RSAPrivateKey.coefficient',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'privateKeyCoefficient'
- }]
- };
- var rsaPublicKeyValidator = {
-
- name: 'RSAPublicKey',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
-
- name: 'RSAPublicKey.modulus',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'publicKeyModulus'
- }, {
-
- name: 'RSAPublicKey.exponent',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.INTEGER,
- constructed: false,
- capture: 'publicKeyExponent'
- }]
- };
- var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {
- name: 'SubjectPublicKeyInfo',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- captureAsn1: 'subjectPublicKeyInfo',
- value: [{
- name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: 'AlgorithmIdentifier.algorithm',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: 'publicKeyOid'
- }]
- }, {
-
- name: 'SubjectPublicKeyInfo.subjectPublicKey',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.BITSTRING,
- constructed: false,
- value: [{
-
- name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- optional: true,
- captureAsn1: 'rsaPublicKey'
- }]
- }]
- };
- var digestInfoValidator = {
- name: 'DigestInfo',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: 'DigestInfo.DigestAlgorithm',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.SEQUENCE,
- constructed: true,
- value: [{
- name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OID,
- constructed: false,
- capture: 'algorithmIdentifier'
- }, {
-
- name: 'DigestInfo.DigestAlgorithm.parameters',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.NULL,
-
- capture: 'parameters',
- optional: true,
- constructed: false
- }]
- }, {
-
- name: 'DigestInfo.digest',
- tagClass: asn1.Class.UNIVERSAL,
- type: asn1.Type.OCTETSTRING,
- constructed: false,
- capture: 'digest'
- }]
- };
- var emsaPkcs1v15encode = function(md) {
-
- var oid;
- if(md.algorithm in pki.oids) {
- oid = pki.oids[md.algorithm];
- } else {
- var error = new Error('Unknown message digest algorithm.');
- error.algorithm = md.algorithm;
- throw error;
- }
- var oidBytes = asn1.oidToDer(oid).getBytes();
-
- var digestInfo = asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- var digestAlgorithm = asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
- digestAlgorithm.value.push(asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));
- digestAlgorithm.value.push(asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));
- var digest = asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,
- false, md.digest().getBytes());
- digestInfo.value.push(digestAlgorithm);
- digestInfo.value.push(digest);
-
- return asn1.toDer(digestInfo).getBytes();
- };
- var _modPow = function(x, key, pub) {
- if(pub) {
- return x.modPow(key.e, key.n);
- }
- if(!key.p || !key.q) {
-
- return x.modPow(key.d, key.n);
- }
-
- if(!key.dP) {
- key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
- }
- if(!key.dQ) {
- key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
- }
- if(!key.qInv) {
- key.qInv = key.q.modInverse(key.p);
- }
-
-
- var r;
- do {
- r = new BigInteger(
- forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),
- 16);
- } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));
- x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);
-
- var xp = x.mod(key.p).modPow(key.dP, key.p);
- var xq = x.mod(key.q).modPow(key.dQ, key.q);
-
- while(xp.compareTo(xq) < 0) {
- xp = xp.add(key.p);
- }
-
- var y = xp.subtract(xq)
- .multiply(key.qInv).mod(key.p)
- .multiply(key.q).add(xq);
-
- y = y.multiply(r.modInverse(key.n)).mod(key.n);
- return y;
- };
- pki.rsa.encrypt = function(m, key, bt) {
- var pub = bt;
- var eb;
-
- var k = Math.ceil(key.n.bitLength() / 8);
- if(bt !== false && bt !== true) {
-
- pub = (bt === 0x02);
- eb = _encodePkcs1_v1_5(m, key, bt);
- } else {
- eb = forge.util.createBuffer();
- eb.putBytes(m);
- }
-
-
- var x = new BigInteger(eb.toHex(), 16);
-
- var y = _modPow(x, key, pub);
-
-
-
- var yhex = y.toString(16);
- var ed = forge.util.createBuffer();
- var zeros = k - Math.ceil(yhex.length / 2);
- while(zeros > 0) {
- ed.putByte(0x00);
- --zeros;
- }
- ed.putBytes(forge.util.hexToBytes(yhex));
- return ed.getBytes();
- };
- pki.rsa.decrypt = function(ed, key, pub, ml) {
-
- var k = Math.ceil(key.n.bitLength() / 8);
-
- if(ed.length !== k) {
- var error = new Error('Encrypted message length is invalid.');
- error.length = ed.length;
- error.expected = k;
- throw error;
- }
-
-
- var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
-
-
- if(y.compareTo(key.n) >= 0) {
- throw new Error('Encrypted message is invalid.');
- }
-
- var x = _modPow(y, key, pub);
-
-
-
- var xhex = x.toString(16);
- var eb = forge.util.createBuffer();
- var zeros = k - Math.ceil(xhex.length / 2);
- while(zeros > 0) {
- eb.putByte(0x00);
- --zeros;
- }
- eb.putBytes(forge.util.hexToBytes(xhex));
- if(ml !== false) {
-
- return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
- }
-
- return eb.getBytes();
- };
- pki.rsa.createKeyPairGenerationState = function(bits, e, options) {
-
-
- if(typeof(bits) === 'string') {
- bits = parseInt(bits, 10);
- }
- bits = bits || 2048;
-
- options = options || {};
- var prng = options.prng || forge.random;
- var rng = {
-
- nextBytes: function(x) {
- var b = prng.getBytesSync(x.length);
- for(var i = 0; i < x.length; ++i) {
- x[i] = b.charCodeAt(i);
- }
- }
- };
- var algorithm = options.algorithm || 'PRIMEINC';
-
- var rval;
- if(algorithm === 'PRIMEINC') {
- rval = {
- algorithm: algorithm,
- 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);
- } else {
- throw new Error('Invalid key generation algorithm: ' + algorithm);
- }
- return rval;
- };
- pki.rsa.stepKeyPairGenerationState = function(state, n) {
-
- if(!('algorithm' in state)) {
- state.algorithm = 'PRIMEINC';
- }
-
-
-
-
-
- var THIRTY = new BigInteger(null);
- THIRTY.fromInt(30);
- var deltaIdx = 0;
- var op_or = function(x, y) {return x | y;};
-
- var t1 = +new Date();
- var t2;
- var total = 0;
- while(state.keys === null && (n <= 0 || total < n)) {
-
- if(state.state === 0) {
-
- var bits = (state.p === null) ? state.pBits : state.qBits;
- var bits1 = bits - 1;
-
- if(state.pqState === 0) {
- state.num = new BigInteger(bits, state.rng);
-
- if(!state.num.testBit(bits1)) {
- state.num.bitwiseTo(
- BigInteger.ONE.shiftLeft(bits1), op_or, state.num);
- }
-
- state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
- deltaIdx = 0;
- ++state.pqState;
- } else if(state.pqState === 1) {
-
- if(state.num.bitLength() > bits) {
-
- state.pqState = 0;
-
- } else if(state.num.isProbablePrime(
- _getMillerRabinTests(state.num.bitLength()))) {
- ++state.pqState;
- } else {
-
- state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
- }
- } else if(state.pqState === 2) {
-
- state.pqState =
- (state.num.subtract(BigInteger.ONE).gcd(state.e)
- .compareTo(BigInteger.ONE) === 0) ? 3 : 0;
- } else if(state.pqState === 3) {
-
- state.pqState = 0;
- if(state.p === null) {
- state.p = state.num;
- } else {
- state.q = state.num;
- }
-
- if(state.p !== null && state.q !== null) {
- ++state.state;
- }
- state.num = null;
- }
- } else if(state.state === 1) {
-
- if(state.p.compareTo(state.q) < 0) {
- state.num = state.p;
- state.p = state.q;
- state.q = state.num;
- }
- ++state.state;
- } else if(state.state === 2) {
-
- state.p1 = state.p.subtract(BigInteger.ONE);
- state.q1 = state.q.subtract(BigInteger.ONE);
- state.phi = state.p1.multiply(state.q1);
- ++state.state;
- } else if(state.state === 3) {
-
- if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {
-
- ++state.state;
- } else {
-
- state.p = null;
- state.q = null;
- state.state = 0;
- }
- } else if(state.state === 4) {
-
- state.n = state.p.multiply(state.q);
-
- if(state.n.bitLength() === state.bits) {
-
- ++state.state;
- } else {
-
- state.q = null;
- state.state = 0;
- }
- } else if(state.state === 5) {
-
- var d = state.e.modInverse(state.phi);
- state.keys = {
- privateKey: pki.rsa.setPrivateKey(
- state.n, state.e, d, state.p, state.q,
- d.mod(state.p1), d.mod(state.q1),
- state.q.modInverse(state.p)),
- publicKey: pki.rsa.setPublicKey(state.n, state.e)
- };
- }
-
- t2 = +new Date();
- total += t2 - t1;
- t1 = t2;
- }
- return state.keys !== null;
- };
- pki.rsa.generateKeyPair = function(bits, e, options, callback) {
-
- if(arguments.length === 1) {
- if(typeof bits === 'object') {
- options = bits;
- bits = undefined;
- } else if(typeof bits === 'function') {
- callback = bits;
- bits = undefined;
- }
- } else if(arguments.length === 2) {
-
- if(typeof bits === 'number') {
- if(typeof e === 'function') {
- callback = e;
- e = undefined;
- } else if(typeof e !== 'number') {
- options = e;
- e = undefined;
- }
- } else {
- options = bits;
- callback = e;
- bits = undefined;
- e = undefined;
- }
- } else if(arguments.length === 3) {
-
- if(typeof e === 'number') {
- if(typeof options === 'function') {
- callback = options;
- options = undefined;
- }
- } else {
- callback = options;
- options = e;
- e = undefined;
- }
- }
- options = options || {};
- if(bits === undefined) {
- bits = options.bits || 2048;
- }
- if(e === undefined) {
- e = options.e || 0x10001;
- }
-
- if(!forge.options.usePureJavaScript && !options.prng &&
- bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {
- if(callback) {
-
- if(_detectNodeCrypto('generateKeyPair')) {
- return _crypto.generateKeyPair('rsa', {
- modulusLength: bits,
- publicExponent: e,
- publicKeyEncoding: {
- type: 'spki',
- format: 'pem'
- },
- privateKeyEncoding: {
- type: 'pkcs8',
- format: 'pem'
- }
- }, function(err, pub, priv) {
- if(err) {
- return callback(err);
- }
- callback(null, {
- privateKey: pki.privateKeyFromPem(priv),
- publicKey: pki.publicKeyFromPem(pub)
- });
- });
- }
- if(_detectSubtleCrypto('generateKey') &&
- _detectSubtleCrypto('exportKey')) {
-
- return util.globalScope.crypto.subtle.generateKey({
- name: 'RSASSA-PKCS1-v1_5',
- modulusLength: bits,
- publicExponent: _intToUint8Array(e),
- hash: {name: 'SHA-256'}
- }, true , ['sign', 'verify'])
- .then(function(pair) {
- return util.globalScope.crypto.subtle.exportKey(
- 'pkcs8', pair.privateKey);
-
- }).then(undefined, function(err) {
- callback(err);
- }).then(function(pkcs8) {
- if(pkcs8) {
- var privateKey = pki.privateKeyFromAsn1(
- asn1.fromDer(forge.util.createBuffer(pkcs8)));
- callback(null, {
- privateKey: privateKey,
- publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
- });
- }
- });
- }
- if(_detectSubtleMsCrypto('generateKey') &&
- _detectSubtleMsCrypto('exportKey')) {
- var genOp = util.globalScope.msCrypto.subtle.generateKey({
- name: 'RSASSA-PKCS1-v1_5',
- modulusLength: bits,
- publicExponent: _intToUint8Array(e),
- hash: {name: 'SHA-256'}
- }, true , ['sign', 'verify']);
- genOp.oncomplete = function(e) {
- var pair = e.target.result;
- var exportOp = util.globalScope.msCrypto.subtle.exportKey(
- 'pkcs8', pair.privateKey);
- exportOp.oncomplete = function(e) {
- var pkcs8 = e.target.result;
- var privateKey = pki.privateKeyFromAsn1(
- asn1.fromDer(forge.util.createBuffer(pkcs8)));
- callback(null, {
- privateKey: privateKey,
- publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
- });
- };
- exportOp.onerror = function(err) {
- callback(err);
- };
- };
- genOp.onerror = function(err) {
- callback(err);
- };
- return;
- }
- } else {
-
- if(_detectNodeCrypto('generateKeyPairSync')) {
- var keypair = _crypto.generateKeyPairSync('rsa', {
- modulusLength: bits,
- publicExponent: e,
- publicKeyEncoding: {
- type: 'spki',
- format: 'pem'
- },
- privateKeyEncoding: {
- type: 'pkcs8',
- format: 'pem'
- }
- });
- return {
- privateKey: pki.privateKeyFromPem(keypair.privateKey),
- publicKey: pki.publicKeyFromPem(keypair.publicKey)
- };
- }
- }
- }
-
- var state = pki.rsa.createKeyPairGenerationState(bits, e, options);
- if(!callback) {
- pki.rsa.stepKeyPairGenerationState(state, 0);
- return state.keys;
- }
- _generateKeyPair(state, options, callback);
- };
- pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {
- var key = {
- n: n,
- e: e
- };
-
- key.encrypt = function(data, scheme, schemeOptions) {
- if(typeof scheme === 'string') {
- scheme = scheme.toUpperCase();
- } else if(scheme === undefined) {
- scheme = 'RSAES-PKCS1-V1_5';
- }
- if(scheme === 'RSAES-PKCS1-V1_5') {
- scheme = {
- encode: function(m, key, pub) {
- return _encodePkcs1_v1_5(m, key, 0x02).getBytes();
- }
- };
- } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
- scheme = {
- encode: function(m, key) {
- return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);
- }
- };
- } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
- scheme = {encode: function(e) {return e;}};
- } else if(typeof scheme === 'string') {
- throw new Error('Unsupported encryption scheme: "' + scheme + '".');
- }
-
- var e = scheme.encode(data, key, true);
- return pki.rsa.encrypt(e, key, true);
- };
-
- key.verify = function(digest, signature, scheme, options) {
- if(typeof scheme === 'string') {
- scheme = scheme.toUpperCase();
- } else if(scheme === undefined) {
- scheme = 'RSASSA-PKCS1-V1_5';
- }
- if(options === undefined) {
- options = {
- _parseAllDigestBytes: true
- };
- }
- if(!('_parseAllDigestBytes' in options)) {
- options._parseAllDigestBytes = true;
- }
- if(scheme === 'RSASSA-PKCS1-V1_5') {
- scheme = {
- verify: function(digest, d) {
-
- d = _decodePkcs1_v1_5(d, key, true);
-
- var obj = asn1.fromDer(d, {
- parseAllBytes: options._parseAllDigestBytes
- });
-
- var capture = {};
- var errors = [];
- if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {
- var error = new Error(
- 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
- 'DigestInfo value.');
- error.errors = errors;
- throw error;
- }
-
-
-
- var oid = asn1.derToOid(capture.algorithmIdentifier);
- if(!(oid === forge.oids.md2 ||
- oid === forge.oids.md5 ||
- oid === forge.oids.sha1 ||
- oid === forge.oids.sha224 ||
- oid === forge.oids.sha256 ||
- oid === forge.oids.sha384 ||
- oid === forge.oids.sha512 ||
- oid === forge.oids['sha512-224'] ||
- oid === forge.oids['sha512-256'])) {
- var error = new Error(
- 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');
- error.oid = oid;
- throw error;
- }
-
- if(oid === forge.oids.md2 || oid === forge.oids.md5) {
- if(!('parameters' in capture)) {
- throw new Error(
- 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
- 'DigestInfo value. ' +
- 'Missing algorithm identifer NULL parameters.');
- }
- }
-
- return digest === capture.digest;
- }
- };
- } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
- scheme = {
- verify: function(digest, d) {
-
- d = _decodePkcs1_v1_5(d, key, true);
- return digest === d;
- }
- };
- }
-
- var d = pki.rsa.decrypt(signature, key, true, false);
- return scheme.verify(digest, d, key.n.bitLength());
- };
- return key;
- };
- pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(
- n, e, d, p, q, dP, dQ, qInv) {
- var key = {
- n: n,
- e: e,
- d: d,
- p: p,
- q: q,
- dP: dP,
- dQ: dQ,
- qInv: qInv
- };
-
- key.decrypt = function(data, scheme, schemeOptions) {
- if(typeof scheme === 'string') {
- scheme = scheme.toUpperCase();
- } else if(scheme === undefined) {
- scheme = 'RSAES-PKCS1-V1_5';
- }
-
- var d = pki.rsa.decrypt(data, key, false, false);
- if(scheme === 'RSAES-PKCS1-V1_5') {
- scheme = {decode: _decodePkcs1_v1_5};
- } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
- scheme = {
- decode: function(d, key) {
- return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);
- }
- };
- } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
- scheme = {decode: function(d) {return d;}};
- } else {
- throw new Error('Unsupported encryption scheme: "' + scheme + '".');
- }
-
- return scheme.decode(d, key, false);
- };
-
- key.sign = function(md, scheme) {
-
-
- var bt = false;
- if(typeof scheme === 'string') {
- scheme = scheme.toUpperCase();
- }
- if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {
- scheme = {encode: emsaPkcs1v15encode};
- bt = 0x01;
- } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
- scheme = {encode: function() {return md;}};
- bt = 0x01;
- }
-
- var d = scheme.encode(md, key.n.bitLength());
- return pki.rsa.encrypt(d, key, bt);
- };
- return key;
- };
- pki.wrapRsaPrivateKey = function(rsaKey) {
-
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- asn1.integerToDer(0).getBytes()),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
- asn1.create(
- asn1.Class.UNIVERSAL, asn1.Type.OID, false,
- asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
- ]),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
- asn1.toDer(rsaKey).getBytes())
- ]);
- };
- pki.privateKeyFromAsn1 = function(obj) {
-
- var capture = {};
- var errors = [];
- if(asn1.validate(obj, privateKeyValidator, capture, errors)) {
- obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));
- }
-
- capture = {};
- errors = [];
- if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
- var error = new Error('Cannot read private key. ' +
- 'ASN.1 object does not contain an RSAPrivateKey.');
- error.errors = errors;
- throw error;
- }
-
-
-
- var n, e, d, p, q, dP, dQ, qInv;
- n = forge.util.createBuffer(capture.privateKeyModulus).toHex();
- e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();
- d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
- p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();
- q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();
- dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();
- dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();
- qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();
-
- return pki.setRsaPrivateKey(
- new BigInteger(n, 16),
- new BigInteger(e, 16),
- new BigInteger(d, 16),
- new BigInteger(p, 16),
- new BigInteger(q, 16),
- new BigInteger(dP, 16),
- new BigInteger(dQ, 16),
- new BigInteger(qInv, 16));
- };
- pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {
-
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- asn1.integerToDer(0).getBytes()),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.n)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.e)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.d)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.p)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.q)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.dP)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.dQ)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.qInv))
- ]);
- };
- pki.publicKeyFromAsn1 = function(obj) {
-
- var capture = {};
- var errors = [];
- if(asn1.validate(obj, publicKeyValidator, capture, errors)) {
-
- var oid = asn1.derToOid(capture.publicKeyOid);
- if(oid !== pki.oids.rsaEncryption) {
- var error = new Error('Cannot read public key. Unknown OID.');
- error.oid = oid;
- throw error;
- }
- obj = capture.rsaPublicKey;
- }
-
- errors = [];
- if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {
- var error = new Error('Cannot read public key. ' +
- 'ASN.1 object does not contain an RSAPublicKey.');
- error.errors = errors;
- throw error;
- }
-
- var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();
- var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();
-
- return pki.setRsaPublicKey(
- new BigInteger(n, 16),
- new BigInteger(e, 16));
- };
- pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {
-
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
- asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
- ]),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [
- pki.publicKeyToRSAPublicKey(key)
- ])
- ]);
- };
- pki.publicKeyToRSAPublicKey = function(key) {
-
- return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.n)),
-
- asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
- _bnToBytes(key.e))
- ]);
- };
- function _encodePkcs1_v1_5(m, key, bt) {
- var eb = forge.util.createBuffer();
-
- var k = Math.ceil(key.n.bitLength() / 8);
-
- if(m.length > (k - 11)) {
- var error = new Error('Message is too long for PKCS#1 v1.5 padding.');
- error.length = m.length;
- error.max = k - 11;
- throw error;
- }
-
-
- eb.putByte(0x00);
- eb.putByte(bt);
-
- var padNum = k - 3 - m.length;
- var padByte;
-
- if(bt === 0x00 || bt === 0x01) {
- padByte = (bt === 0x00) ? 0x00 : 0xFF;
- for(var i = 0; i < padNum; ++i) {
- eb.putByte(padByte);
- }
- } else {
-
-
- while(padNum > 0) {
- var numZeros = 0;
- var padBytes = forge.random.getBytes(padNum);
- for(var i = 0; i < padNum; ++i) {
- padByte = padBytes.charCodeAt(i);
- if(padByte === 0) {
- ++numZeros;
- } else {
- eb.putByte(padByte);
- }
- }
- padNum = numZeros;
- }
- }
-
- eb.putByte(0x00);
- eb.putBytes(m);
- return eb;
- }
- function _decodePkcs1_v1_5(em, key, pub, ml) {
-
- var k = Math.ceil(key.n.bitLength() / 8);
-
-
- var eb = forge.util.createBuffer(em);
- 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 new Error('Encryption block is invalid.');
- }
- var padNum = 0;
- if(bt === 0x00) {
-
- padNum = k - 3 - ml;
- for(var i = 0; i < padNum; ++i) {
- if(eb.getByte() !== 0x00) {
- throw new Error('Encryption block is invalid.');
- }
- }
- } else if(bt === 0x01) {
-
- padNum = 0;
- while(eb.length() > 1) {
- if(eb.getByte() !== 0xFF) {
- --eb.read;
- break;
- }
- ++padNum;
- }
- } else if(bt === 0x02) {
-
- padNum = 0;
- while(eb.length() > 1) {
- if(eb.getByte() === 0x00) {
- --eb.read;
- break;
- }
- ++padNum;
- }
- }
-
- var zero = eb.getByte();
- if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {
- throw new Error('Encryption block is invalid.');
- }
- return eb.getBytes();
- }
- function _generateKeyPair(state, options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = {};
- }
- options = options || {};
- var opts = {
- algorithm: {
- name: options.algorithm || 'PRIMEINC',
- options: {
- workers: options.workers || 2,
- workLoad: options.workLoad || 100,
- workerScript: options.workerScript
- }
- }
- };
- if('prng' in options) {
- opts.prng = options.prng;
- }
- generate();
- function generate() {
-
- getPrime(state.pBits, function(err, num) {
- if(err) {
- return callback(err);
- }
- state.p = num;
- if(state.q !== null) {
- return finish(err, state.q);
- }
- getPrime(state.qBits, finish);
- });
- }
- function getPrime(bits, callback) {
- forge.prime.generateProbablePrime(bits, opts, callback);
- }
- function finish(err, num) {
- if(err) {
- return callback(err);
- }
-
- state.q = num;
-
- if(state.p.compareTo(state.q) < 0) {
- var tmp = state.p;
- state.p = state.q;
- state.q = tmp;
- }
-
- if(state.p.subtract(BigInteger.ONE).gcd(state.e)
- .compareTo(BigInteger.ONE) !== 0) {
- state.p = null;
- generate();
- return;
- }
-
- if(state.q.subtract(BigInteger.ONE).gcd(state.e)
- .compareTo(BigInteger.ONE) !== 0) {
- state.q = null;
- getPrime(state.qBits, finish);
- return;
- }
-
- state.p1 = state.p.subtract(BigInteger.ONE);
- state.q1 = state.q.subtract(BigInteger.ONE);
- state.phi = state.p1.multiply(state.q1);
-
- if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {
-
- state.p = state.q = null;
- generate();
- return;
- }
-
- state.n = state.p.multiply(state.q);
- if(state.n.bitLength() !== state.bits) {
-
- state.q = null;
- getPrime(state.qBits, finish);
- return;
- }
-
- var d = state.e.modInverse(state.phi);
- state.keys = {
- privateKey: pki.rsa.setPrivateKey(
- state.n, state.e, d, state.p, state.q,
- d.mod(state.p1), d.mod(state.q1),
- state.q.modInverse(state.p)),
- publicKey: pki.rsa.setPublicKey(state.n, state.e)
- };
- callback(null, state.keys);
- }
- }
- function _bnToBytes(b) {
-
- var hex = b.toString(16);
- if(hex[0] >= '8') {
- hex = '00' + hex;
- }
- var bytes = forge.util.hexToBytes(hex);
-
- if(bytes.length > 1 &&
-
- ((bytes.charCodeAt(0) === 0 &&
- (bytes.charCodeAt(1) & 0x80) === 0) ||
-
- (bytes.charCodeAt(0) === 0xFF &&
- (bytes.charCodeAt(1) & 0x80) === 0x80))) {
- return bytes.substr(1);
- }
- return bytes;
- }
- function _getMillerRabinTests(bits) {
- if(bits <= 100) return 27;
- if(bits <= 150) return 18;
- if(bits <= 200) return 15;
- if(bits <= 250) return 12;
- if(bits <= 300) return 9;
- if(bits <= 350) return 8;
- if(bits <= 400) return 7;
- if(bits <= 500) return 6;
- if(bits <= 600) return 5;
- if(bits <= 800) return 4;
- if(bits <= 1250) return 3;
- return 2;
- }
- function _detectNodeCrypto(fn) {
- return forge.util.isNodejs && typeof _crypto[fn] === 'function';
- }
- function _detectSubtleCrypto(fn) {
- return (typeof util.globalScope !== 'undefined' &&
- typeof util.globalScope.crypto === 'object' &&
- typeof util.globalScope.crypto.subtle === 'object' &&
- typeof util.globalScope.crypto.subtle[fn] === 'function');
- }
- function _detectSubtleMsCrypto(fn) {
- return (typeof util.globalScope !== 'undefined' &&
- typeof util.globalScope.msCrypto === 'object' &&
- typeof util.globalScope.msCrypto.subtle === 'object' &&
- typeof util.globalScope.msCrypto.subtle[fn] === 'function');
- }
- function _intToUint8Array(x) {
- var bytes = forge.util.hexToBytes(x.toString(16));
- var buffer = new Uint8Array(bytes.length);
- for(var i = 0; i < bytes.length; ++i) {
- buffer[i] = bytes.charCodeAt(i);
- }
- return buffer;
- }
- function _privateKeyFromJwk(jwk) {
- if(jwk.kty !== 'RSA') {
- throw new Error(
- 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".');
- }
- return pki.setRsaPrivateKey(
- _base64ToBigInt(jwk.n),
- _base64ToBigInt(jwk.e),
- _base64ToBigInt(jwk.d),
- _base64ToBigInt(jwk.p),
- _base64ToBigInt(jwk.q),
- _base64ToBigInt(jwk.dp),
- _base64ToBigInt(jwk.dq),
- _base64ToBigInt(jwk.qi));
- }
- function _publicKeyFromJwk(jwk) {
- if(jwk.kty !== 'RSA') {
- throw new Error('Key algorithm must be "RSA".');
- }
- return pki.setRsaPublicKey(
- _base64ToBigInt(jwk.n),
- _base64ToBigInt(jwk.e));
- }
- function _base64ToBigInt(b64) {
- return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);
- }
|