-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPKCS7.java
More file actions
1288 lines (1150 loc) · 46 KB
/
PKCS7.java
File metadata and controls
1288 lines (1150 loc) · 46 KB
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
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008 Ola Bini <ola.bini@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl.impl;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.X509CRL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.RC2ParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTCTime;
import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.X509Name;
import org.jruby.ext.openssl.OpenSSLReal;
import org.jruby.ext.openssl.x509store.Name;
import org.jruby.ext.openssl.x509store.Store;
import org.jruby.ext.openssl.x509store.StoreContext;
import org.jruby.ext.openssl.x509store.X509AuxCertificate;
import org.jruby.ext.openssl.x509store.X509Utils;
/** c: PKCS7
*
* Basically equivalent of the ContentInfo structures in PKCS#7.
*
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class PKCS7 {
// OpenSSL behavior: PKCS#7 ObjectId for "ITU-T" + "0"
private static final String EMPTY_PKCS7_OID = "0.0";
/* content as defined by the type */
/* all encryption/message digests are applied to the 'contents',
* leaving out the 'type' field. */
private PKCS7Data data;
public Object ctrl(int cmd, Object v, Object ignored) throws PKCS7Exception {
return this.data.ctrl(cmd, v, ignored);
}
public void setDetached(int v) throws PKCS7Exception {
ctrl(OP_SET_DETACHED_SIGNATURE, Integer.valueOf(v), null);
}
public int getDetached() throws PKCS7Exception {
return ((Integer)ctrl(OP_GET_DETACHED_SIGNATURE, null, null)).intValue();
}
public boolean isDetached() throws PKCS7Exception {
return isSigned() && getDetached() != 0;
}
private void initiateWith(Integer nid, DEREncodable content) throws PKCS7Exception {
this.data = PKCS7Data.fromASN1(nid, content);
}
/**
* ContentInfo ::= SEQUENCE {
* contentType ContentType,
* content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
*
* ContentType ::= OBJECT IDENTIFIER
*/
public static PKCS7 fromASN1(DEREncodable obj) throws PKCS7Exception {
PKCS7 p7 = new PKCS7();
int size = ((ASN1Sequence) obj).size();
if (size == 0) {
return p7;
}
DERObjectIdentifier contentType = (DERObjectIdentifier) (((ASN1Sequence) obj).getObjectAt(0));
if (EMPTY_PKCS7_OID.equals(contentType.getId())) {
// OpenSSL behavior
p7.setType(ASN1Registry.NID_undef);
} else {
int nid = ASN1Registry.obj2nid(contentType);
DEREncodable content = size == 1 ? (DEREncodable) null : ((ASN1Sequence) obj).getObjectAt(1);
if (content != null && content instanceof DERTaggedObject && ((DERTaggedObject) content).getTagNo() == 0) {
content = ((DERTaggedObject) content).getObject();
}
p7.initiateWith(nid, content);
}
return p7;
}
/* c: d2i_PKCS7_bio
*
*/
public static PKCS7 fromASN1(BIO bio) throws IOException, PKCS7Exception {
ASN1InputStream ais = new ASN1InputStream(BIO.asInputStream(bio));
return fromASN1(ais.readObject());
}
public ASN1Encodable asASN1() {
ASN1EncodableVector vector = new ASN1EncodableVector();
DERObjectIdentifier contentType;
if (data == null) {
// OpenSSL behavior
contentType = new DERObjectIdentifier(EMPTY_PKCS7_OID);
} else {
contentType = ASN1Registry.nid2obj(getType());
}
vector.add(contentType);
if (data != null) {
vector.add(new DERTaggedObject(0, data.asASN1()));
}
return new DERSequence(vector);
}
/* c: i2d_PKCS7
*
*/
public byte[] toASN1() throws IOException {
return asASN1().getEncoded();
}
/* c: PKCS7_add_signature
*
*/
public SignerInfoWithPkey addSignature(X509AuxCertificate x509, PrivateKey pkey, MessageDigest dgst) throws PKCS7Exception{
SignerInfoWithPkey si = new SignerInfoWithPkey();
si.set(x509, pkey, dgst);
addSigner(si);
return si;
}
/* c: X509_find_by_issuer_and_serial
*
*/
public static X509AuxCertificate findByIssuerAndSerial(Collection<X509AuxCertificate> certs, X509Name issuer, BigInteger serial) {
Name name = new Name(issuer);
for(X509AuxCertificate cert : certs) {
if(name.isEqual(cert.getIssuerX500Principal()) && serial.equals(cert.getSerialNumber())) {
return cert;
}
}
return null;
}
/* c: PKCS7_get0_signers
*
*/
public List<X509AuxCertificate> getSigners(Collection<X509AuxCertificate> certs, List<SignerInfoWithPkey> sinfos, int flags) throws PKCS7Exception {
List<X509AuxCertificate> signers = new ArrayList<X509AuxCertificate>();
if(!isSigned()) {
throw new PKCS7Exception(F_PKCS7_GET0_SIGNERS,R_WRONG_CONTENT_TYPE);
}
if(sinfos.size() == 0) {
throw new PKCS7Exception(F_PKCS7_GET0_SIGNERS,R_NO_SIGNERS);
}
for(SignerInfoWithPkey si : sinfos) {
IssuerAndSerialNumber ias = si.getIssuerAndSerialNumber();
X509AuxCertificate signer = null;
// System.err.println("looking for: " + ias.getName() + " and " + ias.getCertificateSerialNumber());
// System.err.println(" in: " + certs);
// System.err.println(" in: " + getSign().getCert());
if(certs != null) {
signer = findByIssuerAndSerial(certs, ias.getName(), ias.getCertificateSerialNumber().getValue());
}
if(signer == null && (flags & NOINTERN) == 0 && getSign().getCert() != null) {
signer = findByIssuerAndSerial(getSign().getCert(), ias.getName(), ias.getCertificateSerialNumber().getValue());
}
if(signer == null) {
throw new PKCS7Exception(F_PKCS7_GET0_SIGNERS,R_SIGNER_CERTIFICATE_NOT_FOUND);
}
signers.add(signer);
}
return signers;
}
/* c: PKCS7_digest_from_attributes
*
*/
public ASN1OctetString digestFromAttributes(ASN1Set attributes) {
return (ASN1OctetString)SignerInfoWithPkey.getAttribute(attributes, ASN1Registry.NID_pkcs9_messageDigest);
}
/* c: PKCS7_signatureVerify
*
*/
public void signatureVerify(BIO bio, SignerInfoWithPkey si, X509AuxCertificate x509) throws PKCS7Exception {
if(!isSigned() && !isSignedAndEnveloped()) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_WRONG_PKCS7_TYPE);
}
int md_type = ASN1Registry.obj2nid(si.getDigestAlgorithm().getObjectId());
BIO btmp = bio;
MessageDigest mdc = null;
for(;;) {
if(btmp == null || (btmp = bio.findType(BIO.TYPE_MD)) == null) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
}
mdc = ((MessageDigestBIOFilter)btmp).getMessageDigest();
if(null == mdc) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, -1);
}
if(EVP.type(mdc) == md_type) {
break;
}
btmp = btmp.next();
}
MessageDigest mdc_tmp = null;
try {
mdc_tmp = (MessageDigest)mdc.clone();
} catch(Exception e) {}
byte[] currentData = new byte[0];
ASN1Set sk = si.getAuthenticatedAttributes();
try {
if(sk != null && sk.size() > 0) {
byte[] md_dat = mdc_tmp.digest();
ASN1OctetString message_digest = digestFromAttributes(sk);
if(message_digest == null) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
}
if(!Arrays.equals(md_dat, message_digest.getOctets())) {
throw new NotVerifiedPKCS7Exception();
}
currentData = sk.getEncoded();
}
ASN1OctetString os = si.getEncryptedDigest();
PublicKey pkey = x509.getPublicKey();
Signature sign = Signature.getInstance(EVP.signatureAlgorithm(mdc_tmp, pkey));
sign.initVerify(pkey);
if(currentData.length > 0) {
sign.update(currentData);
}
if(!sign.verify(os.getOctets())) {
throw new NotVerifiedPKCS7Exception();
}
} catch(NotVerifiedPKCS7Exception e) {
throw e;
} catch(Exception e) {
System.err.println("Other exception");
e.printStackTrace();
throw new NotVerifiedPKCS7Exception();
}
}
/* c: PKCS7_verify
*
*/
public void verify(Collection<X509AuxCertificate> certs, Store store, BIO indata, BIO out, int flags) throws PKCS7Exception {
if(!isSigned()) {
throw new PKCS7Exception(F_PKCS7_VERIFY, R_WRONG_CONTENT_TYPE);
}
if(getDetached() != 0 && indata == null) {
throw new PKCS7Exception(F_PKCS7_VERIFY, R_NO_CONTENT);
}
List<SignerInfoWithPkey> sinfos = new ArrayList<SignerInfoWithPkey>(getSignerInfo());
if(sinfos.size() == 0) {
throw new PKCS7Exception(F_PKCS7_VERIFY, R_NO_SIGNATURES_ON_DATA);
}
List<X509AuxCertificate> signers = getSigners(certs, sinfos, flags);
if(signers == null) {
throw new NotVerifiedPKCS7Exception();
}
/* Now verify the certificates */
if((flags & NOVERIFY) == 0) {
for(X509AuxCertificate signer : signers) {
StoreContext cert_ctx = new StoreContext();
if((flags & NOCHAIN) == 0) {
if(cert_ctx.init(store, signer, new ArrayList<X509AuxCertificate>(getSign().getCert())) == 0) {
throw new PKCS7Exception(F_PKCS7_VERIFY, -1);
}
cert_ctx.setPurpose(X509Utils.X509_PURPOSE_SMIME_SIGN);
} else if(cert_ctx.init(store, signer, null) == 0) {
throw new PKCS7Exception(F_PKCS7_VERIFY, -1);
}
cert_ctx.setExtraData(1, store.getExtraData(1));
if((flags & NOCRL) == 0) {
cert_ctx.setCRLs((List<X509CRL>)getSign().getCrl());
}
try {
int i = cert_ctx.verifyCertificate();
int j = 0;
if(i <= 0) {
j = cert_ctx.getError();
}
cert_ctx.cleanup();
if(i <= 0) {
throw new PKCS7Exception(F_PKCS7_VERIFY, R_CERTIFICATE_VERIFY_ERROR, "Verify error:" + X509Utils.verifyCertificateErrorString(j));
}
} catch(PKCS7Exception e) {
throw e;
} catch(Exception e) {
throw new PKCS7Exception(F_PKCS7_VERIFY, R_CERTIFICATE_VERIFY_ERROR, e);
}
}
}
BIO tmpin = indata;
BIO p7bio = dataInit(tmpin);
BIO tmpout = null;
if((flags & TEXT) != 0) {
tmpout = BIO.mem();
} else {
tmpout = out;
}
byte[] buf = new byte[4096];
for(;;) {
try {
int i = p7bio.read(buf, 0, buf.length);
if(i <= 0) {
break;
}
if(tmpout != null) {
tmpout.write(buf, 0, i);
}
} catch(IOException e) {
throw new PKCS7Exception(F_PKCS7_VERIFY, -1, e);
}
}
if((flags & TEXT) != 0) {
new SMIME(Mime.DEFAULT).text(tmpout, out);
}
if((flags & NOSIGS) == 0) {
for(int i=0; i<sinfos.size(); i++) {
SignerInfoWithPkey si = sinfos.get(i);
X509AuxCertificate signer = signers.get(i);
signatureVerify(p7bio, si, signer);
}
}
if(tmpin == indata) {
if(indata != null) {
p7bio.pop();
}
}
}
/* c: PKCS7_sign
*
*/
public static PKCS7 sign(X509AuxCertificate signcert, PrivateKey pkey, Collection<X509AuxCertificate> certs, BIO data, int flags) throws PKCS7Exception {
PKCS7 p7 = new PKCS7();
p7.setType(ASN1Registry.NID_pkcs7_signed);
p7.contentNew(ASN1Registry.NID_pkcs7_data);
SignerInfoWithPkey si = p7.addSignature(signcert, pkey, EVP.sha1());
if((flags & NOCERTS) == 0) {
p7.addCertificate(signcert);
if(certs != null) {
for(X509AuxCertificate c : certs) {
p7.addCertificate(c);
}
}
}
if((flags & NOATTR) == 0) {
si.addSignedAttribute(ASN1Registry.NID_pkcs9_contentType, ASN1Registry.nid2obj(ASN1Registry.NID_pkcs7_data));
if((flags & NOSMIMECAP) == 0) {
ASN1EncodableVector smcap = new ASN1EncodableVector();
smcap.add(new AlgorithmIdentifier(ASN1Registry.nid2obj(ASN1Registry.NID_des_ede3_cbc)));
smcap.add(new AlgorithmIdentifier(ASN1Registry.nid2obj(ASN1Registry.NID_rc2_cbc), new DERInteger(128)));
smcap.add(new AlgorithmIdentifier(ASN1Registry.nid2obj(ASN1Registry.NID_rc2_cbc), new DERInteger(64)));
smcap.add(new AlgorithmIdentifier(ASN1Registry.nid2obj(ASN1Registry.NID_rc2_cbc), new DERInteger(40)));
smcap.add(new AlgorithmIdentifier(ASN1Registry.nid2obj(ASN1Registry.NID_des_cbc)));
si.addSignedAttribute(ASN1Registry.NID_SMIMECapabilities, new DERSequence(smcap));
}
}
if((flags & STREAM) != 0) {
return p7;
}
BIO p7bio = p7.dataInit(null);
try {
data.crlfCopy(p7bio, flags);
} catch(IOException e) {
throw new PKCS7Exception(F_PKCS7_SIGN, R_PKCS7_DATAFINAL_ERROR, e);
}
if((flags & DETACHED) != 0) {
p7.setDetached(1);
}
p7.dataFinal(p7bio);
return p7;
}
/* c: PKCS7_encrypt
*
*/
public static PKCS7 encrypt(Collection<X509AuxCertificate> certs, byte[] in, CipherSpec cipher, int flags) throws PKCS7Exception {
PKCS7 p7 = new PKCS7();
p7.setType(ASN1Registry.NID_pkcs7_enveloped);
try {
p7.setCipher(cipher);
for(X509AuxCertificate x509 : certs) {
p7.addRecipient(x509);
}
BIO p7bio = p7.dataInit(null);
BIO.memBuf(in).crlfCopy(p7bio, flags);
p7bio.flush();
p7.dataFinal(p7bio);
return p7;
} catch(IOException e) {
throw new PKCS7Exception(F_PKCS7_ENCRYPT, R_PKCS7_DATAFINAL_ERROR, e);
}
}
/* c: PKCS7_decrypt
*
*/
public void decrypt(PrivateKey pkey, X509AuxCertificate cert, BIO data, int flags) throws PKCS7Exception {
if(!isEnveloped()) {
throw new PKCS7Exception(F_PKCS7_DECRYPT, R_WRONG_CONTENT_TYPE);
}
try {
BIO tmpmem = dataDecode(pkey, null, cert);
if((flags & TEXT) == TEXT) {
BIO tmpbuf = BIO.buffered();
BIO bread = tmpbuf.push(tmpmem);
new SMIME(Mime.DEFAULT).text(bread, data);
} else {
int i;
byte[] buf = new byte[4096];
while((i = tmpmem.read(buf, 0, 4096)) > 0) {
data.write(buf, 0, i);
}
}
} catch(IOException e) {
throw new PKCS7Exception(F_PKCS7_DECRYPT, R_DECRYPT_ERROR, e);
}
}
/** c: PKCS7_set_type
*
*/
public void setType(int type) throws PKCS7Exception {
switch(type) {
case ASN1Registry.NID_undef:
this.data = null;
break;
case ASN1Registry.NID_pkcs7_signed:
this.data = new PKCS7DataSigned();
break;
case ASN1Registry.NID_pkcs7_data:
this.data = new PKCS7DataData();
break;
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
this.data = new PKCS7DataSignedAndEnveloped();
break;
case ASN1Registry.NID_pkcs7_enveloped:
this.data = new PKCS7DataEnveloped();
break;
case ASN1Registry.NID_pkcs7_encrypted:
this.data = new PKCS7DataEncrypted();
break;
case ASN1Registry.NID_pkcs7_digest:
this.data = new PKCS7DataDigest();
break;
default:
throw new PKCS7Exception(F_PKCS7_SET_TYPE,R_UNSUPPORTED_CONTENT_TYPE);
}
}
/** c: PKCS7_set_cipher
*
*/
public void setCipher(CipherSpec cipher) throws PKCS7Exception {
this.data.setCipher(cipher);
}
/** c: PKCS7_add_recipient
*
*/
public RecipInfo addRecipient(X509AuxCertificate recip) throws PKCS7Exception {
RecipInfo ri = new RecipInfo();
ri.set(recip);
addRecipientInfo(ri);
return ri;
}
/** c: PKCS7_content_new
*
*/
public void contentNew(int nid) throws PKCS7Exception {
PKCS7 ret = new PKCS7();
ret.setType(nid);
this.setContent(ret);
}
/** c: PKCS7_add_signer
*
*/
public void addSigner(SignerInfoWithPkey psi) throws PKCS7Exception {
this.data.addSigner(psi);
}
/** c: PKCS7_add_certificate
*
*/
public void addCertificate(X509AuxCertificate cert) throws PKCS7Exception {
this.data.addCertificate(cert);
}
/** c: PKCS7_add_crl
*
*/
public void addCRL(X509CRL crl) throws PKCS7Exception {
this.data.addCRL(crl);
}
/** c: PKCS7_add_recipient_info
*
*/
public void addRecipientInfo(RecipInfo ri) throws PKCS7Exception {
this.data.addRecipientInfo(ri);
}
/** c: PKCS7_set_content
*
*/
public void setContent(PKCS7 p7) throws PKCS7Exception {
this.data.setContent(p7);
}
/** c: PKCS7_get_signer_info
*
*/
public Collection<SignerInfoWithPkey> getSignerInfo() {
return this.data.getSignerInfo();
}
private final static byte[] PEM_STRING_PKCS7_START = "-----BEGIN PKCS7-----".getBytes();
/** c: PEM_read_bio_PKCS7
*
*/
public static PKCS7 readPEM(BIO input) throws PKCS7Exception {
try {
byte[] buffer = new byte[SMIME.MAX_SMLEN];
int read = -1;
read = input.gets(buffer, SMIME.MAX_SMLEN);
if(read > PEM_STRING_PKCS7_START.length) {
byte[] tmp = new byte[PEM_STRING_PKCS7_START.length];
System.arraycopy(buffer, 0, tmp, 0, tmp.length);
if(Arrays.equals(PEM_STRING_PKCS7_START, tmp)) {
return fromASN1(BIO.base64Filter(input));
} else {
return null;
}
} else {
return null;
}
} catch(IOException e) {
return null;
}
}
/** c: stati PKCS7_bio_add_digest
*
*/
public BIO bioAddDigest(BIO pbio, AlgorithmIdentifier alg) throws PKCS7Exception {
try {
MessageDigest md = EVP.getDigest(alg.getObjectId());
BIO btmp = BIO.mdFilter(md);
if(pbio == null) {
return btmp;
} else {
pbio.push(btmp);
return pbio;
}
} catch(Exception e) {
throw new PKCS7Exception(F_PKCS7_BIO_ADD_DIGEST, R_UNKNOWN_DIGEST_TYPE, e);
}
}
/** c: PKCS7_dataDecode
*
*/
public BIO dataDecode(PrivateKey pkey, BIO inBio, X509AuxCertificate pcert) throws PKCS7Exception {
BIO out = null;
BIO btmp = null;
BIO etmp = null;
BIO bio = null;
byte[] dataBody = null;
Collection<AlgorithmIdentifier> mdSk = null;
Collection<RecipInfo> rsk = null;
AlgorithmIdentifier encAlg = null;
Cipher evpCipher = null;
RecipInfo ri = null;
int i = getType();
switch(i) {
case ASN1Registry.NID_pkcs7_signed:
dataBody = getSign().getContents().getOctetString().getOctets();
mdSk = getSign().getMdAlgs();
break;
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
rsk = getSignedAndEnveloped().getRecipientInfo();
mdSk = getSignedAndEnveloped().getMdAlgs();
dataBody = getSignedAndEnveloped().getEncData().getEncData().getOctets();
encAlg = getSignedAndEnveloped().getEncData().getAlgorithm();
try {
evpCipher = getCipher(encAlg.getObjectId());
} catch(Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
}
break;
case ASN1Registry.NID_pkcs7_enveloped:
rsk = getEnveloped().getRecipientInfo();
dataBody = getEnveloped().getEncData().getEncData().getOctets();
encAlg = getEnveloped().getEncData().getAlgorithm();
try {
evpCipher = getCipher(encAlg.getObjectId());
} catch(Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
}
break;
default:
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CONTENT_TYPE);
}
/* We will be checking the signature */
if(mdSk != null) {
for(AlgorithmIdentifier xa : mdSk) {
try {
MessageDigest evpMd = EVP.getDigest(xa.getObjectId());
btmp = BIO.mdFilter(evpMd);
if(out == null) {
out = btmp;
} else {
out.push(btmp);
}
btmp = null;
} catch(Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNKNOWN_DIGEST_TYPE, e);
}
}
}
if(evpCipher != null) {
/* It was encrypted, we need to decrypt the secret key
* with the private key */
/* Find the recipientInfo which matches the passed certificate
* (if any)
*/
if(pcert != null) {
for(Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext();) {
ri = iter.next();
if(ri.compare(pcert)) {
break;
}
ri = null;
}
if(null == ri) {
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_CERTIFICATE);
}
}
byte[] tmp = null;
/* If we haven't got a certificate try each ri in turn */
if(null == pcert) {
for(Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext();) {
ri = iter.next();
try {
tmp = EVP.decrypt(ri.getEncKey().getOctets(), pkey);
if(tmp != null) {
break;
}
} catch(Exception e) {
tmp = null;
}
ri = null;
}
if(ri == null) {
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_KEY);
}
} else {
try {
Cipher cipher = Cipher.getInstance(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
cipher.init(Cipher.DECRYPT_MODE, pkey);
tmp = cipher.doFinal(ri.getEncKey().getOctets());
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
}
}
DEREncodable params = encAlg.getParameters();
try {
if(params != null && params instanceof ASN1OctetString) {
if (evpCipher.getAlgorithm().startsWith("RC2")) {
// J9's IBMJCE needs this exceptional RC2 support.
// Giving IvParameterSpec throws 'Illegal parameter' on IBMJCE.
SecretKeySpec sks = new SecretKeySpec(tmp, evpCipher.getAlgorithm());
RC2ParameterSpec s = new RC2ParameterSpec(tmp.length * 8, ((ASN1OctetString) params).getOctets());
evpCipher.init(Cipher.DECRYPT_MODE, sks, s);
} else {
SecretKeySpec sks = new SecretKeySpec(tmp, evpCipher.getAlgorithm());
IvParameterSpec iv = new IvParameterSpec(((ASN1OctetString) params).getOctets());
evpCipher.init(Cipher.DECRYPT_MODE, sks, iv);
}
} else {
evpCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(tmp, evpCipher.getAlgorithm()));
}
} catch(Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
}
etmp = BIO.cipherFilter(evpCipher);
if(out == null) {
out = etmp;
} else {
out.push(etmp);
}
etmp = null;
}
if(isDetached() || inBio != null) {
bio = inBio;
} else {
if(dataBody != null && dataBody.length > 0) {
bio = BIO.memBuf(dataBody);
} else {
bio = BIO.mem();
}
}
out.push(bio);
bio = null;
return out;
}
// Without Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files,
// getting Cipher object via OID(1.2.840.113549.3.7 - DES-EDE3-CBC) causes 'Illegal Key Length'
// exception. To avoid this, we get Cipher object via algo name(DESede/cbc/PKCS5Padding).
private static Cipher getCipher(DERObjectIdentifier oid) throws GeneralSecurityException {
// check DES-EDE3-CBC
if (oid.getId().equals("1.2.840.113549.3.7")) {
return OpenSSLReal.getCipherBC("DESede/cbc/PKCS5Padding");
}
return EVP.getCipher(oid);
}
/** c: PKCS7_dataInit
*
*/
public BIO dataInit(BIO bio) throws PKCS7Exception {
Collection<AlgorithmIdentifier> mdSk = null;
ASN1OctetString os = null;
int i = this.data.getType();
Collection<RecipInfo> rsk = null;
AlgorithmIdentifier xa = null;
CipherSpec evpCipher = null;
BIO out = null;
BIO btmp = null;
EncContent enc = null;
switch (i) {
case ASN1Registry.NID_pkcs7_signed:
mdSk = getSign().getMdAlgs();
os = getSign().getContents().getOctetString();
break;
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
rsk = getSignedAndEnveloped().getRecipientInfo();
mdSk = getSignedAndEnveloped().getMdAlgs();
enc = getSignedAndEnveloped().getEncData();
evpCipher = getSignedAndEnveloped().getEncData().getCipher();
if (null == evpCipher) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
}
break;
case ASN1Registry.NID_pkcs7_enveloped:
rsk = getEnveloped().getRecipientInfo();
enc = getEnveloped().getEncData();
evpCipher = getEnveloped().getEncData().getCipher();
if (null == evpCipher) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
}
break;
case ASN1Registry.NID_pkcs7_digest:
xa = getDigest().getMd();
os = getDigest().getContents().getOctetString();
break;
default:
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_UNSUPPORTED_CONTENT_TYPE);
}
if (mdSk != null) {
for (AlgorithmIdentifier ai : mdSk) {
if ((out = bioAddDigest(out, ai)) == null) {
return null;
}
}
}
if (xa != null && (out = bioAddDigest(out, xa)) == null) {
return null;
}
if (evpCipher != null) {
byte[] tmp;
btmp = BIO.cipherFilter(evpCipher.getCipher());
String algoBase = evpCipher.getCipher().getAlgorithm();
if (algoBase.indexOf('/') != -1) {
algoBase = algoBase.split("/")[0];
}
try {
KeyGenerator gen = KeyGenerator.getInstance(algoBase);
gen.init(evpCipher.getKeyLenInBits(), new SecureRandom());
SecretKey key = gen.generateKey();
evpCipher.getCipher().init(Cipher.ENCRYPT_MODE, key);
if (null != rsk) {
for (RecipInfo ri : rsk) {
PublicKey pkey = ri.getCert().getPublicKey();
Cipher cipher = Cipher.getInstance(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
cipher.init(Cipher.ENCRYPT_MODE, pkey);
tmp = cipher.doFinal(key.getEncoded());
ri.setEncKey(new DEROctetString(tmp));
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_ERROR_SETTING_CIPHER, e);
}
DERObjectIdentifier encAlgo = ASN1Registry.sym2oid(evpCipher.getOsslName());
if (encAlgo == null) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_HAS_NO_OBJECT_IDENTIFIER);
}
if (evpCipher.getCipher().getIV() != null) {
enc.setAlgorithm(new AlgorithmIdentifier(encAlgo, new DEROctetString(evpCipher.getCipher().getIV())));
} else {
enc.setAlgorithm(new AlgorithmIdentifier(encAlgo));
}
if (out == null) {
out = btmp;
} else {
out.push(btmp);
}
btmp = null;
}
if (bio == null) {
if (isDetached()) {
bio = BIO.nullSink();
} else if (os != null && os.getOctets().length > 0) {
bio = BIO.memBuf(os.getOctets());
}
if (bio == null) {
bio = BIO.mem();
bio.setMemEofReturn(0);
}
}
if (out != null) {
out.push(bio);
} else {
out = bio;
}
bio = null;
return out;
}
/** c: static PKCS7_find_digest
*
*/
public BIO findDigest(MessageDigest[] pmd, BIO bio, int nid) throws PKCS7Exception {
while(true) {
bio = bio.findType(BIO.TYPE_MD);
if(bio == null) {
throw new PKCS7Exception(F_PKCS7_FIND_DIGEST, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
}
pmd[0] = ((MessageDigestBIOFilter)bio).getMessageDigest();
if(pmd[0] == null) {
throw new PKCS7Exception(F_PKCS7_FIND_DIGEST, -1);
}
if(nid == EVP.type(pmd[0])) {
return bio;
}
bio = bio.next();
}
}
/** c: PKCS7_dataFinal
*
*/
public int dataFinal(BIO bio) throws PKCS7Exception {
Collection<SignerInfoWithPkey> siSk = null;
BIO btmp;
byte[] buf;
MessageDigest mdc = null;
MessageDigest ctx_tmp = null;
ASN1Set sk;
int i = this.data.getType();
switch(i) {
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
siSk = getSignedAndEnveloped().getSignerInfo();
break;
case ASN1Registry.NID_pkcs7_signed:
siSk = getSign().getSignerInfo();
break;
case ASN1Registry.NID_pkcs7_digest:
break;
default:
break;
}
if(siSk != null) {
for(SignerInfoWithPkey si : siSk) {
if(si.getPkey() == null) {
continue;
}