-
Notifications
You must be signed in to change notification settings - Fork 582
/
pkcs7-modified.js
1279 lines (1154 loc) · 39.8 KB
/
pkcs7-modified.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 PKCS#7 v1.5.
*
* @author Stefan Siegl
* @author Dave Longley
*
* Copyright (c) 2012 Stefan Siegl <[email protected]>
* Copyright (c) 2012-2015 Digital Bazaar, Inc.
*
* Currently this implementation only supports ContentType of EnvelopedData,
* EncryptedData, or SignedData at the root level. The top level elements may
* contain only a ContentInfo of ContentType Data, i.e. plain data. Further
* nesting is not (yet) supported.
*
* The Forge validators for PKCS #7's ASN.1 structures are available from
* a separate file pkcs7asn1.js, since those are referenced from other
* PKCS standards like PKCS #12.
*/
var forge;
try {
forge = require('../node-forge/lib/forge');
require('../node-forge/lib/aes');
require('../node-forge/lib/asn1');
require('../node-forge/lib/des');
require('../node-forge/lib/oids');
require('../node-forge/lib/pem');
require('../node-forge/lib/pkcs7asn1');
require('../node-forge/lib/random');
require('../node-forge/lib/util');
require('../node-forge/lib/x509'); f
} catch (ex) { }
if (forge == null) {
forge = require('./node_modules/node-forge/lib/forge');
require('./node_modules/node-forge/lib/aes');
require('./node_modules/node-forge/lib/asn1');
require('./node_modules/node-forge/lib/des');
require('./node_modules/node-forge/lib/oids');
require('./node_modules/node-forge/lib/pem');
require('./node_modules/node-forge/lib/pkcs7asn1');
require('./node_modules/node-forge/lib/random');
require('./node_modules/node-forge/lib/util');
require('./node_modules/node-forge/lib/x509');
}
// shortcut for ASN.1 API
var asn1 = forge.asn1;
// shortcut for PKCS#7 API
var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};
/**
* Converts a PKCS#7 message from PEM format.
*
* @param pem the PEM-formatted PKCS#7 message.
*
* @return the PKCS#7 message.
*/
p7.messageFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if(msg.type !== 'PKCS7') {
var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +
'header type is not "PKCS#7".');
error.headerType = msg.type;
throw error;
}
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');
}
// convert DER to ASN.1 object
var obj = asn1.fromDer(msg.body);
return p7.messageFromAsn1(obj);
};
/**
* Converts a PKCS#7 message to PEM format.
*
* @param msg The PKCS#7 message object
* @param maxline The maximum characters per line, defaults to 64.
*
* @return The PEM-formatted PKCS#7 message.
*/
p7.messageToPem = function(msg, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var pemObj = {
type: 'PKCS7',
body: asn1.toDer(msg.toAsn1()).getBytes()
};
return forge.pem.encode(pemObj, {maxline: maxline});
};
/**
* Converts a PKCS#7 message from an ASN.1 object.
*
* @param obj the ASN.1 representation of a ContentInfo.
*
* @return the PKCS#7 message.
*/
p7.messageFromAsn1 = function(obj) {
// validate root level ContentInfo and capture data
var capture = {};
var errors = [];
if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
var error = new Error('Cannot read PKCS#7 message. ' +
'ASN.1 object is not an PKCS#7 ContentInfo.');
error.errors = errors;
throw error;
}
var contentType = asn1.derToOid(capture.contentType);
var msg;
switch(contentType) {
case forge.pki.oids.envelopedData:
msg = p7.createEnvelopedData();
break;
case forge.pki.oids.encryptedData:
msg = p7.createEncryptedData();
break;
case forge.pki.oids.signedData:
msg = p7.createSignedData();
break;
default:
throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +
contentType + ' is not (yet) supported.');
}
msg.fromAsn1(capture.content.value[0]);
return msg;
};
p7.createSignedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.signedData,
version: 1,
certificates: [],
crls: [],
// TODO: add json-formatted signer stuff here?
signers: [],
// populated during sign()
digestAlgorithmIdentifiers: [],
contentInfo: null,
signerInfos: [],
fromAsn1: function(obj) {
// validate SignedData content block and capture data.
_fromAsn1(msg, obj, p7.asn1.signedDataValidator);
msg.certificates = [];
msg.crls = [];
msg.digestAlgorithmIdentifiers = [];
msg.contentInfo = null;
msg.signerInfos = [];
if(msg.rawCapture.certificates) {
var certs = msg.rawCapture.certificates.value;
for(var i = 0; i < certs.length; ++i) {
msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));
}
}
// TODO: parse crls
},
toAsn1: function() {
// degenerate case with no content
if(!msg.contentInfo) {
msg.sign();
}
var certs = [];
for(var i = 0; i < msg.certificates.length; ++i) {
certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));
}
var crls = [];
// TODO: implement CRLs
// [0] SignedData
var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
asn1.integerToDer(msg.version).getBytes()),
// DigestAlgorithmIdentifiers
asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SET, true,
msg.digestAlgorithmIdentifiers),
// ContentInfo
msg.contentInfo
])
]);
if(certs.length > 0) {
// [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
signedData.value[0].value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));
}
if(crls.length > 0) {
// [1] IMPLICIT CertificateRevocationLists OPTIONAL
signedData.value[0].value.push(
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));
}
// SignerInfos
signedData.value[0].value.push(
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
msg.signerInfos));
// ContentInfo
return asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// ContentType
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(msg.type).getBytes()),
// [0] SignedData
signedData
]);
},
/**
* Add (another) entity to list of signers.
*
* Note: If authenticatedAttributes are provided, then, per RFC 2315,
* they must include at least two attributes: content type and
* message digest. The message digest attribute value will be
* auto-calculated during signing and will be ignored if provided.
*
* Here's an example of providing these two attributes:
*
* forge.pkcs7.createSignedData();
* p7.addSigner({
* issuer: cert.issuer.attributes,
* serialNumber: cert.serialNumber,
* key: privateKey,
* digestAlgorithm: forge.pki.oids.sha1,
* authenticatedAttributes: [{
* type: forge.pki.oids.contentType,
* value: forge.pki.oids.data
* }, {
* type: forge.pki.oids.messageDigest
* }]
* });
*
* TODO: Support [subjectKeyIdentifier] as signer's ID.
*
* @param signer the signer information:
* key the signer's private key.
* [certificate] a certificate containing the public key
* associated with the signer's private key; use this option as
* an alternative to specifying signer.issuer and
* signer.serialNumber.
* [issuer] the issuer attributes (eg: cert.issuer.attributes).
* [serialNumber] the signer's certificate's serial number in
* hexadecimal (eg: cert.serialNumber).
* [digestAlgorithm] the message digest OID, as a string, to use
* (eg: forge.pki.oids.sha1).
* [authenticatedAttributes] an optional array of attributes
* to also sign along with the content.
*/
addSigner: function(signer) {
var issuer = signer.issuer;
var serialNumber = signer.serialNumber;
if(signer.certificate) {
var cert = signer.certificate;
if(typeof cert === 'string') {
cert = forge.pki.certificateFromPem(cert);
}
issuer = cert.issuer.attributes;
serialNumber = cert.serialNumber;
}
var key = signer.key;
if(!key) {
throw new Error(
'Could not add PKCS#7 signer; no private key specified.');
}
if(typeof key === 'string') {
key = forge.pki.privateKeyFromPem(key);
}
// ensure OID known for digest algorithm
var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;
switch(digestAlgorithm) {
case forge.pki.oids.sha1:
case forge.pki.oids.sha256:
case forge.pki.oids.sha384:
case forge.pki.oids.sha512:
case forge.pki.oids.md5:
break;
default:
throw new Error(
'Could not add PKCS#7 signer; unknown message digest algorithm: ' +
digestAlgorithm);
}
// if authenticatedAttributes is present, then the attributes
// must contain at least PKCS #9 content-type and message-digest
var authenticatedAttributes = signer.authenticatedAttributes || [];
if(authenticatedAttributes.length > 0) {
var contentType = false;
var messageDigest = false;
for(var i = 0; i < authenticatedAttributes.length; ++i) {
var attr = authenticatedAttributes[i];
if(!contentType && attr.type === forge.pki.oids.contentType) {
contentType = true;
if(messageDigest) {
break;
}
continue;
}
if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {
messageDigest = true;
if(contentType) {
break;
}
continue;
}
}
if(!contentType || !messageDigest) {
throw new Error('Invalid signer.authenticatedAttributes. If ' +
'signer.authenticatedAttributes is specified, then it must ' +
'contain at least two attributes, PKCS #9 content-type and ' +
'PKCS #9 message-digest.');
}
}
msg.signers.push({
key: key,
version: 1,
issuer: issuer,
serialNumber: serialNumber,
digestAlgorithm: digestAlgorithm,
signatureAlgorithm: forge.pki.oids.rsaEncryption,
signature: null,
authenticatedAttributes: authenticatedAttributes,
unauthenticatedAttributes: []
});
},
/**
* Signs the content.
* @param options Options to apply when signing:
* [detached] boolean. If signing should be done in detached mode. Defaults to false.
*/
sign: function(options) {
options = options || {};
// auto-generate content info
if(typeof msg.content !== 'object' || msg.contentInfo === null) {
// use Data ContentInfo
msg.contentInfo = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// ContentType
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(forge.pki.oids.data).getBytes())
]);
// add actual content, if present
if('content' in msg) {
var content;
if(msg.content instanceof forge.util.ByteBuffer) {
content = msg.content.bytes();
} else if(typeof msg.content === 'string') {
content = forge.util.encodeUtf8(msg.content);
}
if (options.detached) {
msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);
} else {
msg.contentInfo.value.push(
// [0] EXPLICIT content
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
content)
]));
}
}
}
// no signers, return early (degenerate case for certificate container)
if(msg.signers.length === 0) {
return;
}
// generate digest algorithm identifiers
var mds = addDigestAlgorithmIds();
// generate signerInfos
addSignerInfos(mds);
},
verify: function() {
throw new Error('PKCS#7 signature verification not yet implemented.');
},
/**
* Add a certificate.
*
* @param cert the certificate to add.
*/
addCertificate: function(cert) {
// convert from PEM
if(typeof cert === 'string') {
cert = forge.pki.certificateFromPem(cert);
}
msg.certificates.push(cert);
},
/**
* Add a certificate revokation list.
*
* @param crl the certificate revokation list to add.
*/
addCertificateRevokationList: function(crl) {
throw new Error('PKCS#7 CRL support not yet implemented.');
}
};
return msg;
function addDigestAlgorithmIds() {
var mds = {};
for(var i = 0; i < msg.signers.length; ++i) {
var signer = msg.signers[i];
var oid = signer.digestAlgorithm;
if(!(oid in mds)) {
// content digest
mds[oid] = forge.md[forge.pki.oids[oid]].create();
}
if(signer.authenticatedAttributes.length === 0) {
// no custom attributes to digest; use content message digest
signer.md = mds[oid];
} else {
// custom attributes to be digested; use own message digest
// TODO: optimize to just copy message digest state if that
// feature is ever supported with message digests
signer.md = forge.md[forge.pki.oids[oid]].create();
}
}
// add unique digest algorithm identifiers
msg.digestAlgorithmIdentifiers = [];
for(var oid in mds) {
msg.digestAlgorithmIdentifiers.push(
// AlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(oid).getBytes()),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
]));
}
return mds;
}
function addSignerInfos(mds) {
var content;
if (msg.detachedContent) {
// Signature has been made in detached mode.
content = msg.detachedContent;
} else {
// Note: ContentInfo is a SEQUENCE with 2 values, second value is
// the content field and is optional for a ContentInfo but required here
// since signers are present
// get ContentInfo content
content = msg.contentInfo.value[1];
// skip [0] EXPLICIT content wrapper
content = content.value[0];
}
if(!content) {
throw new Error(
'Could not sign PKCS#7 message; there is no content to sign.');
}
// get ContentInfo content type
var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
// serialize content
var bytes = asn1.toDer(content);
// skip identifier and length per RFC 2315 9.3
// skip identifier (1 byte)
bytes.getByte();
// read and discard length bytes
asn1.getBerValueLength(bytes);
bytes = bytes.getBytes();
// digest content DER value bytes
for(var oid in mds) {
mds[oid].start().update(bytes);
}
// sign content
var signingTime = new Date();
for(var i = 0; i < msg.signers.length; ++i) {
var signer = msg.signers[i];
if(signer.authenticatedAttributes.length === 0) {
// if ContentInfo content type is not "Data", then
// authenticatedAttributes must be present per RFC 2315
if(contentType !== forge.pki.oids.data) {
throw new Error(
'Invalid signer; authenticatedAttributes must be present ' +
'when the ContentInfo content type is not PKCS#7 Data.');
}
} else {
// process authenticated attributes
// [0] IMPLICIT
signer.authenticatedAttributesAsn1 = asn1.create(
asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
// per RFC 2315, attributes are to be digested using a SET container
// not the above [0] IMPLICIT container
var attrsAsn1 = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);
for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {
var attr = signer.authenticatedAttributes[ai];
if(attr.type === forge.pki.oids.messageDigest) {
// use content message digest as value
attr.value = mds[signer.digestAlgorithm].digest();
} else if(attr.type === forge.pki.oids.signingTime) {
// auto-populate signing time if not already set
if(!attr.value) {
attr.value = signingTime;
}
}
// convert to ASN.1 and push onto Attributes SET (for signing) and
// onto authenticatedAttributesAsn1 to complete SignedData ASN.1
// TODO: optimize away duplication
attrsAsn1.value.push(_attributeToAsn1(attr));
signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
}
// DER-serialize and digest SET OF attributes only
bytes = asn1.toDer(attrsAsn1).getBytes();
signer.md.start().update(bytes);
}
// sign digest
signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');
}
// add signer info
msg.signerInfos = _signersToAsn1(msg.signers);
}
};
/**
* Creates an empty PKCS#7 message of type EncryptedData.
*
* @return the message.
*/
p7.createEncryptedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.encryptedData,
version: 0,
encryptedContent: {
algorithm: forge.pki.oids['aes256-CBC']
},
/**
* Reads an EncryptedData content block (in ASN.1 format)
*
* @param obj The ASN.1 representation of the EncryptedData content block
*/
fromAsn1: function(obj) {
// Validate EncryptedData content block and capture data.
_fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
},
/**
* Decrypt encrypted content
*
* @param key The (symmetric) key as a byte buffer
*/
decrypt: function(key) {
if(key !== undefined) {
msg.encryptedContent.key = key;
}
_decryptContent(msg);
}
};
return msg;
};
/**
* Creates an empty PKCS#7 message of type EnvelopedData.
*
* @return the message.
*/
p7.createEnvelopedData = function() {
var msg = null;
msg = {
type: forge.pki.oids.envelopedData,
version: 0,
recipients: [],
encryptedContent: {
algorithm: forge.pki.oids['aes256-CBC']
},
/**
* Reads an EnvelopedData content block (in ASN.1 format)
*
* @param obj the ASN.1 representation of the EnvelopedData content block.
*/
fromAsn1: function(obj) {
// validate EnvelopedData content block and capture data
var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
},
toAsn1: function() {
// ContentInfo
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// ContentType
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(msg.type).getBytes()),
// [0] EnvelopedData
asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
asn1.integerToDer(msg.version).getBytes()),
// RecipientInfos
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
_recipientsToAsn1(msg.recipients)),
// EncryptedContentInfo
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,
_encryptedContentToAsn1(msg.encryptedContent))
])
])
]);
},
/**
* Find recipient by X.509 certificate's issuer.
*
* @param cert the certificate with the issuer to look for.
*
* @return the recipient object.
*/
findRecipient: function(cert) {
var sAttr = cert.issuer.attributes;
for(var i = 0; i < msg.recipients.length; ++i) {
var r = msg.recipients[i];
var rAttr = r.issuer;
if(r.serialNumber !== cert.serialNumber) {
continue;
}
if(rAttr.length !== sAttr.length) {
continue;
}
var match = true;
for(var j = 0; j < sAttr.length; ++j) {
if(rAttr[j].type !== sAttr[j].type ||
rAttr[j].value !== sAttr[j].value) {
match = false;
break;
}
}
if(match) {
return r;
}
}
return null;
},
/**
* Decrypt enveloped content
*
* @param recipient The recipient object related to the private key
* @param privKey The (RSA) private key object
*/
decrypt: function(recipient, privKey) {
if(msg.encryptedContent.key === undefined && recipient !== undefined &&
privKey !== undefined) {
switch(recipient.encryptedContent.algorithm) {
case forge.pki.oids.rsaEncryption:
case forge.pki.oids.desCBC:
var key = privKey.decrypt(recipient.encryptedContent.content);
msg.encryptedContent.key = forge.util.createBuffer(key);
break;
default:
throw new Error('Unsupported asymmetric cipher, ' +
'OID ' + recipient.encryptedContent.algorithm);
}
}
_decryptContent(msg);
},
/**
* Add (another) entity to list of recipients.
*
* @param cert The certificate of the entity to add.
*/
addRecipient: function(cert) {
msg.recipients.push({
version: 0,
issuer: cert.issuer.attributes,
serialNumber: cert.serialNumber,
encryptedContent: {
// We simply assume rsaEncryption here, since forge.pki only
// supports RSA so far. If the PKI module supports other
// ciphers one day, we need to modify this one as well.
algorithm: forge.pki.oids.rsaEncryption,
key: cert.publicKey
}
});
},
/**
* Encrypt enveloped content.
*
* This function supports two optional arguments, cipher and key, which
* can be used to influence symmetric encryption. Unless cipher is
* provided, the cipher specified in encryptedContent.algorithm is used
* (defaults to AES-256-CBC). If no key is provided, encryptedContent.key
* is (re-)used. If that one's not set, a random key will be generated
* automatically.
*
* @param [key] The key to be used for symmetric encryption.
* @param [cipher] The OID of the symmetric cipher to use.
*/
encrypt: function(key, cipher) {
// Part 1: Symmetric encryption
if(msg.encryptedContent.content === undefined) {
cipher = cipher || msg.encryptedContent.algorithm;
key = key || msg.encryptedContent.key;
var keyLen, ivLen, ciphFn;
switch(cipher) {
case forge.pki.oids['aes128-CBC']:
keyLen = 16;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids['aes192-CBC']:
keyLen = 24;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids['aes256-CBC']:
keyLen = 32;
ivLen = 16;
ciphFn = forge.aes.createEncryptionCipher;
break;
case forge.pki.oids['des-EDE3-CBC']:
keyLen = 24;
ivLen = 8;
ciphFn = forge.des.createEncryptionCipher;
break;
default:
throw new Error('Unsupported symmetric cipher, OID ' + cipher);
}
if(key === undefined) {
key = forge.util.createBuffer(forge.random.getBytes(keyLen));
} else if(key.length() != keyLen) {
throw new Error('Symmetric key has wrong length; ' +
'got ' + key.length() + ' bytes, expected ' + keyLen + '.');
}
// Keep a copy of the key & IV in the object, so the caller can
// use it for whatever reason.
msg.encryptedContent.algorithm = cipher;
msg.encryptedContent.key = key;
msg.encryptedContent.parameter = forge.util.createBuffer(
forge.random.getBytes(ivLen));
var ciph = ciphFn(key);
ciph.start(msg.encryptedContent.parameter.copy());
ciph.update(msg.content);
// The finish function does PKCS#7 padding by default, therefore
// no action required by us.
if(!ciph.finish()) {
throw new Error('Symmetric encryption failed.');
}
msg.encryptedContent.content = ciph.output;
}
// Part 2: asymmetric encryption for each recipient
for(var i = 0; i < msg.recipients.length; ++i) {
var recipient = msg.recipients[i];
// Nothing to do, encryption already done.
if(recipient.encryptedContent.content !== undefined) {
continue;
}
switch(recipient.encryptedContent.algorithm) {
case forge.pki.oids.rsaEncryption:
recipient.encryptedContent.content =
recipient.encryptedContent.key.encrypt(
msg.encryptedContent.key.data);
break;
default:
throw new Error('Unsupported asymmetric cipher, OID ' +
recipient.encryptedContent.algorithm);
}
}
}
};
return msg;
};
/**
* Converts a single recipient from an ASN.1 object.
*
* @param obj the ASN.1 RecipientInfo.
*
* @return the recipient object.
*/
function _recipientFromAsn1(obj) {
// validate EnvelopedData content block and capture data
var capture = {};
var errors = [];
if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +
'ASN.1 object is not an PKCS#7 RecipientInfo.');
error.errors = errors;
throw error;
}
return {
version: capture.version.charCodeAt(0),
issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
serialNumber: forge.util.createBuffer(capture.serial).toHex(),
encryptedContent: {
algorithm: asn1.derToOid(capture.encAlgorithm),
parameter: capture.encParameter ? capture.encParameter.value : undefined,
content: capture.encKey
}
};
}
/**
* Converts a single recipient object to an ASN.1 object.
*
* @param obj the recipient object.
*
* @return the ASN.1 RecipientInfo.
*/
function _recipientToAsn1(obj) {
return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Version
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
asn1.integerToDer(obj.version).getBytes()),
// IssuerAndSerialNumber
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Name
forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
// Serial
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
forge.util.hexToBytes(obj.serialNumber))
]),
// KeyEncryptionAlgorithmIdentifier
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// Algorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),
// Parameter, force NULL, only RSA supported for now.
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
]),
// EncryptedKey
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
obj.encryptedContent.content)
]);
}
/**
* Map a set of RecipientInfo ASN.1 objects to recipient objects.
*
* @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).
*
* @return an array of recipient objects.
*/
function _recipientsFromAsn1(infos) {
var ret = [];
for(var i = 0; i < infos.length; ++i) {
ret.push(_recipientFromAsn1(infos[i]));
}
return ret;
}
/**
* Map an array of recipient objects to ASN.1 RecipientInfo objects.
*
* @param recipients an array of recipientInfo objects.
*
* @return an array of ASN.1 RecipientInfos.
*/
function _recipientsToAsn1(recipients) {
var ret = [];
for(var i = 0; i < recipients.length; ++i) {
ret.push(_recipientToAsn1(recipients[i]));
}
return ret;
}
/**
* Converts a single signer from an ASN.1 object.
*
* @param obj the ASN.1 representation of a SignerInfo.
*
* @return the signer object.
*/
function _signerFromAsn1(obj) {
// validate EnvelopedData content block and capture data
var capture = {};
var errors = [];
if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {
var error = new Error('Cannot read PKCS#7 SignerInfo. ' +
'ASN.1 object is not an PKCS#7 SignerInfo.');
error.errors = errors;
throw error;
}
var rval = {
version: capture.version.charCodeAt(0),
issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
serialNumber: forge.util.createBuffer(capture.serial).toHex(),
digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),
signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),
signature: capture.signature,
authenticatedAttributes: [],
unauthenticatedAttributes: []
};
// TODO: convert attributes
var authenticatedAttributes = capture.authenticatedAttributes || [];
var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];
return rval;
}
/**
* Converts a single signerInfo object to an ASN.1 object.
*
* @param obj the signerInfo object.
*
* @return the ASN.1 representation of a SignerInfo.
*/
function _signerToAsn1(obj) {
// SignerInfo
var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// version
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
asn1.integerToDer(obj.version).getBytes()),
// issuerAndSerialNumber
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// name
forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
// serial
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
forge.util.hexToBytes(obj.serialNumber))
]),
// digestAlgorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// algorithm
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(obj.digestAlgorithm).getBytes()),
// parameters (null)
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
])
]);
// authenticatedAttributes (OPTIONAL)
if(obj.authenticatedAttributesAsn1) {
// add ASN.1 previously generated during signing
rval.value.push(obj.authenticatedAttributesAsn1);
}
// digestEncryptionAlgorithm
rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [