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
//! Multiprecision Integers.
//!
//! Cryptographic objects like [public keys], [secret keys],
//! [ciphertexts], and [signatures] are scalar numbers of arbitrary
//! precision.  OpenPGP specifies that these are stored encoded as
//! big-endian integers with leading zeros stripped (See [Section 3.2
//! of RFC 4880]).  Multiprecision integers in OpenPGP are extended by
//! [RFC 6637] to store curves and coordinates used in elliptic curve
//! cryptography (ECC).
//!
//!   [public keys]: PublicKey
//!   [secret keys]: SecretKeyMaterial
//!   [ciphertexts]: Ciphertext
//!   [signatures]: Signature
//!   [Section 3.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-3.2
//!   [RFC 6637]: https://tools.ietf.org/html/rfc6637

use std::fmt;
use std::cmp::Ordering;
use std::io::Write;
use std::borrow::Cow;

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

use crate::types::{
    Curve,
    HashAlgorithm,
    PublicKeyAlgorithm,
    SymmetricAlgorithm,
};
use crate::crypto::hash::{self, Hash};
use crate::crypto::mem::{secure_cmp, Protected};
use crate::serialize::Marshal;

use crate::Error;
use crate::Result;

/// A Multiprecision Integer.
#[derive(Clone)]
pub struct MPI {
    /// Integer value as big-endian with leading zeros stripped.
    value: Box<[u8]>,
}
assert_send_and_sync!(MPI);

impl From<Vec<u8>> for MPI {
    fn from(v: Vec<u8>) -> Self {
        // XXX: This will leak secrets in v into the heap.  But,
        // eagerly clearing the memory may have a very high overhead,
        // after all, most MPIs that we encounter will not contain
        // secrets.  I think it is better to avoid creating MPIs that
        // contain secrets in the first place.  In 2.0, we can remove
        // the impl From<MPI> for ProtectedMPI.
        Self::new(&v)
    }
}

impl From<Box<[u8]>> for MPI {
    fn from(v: Box<[u8]>) -> Self {
        // XXX: This will leak secrets in v into the heap.  But,
        // eagerly clearing the memory may have a very high overhead,
        // after all, most MPIs that we encounter will not contain
        // secrets.  I think it is better to avoid creating MPIs that
        // contain secrets in the first place.  In 2.0, we can remove
        // the impl From<MPI> for ProtectedMPI.
        Self::new(&v)
    }
}

impl MPI {
    /// Trims leading zero octets.
    fn trim_leading_zeros(v: &[u8]) -> &[u8] {
        let offset = v.iter().take_while(|&&o| o == 0).count();
        &v[offset..]
    }

    /// Creates a new MPI.
    ///
    /// This function takes care of removing leading zeros.
    pub fn new(value: &[u8]) -> Self {
        let value = Self::trim_leading_zeros(value).to_vec().into_boxed_slice();

        MPI {
            value,
        }
    }

    /// Creates new MPI encoding an uncompressed EC point.
    ///
    /// Encodes the given point on a elliptic curve (see [Section 6 of
    /// RFC 6637] for details).  This is used to encode public keys
    /// and ciphertexts for the NIST curves (`NistP256`, `NistP384`,
    /// and `NistP521`).
    ///
    ///   [Section 6 of RFC 6637]: https://tools.ietf.org/html/rfc6637#section-6
    pub fn new_point(x: &[u8], y: &[u8], field_bits: usize) -> Self {
        Self::new_point_common(x, y, field_bits).into()
    }

    /// Common implementation shared between MPI and ProtectedMPI.
    fn new_point_common(x: &[u8], y: &[u8], field_bits: usize) -> Vec<u8> {
        let field_sz = if field_bits % 8 > 0 { 1 } else { 0 } + field_bits / 8;
        let mut val = vec![0x0u8; 1 + 2 * field_sz];
        let x_missing = field_sz - x.len();
        let y_missing = field_sz - y.len();

        val[0] = 0x4;
        val[1 + x_missing..1 + field_sz].copy_from_slice(x);
        val[1 + field_sz + y_missing..].copy_from_slice(y);
        val
    }

    /// Creates new MPI encoding a compressed EC point using native
    /// encoding.
    ///
    /// Encodes the given point on a elliptic curve (see [Section 13.2
    /// of RFC4880bis] for details).  This is used to encode public
    /// keys and ciphertexts for the Bernstein curves (currently
    /// `X25519`).
    ///
    ///   [Section 13.2 of RFC4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-13.2
    pub fn new_compressed_point(x: &[u8]) -> Self {
        Self::new_compressed_point_common(x).into()
    }

    /// Common implementation shared between MPI and ProtectedMPI.
    fn new_compressed_point_common(x: &[u8]) -> Vec<u8> {
        let mut val = vec![0; 1 + x.len()];
        val[0] = 0x40;
        val[1..].copy_from_slice(x);
        val
    }

    /// Creates a new MPI representing zero.
    pub fn zero() -> Self {
        Self::new(&[])
    }

    /// Tests whether the MPI represents zero.
    pub fn is_zero(&self) -> bool {
        self.value().is_empty()
    }

    /// Returns the length of the MPI in bits.
    ///
    /// Leading zero-bits are not included in the returned size.
    pub fn bits(&self) -> usize {
        self.value.len() * 8
            - self.value.get(0).map(|&b| b.leading_zeros() as usize)
                  .unwrap_or(0)
    }

