source: frontend/node_modules/node-forge/lib/rsa.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

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