Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java
41159 views
1
/*
2
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.pkcs;
27
28
import java.io.OutputStream;
29
import java.io.IOException;
30
import java.math.BigInteger;
31
import java.security.cert.CertPathValidatorException;
32
import java.security.cert.CertificateException;
33
import java.security.cert.CertificateFactory;
34
import java.security.cert.CertPath;
35
import java.security.cert.X509Certificate;
36
import java.security.*;
37
import java.security.spec.PSSParameterSpec;
38
import java.util.ArrayList;
39
import java.util.Collections;
40
import java.util.Date;
41
import java.util.HashMap;
42
import java.util.HashSet;
43
import java.util.Map;
44
import java.util.Set;
45
46
import sun.security.provider.SHAKE256;
47
import sun.security.timestamp.TimestampToken;
48
import sun.security.util.*;
49
import sun.security.x509.AlgorithmId;
50
import sun.security.x509.X500Name;
51
import sun.security.x509.KeyUsageExtension;
52
53
/**
54
* A SignerInfo, as defined in PKCS#7's signedData type.
55
*
56
* @author Benjamin Renaud
57
*/
58
public class SignerInfo implements DerEncoder {
59
60
private static final DisabledAlgorithmConstraints JAR_DISABLED_CHECK =
61
DisabledAlgorithmConstraints.jarConstraints();
62
63
BigInteger version;
64
X500Name issuerName;
65
BigInteger certificateSerialNumber;
66
AlgorithmId digestAlgorithmId;
67
AlgorithmId digestEncryptionAlgorithmId;
68
byte[] encryptedDigest;
69
Timestamp timestamp;
70
private boolean hasTimestamp = true;
71
private static final Debug debug = Debug.getInstance("jar");
72
73
PKCS9Attributes authenticatedAttributes;
74
PKCS9Attributes unauthenticatedAttributes;
75
76
/**
77
* A map containing the algorithms in this SignerInfo. This is used to
78
* avoid checking algorithms to see if they are disabled more than once.
79
* The key is the AlgorithmId of the algorithm, and the value is the name of
80
* the field or attribute.
81
*/
82
private Map<AlgorithmId, String> algorithms = new HashMap<>();
83
84
public SignerInfo(X500Name issuerName,
85
BigInteger serial,
86
AlgorithmId digestAlgorithmId,
87
AlgorithmId digestEncryptionAlgorithmId,
88
byte[] encryptedDigest) {
89
this(issuerName, serial, digestAlgorithmId, null,
90
digestEncryptionAlgorithmId, encryptedDigest, null);
91
}
92
93
public SignerInfo(X500Name issuerName,
94
BigInteger serial,
95
AlgorithmId digestAlgorithmId,
96
PKCS9Attributes authenticatedAttributes,
97
AlgorithmId digestEncryptionAlgorithmId,
98
byte[] encryptedDigest,
99
PKCS9Attributes unauthenticatedAttributes) {
100
this.version = BigInteger.ONE;
101
this.issuerName = issuerName;
102
this.certificateSerialNumber = serial;
103
this.digestAlgorithmId = digestAlgorithmId;
104
this.authenticatedAttributes = authenticatedAttributes;
105
this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
106
this.encryptedDigest = encryptedDigest;
107
this.unauthenticatedAttributes = unauthenticatedAttributes;
108
}
109
110
/**
111
* Parses a PKCS#7 signer info.
112
*/
113
public SignerInfo(DerInputStream derin)
114
throws IOException, ParsingException
115
{
116
this(derin, false);
117
}
118
119
/**
120
* Parses a PKCS#7 signer info.
121
*
122
* <p>This constructor is used only for backwards compatibility with
123
* PKCS#7 blocks that were generated using JDK1.1.x.
124
*
125
* @param derin the ASN.1 encoding of the signer info.
126
* @param oldStyle flag indicating whether or not the given signer info
127
* is encoded according to JDK1.1.x.
128
*/
129
public SignerInfo(DerInputStream derin, boolean oldStyle)
130
throws IOException, ParsingException
131
{
132
// version
133
version = derin.getBigInteger();
134
135
// issuerAndSerialNumber
136
DerValue[] issuerAndSerialNumber = derin.getSequence(2);
137
if (issuerAndSerialNumber.length != 2) {
138
throw new ParsingException("Invalid length for IssuerAndSerialNumber");
139
}
140
byte[] issuerBytes = issuerAndSerialNumber[0].toByteArray();
141
issuerName = new X500Name(new DerValue(DerValue.tag_Sequence,
142
issuerBytes));
143
certificateSerialNumber = issuerAndSerialNumber[1].getBigInteger();
144
145
// digestAlgorithmId
146
DerValue tmp = derin.getDerValue();
147
148
digestAlgorithmId = AlgorithmId.parse(tmp);
149
150
// authenticatedAttributes
151
if (oldStyle) {
152
// In JDK1.1.x, the authenticatedAttributes are always present,
153
// encoded as an empty Set (Set of length zero)
154
derin.getSet(0);
155
} else {
156
// check if set of auth attributes (implicit tag) is provided
157
// (auth attributes are OPTIONAL)
158
if ((byte)(derin.peekByte()) == (byte)0xA0) {
159
authenticatedAttributes = new PKCS9Attributes(derin);
160
}
161
}
162
163
// digestEncryptionAlgorithmId - little RSA naming scheme -
164
// signature == encryption...
165
tmp = derin.getDerValue();
166
167
digestEncryptionAlgorithmId = AlgorithmId.parse(tmp);
168
169
// encryptedDigest
170
encryptedDigest = derin.getOctetString();
171
172
// unauthenticatedAttributes
173
if (oldStyle) {
174
// In JDK1.1.x, the unauthenticatedAttributes are always present,
175
// encoded as an empty Set (Set of length zero)
176
derin.getSet(0);
177
} else {
178
// check if set of unauth attributes (implicit tag) is provided
179
// (unauth attributes are OPTIONAL)
180
if (derin.available() != 0
181
&& (byte)(derin.peekByte()) == (byte)0xA1) {
182
unauthenticatedAttributes =
183
new PKCS9Attributes(derin, true);// ignore unsupported attrs
184
}
185
}
186
187
// all done
188
if (derin.available() != 0) {
189
throw new ParsingException("extra data at the end");
190
}
191
192
// verify CMSAlgorithmProtection
193
checkCMSAlgorithmProtection();
194
}
195
196
// CMSAlgorithmProtection verification as described in RFC 6211
197
private void checkCMSAlgorithmProtection() throws IOException {
198
if (authenticatedAttributes == null) {
199
return;
200
}
201
PKCS9Attribute ap = authenticatedAttributes.getAttribute(
202
PKCS9Attribute.CMS_ALGORITHM_PROTECTION_OID);
203
if (ap == null) {
204
return;
205
}
206
DerValue dv = new DerValue((byte[])ap.getValue());
207
DerInputStream data = dv.data();
208
AlgorithmId d = AlgorithmId.parse(data.getDerValue());
209
DerValue ds = data.getDerValue();
210
if (data.available() > 0) {
211
throw new IOException("Unknown field in CMSAlgorithmProtection");
212
}
213
if (!ds.isContextSpecific((byte)1)) {
214
throw new IOException("No signature algorithm in CMSAlgorithmProtection");
215
}
216
AlgorithmId s = AlgorithmId.parse(ds.withTag(DerValue.tag_Sequence));
217
if (!s.equals(digestEncryptionAlgorithmId)
218
|| !d.equals(digestAlgorithmId)) {
219
throw new IOException("CMSAlgorithmProtection check failed");
220
}
221
}
222
223
public void encode(DerOutputStream out) throws IOException {
224
225
derEncode(out);
226
}
227
228
/**
229
* DER encode this object onto an output stream.
230
* Implements the {@code DerEncoder} interface.
231
*
232
* @param out
233
* the output stream on which to write the DER encoding.
234
*
235
* @exception IOException on encoding error.
236
*/
237
public void derEncode(OutputStream out) throws IOException {
238
DerOutputStream seq = new DerOutputStream();
239
seq.putInteger(version);
240
DerOutputStream issuerAndSerialNumber = new DerOutputStream();
241
issuerName.encode(issuerAndSerialNumber);
242
issuerAndSerialNumber.putInteger(certificateSerialNumber);
243
seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
244
245
digestAlgorithmId.encode(seq);
246
247
// encode authenticated attributes if there are any
248
if (authenticatedAttributes != null)
249
authenticatedAttributes.encode((byte)0xA0, seq);
250
251
digestEncryptionAlgorithmId.encode(seq);
252
253
seq.putOctetString(encryptedDigest);
254
255
// encode unauthenticated attributes if there are any
256
if (unauthenticatedAttributes != null)
257
unauthenticatedAttributes.encode((byte)0xA1, seq);
258
259
DerOutputStream tmp = new DerOutputStream();
260
tmp.write(DerValue.tag_Sequence, seq);
261
262
out.write(tmp.toByteArray());
263
}
264
265
/*
266
* Returns the (user) certificate pertaining to this SignerInfo.
267
*/
268
public X509Certificate getCertificate(PKCS7 block)
269
throws IOException
270
{
271
return block.getCertificate(certificateSerialNumber, issuerName);
272
}
273
274
/*
275
* Returns the certificate chain pertaining to this SignerInfo.
276
*/
277
public ArrayList<X509Certificate> getCertificateChain(PKCS7 block)
278
throws IOException
279
{
280
X509Certificate userCert;
281
userCert = block.getCertificate(certificateSerialNumber, issuerName);
282
if (userCert == null)
283
return null;
284
285
ArrayList<X509Certificate> certList = new ArrayList<>();
286
certList.add(userCert);
287
288
X509Certificate[] pkcsCerts = block.getCertificates();
289
if (pkcsCerts == null
290
|| userCert.getSubjectX500Principal().equals(userCert.getIssuerX500Principal())) {
291
return certList;
292
}
293
294
Principal issuer = userCert.getIssuerX500Principal();
295
int start = 0;
296
while (true) {
297
boolean match = false;
298
int i = start;
299
while (i < pkcsCerts.length) {
300
if (issuer.equals(pkcsCerts[i].getSubjectX500Principal())) {
301
// next cert in chain found
302
certList.add(pkcsCerts[i]);
303
// if selected cert is self-signed, we're done
304
// constructing the chain
305
if (pkcsCerts[i].getSubjectX500Principal().equals(
306
pkcsCerts[i].getIssuerX500Principal())) {
307
start = pkcsCerts.length;
308
} else {
309
issuer = pkcsCerts[i].getIssuerX500Principal();
310
X509Certificate tmpCert = pkcsCerts[start];
311
pkcsCerts[start] = pkcsCerts[i];
312
pkcsCerts[i] = tmpCert;
313
start++;
314
}
315
match = true;
316
break;
317
} else {
318
i++;
319
}
320
}
321
if (!match)
322
break;
323
}
324
325
return certList;
326
}
327
328
/* Returns null if verify fails, this signerInfo if
329
verify succeeds. */
330
SignerInfo verify(PKCS7 block, byte[] data)
331
throws NoSuchAlgorithmException, SignatureException {
332
333
try {
334
Timestamp timestamp = getTimestamp();
335
336
ContentInfo content = block.getContentInfo();
337
if (data == null) {
338
data = content.getContentBytes();
339
}
340
341
String digestAlgName = digestAlgorithmId.getName();
342
algorithms.put(digestAlgorithmId, "SignerInfo digestAlgorithm field");
343
344
byte[] dataSigned;
345
346
// if there are authenticate attributes, get the message
347
// digest and compare it with the digest of data
348
if (authenticatedAttributes == null) {
349
dataSigned = data;
350
} else {
351
352
// first, check content type
353
ObjectIdentifier contentType = (ObjectIdentifier)
354
authenticatedAttributes.getAttributeValue(
355
PKCS9Attribute.CONTENT_TYPE_OID);
356
if (contentType == null ||
357
!contentType.equals(content.contentType))
358
return null; // contentType does not match, bad SignerInfo
359
360
// now, check message digest
361
byte[] messageDigest = (byte[])
362
authenticatedAttributes.getAttributeValue(
363
PKCS9Attribute.MESSAGE_DIGEST_OID);
364
365
if (messageDigest == null) // fail if there is no message digest
366
return null;
367
368
byte[] computedMessageDigest;
369
if (digestAlgName.equals("SHAKE256")
370
|| digestAlgName.equals("SHAKE256-LEN")) {
371
if (digestAlgName.equals("SHAKE256-LEN")) {
372
int v = new DerValue(digestAlgorithmId
373
.getEncodedParams()).getInteger();
374
if (v != 512) {
375
throw new SignatureException(
376
"Unsupported id-shake256-" + v);
377
}
378
}
379
var md = new SHAKE256(64);
380
md.update(data, 0, data.length);
381
computedMessageDigest = md.digest();
382
} else {
383
MessageDigest md = MessageDigest.getInstance(digestAlgName);
384
computedMessageDigest = md.digest(data);
385
}
386
387
if (!MessageDigest.isEqual(messageDigest, computedMessageDigest)) {
388
return null;
389
}
390
391
// message digest attribute matched
392
// digest of original data
393
394
// the data actually signed is the DER encoding of
395
// the authenticated attributes (tagged with
396
// the "SET OF" tag, not 0xA0).
397
dataSigned = authenticatedAttributes.getDerEncoding();
398
}
399
400
// put together digest algorithm and encryption algorithm
401
// to form signing algorithm. See makeSigAlg for details.
402
String sigAlgName = makeSigAlg(
403
digestAlgorithmId,
404
digestEncryptionAlgorithmId,
405
authenticatedAttributes == null);
406
407
KnownOIDs oid = KnownOIDs.findMatch(sigAlgName);
408
if (oid != null) {
409
AlgorithmId sigAlgId =
410
new AlgorithmId(ObjectIdentifier.of(oid),
411
digestEncryptionAlgorithmId.getParameters());
412
algorithms.put(sigAlgId,
413
"SignerInfo digestEncryptionAlgorithm field");
414
}
415
416
X509Certificate cert = getCertificate(block);
417
if (cert == null) {
418
return null;
419
}
420
PublicKey key = cert.getPublicKey();
421
422
if (cert.hasUnsupportedCriticalExtension()) {
423
throw new SignatureException("Certificate has unsupported "
424
+ "critical extension(s)");
425
}
426
427
// Make sure that if the usage of the key in the certificate is
428
// restricted, it can be used for digital signatures.
429
// XXX We may want to check for additional extensions in the
430
// future.
431
boolean[] keyUsageBits = cert.getKeyUsage();
432
if (keyUsageBits != null) {
433
KeyUsageExtension keyUsage;
434
try {
435
// We don't care whether or not this extension was marked
436
// critical in the certificate.
437
// We're interested only in its value (i.e., the bits set)
438
// and treat the extension as critical.
439
keyUsage = new KeyUsageExtension(keyUsageBits);
440
} catch (IOException ioe) {
441
throw new SignatureException("Failed to parse keyUsage "
442
+ "extension");
443
}
444
445
boolean digSigAllowed
446
= keyUsage.get(KeyUsageExtension.DIGITAL_SIGNATURE);
447
448
boolean nonRepuAllowed
449
= keyUsage.get(KeyUsageExtension.NON_REPUDIATION);
450
451
if (!digSigAllowed && !nonRepuAllowed) {
452
throw new SignatureException("Key usage restricted: "
453
+ "cannot be used for "
454
+ "digital signatures");
455
}
456
}
457
458
Signature sig = Signature.getInstance(sigAlgName);
459
460
AlgorithmParameters ap =
461
digestEncryptionAlgorithmId.getParameters();
462
try {
463
SignatureUtil.initVerifyWithParam(sig, key,
464
SignatureUtil.getParamSpec(sigAlgName, ap));
465
} catch (ProviderException | InvalidAlgorithmParameterException |
466
InvalidKeyException e) {
467
throw new SignatureException(e.getMessage(), e);
468
}
469
470
sig.update(dataSigned);
471
if (sig.verify(encryptedDigest)) {
472
return this;
473
}
474
} catch (IOException | CertificateException e) {
475
throw new SignatureException("Error verifying signature", e);
476
}
477
return null;
478
}
479
480
/**
481
* Derives the signature algorithm name from the digest algorithm
482
* and the encryption algorithm inside a PKCS7 SignerInfo.
483
*
484
* The digest algorithm is in the form "DIG", and the encryption
485
* algorithm can be in any of the 3 forms:
486
*
487
* 1. Old style key algorithm like RSA, DSA, EC, this method returns
488
* DIGwithKEY.
489
* 2. New style signature algorithm in the form of HASHwithKEY, this
490
* method returns DIGwithKEY. Please note this is not HASHwithKEY.
491
* 3. Modern signature algorithm like RSASSA-PSS and EdDSA, this method
492
* returns the signature algorithm itself but ensures digAlgId is
493
* compatible with the algorithm as described in RFC 4056 and 8419.
494
*
495
* @param digAlgId the digest algorithm
496
* @param encAlgId the encryption algorithm
497
* @param directSign whether the signature is calculated on the content
498
* directly. This makes difference for Ed448.
499
*/
500
public static String makeSigAlg(AlgorithmId digAlgId, AlgorithmId encAlgId,
501
boolean directSign) throws NoSuchAlgorithmException {
502
String encAlg = encAlgId.getName();
503
switch (encAlg) {
504
case "RSASSA-PSS":
505
PSSParameterSpec spec = (PSSParameterSpec)
506
SignatureUtil.getParamSpec(encAlg, encAlgId.getParameters());
507
if (!AlgorithmId.get(spec.getDigestAlgorithm()).equals(digAlgId)) {
508
throw new NoSuchAlgorithmException("Incompatible digest algorithm");
509
}
510
return encAlg;
511
case "Ed25519":
512
if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.sha512)) {
513
throw new NoSuchAlgorithmException("Incompatible digest algorithm");
514
}
515
return encAlg;
516
case "Ed448":
517
if (directSign) {
518
if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.shake256)) {
519
throw new NoSuchAlgorithmException("Incompatible digest algorithm");
520
}
521
} else {
522
if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.shake256$512)) {
523
throw new NoSuchAlgorithmException("Incompatible digest algorithm");
524
}
525
}
526
return encAlg;
527
default:
528
String digAlg = digAlgId.getName();
529
String keyAlg = SignatureUtil.extractKeyAlgFromDwithE(encAlg);
530
if (keyAlg == null) {
531
// The encAlg used to be only the key alg
532
keyAlg = encAlg;
533
}
534
if (digAlg.startsWith("SHA-")) {
535
digAlg = "SHA" + digAlg.substring(4);
536
}
537
if (keyAlg.equals("EC")) keyAlg = "ECDSA";
538
return digAlg + "with" + keyAlg;
539
}
540
}
541
542
/* Verify the content of the pkcs7 block. */
543
SignerInfo verify(PKCS7 block)
544
throws NoSuchAlgorithmException, SignatureException {
545
return verify(block, null);
546
}
547
548
public BigInteger getVersion() {
549
return version;
550
}
551
552
public X500Name getIssuerName() {
553
return issuerName;
554
}
555
556
public BigInteger getCertificateSerialNumber() {
557
return certificateSerialNumber;
558
}
559
560
public AlgorithmId getDigestAlgorithmId() {
561
return digestAlgorithmId;
562
}
563
564
public PKCS9Attributes getAuthenticatedAttributes() {
565
return authenticatedAttributes;
566
}
567
568
public AlgorithmId getDigestEncryptionAlgorithmId() {
569
return digestEncryptionAlgorithmId;
570
}
571
572
public byte[] getEncryptedDigest() {
573
return encryptedDigest;
574
}
575
576
public PKCS9Attributes getUnauthenticatedAttributes() {
577
return unauthenticatedAttributes;
578
}
579
580
/**
581
* Returns the timestamp PKCS7 data unverified.
582
* @return a PKCS7 object
583
*/
584
public PKCS7 getTsToken() throws IOException {
585
if (unauthenticatedAttributes == null) {
586
return null;
587
}
588
PKCS9Attribute tsTokenAttr =
589
unauthenticatedAttributes.getAttribute(
590
PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
591
if (tsTokenAttr == null) {
592
return null;
593
}
594
return new PKCS7((byte[])tsTokenAttr.getValue());
595
}
596
597
/*
598
* Extracts a timestamp from a PKCS7 SignerInfo.
599
*
600
* Examines the signer's unsigned attributes for a
601
* {@code signatureTimestampToken} attribute. If present,
602
* then it is parsed to extract the date and time at which the
603
* timestamp was generated.
604
*
605
* @param info A signer information element of a PKCS 7 block.
606
*
607
* @return A timestamp token or null if none is present.
608
* @throws IOException if an error is encountered while parsing the
609
* PKCS7 data.
610
* @throws NoSuchAlgorithmException if an error is encountered while
611
* verifying the PKCS7 object.
612
* @throws SignatureException if an error is encountered while
613
* verifying the PKCS7 object.
614
* @throws CertificateException if an error is encountered while generating
615
* the TSA's certpath.
616
*/
617
public Timestamp getTimestamp()
618
throws IOException, NoSuchAlgorithmException, SignatureException,
619
CertificateException
620
{
621
if (timestamp != null || !hasTimestamp)
622
return timestamp;
623
624
PKCS7 tsToken = getTsToken();
625
if (tsToken == null) {
626
hasTimestamp = false;
627
return null;
628
}
629
630
// Extract the content (an encoded timestamp token info)
631
byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
632
// Extract the signer (the Timestamping Authority)
633
// while verifying the content
634
SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
635
if (tsa == null || tsa.length == 0) {
636
throw new SignatureException("Unable to verify timestamp");
637
}
638
// Expect only one signer
639
ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
640
CertificateFactory cf = CertificateFactory.getInstance("X.509");
641
CertPath tsaChain = cf.generateCertPath(chain);
642
// Create a timestamp token info object
643
TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
644
// Check that the signature timestamp applies to this signature
645
verifyTimestamp(tsTokenInfo);
646
algorithms.putAll(tsa[0].algorithms);
647
// Create a timestamp object
648
timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
649
return timestamp;
650
}
651
652
/*
653
* Check that the signature timestamp applies to this signature.
654
* Match the hash present in the signature timestamp token against the hash
655
* of this signature.
656
*/
657
private void verifyTimestamp(TimestampToken token)
658
throws NoSuchAlgorithmException, SignatureException {
659
660
AlgorithmId digestAlgId = token.getHashAlgorithm();
661
algorithms.put(digestAlgId, "TimestampToken digestAlgorithm field");
662
663
MessageDigest md = MessageDigest.getInstance(digestAlgId.getName());
664
665
if (!MessageDigest.isEqual(token.getHashedMessage(),
666
md.digest(encryptedDigest))) {
667
668
throw new SignatureException("Signature timestamp (#" +
669
token.getSerialNumber() + ") generated on " + token.getDate() +
670
" is inapplicable");
671
}
672
673
if (debug != null) {
674
debug.println();
675
debug.println("Detected signature timestamp (#" +
676
token.getSerialNumber() + ") generated on " + token.getDate());
677
debug.println();
678
}
679
}
680
681
public String toString() {
682
HexDumpEncoder hexDump = new HexDumpEncoder();
683
684
String out = "";
685
686
out += "Signer Info for (issuer): " + issuerName + "\n";
687
out += "\tversion: " + Debug.toHexString(version) + "\n";
688
out += "\tcertificateSerialNumber: " +
689
Debug.toHexString(certificateSerialNumber) + "\n";
690
out += "\tdigestAlgorithmId: " + digestAlgorithmId + "\n";
691
if (authenticatedAttributes != null) {
692
out += "\tauthenticatedAttributes: " + authenticatedAttributes +
693
"\n";
694
}
695
out += "\tdigestEncryptionAlgorithmId: " + digestEncryptionAlgorithmId +
696
"\n";
697
698
out += "\tencryptedDigest: " + "\n" +
699
hexDump.encodeBuffer(encryptedDigest) + "\n";
700
if (unauthenticatedAttributes != null) {
701
out += "\tunauthenticatedAttributes: " +
702
unauthenticatedAttributes + "\n";
703
}
704
return out;
705
}
706
707
/**
708
* Verify all of the algorithms in the array of SignerInfos against the
709
* constraints in the jdk.jar.disabledAlgorithms security property.
710
*
711
* @param infos array of SignerInfos
712
* @param params constraint parameters
713
* @param name the name of the signer's PKCS7 file
714
* @return a set of algorithms that passed the checks and are not disabled
715
*/
716
public static Set<String> verifyAlgorithms(SignerInfo[] infos,
717
JarConstraintsParameters params, String name) throws SignatureException {
718
Map<AlgorithmId, String> algorithms = new HashMap<>();
719
for (SignerInfo info : infos) {
720
algorithms.putAll(info.algorithms);
721
}
722
723
Set<String> enabledAlgorithms = new HashSet<>();
724
try {
725
for (Map.Entry<AlgorithmId, String> algorithm : algorithms.entrySet()) {
726
params.setExtendedExceptionMsg(name, algorithm.getValue());
727
AlgorithmId algId = algorithm.getKey();
728
JAR_DISABLED_CHECK.permits(algId.getName(),
729
algId.getParameters(), params);
730
enabledAlgorithms.add(algId.getName());
731
}
732
} catch (CertPathValidatorException e) {
733
throw new SignatureException(e);
734
}
735
return enabledAlgorithms;
736
}
737
}
738
739