    /// Returns the value of this MPI.
    ///
    /// Note that due to stripping of zero-bytes, the returned value
    /// may be shorter than expected.
    pub fn value(&self) -> &[u8] {
        &self.value
    }

    /// Returns the value of this MPI zero-padded to the given length.
    ///
    /// MPI-encoding strips leading zero-bytes.  This function adds
    /// them back, if necessary.  If the size exceeds `to`, an error
    /// is returned.
    pub fn value_padded(&self, to: usize) -> Result<Cow<[u8]>> {
        crate::crypto::pad(self.value(), to)
    }

    /// Decodes an EC point encoded as MPI.
    ///
    /// Decodes the MPI into a point on an elliptic curve (see
    /// [Section 6 of RFC 6637] and [Section 13.2 of RFC4880bis] for
    /// details).  If the point is not compressed, the function
    /// returns `(x, y)`.  If it is compressed, `y` will be empty.
    ///
    ///   [Section 6 of RFC 6637]: https://tools.ietf.org/html/rfc6637#section-6
    ///   [Section 13.2 of RFC4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-13.2
    ///
    /// # Errors
    ///
    /// Returns `Error::UnsupportedEllipticCurve` if the curve is not
    /// supported, `Error::MalformedMPI` if the point is formatted
    /// incorrectly, `Error::InvalidOperation` if the given curve is
    /// operating on native octet strings.
    pub fn decode_point(&self, curve: &Curve) -> Result<(&[u8], &[u8])> {
        Self::decode_point_common(self.value(), curve)
    }

    /// Common implementation shared between MPI and ProtectedMPI.
    fn decode_point_common<'a>(value: &'a [u8], curve: &Curve)
                               -> Result<(&'a [u8], &'a [u8])> {
        const ED25519_KEY_SIZE: usize = 32;
        const CURVE25519_SIZE: usize = 32;
        use self::Curve::*;
        match &curve {
            Ed25519 | Cv25519 => {
                assert_eq!(CURVE25519_SIZE, ED25519_KEY_SIZE);
                // This curve uses a custom compression format which
                // only contains the X coordinate.
                if value.len() != 1 + CURVE25519_SIZE {
                    return Err(Error::MalformedMPI(
                        format!("Bad size of Curve25519 key: {} expected: {}",
                                value.len(),
                                1 + CURVE25519_SIZE
                        )
                    ).into());
                }

                if value.get(0).map(|&b| b != 0x40).unwrap_or(true) {
                    return Err(Error::MalformedMPI(
                        "Bad encoding of Curve25519 key".into()).into());
                }

                Ok((&value[1..], &[]))
            },

            Unknown(_) if ! curve.is_brainpoolp384() =>
                Err(Error::UnsupportedEllipticCurve(curve.clone()).into()),

            NistP256
                | NistP384
                | NistP521
                | BrainpoolP256
                | Unknown(_)
                | BrainpoolP512
                =>
            {
                // Length of one coordinate in bytes, rounded up.
                let coordinate_length = curve.field_size()?;

                // Check length of Q.
                let expected_length =
                    1 // 0x04.
                    + (2 // (x, y)
                       * coordinate_length);

                if value.len() != expected_length {
                    return Err(Error::MalformedMPI(
                        format!("Invalid length of MPI: {} (expected {})",
                                value.len(), expected_length)).into());
                }

                if value.get(0).map(|&b| b != 0x04).unwrap_or(true) {
                    return Err(Error::MalformedMPI(
                        format!("Bad prefix: {:?} (expected Some(0x04))",
                                value.get(0))).into());
                }

                Ok((&value[1..1 + coordinate_length],
                    &value[1 + coordinate_length..]))
            },
        }
    }

    /// Securely compares two MPIs in constant time.
    fn secure_memcmp(&self, other: &Self) -> Ordering {
        let cmp = unsafe {
            if self.value.len() == other.value.len() {
                ::memsec::memcmp(self.value.as_ptr(), other.value.as_ptr(),
                                 other.value.len())
            } else {
                self.value.len() as i32 - other.value.len() as i32
            }
        };

        match cmp {
            0 => Ordering::Equal,
            x if x < 0 => Ordering::Less,
            _ => Ordering::Greater,
        }
    }
}

impl fmt::Debug for MPI {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_fmt(format_args!(
            "{} bits: {}", self.bits(),
            crate::fmt::to_hex(&*self.value, true)))
    }
}

impl Hash for MPI {
    fn hash(&self, hash: &mut dyn hash::Digest) {
        let len = self.bits() as u16;

        hash.update(&len.to_be_bytes());
        hash.update(&self.value);
    }
}

#[cfg(test)]
impl Arbitrary for MPI {
    fn arbitrary(g: &mut Gen) -> Self {
        loop {
            let buf = <Vec<u8>>::arbitrary(g);

            if !buf.is_empty() && buf[0] != 0 {
                break MPI::new(&buf);
            }
        }
    }
}

impl PartialOrd for MPI {
    fn partial_cmp(&self, other: &MPI) -> Option<Ordering> {
        Some(self.secure_memcmp(other))
    }
}

