rsa.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. /**
  2. * Javascript implementation of basic RSA algorithms.
  3. *
  4. * @author Dave Longley
  5. *
  6. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  7. *
  8. * The only algorithm currently supported for PKI is RSA.
  9. *
  10. * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo
  11. * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier
  12. * and a subjectPublicKey of type bit string.
  13. *
  14. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  15. * for the algorithm, if any. In the case of RSA, there aren't any.
  16. *
  17. * SubjectPublicKeyInfo ::= SEQUENCE {
  18. * algorithm AlgorithmIdentifier,
  19. * subjectPublicKey BIT STRING
  20. * }
  21. *
  22. * AlgorithmIdentifer ::= SEQUENCE {
  23. * algorithm OBJECT IDENTIFIER,
  24. * parameters ANY DEFINED BY algorithm OPTIONAL
  25. * }
  26. *
  27. * For an RSA public key, the subjectPublicKey is:
  28. *
  29. * RSAPublicKey ::= SEQUENCE {
  30. * modulus INTEGER, -- n
  31. * publicExponent INTEGER -- e
  32. * }
  33. *
  34. * PrivateKeyInfo ::= SEQUENCE {
  35. * version Version,
  36. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  37. * privateKey PrivateKey,
  38. * attributes [0] IMPLICIT Attributes OPTIONAL
  39. * }
  40. *
  41. * Version ::= INTEGER
  42. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  43. * PrivateKey ::= OCTET STRING
  44. * Attributes ::= SET OF Attribute
  45. *
  46. * An RSA private key as the following structure:
  47. *
  48. * RSAPrivateKey ::= SEQUENCE {
  49. * version Version,
  50. * modulus INTEGER, -- n
  51. * publicExponent INTEGER, -- e
  52. * privateExponent INTEGER, -- d
  53. * prime1 INTEGER, -- p
  54. * prime2 INTEGER, -- q
  55. * exponent1 INTEGER, -- d mod (p-1)
  56. * exponent2 INTEGER, -- d mod (q-1)
  57. * coefficient INTEGER -- (inverse of q) mod p
  58. * }
  59. *
  60. * Version ::= INTEGER
  61. *
  62. * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1
  63. */
  64. var forge = require('./forge');
  65. require('./asn1');
  66. require('./jsbn');
  67. require('./oids');
  68. require('./pkcs1');
  69. require('./prime');
  70. require('./random');
  71. require('./util');
  72. if(typeof BigInteger === 'undefined') {
  73. var BigInteger = forge.jsbn.BigInteger;
  74. }
  75. var _crypto = forge.util.isNodejs ? require('crypto') : null;
  76. // shortcut for asn.1 API
  77. var asn1 = forge.asn1;
  78. // shortcut for util API
  79. var util = forge.util;
  80. /*
  81. * RSA encryption and decryption, see RFC 2313.
  82. */
  83. forge.pki = forge.pki || {};
  84. module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};
  85. var pki = forge.pki;
  86. // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
  87. var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
  88. // validator for a PrivateKeyInfo structure
  89. var privateKeyValidator = {
  90. // PrivateKeyInfo
  91. name: 'PrivateKeyInfo',
  92. tagClass: asn1.Class.UNIVERSAL,
  93. type: asn1.Type.SEQUENCE,
  94. constructed: true,
  95. value: [{
  96. // Version (INTEGER)
  97. name: 'PrivateKeyInfo.version',
  98. tagClass: asn1.Class.UNIVERSAL,
  99. type: asn1.Type.INTEGER,
  100. constructed: false,
  101. capture: 'privateKeyVersion'
  102. }, {
  103. // privateKeyAlgorithm
  104. name: 'PrivateKeyInfo.privateKeyAlgorithm',
  105. tagClass: asn1.Class.UNIVERSAL,
  106. type: asn1.Type.SEQUENCE,
  107. constructed: true,
  108. value: [{
  109. name: 'AlgorithmIdentifier.algorithm',
  110. tagClass: asn1.Class.UNIVERSAL,
  111. type: asn1.Type.OID,
  112. constructed: false,
  113. capture: 'privateKeyOid'
  114. }]
  115. }, {
  116. // PrivateKey
  117. name: 'PrivateKeyInfo',
  118. tagClass: asn1.Class.UNIVERSAL,
  119. type: asn1.Type.OCTETSTRING,
  120. constructed: false,
  121. capture: 'privateKey'
  122. }]
  123. };
  124. // validator for an RSA private key
  125. var rsaPrivateKeyValidator = {
  126. // RSAPrivateKey
  127. name: 'RSAPrivateKey',
  128. tagClass: asn1.Class.UNIVERSAL,
  129. type: asn1.Type.SEQUENCE,
  130. constructed: true,
  131. value: [{
  132. // Version (INTEGER)
  133. name: 'RSAPrivateKey.version',
  134. tagClass: asn1.Class.UNIVERSAL,
  135. type: asn1.Type.INTEGER,
  136. constructed: false,
  137. capture: 'privateKeyVersion'
  138. }, {
  139. // modulus (n)
  140. name: 'RSAPrivateKey.modulus',
  141. tagClass: asn1.Class.UNIVERSAL,
  142. type: asn1.Type.INTEGER,
  143. constructed: false,
  144. capture: 'privateKeyModulus'
  145. }, {
  146. // publicExponent (e)
  147. name: 'RSAPrivateKey.publicExponent',
  148. tagClass: asn1.Class.UNIVERSAL,
  149. type: asn1.Type.INTEGER,
  150. constructed: false,
  151. capture: 'privateKeyPublicExponent'
  152. }, {
  153. // privateExponent (d)
  154. name: 'RSAPrivateKey.privateExponent',
  155. tagClass: asn1.Class.UNIVERSAL,
  156. type: asn1.Type.INTEGER,
  157. constructed: false,
  158. capture: 'privateKeyPrivateExponent'
  159. }, {
  160. // prime1 (p)
  161. name: 'RSAPrivateKey.prime1',
  162. tagClass: asn1.Class.UNIVERSAL,
  163. type: asn1.Type.INTEGER,
  164. constructed: false,
  165. capture: 'privateKeyPrime1'
  166. }, {
  167. // prime2 (q)
  168. name: 'RSAPrivateKey.prime2',
  169. tagClass: asn1.Class.UNIVERSAL,
  170. type: asn1.Type.INTEGER,
  171. constructed: false,
  172. capture: 'privateKeyPrime2'
  173. }, {
  174. // exponent1 (d mod (p-1))
  175. name: 'RSAPrivateKey.exponent1',
  176. tagClass: asn1.Class.UNIVERSAL,
  177. type: asn1.Type.INTEGER,
  178. constructed: false,
  179. capture: 'privateKeyExponent1'
  180. }, {
  181. // exponent2 (d mod (q-1))
  182. name: 'RSAPrivateKey.exponent2',
  183. tagClass: asn1.Class.UNIVERSAL,
  184. type: asn1.Type.INTEGER,
  185. constructed: false,
  186. capture: 'privateKeyExponent2'
  187. }, {
  188. // coefficient ((inverse of q) mod p)
  189. name: 'RSAPrivateKey.coefficient',
  190. tagClass: asn1.Class.UNIVERSAL,
  191. type: asn1.Type.INTEGER,
  192. constructed: false,
  193. capture: 'privateKeyCoefficient'
  194. }]
  195. };
  196. // validator for an RSA public key
  197. var rsaPublicKeyValidator = {
  198. // RSAPublicKey
  199. name: 'RSAPublicKey',
  200. tagClass: asn1.Class.UNIVERSAL,
  201. type: asn1.Type.SEQUENCE,
  202. constructed: true,
  203. value: [{
  204. // modulus (n)
  205. name: 'RSAPublicKey.modulus',
  206. tagClass: asn1.Class.UNIVERSAL,
  207. type: asn1.Type.INTEGER,
  208. constructed: false,
  209. capture: 'publicKeyModulus'
  210. }, {
  211. // publicExponent (e)
  212. name: 'RSAPublicKey.exponent',
  213. tagClass: asn1.Class.UNIVERSAL,
  214. type: asn1.Type.INTEGER,
  215. constructed: false,
  216. capture: 'publicKeyExponent'
  217. }]
  218. };
  219. // validator for an SubjectPublicKeyInfo structure
  220. // Note: Currently only works with an RSA public key
  221. var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {
  222. name: 'SubjectPublicKeyInfo',
  223. tagClass: asn1.Class.UNIVERSAL,
  224. type: asn1.Type.SEQUENCE,
  225. constructed: true,
  226. captureAsn1: 'subjectPublicKeyInfo',
  227. value: [{
  228. name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
  229. tagClass: asn1.Class.UNIVERSAL,
  230. type: asn1.Type.SEQUENCE,
  231. constructed: true,
  232. value: [{
  233. name: 'AlgorithmIdentifier.algorithm',
  234. tagClass: asn1.Class.UNIVERSAL,
  235. type: asn1.Type.OID,
  236. constructed: false,
  237. capture: 'publicKeyOid'
  238. }]
  239. }, {
  240. // subjectPublicKey
  241. name: 'SubjectPublicKeyInfo.subjectPublicKey',
  242. tagClass: asn1.Class.UNIVERSAL,
  243. type: asn1.Type.BITSTRING,
  244. constructed: false,
  245. value: [{
  246. // RSAPublicKey
  247. name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
  248. tagClass: asn1.Class.UNIVERSAL,
  249. type: asn1.Type.SEQUENCE,
  250. constructed: true,
  251. optional: true,
  252. captureAsn1: 'rsaPublicKey'
  253. }]
  254. }]
  255. };
  256. // validator for a DigestInfo structure
  257. var digestInfoValidator = {
  258. name: 'DigestInfo',
  259. tagClass: asn1.Class.UNIVERSAL,
  260. type: asn1.Type.SEQUENCE,
  261. constructed: true,
  262. value: [{
  263. name: 'DigestInfo.DigestAlgorithm',
  264. tagClass: asn1.Class.UNIVERSAL,
  265. type: asn1.Type.SEQUENCE,
  266. constructed: true,
  267. value: [{
  268. name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',
  269. tagClass: asn1.Class.UNIVERSAL,
  270. type: asn1.Type.OID,
  271. constructed: false,
  272. capture: 'algorithmIdentifier'
  273. }, {
  274. // NULL paramters
  275. name: 'DigestInfo.DigestAlgorithm.parameters',
  276. tagClass: asn1.Class.UNIVERSAL,
  277. type: asn1.Type.NULL,
  278. // captured only to check existence for md2 and md5
  279. capture: 'parameters',
  280. optional: true,
  281. constructed: false
  282. }]
  283. }, {
  284. // digest
  285. name: 'DigestInfo.digest',
  286. tagClass: asn1.Class.UNIVERSAL,
  287. type: asn1.Type.OCTETSTRING,
  288. constructed: false,
  289. capture: 'digest'
  290. }]
  291. };
  292. /**
  293. * Wrap digest in DigestInfo object.
  294. *
  295. * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.
  296. *
  297. * DigestInfo ::= SEQUENCE {
  298. * digestAlgorithm DigestAlgorithmIdentifier,
  299. * digest Digest
  300. * }
  301. *
  302. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  303. * Digest ::= OCTET STRING
  304. *
  305. * @param md the message digest object with the hash to sign.
  306. *
  307. * @return the encoded message (ready for RSA encrytion)
  308. */
  309. var emsaPkcs1v15encode = function(md) {
  310. // get the oid for the algorithm
  311. var oid;
  312. if(md.algorithm in pki.oids) {
  313. oid = pki.oids[md.algorithm];
  314. } else {
  315. var error = new Error('Unknown message digest algorithm.');
  316. error.algorithm = md.algorithm;
  317. throw error;
  318. }
  319. var oidBytes = asn1.oidToDer(oid).getBytes();
  320. // create the digest info
  321. var digestInfo = asn1.create(
  322. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  323. var digestAlgorithm = asn1.create(
  324. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  325. digestAlgorithm.value.push(asn1.create(
  326. asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));
  327. digestAlgorithm.value.push(asn1.create(
  328. asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));
  329. var digest = asn1.create(
  330. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,
  331. false, md.digest().getBytes());
  332. digestInfo.value.push(digestAlgorithm);
  333. digestInfo.value.push(digest);
  334. // encode digest info
  335. return asn1.toDer(digestInfo).getBytes();
  336. };
  337. /**
  338. * Performs x^c mod n (RSA encryption or decryption operation).
  339. *
  340. * @param x the number to raise and mod.
  341. * @param key the key to use.
  342. * @param pub true if the key is public, false if private.
  343. *
  344. * @return the result of x^c mod n.
  345. */
  346. var _modPow = function(x, key, pub) {
  347. if(pub) {
  348. return x.modPow(key.e, key.n);
  349. }
  350. if(!key.p || !key.q) {
  351. // allow calculation without CRT params (slow)
  352. return x.modPow(key.d, key.n);
  353. }
  354. // pre-compute dP, dQ, and qInv if necessary
  355. if(!key.dP) {
  356. key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
  357. }
  358. if(!key.dQ) {
  359. key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
  360. }
  361. if(!key.qInv) {
  362. key.qInv = key.q.modInverse(key.p);
  363. }
  364. /* Chinese remainder theorem (CRT) states:
  365. Suppose n1, n2, ..., nk are positive integers which are pairwise
  366. coprime (n1 and n2 have no common factors other than 1). For any
  367. integers x1, x2, ..., xk there exists an integer x solving the
  368. system of simultaneous congruences (where ~= means modularly
  369. congruent so a ~= b mod n means a mod n = b mod n):
  370. x ~= x1 mod n1
  371. x ~= x2 mod n2
  372. ...
  373. x ~= xk mod nk
  374. This system of congruences has a single simultaneous solution x
  375. between 0 and n - 1. Furthermore, each xk solution and x itself
  376. is congruent modulo the product n = n1*n2*...*nk.
  377. So x1 mod n = x2 mod n = xk mod n = x mod n.
  378. The single simultaneous solution x can be solved with the following
  379. equation:
  380. x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.
  381. Where x is less than n, xi = x mod ni.
  382. For RSA we are only concerned with k = 2. The modulus n = pq, where
  383. p and q are coprime. The RSA decryption algorithm is:
  384. y = x^d mod n
  385. Given the above:
  386. x1 = x^d mod p
  387. r1 = n/p = q
  388. s1 = q^-1 mod p
  389. x2 = x^d mod q
  390. r2 = n/q = p
  391. s2 = p^-1 mod q
  392. So y = (x1r1s1 + x2r2s2) mod n
  393. = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n
  394. According to Fermat's Little Theorem, if the modulus P is prime,
  395. for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.
  396. Since A is not divisible by P it follows that if:
  397. N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:
  398. A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort
  399. to calculate). In order to calculate x^d mod p more quickly the
  400. exponent d mod (p - 1) is stored in the RSA private key (the same
  401. is done for x^d mod q). These values are referred to as dP and dQ
  402. respectively. Therefore we now have:
  403. y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n
  404. Since we'll be reducing x^dP by modulo p (same for q) we can also
  405. reduce x by p (and q respectively) before hand. Therefore, let
  406. xp = ((x mod p)^dP mod p), and
  407. xq = ((x mod q)^dQ mod q), yielding:
  408. y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n
  409. This can be further reduced to a simple algorithm that only
  410. requires 1 inverse (the q inverse is used) to be used and stored.
  411. The algorithm is called Garner's algorithm. If qInv is the
  412. inverse of q, we simply calculate:
  413. y = (qInv*(xp - xq) mod p) * q + xq
  414. However, there are two further complications. First, we need to
  415. ensure that xp > xq to prevent signed BigIntegers from being used
  416. so we add p until this is true (since we will be mod'ing with
  417. p anyway). Then, there is a known timing attack on algorithms
  418. using the CRT. To mitigate this risk, "cryptographic blinding"
  419. should be used. This requires simply generating a random number r
  420. between 0 and n-1 and its inverse and multiplying x by r^e before
  421. calculating y and then multiplying y by r^-1 afterwards. Note that
  422. r must be coprime with n (gcd(r, n) === 1) in order to have an
  423. inverse.
  424. */
  425. // cryptographic blinding
  426. var r;
  427. do {
  428. r = new BigInteger(
  429. forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),
  430. 16);
  431. } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));
  432. x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);
  433. // calculate xp and xq
  434. var xp = x.mod(key.p).modPow(key.dP, key.p);
  435. var xq = x.mod(key.q).modPow(key.dQ, key.q);
  436. // xp must be larger than xq to avoid signed bit usage
  437. while(xp.compareTo(xq) < 0) {
  438. xp = xp.add(key.p);
  439. }
  440. // do last step
  441. var y = xp.subtract(xq)
  442. .multiply(key.qInv).mod(key.p)
  443. .multiply(key.q).add(xq);
  444. // remove effect of random for cryptographic blinding
  445. y = y.multiply(r.modInverse(key.n)).mod(key.n);
  446. return y;
  447. };
  448. /**
  449. * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or
  450. * 'encrypt' on a public key object instead.
  451. *
  452. * Performs RSA encryption.
  453. *
  454. * The parameter bt controls whether to put padding bytes before the
  455. * message passed in. Set bt to either true or false to disable padding
  456. * completely (in order to handle e.g. EMSA-PSS encoding seperately before),
  457. * signaling whether the encryption operation is a public key operation
  458. * (i.e. encrypting data) or not, i.e. private key operation (data signing).
  459. *
  460. * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01
  461. * (for signing) or 0x02 (for encryption). The key operation mode (private
  462. * or public) is derived from this flag in that case).
  463. *
  464. * @param m the message to encrypt as a byte string.
  465. * @param key the RSA key to use.
  466. * @param bt for PKCS#1 v1.5 padding, the block type to use
  467. * (0x01 for private key, 0x02 for public),
  468. * to disable padding: true = public key, false = private key.
  469. *
  470. * @return the encrypted bytes as a string.
  471. */
  472. pki.rsa.encrypt = function(m, key, bt) {
  473. var pub = bt;
  474. var eb;
  475. // get the length of the modulus in bytes
  476. var k = Math.ceil(key.n.bitLength() / 8);
  477. if(bt !== false && bt !== true) {
  478. // legacy, default to PKCS#1 v1.5 padding
  479. pub = (bt === 0x02);
  480. eb = _encodePkcs1_v1_5(m, key, bt);
  481. } else {
  482. eb = forge.util.createBuffer();
  483. eb.putBytes(m);
  484. }
  485. // load encryption block as big integer 'x'
  486. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  487. var x = new BigInteger(eb.toHex(), 16);
  488. // do RSA encryption
  489. var y = _modPow(x, key, pub);
  490. // convert y into the encrypted data byte string, if y is shorter in
  491. // bytes than k, then prepend zero bytes to fill up ed
  492. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  493. var yhex = y.toString(16);
  494. var ed = forge.util.createBuffer();
  495. var zeros = k - Math.ceil(yhex.length / 2);
  496. while(zeros > 0) {
  497. ed.putByte(0x00);
  498. --zeros;
  499. }
  500. ed.putBytes(forge.util.hexToBytes(yhex));
  501. return ed.getBytes();
  502. };
  503. /**
  504. * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or
  505. * 'verify' on a public key object instead.
  506. *
  507. * Performs RSA decryption.
  508. *
  509. * The parameter ml controls whether to apply PKCS#1 v1.5 padding
  510. * or not. Set ml = false to disable padding removal completely
  511. * (in order to handle e.g. EMSA-PSS later on) and simply pass back
  512. * the RSA encryption block.
  513. *
  514. * @param ed the encrypted data to decrypt in as a byte string.
  515. * @param key the RSA key to use.
  516. * @param pub true for a public key operation, false for private.
  517. * @param ml the message length, if known, false to disable padding.
  518. *
  519. * @return the decrypted message as a byte string.
  520. */
  521. pki.rsa.decrypt = function(ed, key, pub, ml) {
  522. // get the length of the modulus in bytes
  523. var k = Math.ceil(key.n.bitLength() / 8);
  524. // error if the length of the encrypted data ED is not k
  525. if(ed.length !== k) {
  526. var error = new Error('Encrypted message length is invalid.');
  527. error.length = ed.length;
  528. error.expected = k;
  529. throw error;
  530. }
  531. // convert encrypted data into a big integer
  532. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  533. var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
  534. // y must be less than the modulus or it wasn't the result of
  535. // a previous mod operation (encryption) using that modulus
  536. if(y.compareTo(key.n) >= 0) {
  537. throw new Error('Encrypted message is invalid.');
  538. }
  539. // do RSA decryption
  540. var x = _modPow(y, key, pub);
  541. // create the encryption block, if x is shorter in bytes than k, then
  542. // prepend zero bytes to fill up eb
  543. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  544. var xhex = x.toString(16);
  545. var eb = forge.util.createBuffer();
  546. var zeros = k - Math.ceil(xhex.length / 2);
  547. while(zeros > 0) {
  548. eb.putByte(0x00);
  549. --zeros;
  550. }
  551. eb.putBytes(forge.util.hexToBytes(xhex));
  552. if(ml !== false) {
  553. // legacy, default to PKCS#1 v1.5 padding
  554. return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
  555. }
  556. // return message
  557. return eb.getBytes();
  558. };
  559. /**
  560. * Creates an RSA key-pair generation state object. It is used to allow
  561. * key-generation to be performed in steps. It also allows for a UI to
  562. * display progress updates.
  563. *
  564. * @param bits the size for the private key in bits, defaults to 2048.
  565. * @param e the public exponent to use, defaults to 65537 (0x10001).
  566. * @param [options] the options to use.
  567. * prng a custom crypto-secure pseudo-random number generator to use,
  568. * that must define "getBytesSync".
  569. * algorithm the algorithm to use (default: 'PRIMEINC').
  570. *
  571. * @return the state object to use to generate the key-pair.
  572. */
  573. pki.rsa.createKeyPairGenerationState = function(bits, e, options) {
  574. // TODO: migrate step-based prime generation code to forge.prime
  575. // set default bits
  576. if(typeof(bits) === 'string') {
  577. bits = parseInt(bits, 10);
  578. }
  579. bits = bits || 2048;
  580. // create prng with api that matches BigInteger secure random
  581. options = options || {};
  582. var prng = options.prng || forge.random;
  583. var rng = {
  584. // x is an array to fill with bytes
  585. nextBytes: function(x) {
  586. var b = prng.getBytesSync(x.length);
  587. for(var i = 0; i < x.length; ++i) {
  588. x[i] = b.charCodeAt(i);
  589. }
  590. }
  591. };
  592. var algorithm = options.algorithm || 'PRIMEINC';
  593. // create PRIMEINC algorithm state
  594. var rval;
  595. if(algorithm === 'PRIMEINC') {
  596. rval = {
  597. algorithm: algorithm,
  598. state: 0,
  599. bits: bits,
  600. rng: rng,
  601. eInt: e || 65537,
  602. e: new BigInteger(null),
  603. p: null,
  604. q: null,
  605. qBits: bits >> 1,
  606. pBits: bits - (bits >> 1),
  607. pqState: 0,
  608. num: null,
  609. keys: null
  610. };
  611. rval.e.fromInt(rval.eInt);
  612. } else {
  613. throw new Error('Invalid key generation algorithm: ' + algorithm);
  614. }
  615. return rval;
  616. };
  617. /**
  618. * Attempts to runs the key-generation algorithm for at most n seconds
  619. * (approximately) using the given state. When key-generation has completed,
  620. * the keys will be stored in state.keys.
  621. *
  622. * To use this function to update a UI while generating a key or to prevent
  623. * causing browser lockups/warnings, set "n" to a value other than 0. A
  624. * simple pattern for generating a key and showing a progress indicator is:
  625. *
  626. * var state = pki.rsa.createKeyPairGenerationState(2048);
  627. * var step = function() {
  628. * // step key-generation, run algorithm for 100 ms, repeat
  629. * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {
  630. * setTimeout(step, 1);
  631. * } else {
  632. * // key-generation complete
  633. * // TODO: turn off progress indicator here
  634. * // TODO: use the generated key-pair in "state.keys"
  635. * }
  636. * };
  637. * // TODO: turn on progress indicator here
  638. * setTimeout(step, 0);
  639. *
  640. * @param state the state to use.
  641. * @param n the maximum number of milliseconds to run the algorithm for, 0
  642. * to run the algorithm to completion.
  643. *
  644. * @return true if the key-generation completed, false if not.
  645. */
  646. pki.rsa.stepKeyPairGenerationState = function(state, n) {
  647. // set default algorithm if not set
  648. if(!('algorithm' in state)) {
  649. state.algorithm = 'PRIMEINC';
  650. }
  651. // TODO: migrate step-based prime generation code to forge.prime
  652. // TODO: abstract as PRIMEINC algorithm
  653. // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)
  654. // with some minor optimizations and designed to run in steps
  655. // local state vars
  656. var THIRTY = new BigInteger(null);
  657. THIRTY.fromInt(30);
  658. var deltaIdx = 0;
  659. var op_or = function(x, y) {return x | y;};
  660. // keep stepping until time limit is reached or done
  661. var t1 = +new Date();
  662. var t2;
  663. var total = 0;
  664. while(state.keys === null && (n <= 0 || total < n)) {
  665. // generate p or q
  666. if(state.state === 0) {
  667. /* Note: All primes are of the form:
  668. 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i
  669. When we generate a random number, we always align it at 30k + 1. Each
  670. time the number is determined not to be prime we add to get to the
  671. next 'i', eg: if the number was at 30k + 1 we add 6. */
  672. var bits = (state.p === null) ? state.pBits : state.qBits;
  673. var bits1 = bits - 1;
  674. // get a random number
  675. if(state.pqState === 0) {
  676. state.num = new BigInteger(bits, state.rng);
  677. // force MSB set
  678. if(!state.num.testBit(bits1)) {
  679. state.num.bitwiseTo(
  680. BigInteger.ONE.shiftLeft(bits1), op_or, state.num);
  681. }
  682. // align number on 30k+1 boundary
  683. state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
  684. deltaIdx = 0;
  685. ++state.pqState;
  686. } else if(state.pqState === 1) {
  687. // try to make the number a prime
  688. if(state.num.bitLength() > bits) {
  689. // overflow, try again
  690. state.pqState = 0;
  691. // do primality test
  692. } else if(state.num.isProbablePrime(
  693. _getMillerRabinTests(state.num.bitLength()))) {
  694. ++state.pqState;
  695. } else {
  696. // get next potential prime
  697. state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
  698. }
  699. } else if(state.pqState === 2) {
  700. // ensure number is coprime with e
  701. state.pqState =
  702. (state.num.subtract(BigInteger.ONE).gcd(state.e)
  703. .compareTo(BigInteger.ONE) === 0) ? 3 : 0;
  704. } else if(state.pqState === 3) {
  705. // store p or q
  706. state.pqState = 0;
  707. if(state.p === null) {
  708. state.p = state.num;
  709. } else {
  710. state.q = state.num;
  711. }
  712. // advance state if both p and q are ready
  713. if(state.p !== null && state.q !== null) {
  714. ++state.state;
  715. }
  716. state.num = null;
  717. }
  718. } else if(state.state === 1) {
  719. // ensure p is larger than q (swap them if not)
  720. if(state.p.compareTo(state.q) < 0) {
  721. state.num = state.p;
  722. state.p = state.q;
  723. state.q = state.num;
  724. }
  725. ++state.state;
  726. } else if(state.state === 2) {
  727. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  728. state.p1 = state.p.subtract(BigInteger.ONE);
  729. state.q1 = state.q.subtract(BigInteger.ONE);
  730. state.phi = state.p1.multiply(state.q1);
  731. ++state.state;
  732. } else if(state.state === 3) {
  733. // ensure e and phi are coprime
  734. if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {
  735. // phi and e are coprime, advance
  736. ++state.state;
  737. } else {
  738. // phi and e aren't coprime, so generate a new p and q
  739. state.p = null;
  740. state.q = null;
  741. state.state = 0;
  742. }
  743. } else if(state.state === 4) {
  744. // create n, ensure n is has the right number of bits
  745. state.n = state.p.multiply(state.q);
  746. // ensure n is right number of bits
  747. if(state.n.bitLength() === state.bits) {
  748. // success, advance
  749. ++state.state;
  750. } else {
  751. // failed, get new q
  752. state.q = null;
  753. state.state = 0;
  754. }
  755. } else if(state.state === 5) {
  756. // set keys
  757. var d = state.e.modInverse(state.phi);
  758. state.keys = {
  759. privateKey: pki.rsa.setPrivateKey(
  760. state.n, state.e, d, state.p, state.q,
  761. d.mod(state.p1), d.mod(state.q1),
  762. state.q.modInverse(state.p)),
  763. publicKey: pki.rsa.setPublicKey(state.n, state.e)
  764. };
  765. }
  766. // update timing
  767. t2 = +new Date();
  768. total += t2 - t1;
  769. t1 = t2;
  770. }
  771. return state.keys !== null;
  772. };
  773. /**
  774. * Generates an RSA public-private key pair in a single call.
  775. *
  776. * To generate a key-pair in steps (to allow for progress updates and to
  777. * prevent blocking or warnings in slow browsers) then use the key-pair
  778. * generation state functions.
  779. *
  780. * To generate a key-pair asynchronously (either through web-workers, if
  781. * available, or by breaking up the work on the main thread), pass a
  782. * callback function.
  783. *
  784. * @param [bits] the size for the private key in bits, defaults to 2048.
  785. * @param [e] the public exponent to use, defaults to 65537.
  786. * @param [options] options for key-pair generation, if given then 'bits'
  787. * and 'e' must *not* be given:
  788. * bits the size for the private key in bits, (default: 2048).
  789. * e the public exponent to use, (default: 65537 (0x10001)).
  790. * workerScript the worker script URL.
  791. * workers the number of web workers (if supported) to use,
  792. * (default: 2).
  793. * workLoad the size of the work load, ie: number of possible prime
  794. * numbers for each web worker to check per work assignment,
  795. * (default: 100).
  796. * prng a custom crypto-secure pseudo-random number generator to use,
  797. * that must define "getBytesSync". Disables use of native APIs.
  798. * algorithm the algorithm to use (default: 'PRIMEINC').
  799. * @param [callback(err, keypair)] called once the operation completes.
  800. *
  801. * @return an object with privateKey and publicKey properties.
  802. */
  803. pki.rsa.generateKeyPair = function(bits, e, options, callback) {
  804. // (bits), (options), (callback)
  805. if(arguments.length === 1) {
  806. if(typeof bits === 'object') {
  807. options = bits;
  808. bits = undefined;
  809. } else if(typeof bits === 'function') {
  810. callback = bits;
  811. bits = undefined;
  812. }
  813. } else if(arguments.length === 2) {
  814. // (bits, e), (bits, options), (bits, callback), (options, callback)
  815. if(typeof bits === 'number') {
  816. if(typeof e === 'function') {
  817. callback = e;
  818. e = undefined;
  819. } else if(typeof e !== 'number') {
  820. options = e;
  821. e = undefined;
  822. }
  823. } else {
  824. options = bits;
  825. callback = e;
  826. bits = undefined;
  827. e = undefined;
  828. }
  829. } else if(arguments.length === 3) {
  830. // (bits, e, options), (bits, e, callback), (bits, options, callback)
  831. if(typeof e === 'number') {
  832. if(typeof options === 'function') {
  833. callback = options;
  834. options = undefined;
  835. }
  836. } else {
  837. callback = options;
  838. options = e;
  839. e = undefined;
  840. }
  841. }
  842. options = options || {};
  843. if(bits === undefined) {
  844. bits = options.bits || 2048;
  845. }
  846. if(e === undefined) {
  847. e = options.e || 0x10001;
  848. }
  849. // use native code if permitted, available, and parameters are acceptable
  850. if(!forge.options.usePureJavaScript && !options.prng &&
  851. bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {
  852. if(callback) {
  853. // try native async
  854. if(_detectNodeCrypto('generateKeyPair')) {
  855. return _crypto.generateKeyPair('rsa', {
  856. modulusLength: bits,
  857. publicExponent: e,
  858. publicKeyEncoding: {
  859. type: 'spki',
  860. format: 'pem'
  861. },
  862. privateKeyEncoding: {
  863. type: 'pkcs8',
  864. format: 'pem'
  865. }
  866. }, function(err, pub, priv) {
  867. if(err) {
  868. return callback(err);
  869. }
  870. callback(null, {
  871. privateKey: pki.privateKeyFromPem(priv),
  872. publicKey: pki.publicKeyFromPem(pub)
  873. });
  874. });
  875. }
  876. if(_detectSubtleCrypto('generateKey') &&
  877. _detectSubtleCrypto('exportKey')) {
  878. // use standard native generateKey
  879. return util.globalScope.crypto.subtle.generateKey({
  880. name: 'RSASSA-PKCS1-v1_5',
  881. modulusLength: bits,
  882. publicExponent: _intToUint8Array(e),
  883. hash: {name: 'SHA-256'}
  884. }, true /* key can be exported*/, ['sign', 'verify'])
  885. .then(function(pair) {
  886. return util.globalScope.crypto.subtle.exportKey(
  887. 'pkcs8', pair.privateKey);
  888. // avoiding catch(function(err) {...}) to support IE <= 8
  889. }).then(undefined, function(err) {
  890. callback(err);
  891. }).then(function(pkcs8) {
  892. if(pkcs8) {
  893. var privateKey = pki.privateKeyFromAsn1(
  894. asn1.fromDer(forge.util.createBuffer(pkcs8)));
  895. callback(null, {
  896. privateKey: privateKey,
  897. publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
  898. });
  899. }
  900. });
  901. }
  902. if(_detectSubtleMsCrypto('generateKey') &&
  903. _detectSubtleMsCrypto('exportKey')) {
  904. var genOp = util.globalScope.msCrypto.subtle.generateKey({
  905. name: 'RSASSA-PKCS1-v1_5',
  906. modulusLength: bits,
  907. publicExponent: _intToUint8Array(e),
  908. hash: {name: 'SHA-256'}
  909. }, true /* key can be exported*/, ['sign', 'verify']);
  910. genOp.oncomplete = function(e) {
  911. var pair = e.target.result;
  912. var exportOp = util.globalScope.msCrypto.subtle.exportKey(
  913. 'pkcs8', pair.privateKey);
  914. exportOp.oncomplete = function(e) {
  915. var pkcs8 = e.target.result;
  916. var privateKey = pki.privateKeyFromAsn1(
  917. asn1.fromDer(forge.util.createBuffer(pkcs8)));
  918. callback(null, {
  919. privateKey: privateKey,
  920. publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
  921. });
  922. };
  923. exportOp.onerror = function(err) {
  924. callback(err);
  925. };
  926. };
  927. genOp.onerror = function(err) {
  928. callback(err);
  929. };
  930. return;
  931. }
  932. } else {
  933. // try native sync
  934. if(_detectNodeCrypto('generateKeyPairSync')) {
  935. var keypair = _crypto.generateKeyPairSync('rsa', {
  936. modulusLength: bits,
  937. publicExponent: e,
  938. publicKeyEncoding: {
  939. type: 'spki',
  940. format: 'pem'
  941. },
  942. privateKeyEncoding: {
  943. type: 'pkcs8',
  944. format: 'pem'
  945. }
  946. });
  947. return {
  948. privateKey: pki.privateKeyFromPem(keypair.privateKey),
  949. publicKey: pki.publicKeyFromPem(keypair.publicKey)
  950. };
  951. }
  952. }
  953. }
  954. // use JavaScript implementation
  955. var state = pki.rsa.createKeyPairGenerationState(bits, e, options);
  956. if(!callback) {
  957. pki.rsa.stepKeyPairGenerationState(state, 0);
  958. return state.keys;
  959. }
  960. _generateKeyPair(state, options, callback);
  961. };
  962. /**
  963. * Sets an RSA public key from BigIntegers modulus and exponent.
  964. *
  965. * @param n the modulus.
  966. * @param e the exponent.
  967. *
  968. * @return the public key.
  969. */
  970. pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {
  971. var key = {
  972. n: n,
  973. e: e
  974. };
  975. /**
  976. * Encrypts the given data with this public key. Newer applications
  977. * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for
  978. * legacy applications.
  979. *
  980. * @param data the byte string to encrypt.
  981. * @param scheme the encryption scheme to use:
  982. * 'RSAES-PKCS1-V1_5' (default),
  983. * 'RSA-OAEP',
  984. * 'RAW', 'NONE', or null to perform raw RSA encryption,
  985. * an object with an 'encode' property set to a function
  986. * with the signature 'function(data, key)' that returns
  987. * a binary-encoded string representing the encoded data.
  988. * @param schemeOptions any scheme-specific options.
  989. *
  990. * @return the encrypted byte string.
  991. */
  992. key.encrypt = function(data, scheme, schemeOptions) {
  993. if(typeof scheme === 'string') {
  994. scheme = scheme.toUpperCase();
  995. } else if(scheme === undefined) {
  996. scheme = 'RSAES-PKCS1-V1_5';
  997. }
  998. if(scheme === 'RSAES-PKCS1-V1_5') {
  999. scheme = {
  1000. encode: function(m, key, pub) {
  1001. return _encodePkcs1_v1_5(m, key, 0x02).getBytes();
  1002. }
  1003. };
  1004. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  1005. scheme = {
  1006. encode: function(m, key) {
  1007. return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);
  1008. }
  1009. };
  1010. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  1011. scheme = {encode: function(e) {return e;}};
  1012. } else if(typeof scheme === 'string') {
  1013. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  1014. }
  1015. // do scheme-based encoding then rsa encryption
  1016. var e = scheme.encode(data, key, true);
  1017. return pki.rsa.encrypt(e, key, true);
  1018. };
  1019. /**
  1020. * Verifies the given signature against the given digest.
  1021. *
  1022. * PKCS#1 supports multiple (currently two) signature schemes:
  1023. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  1024. *
  1025. * By default this implementation uses the "old scheme", i.e.
  1026. * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the
  1027. * signature is an OCTET STRING that holds a DigestInfo.
  1028. *
  1029. * DigestInfo ::= SEQUENCE {
  1030. * digestAlgorithm DigestAlgorithmIdentifier,
  1031. * digest Digest
  1032. * }
  1033. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  1034. * Digest ::= OCTET STRING
  1035. *
  1036. * To perform PSS signature verification, provide an instance
  1037. * of Forge PSS object as the scheme parameter.
  1038. *
  1039. * @param digest the message digest hash to compare against the signature,
  1040. * as a binary-encoded string.
  1041. * @param signature the signature to verify, as a binary-encoded string.
  1042. * @param scheme signature verification scheme to use:
  1043. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  1044. * a Forge PSS object for RSASSA-PSS,
  1045. * 'NONE' or null for none, DigestInfo will not be expected, but
  1046. * PKCS#1 v1.5 padding will still be used.
  1047. * @param options optional verify options
  1048. * _parseAllDigestBytes testing flag to control parsing of all
  1049. * digest bytes. Unsupported and not for general usage.
  1050. * (default: true)
  1051. *
  1052. * @return true if the signature was verified, false if not.
  1053. */
  1054. key.verify = function(digest, signature, scheme, options) {
  1055. if(typeof scheme === 'string') {
  1056. scheme = scheme.toUpperCase();
  1057. } else if(scheme === undefined) {
  1058. scheme = 'RSASSA-PKCS1-V1_5';
  1059. }
  1060. if(options === undefined) {
  1061. options = {
  1062. _parseAllDigestBytes: true
  1063. };
  1064. }
  1065. if(!('_parseAllDigestBytes' in options)) {
  1066. options._parseAllDigestBytes = true;
  1067. }
  1068. if(scheme === 'RSASSA-PKCS1-V1_5') {
  1069. scheme = {
  1070. verify: function(digest, d) {
  1071. // remove padding
  1072. d = _decodePkcs1_v1_5(d, key, true);
  1073. // d is ASN.1 BER-encoded DigestInfo
  1074. var obj = asn1.fromDer(d, {
  1075. parseAllBytes: options._parseAllDigestBytes
  1076. });
  1077. // validate DigestInfo
  1078. var capture = {};
  1079. var errors = [];
  1080. if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {
  1081. var error = new Error(
  1082. 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
  1083. 'DigestInfo value.');
  1084. error.errors = errors;
  1085. throw error;
  1086. }
  1087. // check hash algorithm identifier
  1088. // see PKCS1-v1-5DigestAlgorithms in RFC 8017
  1089. // FIXME: add support to vaidator for strict value choices
  1090. var oid = asn1.derToOid(capture.algorithmIdentifier);
  1091. if(!(oid === forge.oids.md2 ||
  1092. oid === forge.oids.md5 ||
  1093. oid === forge.oids.sha1 ||
  1094. oid === forge.oids.sha224 ||
  1095. oid === forge.oids.sha256 ||
  1096. oid === forge.oids.sha384 ||
  1097. oid === forge.oids.sha512 ||
  1098. oid === forge.oids['sha512-224'] ||
  1099. oid === forge.oids['sha512-256'])) {
  1100. var error = new Error(
  1101. 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');
  1102. error.oid = oid;
  1103. throw error;
  1104. }
  1105. // special check for md2 and md5 that NULL parameters exist
  1106. if(oid === forge.oids.md2 || oid === forge.oids.md5) {
  1107. if(!('parameters' in capture)) {
  1108. throw new Error(
  1109. 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
  1110. 'DigestInfo value. ' +
  1111. 'Missing algorithm identifer NULL parameters.');
  1112. }
  1113. }
  1114. // compare the given digest to the decrypted one
  1115. return digest === capture.digest;
  1116. }
  1117. };
  1118. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  1119. scheme = {
  1120. verify: function(digest, d) {
  1121. // remove padding
  1122. d = _decodePkcs1_v1_5(d, key, true);
  1123. return digest === d;
  1124. }
  1125. };
  1126. }
  1127. // do rsa decryption w/o any decoding, then verify -- which does decoding
  1128. var d = pki.rsa.decrypt(signature, key, true, false);
  1129. return scheme.verify(digest, d, key.n.bitLength());
  1130. };
  1131. return key;
  1132. };
  1133. /**
  1134. * Sets an RSA private key from BigIntegers modulus, exponent, primes,
  1135. * prime exponents, and modular multiplicative inverse.
  1136. *
  1137. * @param n the modulus.
  1138. * @param e the public exponent.
  1139. * @param d the private exponent ((inverse of e) mod n).
  1140. * @param p the first prime.
  1141. * @param q the second prime.
  1142. * @param dP exponent1 (d mod (p-1)).
  1143. * @param dQ exponent2 (d mod (q-1)).
  1144. * @param qInv ((inverse of q) mod p)
  1145. *
  1146. * @return the private key.
  1147. */
  1148. pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(
  1149. n, e, d, p, q, dP, dQ, qInv) {
  1150. var key = {
  1151. n: n,
  1152. e: e,
  1153. d: d,
  1154. p: p,
  1155. q: q,
  1156. dP: dP,
  1157. dQ: dQ,
  1158. qInv: qInv
  1159. };
  1160. /**
  1161. * Decrypts the given data with this private key. The decryption scheme
  1162. * must match the one used to encrypt the data.
  1163. *
  1164. * @param data the byte string to decrypt.
  1165. * @param scheme the decryption scheme to use:
  1166. * 'RSAES-PKCS1-V1_5' (default),
  1167. * 'RSA-OAEP',
  1168. * 'RAW', 'NONE', or null to perform raw RSA decryption.
  1169. * @param schemeOptions any scheme-specific options.
  1170. *
  1171. * @return the decrypted byte string.
  1172. */
  1173. key.decrypt = function(data, scheme, schemeOptions) {
  1174. if(typeof scheme === 'string') {
  1175. scheme = scheme.toUpperCase();
  1176. } else if(scheme === undefined) {
  1177. scheme = 'RSAES-PKCS1-V1_5';
  1178. }
  1179. // do rsa decryption w/o any decoding
  1180. var d = pki.rsa.decrypt(data, key, false, false);
  1181. if(scheme === 'RSAES-PKCS1-V1_5') {
  1182. scheme = {decode: _decodePkcs1_v1_5};
  1183. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  1184. scheme = {
  1185. decode: function(d, key) {
  1186. return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);
  1187. }
  1188. };
  1189. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  1190. scheme = {decode: function(d) {return d;}};
  1191. } else {
  1192. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  1193. }
  1194. // decode according to scheme
  1195. return scheme.decode(d, key, false);
  1196. };
  1197. /**
  1198. * Signs the given digest, producing a signature.
  1199. *
  1200. * PKCS#1 supports multiple (currently two) signature schemes:
  1201. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  1202. *
  1203. * By default this implementation uses the "old scheme", i.e.
  1204. * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide
  1205. * an instance of Forge PSS object as the scheme parameter.
  1206. *
  1207. * @param md the message digest object with the hash to sign.
  1208. * @param scheme the signature scheme to use:
  1209. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  1210. * a Forge PSS object for RSASSA-PSS,
  1211. * 'NONE' or null for none, DigestInfo will not be used but
  1212. * PKCS#1 v1.5 padding will still be used.
  1213. *
  1214. * @return the signature as a byte string.
  1215. */
  1216. key.sign = function(md, scheme) {
  1217. /* Note: The internal implementation of RSA operations is being
  1218. transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy
  1219. code like the use of an encoding block identifier 'bt' will eventually
  1220. be removed. */
  1221. // private key operation
  1222. var bt = false;
  1223. if(typeof scheme === 'string') {
  1224. scheme = scheme.toUpperCase();
  1225. }
  1226. if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {
  1227. scheme = {encode: emsaPkcs1v15encode};
  1228. bt = 0x01;
  1229. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  1230. scheme = {encode: function() {return md;}};
  1231. bt = 0x01;
  1232. }
  1233. // encode and then encrypt
  1234. var d = scheme.encode(md, key.n.bitLength());
  1235. return pki.rsa.encrypt(d, key, bt);
  1236. };
  1237. return key;
  1238. };
  1239. /**
  1240. * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.
  1241. *
  1242. * @param rsaKey the ASN.1 RSAPrivateKey.
  1243. *
  1244. * @return the ASN.1 PrivateKeyInfo.
  1245. */
  1246. pki.wrapRsaPrivateKey = function(rsaKey) {
  1247. // PrivateKeyInfo
  1248. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1249. // version (0)
  1250. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1251. asn1.integerToDer(0).getBytes()),
  1252. // privateKeyAlgorithm
  1253. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1254. asn1.create(
  1255. asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1256. asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
  1257. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  1258. ]),
  1259. // PrivateKey
  1260. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  1261. asn1.toDer(rsaKey).getBytes())
  1262. ]);
  1263. };
  1264. /**
  1265. * Converts a private key from an ASN.1 object.
  1266. *
  1267. * @param obj the ASN.1 representation of a PrivateKeyInfo containing an
  1268. * RSAPrivateKey or an RSAPrivateKey.
  1269. *
  1270. * @return the private key.
  1271. */
  1272. pki.privateKeyFromAsn1 = function(obj) {
  1273. // get PrivateKeyInfo
  1274. var capture = {};
  1275. var errors = [];
  1276. if(asn1.validate(obj, privateKeyValidator, capture, errors)) {
  1277. obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));
  1278. }
  1279. // get RSAPrivateKey
  1280. capture = {};
  1281. errors = [];
  1282. if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
  1283. var error = new Error('Cannot read private key. ' +
  1284. 'ASN.1 object does not contain an RSAPrivateKey.');
  1285. error.errors = errors;
  1286. throw error;
  1287. }
  1288. // Note: Version is currently ignored.
  1289. // capture.privateKeyVersion
  1290. // FIXME: inefficient, get a BigInteger that uses byte strings
  1291. var n, e, d, p, q, dP, dQ, qInv;
  1292. n = forge.util.createBuffer(capture.privateKeyModulus).toHex();
  1293. e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();
  1294. d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
  1295. p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();
  1296. q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();
  1297. dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();
  1298. dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();
  1299. qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();
  1300. // set private key
  1301. return pki.setRsaPrivateKey(
  1302. new BigInteger(n, 16),
  1303. new BigInteger(e, 16),
  1304. new BigInteger(d, 16),
  1305. new BigInteger(p, 16),
  1306. new BigInteger(q, 16),
  1307. new BigInteger(dP, 16),
  1308. new BigInteger(dQ, 16),
  1309. new BigInteger(qInv, 16));
  1310. };
  1311. /**
  1312. * Converts a private key to an ASN.1 RSAPrivateKey.
  1313. *
  1314. * @param key the private key.
  1315. *
  1316. * @return the ASN.1 representation of an RSAPrivateKey.
  1317. */
  1318. pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {
  1319. // RSAPrivateKey
  1320. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1321. // version (0 = only 2 primes, 1 multiple primes)
  1322. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1323. asn1.integerToDer(0).getBytes()),
  1324. // modulus (n)
  1325. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1326. _bnToBytes(key.n)),
  1327. // publicExponent (e)
  1328. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1329. _bnToBytes(key.e)),
  1330. // privateExponent (d)
  1331. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1332. _bnToBytes(key.d)),
  1333. // privateKeyPrime1 (p)
  1334. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1335. _bnToBytes(key.p)),
  1336. // privateKeyPrime2 (q)
  1337. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1338. _bnToBytes(key.q)),
  1339. // privateKeyExponent1 (dP)
  1340. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1341. _bnToBytes(key.dP)),
  1342. // privateKeyExponent2 (dQ)
  1343. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1344. _bnToBytes(key.dQ)),
  1345. // coefficient (qInv)
  1346. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1347. _bnToBytes(key.qInv))
  1348. ]);
  1349. };
  1350. /**
  1351. * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.
  1352. *
  1353. * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.
  1354. *
  1355. * @return the public key.
  1356. */
  1357. pki.publicKeyFromAsn1 = function(obj) {
  1358. // get SubjectPublicKeyInfo
  1359. var capture = {};
  1360. var errors = [];
  1361. if(asn1.validate(obj, publicKeyValidator, capture, errors)) {
  1362. // get oid
  1363. var oid = asn1.derToOid(capture.publicKeyOid);
  1364. if(oid !== pki.oids.rsaEncryption) {
  1365. var error = new Error('Cannot read public key. Unknown OID.');
  1366. error.oid = oid;
  1367. throw error;
  1368. }
  1369. obj = capture.rsaPublicKey;
  1370. }
  1371. // get RSA params
  1372. errors = [];
  1373. if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {
  1374. var error = new Error('Cannot read public key. ' +
  1375. 'ASN.1 object does not contain an RSAPublicKey.');
  1376. error.errors = errors;
  1377. throw error;
  1378. }
  1379. // FIXME: inefficient, get a BigInteger that uses byte strings
  1380. var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();
  1381. var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();
  1382. // set public key
  1383. return pki.setRsaPublicKey(
  1384. new BigInteger(n, 16),
  1385. new BigInteger(e, 16));
  1386. };
  1387. /**
  1388. * Converts a public key to an ASN.1 SubjectPublicKeyInfo.
  1389. *
  1390. * @param key the public key.
  1391. *
  1392. * @return the asn1 representation of a SubjectPublicKeyInfo.
  1393. */
  1394. pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {
  1395. // SubjectPublicKeyInfo
  1396. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1397. // AlgorithmIdentifier
  1398. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1399. // algorithm
  1400. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1401. asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),
  1402. // parameters (null)
  1403. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  1404. ]),
  1405. // subjectPublicKey
  1406. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [
  1407. pki.publicKeyToRSAPublicKey(key)
  1408. ])
  1409. ]);
  1410. };
  1411. /**
  1412. * Converts a public key to an ASN.1 RSAPublicKey.
  1413. *
  1414. * @param key the public key.
  1415. *
  1416. * @return the asn1 representation of a RSAPublicKey.
  1417. */
  1418. pki.publicKeyToRSAPublicKey = function(key) {
  1419. // RSAPublicKey
  1420. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1421. // modulus (n)
  1422. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1423. _bnToBytes(key.n)),
  1424. // publicExponent (e)
  1425. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  1426. _bnToBytes(key.e))
  1427. ]);
  1428. };
  1429. /**
  1430. * Encodes a message using PKCS#1 v1.5 padding.
  1431. *
  1432. * @param m the message to encode.
  1433. * @param key the RSA key to use.
  1434. * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02
  1435. * (for encryption).
  1436. *
  1437. * @return the padded byte buffer.
  1438. */
  1439. function _encodePkcs1_v1_5(m, key, bt) {
  1440. var eb = forge.util.createBuffer();
  1441. // get the length of the modulus in bytes
  1442. var k = Math.ceil(key.n.bitLength() / 8);
  1443. /* use PKCS#1 v1.5 padding */
  1444. if(m.length > (k - 11)) {
  1445. var error = new Error('Message is too long for PKCS#1 v1.5 padding.');
  1446. error.length = m.length;
  1447. error.max = k - 11;
  1448. throw error;
  1449. }
  1450. /* A block type BT, a padding string PS, and the data D shall be
  1451. formatted into an octet string EB, the encryption block:
  1452. EB = 00 || BT || PS || 00 || D
  1453. The block type BT shall be a single octet indicating the structure of
  1454. the encryption block. For this version of the document it shall have
  1455. value 00, 01, or 02. For a private-key operation, the block type
  1456. shall be 00 or 01. For a public-key operation, it shall be 02.
  1457. The padding string PS shall consist of k-3-||D|| octets. For block
  1458. type 00, the octets shall have value 00; for block type 01, they
  1459. shall have value FF; and for block type 02, they shall be
  1460. pseudorandomly generated and nonzero. This makes the length of the
  1461. encryption block EB equal to k. */
  1462. // build the encryption block
  1463. eb.putByte(0x00);
  1464. eb.putByte(bt);
  1465. // create the padding
  1466. var padNum = k - 3 - m.length;
  1467. var padByte;
  1468. // private key op
  1469. if(bt === 0x00 || bt === 0x01) {
  1470. padByte = (bt === 0x00) ? 0x00 : 0xFF;
  1471. for(var i = 0; i < padNum; ++i) {
  1472. eb.putByte(padByte);
  1473. }
  1474. } else {
  1475. // public key op
  1476. // pad with random non-zero values
  1477. while(padNum > 0) {
  1478. var numZeros = 0;
  1479. var padBytes = forge.random.getBytes(padNum);
  1480. for(var i = 0; i < padNum; ++i) {
  1481. padByte = padBytes.charCodeAt(i);
  1482. if(padByte === 0) {
  1483. ++numZeros;
  1484. } else {
  1485. eb.putByte(padByte);
  1486. }
  1487. }
  1488. padNum = numZeros;
  1489. }
  1490. }
  1491. // zero followed by message
  1492. eb.putByte(0x00);
  1493. eb.putBytes(m);
  1494. return eb;
  1495. }
  1496. /**
  1497. * Decodes a message using PKCS#1 v1.5 padding.
  1498. *
  1499. * @param em the message to decode.
  1500. * @param key the RSA key to use.
  1501. * @param pub true if the key is a public key, false if it is private.
  1502. * @param ml the message length, if specified.
  1503. *
  1504. * @return the decoded bytes.
  1505. */
  1506. function _decodePkcs1_v1_5(em, key, pub, ml) {
  1507. // get the length of the modulus in bytes
  1508. var k = Math.ceil(key.n.bitLength() / 8);
  1509. /* It is an error if any of the following conditions occurs:
  1510. 1. The encryption block EB cannot be parsed unambiguously.
  1511. 2. The padding string PS consists of fewer than eight octets
  1512. or is inconsisent with the block type BT.
  1513. 3. The decryption process is a public-key operation and the block
  1514. type BT is not 00 or 01, or the decryption process is a
  1515. private-key operation and the block type is not 02.
  1516. */
  1517. // parse the encryption block
  1518. var eb = forge.util.createBuffer(em);
  1519. var first = eb.getByte();
  1520. var bt = eb.getByte();
  1521. if(first !== 0x00 ||
  1522. (pub && bt !== 0x00 && bt !== 0x01) ||
  1523. (!pub && bt != 0x02) ||
  1524. (pub && bt === 0x00 && typeof(ml) === 'undefined')) {
  1525. throw new Error('Encryption block is invalid.');
  1526. }
  1527. var padNum = 0;
  1528. if(bt === 0x00) {
  1529. // check all padding bytes for 0x00
  1530. padNum = k - 3 - ml;
  1531. for(var i = 0; i < padNum; ++i) {
  1532. if(eb.getByte() !== 0x00) {
  1533. throw new Error('Encryption block is invalid.');
  1534. }
  1535. }
  1536. } else if(bt === 0x01) {
  1537. // find the first byte that isn't 0xFF, should be after all padding
  1538. padNum = 0;
  1539. while(eb.length() > 1) {
  1540. if(eb.getByte() !== 0xFF) {
  1541. --eb.read;
  1542. break;
  1543. }
  1544. ++padNum;
  1545. }
  1546. } else if(bt === 0x02) {
  1547. // look for 0x00 byte
  1548. padNum = 0;
  1549. while(eb.length() > 1) {
  1550. if(eb.getByte() === 0x00) {
  1551. --eb.read;
  1552. break;
  1553. }
  1554. ++padNum;
  1555. }
  1556. }
  1557. // zero must be 0x00 and padNum must be (k - 3 - message length)
  1558. var zero = eb.getByte();
  1559. if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {
  1560. throw new Error('Encryption block is invalid.');
  1561. }
  1562. return eb.getBytes();
  1563. }
  1564. /**
  1565. * Runs the key-generation algorithm asynchronously, either in the background
  1566. * via Web Workers, or using the main thread and setImmediate.
  1567. *
  1568. * @param state the key-pair generation state.
  1569. * @param [options] options for key-pair generation:
  1570. * workerScript the worker script URL.
  1571. * workers the number of web workers (if supported) to use,
  1572. * (default: 2, -1 to use estimated cores minus one).
  1573. * workLoad the size of the work load, ie: number of possible prime
  1574. * numbers for each web worker to check per work assignment,
  1575. * (default: 100).
  1576. * @param callback(err, keypair) called once the operation completes.
  1577. */
  1578. function _generateKeyPair(state, options, callback) {
  1579. if(typeof options === 'function') {
  1580. callback = options;
  1581. options = {};
  1582. }
  1583. options = options || {};
  1584. var opts = {
  1585. algorithm: {
  1586. name: options.algorithm || 'PRIMEINC',
  1587. options: {
  1588. workers: options.workers || 2,
  1589. workLoad: options.workLoad || 100,
  1590. workerScript: options.workerScript
  1591. }
  1592. }
  1593. };
  1594. if('prng' in options) {
  1595. opts.prng = options.prng;
  1596. }
  1597. generate();
  1598. function generate() {
  1599. // find p and then q (done in series to simplify)
  1600. getPrime(state.pBits, function(err, num) {
  1601. if(err) {
  1602. return callback(err);
  1603. }
  1604. state.p = num;
  1605. if(state.q !== null) {
  1606. return finish(err, state.q);
  1607. }
  1608. getPrime(state.qBits, finish);
  1609. });
  1610. }
  1611. function getPrime(bits, callback) {
  1612. forge.prime.generateProbablePrime(bits, opts, callback);
  1613. }
  1614. function finish(err, num) {
  1615. if(err) {
  1616. return callback(err);
  1617. }
  1618. // set q
  1619. state.q = num;
  1620. // ensure p is larger than q (swap them if not)
  1621. if(state.p.compareTo(state.q) < 0) {
  1622. var tmp = state.p;
  1623. state.p = state.q;
  1624. state.q = tmp;
  1625. }
  1626. // ensure p is coprime with e
  1627. if(state.p.subtract(BigInteger.ONE).gcd(state.e)
  1628. .compareTo(BigInteger.ONE) !== 0) {
  1629. state.p = null;
  1630. generate();
  1631. return;
  1632. }
  1633. // ensure q is coprime with e
  1634. if(state.q.subtract(BigInteger.ONE).gcd(state.e)
  1635. .compareTo(BigInteger.ONE) !== 0) {
  1636. state.q = null;
  1637. getPrime(state.qBits, finish);
  1638. return;
  1639. }
  1640. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  1641. state.p1 = state.p.subtract(BigInteger.ONE);
  1642. state.q1 = state.q.subtract(BigInteger.ONE);
  1643. state.phi = state.p1.multiply(state.q1);
  1644. // ensure e and phi are coprime
  1645. if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {
  1646. // phi and e aren't coprime, so generate a new p and q
  1647. state.p = state.q = null;
  1648. generate();
  1649. return;
  1650. }
  1651. // create n, ensure n is has the right number of bits
  1652. state.n = state.p.multiply(state.q);
  1653. if(state.n.bitLength() !== state.bits) {
  1654. // failed, get new q
  1655. state.q = null;
  1656. getPrime(state.qBits, finish);
  1657. return;
  1658. }
  1659. // set keys
  1660. var d = state.e.modInverse(state.phi);
  1661. state.keys = {
  1662. privateKey: pki.rsa.setPrivateKey(
  1663. state.n, state.e, d, state.p, state.q,
  1664. d.mod(state.p1), d.mod(state.q1),
  1665. state.q.modInverse(state.p)),
  1666. publicKey: pki.rsa.setPublicKey(state.n, state.e)
  1667. };
  1668. callback(null, state.keys);
  1669. }
  1670. }
  1671. /**
  1672. * Converts a positive BigInteger into 2's-complement big-endian bytes.
  1673. *
  1674. * @param b the big integer to convert.
  1675. *
  1676. * @return the bytes.
  1677. */
  1678. function _bnToBytes(b) {
  1679. // prepend 0x00 if first byte >= 0x80
  1680. var hex = b.toString(16);
  1681. if(hex[0] >= '8') {
  1682. hex = '00' + hex;
  1683. }
  1684. var bytes = forge.util.hexToBytes(hex);
  1685. // ensure integer is minimally-encoded
  1686. if(bytes.length > 1 &&
  1687. // leading 0x00 for positive integer
  1688. ((bytes.charCodeAt(0) === 0 &&
  1689. (bytes.charCodeAt(1) & 0x80) === 0) ||
  1690. // leading 0xFF for negative integer
  1691. (bytes.charCodeAt(0) === 0xFF &&
  1692. (bytes.charCodeAt(1) & 0x80) === 0x80))) {
  1693. return bytes.substr(1);
  1694. }
  1695. return bytes;
  1696. }
  1697. /**
  1698. * Returns the required number of Miller-Rabin tests to generate a
  1699. * prime with an error probability of (1/2)^80.
  1700. *
  1701. * See Handbook of Applied Cryptography Chapter 4, Table 4.4.
  1702. *
  1703. * @param bits the bit size.
  1704. *
  1705. * @return the required number of iterations.
  1706. */
  1707. function _getMillerRabinTests(bits) {
  1708. if(bits <= 100) return 27;
  1709. if(bits <= 150) return 18;
  1710. if(bits <= 200) return 15;
  1711. if(bits <= 250) return 12;
  1712. if(bits <= 300) return 9;
  1713. if(bits <= 350) return 8;
  1714. if(bits <= 400) return 7;
  1715. if(bits <= 500) return 6;
  1716. if(bits <= 600) return 5;
  1717. if(bits <= 800) return 4;
  1718. if(bits <= 1250) return 3;
  1719. return 2;
  1720. }
  1721. /**
  1722. * Performs feature detection on the Node crypto interface.
  1723. *
  1724. * @param fn the feature (function) to detect.
  1725. *
  1726. * @return true if detected, false if not.
  1727. */
  1728. function _detectNodeCrypto(fn) {
  1729. return forge.util.isNodejs && typeof _crypto[fn] === 'function';
  1730. }
  1731. /**
  1732. * Performs feature detection on the SubtleCrypto interface.
  1733. *
  1734. * @param fn the feature (function) to detect.
  1735. *
  1736. * @return true if detected, false if not.
  1737. */
  1738. function _detectSubtleCrypto(fn) {
  1739. return (typeof util.globalScope !== 'undefined' &&
  1740. typeof util.globalScope.crypto === 'object' &&
  1741. typeof util.globalScope.crypto.subtle === 'object' &&
  1742. typeof util.globalScope.crypto.subtle[fn] === 'function');
  1743. }
  1744. /**
  1745. * Performs feature detection on the deprecated Microsoft Internet Explorer
  1746. * outdated SubtleCrypto interface. This function should only be used after
  1747. * checking for the modern, standard SubtleCrypto interface.
  1748. *
  1749. * @param fn the feature (function) to detect.
  1750. *
  1751. * @return true if detected, false if not.
  1752. */
  1753. function _detectSubtleMsCrypto(fn) {
  1754. return (typeof util.globalScope !== 'undefined' &&
  1755. typeof util.globalScope.msCrypto === 'object' &&
  1756. typeof util.globalScope.msCrypto.subtle === 'object' &&
  1757. typeof util.globalScope.msCrypto.subtle[fn] === 'function');
  1758. }
  1759. function _intToUint8Array(x) {
  1760. var bytes = forge.util.hexToBytes(x.toString(16));
  1761. var buffer = new Uint8Array(bytes.length);
  1762. for(var i = 0; i < bytes.length; ++i) {
  1763. buffer[i] = bytes.charCodeAt(i);
  1764. }
  1765. return buffer;
  1766. }
  1767. function _privateKeyFromJwk(jwk) {
  1768. if(jwk.kty !== 'RSA') {
  1769. throw new Error(
  1770. 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".');
  1771. }
  1772. return pki.setRsaPrivateKey(
  1773. _base64ToBigInt(jwk.n),
  1774. _base64ToBigInt(jwk.e),
  1775. _base64ToBigInt(jwk.d),
  1776. _base64ToBigInt(jwk.p),
  1777. _base64ToBigInt(jwk.q),
  1778. _base64ToBigInt(jwk.dp),
  1779. _base64ToBigInt(jwk.dq),
  1780. _base64ToBigInt(jwk.qi));
  1781. }
  1782. function _publicKeyFromJwk(jwk) {
  1783. if(jwk.kty !== 'RSA') {
  1784. throw new Error('Key algorithm must be "RSA".');
  1785. }
  1786. return pki.setRsaPublicKey(
  1787. _base64ToBigInt(jwk.n),
  1788. _base64ToBigInt(jwk.e));
  1789. }
  1790. function _base64ToBigInt(b64) {
  1791. return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);
  1792. }