You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1858 lines
56 KiB

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