impl Ord for MPI {
    fn cmp(&self, other: &MPI) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialEq for MPI {
    fn eq(&self, other: &MPI) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for MPI {}

impl std::hash::Hash for MPI {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.value.hash(state);
    }
}

/// Holds a single MPI containing secrets.
///
/// The memory will be cleared when the object is dropped.  Used by
/// [`SecretKeyMaterial`] to protect secret keys.
///
#[derive(Clone)]
pub struct ProtectedMPI {
    /// Integer value as big-endian.
    value: Protected,
}
assert_send_and_sync!(ProtectedMPI);

impl From<&[u8]> for ProtectedMPI {
    fn from(m: &[u8]) -> Self {
        let value = Protected::from(MPI::trim_leading_zeros(m));
        ProtectedMPI {
            value,
        }
    }
}

impl From<Vec<u8>> for ProtectedMPI {
    fn from(m: Vec<u8>) -> Self {
        let value = Protected::from(MPI::trim_leading_zeros(&m));
        drop(Protected::from(m)); // Erase source.
        ProtectedMPI {
            value,
        }
    }
}

impl From<Box<[u8]>> for ProtectedMPI {
    fn from(m: Box<[u8]>) -> Self {
        let value = Protected::from(MPI::trim_leading_zeros(&m));
        drop(Protected::from(m)); // Erase source.
        ProtectedMPI {
            value,
        }
    }
}

impl From<Protected> for ProtectedMPI {
    fn from(m: Protected) -> Self {
        let value = Protected::from(MPI::trim_leading_zeros(&m));
        drop(m); // Erase source.
        ProtectedMPI {
            value,
        }
    }
}

// XXX: In 2.0, get rid of this conversion.  If the value has been
// parsed into an MPI, it may have already leaked.
impl From<MPI> for ProtectedMPI {
    fn from(m: MPI) -> Self {
        ProtectedMPI {
            value: m.value.into(),
        }
    }
}

impl PartialOrd for ProtectedMPI {
    fn partial_cmp(&self, other: &ProtectedMPI) -> Option<Ordering> {
        Some(self.secure_memcmp(other))
    }
}

impl Ord for ProtectedMPI {
    fn cmp(&self, other: &ProtectedMPI) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialEq for ProtectedMPI {
    fn eq(&self, other: &ProtectedMPI) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for ProtectedMPI {}

impl std::hash::Hash for ProtectedMPI {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.value.hash(state);
    }
}

impl ProtectedMPI {
    /// Creates new MPI encoding an uncompressed EC point.
    ///
    /// Encodes the given point on a elliptic curve (see [Section 6 of
    /// RFC 6637] for details).  This is used to encode public keys
    /// and ciphertexts for the NIST curves (`NistP256`, `NistP384`,
    /// and `NistP521`).
    ///
    ///   [Section 6 of RFC 6637]: https://tools.ietf.org/html/rfc6637#section-6
    pub fn new_point(x: &[u8], y: &[u8], field_bits: usize) -> Self {
        MPI::new_point_common(x, y, field_bits).into()
    }

    /// Creates new MPI encoding a compressed EC point using native
    /// encoding.
    ///
    /// Encodes the given point on a elliptic curve (see [Section 13.2
    /// of RFC4880bis] for details).  This is used to encode public
    /// keys and ciphertexts for the Bernstein curves (currently
    /// `X25519`).
    ///
    ///   [Section 13.2 of RFC4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-13.2
    pub fn new_compressed_point(x: &[u8]) -> Self {
        MPI::new_compressed_point_common(x).into()
    }

    /// Returns the length of the MPI in bits.
    ///
    /// Leading zero-bits are not included in the returned size.
    pub fn bits(&self) -> usize {
        self.value.len() * 8
            - self.value.get(0).map(|&b| b.leading_zeros() as usize)
                  .unwrap_or(0)
    }

    /// Returns the value of this MPI.
    ///
    /// Note that due to stripping of zero-bytes, the returned value
    /// may be shorter than expected.
    pub fn value(&self) -> &[u8] {
        &self.value
    }

    /// Returns the value of this MPI zero-padded to the given length.
    ///
    /// MPI-encoding strips leading zero-bytes.  This function adds
    /// them back.  This operation is done unconditionally to avoid
    /// timing differences.  If the size exceeds `to`, the result is
    /// silently truncated to avoid timing differences.
    pub fn value_padded(&self, to: usize) -> Protected {
        let missing = to.saturating_sub(self.value.len());
        let limit = self.value.len().min(to);
        let mut v: Protected = vec![0; to].into();
        v[missing..].copy_from_slice(&self.value()[..limit]);
        v
    }

    /// Decodes an EC point encoded as MPI.
    ///
    /// Decodes the MPI into a point on an elliptic curve (see
    /// [Section 6 of RFC 6637] and [Section 13.2 of RFC4880bis] for
    /// details).  If the point is not compressed, the function
    /// returns `(x, y)`.  If it is compressed, `y` will be empty.
    ///
    ///   [Section 6 of RFC 6637]: https://tools.ietf.org/html/rfc6637#section-6
    ///   [Section 13.2 of RFC4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-13.2
    ///
    /// # Errors
    ///
    /// Returns `Error::UnsupportedEllipticCurve` if the curve is not
    /// supported, `Error::MalformedMPI` if the point is formatted
    /// incorrectly, `Error::InvalidOperation` if the given curve is
    /// operating on native octet strings.
    pub fn decode_point(&self, curve: &Curve) -> Result<(&[u8], &[u8])> {
        MPI::decode_point_common(self.value(), curve)
    }

