-
Notifications
You must be signed in to change notification settings - Fork 790
/
rsa.js
1858 lines (1705 loc) · 55.7 KB
/
rsa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Javascript implementation of basic RSA algorithms.
*
* @author Dave Longley
*
* Copyright (c) 2010-2014 Digital Bazaar, Inc.
*
* The only algorithm currently supported for PKI is RSA.
*
* An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo
* ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier
* and a subjectPublicKey of type bit string.
*
* The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
* for the algorithm, if any. In the case of RSA, there aren't any.
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
*
* AlgorithmIdentifer ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* For an RSA public key, the subjectPublicKey is:
*
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER -- e
* }
*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
*
* Version ::= INTEGER
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
* PrivateKey ::= OCTET STRING
* Attributes ::= SET OF Attribute
*
* An RSA private key as the following structure:
*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER -- (inverse of q) mod p
* }
*
* Version ::= INTEGER
*
* The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1
*/
var forge = require('./forge');
require('./asn1');
require('./jsbn');
require('./oids');
require('./pkcs1');
require('./prime');
require('./random');
require('./util');
if(typeof BigInteger === 'undefined') {
var BigInteger = forge.jsbn.BigInteger;
}
var _crypto = forge.util.isNodejs ? require('crypto') : null;
// shortcut for asn.1 API
var asn1 = forge.asn1;
// shortcut for util API
var util = forge.util;
/*
* RSA encryption and decryption, see RFC 2313.
*/
forge.pki = forge.pki || {};
module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};
var pki = forge.pki;
// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
// validator for a PrivateKeyInfo structure
var privateKeyValidator = {
// PrivateKeyInfo
name: 'PrivateKeyInfo',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// Version (INTEGER)
name: 'PrivateKeyInfo.version',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyVersion'
}, {
// privateKeyAlgorithm
name: 'PrivateKeyInfo.privateKeyAlgorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'AlgorithmIdentifier.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'privateKeyOid'
}]
}, {
// PrivateKey
name: 'PrivateKeyInfo',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OCTETSTRING,
constructed: false,
capture: 'privateKey'
}]
};
// validator for an RSA private key
var rsaPrivateKeyValidator = {
// RSAPrivateKey
name: 'RSAPrivateKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// Version (INTEGER)
name: 'RSAPrivateKey.version',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyVersion'
}, {
// modulus (n)
name: 'RSAPrivateKey.modulus',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyModulus'
}, {
// publicExponent (e)
name: 'RSAPrivateKey.publicExponent',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyPublicExponent'
}, {
// privateExponent (d)
name: 'RSAPrivateKey.privateExponent',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyPrivateExponent'
}, {
// prime1 (p)
name: 'RSAPrivateKey.prime1',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyPrime1'
}, {
// prime2 (q)
name: 'RSAPrivateKey.prime2',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyPrime2'
}, {
// exponent1 (d mod (p-1))
name: 'RSAPrivateKey.exponent1',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyExponent1'
}, {
// exponent2 (d mod (q-1))
name: 'RSAPrivateKey.exponent2',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyExponent2'
}, {
// coefficient ((inverse of q) mod p)
name: 'RSAPrivateKey.coefficient',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'privateKeyCoefficient'
}]
};
// validator for an RSA public key
var rsaPublicKeyValidator = {
// RSAPublicKey
name: 'RSAPublicKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// modulus (n)
name: 'RSAPublicKey.modulus',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'publicKeyModulus'
}, {
// publicExponent (e)
name: 'RSAPublicKey.exponent',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'publicKeyExponent'
}]
};
// validator for an SubjectPublicKeyInfo structure
// Note: Currently only works with an RSA public key
var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {
name: 'SubjectPublicKeyInfo',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'subjectPublicKeyInfo',
value: [{
name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'AlgorithmIdentifier.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'publicKeyOid'
}]
}, {
// subjectPublicKey
name: 'SubjectPublicKeyInfo.subjectPublicKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
value: [{
// RSAPublicKey
name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
optional: true,
captureAsn1: 'rsaPublicKey'
}]
}]
};
/**
* Wrap digest in DigestInfo object.
*
* This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.
*
* DigestInfo ::= SEQUENCE {
* digestAlgorithm DigestAlgorithmIdentifier,
* digest Digest
* }
*
* DigestAlgorithmIdentifier ::= AlgorithmIdentifier
* Digest ::= OCTET STRING
*
* @param md the message digest object with the hash to sign.
*
* @return the encoded message (ready for RSA encrytion)
*/
var emsaPkcs1v15encode = function(md) {
// get the oid for the algorithm
var oid;
if(md.algorithm in pki.oids) {
oid = pki.oids[md.algorithm];
} else {
var error = new Error('Unknown message digest algorithm.');
error.algorithm = md.algorithm;
throw error;
}
var oidBytes = asn1.oidToDer(oid).getBytes();
// create the digest info
var digestInfo = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var digestAlgorithm = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
digestAlgorithm.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));
digestAlgorithm.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));
var digest = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,
false, md.digest().getBytes());
digestInfo.value.push(digestAlgorithm);
digestInfo.value.push(digest);
// encode digest info
return asn1.toDer(digestInfo).getBytes();
};
/**
* Performs x^c mod n (RSA encryption or decryption operation).
*
* @param x the number to raise and mod.
* @param key the key to use.
* @param pub true if the key is public, false if private.
*
* @return the result of x^c mod n.
*/
var _modPow = function(x, key, pub) {
if(pub) {
return x.modPow(key.e, key.n);
}
if(!key.p || !key.q) {
// allow calculation without CRT params (slow)
return x.modPow(key.d, key.n);
}
// pre-compute dP, dQ, and qInv if necessary
if(!key.dP) {
key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
}
if(!key.dQ) {
key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
}
if(!key.qInv) {
key.qInv = key.q.modInverse(key.p);
}
/* Chinese remainder theorem (CRT) states:
Suppose n1, n2, ..., nk are positive integers which are pairwise
coprime (n1 and n2 have no common factors other than 1). For any
integers x1, x2, ..., xk there exists an integer x solving the
system of simultaneous congruences (where ~= means modularly
congruent so a ~= b mod n means a mod n = b mod n):
x ~= x1 mod n1
x ~= x2 mod n2
...
x ~= xk mod nk
This system of congruences has a single simultaneous solution x
between 0 and n - 1. Furthermore, each xk solution and x itself
is congruent modulo the product n = n1*n2*...*nk.
So x1 mod n = x2 mod n = xk mod n = x mod n.
The single simultaneous solution x can be solved with the following
equation:
x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.
Where x is less than n, xi = x mod ni.
For RSA we are only concerned with k = 2. The modulus n = pq, where
p and q are coprime. The RSA decryption algorithm is:
y = x^d mod n
Given the above:
x1 = x^d mod p
r1 = n/p = q
s1 = q^-1 mod p
x2 = x^d mod q
r2 = n/q = p
s2 = p^-1 mod q
So y = (x1r1s1 + x2r2s2) mod n
= ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n
According to Fermat's Little Theorem, if the modulus P is prime,
for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.
Since A is not divisible by P it follows that if:
N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:
A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort
to calculate). In order to calculate x^d mod p more quickly the
exponent d mod (p - 1) is stored in the RSA private key (the same
is done for x^d mod q). These values are referred to as dP and dQ
respectively. Therefore we now have:
y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n
Since we'll be reducing x^dP by modulo p (same for q) we can also
reduce x by p (and q respectively) before hand. Therefore, let
xp = ((x mod p)^dP mod p), and
xq = ((x mod q)^dQ mod q), yielding:
y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n
This can be further reduced to a simple algorithm that only
requires 1 inverse (the q inverse is used) to be used and stored.
The algorithm is called Garner's algorithm. If qInv is the
inverse of q, we simply calculate:
y = (qInv*(xp - xq) mod p) * q + xq
However, there are two further complications. First, we need to
ensure that xp > xq to prevent signed BigIntegers from being used
so we add p until this is true (since we will be mod'ing with
p anyway). Then, there is a known timing attack on algorithms
using the CRT. To mitigate this risk, "cryptographic blinding"
should be used. This requires simply generating a random number r
between 0 and n-1 and its inverse and multiplying x by r^e before
calculating y and then multiplying y by r^-1 afterwards. Note that
r must be coprime with n (gcd(r, n) === 1) in order to have an
inverse.
*/
// cryptographic blinding
var r;
do {
r = new BigInteger(
forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),
16);
} while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));
x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);
// calculate xp and xq
var xp = x.mod(key.p).modPow(key.dP, key.p);
var xq = x.mod(key.q).modPow(key.dQ, key.q);
// xp must be larger than xq to avoid signed bit usage
while(xp.compareTo(xq) < 0) {
xp = xp.add(key.p);
}
// do last step
var y = xp.subtract(xq)
.multiply(key.qInv).mod(key.p)
.multiply(key.q).add(xq);
// remove effect of random for cryptographic blinding
y = y.multiply(r.modInverse(key.n)).mod(key.n);
return y;
};
/**
* NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or
* 'encrypt' on a public key object instead.
*
* Performs RSA encryption.
*
* The parameter bt controls whether to put padding bytes before the
* message passed in. Set bt to either true or false to disable padding
* completely (in order to handle e.g. EMSA-PSS encoding seperately before),
* signaling whether the encryption operation is a public key operation
* (i.e. encrypting data) or not, i.e. private key operation (data signing).
*
* For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01
* (for signing) or 0x02 (for encryption). The key operation mode (private
* or public) is derived from this flag in that case).
*
* @param m the message to encrypt as a byte string.
* @param key the RSA key to use.
* @param bt for PKCS#1 v1.5 padding, the block type to use
* (0x01 for private key, 0x02 for public),
* to disable padding: true = public key, false = private key.
*
* @return the encrypted bytes as a string.
*/
pki.rsa.encrypt = function(m, key, bt) {
var pub = bt;
var eb;
// get the length of the modulus in bytes
var k = Math.ceil(key.n.bitLength() / 8);
if(bt !== false && bt !== true) {
// legacy, default to PKCS#1 v1.5 padding
pub = (bt === 0x02);
eb = _encodePkcs1_v1_5(m, key, bt);
} else {
eb = forge.util.createBuffer();
eb.putBytes(m);
}
// load encryption block as big integer 'x'
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
var x = new BigInteger(eb.toHex(), 16);
// do RSA encryption
var y = _modPow(x, key, pub);
// convert y into the encrypted data byte string, if y is shorter in
// bytes than k, then prepend zero bytes to fill up ed
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
var yhex = y.toString(16);
var ed = forge.util.createBuffer();
var zeros = k - Math.ceil(yhex.length / 2);
while(zeros > 0) {
ed.putByte(0x00);
--zeros;
}
ed.putBytes(forge.util.hexToBytes(yhex));
return ed.getBytes();
};
/**
* NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or
* 'verify' on a public key object instead.
*
* Performs RSA decryption.
*
* The parameter ml controls whether to apply PKCS#1 v1.5 padding
* or not. Set ml = false to disable padding removal completely
* (in order to handle e.g. EMSA-PSS later on) and simply pass back
* the RSA encryption block.
*
* @param ed the encrypted data to decrypt in as a byte string.
* @param key the RSA key to use.
* @param pub true for a public key operation, false for private.
* @param ml the message length, if known, false to disable padding.
*
* @return the decrypted message as a byte string.
*/
pki.rsa.decrypt = function(ed, key, pub, ml) {
// get the length of the modulus in bytes
var k = Math.ceil(key.n.bitLength() / 8);
// error if the length of the encrypted data ED is not k
if(ed.length !== k) {
var error = new Error('Encrypted message length is invalid.');
error.length = ed.length;
error.expected = k;
throw error;
}
// convert encrypted data into a big integer
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);
// y must be less than the modulus or it wasn't the result of
// a previous mod operation (encryption) using that modulus
if(y.compareTo(key.n) >= 0) {
throw new Error('Encrypted message is invalid.');
}
// do RSA decryption
var x = _modPow(y, key, pub);
// create the encryption block, if x is shorter in bytes than k, then
// prepend zero bytes to fill up eb
// FIXME: hex conversion inefficient, get BigInteger w/byte strings
var xhex = x.toString(16);
var eb = forge.util.createBuffer();
var zeros = k - Math.ceil(xhex.length / 2);
while(zeros > 0) {
eb.putByte(0x00);
--zeros;
}
eb.putBytes(forge.util.hexToBytes(xhex));
if(ml !== false) {
// legacy, default to PKCS#1 v1.5 padding
return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
}
// return message
return eb.getBytes();
};
/**
* Creates an RSA key-pair generation state object. It is used to allow
* key-generation to be performed in steps. It also allows for a UI to
* display progress updates.
*
* @param bits the size for the private key in bits, defaults to 2048.
* @param e the public exponent to use, defaults to 65537 (0x10001).
* @param [options] the options to use.
* prng a custom crypto-secure pseudo-random number generator to use,
* that must define "getBytesSync".
* algorithm the algorithm to use (default: 'PRIMEINC').
*
* @return the state object to use to generate the key-pair.
*/
pki.rsa.createKeyPairGenerationState = function(bits, e, options) {
// TODO: migrate step-based prime generation code to forge.prime
// set default bits
if(typeof(bits) === 'string') {
bits = parseInt(bits, 10);
}
bits = bits || 2048;
// create prng with api that matches BigInteger secure random
options = options || {};
var prng = options.prng || forge.random;
var rng = {
// x is an array to fill with bytes
nextBytes: function(x) {
var b = prng.getBytesSync(x.length);
for(var i = 0; i < x.length; ++i) {
x[i] = b.charCodeAt(i);
}
}
};
var algorithm = options.algorithm || 'PRIMEINC';
// create PRIMEINC algorithm state
var rval;
if(algorithm === 'PRIMEINC') {
rval = {
algorithm: algorithm,
state: 0,
bits: bits,
rng: rng,
eInt: e || 65537,
e: new BigInteger(null),
p: null,
q: null,
qBits: bits >> 1,
pBits: bits - (bits >> 1),
pqState: 0,
num: null,
keys: null
};
rval.e.fromInt(rval.eInt);
} else {
throw new Error('Invalid key generation algorithm: ' + algorithm);
}
return rval;
};
/**
* Attempts to runs the key-generation algorithm for at most n seconds
* (approximately) using the given state. When key-generation has completed,
* the keys will be stored in state.keys.
*
* To use this function to update a UI while generating a key or to prevent
* causing browser lockups/warnings, set "n" to a value other than 0. A
* simple pattern for generating a key and showing a progress indicator is:
*
* var state = pki.rsa.createKeyPairGenerationState(2048);
* var step = function() {
* // step key-generation, run algorithm for 100 ms, repeat
* if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {
* setTimeout(step, 1);
* } else {
* // key-generation complete
* // TODO: turn off progress indicator here
* // TODO: use the generated key-pair in "state.keys"
* }
* };
* // TODO: turn on progress indicator here
* setTimeout(step, 0);
*
* @param state the state to use.
* @param n the maximum number of milliseconds to run the algorithm for, 0
* to run the algorithm to completion.
*
* @return true if the key-generation completed, false if not.
*/
pki.rsa.stepKeyPairGenerationState = function(state, n) {
// set default algorithm if not set
if(!('algorithm' in state)) {
state.algorithm = 'PRIMEINC';
}
// TODO: migrate step-based prime generation code to forge.prime
// TODO: abstract as PRIMEINC algorithm
// do key generation (based on Tom Wu's rsa.js, see jsbn.js license)
// with some minor optimizations and designed to run in steps
// local state vars
var THIRTY = new BigInteger(null);
THIRTY.fromInt(30);
var deltaIdx = 0;
var op_or = function(x, y) {return x | y;};
// keep stepping until time limit is reached or done
var t1 = +new Date();
var t2;
var total = 0;
while(state.keys === null && (n <= 0 || total < n)) {
// generate p or q
if(state.state === 0) {
/* Note: All primes are of the form:
30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i
When we generate a random number, we always align it at 30k + 1. Each
time the number is determined not to be prime we add to get to the
next 'i', eg: if the number was at 30k + 1 we add 6. */
var bits = (state.p === null) ? state.pBits : state.qBits;
var bits1 = bits - 1;
// get a random number
if(state.pqState === 0) {
state.num = new BigInteger(bits, state.rng);
// force MSB set
if(!state.num.testBit(bits1)) {
state.num.bitwiseTo(
BigInteger.ONE.shiftLeft(bits1), op_or, state.num);
}
// align number on 30k+1 boundary
state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
deltaIdx = 0;
++state.pqState;
} else if(state.pqState === 1) {
// try to make the number a prime
if(state.num.bitLength() > bits) {
// overflow, try again
state.pqState = 0;
// do primality test
} else if(state.num.isProbablePrime(
_getMillerRabinTests(state.num.bitLength()))) {
++state.pqState;
} else {
// get next potential prime
state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
}
} else if(state.pqState === 2) {
// ensure number is coprime with e
state.pqState =
(state.num.subtract(BigInteger.ONE).gcd(state.e)
.compareTo(BigInteger.ONE) === 0) ? 3 : 0;
} else if(state.pqState === 3) {
// store p or q
state.pqState = 0;
if(state.p === null) {
state.p = state.num;
} else {
state.q = state.num;
}
// advance state if both p and q are ready
if(state.p !== null && state.q !== null) {
++state.state;
}
state.num = null;
}
} else if(state.state === 1) {
// ensure p is larger than q (swap them if not)
if(state.p.compareTo(state.q) < 0) {
state.num = state.p;
state.p = state.q;
state.q = state.num;
}
++state.state;
} else if(state.state === 2) {
// compute phi: (p - 1)(q - 1) (Euler's totient function)
state.p1 = state.p.subtract(BigInteger.ONE);
state.q1 = state.q.subtract(BigInteger.ONE);
state.phi = state.p1.multiply(state.q1);
++state.state;
} else if(state.state === 3) {
// ensure e and phi are coprime
if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {
// phi and e are coprime, advance
++state.state;
} else {
// phi and e aren't coprime, so generate a new p and q
state.p = null;
state.q = null;
state.state = 0;
}
} else if(state.state === 4) {
// create n, ensure n is has the right number of bits
state.n = state.p.multiply(state.q);
// ensure n is right number of bits
if(state.n.bitLength() === state.bits) {
// success, advance
++state.state;
} else {
// failed, get new q
state.q = null;
state.state = 0;
}
} else if(state.state === 5) {
// set keys
var d = state.e.modInverse(state.phi);
state.keys = {
privateKey: pki.rsa.setPrivateKey(
state.n, state.e, d, state.p, state.q,
d.mod(state.p1), d.mod(state.q1),
state.q.modInverse(state.p)),
publicKey: pki.rsa.setPublicKey(state.n, state.e)
};
}
// update timing
t2 = +new Date();
total += t2 - t1;
t1 = t2;
}
return state.keys !== null;
};
/**
* Generates an RSA public-private key pair in a single call.
*
* To generate a key-pair in steps (to allow for progress updates and to
* prevent blocking or warnings in slow browsers) then use the key-pair
* generation state functions.
*
* To generate a key-pair asynchronously (either through web-workers, if
* available, or by breaking up the work on the main thread), pass a
* callback function.
*
* @param [bits] the size for the private key in bits, defaults to 2048.
* @param [e] the public exponent to use, defaults to 65537.
* @param [options] options for key-pair generation, if given then 'bits'
* and 'e' must *not* be given:
* bits the size for the private key in bits, (default: 2048).
* e the public exponent to use, (default: 65537 (0x10001)).
* workerScript the worker script URL.
* workers the number of web workers (if supported) to use,
* (default: 2).
* workLoad the size of the work load, ie: number of possible prime
* numbers for each web worker to check per work assignment,
* (default: 100).
* prng a custom crypto-secure pseudo-random number generator to use,
* that must define "getBytesSync". Disables use of native APIs.
* algorithm the algorithm to use (default: 'PRIMEINC').
* @param [callback(err, keypair)] called once the operation completes.
*
* @return an object with privateKey and publicKey properties.
*/
pki.rsa.generateKeyPair = function(bits, e, options, callback) {
// (bits), (options), (callback)
if(arguments.length === 1) {
if(typeof bits === 'object') {
options = bits;
bits = undefined;
} else if(typeof bits === 'function') {
callback = bits;
bits = undefined;
}
} else if(arguments.length === 2) {
// (bits, e), (bits, options), (bits, callback), (options, callback)
if(typeof bits === 'number') {
if(typeof e === 'function') {
callback = e;
e = undefined;
} else if(typeof e !== 'number') {
options = e;
e = undefined;
}
} else {
options = bits;
callback = e;
bits = undefined;
e = undefined;
}
} else if(arguments.length === 3) {
// (bits, e, options), (bits, e, callback), (bits, options, callback)
if(typeof e === 'number') {
if(typeof options === 'function') {
callback = options;
options = undefined;
}
} else {
callback = options;
options = e;
e = undefined;
}
}
options = options || {};
if(bits === undefined) {
bits = options.bits || 2048;
}
if(e === undefined) {
e = options.e || 0x10001;
}
// use native code if permitted, available, and parameters are acceptable
if(!forge.options.usePureJavaScript && !options.prng &&
bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {
if(callback) {
// try native async
if(_detectNodeCrypto('generateKeyPair')) {
return _crypto.generateKeyPair('rsa', {
modulusLength: bits,
publicExponent: e,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
}, function(err, pub, priv) {
if(err) {
return callback(err);
}
callback(null, {
privateKey: pki.privateKeyFromPem(priv),
publicKey: pki.publicKeyFromPem(pub)
});
});
}
if(_detectSubtleCrypto('generateKey') &&
_detectSubtleCrypto('exportKey')) {
// use standard native generateKey
return util.globalScope.crypto.subtle.generateKey({
name: 'RSASSA-PKCS1-v1_5',
modulusLength: bits,
publicExponent: _intToUint8Array(e),
hash: {name: 'SHA-256'}
}, true /* key can be exported*/, ['sign', 'verify'])
.then(function(pair) {
return util.globalScope.crypto.subtle.exportKey(
'pkcs8', pair.privateKey);
// avoiding catch(function(err) {...}) to support IE <= 8
}).then(undefined, function(err) {
callback(err);
}).then(function(pkcs8) {
if(pkcs8) {
var privateKey = pki.privateKeyFromAsn1(
asn1.fromDer(forge.util.createBuffer(pkcs8)));
callback(null, {
privateKey: privateKey,
publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
});
}
});
}
if(_detectSubtleMsCrypto('generateKey') &&
_detectSubtleMsCrypto('exportKey')) {
var genOp = util.globalScope.msCrypto.subtle.generateKey({
name: 'RSASSA-PKCS1-v1_5',
modulusLength: bits,
publicExponent: _intToUint8Array(e),
hash: {name: 'SHA-256'}
}, true /* key can be exported*/, ['sign', 'verify']);
genOp.oncomplete = function(e) {
var pair = e.target.result;
var exportOp = util.globalScope.msCrypto.subtle.exportKey(
'pkcs8', pair.privateKey);
exportOp.oncomplete = function(e) {
var pkcs8 = e.target.result;
var privateKey = pki.privateKeyFromAsn1(
asn1.fromDer(forge.util.createBuffer(pkcs8)));
callback(null, {
privateKey: privateKey,
publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)
});
};
exportOp.onerror = function(err) {
callback(err);
};
};
genOp.onerror = function(err) {
callback(err);
};
return;
}
} else {
// try native sync
if(_detectNodeCrypto('generateKeyPairSync')) {
var keypair = _crypto.generateKeyPairSync('rsa', {
modulusLength: bits,
publicExponent: e,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
return {
privateKey: pki.privateKeyFromPem(keypair.privateKey),
publicKey: pki.publicKeyFromPem(keypair.publicKey)
};
}
}
}
// use JavaScript implementation
var state = pki.rsa.createKeyPairGenerationState(bits, e, options);
if(!callback) {
pki.rsa.stepKeyPairGenerationState(state, 0);