sequoia-openpgp 2.4.0

OpenPGP data types and associated machinery
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! OpenPGP v6 key packet.

use std::fmt;
use std::cmp::Ordering;
use std::hash::Hasher;
use std::time;

#[cfg(test)]
use quickcheck::{Arbitrary, Gen};

use crate::Error;
use crate::crypto::{mpi, hash::Hash, mem::Protected, KeyPair};
use crate::packet::key::{
    KeyParts,
    KeyRole,
    KeyRoleRT,
    PublicParts,
    SecretParts,
    UnspecifiedParts,
};
use crate::packet::prelude::*;
use crate::PublicKeyAlgorithm;
use crate::HashAlgorithm;
use crate::types::Timestamp;
use crate::Result;
use crate::crypto::Password;
use crate::KeyID;
use crate::Fingerprint;
use crate::KeyHandle;
use crate::policy::HashAlgoSecurity;

/// Holds a public key, public subkey, private key or private subkey
/// packet.
///
/// Use [`Key6::generate_rsa`] or [`Key6::generate_ecc`] to create a
/// new key.
///
/// Existing key material can be turned into an OpenPGP key using
/// [`Key6::new`], [`Key6::with_secret`], [`Key6::import_public_x25519`],
/// [`Key6::import_public_ed25519`], [`Key6::import_public_rsa`],
/// [`Key6::import_secret_x25519`], [`Key6::import_secret_ed25519`],
/// and [`Key6::import_secret_rsa`].
///
/// Whether you create a new key or import existing key material, you
/// still need to create a binding signature, and, for signing keys, a
/// back signature before integrating the key into a certificate.
///
/// Normally, you won't directly use `Key6`, but [`Key`], which is a
/// relatively thin wrapper around `Key6`.
///
/// See [Section 5.5 of RFC 9580] and [the documentation for `Key`]
/// for more details.
///
/// [Section 5.5 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5
/// [the documentation for `Key`]: super::Key
/// [`Key`]: super::Key
#[derive(PartialEq, Eq, Hash)]
pub struct Key6<P: KeyParts, R: KeyRole> {
    pub(crate) common: Key4<P, R>,
}

// derive(Clone) doesn't work as expected with generic type parameters
// that don't implement clone: it adds a trait bound on Clone to P and
// R in the Clone implementation.  Happily, we don't need P or R to
// implement Clone: they are just marker traits, which we can clone
// manually.
//
// See: https://github.com/rust-lang/rust/issues/26925
impl<P, R> Clone for Key6<P, R>
    where P: KeyParts, R: KeyRole
{
    fn clone(&self) -> Self {
        Key6 {
            common: self.common.clone(),
        }
    }
}

impl<P, R> fmt::Debug for Key6<P, R>
where P: KeyParts,
      R: KeyRole,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Key6")
            .field("fingerprint", &self.fingerprint())
            .field("creation_time", &self.creation_time())
            .field("pk_algo", &self.pk_algo())
            .field("mpis", &self.mpis())
            .field("secret", &self.optional_secret())
            .finish()
    }
}

impl<P, R> fmt::Display for Key6<P, R>
where P: KeyParts,
      R: KeyRole,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.fingerprint())
    }
}

impl<P, R> Key6<P, R>
where P: KeyParts,
      R: KeyRole,
{
    /// The security requirements of the hash algorithm for
    /// self-signatures.
    ///
    /// A cryptographic hash algorithm usually has [three security
    /// properties]: pre-image resistance, second pre-image
    /// resistance, and collision resistance.  If an attacker can
    /// influence the signed data, then the hash algorithm needs to
    /// have both second pre-image resistance, and collision
    /// resistance.  If not, second pre-image resistance is
    /// sufficient.
    ///
    ///   [three security properties]: https://en.wikipedia.org/wiki/Cryptographic_hash_function#Properties
    ///
    /// In general, an attacker may be able to influence third-party
    /// signatures.  But direct key signatures, and binding signatures
    /// are only over data fully determined by signer.  And, an
    /// attacker's control over self signatures over User IDs is
    /// limited due to their structure.
    ///
    /// These observations can be used to extend the life of a hash
    /// algorithm after its collision resistance has been partially
    /// compromised, but not completely broken.  For more details,
    /// please refer to the documentation for [HashAlgoSecurity].
    ///
    ///   [HashAlgoSecurity]: crate::policy::HashAlgoSecurity
    pub fn hash_algo_security(&self) -> HashAlgoSecurity {
        HashAlgoSecurity::SecondPreImageResistance
    }

    /// Compares the public bits of two keys.
    ///
    /// This returns `Ordering::Equal` if the public MPIs, creation
    /// time, and algorithm of the two `Key6`s match.  This does not
    /// consider the packets' encodings, packets' tags or their secret
    /// key material.
    pub fn public_cmp<PB, RB>(&self, b: &Key6<PB, RB>) -> Ordering
    where PB: KeyParts,
          RB: KeyRole,
    {
        self.mpis().cmp(b.mpis())
            .then_with(|| self.creation_time().cmp(&b.creation_time()))
            .then_with(|| self.pk_algo().cmp(&b.pk_algo()))
    }

    /// Tests whether two keys are equal modulo their secret key
    /// material.
    ///
    /// This returns true if the public MPIs, creation time and
    /// algorithm of the two `Key6`s match.  This does not consider
    /// the packets' encodings, packets' tags or their secret key
    /// material.
    pub fn public_eq<PB, RB>(&self, b: &Key6<PB, RB>) -> bool
    where PB: KeyParts,
          RB: KeyRole,
    {
        self.public_cmp(b) == Ordering::Equal
    }

    /// Hashes everything but any secret key material into state.
    ///
    /// This is an alternate implementation of [`Hash`], which never
    /// hashes the secret key material.
    ///
    ///   [`Hash`]: std::hash::Hash
    pub fn public_hash<H>(&self, state: &mut H)
    where H: Hasher
    {
        self.common.public_hash(state);
    }
}