    /// Securely compares two MPIs in constant time.
    fn secure_memcmp(&self, other: &Self) -> Ordering {
        (self.value.len() as i32).cmp(&(other.value.len() as i32))
            .then(
                // Protected compares in constant time.
                self.value.cmp(&other.value))
    }
}

impl fmt::Debug for ProtectedMPI {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if cfg!(debug_assertions) {
            f.write_fmt(format_args!(
                "{} bits: {}", self.bits(),
                crate::fmt::to_hex(&*self.value, true)))
        } else {
            f.write_str("<Redacted>")
        }
    }
}

/// A public key.
///
/// Provides a typed and structured way of storing multiple MPIs (and
/// the occasional elliptic curve) in [`Key`] packets.
///
///   [`Key`]: crate::packet::Key
///
/// Note: This enum cannot be exhaustively matched to allow future
/// extensions.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum PublicKey {
    /// RSA public key.
    RSA {
        /// Public exponent
        e: MPI,
        /// Public modulo N = pq.
        n: MPI,
    },

    /// NIST DSA public key.
    DSA {
        /// Prime of the ring Zp.
        p: MPI,
        /// Order of `g` in Zp.
        q: MPI,
        /// Public generator of Zp.
        g: MPI,
        /// Public key g^x mod p.
        y: MPI,
    },

    /// ElGamal public key.
    ElGamal {
        /// Prime of the ring Zp.
        p: MPI,
        /// Generator of Zp.
        g: MPI,
        /// Public key g^x mod p.
        y: MPI,
    },

    /// DJB's "Twisted" Edwards curve DSA public key.
    EdDSA {
        /// Curve we're using. Must be curve 25519.
        curve: Curve,
        /// Public point.
        q: MPI,
    },

    /// NIST's Elliptic Curve DSA public key.
    ECDSA {
        /// Curve we're using.
        curve: Curve,
        /// Public point.
        q: MPI,
    },

    /// Elliptic Curve Diffie-Hellman public key.
    ECDH {
        /// Curve we're using.
        curve: Curve,
        /// Public point.
        q: MPI,
        /// Algorithm used to derive the Key Encapsulation Key.
        hash: HashAlgorithm,
        /// Algorithm used to encapsulate the session key.
        sym: SymmetricAlgorithm,
    },

    /// Unknown number of MPIs for an unknown algorithm.
    Unknown {
        /// The successfully parsed MPIs.
        mpis: Box<[MPI]>,
        /// Any data that failed to parse.
        rest: Box<[u8]>,
    },
}
assert_send_and_sync!(PublicKey);

impl PublicKey {
    /// Returns the length of the public key in bits.
    ///
    /// For finite field crypto this returns the size of the field we
    /// operate in, for ECC it returns `Curve::bits()`.
    ///
    /// Note: This information is useless and should not be used to
    /// gauge the security of a particular key. This function exists
    /// only because some legacy PGP application like HKP need it.
    ///
    /// Returns `None` for unknown keys and curves.
    pub fn bits(&self) -> Option<usize> {
        use self::PublicKey::*;
        match self {
            RSA { ref n,.. } => Some(n.bits()),
            DSA { ref p,.. } => Some(p.bits()),
            ElGamal { ref p,.. } => Some(p.bits()),
            EdDSA { ref curve,.. } => curve.bits(),
            ECDSA { ref curve,.. } => curve.bits(),
            ECDH { ref curve,.. } => curve.bits(),
            Unknown { .. } => None,
        }
    }

    /// Returns, if known, the public-key algorithm for this public
    /// key.
    pub fn algo(&self) -> Option<PublicKeyAlgorithm> {
        use self::PublicKey::*;
        match self {
            RSA { .. } => Some(PublicKeyAlgorithm::RSAEncryptSign),
            DSA { .. } => Some(PublicKeyAlgorithm::DSA),
            ElGamal { .. } => Some(PublicKeyAlgorithm::ElGamalEncrypt),
            EdDSA { .. } => Some(PublicKeyAlgorithm::EdDSA),
            ECDSA { .. } => Some(PublicKeyAlgorithm::ECDSA),
            ECDH { .. } => Some(PublicKeyAlgorithm::ECDH),
            Unknown { .. } => None,
        }
    }
}

impl Hash for PublicKey {
    fn hash(&self, mut hash: &mut dyn hash::Digest) {
        self.serialize(&mut hash as &mut dyn Write)
            .expect("hashing does not fail")
    }
}

#[cfg(test)]
impl Arbitrary for PublicKey {
    fn arbitrary(g: &mut Gen) -> Self {
        use self::PublicKey::*;
        use crate::arbitrary_helper::gen_arbitrary_from_range;

        match gen_arbitrary_from_range(0..6, g) {
            0 => RSA {
                e: MPI::arbitrary(g),
                n: MPI::arbitrary(g),
            },

            1 => DSA {
                p: MPI::arbitrary(g),
                q: MPI::arbitrary(g),
                g: MPI::arbitrary(g),
                y: MPI::arbitrary(g),
            },

            2 => ElGamal {
                p: MPI::arbitrary(g),
                g: MPI::arbitrary(g),
                y: MPI::arbitrary(g),
            },

            3 => EdDSA {
                curve: Curve::arbitrary(g),
                q: MPI::arbitrary(g),
            },

            4 => ECDSA {
                curve: Curve::arbitrary(g),
                q: MPI::arbitrary(g),
            },

            5 => ECDH {
                curve: Curve::arbitrary(g),
                q: MPI::arbitrary(g),
                hash: HashAlgorithm::arbitrary(g),
                sym: SymmetricAlgorithm::arbitrary(g),
            },

            _ => unreachable!(),
        }
    }
}

