mirrored from https://www.bouncycastle.org/repositories/bc-java
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathOpenPGPCertificate.java
More file actions
3672 lines (3345 loc) · 130 KB
/
OpenPGPCertificate.java
File metadata and controls
3672 lines (3345 loc) · 130 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
package org.bouncycastle.openpgp.api;
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;
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;
/**
* 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;
protected 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 LinkedHashMap<KeyIdentifier, OpenPGPSubkey>();
this.componentSignatureChains = new LinkedHashMap<OpenPGPCertificateComponent, OpenPGPSignatureChains>();
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);
}
}
/**
* Return true, if this object is an {@link OpenPGPKey}, false otherwise.
*
* @return true if this is a secret key
*/
public boolean isSecretKey()
{
return false;
}
/**
* Return a {@link List} of all {@link OpenPGPUserId OpenPGPUserIds} on the certificate, regardless of their
* validity.
*
* @return all user ids
*/
public List<OpenPGPUserId> getAllUserIds()
{
return getPrimaryKey().getUserIDs();
}
/**
* Return a {@link List} of all valid {@link OpenPGPUserId OpenPGPUserIds} on the certificate.
*
* @return valid user ids
*/
public List<OpenPGPUserId> getValidUserIds()
{
return getValidUserIds(new Date());
}
/**
* Return a {@link List} containing all {@link OpenPGPUserId OpenPGPUserIds} that are valid at the given
* evaluation time.
*
* @param evaluationTime reference time
* @return user ids that are valid at the given evaluation time
*/
public List<OpenPGPUserId> getValidUserIds(Date evaluationTime)
{
return getPrimaryKey().getValidUserIDs(evaluationTime);
}
/**
* Get a {@link Map} of all public {@link OpenPGPComponentKey component keys} keyed by their {@link KeyIdentifier}.
*
* @return all public keys
*/
public Map<KeyIdentifier, OpenPGPComponentKey> getPublicKeys()
{
Map<KeyIdentifier, OpenPGPComponentKey> keys = new HashMap<KeyIdentifier, OpenPGPComponentKey>();
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 LinkedHashMap<KeyIdentifier, OpenPGPSubkey>(subkeys);
}
/**
* Return a {@link List} containing all {@link OpenPGPComponentKey component keys} that carry any of the
* given key flags at evaluation time.
* <b>
* Note: To get all component keys that have EITHER {@link KeyFlags#ENCRYPT_COMMS} OR {@link KeyFlags#ENCRYPT_STORAGE},
* call this method like this:
* <pre>
* keys = getComponentKeysWithFlag(date, KeyFlags.ENCRYPT_COMMS, KeyFlags.ENCRYPT_STORAGE);
* </pre>
* If you instead want to access all keys, that have BOTH flags, you need to <pre>&</pre> both flags:
* <pre>
* keys = getComponentKeysWithFlag(date, KeyFlags.ENCRYPT_COMMS & KeyFlags.ENCRYPT_STORAGE);
* </pre>
*
* @param evaluationTime reference time
* @param keyFlags key flags
* @return list of keys that carry any of the given key flags at evaluation time
*/
public List<OpenPGPComponentKey> getComponentKeysWithFlag(Date evaluationTime, final int... keyFlags)
{
return filterKeys(evaluationTime, new KeyFilter()
{
@Override
public boolean test(OpenPGPComponentKey key, Date time)
{
return key.hasKeyFlags(time, keyFlags);
}
});
}
/**
* 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<OpenPGPCertificateComponent>(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<OpenPGPComponentKey>();
keys.add(primaryKey);
keys.addAll(subkeys.values());
return keys;
}
/**
* Return a {@link List} of all {@link OpenPGPComponentKey component keys} that are valid right now.
*
* @return all valid keys
*/
public List<OpenPGPComponentKey> getValidKeys()
{
return getValidKeys(new Date());
}
/**
* Return a {@link List} of all {@link OpenPGPComponentKey component keys} that are valid at the given
* evaluation time.
*
* @param evaluationTime reference time
* @return all keys that are valid at evaluation time
*/
public List<OpenPGPComponentKey> getValidKeys(Date evaluationTime)
{
return filterKeys(evaluationTime, new KeyFilter()
{
@Override
public boolean test(OpenPGPComponentKey key, Date time)
{
return true;
}
});
}
/**
* 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.matchesExplicit(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();
// Subkey binding signatures do not require issuer
int type = signature.getSignatureType();
if (type == PGPSignature.SUBKEY_BINDING ||
type == PGPSignature.SUBKEY_REVOCATION)
{
return primaryKey;
}
// issuer is primary key
if (KeyIdentifier.matches(keyIdentifiers, getPrimaryKey().getKeyIdentifier(), true))
{
return primaryKey;
}
for (Iterator<KeyIdentifier> it = subkeys.keySet().iterator(); it.hasNext(); )
{
KeyIdentifier subkeyIdentifier = it.next();
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<PGPPublicKey>();
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<KeyIdentifier>();
for (Iterator<PGPPublicKey> it = keyRing.getPublicKeys(); it.hasNext(); )
{
PGPPublicKey key = it.next();
identifiers.add(key.getKeyIdentifier());
}
return identifiers;
}
/**
* Return the current self-certification signature.
* This is either a DirectKey signature on the primary key, or the latest self-certification on
* a {@link OpenPGPUserId}.
*
* @return latest certification signature
*/
public OpenPGPComponentSignature getCertification()
{
return getCertification(new Date());
}
/**
* Return the most recent self-certification signature at evaluation time.
* This is either a DirectKey signature on the primary key, or the (at evaluation time) latest
* self-certification on an {@link OpenPGPUserId}.
*
* @param evaluationTime reference time
* @return latest certification signature
*/
public OpenPGPComponentSignature getCertification(Date evaluationTime)
{
return primaryKey.getCertification(evaluationTime);
}
/**
* Return the most recent revocation signature on the certificate.
* This is either a KeyRevocation signature on the primary key, or the latest certification revocation
* signature on an {@link OpenPGPUserId}.
*
* @return latest certification revocation
*/
public OpenPGPComponentSignature getRevocation()
{
return getRevocation(new Date());
}
/**
* Return the (at evaluation time) most recent revocation signature on the certificate.
* This is either a KeyRevocation signature on the primary key, or the latest certification revocation
* signature on an {@link OpenPGPUserId}.
*
* @param evaluationTime reference time
* @return latest certification revocation
*/
public OpenPGPComponentSignature getRevocation(Date evaluationTime)
{
return primaryKey.getRevocation(evaluationTime);
}
/**
* 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 (Iterator<OpenPGPCertificateComponent> it = getComponents().iterator(); it.hasNext(); )
{
OpenPGPSignatureChains componentChains = getAllSignatureChainsFor(it.next());
componentChains = componentChains.getChainsAt(evaluationTime);
for (Iterator<OpenPGPSignatureChain> it2 = componentChains.iterator(); it2.hasNext(); )
{
for (Iterator<OpenPGPSignatureChain.Link> it3 = it2.next().iterator(); it3.hasNext(); )
{
OpenPGPSignatureChain.Link link = it3.next();
if (latestModification == null || link.since().after(latestModification))
{
latestModification = link.since();
}
}
}
}
if (latestModification != null)
{
return latestModification;
}
// Key creation times
for (Iterator<OpenPGPComponentKey> it = getKeys().iterator(); it.hasNext(); )
{
OpenPGPComponentKey key = it.next();
if (key.getCreationTime().after(evaluationTime))
{
continue;
}
if (latestModification == null || key.getCreationTime().after(latestModification))
{
latestModification = key.getCreationTime();
}
}
return latestModification;
}
/**
* Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components}
* into a single instance.
* The ASCII armored {@link String} might contain more than one {@link OpenPGPCertificate}.
* Items that are not a copy of the base certificate are silently ignored.
*
* @param certificate base certificate
* @param armored ASCII armored {@link String} containing one or more copies of the same certificate,
* possibly containing a different set of components
* @return merged certificate
* @throws IOException if the armored data cannot be processed
* @throws PGPException if a protocol level error occurs
*
* @deprecated use non-static {@link #join(String)} instead.
*/
@Deprecated
public static OpenPGPCertificate join(OpenPGPCertificate certificate, String armored)
throws IOException, PGPException
{
return certificate.join(armored);
}
/**
* Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components}
* into a single instance.
*
* @param certificate base certificate
* @param other copy of the same certificate, potentially carrying a different set of components
* @return merged certificate
* @throws PGPException if a protocol level error occurs
* @deprecated use non-static {@link #join(OpenPGPCertificate)} instead.
*/
@Deprecated
public static OpenPGPCertificate join(OpenPGPCertificate certificate, OpenPGPCertificate other)
throws PGPException
{
return certificate.join(other);
}
/**
* Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components}
* into a single instance.
* The ASCII armored {@link String} might contain more than one {@link OpenPGPCertificate}.
* Items that are not a copy of the base certificate are silently ignored.
*
* @param armored ASCII armored {@link String} containing one or more copies of this certificate,
* possibly containing a different set of components
* @return merged certificate
* @throws IOException if the armored data cannot be processed
* @throws PGPException if a protocol level error occurs
*/
public OpenPGPCertificate join(String armored)
throws PGPException, IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(armored.getBytes());
InputStream decoderStream = PGPUtil.getDecoderStream(bIn);
BCPGInputStream wrapper = BCPGInputStream.wrap(decoderStream);
PGPObjectFactory objFac = implementation.pgpObjectFactory(wrapper);
Object next;
while ((next = objFac.nextObject()) != null)
{
if (next instanceof PGPPublicKeyRing)
{
OpenPGPCertificate otherCert = new OpenPGPCertificate((PGPPublicKeyRing) next, implementation);
try
{
return join(otherCert);
}
catch (IllegalArgumentException e)
{
// skip over wrong certificate
}
}
else if (next instanceof PGPSecretKeyRing)
{
throw new IllegalArgumentException("Joining certificate with a secret key is not supported." +
" Try the other way round.");
}
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 = getPGPPublicKeyRing();
PGPPublicKey primaryKey = publicKeys.getPublicKey();
for (Iterator<PGPSignature> it = signatures.iterator(); it.hasNext(); )
{
primaryKey = PGPPublicKey.addCertification(primaryKey, it.next());
}
publicKeys = PGPPublicKeyRing.insertPublicKey(publicKeys, primaryKey);
return new OpenPGPCertificate(publicKeys, implementation);
}
}
return this;
}
/**
* Join two copies of the same {@link OpenPGPCertificate}, merging its {@link OpenPGPCertificateComponent components}
* into a single instance.
*
* @param other copy of this certificate, potentially carrying a different set of components
* @return merged certificate
* @throws PGPException if a protocol level error occurs
*/
public OpenPGPCertificate join(OpenPGPCertificate other)
throws PGPException
{
PGPPublicKeyRing joined = PGPPublicKeyRing.join(
getPGPPublicKeyRing(), other.getPGPPublicKeyRing());
return new OpenPGPCertificate(joined, 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
{
return toAsciiArmoredString(PacketFormat.ROUNDTRIP);
}
/**
* Return an ASCII armored {@link String} containing the certificate.
*
* @param packetFormat packet length encoding format
* @return armored certificate
* @throws IOException if the cert cannot be encoded
*/
public String toAsciiArmoredString(PacketFormat packetFormat)
throws IOException
{
ArmoredOutputStream.Builder armorBuilder = ArmoredOutputStream.builder()
.clearHeaders();
// Add fingerprint comment
armorBuilder.addSplitMultilineComment(getPrettyFingerprint());
// Add user-id comments
for (Iterator<OpenPGPUserId> it = getPrimaryKey().getUserIDs().iterator(); it.hasNext(); )
{
armorBuilder.addEllipsizedComment(it.next().getUserId());
}
return toAsciiArmoredString(packetFormat, armorBuilder);
}
/**
* Return an ASCII armored {@link String} containing the certificate.
* The {@link ArmoredOutputStream.Builder} can be used to customize the ASCII armor (headers, CRC etc.).
*
* @param packetFormat packet length encoding format
* @param armorBuilder builder for the ASCII armored output stream
* @return armored certificate
* @throws IOException if the cert cannot be encoded
*/
public String toAsciiArmoredString(PacketFormat packetFormat, ArmoredOutputStream.Builder armorBuilder)
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ArmoredOutputStream aOut = armorBuilder.build(bOut);
aOut.write(getEncoded(packetFormat));
aOut.close();
return bOut.toString();
}
/**
* Return a byte array containing the binary representation of the certificate.
*
* @return binary encoded certificate
* @throws IOException if the certificate cannot be encoded
*/
public byte[] getEncoded()
throws IOException
{
return getEncoded(PacketFormat.ROUNDTRIP);
}
/**
* Return a byte array containing the binary representation of the certificate, encoded using the
* given packet length encoding format.
*
* @param format packet length encoding format
* @return binary encoded certificate
* @throws IOException if the certificate cannot be encoded
*/
public byte[] getEncoded(PacketFormat format)
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
BCPGOutputStream pOut = new BCPGOutputStream(bOut, format);
// Make sure we export a TPK
List<PGPPublicKey> list = new ArrayList<PGPPublicKey>();
for (Iterator<PGPPublicKey> it = getPGPKeyRing().getPublicKeys(); it.hasNext(); )
{
list.add(it.next());
}
PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(list);
publicKeys.encode(pOut, true);
pOut.close();
return bOut.toByteArray();
}
private OpenPGPSignatureChain getSignatureChainFor(OpenPGPCertificateComponent component,
OpenPGPComponentKey origin,
Date evaluationDate)
{
// Check if there are signatures at all for the component
OpenPGPSignatureChains chainsForComponent = getAllSignatureChainsFor(component);
boolean isPrimaryKey = component == getPrimaryKey();
if (isPrimaryKey && chainsForComponent.getCertificationAt(evaluationDate) == null)
{
// 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);
}
/**
* Return all {@link OpenPGPSignatureChain OpenPGPSignatureChains} binding the given
* {@link OpenPGPCertificateComponent}.
*
* @param component certificate component
* @return all chains of the component
*/
private OpenPGPSignatureChains getAllSignatureChainsFor(OpenPGPCertificateComponent component)
{
OpenPGPSignatureChains chains = new OpenPGPSignatureChains(component.getPublicComponent());
chains.addAll(componentSignatureChains.get(component.getPublicComponent()));
return chains;
}
/**
* Process the given {@link OpenPGPPrimaryKey}, parsing all its signatures and identities.
*
* @param primaryKey primary key
*/
private void processPrimaryKey(OpenPGPPrimaryKey primaryKey)
{
OpenPGPSignatureChains keySignatureChains = new OpenPGPSignatureChains(primaryKey);
List<OpenPGPComponentSignature> keySignatures = primaryKey.getKeySignatures();
// Key Signatures
addSignaturesToChains(keySignatures, keySignatureChains);
componentSignatureChains.put(primaryKey, keySignatureChains);
// Identities
for (Iterator<OpenPGPIdentityComponent> it = primaryKey.identityComponents.iterator(); it.hasNext(); )
{
OpenPGPIdentityComponent identity = it.next();
OpenPGPSignatureChains identityChains = new OpenPGPSignatureChains(identity);
List<OpenPGPComponentSignature> bindings;
if (identity instanceof OpenPGPUserId)
{
bindings = primaryKey.getUserIdSignatures((OpenPGPUserId)identity);
}
else
{
bindings = primaryKey.getUserAttributeSignatures((OpenPGPUserAttribute)identity);
}
addSignaturesToChains(bindings, identityChains);
componentSignatureChains.put(identity, identityChains);
}
}
/**
* Process the given {@link OpenPGPSubkey}, parsing all its binding signatures.
*
* @param subkey subkey
*/
private void processSubkey(OpenPGPSubkey subkey)
{
List<OpenPGPComponentSignature> bindingSignatures = subkey.getKeySignatures();
OpenPGPSignatureChains subkeyChains = new OpenPGPSignatureChains(subkey);
for (Iterator<OpenPGPComponentSignature> it = bindingSignatures.iterator(); it.hasNext(); )
{
OpenPGPComponentSignature sig = it.next();
OpenPGPComponentKey issuer = subkey.getCertificate().getSigningKeyFor(sig.getSignature());
if (issuer == null)
{
continue; // external key
}
OpenPGPSignatureChains issuerChains = getAllSignatureChainsFor(issuer);
if (!issuerChains.chains.isEmpty())
{
for (Iterator<OpenPGPSignatureChain> it2 = issuerChains.chains.iterator(); it2.hasNext(); )
{
subkeyChains.add(it2.next().plus(sig));
}
}
else
{
subkeyChains.add(new OpenPGPSignatureChain(OpenPGPSignatureChain.Link.create(sig)));
}
}
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)
{
OpenPGPSignature.OpenPGPSignatureSubpacket keyExpiration =
component.getApplyingSubpacket(evaluationTime, SignatureSubpacketTags.KEY_EXPIRE_TIME);
if (keyExpiration != null)
{
KeyExpirationTime kexp = (KeyExpirationTime)keyExpiration.getSubpacket();
if (kexp.getTime() != 0)
{
OpenPGPComponentKey key = component.getKeyComponent();
Date expirationDate = new Date(1000 * kexp.getTime() + key.getCreationTime().getTime());
if (expirationDate.before(evaluationTime))
{
// Key is expired.
return false;
}
}
}
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)
{
return filterKeys(evaluationTime, new KeyFilter()
{
@Override
public boolean test(OpenPGPComponentKey key, Date time)
{
return key.isEncryptionKey(time);
}
});
}
/**
* 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)
{
return filterKeys(evaluationTime, new KeyFilter()
{
@Override
public boolean test(OpenPGPComponentKey key, Date time)
{
return key.isSigningKey(time);
}
});
}
/**
* Return a {@link List} containing all currently valid marked certification keys.
*
* @return list of certification keys
*/
public List<OpenPGPComponentKey> getCertificationKeys()
{
return getCertificationKeys(new Date());
}
/**
* Return a list of all keys that - at evaluation time - are validly marked as certification keys.
*
* @param evaluationTime evaluation time
* @return list of certification keys
*/