mirrored from https://www.bouncycastle.org/repositories/bc-java
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathOpenPGPCertificate.java
2417 lines (2172 loc) · 82.2 KB
/
OpenPGPCertificate.java
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
package org.bouncycastle.openpgp.api;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGInputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.bcpg.FingerprintUtil;
import org.bouncycastle.bcpg.KeyIdentifier;
import org.bouncycastle.bcpg.PacketFormat;
import org.bouncycastle.bcpg.PublicKeyUtils;
import org.bouncycastle.bcpg.SignatureSubpacket;
import org.bouncycastle.bcpg.SignatureSubpacketTags;
import org.bouncycastle.bcpg.sig.Features;
import org.bouncycastle.bcpg.sig.KeyExpirationTime;
import org.bouncycastle.bcpg.sig.KeyFlags;
import org.bouncycastle.bcpg.sig.PreferredAEADCiphersuites;
import org.bouncycastle.bcpg.sig.PreferredAlgorithms;
import org.bouncycastle.bcpg.sig.PrimaryUserID;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureException;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.bouncycastle.openpgp.PGPUserAttributeSubpacketVector;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.api.exception.IncorrectOpenPGPSignatureException;
import org.bouncycastle.openpgp.api.exception.MalformedOpenPGPSignatureException;
import org.bouncycastle.openpgp.api.exception.MissingIssuerCertException;
import org.bouncycastle.openpgp.api.util.UTCUtil;
import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* OpenPGP certificates (TPKs - transferable public keys) are long-living structures that may change during
* their lifetime. A key-holder may add new components like subkeys or identities, along with associated
* binding self-signatures to the certificate and old components may expire / get revoked at some point.
* Since any such changes may have an influence on whether a data signature is valid at a given time, or what subkey
* should be used when generating an encrypted / signed message, an API is needed that provides a view on the
* certificate that takes into consideration a relevant window in time.
* <p>
* Compared to a {@link PGPPublicKeyRing}, an {@link OpenPGPCertificate} has been evaluated at (or rather for)
* a given evaluation time. It offers a clean API for accessing the key-holder's preferences at a specific
* point in time and makes sure, that relevant self-signatures on certificate components are validated and verified.
*
* @see <a href="https://openpgp.dev/book/certificates.html#">OpenPGP for Application Developers - Chapter 4</a>
* for background information on the terminology used in this class.
*/
public class OpenPGPCertificate
{
final OpenPGPImplementation implementation;
final OpenPGPPolicy policy;
private final PGPKeyRing keyRing;
private final OpenPGPPrimaryKey primaryKey;
private final Map<KeyIdentifier, OpenPGPSubkey> subkeys;
// Note: get() needs to be accessed with OpenPGPCertificateComponent.getPublicComponent() to ensure
// proper functionality with secret key components.
private final Map<OpenPGPCertificateComponent, OpenPGPSignatureChains> componentSignatureChains;
/**
* Instantiate an {@link OpenPGPCertificate} from a passed {@link PGPKeyRing} using the default
* {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}.
*
* @param keyRing key ring
*/
public OpenPGPCertificate(PGPKeyRing keyRing)
{
this(keyRing, OpenPGPImplementation.getInstance());
}
/**
* Instantiate an {@link OpenPGPCertificate} from a parsed {@link PGPKeyRing}
* using the provided {@link OpenPGPImplementation} and its {@link OpenPGPPolicy}.
*
* @param keyRing public key ring
* @param implementation OpenPGP implementation
*/
public OpenPGPCertificate(PGPKeyRing keyRing, OpenPGPImplementation implementation)
{
this(keyRing, implementation, implementation.policy());
}
/**
* Instantiate an {@link OpenPGPCertificate} from a parsed {@link PGPKeyRing}
* using the provided {@link OpenPGPImplementation} and provided {@link OpenPGPPolicy}.
*
* @param keyRing public key ring
* @param implementation OpenPGP implementation
* @param policy OpenPGP policy
*/
public OpenPGPCertificate(PGPKeyRing keyRing, OpenPGPImplementation implementation, OpenPGPPolicy policy)
{
this.implementation = implementation;
this.policy = policy;
this.keyRing = keyRing;
this.subkeys = new HashMap<>();
this.componentSignatureChains = new LinkedHashMap<>();
Iterator<PGPPublicKey> rawKeys = keyRing.getPublicKeys();
PGPPublicKey rawPrimaryKey = rawKeys.next();
this.primaryKey = new OpenPGPPrimaryKey(rawPrimaryKey, this);
processPrimaryKey(primaryKey);
while (rawKeys.hasNext())
{
PGPPublicKey rawSubkey = rawKeys.next();
OpenPGPSubkey subkey = new OpenPGPSubkey(rawSubkey, this);
subkeys.put(rawSubkey.getKeyIdentifier(), subkey);
processSubkey(subkey);
}
}
public Map<KeyIdentifier, OpenPGPComponentKey> getPublicKeys()
{
Map<KeyIdentifier, OpenPGPComponentKey> keys = new HashMap<>();
keys.put(primaryKey.getKeyIdentifier(), primaryKey);
keys.putAll(subkeys);
return keys;
}
/**
* Return the primary key of the certificate.
*
* @return primary key
*/
public OpenPGPPrimaryKey getPrimaryKey()
{
return primaryKey;
}
/**
* Return a {@link Map} containing the subkeys of this certificate, keyed by their {@link KeyIdentifier}.
* Note: This map does NOT contain the primary key ({@link #getPrimaryKey()}).
*
* @return subkeys
*/
public Map<KeyIdentifier, OpenPGPSubkey> getSubkeys()
{
return new HashMap<>(subkeys);
}
/**
* Return a {@link List} containing all {@link OpenPGPCertificateComponent components} of the certificate.
* Components are primary key, subkeys and identities (user-ids, user attributes).
*
* @return list of components
*/
public List<OpenPGPCertificateComponent> getComponents()
{
return new ArrayList<>(componentSignatureChains.keySet());
}
/**
* Return all {@link OpenPGPComponentKey OpenPGPComponentKeys} in the certificate.
* The return value is a {@link List} containing the {@link OpenPGPPrimaryKey} and all
* {@link OpenPGPSubkey OpenPGPSubkeys}.
*
* @return list of all component keys
*/
public List<OpenPGPComponentKey> getKeys()
{
List<OpenPGPComponentKey> keys = new ArrayList<>();
keys.add(primaryKey);
keys.addAll(subkeys.values());
return keys;
}
/**
* Return the {@link OpenPGPComponentKey} identified by the passed in {@link KeyIdentifier}.
*
* @param identifier key identifier
* @return component key
*/
public OpenPGPComponentKey getKey(KeyIdentifier identifier)
{
if (identifier.matches(getPrimaryKey().getPGPPublicKey().getKeyIdentifier()))
{
return primaryKey;
}
return subkeys.get(identifier);
}
/**
* Return the {@link OpenPGPComponentKey} that likely issued the passed in {@link PGPSignature}.
*
* @param signature signature
* @return issuer (sub-)key
*/
public OpenPGPComponentKey getSigningKeyFor(PGPSignature signature)
{
List<KeyIdentifier> keyIdentifiers = signature.getKeyIdentifiers();
// issuer is primary key
if (KeyIdentifier.matches(keyIdentifiers, getPrimaryKey().getKeyIdentifier(), true))
{
return primaryKey;
}
for (KeyIdentifier subkeyIdentifier : subkeys.keySet())
{
if (KeyIdentifier.matches(keyIdentifiers, subkeyIdentifier, true))
{
return subkeys.get(subkeyIdentifier);
}
}
return null; // external issuer
}
/**
* Return the {@link PGPKeyRing} that this certificate is based on.
*
* @return underlying key ring
*/
public PGPKeyRing getPGPKeyRing()
{
return keyRing;
}
/**
* Return the underlying {@link PGPPublicKeyRing}.
*
* @return public keys
*/
public PGPPublicKeyRing getPGPPublicKeyRing()
{
if (keyRing instanceof PGPPublicKeyRing)
{
return (PGPPublicKeyRing) keyRing;
}
List<PGPPublicKey> list = new ArrayList<>();
for (Iterator<PGPPublicKey> it = keyRing.getPublicKeys(); it.hasNext(); )
{
list.add(it.next());
}
return new PGPPublicKeyRing(list);
}
/**
* Return the {@link KeyIdentifier} of the certificates primary key.
*
* @return primary key identifier
*/
public KeyIdentifier getKeyIdentifier()
{
return primaryKey.getKeyIdentifier();
}
/**
* Return a list of ALL (sub-)key's identifiers, including those of expired / revoked / unbound keys.
* @return all keys identifiers
*/
public List<KeyIdentifier> getAllKeyIdentifiers()
{
List<KeyIdentifier> identifiers = new ArrayList<>();
for (Iterator<PGPPublicKey> it = keyRing.getPublicKeys(); it.hasNext(); )
{
PGPPublicKey key = it.next();
identifiers.add(key.getKeyIdentifier());
}
return identifiers;
}
/**
* Return the last time, the key was modified (before right now).
* A modification is the addition of a new subkey, or key signature.
*
* @return last modification time
*/
public Date getLastModificationDate()
{
return getLastModificationDateAt(new Date());
}
/**
* Return the last time, the key was modified before or at the given evaluation time.
*
* @param evaluationTime evaluation time
* @return last modification time before or at evaluation time
*/
public Date getLastModificationDateAt(Date evaluationTime)
{
Date latestModification = null;
// Signature creation times
for (OpenPGPCertificateComponent component : getComponents())
{
OpenPGPSignatureChains componentChains = componentSignatureChains.get(component);
if (componentChains == null)
{
continue;
}
componentChains = componentChains.getChainsAt(evaluationTime);
for (OpenPGPSignatureChain chain : componentChains)
{
for (OpenPGPSignatureChain.Link link : chain)
{
if (latestModification == null || link.since().after(latestModification))
{
latestModification = link.since();
}
}
}
}
// Key creation times
for (OpenPGPComponentKey key : getKeys())
{
if (key.getCreationTime().after(evaluationTime))
{
continue;
}
if (latestModification == null || key.getCreationTime().after(latestModification))
{
latestModification = key.getCreationTime();
}
}
return latestModification;
}
public static OpenPGPCertificate join(OpenPGPCertificate certificate, String armored)
throws IOException, PGPException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(armored.getBytes());
InputStream decoderStream = PGPUtil.getDecoderStream(bIn);
BCPGInputStream wrapper = BCPGInputStream.wrap(decoderStream);
PGPObjectFactory objFac = certificate.implementation.pgpObjectFactory(wrapper);
Object next;
while ((next = objFac.nextObject()) != null)
{
if (next instanceof PGPPublicKeyRing)
{
PGPPublicKeyRing publicKeys = (PGPPublicKeyRing) next;
OpenPGPCertificate otherCert = new OpenPGPCertificate(publicKeys, certificate.implementation);
try
{
return join(certificate, otherCert);
}
catch (IllegalArgumentException e)
{
// skip over wrong certificate
}
}
else if (next instanceof PGPSecretKeyRing)
{
throw new IllegalArgumentException("Joining with a secret key is not supported.");
}
else if (next instanceof PGPSignatureList)
{
// parse and join delegations / revocations
// those are signatures of type DIRECT_KEY or KEY_REVOCATION issued either by the primary key itself
// (self-signatures) or by a 3rd party (delegations / delegation revocations)
PGPSignatureList signatures = (PGPSignatureList) next;
PGPPublicKeyRing publicKeys = certificate.getPGPPublicKeyRing();
PGPPublicKey primaryKey = publicKeys.getPublicKey();
for (PGPSignature signature : signatures)
{
primaryKey = PGPPublicKey.addCertification(primaryKey, signature);
}
publicKeys = PGPPublicKeyRing.insertPublicKey(publicKeys, primaryKey);
return new OpenPGPCertificate(publicKeys, certificate.implementation);
}
}
return null;
}
public static OpenPGPCertificate join(OpenPGPCertificate certificate, OpenPGPCertificate other)
throws PGPException
{
PGPPublicKeyRing joined = PGPPublicKeyRing.join(
certificate.getPGPPublicKeyRing(), other.getPGPPublicKeyRing());
return new OpenPGPCertificate(joined, certificate.implementation);
}
/**
* Return the primary keys fingerprint in binary format.
*
* @return primary key fingerprint
*/
public byte[] getFingerprint()
{
return primaryKey.getPGPPublicKey().getFingerprint();
}
/**
* Return the primary keys fingerprint as a pretty-printed {@link String}.
*
* @return pretty-printed primary key fingerprint
*/
public String getPrettyFingerprint()
{
return FingerprintUtil.prettifyFingerprint(getFingerprint());
}
/**
* Return an ASCII armored {@link String} containing the certificate.
*
* @return armored certificate
* @throws IOException if the cert cannot be encoded
*/
public String toAsciiArmoredString()
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ArmoredOutputStream.Builder armorBuilder = ArmoredOutputStream.builder()
.clearHeaders();
// Add fingerprint comment
armorBuilder.addSplitMultilineComment(getPrettyFingerprint());
// Add user-id comments
for (OpenPGPUserId userId : getPrimaryKey().getUserIDs())
{
armorBuilder.addEllipsizedComment(userId.getUserId());
}
ArmoredOutputStream aOut = armorBuilder.build(bOut);
BCPGOutputStream pOut = new BCPGOutputStream(aOut, PacketFormat.CURRENT);
// Make sure we export a TPK
List<PGPPublicKey> list = new ArrayList<>();
for (Iterator<PGPPublicKey> it = getPGPKeyRing().getPublicKeys(); it.hasNext(); )
{
list.add(it.next());
}
PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(list);
publicKeys.encode(pOut, true);
pOut.close();
aOut.close();
return bOut.toString();
}
private OpenPGPSignatureChain getSignatureChainFor(OpenPGPCertificateComponent component,
OpenPGPComponentKey origin,
Date evaluationDate)
{
// Check if there are signatures at all for the component
OpenPGPSignatureChains chainsForComponent = getAllSignatureChainsFor(component);
if (component == getPrimaryKey() && chainsForComponent.isEmpty())
{
// If cert has no direct-key signatures, consider primary UID bindings instead
OpenPGPUserId primaryUserId = getPrimaryUserId(evaluationDate);
if (primaryUserId != null)
{
chainsForComponent.addAll(getAllSignatureChainsFor(primaryUserId));
}
}
// Isolate chains which originate from the passed origin key component
OpenPGPSignatureChains fromOrigin = chainsForComponent.fromOrigin(origin);
if (fromOrigin == null)
{
return null;
}
// Return chain that currently takes precedence
return fromOrigin.getChainAt(evaluationDate);
}
private OpenPGPSignatureChains getAllSignatureChainsFor(OpenPGPCertificateComponent component)
{
return componentSignatureChains.get(component.getPublicComponent());
}
private void processPrimaryKey(OpenPGPPrimaryKey primaryKey)
{
OpenPGPSignatureChains keySignatureChains = new OpenPGPSignatureChains(primaryKey);
List<OpenPGPComponentSignature> keySignatures = primaryKey.getKeySignatures();
// Key Signatures
for (OpenPGPComponentSignature sig : keySignatures)
{
OpenPGPSignatureChain chain = OpenPGPSignatureChain.direct(sig, sig.issuer, primaryKey);
keySignatureChains.add(chain);
}
componentSignatureChains.put(primaryKey, keySignatureChains);
// Identities
for (OpenPGPIdentityComponent identity : primaryKey.identityComponents)
{
OpenPGPSignatureChains identityChains = new OpenPGPSignatureChains(identity);
List<OpenPGPComponentSignature> bindings;
if (identity instanceof OpenPGPUserId)
{
bindings = primaryKey.getUserIdSignatures((OpenPGPUserId) identity);
}
else
{
bindings = primaryKey.getUserAttributeSignatures((OpenPGPUserAttribute) identity);
}
for (OpenPGPComponentSignature sig : bindings)
{
OpenPGPSignatureChain chain = OpenPGPSignatureChain.direct(sig, sig.getIssuerComponent(), identity);
identityChains.add(chain);
}
componentSignatureChains.put(identity, identityChains);
}
}
private void processSubkey(OpenPGPSubkey subkey)
{
List<OpenPGPComponentSignature> bindingSignatures = subkey.getKeySignatures();
OpenPGPSignatureChains subkeyChains = new OpenPGPSignatureChains(subkey);
for (OpenPGPComponentSignature sig : bindingSignatures)
{
OpenPGPComponentKey issuer = subkey.getCertificate().getSigningKeyFor(sig.getSignature());
if (issuer == null)
{
continue; // external key
}
OpenPGPSignatureChains issuerChains = getAllSignatureChainsFor(issuer);
if (!issuerChains.chains.isEmpty())
{
for (OpenPGPSignatureChain issuerChain : issuerChains.chains)
{
subkeyChains.add(issuerChain.plus(sig, subkey));
}
}
else
{
subkeyChains.add(new OpenPGPSignatureChain(
new OpenPGPSignatureChain.Certification(sig, issuer, subkey)));
}
}
this.componentSignatureChains.put(subkey, subkeyChains);
}
/**
* Return true, if the passed in component is - at evaluation time - properly bound to the certificate.
*
* @param component OpenPGP certificate component
* @param evaluationTime evaluation time
* @return true if component is bound at evaluation time, false otherwise
*/
private boolean isBound(OpenPGPCertificateComponent component,
Date evaluationTime)
{
return isBoundBy(component, getPrimaryKey(), evaluationTime);
}
/**
* Return true, if the passed in component is - at evaluation time - properly bound to the certificate with
* a signature chain originating at the passed in root component.
*
* @param component OpenPGP certificate component
* @param root root certificate component
* @param evaluationTime evaluation time
* @return true if component is bound at evaluation time, originating at root, false otherwise
*/
private boolean isBoundBy(OpenPGPCertificateComponent component,
OpenPGPComponentKey root,
Date evaluationTime)
{
try
{
OpenPGPSignatureChain chain = getSignatureChainFor(component, root, evaluationTime);
if (chain == null)
{
// Component is not bound at all
return false;
}
// Chain needs to be valid (signatures correct)
if (chain.isValid(implementation.pgpContentVerifierBuilderProvider(), policy))
{
// Chain needs to not contain a revocation signature, otherwise the component is considered revoked
return !chain.isRevocation();
}
// Signature is not correct
return false;
}
catch (PGPException e)
{
// Signature verification failed (signature broken?)
return false;
}
}
/**
* Return a {@link List} containing all currently marked, valid encryption keys.
*
* @return encryption keys
*/
public List<OpenPGPComponentKey> getEncryptionKeys()
{
return getEncryptionKeys(new Date());
}
/**
* Return a list of all keys that are - at evaluation time - valid encryption keys.
*
* @param evaluationTime evaluation time
* @return encryption keys
*/
public List<OpenPGPComponentKey> getEncryptionKeys(Date evaluationTime)
{
List<OpenPGPComponentKey> encryptionKeys = new ArrayList<>();
for (OpenPGPComponentKey key : getKeys())
{
if (!isBound(key, evaluationTime))
{
// Key is not bound
continue;
}
if (!key.isEncryptionKey(evaluationTime))
{
continue;
}
encryptionKeys.add(key);
}
return encryptionKeys;
}
/**
* Return a {@link List} containing all currently valid marked signing keys.
*
* @return list of signing keys
*/
public List<OpenPGPComponentKey> getSigningKeys()
{
return getSigningKeys(new Date());
}
/**
* Return a list of all keys that - at evaluation time - are validly marked as signing keys.
*
* @param evaluationTime evaluation time
* @return list of signing keys
*/
public List<OpenPGPComponentKey> getSigningKeys(Date evaluationTime)
{
List<OpenPGPComponentKey> signingKeys = new ArrayList<>();
for (OpenPGPComponentKey key : getKeys())
{
if (!isBound(key, evaluationTime))
{
// Key is not bound
continue;
}
if (!key.isSigningKey(evaluationTime))
{
continue;
}
signingKeys.add(key);
}
return signingKeys;
}
/**
* Return {@link OpenPGPSignatureChains} that contain preference information.
*
* @return signature chain containing certificate-wide preferences (typically DK signature)
*/
private OpenPGPSignatureChain getPreferenceSignature(Date evaluationTime)
{
OpenPGPSignatureChain directKeyBinding = getPrimaryKey().getSignatureChains()
.fromOrigin(getPrimaryKey())
.getCertificationAt(evaluationTime);
if (directKeyBinding != null)
{
return directKeyBinding;
}
List<OpenPGPSignatureChain> uidBindings = new ArrayList<>();
for (OpenPGPUserId userId : getPrimaryKey().getUserIDs())
{
OpenPGPSignatureChain uidBinding = getAllSignatureChainsFor(userId)
.fromOrigin(getPrimaryKey())
.getCertificationAt(evaluationTime);
if (uidBinding != null)
{
uidBindings.add(uidBinding);
}
}
uidBindings.sort(Comparator.comparing(OpenPGPSignatureChain::getSince).reversed());
for (OpenPGPSignatureChain binding : uidBindings)
{
PGPSignature sig = binding.getHeadLink().getSignature().getSignature();
if (sig.getHashedSubPackets().isPrimaryUserID())
{
return binding;
}
}
return uidBindings.isEmpty() ? null : uidBindings.get(0);
}
/**
* Return all identities ({@link OpenPGPUserId User IDs}, {@link OpenPGPUserAttribute User Attributes}
* of the certificate.
*
* @return identities
*/
public List<OpenPGPIdentityComponent> getIdentities()
{
return new ArrayList<>(primaryKey.identityComponents);
}
/**
* Return the current primary {@link OpenPGPUserId} of the certificate.
*
* @return primary user id
*/
public OpenPGPUserId getPrimaryUserId()
{
return getPrimaryUserId(new Date());
}
/**
* Return the {@link OpenPGPUserId} that is considered primary at the given evaluation time.
*
* @param evaluationTime evaluation time
* @return primary user-id at evaluation time
*/
public OpenPGPUserId getPrimaryUserId(Date evaluationTime)
{
return primaryKey.getExplicitOrImplicitPrimaryUserId(evaluationTime);
}
/**
* Return the {@link OpenPGPUserId} object matching the given user-id {@link String}.
* @param userId user-id
* @return user-id
*/
public OpenPGPUserId getUserId(String userId)
{
for (OpenPGPUserId uid : primaryKey.getUserIDs())
{
if (uid.getUserId().equals(userId))
{
return uid;
}
}
return null;
}
public Date getExpirationTime()
{
return getExpirationTime(new Date());
}
public Date getExpirationTime(Date evaluationTime)
{
return getPrimaryKey().getKeyExpirationDateAt(evaluationTime);
}
/**
* Component on an OpenPGP certificate.
* Components can either be {@link OpenPGPComponentKey keys} or {@link OpenPGPIdentityComponent identities}.
*/
public static abstract class OpenPGPCertificateComponent
{
private final OpenPGPCertificate certificate;
public OpenPGPCertificateComponent(OpenPGPCertificate certificate)
{
this.certificate = certificate;
}
/**
* Return this components {@link OpenPGPCertificate}.
*
* @return certificate
*/
public OpenPGPCertificate getCertificate()
{
return certificate;
}
/**
* Return a detailed String representation of this component.
*
* @return detailed String representation
*/
public abstract String toDetailString();
/**
* Return true, if the component is currently validly bound to the certificate.
*
* @return true if bound
*/
public boolean isBound()
{
return isBoundAt(new Date());
}
/**
* Return true, if this component is - at evaluation time - properly bound to its certificate.
*
* @param evaluationTime evaluation time
* @return true if bound, false otherwise
*/
public boolean isBoundAt(Date evaluationTime)
{
return getCertificate().isBound(this, evaluationTime);
}
/**
* Return all {@link OpenPGPSignatureChains} that bind this component.
*
* @return signature chains
*/
public OpenPGPSignatureChains getSignatureChains()
{
OpenPGPSignatureChains chains = getCertificate().getAllSignatureChainsFor(this);
if (getPublicComponent() instanceof OpenPGPPrimaryKey)
{
OpenPGPPrimaryKey pk = (OpenPGPPrimaryKey) getPublicComponent();
if (!pk.getUserIDs().isEmpty())
{
chains.addAll(getCertificate().getAllSignatureChainsFor(pk.getUserIDs().get(0)));
}
}
return chains;
}
/**
* Return the public {@link OpenPGPCertificateComponent} that belongs to this component.
* For public components (pubkeys, identities...), that's simply this, while secret components
* return their corresponding public component.
* This is used to properly map secret key and public key components in {@link Map Maps} that use
* {@link OpenPGPCertificateComponent components} as map keys.
*
* @return public certificate component
*/
protected OpenPGPCertificateComponent getPublicComponent()
{
return this;
}
/**
* Return the {@link SignatureSubpacket} instance of the given subpacketType, which currently applies to
* the key. Since subpackets from the Direct-Key signature apply to all subkeys of a certificate,
* this method first inspects the signature that immediately applies to this key (e.g. a subkey-binding
* signature), and - if the queried subpacket is found in there, returns that instance.
* Otherwise, indirectly applying signatures (e.g. Direct-Key signatures) are queried.
* That way, preferences from the direct-key signature are considered, but per-key overwrites take precedence.
*
* @see <a href="https://openpgp.dev/book/adv/verification.html#attribute-shadowing">
* OpenPGP for application developers - Attribute Shadowing</a>
*
* @param evaluationTime evaluation time
* @param subpacketType subpacket type that is being searched for
* @return subpacket from directly or indirectly applying signature
*/
protected OpenPGPSignature.OpenPGPSignatureSubpacket getApplyingSubpacket(Date evaluationTime, int subpacketType)
{
OpenPGPSignatureChain binding = getSignatureChains().getCertificationAt(evaluationTime);
if (binding == null)
{
// is not bound
return null;
}
// Check signatures
try
{
if (!binding.isValid())
{
// Binding is incorrect
return null;
}
}
catch (PGPSignatureException e)
{
// Binding cannot be verified
return null;
}
// find signature "closest to the key", e.g. subkey binding signature
OpenPGPComponentSignature keySignature = binding.getHeadLink().getSignature();
PGPSignatureSubpacketVector hashedSubpackets = keySignature.getSignature().getHashedSubPackets();
if (hashedSubpackets == null || !hashedSubpackets.hasSubpacket(subpacketType))
{
// If the subkey binding signature doesn't carry the desired subpacket,
// check direct-key or primary uid sig instead
OpenPGPSignatureChain preferenceBinding = getCertificate().getPreferenceSignature(evaluationTime);
if (preferenceBinding == null)
{
// No direct-key / primary uid sig found -> No subpacket
return null;
}
keySignature = preferenceBinding.getHeadLink().signature;
hashedSubpackets = keySignature.getSignature().getHashedSubPackets();
}
// else -> attribute from DK sig is shadowed by SB sig
// Extract subpacket from hashed area
SignatureSubpacket subpacket = hashedSubpackets.getSubpacket(subpacketType);
if (subpacket == null)
{
return null;
}
return OpenPGPSignature.OpenPGPSignatureSubpacket.hashed(subpacket, keySignature);
}
}
/**
* OpenPGP Signature made over some {@link OpenPGPCertificateComponent} on a {@link OpenPGPCertificate}.
*/
public static class OpenPGPComponentSignature
extends OpenPGPSignature
{
private final OpenPGPCertificateComponent target;
/**
* Component signature.
* @param signature signature
* @param issuer key that issued the signature.
* Is nullable (e.g. for 3rd party sigs where the certificate is not available).
* @param target signed certificate component
*/
public OpenPGPComponentSignature(PGPSignature signature,
OpenPGPComponentKey issuer,
OpenPGPCertificateComponent target)
{
super(signature, issuer);
this.target = target;
}
/**
* Return the {@link OpenPGPComponentKey} that issued this signature.
*
* @return issuer
*/
public OpenPGPComponentKey getIssuerComponent()
{
return getIssuer();
}
/**
* Return the {@link OpenPGPCertificateComponent} that this signature was calculated over.
*
* @return target
*/
public OpenPGPCertificateComponent getTargetComponent()
{
return target;
}
/**
* Return the {@link OpenPGPComponentKey} that this signature is calculated over.
* Contrary to {@link #getTargetComponent()}, which returns the actual target, this method returns the
* {@link OpenPGPComponentKey} "closest" to the target.
* For a subkey-binding signature, this is the target subkey, while for an identity-binding signature
* (binding for a user-id or attribute) the return value is the {@link OpenPGPComponentKey} which
* carries the identity.
*
* @return target key component of the signature
*/
public OpenPGPComponentKey getTargetKeyComponent()
{
if (getTargetComponent() instanceof OpenPGPIdentityComponent)
{