/// A secret key.
///
/// Provides a typed and structured way of storing multiple MPIs in
/// [`Key`] packets.  Secret key components are protected by storing
/// them using [`ProtectedMPI`].
///
///   [`Key`]: crate::packet::Key
///
/// Note: This enum cannot be exhaustively matched to allow future
/// extensions.
// Deriving Hash here is okay: PartialEq is manually implemented to
// ensure that secrets are compared in constant-time.
#[allow(clippy::derived_hash_with_manual_eq)]
#[non_exhaustive]
#[derive(Clone, Hash)]
pub enum SecretKeyMaterial {
    /// RSA secret key.
    RSA {
        /// Secret exponent, inverse of e in Phi(N).
        d: ProtectedMPI,
        /// Smaller secret prime.
        p: ProtectedMPI,
        /// Larger secret prime.
        q: ProtectedMPI,
        /// Inverse of p mod q.
        u: ProtectedMPI,
    },

    /// NIST DSA secret key.
    DSA {
        /// Secret key log_g(y) in Zp.
        x: ProtectedMPI,
    },

    /// ElGamal secret key.
    ElGamal {
        /// Secret key log_g(y) in Zp.
        x: ProtectedMPI,
    },

    /// DJB's "Twisted" Edwards curve DSA secret key.
    EdDSA {
        /// Secret scalar.
        scalar: ProtectedMPI,
    },

    /// NIST's Elliptic Curve DSA secret key.
    ECDSA {
        /// Secret scalar.
        scalar: ProtectedMPI,
    },

    /// Elliptic Curve Diffie-Hellman secret key.
    ECDH {
        /// Secret scalar.
        scalar: ProtectedMPI,
    },

    /// Unknown number of MPIs for an unknown algorithm.
    Unknown {
        /// The successfully parsed MPIs.
        mpis: Box<[ProtectedMPI]>,
        /// Any data that failed to parse.
        rest: Protected,
    },
}
assert_send_and_sync!(SecretKeyMaterial);

impl fmt::Debug for SecretKeyMaterial {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if cfg!(debug_assertions) {
            match self {
                SecretKeyMaterial::RSA{ ref d, ref p, ref q, ref u } =>
                    write!(f, "RSA {{ d: {:?}, p: {:?}, q: {:?}, u: {:?} }}", d, p, q, u),
                SecretKeyMaterial::DSA{ ref x } =>
                    write!(f, "DSA {{ x: {:?} }}", x),
                SecretKeyMaterial::ElGamal{ ref x } =>
                    write!(f, "ElGamal {{ x: {:?} }}", x),
                SecretKeyMaterial::EdDSA{ ref scalar } =>
                    write!(f, "EdDSA {{ scalar: {:?} }}", scalar),
                SecretKeyMaterial::ECDSA{ ref scalar } =>
                    write!(f, "ECDSA {{ scalar: {:?} }}", scalar),
                SecretKeyMaterial::ECDH{ ref scalar } =>
                    write!(f, "ECDH {{ scalar: {:?} }}", scalar),
                SecretKeyMaterial::Unknown{ ref mpis, ref rest } =>
                    write!(f, "Unknown {{ mips: {:?}, rest: {:?} }}", mpis, rest),
            }
        } else {
            match self {
                SecretKeyMaterial::RSA{ .. } =>
                    f.write_str("RSA { <Redacted> }"),
                SecretKeyMaterial::DSA{ .. } =>
                    f.write_str("DSA { <Redacted> }"),
                SecretKeyMaterial::ElGamal{ .. } =>
                    f.write_str("ElGamal { <Redacted> }"),
                SecretKeyMaterial::EdDSA{ .. } =>
                    f.write_str("EdDSA { <Redacted> }"),
                SecretKeyMaterial::ECDSA{ .. } =>
                    f.write_str("ECDSA { <Redacted> }"),
                SecretKeyMaterial::ECDH{ .. } =>
                    f.write_str("ECDH { <Redacted> }"),
                SecretKeyMaterial::Unknown{ .. } =>
                    f.write_str("Unknown { <Redacted> }"),
            }
        }
    }
}