impl<P, R> Key6<P, R>
where
    P: KeyParts,
    R: KeyRole,
{
    /// Gets the `Key`'s creation time.
    pub fn creation_time(&self) -> time::SystemTime {
        self.common.creation_time()
    }

    /// Gets the `Key`'s creation time without converting it to a
    /// system time.
    ///
    /// This conversion may truncate the time to signed 32-bit time_t.
    pub(crate) fn creation_time_raw(&self) -> Timestamp {
        self.common.creation_time_raw()
    }

    /// Sets the `Key`'s creation time.
    ///
    /// `timestamp` is converted to OpenPGP's internal format,
    /// [`Timestamp`]: a 32-bit quantity containing the number of
    /// seconds since the Unix epoch.
    ///
    /// `timestamp` is silently rounded to match the internal
    /// resolution.  An error is returned if `timestamp` is out of
    /// range.
    ///
    /// [`Timestamp`]: crate::types::Timestamp
    pub fn set_creation_time<T>(&mut self, timestamp: T)
                                -> Result<time::SystemTime>
    where T: Into<time::SystemTime>
    {
        self.common.set_creation_time(timestamp)
    }

    /// Gets the public key algorithm.
    pub fn pk_algo(&self) -> PublicKeyAlgorithm {
        self.common.pk_algo()
    }

    /// Sets the public key algorithm.
    ///
    /// Returns the old public key algorithm.
    pub fn set_pk_algo(&mut self, pk_algo: PublicKeyAlgorithm)
                       -> PublicKeyAlgorithm
    {
        self.common.set_pk_algo(pk_algo)
    }

    /// Returns a reference to the `Key`'s MPIs.
    pub fn mpis(&self) -> &mpi::PublicKey {
        self.common.mpis()
    }

    /// Returns a mutable reference to the `Key`'s MPIs.
    pub fn mpis_mut(&mut self) -> &mut mpi::PublicKey {
        self.common.mpis_mut()
    }

    /// Sets the `Key`'s MPIs.
    ///
    /// This function returns the old MPIs, if any.
    pub fn set_mpis(&mut self, mpis: mpi::PublicKey) -> mpi::PublicKey {
        self.common.set_mpis(mpis)
    }

    /// Returns whether the `Key` contains secret key material.
    pub fn has_secret(&self) -> bool {
        self.common.has_secret()
    }

    /// Returns whether the `Key` contains unencrypted secret key
    /// material.
    ///
    /// This returns false if the `Key` doesn't contain any secret key
    /// material.
    pub fn has_unencrypted_secret(&self) -> bool {
        self.common.has_unencrypted_secret()
    }

    /// Returns `Key`'s secret key material, if any.
    pub fn optional_secret(&self) -> Option<&SecretKeyMaterial> {
        self.common.optional_secret()
    }

    /// Computes and returns the `Key`'s `Fingerprint` and returns it as
    /// a `KeyHandle`.
    ///
    /// See [Section 5.5.4 of RFC 9580].
    ///
    /// [Section 5.5.4 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5.4
    pub fn key_handle(&self) -> KeyHandle {
        self.fingerprint().into()
    }

    /// Computes and returns the `Key`'s `Fingerprint`.
    ///
    /// See [Key IDs and Fingerprints].
    ///
    /// [Key IDs and Fingerprints]: https://www.rfc-editor.org/rfc/rfc9580.html#key-ids-fingerprints
    pub fn fingerprint(&self) -> Fingerprint {
        let fp = self.common.fingerprint.get_or_init(|| {
            let mut h = HashAlgorithm::SHA256.context()
                .expect("SHA256 is MTI for RFC9580")
            // v6 fingerprints are computed the same way a key is
            // hashed for v6 signatures.
                .for_signature(6);

            self.hash(&mut h).expect("v6 key hashing is infallible");

            let mut digest = [0u8; 32];
            let _ = h.digest(&mut digest);
            Fingerprint::V6(digest)
        });

        // Currently, it could happen that a Key4 has its fingerprint
        // computed, and is then converted to a Key6.  That is only
        // possible within this crate, and should not happen.  Assert
        // that.  The better way to handle this is to have a CommonKey
        // struct which both Key4 and Key6 use, so that a Key6 does
        // not start out as a Key4, preventing this issue.
        debug_assert!(matches!(fp, Fingerprint::V6(_)));

        fp.clone()
    }

    /// Computes and returns the `Key`'s `Key ID`.
    ///
    /// See [Section 5.5.4 of RFC 9580].
    ///
    /// [Section 5.5.4 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5.4
    pub fn keyid(&self) -> KeyID {
        self.fingerprint().into()
    }

    /// Creates a v6 key from a v4 key.  Used internally in
    /// constructors.
    pub(crate) fn from_common(common: Key4<P, R>) -> Self {
        Key6 { common }
    }

    /// Creates an OpenPGP public key from the specified key material.
    ///
    /// This is an internal version for parse.rs that avoids going
    /// through SystemTime.
    pub(crate) fn make(creation_time: Timestamp,
                       pk_algo: PublicKeyAlgorithm,
                       mpis: mpi::PublicKey,
                       secret: Option<SecretKeyMaterial>)
                       -> Result<Self>
    where
    {
        Ok(Key6 {
            common: Key4::make(creation_time, pk_algo, mpis, secret)?,
        })
    }

    pub(crate) fn role(&self) -> KeyRoleRT {
        self.common.role()
    }

    pub(crate) fn set_role(&mut self, role: KeyRoleRT) {
        self.common.set_role(role);
    }
}

