-
Notifications
You must be signed in to change notification settings - Fork 796
/
Copy pathx509.js
3242 lines (2983 loc) · 99.4 KB
/
x509.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 X.509 and related components (such as
* Certification Signing Requests) of a Public Key Infrastructure.
*
* @author Dave Longley
*
* Copyright (c) 2010-2014 Digital Bazaar, Inc.
*
* The ASN.1 representation of an X.509v3 certificate is as follows
* (see RFC 2459):
*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
* }
*
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version shall be v3
* }
*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* Name ::= CHOICE {
* // only one possible choice for now
* RDNSequence
* }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue
* }
* AttributeType ::= OBJECT IDENTIFIER
* AttributeValue ::= ANY DEFINED BY AttributeType
*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time
* }
*
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime
* }
*
* UniqueIdentifier ::= BIT STRING
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* }
*
* The only key algorithm currently supported for PKI is RSA.
*
* RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
*
* PKCS#10 v1.7 describes certificate signing requests:
*
* CertificationRequestInfo:
*
* CertificationRequestInfo ::= SEQUENCE {
* version INTEGER { v1(0) } (v1,...),
* subject Name,
* subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
* attributes [0] Attributes{{ CRIAttributes }}
* }
*
* Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
*
* CRIAttributes ATTRIBUTE ::= {
* ... -- add any locally defined attributes here -- }
*
* Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
* type ATTRIBUTE.&id({IOSet}),
* values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
* }
*
* CertificationRequest ::= SEQUENCE {
* certificationRequestInfo CertificationRequestInfo,
* signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
* signature BIT STRING
* }
*/
var forge = require('./forge');
require('./aes');
require('./asn1');
require('./des');
require('./md');
require('./mgf');
require('./oids');
require('./pem');
require('./pss');
require('./rsa');
require('./util');
// shortcut for asn.1 API
var asn1 = forge.asn1;
/* Public Key Infrastructure (PKI) implementation. */
var pki = module.exports = forge.pki = forge.pki || {};
var oids = pki.oids;
// short name OID mappings
var _shortNames = {};
_shortNames['CN'] = oids['commonName'];
_shortNames['commonName'] = 'CN';
_shortNames['C'] = oids['countryName'];
_shortNames['countryName'] = 'C';
_shortNames['L'] = oids['localityName'];
_shortNames['localityName'] = 'L';
_shortNames['ST'] = oids['stateOrProvinceName'];
_shortNames['stateOrProvinceName'] = 'ST';
_shortNames['O'] = oids['organizationName'];
_shortNames['organizationName'] = 'O';
_shortNames['OU'] = oids['organizationalUnitName'];
_shortNames['organizationalUnitName'] = 'OU';
_shortNames['E'] = oids['emailAddress'];
_shortNames['emailAddress'] = 'E';
// validator for an SubjectPublicKeyInfo structure
// Note: Currently only works with an RSA public key
var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
// validator for an X.509v3 certificate
var x509CertificateValidator = {
name: 'Certificate',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'Certificate.TBSCertificate',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'tbsCertificate',
value: [{
name: 'Certificate.TBSCertificate.version',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
value: [{
name: 'Certificate.TBSCertificate.version.integer',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'certVersion'
}]
}, {
name: 'Certificate.TBSCertificate.serialNumber',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'certSerialNumber'
}, {
name: 'Certificate.TBSCertificate.signature',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'Certificate.TBSCertificate.signature.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'certinfoSignatureOid'
}, {
name: 'Certificate.TBSCertificate.signature.parameters',
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: 'certinfoSignatureParams'
}]
}, {
name: 'Certificate.TBSCertificate.issuer',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'certIssuer'
}, {
name: 'Certificate.TBSCertificate.validity',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
// Note: UTC and generalized times may both appear so the capture
// names are based on their detected order, the names used below
// are only for the common case, which validity time really means
// "notBefore" and which means "notAfter" will be determined by order
value: [{
// notBefore (Time) (UTC time case)
name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.UTCTIME,
constructed: false,
optional: true,
capture: 'certValidity1UTCTime'
}, {
// notBefore (Time) (generalized time case)
name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.GENERALIZEDTIME,
constructed: false,
optional: true,
capture: 'certValidity2GeneralizedTime'
}, {
// notAfter (Time) (only UTC time is supported)
name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.UTCTIME,
constructed: false,
optional: true,
capture: 'certValidity3UTCTime'
}, {
// notAfter (Time) (only UTC time is supported)
name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.GENERALIZEDTIME,
constructed: false,
optional: true,
capture: 'certValidity4GeneralizedTime'
}]
}, {
// Name (subject) (RDNSequence)
name: 'Certificate.TBSCertificate.subject',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'certSubject'
},
// SubjectPublicKeyInfo
publicKeyValidator,
{
// issuerUniqueID (optional)
name: 'Certificate.TBSCertificate.issuerUniqueID',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
constructed: true,
optional: true,
value: [{
name: 'Certificate.TBSCertificate.issuerUniqueID.id',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
// TODO: support arbitrary bit length ids
captureBitStringValue: 'certIssuerUniqueId'
}]
}, {
// subjectUniqueID (optional)
name: 'Certificate.TBSCertificate.subjectUniqueID',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 2,
constructed: true,
optional: true,
value: [{
name: 'Certificate.TBSCertificate.subjectUniqueID.id',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
// TODO: support arbitrary bit length ids
captureBitStringValue: 'certSubjectUniqueId'
}]
}, {
// Extensions (optional)
name: 'Certificate.TBSCertificate.extensions',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 3,
constructed: true,
captureAsn1: 'certExtensions',
optional: true
}]
}, {
// AlgorithmIdentifier (signature algorithm)
name: 'Certificate.signatureAlgorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// algorithm
name: 'Certificate.signatureAlgorithm.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'certSignatureOid'
}, {
name: 'Certificate.TBSCertificate.signature.parameters',
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: 'certSignatureParams'
}]
}, {
// SignatureValue
name: 'Certificate.signatureValue',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
captureBitStringValue: 'certSignature'
}]
};
var rsassaPssParameterValidator = {
name: 'rsapss',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'rsapss.hashAlgorithm',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
value: [{
name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.SEQUENCE,
constructed: true,
optional: true,
value: [{
name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'hashOid'
/* parameter block omitted, for SHA1 NULL anyhow. */
}]
}]
}, {
name: 'rsapss.maskGenAlgorithm',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 1,
constructed: true,
value: [{
name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.SEQUENCE,
constructed: true,
optional: true,
value: [{
name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'maskGenOid'
}, {
name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'maskGenHashOid'
/* parameter block omitted, for SHA1 NULL anyhow. */
}]
}]
}]
}, {
name: 'rsapss.saltLength',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 2,
optional: true,
value: [{
name: 'rsapss.saltLength.saltLength',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.INTEGER,
constructed: false,
capture: 'saltLength'
}]
}, {
name: 'rsapss.trailerField',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 3,
optional: true,
value: [{
name: 'rsapss.trailer.trailer',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Class.INTEGER,
constructed: false,
capture: 'trailer'
}]
}]
};
// validator for a CertificationRequestInfo structure
var certificationRequestInfoValidator = {
name: 'CertificationRequestInfo',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'certificationRequestInfo',
value: [{
name: 'CertificationRequestInfo.integer',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.INTEGER,
constructed: false,
capture: 'certificationRequestInfoVersion'
}, {
// Name (subject) (RDNSequence)
name: 'CertificationRequestInfo.subject',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'certificationRequestInfoSubject'
},
// SubjectPublicKeyInfo
publicKeyValidator,
{
name: 'CertificationRequestInfo.attributes',
tagClass: asn1.Class.CONTEXT_SPECIFIC,
type: 0,
constructed: true,
optional: true,
capture: 'certificationRequestInfoAttributes',
value: [{
name: 'CertificationRequestInfo.attributes',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
name: 'CertificationRequestInfo.attributes.type',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false
}, {
name: 'CertificationRequestInfo.attributes.value',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SET,
constructed: true
}]
}]
}]
};
// validator for a CertificationRequest structure
var certificationRequestValidator = {
name: 'CertificationRequest',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
captureAsn1: 'csr',
value: [
certificationRequestInfoValidator, {
// AlgorithmIdentifier (signature algorithm)
name: 'CertificationRequest.signatureAlgorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.SEQUENCE,
constructed: true,
value: [{
// algorithm
name: 'CertificationRequest.signatureAlgorithm.algorithm',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.OID,
constructed: false,
capture: 'csrSignatureOid'
}, {
name: 'CertificationRequest.signatureAlgorithm.parameters',
tagClass: asn1.Class.UNIVERSAL,
optional: true,
captureAsn1: 'csrSignatureParams'
}]
}, {
// signature
name: 'CertificationRequest.signature',
tagClass: asn1.Class.UNIVERSAL,
type: asn1.Type.BITSTRING,
constructed: false,
captureBitStringValue: 'csrSignature'
}
]
};
/**
* Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
* sets into an array with objects that have type and value properties.
*
* @param rdn the RDNSequence to convert.
* @param md a message digest to append type and value to if provided.
*/
pki.RDNAttributesAsArray = function(rdn, md) {
var rval = [];
// each value in 'rdn' in is a SET of RelativeDistinguishedName
var set, attr, obj;
for(var si = 0; si < rdn.value.length; ++si) {
// get the RelativeDistinguishedName set
set = rdn.value[si];
// each value in the SET is an AttributeTypeAndValue sequence
// containing first a type (an OID) and second a value (defined by
// the OID)
for(var i = 0; i < set.value.length; ++i) {
obj = {};
attr = set.value[i];
obj.type = asn1.derToOid(attr.value[0].value);
obj.value = attr.value[1].value;
obj.valueTagClass = attr.value[1].type;
// if the OID is known, get its name and short name
if(obj.type in oids) {
obj.name = oids[obj.type];
if(obj.name in _shortNames) {
obj.shortName = _shortNames[obj.name];
}
}
if(md) {
md.update(obj.type);
md.update(obj.value);
}
rval.push(obj);
}
}
return rval;
};
/**
* Converts ASN.1 CRIAttributes into an array with objects that have type and
* value properties.
*
* @param attributes the CRIAttributes to convert.
*/
pki.CRIAttributesAsArray = function(attributes) {
var rval = [];
// each value in 'attributes' in is a SEQUENCE with an OID and a SET
for(var si = 0; si < attributes.length; ++si) {
// get the attribute sequence
var seq = attributes[si];
// each value in the SEQUENCE containing first a type (an OID) and
// second a set of values (defined by the OID)
var type = asn1.derToOid(seq.value[0].value);
var values = seq.value[1].value;
for(var vi = 0; vi < values.length; ++vi) {
var obj = {};
obj.type = type;
obj.value = values[vi].value;
obj.valueTagClass = values[vi].type;
// if the OID is known, get its name and short name
if(obj.type in oids) {
obj.name = oids[obj.type];
if(obj.name in _shortNames) {
obj.shortName = _shortNames[obj.name];
}
}
// parse extensions
if(obj.type === oids.extensionRequest) {
obj.extensions = [];
for(var ei = 0; ei < obj.value.length; ++ei) {
obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
}
}
rval.push(obj);
}
}
return rval;
};
/**
* Gets an issuer or subject attribute from its name, type, or short name.
*
* @param obj the issuer or subject object.
* @param options a short name string or an object with:
* shortName the short name for the attribute.
* name the name for the attribute.
* type the type for the attribute.
*
* @return the attribute.
*/
function _getAttribute(obj, options) {
if(typeof options === 'string') {
options = {shortName: options};
}
var rval = null;
var attr;
for(var i = 0; rval === null && i < obj.attributes.length; ++i) {
attr = obj.attributes[i];
if(options.type && options.type === attr.type) {
rval = attr;
} else if(options.name && options.name === attr.name) {
rval = attr;
} else if(options.shortName && options.shortName === attr.shortName) {
rval = attr;
}
}
return rval;
}
/**
* Converts signature parameters from ASN.1 structure.
*
* Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
* no parameters.
*
* RSASSA-PSS-params ::= SEQUENCE {
* hashAlgorithm [0] HashAlgorithm DEFAULT
* sha1Identifier,
* maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
* mgf1SHA1Identifier,
* saltLength [2] INTEGER DEFAULT 20,
* trailerField [3] INTEGER DEFAULT 1
* }
*
* HashAlgorithm ::= AlgorithmIdentifier
*
* MaskGenAlgorithm ::= AlgorithmIdentifier
*
* AlgorithmIdentifer ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* @param oid The OID specifying the signature algorithm
* @param obj The ASN.1 structure holding the parameters
* @param fillDefaults Whether to use return default values where omitted
* @return signature parameter object
*/
var _readSignatureParameters = function(oid, obj, fillDefaults) {
var params = {};
if(oid !== oids['RSASSA-PSS']) {
return params;
}
if(fillDefaults) {
params = {
hash: {
algorithmOid: oids['sha1']
},
mgf: {
algorithmOid: oids['mgf1'],
hash: {
algorithmOid: oids['sha1']
}
},
saltLength: 20
};
}
var capture = {};
var errors = [];
if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
var error = new Error('Cannot read RSASSA-PSS parameter block.');
error.errors = errors;
throw error;
}
if(capture.hashOid !== undefined) {
params.hash = params.hash || {};
params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
}
if(capture.maskGenOid !== undefined) {
params.mgf = params.mgf || {};
params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
params.mgf.hash = params.mgf.hash || {};
params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
}
if(capture.saltLength !== undefined) {
params.saltLength = capture.saltLength.charCodeAt(0);
}
return params;
};
/**
* Create signature digest for OID.
*
* @param options
* signatureOid: the OID specifying the signature algorithm.
* type: a human readable type for error messages
* @return a created md instance. throws if unknown oid.
*/
var _createSignatureDigest = function(options) {
switch(oids[options.signatureOid]) {
case 'sha1WithRSAEncryption':
// deprecated alias
case 'sha1WithRSASignature':
return forge.md.sha1.create();
case 'md5WithRSAEncryption':
return forge.md.md5.create();
case 'sha256WithRSAEncryption':
return forge.md.sha256.create();
case 'sha384WithRSAEncryption':
return forge.md.sha384.create();
case 'sha512WithRSAEncryption':
return forge.md.sha512.create();
case 'RSASSA-PSS':
return forge.md.sha256.create();
default:
var error = new Error(
'Could not compute ' + options.type + ' digest. ' +
'Unknown signature OID.');
error.signatureOid = options.signatureOid;
throw error;
}
};
/**
* Verify signature on certificate or CSR.
*
* @param options:
* certificate the certificate or CSR to verify.
* md the signature digest.
* signature the signature
* @return a created md instance. throws if unknown oid.
*/
var _verifySignature = function(options) {
var cert = options.certificate;
var scheme;
switch(cert.signatureOid) {
case oids.sha1WithRSAEncryption:
// deprecated alias
case oids.sha1WithRSASignature:
/* use PKCS#1 v1.5 padding scheme */
break;
case oids['RSASSA-PSS']:
var hash, mgf;
/* initialize mgf */
hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];
if(hash === undefined || forge.md[hash] === undefined) {
var error = new Error('Unsupported MGF hash function.');
error.oid = cert.signatureParameters.mgf.hash.algorithmOid;
error.name = hash;
throw error;
}
mgf = oids[cert.signatureParameters.mgf.algorithmOid];
if(mgf === undefined || forge.mgf[mgf] === undefined) {
var error = new Error('Unsupported MGF function.');
error.oid = cert.signatureParameters.mgf.algorithmOid;
error.name = mgf;
throw error;
}
mgf = forge.mgf[mgf].create(forge.md[hash].create());
/* initialize hash function */
hash = oids[cert.signatureParameters.hash.algorithmOid];
if(hash === undefined || forge.md[hash] === undefined) {
var error = new Error('Unsupported RSASSA-PSS hash function.');
error.oid = cert.signatureParameters.hash.algorithmOid;
error.name = hash;
throw error;
}
scheme = forge.pss.create(
forge.md[hash].create(), mgf, cert.signatureParameters.saltLength
);
break;
}
// verify signature on cert using public key
return cert.publicKey.verify(
options.md.digest().getBytes(), options.signature, scheme
);
};
/**
* Converts an X.509 certificate from PEM format.
*
* Note: If the certificate is to be verified then compute hash should
* be set to true. This will scan the TBSCertificate part of the ASN.1
* object while it is converted so it doesn't need to be converted back
* to ASN.1-DER-encoding later.
*
* @param pem the PEM-formatted certificate.
* @param computeHash true to compute the hash for verification.
* @param strict true to be strict when checking ASN.1 value lengths, false to
* allow truncated values (default: true).
*
* @return the certificate.
*/
pki.certificateFromPem = function(pem, computeHash, strict) {
var msg = forge.pem.decode(pem)[0];
if(msg.type !== 'CERTIFICATE' &&
msg.type !== 'X509 CERTIFICATE' &&
msg.type !== 'TRUSTED CERTIFICATE') {
var error = new Error(
'Could not convert certificate from PEM; PEM header type ' +
'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
error.headerType = msg.type;
throw error;
}
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error(
'Could not convert certificate from PEM; PEM is encrypted.');
}
// convert DER to ASN.1 object
var obj = asn1.fromDer(msg.body, strict);
return pki.certificateFromAsn1(obj, computeHash);
};
/**
* Converts an X.509 certificate to PEM format.
*
* @param cert the certificate.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted certificate.
*/
pki.certificateToPem = function(cert, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var msg = {
type: 'CERTIFICATE',
body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});
};
/**
* Converts an RSA public key from PEM format.
*
* @param pem the PEM-formatted public key.
*
* @return the public key.
*/
pki.publicKeyFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
var error = new Error('Could not convert public key from PEM; PEM header ' +
'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
error.headerType = msg.type;
throw error;
}
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error('Could not convert public key from PEM; PEM is encrypted.');
}
// convert DER to ASN.1 object
var obj = asn1.fromDer(msg.body);
return pki.publicKeyFromAsn1(obj);
};
/**
* Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
*
* @param key the public key.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted public key.
*/
pki.publicKeyToPem = function(key, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var msg = {
type: 'PUBLIC KEY',
body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});
};
/**
* Converts an RSA public key to PEM format (using an RSAPublicKey).
*
* @param key the public key.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted public key.
*/
pki.publicKeyToRSAPublicKeyPem = function(key, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var msg = {
type: 'RSA PUBLIC KEY',
body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});
};
/**
* Gets a fingerprint for the given public key.
*
* @param options the options to use.
* [md] the message digest object to use (defaults to forge.md.sha1).
* [type] the type of fingerprint, such as 'RSAPublicKey',
* 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
* [encoding] an alternative output encoding, such as 'hex'
* (defaults to none, outputs a byte buffer).
* [delimiter] the delimiter to use between bytes for 'hex' encoded
* output, eg: ':' (defaults to none).
*
* @return the fingerprint as a byte buffer or other encoding based on options.
*/
pki.getPublicKeyFingerprint = function(key, options) {
options = options || {};
var md = options.md || forge.md.sha1.create();
var type = options.type || 'RSAPublicKey';
var bytes;
switch(type) {
case 'RSAPublicKey':
bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();
break;
case 'SubjectPublicKeyInfo':
bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();
break;
default:
throw new Error('Unknown fingerprint type "' + options.type + '".');
}
// hash public key bytes
md.start();
md.update(bytes);
var digest = md.digest();
if(options.encoding === 'hex') {
var hex = digest.toHex();
if(options.delimiter) {
return hex.match(/.{2}/g).join(options.delimiter);
}
return hex;
} else if(options.encoding === 'binary') {
return digest.getBytes();
} else if(options.encoding) {
throw new Error('Unknown encoding "' + options.encoding + '".');
}
return digest;
};
/**
* Converts a PKCS#10 certification request (CSR) from PEM format.
*
* Note: If the certification request is to be verified then compute hash
* should be set to true. This will scan the CertificationRequestInfo part of
* the ASN.1 object while it is converted so it doesn't need to be converted
* back to ASN.1-DER-encoding later.
*
* @param pem the PEM-formatted certificate.
* @param computeHash true to compute the hash for verification.
* @param strict true to be strict when checking ASN.1 value lengths, false to
* allow truncated values (default: true).
*
* @return the certification request (CSR).
*/
pki.certificationRequestFromPem = function(pem, computeHash, strict) {
var msg = forge.pem.decode(pem)[0];
if(msg.type !== 'CERTIFICATE REQUEST') {
var error = new Error('Could not convert certification request from PEM; ' +
'PEM header type is not "CERTIFICATE REQUEST".');
error.headerType = msg.type;
throw error;
}
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error('Could not convert certification request from PEM; ' +
'PEM is encrypted.');
}
// convert DER to ASN.1 object
var obj = asn1.fromDer(msg.body, strict);
return pki.certificationRequestFromAsn1(obj, computeHash);
};
/**
* Converts a PKCS#10 certification request (CSR) to PEM format.
*
* @param csr the certification request.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted certification request.
*/
pki.certificationRequestToPem = function(csr, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var msg = {
type: 'CERTIFICATE REQUEST',
body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});