impl PartialOrd for SecretKeyMaterial {
    fn partial_cmp(&self, other: &SecretKeyMaterial) -> Option<Ordering> {
        use std::iter;

        fn discriminant(sk: &SecretKeyMaterial) -> usize {
            match sk {
                SecretKeyMaterial::RSA{ .. } => 0,
                SecretKeyMaterial::DSA{ .. } => 1,
                SecretKeyMaterial::ElGamal{ .. } => 2,
                SecretKeyMaterial::EdDSA{ .. } => 3,
                SecretKeyMaterial::ECDSA{ .. } => 4,
                SecretKeyMaterial::ECDH{ .. } => 5,
                SecretKeyMaterial::Unknown{ .. } => 6,
            }
        }

        let ret = match (self, other) {
            (&SecretKeyMaterial::RSA{ d: ref d1, p: ref p1, q: ref q1, u: ref u1 }
            ,&SecretKeyMaterial::RSA{ d: ref d2, p: ref p2, q: ref q2, u: ref u2 }) => {
                let o1 = d1.cmp(d2);
                let o2 = p1.cmp(p2);
                let o3 = q1.cmp(q2);
                let o4 = u1.cmp(u2);

                if o1 != Ordering::Equal { return Some(o1); }
                if o2 != Ordering::Equal { return Some(o2); }
                if o3 != Ordering::Equal { return Some(o3); }
                o4
            }
            (&SecretKeyMaterial::DSA{ x: ref x1 }
            ,&SecretKeyMaterial::DSA{ x: ref x2 }) => {
                x1.cmp(x2)
            }
            (&SecretKeyMaterial::ElGamal{ x: ref x1 }
            ,&SecretKeyMaterial::ElGamal{ x: ref x2 }) => {
                x1.cmp(x2)
            }
            (&SecretKeyMaterial::EdDSA{ scalar: ref scalar1 }
            ,&SecretKeyMaterial::EdDSA{ scalar: ref scalar2 }) => {
                scalar1.cmp(scalar2)
            }
            (&SecretKeyMaterial::ECDSA{ scalar: ref scalar1 }
            ,&SecretKeyMaterial::ECDSA{ scalar: ref scalar2 }) => {
                scalar1.cmp(scalar2)
            }
            (&SecretKeyMaterial::ECDH{ scalar: ref scalar1 }
            ,&SecretKeyMaterial::ECDH{ scalar: ref scalar2 }) => {
                scalar1.cmp(scalar2)
            }
            (&SecretKeyMaterial::Unknown{ mpis: ref mpis1, rest: ref rest1 }
            ,&SecretKeyMaterial::Unknown{ mpis: ref mpis2, rest: ref rest2 }) => {
                let o1 = secure_cmp(rest1, rest2);
                let on = mpis1.iter().zip(mpis2.iter()).map(|(a,b)| {
                    a.cmp(b)
                }).collect::<Vec<_>>();

                iter::once(o1)
                    .chain(on.iter().cloned())
                    .fold(Ordering::Equal, |acc, x| acc.then(x))
            }

            (a, b) => {
                let ret = discriminant(a).cmp(&discriminant(b));

                assert!(ret != Ordering::Equal);
                ret
            }
        };

        Some(ret)
    }
}

impl Ord for SecretKeyMaterial {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialEq for SecretKeyMaterial {
    fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal }
}

impl Eq for SecretKeyMaterial {}

impl SecretKeyMaterial {
    /// Returns, if known, the public-key algorithm for this secret
    /// key.
    pub fn algo(&self) -> Option<PublicKeyAlgorithm> {
        use self::SecretKeyMaterial::*;
        match self {
            RSA { .. } => Some(PublicKeyAlgorithm::RSAEncryptSign),
            DSA { .. } => Some(PublicKeyAlgorithm::DSA),
            ElGamal { .. } => Some(PublicKeyAlgorithm::ElGamalEncrypt),
            EdDSA { .. } => Some(PublicKeyAlgorithm::EdDSA),
            ECDSA { .. } => Some(PublicKeyAlgorithm::ECDSA),
            ECDH { .. } => Some(PublicKeyAlgorithm::ECDH),
            Unknown { .. } => None,
        }
    }
}

impl Hash for SecretKeyMaterial {
    fn hash(&self, mut hash: &mut dyn hash::Digest) {
        self.serialize(&mut hash as &mut dyn Write)
            .expect("hashing does not fail")
    }
}

#[cfg(test)]
impl SecretKeyMaterial {
    pub(crate) fn arbitrary_for(g: &mut Gen, pk: PublicKeyAlgorithm) -> Result<Self> {
        use self::PublicKeyAlgorithm::*;
        #[allow(deprecated)]
        match pk {
            RSAEncryptSign | RSASign | RSAEncrypt => Ok(SecretKeyMaterial::RSA {
                d: MPI::arbitrary(g).into(),
                p: MPI::arbitrary(g).into(),
                q: MPI::arbitrary(g).into(),
                u: MPI::arbitrary(g).into(),
            }),

            DSA => Ok(SecretKeyMaterial::DSA {
                x: MPI::arbitrary(g).into(),
            }),

            ElGamalEncryptSign | ElGamalEncrypt => Ok(SecretKeyMaterial::ElGamal {
                x: MPI::arbitrary(g).into(),
            }),

            EdDSA => Ok(SecretKeyMaterial::EdDSA {
                scalar: MPI::arbitrary(g).into(),
            }),

            ECDSA => Ok(SecretKeyMaterial::ECDSA {
                scalar: MPI::arbitrary(g).into(),
            }),

            ECDH => Ok(SecretKeyMaterial::ECDH {
                scalar: MPI::arbitrary(g).into(),
            }),

            Private(_) | Unknown(_) =>
                Err(Error::UnsupportedPublicKeyAlgorithm(pk).into()),
        }
    }
}
#[cfg(test)]
impl Arbitrary for SecretKeyMaterial {
    fn arbitrary(g: &mut Gen) -> Self {
        let pk = *g.choose(&crate::types::PUBLIC_KEY_ALGORITHM_VARIANTS)
            .expect("not empty");
        Self::arbitrary_for(g, pk).expect("only known variants")
    }
}

/// Checksum method for secret key material.
///
/// Secret key material may be protected by a checksum.  See [Section
/// 5.5.3 of RFC 4880] for details.
///
///   [Section 5.5.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.5.3
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum SecretKeyChecksum {
    /// SHA1 over the decrypted secret key.
    SHA1,

    /// Sum of the decrypted secret key octets modulo 65536.
    Sum16,
}
assert_send_and_sync!(SecretKeyChecksum);

impl Default for SecretKeyChecksum {
    fn default() -> Self {
        SecretKeyChecksum::SHA1
    }
}