impl<R> Key6<key::PublicParts, R>
where R: KeyRole,
{
    /// Creates an OpenPGP public key from the specified key material.
    pub fn new<T>(creation_time: T, pk_algo: PublicKeyAlgorithm,
                  mpis: mpi::PublicKey)
                  -> Result<Self>
    where T: Into<time::SystemTime>
    {
        Ok(Key6 {
            common: Key4::new(creation_time, pk_algo, mpis)?,
        })
    }

    /// Creates an OpenPGP public key packet from existing X25519 key
    /// material.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_x25519<T>(public_key: &[u8], ctime: T)
                                   -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::X25519,
                              mpi::PublicKey::X25519 {
                                  u: public_key.try_into()?,
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing X448 key
    /// material.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_x448<T>(public_key: &[u8], ctime: T)
                                 -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::X448,
                              mpi::PublicKey::X448 {
                                  u: Box::new(public_key.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing Ed25519 key
    /// material.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_ed25519<T>(public_key: &[u8], ctime: T) -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::Ed25519,
                              mpi::PublicKey::Ed25519 {
                                  a: public_key.try_into()?,
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing Ed448 key
    /// material.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_ed448<T>(public_key: &[u8], ctime: T) -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::Ed448,
                              mpi::PublicKey::Ed448 {
                                  a: Box::new(public_key.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing RSA key
    /// material.
    ///
    /// The RSA key will use the public exponent `e` and the modulo
    /// `n`. The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_rsa<T>(e: &[u8], n: &[u8], ctime: T)
                                -> Result<Self> where T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::import_public_rsa(e, n, ctime)?,
        })
    }

    /// Creates an OpenPGP public key packet from existing ML-DSA-65
    /// and Ed25519 key material.
    ///
    /// Note: in OpenPGP, ML-DSA keys are composite keys and include
    /// an EdDSA key to provide a pre-quantum security fallback.
    ///
    /// The ML-DSA-65 public key must be exactly 1952 bytes.  The
    /// Ed25519 public key must be exactly 32 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_mldsa65_ed25519<T>(
        mldsa: &[u8], eddsa: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::MLDSA65_Ed25519,
                              mpi::PublicKey::MLDSA65_Ed25519 {
                                  eddsa: Box::new(eddsa.try_into()?),
                                  mldsa: Box::new(mldsa.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing ML-DSA-87
    /// and Ed448 key material.
    ///
    /// Note: in OpenPGP, ML-DSA keys are composite keys and include
    /// an EdDSA key to provide a pre-quantum security fallback.
    ///
    /// The ML-DSA-87 public key must be exactly 2592 bytes.  The
    /// Ed448 public key must be exactly 57 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_mldsa87_ed448<T>(
        mldsa: &[u8], eddsa: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::MLDSA87_Ed448,
                              mpi::PublicKey::MLDSA87_Ed448 {
                                  eddsa: Box::new(eddsa.try_into()?),
                                  mldsa: Box::new(mldsa.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing
    /// SLH-DSA-128s key material.
    ///
    /// SLH-DSA-128s keys must be exactly 32 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_slhdsa128s<T>(public: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::SLHDSA128s,
                              mpi::PublicKey::SLHDSA128s {
                                  public: public.try_into()?,
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing
    /// SLH-DSA-128f key material.
    ///
    /// SLH-DSA-128f keys must be exactly 32 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_slhdsa128f<T>(public: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::SLHDSA128f,
                              mpi::PublicKey::SLHDSA128f {
                                  public: public.try_into()?,
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing
    /// SLH-DSA-256s key material.
    ///
    /// SLH-DSA-256s keys must be exactly 64 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_slhdsa256s<T>(public: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::SLHDSA256s,
                              mpi::PublicKey::SLHDSA256s {
                                  public: Box::new(public.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing
    /// ML-KEM768+X25519 key material.
    ///
    /// Note: in OpenPGP, ML-KEM keys are composite keys and include
    /// an X25519 key to provide a pre-quantum security fallback.
    ///
    /// ML-KEM768 keys must be exactly 1184 bytes, and X25519 keys
    /// must be exactly 32 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_mlkem768_x25519<T>(mlkem: &[u8], ecdh: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::MLKEM768_X25519,
                              mpi::PublicKey::MLKEM768_X25519 {
                                  ecdh: Box::new(ecdh.try_into()?),
                                  mlkem: Box::new(mlkem.try_into()?),
                              })?,
        })
    }

    /// Creates an OpenPGP public key packet from existing
    /// ML-KEM1024+X448 key material.
    ///
    /// Note: in OpenPGP, ML-KEM keys are composite keys and include
    /// an X448 key to provide a pre-quantum security fallback.
    ///
    /// ML-KEM1024 keys must be exactly 1568 bytes, and X448 keys must
    /// be exactly 56 bytes.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_public_mlkem1024_x448<T>(mlkem: &[u8], ecdh: &[u8], ctime: T)
        -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>
    {
        Ok(Key6 {
            common: Key4::new(ctime.into().unwrap_or_else(crate::now),
                              PublicKeyAlgorithm::MLKEM1024_X448,
                              mpi::PublicKey::MLKEM1024_X448 {
                                  ecdh: Box::new(ecdh.try_into()?),
                                  mlkem: Box::new(mlkem.try_into()?),
                              })?,
        })
    }
}

impl<R> Key6<SecretParts, R>
where R: KeyRole,
{
    /// Creates an OpenPGP key packet from the specified secret key
    /// material.
    pub fn with_secret<T>(creation_time: T, pk_algo: PublicKeyAlgorithm,
                          mpis: mpi::PublicKey,
                          secret: SecretKeyMaterial)
                          -> Result<Self>
    where T: Into<time::SystemTime>
    {
        Ok(Key6 {
            common: Key4::with_secret(creation_time, pk_algo, mpis, secret)?,
        })
    }

    /// Creates a new OpenPGP secret key packet for an existing X25519
    /// key.
    ///
    /// The given `private_key` is expected to be in the native X25519
    /// representation, i.e. as opaque byte string of length 32.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_secret_x25519<T>(private_key: &[u8],
                                   ctime: T)
                                   -> Result<Self>
    where
        T: Into<Option<std::time::SystemTime>>,
    {
        use crate::crypto::backend::{Backend, interface::Asymmetric};

        let private_key = Protected::from(private_key);
        let public_key = Backend::x25519_derive_public(&private_key)?;

        Self::with_secret(
            ctime.into().unwrap_or_else(crate::now),
            PublicKeyAlgorithm::X25519,
            mpi::PublicKey::X25519 {
                u: public_key,
            },
            mpi::SecretKeyMaterial::X25519 {
                x: private_key.into(),
            }.into())
    }

    /// Creates a new OpenPGP secret key packet for an existing X448
    /// key.
    ///
    /// The given `private_key` is expected to be in the native X448
    /// representation, i.e. as opaque byte string of length 32.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_secret_x448<T>(private_key: &[u8],
                                 ctime: T)
                                 -> Result<Self>
    where
        T: Into<Option<std::time::SystemTime>>,
    {
        use crate::crypto::backend::{Backend, interface::Asymmetric};

        let private_key = Protected::from(private_key);
        let public_key = Backend::x448_derive_public(&private_key)?;

        Self::with_secret(
            ctime.into().unwrap_or_else(crate::now),
            PublicKeyAlgorithm::X448,
            mpi::PublicKey::X448 {
                u: Box::new(public_key),
            },
            mpi::SecretKeyMaterial::X448 {
                x: private_key.into(),
            }.into())
    }

    /// Creates a new OpenPGP secret key packet for an existing
    /// Ed25519 key.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_secret_ed25519<T>(private_key: &[u8], ctime: T)
                                    -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        use crate::crypto::backend::{Backend, interface::Asymmetric};

        let private_key = Protected::from(private_key);
        let public_key = Backend::ed25519_derive_public(&private_key)?;

        Self::with_secret(
            ctime.into().unwrap_or_else(crate::now),
            PublicKeyAlgorithm::Ed25519,
            mpi::PublicKey::Ed25519 {
                a: public_key,
            },
            mpi::SecretKeyMaterial::Ed25519 {
                x: private_key.into(),
            }.into())
    }

    /// Creates a new OpenPGP secret key packet for an existing
    /// Ed448 key.
    ///
    /// The key will have its creation date set to `ctime` or the
    /// current time if `None` is given.
    pub fn import_secret_ed448<T>(private_key: &[u8], ctime: T)
                                  -> Result<Self>
    where
        T: Into<Option<time::SystemTime>>,
    {
        use crate::crypto::backend::{Backend, interface::Asymmetric};

        let private_key = Protected::from(private_key);
        let public_key = Backend::ed448_derive_public(&private_key)?;

        Self::with_secret(
            ctime.into().unwrap_or_else(crate::now),
            PublicKeyAlgorithm::Ed448,
            mpi::PublicKey::Ed448 {
                a: Box::new(public_key),
            },
            mpi::SecretKeyMaterial::Ed448 {
                x: private_key.into(),
            }.into())
    }

    /// Creates a new key pair from a secret `Key` with an unencrypted
    /// secret key.
    ///
    /// # Errors
    ///
    /// Fails if the secret key is encrypted.  You can use
    /// [`Key::decrypt_secret`] to decrypt a key.
    pub fn into_keypair(self) -> Result<KeyPair> {
        let (key, secret) = self.take_secret();
        let secret = match secret {
            SecretKeyMaterial::Unencrypted(secret) => secret,
            SecretKeyMaterial::Encrypted(_) =>
                return Err(Error::InvalidArgument(
                    "secret key material is encrypted".into()).into()),
        };

        KeyPair::new(key.role_into_unspecified().into(), secret)
    }
}

macro_rules! impl_common_secret_functions_v6 {
    ($t: ident) => {
        /// Secret key material handling.
        impl<R> Key6<$t, R>
        where R: KeyRole,
        {
            /// Takes the `Key`'s `SecretKeyMaterial`, if any.
            pub fn take_secret(mut self)
                               -> (Key6<PublicParts, R>, Option<SecretKeyMaterial>)
            {
                let old = std::mem::replace(&mut self.common.secret, None);
                (self.parts_into_public(), old)
            }

            /// Adds the secret key material to the `Key`, returning
            /// the old secret key material, if any.
            pub fn add_secret(mut self, secret: SecretKeyMaterial)
                              -> (Key6<SecretParts, R>, Option<SecretKeyMaterial>)
            {
                let old = std::mem::replace(&mut self.common.secret, Some(secret));
                (self.parts_into_secret().expect("secret just set"), old)
            }

            /// Takes the `Key`'s `SecretKeyMaterial`, if any.
            pub fn steal_secret(&mut self) -> Option<SecretKeyMaterial>
            {
                std::mem::replace(&mut self.common.secret, None)
            }
        }
    }
}
impl_common_secret_functions_v6!(PublicParts);
impl_common_secret_functions_v6!(UnspecifiedParts);

/// Secret key handling.
impl<R> Key6<SecretParts, R>
where R: KeyRole,
{
    /// Gets the `Key`'s `SecretKeyMaterial`.
    pub fn secret(&self) -> &SecretKeyMaterial {
        self.common.secret()
    }

    /// Gets a mutable reference to the `Key`'s `SecretKeyMaterial`.
    pub fn secret_mut(&mut self) -> &mut SecretKeyMaterial {
        self.common.secret_mut()
    }

    /// Takes the `Key`'s `SecretKeyMaterial`.
    pub fn take_secret(mut self)
                       -> (Key6<PublicParts, R>, SecretKeyMaterial)
    {
        let old = std::mem::replace(&mut self.common.secret, None);
        (self.parts_into_public(),
         old.expect("Key<SecretParts, _> has a secret key material"))
    }

    /// Adds `SecretKeyMaterial` to the `Key`.
    ///
    /// This function returns the old secret key material, if any.
    pub fn add_secret(mut self, secret: SecretKeyMaterial)
                      -> (Key6<SecretParts, R>, SecretKeyMaterial)
    {
        let old = std::mem::replace(&mut self.common.secret, Some(secret));
        (self.parts_into_secret().expect("secret just set"),
         old.expect("Key<SecretParts, _> has a secret key material"))
    }

    /// Decrypts the secret key material using `password`.
    ///
    /// In OpenPGP, secret key material can be [protected with a
    /// password].  The password is usually hardened using a [KDF].
    ///
    /// Refer to the documentation of [`Key::decrypt_secret`] for
    /// details.
    ///
    /// This function returns an error if the secret key material is
    /// not encrypted or the password is incorrect.
    ///
    /// [protected with a password]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5.3
    /// [KDF]: https://www.rfc-editor.org/rfc/rfc9580.html#section-3.7
    /// [`Key::decrypt_secret`]: super::Key::decrypt_secret()
    pub fn decrypt_secret(self, password: &Password) -> Result<Self> {
        let (key, mut secret) = self.take_secret();
        // Note: Key version is authenticated.
        let key = Key::V6(key);
        secret.decrypt_in_place(&key, password)?;
        let key = if let Key::V6(k) = key { k } else { unreachable!() };
        Ok(key.add_secret(secret).0)
    }

    /// Encrypts the secret key material using `password`.
    ///
    /// In OpenPGP, secret key material can be [protected with a
    /// password].  The password is usually hardened using a [KDF].
    ///
    /// Refer to the documentation of [`Key::encrypt_secret`] for
    /// details.
    ///
    /// This returns an error if the secret key material is already
    /// encrypted.
    ///
    /// [protected with a password]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5.3
    /// [KDF]: https://www.rfc-editor.org/rfc/rfc9580.html#section-3.7
    /// [`Key::encrypt_secret`]: super::Key::encrypt_secret()
    pub fn encrypt_secret(self, password: &Password)
                          -> Result<Key6<SecretParts, R>>
    {
        let (key, mut secret) = self.take_secret();
        // Note: Key version is authenticated.
        let key = Key::V6(key);
        secret.encrypt_in_place(&key, password)?;
        let key = if let Key::V6(k) = key { k } else { unreachable!() };
        Ok(key.add_secret(secret).0)
    }
}

impl<P, R> From<Key6<P, R>> for super::Key<P, R>
where P: KeyParts,
      R: KeyRole,
{
    fn from(p: Key6<P, R>) -> Self {
        super::Key::V6(p)
    }
}

#[cfg(test)]
use crate::packet::key::{
    PrimaryRole,
    SubordinateRole,
    UnspecifiedRole,
};

#[cfg(test)]
impl Arbitrary for Key6<PublicParts, PrimaryRole> {
    fn arbitrary(g: &mut Gen) -> Self {
        Key6::from_common(Key4::arbitrary(g))
    }
}

#[cfg(test)]
impl Arbitrary for Key6<PublicParts, SubordinateRole> {
    fn arbitrary(g: &mut Gen) -> Self {
        Key6::from_common(Key4::arbitrary(g))
    }
}

#[cfg(test)]
impl Arbitrary for Key6<PublicParts, UnspecifiedRole> {
    fn arbitrary(g: &mut Gen) -> Self {
        Key6::from_common(Key4::arbitrary(g))
    }
}

#[cfg(test)]
impl Arbitrary for Key6<SecretParts, PrimaryRole> {
    fn arbitrary(g: &mut Gen) -> Self {
        Key6::from_common(Key4::arbitrary(g))
    }
}

#[cfg(test)]
impl Arbitrary for Key6<SecretParts, SubordinateRole> {
    fn arbitrary(g: &mut Gen) -> Self {
        Key6::from_common(Key4::arbitrary(g))
    }
}


#[cfg(test)]
mod tests {
    use std::time::Duration;
    use std::time::UNIX_EPOCH;

    use crate::crypto::S2K;
    use crate::packet::Key;
    use crate::packet::key;
    use crate::packet::Packet;
    use super::*;
    use crate::PacketPile;
    use crate::serialize::Serialize;
    use crate::types::*;
    use crate::parse::Parse;

    #[test]
    fn primary_key_encrypt_decrypt() -> Result<()> {
        key_encrypt_decrypt::<PrimaryRole>()
    }

    #[test]
    fn subkey_encrypt_decrypt() -> Result<()> {
        key_encrypt_decrypt::<SubordinateRole>()
    }

    fn key_encrypt_decrypt<R>() -> Result<()>
    where
        R: KeyRole + PartialEq,
    {
        let mut g = quickcheck::Gen::new(256);
        let p: Password = Vec::<u8>::arbitrary(&mut g).into();

        let check = |key: Key6<SecretParts, R>| -> Result<()> {
            let key: Key<_, _> = key.into();
            let encrypted = key.clone().encrypt_secret(&p)?;
            let decrypted = encrypted.decrypt_secret(&p)?;
            assert_eq!(key, decrypted);
            Ok(())
        };

        use crate::types::Curve::*;
        for curve in vec![NistP256, NistP384, NistP521, Ed25519] {
            if ! curve.is_supported() {
                eprintln!("Skipping unsupported {}", curve);
                continue;
            }

            let key: Key6<_, R>
                = Key6::generate_ecc(true, curve.clone())?;
            check(key)?;
        }

        for bits in vec![2048, 3072] {
            if ! PublicKeyAlgorithm::RSAEncryptSign.is_supported() {
                eprintln!("Skipping unsupported RSA");
                continue;
            }

            let key: Key6<_, R>
                = Key6::generate_rsa(bits)?;
            check(key)?;
        }

        Ok(())
    }

    #[test]
    fn eq() {
        use crate::types::Curve::*;

        for curve in vec![NistP256, NistP384, NistP521] {
            if ! curve.is_supported() {
                eprintln!("Skipping unsupported {}", curve);
                continue;
            }

            let sign_key : Key6<_, key::UnspecifiedRole>
                = Key6::generate_ecc(true, curve.clone()).unwrap();
            let enc_key : Key6<_, key::UnspecifiedRole>
                = Key6::generate_ecc(false, curve).unwrap();
            let sign_clone = sign_key.clone();
            let enc_clone = enc_key.clone();

            assert_eq!(sign_key, sign_clone);
            assert_eq!(enc_key, enc_clone);
        }

        for bits in vec![1024, 2048, 3072, 4096] {
            if ! PublicKeyAlgorithm::RSAEncryptSign.is_supported() {
                eprintln!("Skipping unsupported RSA");
                continue;
            }

            let key : Key6<_, key::UnspecifiedRole>
                = Key6::generate_rsa(bits).unwrap();
            let clone = key.clone();
            assert_eq!(key, clone);
        }
    }

    #[test]
    fn generate_roundtrip() {
        use crate::types::Curve::*;

        let keys = vec![NistP256, NistP384, NistP521].into_iter().flat_map(|cv|
        {
            if ! cv.is_supported() {
                eprintln!("Skipping unsupported {}", cv);
                return Vec::new();
            }

            let sign_key : Key6<key::SecretParts, key::PrimaryRole>
                = Key6::generate_ecc(true, cv.clone()).unwrap();
            let enc_key = Key6::generate_ecc(false, cv).unwrap();

            vec![sign_key, enc_key]
        }).chain(vec![1024, 2048, 3072, 4096].into_iter().filter_map(|b| {
            Key6::generate_rsa(b).ok()
        }));

        for key in keys {
            let mut b = Vec::new();
            Packet::SecretKey(key.clone().into()).serialize(&mut b).unwrap();

            let pp = PacketPile::from_bytes(&b).unwrap();
            if let Some(Packet::SecretKey(Key::V6(ref parsed_key))) =
                pp.path_ref(&[0])
            {
                assert_eq!(key.creation_time(), parsed_key.creation_time());
                assert_eq!(key.pk_algo(), parsed_key.pk_algo());
                assert_eq!(key.mpis(), parsed_key.mpis());
                assert_eq!(key.secret(), parsed_key.secret());

                assert_eq!(&key, parsed_key);
            } else {
                panic!("bad packet: {:?}", pp.path_ref(&[0]));
            }

            let mut b = Vec::new();
            let pk4 : Key6<PublicParts, PrimaryRole> = key.clone().into();
            Packet::PublicKey(pk4.into()).serialize(&mut b).unwrap();

            let pp = PacketPile::from_bytes(&b).unwrap();
            if let Some(Packet::PublicKey(Key::V6(ref parsed_key))) =
                pp.path_ref(&[0])
            {
                assert!(! parsed_key.has_secret());

                let key = key.take_secret().0;
                assert_eq!(&key, parsed_key);
            } else {
                panic!("bad packet: {:?}", pp.path_ref(&[0]));
            }
        }
    }

    #[test]
    fn encryption_roundtrip() {
        use crate::crypto::SessionKey;
        use crate::types::Curve::*;

        let keys = vec![NistP256, NistP384, NistP521].into_iter()
            .filter_map(|cv| {
                Key6::generate_ecc(false, cv).ok()
            }).chain(vec![1024, 2048, 3072, 4096].into_iter().filter_map(|b| {
                Key6::generate_rsa(b).ok()
            })).chain([
                (PublicKeyAlgorithm::MLKEM768_X25519, Key6::generate_mlkem768_x25519 as fn() -> Result<_>),
                (PublicKeyAlgorithm::MLKEM1024_X448, Key6::generate_mlkem1024_x448),
            ].into_iter().filter_map(|(algo, gen)| {
                if algo.is_supported() {
                    Some(gen().expect(&format!("{} is supported", algo)))
                } else {
                    None
                }
            }));

        for key in keys.into_iter() {
            let key: Key<key::SecretParts, key::UnspecifiedRole> = key.into();
            let mut keypair = key.clone().into_keypair().unwrap();
            let cipher = SymmetricAlgorithm::AES256;
            let sk = SessionKey::new(cipher.key_size().unwrap()).unwrap();

            let pkesk = PKESK6::for_recipient(&sk, &key).unwrap();
            let sk_ = pkesk.decrypt(&mut keypair, None)
                .expect("keypair should be able to decrypt PKESK");
            assert_eq!(sk, sk_);

            let sk_ =
                pkesk.decrypt(&mut keypair, Some(cipher)).unwrap();
            assert_eq!(sk, sk_);
        }
    }

    #[test]
    fn signature_roundtrip() {
        use crate::types::{Curve::*, SignatureType};

        let keys = vec![NistP256, NistP384, NistP521].into_iter()
            .filter_map(|cv| {
                Key6::generate_ecc(true, cv).ok()
            }).chain(vec![1024, 2048, 3072, 4096].into_iter().filter_map(|b| {
                Key6::generate_rsa(b).ok()
            })).chain([
                (PublicKeyAlgorithm::MLDSA65_Ed25519, Key6::generate_mldsa65_ed25519 as fn() -> Result<_>),
                (PublicKeyAlgorithm::MLDSA87_Ed448, Key6::generate_mldsa87_ed448),
                (PublicKeyAlgorithm::SLHDSA128s, Key6::generate_slhdsa128s),
                (PublicKeyAlgorithm::SLHDSA128f, Key6::generate_slhdsa128f),
                (PublicKeyAlgorithm::SLHDSA256s, Key6::generate_slhdsa256s),
            ].into_iter().filter_map(|(algo, gen)| {
                if algo.is_supported() {
                    Some(gen().expect(&format!("{} is supported", algo)))
                } else {
                    None
                }
            }));

        for key in keys.into_iter() {
            let key: Key<key::SecretParts, key::UnspecifiedRole> = key.into();
            let mut keypair = key.clone().into_keypair().unwrap();
            let hash = HashAlgorithm::default();

            // Sign.
            let ctx = hash.context().unwrap().for_signature(key.version());
            let sig = SignatureBuilder::new(SignatureType::Binary)
                .sign_hash(&mut keypair, ctx).unwrap();

            // Verify.
            let ctx = hash.context().unwrap().for_signature(key.version());
            sig.verify_hash(&key, ctx).unwrap();
        }
    }

    #[test]
    fn secret_encryption_roundtrip() {
        use crate::types::Curve::*;
        use crate::types::SymmetricAlgorithm::*;
        use crate::types::AEADAlgorithm::*;

        let keys = vec![NistP256, NistP384, NistP521].into_iter()
            .filter_map(|cv| -> Option<Key<key::SecretParts, key::PrimaryRole>> {
                Key6::generate_ecc(false, cv).map(Into::into).ok()
            }).chain(vec![1024, 2048, 3072, 4096].into_iter().filter_map(|b| {
                Key6::generate_rsa(b).map(Into::into).ok()
            }));

        for key in keys {
          for (symm, aead) in [(AES128, None),
                               (AES128, Some(OCB)),
                               (AES256, Some(EAX))] {
            if ! aead.map(|a| a.is_supported()).unwrap_or(true) {
                continue;
            }
            assert!(! key.secret().is_encrypted());

            let password = Password::from("foobarbaz");
            let mut encrypted_key = key.clone();

            encrypted_key.secret_mut()
                .encrypt_in_place_with(&key, S2K::default(), symm, aead,
                                       &password).unwrap();
            assert!(encrypted_key.secret().is_encrypted());

            encrypted_key.secret_mut()
                .decrypt_in_place(&key, &password).unwrap();
            assert!(! key.secret().is_encrypted());
            assert_eq!(key, encrypted_key);
            assert_eq!(key.secret(), encrypted_key.secret());
          }
        }
    }

    #[test]
    fn encrypt_huge_plaintext() -> Result<()> {
        let sk = crate::crypto::SessionKey::new(256).unwrap();

        if PublicKeyAlgorithm::RSAEncryptSign.is_supported() {
            let rsa2k: Key<SecretParts, UnspecifiedRole> =
                Key6::generate_rsa(2048)?.into();
            assert!(matches!(
                rsa2k.encrypt(&sk).unwrap_err().downcast().unwrap(),
                crate::Error::InvalidArgument(_)
            ));
        }

        Ok(())
    }

    #[test]
    fn issue_1016() {
        // The fingerprint is a function of the creation time,
        // algorithm, and public MPIs.  When we change them make sure
        // the fingerprint also changes.

        let mut g = quickcheck::Gen::new(256);

        let mut key = Key6::<PublicParts, UnspecifiedRole>::arbitrary(&mut g);
        let fpr1 = key.fingerprint();
        if key.creation_time() == UNIX_EPOCH {
            key.set_creation_time(UNIX_EPOCH + Duration::new(1, 0)).expect("ok");
        } else {
            key.set_creation_time(UNIX_EPOCH).expect("ok");
        }
        assert_ne!(fpr1, key.fingerprint());

        let mut key = Key6::<PublicParts, UnspecifiedRole>::arbitrary(&mut g);
        let fpr1 = key.fingerprint();
        key.set_pk_algo(PublicKeyAlgorithm::from(u8::from(key.pk_algo()) + 1));
        assert_ne!(fpr1, key.fingerprint());

        let mut key = Key6::<PublicParts, UnspecifiedRole>::arbitrary(&mut g);
        let fpr1 = key.fingerprint();
        loop {
            let mpis2 = mpi::PublicKey::arbitrary(&mut g);
            if key.mpis() != &mpis2 {
                *key.mpis_mut() = mpis2;
                break;
            }
        }
        assert_ne!(fpr1, key.fingerprint());

        let mut key = Key6::<PublicParts, UnspecifiedRole>::arbitrary(&mut g);
        let fpr1 = key.fingerprint();
        loop {
            let mpis2 = mpi::PublicKey::arbitrary(&mut g);
            if key.mpis() != &mpis2 {
                key.set_mpis(mpis2);
                break;
            }
        }
        assert_ne!(fpr1, key.fingerprint());
    }

    /// Smoke test for ECC key creation, signing and verification, and
    /// encryption and decryption.
    #[test]
    fn ecc_support() -> Result<()> {
        for for_signing in [true, false] {
            for curve in Curve::variants()
                .filter(Curve::is_supported)
            {
                match curve {
                    Curve::Cv25519 if for_signing => continue,
                    Curve::Ed25519 if ! for_signing => continue,
                    _ => (),
                }

                eprintln!("curve {}, for signing {:?}", curve, for_signing);
                let key: Key<SecretParts, UnspecifiedRole> =
                    Key6::generate_ecc(for_signing, curve.clone())?.into();
                let mut pair = key.into_keypair()?;

                if for_signing {
                    use crate::crypto::Signer;
                    let hash = HashAlgorithm::default();
                    let digest = hash.context()?
                        .for_signature(pair.public().version())
                        .into_digest()?;
                    let sig = pair.sign(hash, &digest)?;
                    pair.public().verify(&sig, hash, &digest)?;
                } else {
                    use crate::crypto::{SessionKey, Decryptor};
                    let sk = SessionKey::new(32).unwrap();
                    let ciphertext = pair.public().encrypt(&sk)?;
                    assert_eq!(pair.decrypt(&ciphertext, Some(sk.len()))?, sk);
                }
            }
        }
        Ok(())
    }

    #[test]
    fn ecc_encoding() -> Result<()> {
        for for_signing in [true, false] {
            for curve in Curve::variants()
                .filter(Curve::is_supported)
            {
                match curve {
                    Curve::Cv25519 if for_signing => continue,
                    Curve::Ed25519 if ! for_signing => continue,
                    _ => (),
                }

                use crate::crypto::mpi::{Ciphertext, MPI, PublicKey};
                eprintln!("curve {}, for signing {:?}", curve, for_signing);

                let key: Key<SecretParts, UnspecifiedRole> =
                    Key6::generate_ecc(for_signing, curve.clone())?.into();

                let uncompressed = |mpi: &MPI| mpi.value()[0] == 0x04;

                match key.mpis() {
                    PublicKey::X25519 { .. } if ! for_signing => (),
                    PublicKey::X448 { .. } if ! for_signing => (),
                    PublicKey::Ed25519 { .. } if for_signing => (),
                    PublicKey::Ed448 { .. } if for_signing => (),
                    PublicKey::ECDSA { curve: c, q } if for_signing => {
                        assert!(c == &curve);
                        assert!(c != &Curve::Ed25519);
                        assert!(uncompressed(q));
                    },
                    PublicKey::ECDH { curve: c, q, .. } if ! for_signing => {
                        assert!(c == &curve);
                        assert!(c != &Curve::Cv25519);
                        assert!(uncompressed(q));

                        use crate::crypto::SessionKey;
                        let sk = SessionKey::new(32).unwrap();
                        let ciphertext = key.encrypt(&sk)?;
                        if let Ciphertext::ECDH { e, .. } = &ciphertext {
                            assert!(uncompressed(e));
                        } else {
                            panic!("unexpected ciphertext: {:?}", ciphertext);
                        }
                    },
                    mpi => unreachable!(
                        "curve {}, mpi {:?}, for signing {:?}",
                        curve, mpi, for_signing),
                }
            }
        }
        Ok(())
    }


    #[test]
    fn v6_key_fingerprint() -> Result<()> {
        let p = Packet::from_bytes("-----BEGIN PGP ARMORED FILE-----

xjcGY4d/4xYAAAAtCSsGAQQB2kcPAQEHQPlNp7tI1gph5WdwamWH0DMZmbudiRoI
JC6thFQ9+JWj
=SgmS
-----END PGP ARMORED FILE-----")?;
        let k: &Key<PublicParts, PrimaryRole> = p.downcast_ref().unwrap();
        assert_eq!(k.fingerprint().to_string(),
                   "4EADF309C6BC874AE04702451548F93F\
                    96FA7A01D0A33B5AF7D4E379E0F9F8EE".to_string());
        Ok(())
    }

    #[test]
    fn import_public_mldsa() -> Result<()> {
        if PublicKeyAlgorithm::MLDSA65_Ed25519.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_mldsa65_ed25519()
                .expect("failed to generate MLDSA65 key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::MLDSA65_Ed25519);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::MLDSA65_Ed25519 {
                eddsa,
                mldsa,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_mldsa65_ed25519(
                &mldsa[..], &eddsa[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        if PublicKeyAlgorithm::MLDSA87_Ed448.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_mldsa87_ed448()
                .expect("failed to generate MLDSA87 key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::MLDSA87_Ed448);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::MLDSA87_Ed448 {
                eddsa,
                mldsa,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_mldsa87_ed448(
                &mldsa[..], &eddsa[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        Ok(())
    }


    #[test]
    fn import_public_slhdsa() -> Result<()> {
        if PublicKeyAlgorithm::SLHDSA128s.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_slhdsa128s()
                .expect("failed to generate SLHDSA128s key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::SLHDSA128s);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::SLHDSA128s {
                public,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_slhdsa128s(
                &public[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        if PublicKeyAlgorithm::SLHDSA128f.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_slhdsa128f()
                .expect("failed to generate SLHDSA128f key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::SLHDSA128f);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::SLHDSA128f {
                public,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_slhdsa128f(
                &public[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        if PublicKeyAlgorithm::SLHDSA256s.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_slhdsa256s()
                .expect("failed to generate SLHDSA256s key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::SLHDSA256s);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::SLHDSA256s {
                public,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_slhdsa256s(
                &public[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        Ok(())
    }

    #[test]
    fn import_public_mlkem() -> Result<()> {
        if PublicKeyAlgorithm::MLKEM768_X25519.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_mlkem768_x25519()
                .expect("failed to generate ML-KEM768 key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::MLKEM768_X25519);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::MLKEM768_X25519 {
                ecdh,
                mlkem,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_mlkem768_x25519(
                &mlkem[..], &ecdh[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        if PublicKeyAlgorithm::MLKEM1024_X448.is_supported() {
            let key: Key6<SecretParts, UnspecifiedRole>
                = Key6::generate_mlkem1024_x448()
                .expect("failed to generate ML-KEM1024 key, but it is supported.");

            assert_eq!(key.pk_algo(), PublicKeyAlgorithm::MLKEM1024_X448);
            let creation_time = key.creation_time();
            let mpis = key.mpis();
            let crate::crypto::mpi::PublicKey::MLKEM1024_X448 {
                ecdh,
                mlkem,
            } = &mpis else {
                panic!("Key generate generated the wrong key");
            };

            let imported_key = Key6::import_public_mlkem1024_x448(
                &mlkem[..], &ecdh[..], creation_time)
                .expect("Can import key");

            assert_eq!(key.parts_into_public(), imported_key);
        }

        Ok(())
    }
}