impl SecretKeyChecksum {
    /// Returns the on-wire length of the checksum.
    pub(crate) fn len(&self) -> usize {
        match self {
            SecretKeyChecksum::SHA1 => 20,
            SecretKeyChecksum::Sum16 => 2,
        }
    }
}

/// An encrypted session key.
///
/// Provides a typed and structured way of storing multiple MPIs in
/// [`PKESK`] packets.
///
///   [`PKESK`]: crate::packet::PKESK
///
/// Note: This enum cannot be exhaustively matched to allow future
/// extensions.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum Ciphertext {
    /// RSA ciphertext.
    RSA {
        ///  m^e mod N.
        c: MPI,
    },

    /// ElGamal ciphertext.
    ElGamal {
        /// Ephemeral key.
        e: MPI,
        /// Ciphertext.
        c: MPI,
    },

    /// Elliptic curve ElGamal public key.
    ECDH {
        /// Ephemeral key.
        e: MPI,
        /// Symmetrically encrypted session key.
        key: Box<[u8]>,
    },

    /// Unknown number of MPIs for an unknown algorithm.
    Unknown {
        /// The successfully parsed MPIs.
        mpis: Box<[MPI]>,
        /// Any data that failed to parse.
        rest: Box<[u8]>,
    },
}
assert_send_and_sync!(Ciphertext);

impl Ciphertext {
    /// Returns, if known, the public-key algorithm for this
    /// ciphertext.
    pub fn pk_algo(&self) -> Option<PublicKeyAlgorithm> {
        use self::Ciphertext::*;

        // Fields are mostly MPIs that consist of two octets length
        // plus the big endian value itself. All other field types are
        // commented.
        match self {
            RSA { .. } => Some(PublicKeyAlgorithm::RSAEncryptSign),
            ElGamal { .. } => Some(PublicKeyAlgorithm::ElGamalEncrypt),
            ECDH { .. } => Some(PublicKeyAlgorithm::ECDH),
            Unknown { .. } => None,
        }
    }
}

impl Hash for Ciphertext {
    fn hash(&self, mut hash: &mut dyn hash::Digest) {
        self.serialize(&mut hash as &mut dyn Write)
            .expect("hashing does not fail")
    }
}

#[cfg(test)]
impl Arbitrary for Ciphertext {
    fn arbitrary(g: &mut Gen) -> Self {
        use crate::arbitrary_helper::gen_arbitrary_from_range;

        match gen_arbitrary_from_range(0..3, g) {
            0 => Ciphertext::RSA {
                c: MPI::arbitrary(g),
            },

            1 => Ciphertext::ElGamal {
                e: MPI::arbitrary(g),
                c: MPI::arbitrary(g)
            },

            2 => Ciphertext::ECDH {
                e: MPI::arbitrary(g),
                key: {
                    let mut k = <Vec<u8>>::arbitrary(g);
                    k.truncate(255);
                    k.into_boxed_slice()
                },
            },
            _ => unreachable!(),
        }
    }
}

/// A cryptographic signature.
///
/// Provides a typed and structured way of storing multiple MPIs in
/// [`Signature`] packets.
///
///   [`Signature`]: crate::packet::Signature
///
/// Note: This enum cannot be exhaustively matched to allow future
/// extensions.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum Signature {
    /// RSA signature.
    RSA {
        /// Signature m^d mod N.
        s: MPI,
    },

    /// NIST's DSA signature.
    DSA {
        /// `r` value.
        r: MPI,
        /// `s` value.
        s: MPI,
    },

    /// ElGamal signature.
    ElGamal {
        /// `r` value.
        r: MPI,
        /// `s` value.
        s: MPI,
    },

    /// DJB's "Twisted" Edwards curve DSA signature.
    EdDSA {
        /// `r` value.
        r: MPI,
        /// `s` value.
        s: MPI,
    },

    /// NIST's Elliptic curve DSA signature.
    ECDSA {
        /// `r` value.
        r: MPI,
        /// `s` value.
        s: MPI,
    },

    /// Unknown number of MPIs for an unknown algorithm.
    Unknown {
        /// The successfully parsed MPIs.
        mpis: Box<[MPI]>,
        /// Any data that failed to parse.
        rest: Box<[u8]>,
    },
}
assert_send_and_sync!(Signature);

impl Hash for Signature {
    fn hash(&self, mut hash: &mut dyn hash::Digest) {
        self.serialize(&mut hash as &mut dyn Write)
            .expect("hashing does not fail")
    }
}

#[cfg(test)]
impl Arbitrary for Signature {
    fn arbitrary(g: &mut Gen) -> Self {
        use crate::arbitrary_helper::gen_arbitrary_from_range;

        match gen_arbitrary_from_range(0..4, g) {
            0 => Signature::RSA  {
                s: MPI::arbitrary(g),
            },

            1 => Signature::DSA {
                r: MPI::arbitrary(g),
                s: MPI::arbitrary(g),
            },

            2 => Signature::EdDSA  {
                r: MPI::arbitrary(g),
                s: MPI::arbitrary(g),
            },

            3 => Signature::ECDSA  {
                r: MPI::arbitrary(g),
                s: MPI::arbitrary(g),
            },

            _ => unreachable!(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Parse;

    quickcheck! {
        fn mpi_roundtrip(mpi: MPI) -> bool {
            let mut buf = Vec::new();
            mpi.serialize(&mut buf).unwrap();
            MPI::from_bytes(&buf).unwrap() == mpi
        }
    }

    quickcheck! {
        fn pk_roundtrip(pk: PublicKey) -> bool {
            use std::io::Cursor;
            use crate::PublicKeyAlgorithm::*;

            let mut buf = Vec::new();
            pk.serialize(&mut buf).unwrap();
            let cur = Cursor::new(buf);

            #[allow(deprecated)]
            let pk_ = match &pk {
                PublicKey::RSA { .. } =>
                    PublicKey::parse(RSAEncryptSign, cur).unwrap(),
                PublicKey::DSA { .. } =>
                    PublicKey::parse(DSA, cur).unwrap(),
                PublicKey::ElGamal { .. } =>
                    PublicKey::parse(ElGamalEncrypt, cur).unwrap(),
                PublicKey::EdDSA { .. } =>
                    PublicKey::parse(EdDSA, cur).unwrap(),
                PublicKey::ECDSA { .. } =>
                    PublicKey::parse(ECDSA, cur).unwrap(),
                PublicKey::ECDH { .. } =>
                    PublicKey::parse(ECDH, cur).unwrap(),

                PublicKey::Unknown { .. } => unreachable!(),
            };

            pk == pk_
        }
    }

    #[test]
    fn pk_bits() {
        for (name, key_no, bits) in &[
            ("testy.pgp", 0, 2048),
            ("testy-new.pgp", 1, 256),
            ("dennis-simon-anton.pgp", 0, 2048),
            ("dsa2048-elgamal3072.pgp", 1, 3072),
            ("emmelie-dorothea-dina-samantha-awina-ed25519.pgp", 0, 256),
            ("erika-corinna-daniela-simone-antonia-nistp256.pgp", 0, 256),
            ("erika-corinna-daniela-simone-antonia-nistp384.pgp", 0, 384),
            ("erika-corinna-daniela-simone-antonia-nistp521.pgp", 0, 521),
        ] {
            let cert = crate::Cert::from_bytes(crate::tests::key(name)).unwrap();
            let ka = cert.keys().nth(*key_no).unwrap();
            assert_eq!(ka.key().mpis().bits().unwrap(), *bits,
                       "Cert {}, key no {}", name, *key_no);
        }
    }

    quickcheck! {
        fn sk_roundtrip(sk: SecretKeyMaterial) -> bool {
            use std::io::Cursor;
            use crate::PublicKeyAlgorithm::*;

            let mut buf = Vec::new();
            sk.serialize(&mut buf).unwrap();
            let cur = Cursor::new(buf);

            #[allow(deprecated)]
            let sk_ = match &sk {
                SecretKeyMaterial::RSA { .. } =>
                    SecretKeyMaterial::parse(RSAEncryptSign, cur).unwrap(),
                SecretKeyMaterial::DSA { .. } =>
                    SecretKeyMaterial::parse(DSA, cur).unwrap(),
                SecretKeyMaterial::EdDSA { .. } =>
                    SecretKeyMaterial::parse(EdDSA, cur).unwrap(),
                SecretKeyMaterial::ECDSA { .. } =>
                    SecretKeyMaterial::parse(ECDSA, cur).unwrap(),
                SecretKeyMaterial::ECDH { .. } =>
                    SecretKeyMaterial::parse(ECDH, cur).unwrap(),
                SecretKeyMaterial::ElGamal { .. } =>
                    SecretKeyMaterial::parse(ElGamalEncrypt, cur).unwrap(),

                SecretKeyMaterial::Unknown { .. } => unreachable!(),
            };

            sk == sk_
        }
    }

    quickcheck! {
        fn ct_roundtrip(ct: Ciphertext) -> bool {
            use std::io::Cursor;
            use crate::PublicKeyAlgorithm::*;

            let mut buf = Vec::new();
            ct.serialize(&mut buf).unwrap();
            let cur = Cursor::new(buf);

            #[allow(deprecated)]
            let ct_ = match &ct {
                Ciphertext::RSA { .. } =>
                    Ciphertext::parse(RSAEncryptSign, cur).unwrap(),
                Ciphertext::ElGamal { .. } =>
                    Ciphertext::parse(ElGamalEncrypt, cur).unwrap(),
                Ciphertext::ECDH { .. } =>
                    Ciphertext::parse(ECDH, cur).unwrap(),

                Ciphertext::Unknown { .. } => unreachable!(),
            };

            ct == ct_
        }
    }

    quickcheck! {
        fn signature_roundtrip(sig: Signature) -> bool {
            use std::io::Cursor;
            use crate::PublicKeyAlgorithm::*;

            let mut buf = Vec::new();
            sig.serialize(&mut buf).unwrap();
            let cur = Cursor::new(buf);

            #[allow(deprecated)]
            let sig_ = match &sig {
                Signature::RSA { .. } =>
                    Signature::parse(RSAEncryptSign, cur).unwrap(),
                Signature::DSA { .. } =>
                    Signature::parse(DSA, cur).unwrap(),
                Signature::ElGamal { .. } =>
                    Signature::parse(ElGamalEncryptSign, cur).unwrap(),
                Signature::EdDSA { .. } =>
                    Signature::parse(EdDSA, cur).unwrap(),
                Signature::ECDSA { .. } =>
                    Signature::parse(ECDSA, cur).unwrap(),

                Signature::Unknown { .. } => unreachable!(),
            };

            sig == sig_
        }
    }
}