pgp 0.19.0

OpenPGP implementation in Rust
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
use std::{
    cmp::Ordering,
    io::{BufRead, Read},
};

use bitfields::bitfield;
use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use bytes::Bytes;
use digest::DynDigest;
use log::debug;
use num_enum::{FromPrimitive, IntoPrimitive};

use crate::{
    crypto::{
        aead::AeadAlgorithm,
        hash::{HashAlgorithm, WriteHasher},
        public_key::PublicKeyAlgorithm,
        sym::SymmetricKeyAlgorithm,
    },
    errors::{bail, ensure, ensure_eq, unimplemented_err, unsupported_err, Result},
    line_writer::LineBreak,
    normalize_lines::NormalizedReader,
    packet::{
        signature::SignatureConfig, PacketHeader, PacketTrait, SignatureVersionSpecific, Subpacket,
        SubpacketData,
    },
    parsing::BufParsing,
    parsing_reader::BufReadParsing,
    ser::Serialize,
    types::{
        self, CompressionAlgorithm, Duration, Fingerprint, KeyDetails, KeyId, KeyVersion,
        PacketLength, SignatureBytes, Tag, Timestamp, VerifyingKey,
    },
};

/// Signature Packet
///
/// Ref <https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-packet-type-id-2>
///
/// OpenPGP Signatures are a very generic mechanism. They are always used by a signer to make a
/// statement about some data payload, and the [`SignatureConfig`] metadata of the signature packet.
/// The statement can be verified by anyone with access to the signer's public key, the payload
/// data, and the signature packet.
///
/// Signature packets are used in two very distinct contexts:
///
/// - As **data signatures** (either inline, in OpenPGP Messages, or as detached signatures
///   over standalone data files).
/// - As **certificate-forming signatures** (e.g. to bind a subkey to a primary key).
///
/// For data signatures, the signer's intended statement is usually either "I am the author of
/// this payload" (e.g. for an email), or "I confirm that this payload has been handled
/// appropriately" (e.g. to signal that a software package has been built by the infrastructure of
/// a Linux distribution).
///
/// For certificate-forming signatures, typical statements of signature packets are "the primary
/// key holder wants to associate this subkey with the primary", or "the key holder wants to
/// associate this identity (e.g. an email address) with their primary key".
/// Third-party signatures can be used by third parties to make statements, e.g. that they have
/// verified that an identity is validly associated with a key (such as: "I have verified that this
/// key belongs to Alice").
///
/// The purpose of a signature packet is marked by its [`SignatureType`].
#[derive(Clone, PartialEq, Eq, derive_more::Debug)]
pub struct Signature {
    packet_header: PacketHeader,
    pub(crate) inner: InnerSignature,
}

#[derive(Clone, PartialEq, Eq, derive_more::Debug)]
pub(crate) enum InnerSignature {
    /// V2, V3, V4 and V6
    Known {
        config: SignatureConfig,
        #[debug("{}", hex::encode(signed_hash_value))]
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
    },
    Unknown {
        version: SignatureVersion,
        #[debug("{}", hex::encode(data))]
        data: Bytes,
    },
}

impl Signature {
    /// Constructor for an OpenPGP v2 signature packet.
    /// Note: This is a historical packet version!
    #[allow(clippy::too_many_arguments)]
    pub fn v2(
        packet_header: PacketHeader,
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        created: Timestamp,
        issuer_key_id: KeyId,
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
    ) -> Self {
        Signature {
            packet_header,
            inner: InnerSignature::Known {
                config: SignatureConfig {
                    typ,
                    pub_alg,
                    hash_alg,
                    hashed_subpackets: vec![],
                    unhashed_subpackets: vec![],
                    version_specific: SignatureVersionSpecific::V2 {
                        created,
                        issuer_key_id,
                    },
                },
                signed_hash_value,
                signature,
            },
        }
    }

    /// Constructor for an OpenPGP v3 signature packet.
    /// Note: This is a historical packet version!
    #[allow(clippy::too_many_arguments)]
    pub fn v3(
        packet_header: PacketHeader,
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        created: Timestamp,
        issuer_key_id: KeyId,
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
    ) -> Self {
        Signature {
            packet_header,
            inner: InnerSignature::Known {
                config: SignatureConfig {
                    typ,
                    pub_alg,
                    hash_alg,
                    hashed_subpackets: vec![],
                    unhashed_subpackets: vec![],
                    version_specific: SignatureVersionSpecific::V3 {
                        created,
                        issuer_key_id,
                    },
                },
                signed_hash_value,
                signature,
            },
        }
    }

    /// Constructor for an OpenPGP v4 signature packet.
    ///
    /// OpenPGP v4 signatures are typically used with OpenPGP v4 keys, as specified in RFC 9580
    /// (and formerly in 4880 and 2440).
    #[allow(clippy::too_many_arguments)]
    pub fn v4(
        packet_header: PacketHeader,
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
        hashed_subpackets: Vec<Subpacket>,
        unhashed_subpackets: Vec<Subpacket>,
    ) -> Self {
        Signature {
            packet_header,
            inner: InnerSignature::Known {
                config: SignatureConfig {
                    typ,
                    pub_alg,
                    hash_alg,
                    hashed_subpackets,
                    unhashed_subpackets,
                    version_specific: SignatureVersionSpecific::V4,
                },
                signed_hash_value,
                signature,
            },
        }
    }

    /// Constructor for an OpenPGP v6 signature packet.
    ///
    /// OpenPGP v6 signatures are specified in RFC 9580 and only used with OpenPGP v6 keys.
    #[allow(clippy::too_many_arguments)]
    pub fn v6(
        packet_header: PacketHeader,
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
        hashed_subpackets: Vec<Subpacket>,
        unhashed_subpackets: Vec<Subpacket>,
        salt: Vec<u8>,
    ) -> Self {
        Signature {
            packet_header,
            inner: InnerSignature::Known {
                config: SignatureConfig {
                    typ,
                    pub_alg,
                    hash_alg,
                    hashed_subpackets,
                    unhashed_subpackets,
                    version_specific: SignatureVersionSpecific::V6 { salt },
                },
                signed_hash_value,
                signature,
            },
        }
    }

    /// Create a signature of unknown version
    pub fn unknown(packet_header: PacketHeader, version: SignatureVersion, data: Bytes) -> Self {
        Self {
            packet_header,
            inner: InnerSignature::Unknown { version, data },
        }
    }

    pub fn from_config(
        config: SignatureConfig,
        signed_hash_value: [u8; 2],
        signature: SignatureBytes,
    ) -> Result<Self> {
        let len = match config.version() {
            SignatureVersion::V2 | SignatureVersion::V3 => {
                let mut sum = 1;
                sum += config.write_len_v3();
                sum += 2; // signed hash value
                sum += signature.write_len();
                sum
            }
            SignatureVersion::V4 | SignatureVersion::V6 => {
                let mut sum = 1;
                sum += config.write_len_v4_v6();
                sum += 2; // signed hash value
                if let SignatureVersionSpecific::V6 { ref salt } = config.version_specific {
                    sum += 1;
                    sum += salt.len();
                }
                sum += signature.write_len();
                sum
            }
            SignatureVersion::V5 => {
                unsupported_err!("crate V5 signature")
            }
            SignatureVersion::Other(version) => unsupported_err!("signature version {}", version),
        };
        let packet_header = PacketHeader::new_fixed(Tag::Signature, len.try_into()?);

        Ok(Signature {
            packet_header,
            inner: InnerSignature::Known {
                config,
                signed_hash_value,
                signature,
            },
        })
    }

    /// Returns the `SignatureConfig` if this is a known signature format.
    pub fn config(&self) -> Option<&SignatureConfig> {
        match self.inner {
            InnerSignature::Known { ref config, .. } => Some(config),
            InnerSignature::Unknown { .. } => None,
        }
    }

    /// Appends a subpacket at the back of the unhashed area
    pub fn unhashed_subpacket_push(&mut self, subpacket: Subpacket) -> Result<()> {
        if let InnerSignature::Known { ref config, .. } = self.inner {
            self.unhashed_subpacket_insert(config.unhashed_subpackets.len(), subpacket)
        } else {
            bail!("Unknown Signature type, can't add Subpacket");
        }
    }

    /// Insert a subpacket into the unhashed area at position `index`, shifting all subpackets
    /// after it to the right
    pub fn unhashed_subpacket_insert(&mut self, index: usize, subpacket: Subpacket) -> Result<()> {
        if let InnerSignature::Known { ref mut config, .. } = self.inner {
            if let PacketLength::Fixed(packetlen) = self.packet_header.packet_length_mut() {
                ensure!(
                    // `<=`, because index may point to the entry *after* the last element
                    index <= config.unhashed_subpackets.len(),
                    "Index {} is larger than the unhashed subpacket area",
                    index
                );

                let len = u32::try_from(subpacket.write_len())?;

                config.unhashed_subpackets.insert(index, subpacket);
                *packetlen += len;
            } else {
                bail!(
                    "Unexpected PacketLength encoding {:?}, can't modify the unhashed area",
                    self.packet_header.packet_length()
                );
            }

            Ok(())
        } else {
            bail!("Unknown Signature type, can't add Subpacket");
        }
    }

    /// Removes and returns the unhashed subpacket at position `index`, shifting all other
    /// unhashed subpackets to the left
    pub fn unhashed_subpacket_remove(&mut self, index: usize) -> Result<Subpacket> {
        if let InnerSignature::Known { ref mut config, .. } = self.inner {
            ensure!(
                // `<`, because index must point at45 an existing element
                index < config.unhashed_subpackets.len(),
                "Index {} is not contained in the unhashed subpacket area",
                index
            );

            if let PacketLength::Fixed(packetlen) = self.packet_header.packet_length_mut() {
                let sp = config.unhashed_subpackets.remove(index);
                *packetlen -= u32::try_from(sp.write_len())?;
                Ok(sp)
            } else {
                bail!(
                    "Unexpected PacketLength encoding {:?}, can't modify the unhashed area",
                    self.packet_header.packet_length()
                );
            }
        } else {
            bail!("Unknown Signature type, can't remove Subpacket");
        }
    }

    /// Sorts the subpackets in the unhashed area with a comparison function,
    /// preserving initial order of equal elements.
    pub fn unhashed_subpackets_sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Subpacket, &Subpacket) -> Ordering,
    {
        if let InnerSignature::Known { ref mut config, .. } = self.inner {
            config.unhashed_subpackets.sort_by(compare);
        }
    }

    /// Returns the `SignatureVersion`.
    pub fn version(&self) -> SignatureVersion {
        match self.inner {
            InnerSignature::Known { ref config, .. } => config.version(),
            InnerSignature::Unknown { version, .. } => version,
        }
    }

    /// Returns what kind of signature this is.
    pub fn typ(&self) -> Option<SignatureType> {
        self.config().map(|c| c.typ())
    }

    /// The used `HashAlgorithm`.
    pub fn hash_alg(&self) -> Option<HashAlgorithm> {
        self.config().map(|c| c.hash_alg)
    }

    /// Returns the actual byte level signature.
    pub fn signature(&self) -> Option<&SignatureBytes> {
        match self.inner {
            InnerSignature::Known { ref signature, .. } => Some(signature),
            InnerSignature::Unknown { .. } => None,
        }
    }

    pub fn signed_hash_value(&self) -> Option<[u8; 2]> {
        match self.inner {
            InnerSignature::Known {
                signed_hash_value, ..
            } => Some(signed_hash_value),
            InnerSignature::Unknown { .. } => None,
        }
    }

    /// Does `key` match any issuer or issuer_fingerprint subpacket in `sig`?
    /// If yes, we consider `key` a candidate to verify `sig` against.
    ///
    /// We also consider `key` a match for `sig` by default, if `sig` contains no issuer-related
    /// subpackets.
    fn match_identity(sig: &Signature, key: &impl KeyDetails) -> bool {
        let issuer_key_ids = sig.issuer_key_id();
        let issuer_fps = sig.issuer_fingerprint();

        // If there is no subpacket that signals the issuer, we consider `sig` and `key` a
        // potential match, and will check the cryptographic validity.
        if issuer_key_ids.is_empty() && issuer_fps.is_empty() {
            return true;
        }

        // Does any issuer or issuer fingerprint subpacket matche the identity of `sig`?
        issuer_key_ids
            .iter()
            .any(|&key_id| key_id == &key.legacy_key_id())
            || issuer_fps.iter().any(|&fp| fp == &key.fingerprint())
    }

    /// Check alignment between signing key version and signature version.
    ///
    /// Version 6 signatures and version 6 keys are strongly linked:
    /// - only a v6 key may produce a v6 signature
    /// - a v6 key may only produce v6 signatures
    fn check_signature_key_version_alignment(
        key: &impl KeyDetails,
        config: &SignatureConfig,
    ) -> Result<()> {
        // Every signature made by a version 6 key MUST be a version 6 signature.
        if key.version() == KeyVersion::V6 {
            ensure_eq!(
                config.version(),
                SignatureVersion::V6,
                "Non v6 signature by a v6 key is not allowed"
            );
        }

        if config.version() == SignatureVersion::V6 {
            ensure_eq!(
                key.version(),
                KeyVersion::V6,
                "v6 signature by a non-v6 key is not allowed"
            );
        }

        Ok(())
    }

    /// Check if the hash algorithm is acceptable for the signature configuration
    /// (in particular, if it's allowed in combination with the public key algorithm).
    pub(crate) fn check_signature_hash_strength(config: &SignatureConfig) -> Result<()> {
        if config.pub_alg.is_pqc() {
            // For all signature algorithms in draft-ietf-openpgp-pqc-10,
            // hash digest sizes of at least 256 bits are required:
            //
            // https://www.ietf.org/archive/id/draft-ietf-openpgp-pqc-10.html#name-signature-packet-tag-2
            // https://www.ietf.org/archive/id/draft-ietf-openpgp-pqc-10.html#name-signature-packet-tag-2-2

            let Some(digest_size) = config.hash_alg.digest_size() else {
                bail!("Illegal hash_alg setting {}", config.hash_alg);
            };

            ensure!(
                digest_size * 8 >= 256,
                "PQC signatures must use hash algorithms with digest size >= 256 bits, {} is insufficient",
                config.hash_alg
            );
        }

        Ok(())
    }

    /// Verify this signature.
    pub fn verify<R>(&self, key: &impl VerifyingKey, data: R) -> Result<()>
    where
        R: Read,
    {
        let InnerSignature::Known {
            ref config,
            ref signed_hash_value,
            ref signature,
        } = self.inner
        else {
            unsupported_err!("signature version {:?}", self.version());
        };

        Self::check_signature_key_version_alignment(&key, config)?;
        Self::check_signature_hash_strength(config)?;

        ensure!(
            Self::match_identity(self, key),
            "verify: No matching issuer_key_id or issuer_fingerprint for Key ID: {:?}",
            &key.legacy_key_id(),
        );

        let mut hasher = config.hash_alg.new_hasher()?;

        if let SignatureVersionSpecific::V6 { salt } = &config.version_specific {
            // Salt size must match the expected length for the hash algorithm that is used
            //
            // See: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3-2.10.2.1.1
            ensure_eq!(
                config.hash_alg.salt_len(),
                Some(salt.len()),
                "Illegal salt length {} for a V6 Signature using {:?}",
                salt.len(),
                config.hash_alg
            );

            hasher.update(salt.as_ref())
        }

        if matches!(self.typ(), Some(SignatureType::Text)) {
            let normalized = NormalizedReader::new(data, LineBreak::Crlf);

            config.hash_data_to_sign(&mut hasher, normalized)?;
        } else {
            config.hash_data_to_sign(&mut hasher, data)?;
        }
        let len = config.hash_signature_data(&mut hasher)?;
        hasher.update(&config.trailer(len)?);

        let hash = &hasher.finalize()[..];

        // Check that the high 16 bits of the hash from the signature packet match with the hash we
        // just calculated.
        //
        // "When verifying a version 6 signature, an implementation MUST reject the signature if
        // these octets do not match the first two octets of the computed hash."
        //
        // (See https://www.rfc-editor.org/rfc/rfc9580.html#name-notes-on-signatures)
        //
        // (Note: we currently also reject v4 signatures if the calculated hash doesn't match the
        // high 16 bits in the signature packet, even though RFC 9580 doesn't strictly require this)
        ensure_eq!(
            signed_hash_value,
            &hash[0..2],
            "signature: invalid signed hash value"
        );

        key.verify(config.hash_alg, hash, signature)
    }

    /// Verifies a certification signature type (for self-signatures).
    pub fn verify_certification<V>(&self, key: &V, tag: Tag, id: &impl Serialize) -> Result<()>
    where
        V: VerifyingKey + Serialize,
    {
        self.verify_third_party_certification(&key, &key, tag, id)
    }

    /// Verifies a certification signature type (for third-party signatures).
    pub fn verify_third_party_certification<V, K>(
        &self,
        signee: &K,
        signer: &V,
        tag: Tag,
        id: &impl Serialize,
    ) -> Result<()>
    where
        V: VerifyingKey + Serialize,
        K: KeyDetails + Serialize,
    {
        let InnerSignature::Known {
            ref config,
            ref signed_hash_value,
            ref signature,
        } = self.inner
        else {
            unsupported_err!("signature version {:?}", self.version());
        };
        let key_id = signee.legacy_key_id();
        debug!("verifying certification {key_id:?} {self:#?}");

        Self::check_signature_key_version_alignment(&signer, config)?;
        Self::check_signature_hash_strength(config)?;

        ensure!(
            Self::match_identity(self, signer),
            "verify_certification: No matching issuer_key_id or issuer_fingerprint for Key ID: {:?}",
            key_id,
        );

        let mut hasher = config.hash_alg.new_hasher()?;

        if let SignatureVersionSpecific::V6 { salt } = &config.version_specific {
            hasher.update(salt.as_ref())
        }

        // the key of the signee
        {
            // TODO: this is different for V5
            serialize_for_hashing(signee, &mut hasher)?;
        }

        // the packet content
        {
            let packet_len = id.write_len();

            match config.version() {
                SignatureVersion::V2 | SignatureVersion::V3 => {
                    // Nothing to do
                }
                SignatureVersion::V4 | SignatureVersion::V6 => {
                    let prefix = match tag {
                        Tag::UserId => 0xB4,
                        Tag::UserAttribute => 0xD1,
                        _ => bail!("invalid tag for certification validation: {:?}", tag),
                    };

                    let mut prefix_buf = [prefix, 0u8, 0u8, 0u8, 0u8];
                    BigEndian::write_u32(&mut prefix_buf[1..], packet_len.try_into()?);

                    // prefixes
                    hasher.update(&prefix_buf);
                }
                SignatureVersion::V5 => {
                    bail!("v5 signature unsupported tpc")
                }
                SignatureVersion::Other(version) => {
                    bail!("unsupported signature version: {:?}", version)
                }
            }

            id.to_writer(&mut WriteHasher(&mut hasher))?;
        }

        let len = config.hash_signature_data(&mut hasher)?;
        hasher.update(&config.trailer(len)?);

        let hash = &hasher.finalize()[..];
        ensure_eq!(
            signed_hash_value,
            &hash[0..2],
            "certification: invalid signed hash value"
        );

        signer.verify(config.hash_alg, hash, signature)
    }

    /// Verifies a subkey binding (which binds a subkey to the primary key).
    ///
    /// The primary key is expected as `signer`, the subkey as `signee`.
    ///
    /// "Subkey Binding Signature (type ID 0x18)"
    pub fn verify_subkey_binding<V, K>(&self, signer: &V, signee: &K) -> Result<()>
    where
        V: VerifyingKey + Serialize,
        K: KeyDetails + Serialize,
    {
        debug!("verifying subkey binding: {self:#?} - {signer:#?} - {signee:#?}",);

        let InnerSignature::Known {
            ref config,
            ref signed_hash_value,
            ref signature,
        } = self.inner
        else {
            unsupported_err!("signature version {:?}", self.version());
        };

        Self::check_signature_key_version_alignment(&signer, config)?;
        Self::check_signature_hash_strength(config)?;

        let mut hasher = config.hash_alg.new_hasher()?;

        if let SignatureVersionSpecific::V6 { salt } = &config.version_specific {
            hasher.update(salt.as_ref())
        }

        serialize_for_hashing(signer, &mut hasher)?; // primary
        serialize_for_hashing(signee, &mut hasher)?; // subkey

        let len = config.hash_signature_data(&mut hasher)?;
        hasher.update(&config.trailer(len)?);

        let hash = &hasher.finalize()[..];
        ensure_eq!(
            signed_hash_value,
            &hash[0..2],
            "subkey binding: invalid signed hash value"
        );

        signer.verify(config.hash_alg, hash, signature)
    }

    /// Verifies a primary key binding signature, or "back signature" (which links the primary to a signing subkey).
    ///
    /// The subkey is expected as `signer`, the primary key as `signee`.
    ///
    /// "Primary Key Binding Signature (type ID 0x19)"
    pub fn verify_primary_key_binding<V, K>(&self, signer: &V, signee: &K) -> Result<()>
    where
        V: VerifyingKey + Serialize,
        K: KeyDetails + Serialize,
    {
        debug!("verifying primary key binding: {self:#?} - {signer:#?} - {signee:#?}");

        let InnerSignature::Known {
            ref config,
            ref signed_hash_value,
            ref signature,
        } = self.inner
        else {
            unsupported_err!("signature version {:?}", self.version());
        };

        Self::check_signature_key_version_alignment(&signer, config)?;
        Self::check_signature_hash_strength(config)?;

        let mut hasher = config.hash_alg.new_hasher()?;

        if let SignatureVersionSpecific::V6 { salt } = &config.version_specific {
            hasher.update(salt.as_ref())
        }

        serialize_for_hashing(signee, &mut hasher)?; // primary
        serialize_for_hashing(signer, &mut hasher)?; // subkey

        let len = config.hash_signature_data(&mut hasher)?;
        hasher.update(&config.trailer(len)?);

        let hash = &hasher.finalize()[..];
        ensure_eq!(
            signed_hash_value,
            &hash[0..2],
            "key binding: invalid signed hash value"
        );

        signer.verify(config.hash_alg, hash, signature)
    }

    /// Verifies a direct key signature or a revocation.
    pub fn verify_key<V>(&self, key: &V) -> Result<()>
    where
        V: VerifyingKey + Serialize,
    {
        self.verify_key_third_party(key, key)
    }

    /// Verifies a third-party direct key signature or a revocation.
    pub fn verify_key_third_party<V, K>(&self, signee: &K, signer: &V) -> Result<()>
    where
        V: VerifyingKey + Serialize,
        K: KeyDetails + Serialize,
    {
        debug!("verifying direct signature: {self:#?} - signer {signer:#?}, signee {signee:#?}");

        let InnerSignature::Known {
            ref config,
            ref signed_hash_value,
            ref signature,
        } = self.inner
        else {
            unsupported_err!("signature version {:?}", self.version());
        };
        Self::check_signature_key_version_alignment(&signer, config)?;
        Self::check_signature_hash_strength(config)?;

        ensure!(
            Self::match_identity(self, signer),
            "verify_key: No matching issuer_key_id or issuer_fingerprint for Key ID: {:?}",
            &signer.legacy_key_id(),
        );

        let mut hasher = config.hash_alg.new_hasher()?;

        if let SignatureVersionSpecific::V6 { salt } = &config.version_specific {
            hasher.update(salt.as_ref())
        }

        serialize_for_hashing(signee, &mut hasher)?;

        let len = config.hash_signature_data(&mut hasher)?;
        hasher.update(&config.trailer(len)?);

        let hash = &hasher.finalize()[..];
        ensure_eq!(
            signed_hash_value,
            &hash[0..2],
            "key: invalid signed hash value"
        );

        signer.verify(config.hash_alg, hash, signature)
    }

    /// Returns if the signature is a certification or not.
    pub fn is_certification(&self) -> bool {
        self.config()
            .map(|c| c.is_certification())
            .unwrap_or_default()
    }

    /// If the hashed area contains any KeyExpirationTime subpacket, then this
    /// returns `Some(Duration)` of the first KeyExpirationTime subpacket encountered.
    ///
    /// If the hashed area contains no KeyExpirationTime subpacket, this returns `None`.
    ///
    /// (Note that a return value of `Some(Duration(0))` also means that no key expiration time
    /// applies to the target component. This corresponds to a different wire-format
    /// representation, but is semantically equivalent to `None`.)
    pub fn key_expiration_time(&self) -> Option<Duration> {
        self.config().and_then(|h| {
            h.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::KeyExpirationTime(d) => Some(*d),
                _ => None,
            })
        })
    }

    pub fn signature_expiration_time(&self) -> Option<Duration> {
        self.config().and_then(|h| {
            h.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::SignatureExpirationTime(d) => Some(*d),
                _ => None,
            })
        })
    }

    pub fn created(&self) -> Option<Timestamp> {
        self.config().and_then(|c| c.created())
    }

    pub fn issuer_key_id(&self) -> Vec<&KeyId> {
        self.config().map(|c| c.issuer_key_id()).unwrap_or_default()
    }

    pub fn issuer_fingerprint(&self) -> Vec<&Fingerprint> {
        self.config()
            .map(|c| c.issuer_fingerprint())
            .unwrap_or_default()
    }

    pub fn preferred_symmetric_algs(&self) -> &[SymmetricKeyAlgorithm] {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::PreferredSymmetricAlgorithms(d) => Some(&d[..]),
                    _ => None,
                })
            })
            .unwrap_or_else(|| &[][..])
    }

    pub fn preferred_aead_algs(&self) -> &[(SymmetricKeyAlgorithm, AeadAlgorithm)] {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::PreferredAeadAlgorithms(d) => Some(&d[..]),
                    _ => None,
                })
            })
            .unwrap_or_else(|| &[][..])
    }

    pub fn preferred_hash_algs(&self) -> &[HashAlgorithm] {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::PreferredHashAlgorithms(d) => Some(&d[..]),
                    _ => None,
                })
            })
            .unwrap_or_else(|| &[][..])
    }

    pub fn preferred_compression_algs(&self) -> &[CompressionAlgorithm] {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::PreferredCompressionAlgorithms(d) => Some(&d[..]),
                    _ => None,
                })
            })
            .unwrap_or_else(|| &[][..])
    }

    pub fn key_server_prefs(&self) -> &[u8] {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::KeyServerPreferences(d) => Some(&d[..]),
                    _ => None,
                })
            })
            .unwrap_or_else(|| &[][..])
    }

    pub fn key_flags(&self) -> KeyFlags {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::KeyFlags(flags) => Some(flags.clone()),
                    _ => None,
                })
            })
            .unwrap_or_default()
    }

    pub fn features(&self) -> Option<&Features> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::Features(feat) => Some(feat),
                _ => None,
            })
        })
    }

    pub fn revocation_reason_code(&self) -> Option<&RevocationCode> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::RevocationReason(code, _) => Some(code),
                _ => None,
            })
        })
    }

    pub fn revocation_reason_string(&self) -> Option<&Bytes> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::RevocationReason(_, reason) => Some(reason),
                _ => None,
            })
        })
    }

    pub fn is_primary(&self) -> bool {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::IsPrimary(d) => Some(*d),
                    _ => None,
                })
            })
            .unwrap_or(false)
    }

    pub fn is_revocable(&self) -> bool {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::Revocable(d) => Some(*d),
                    _ => None,
                })
            })
            .unwrap_or(true)
    }

    pub fn embedded_signature(&self) -> Option<&Signature> {
        // We consider data from both the hashed and unhashed area here, because the embedded
        // signature is inherently cryptographically secured. An attacker can't add a valid
        // embedded signature, canonicalization will remove any invalid embedded signature
        // subpackets.
        if let Some(sub) = self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::EmbeddedSignature(d) => Some(&**d),
                _ => None,
            })
        }) {
            return Some(sub);
        }
        if let Some(sub) = self.config().and_then(|c| {
            c.unhashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::EmbeddedSignature(d) => Some(&**d),
                _ => None,
            })
        }) {
            return Some(sub);
        }

        None
    }

    pub fn preferred_key_server(&self) -> Option<&str> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::PreferredKeyServer(d) => Some(d.as_str()),
                _ => None,
            })
        })
    }

    pub fn notations(&self) -> Vec<&Notation> {
        self.config()
            .map(|c| {
                c.hashed_subpackets()
                    .filter_map(|p| match &p.data {
                        SubpacketData::Notation(d) => Some(d),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default()
    }

    pub fn revocation_key(&self) -> Option<&types::RevocationKey> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::RevocationKey(d) => Some(d),
                _ => None,
            })
        })
    }

    /// Gets the user id of the signer
    ///
    /// Note that the user id may not be valid utf-8, if it was created
    /// using a different encoding. But since the RFC describes every
    /// text as utf-8 it is up to the caller whether to error on non utf-8 data.
    pub fn signers_userid(&self) -> Option<&Bytes> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::SignersUserID(d) => Some(d),
                _ => None,
            })
        })
    }

    pub fn policy_uri(&self) -> Option<&str> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::PolicyURI(d) => Some(d.as_ref()),
                _ => None,
            })
        })
    }

    pub fn trust_signature(&self) -> Option<(u8, u8)> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::TrustSignature(depth, value) => Some((*depth, *value)),
                _ => None,
            })
        })
    }

    pub fn regular_expression(&self) -> Option<&Bytes> {
        self.config().and_then(|c| {
            c.hashed_subpackets().find_map(|p| match &p.data {
                SubpacketData::RegularExpression(d) => Some(d),
                _ => None,
            })
        })
    }

    pub fn exportable_certification(&self) -> bool {
        self.config()
            .and_then(|c| {
                c.hashed_subpackets().find_map(|p| match &p.data {
                    SubpacketData::ExportableCertification(d) => Some(*d),
                    _ => None,
                })
            })
            .unwrap_or(true)
    }
}

/// The version of a [`Signature`] packet
#[derive(derive_more::Debug, PartialEq, Eq, Clone, Copy, FromPrimitive, IntoPrimitive)]
#[repr(u8)]
pub enum SignatureVersion {
    /// Deprecated
    V2 = 2,
    V3 = 3,
    V4 = 4,
    V5 = 5,
    V6 = 6,

    #[num_enum(catch_all)]
    Other(#[debug("0x{:x}", _0)] u8),
}

#[allow(clippy::derivable_impls)]
impl Default for SignatureVersion {
    fn default() -> Self {
        Self::V4
    }
}

/// A signature type defines the meaning of an OpenPGP [`Signature`].
///
/// The signature type is part of the [`SignatureConfig`] metadata.
///
/// OpenPGP signatures over data use either [`SignatureType::Binary`] or [`SignatureType::Text`].
///
/// Most other signature types are used to form certificates (aka OpenPGP public keys), e.g.
/// to associate subkeys with a primary key, bind identities to a certificate, and specify
/// various certificate metadata such as expiration/revocation status, and algorithm preferences.
///
/// See <https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-types>
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive, IntoPrimitive)]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
#[repr(u8)]
pub enum SignatureType {
    /// Signature of a binary document.
    /// This means the signer owns it, created it, or certifies that it has not been modified.
    Binary = 0x00,
    /// Signature of a canonical text document.
    /// This means the signer owns it, created it, or certifies that it
    /// has not been modified.  The signature is calculated over the text
    /// data with its line endings converted to `<CR><LF>`.
    Text = 0x01,
    /// Standalone signature.
    /// This signature is a signature of only its own subpacket contents.
    /// It is calculated identically to a signature over a zero-length
    /// binary document.  Note that it doesn't make sense to have a V3 standalone signature.
    Standalone = 0x02,
    /// Generic certification of a User ID and Public-Key packet.
    /// The issuer of this certification does not make any particular
    /// assertion as to how well the certifier has checked that the owner
    /// of the key is in fact the person described by the User ID.
    CertGeneric = 0x10,
    /// Persona certification of a User ID and Public-Key packet.
    /// The issuer of this certification has not done any verification of
    /// the claim that the owner of this key is the User ID specified.
    CertPersona = 0x11,
    /// Casual certification of a User ID and Public-Key packet.
    /// The issuer of this certification has done some casual
    /// verification of the claim of identity.
    CertCasual = 0x12,
    /// Positive certification of a User ID and Public-Key packet.
    /// The issuer of this certification has done substantial
    /// verification of the claim of identity.
    ///
    /// Most OpenPGP implementations make their "key signatures" as 0x10
    /// certifications.  Some implementations can issue 0x11-0x13
    /// certifications, but few differentiate between the types.
    CertPositive = 0x13,
    /// Subkey Binding Signature
    /// This signature is a statement by the top-level signing key that
    /// indicates that it owns the subkey.  This signature is calculated
    /// directly on the primary key and subkey, and not on any User ID or
    /// other packets.  A signature that binds a signing subkey MUST have
    /// an Embedded Signature subpacket in this binding signature that
    /// contains a 0x19 signature made by the signing subkey on the
    /// primary key and subkey.
    SubkeyBinding = 0x18,
    /// Primary Key Binding Signature
    /// This signature is a statement by a signing subkey, indicating
    /// that it is owned by the primary key and subkey.  This signature
    /// is calculated the same way as a 0x18 signature: directly on the
    /// primary key and subkey, and not on any User ID or other packets.
    KeyBinding = 0x19,
    /// Signature directly on a key
    /// This signature is calculated directly on a key.  It binds the
    /// information in the Signature subpackets to the key, and is
    /// appropriate to be used for subpackets that provide information
    /// about the key, such as the Revocation Key subpacket.  It is also
    /// appropriate for statements that non-self certifiers want to make
    /// about the key itself, rather than the binding between a key and a name.
    Key = 0x1F,
    /// Key revocation signature
    /// The signature is calculated directly on the key being revoked.  A
    /// revoked key is not to be used.  Only revocation signatures by the
    /// key being revoked, or by an authorized revocation key, should be
    /// considered valid revocation signatures.
    KeyRevocation = 0x20,
    /// Subkey revocation signature
    /// The signature is calculated directly on the subkey being revoked.
    /// A revoked subkey is not to be used.  Only revocation signatures
    /// by the top-level signature key that is bound to this subkey, or
    /// by an authorized revocation key, should be considered valid
    /// revocation signatures.
    SubkeyRevocation = 0x28,
    /// Certification revocation signature
    /// This signature revokes an earlier User ID certification signature
    /// (signature class 0x10 through 0x13) or direct-key signature
    /// (0x1F).  It should be issued by the same key that issued the
    /// revoked signature or an authorized revocation key.  The signature
    /// is computed over the same data as the certificate that it
    /// revokes, and should have a later creation date than that
    /// certificate.
    CertRevocation = 0x30,
    /// Timestamp signature.
    /// This signature is only meaningful for the timestamp contained in
    /// it.
    Timestamp = 0x40,
    /// Third-Party Confirmation signature.
    /// This signature is a signature over some other OpenPGP Signature
    /// packet(s).  It is analogous to a notary seal on the signed data.
    /// A third-party signature SHOULD include Signature Target
    /// subpacket(s) to give easy identification.  Note that we really do
    /// mean SHOULD.  There are plausible uses for this (such as a blind
    /// party that only sees the signature, not the key or source
    /// document) that cannot include a target subpacket.
    ThirdParty = 0x50,

    #[num_enum(catch_all)]
    Other(#[cfg_attr(test, proptest(strategy = "0x51u8.."))] u8),
}

pub const CERTIFICATION_SIGNATURE_TYPES: &[SignatureType] = &[
    SignatureType::CertPositive,
    SignatureType::CertGeneric,
    SignatureType::CertCasual,
    SignatureType::CertPersona,
];

/// Key Flags signature subpacket
///
/// A key flag is a semantical annotation to specify which OpenPGP operations a component key
/// is intended for.
///
/// Key flags usually consist of only 1 byte, but the specification allows extension of the field,
/// making it potentially arbitrarily long.
/// Fields that are currently reserved in the specification can make Key Flags up to 2 bytes long.
///
/// Ref <https://www.rfc-editor.org/rfc/rfc9580.html#name-key-flags>
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct KeyFlags {
    /// Handles the first two bytes.
    known: KnownKeyFlags,
    /// Any additional key flag bytes.
    rest: Option<Bytes>,
    /// Need to store this, to fully roundtrip..
    original_len: usize,
}

impl Default for KeyFlags {
    fn default() -> Self {
        Self {
            known: KnownKeyFlags::default(),
            rest: None,
            original_len: 1,
        }
    }
}

impl KeyFlags {
    /// Parse the key flags from the given buffer.
    pub fn try_from_reader<B: BufRead>(mut reader: B) -> Result<Self> {
        let mut buf = reader.rest()?.freeze();
        let remaining = buf.len();

        if remaining == 0 {
            return Ok(Self {
                known: KnownKeyFlags::default(),
                rest: None,
                original_len: remaining,
            });
        }
        if remaining == 1 {
            let known = KnownKeyFlags::from_bits(buf.read_u8()? as u16);
            return Ok(Self {
                known,
                rest: None,
                original_len: remaining,
            });
        }
        if remaining == 2 {
            let known = KnownKeyFlags::from_bits(buf.read_le_u16()?);
            return Ok(Self {
                known,
                rest: None,
                original_len: remaining,
            });
        }
        let known = KnownKeyFlags::from_bits(buf.read_le_u16()?);
        let rest = Some(buf.rest());
        Ok(Self {
            known,
            rest,
            original_len: remaining,
        })
    }

    pub fn set_certify(&mut self, val: bool) {
        self.known.set_certify(val);
    }
    pub fn set_encrypt_comms(&mut self, val: bool) {
        self.known.set_encrypt_comms(val);
    }
    pub fn set_encrypt_storage(&mut self, val: bool) {
        self.known.set_encrypt_storage(val);
    }
    pub fn set_sign(&mut self, val: bool) {
        self.known.set_sign(val);
    }
    pub fn set_shared(&mut self, val: bool) {
        self.known.set_shared(val);
    }
    pub fn set_authentication(&mut self, val: bool) {
        self.known.set_authentication(val);
    }
    pub fn set_group(&mut self, val: bool) {
        self.known.set_group(val);
    }

    pub fn set_adsk(&mut self, val: bool) {
        self.known.set_adsk(val);
    }

    pub fn set_timestamping(&mut self, val: bool) {
        self.known.set_timestamping(val);
    }

    pub fn certify(&self) -> bool {
        self.known.certify()
    }

    pub fn encrypt_comms(&self) -> bool {
        self.known.encrypt_comms()
    }

    pub fn encrypt_storage(&self) -> bool {
        self.known.encrypt_storage()
    }

    pub fn sign(&self) -> bool {
        self.known.sign()
    }

    pub fn shared(&self) -> bool {
        self.known.shared()
    }

    pub fn authentication(&self) -> bool {
        self.known.authentication()
    }

    /// Draft key flag: "This key may be used for forwarded communication"
    ///
    /// Ref <https://datatracker.ietf.org/doc/html/draft-wussler-openpgp-forwarding#name-key-flag-0x40>
    pub fn draft_decrypt_forwarded(&self) -> bool {
        self.known.draft_decrypt_forwarded()
    }

    pub fn group(&self) -> bool {
        self.known.group()
    }

    pub fn adsk(&self) -> bool {
        self.known.adsk()
    }

    pub fn timestamping(&self) -> bool {
        self.known.timestamping()
    }
}

impl Serialize for KeyFlags {
    fn to_writer<W: std::io::Write>(&self, writer: &mut W) -> Result<()> {
        if self.original_len == 0 {
            return Ok(());
        }

        let [a, b] = self.known.into_bits().to_le_bytes();
        writer.write_u8(a)?;

        if self.original_len > 1 || b != 0 {
            writer.write_u8(b)?;
        }

        if let Some(ref rest) = self.rest {
            writer.write_all(rest)?;
        }
        Ok(())
    }

    fn write_len(&self) -> usize {
        if self.original_len == 0 {
            return 0;
        }
        let mut sum = 0;
        let [_, b] = self.known.into_bits().to_le_bytes();
        if self.original_len > 1 || b > 0 {
            sum += 2;
        } else {
            sum += 1;
        }

        if let Some(ref rest) = self.rest {
            sum += rest.len();
        }
        sum
    }
}

/// Encodes the known fields of a [`KeyFlags`].
///
/// Ref <https://www.rfc-editor.org/rfc/rfc9580.html#name-key-flags>
#[bitfield(u16, order = lsb)]
#[derive(PartialEq, Eq, Copy, Clone)]
pub struct KnownKeyFlags {
    #[bits(1)]
    certify: bool,
    #[bits(1)]
    sign: bool,
    #[bits(1)]
    encrypt_comms: bool,
    #[bits(1)]
    encrypt_storage: bool,
    #[bits(1)]
    shared: bool,
    #[bits(1)]
    authentication: bool,
    #[bits(1)]
    draft_decrypt_forwarded: bool,
    #[bits(1)]
    group: bool,
    #[bits(2)]
    _padding1: u8,
    #[bits(1)]
    adsk: bool,
    #[bits(1)]
    timestamping: bool,
    #[bits(4)]
    _padding2: u8,
}

/// Features signature subpacket.
///
/// The Features subpacket denotes which advanced OpenPGP features a user's implementation
/// supports, mainly as a signal to communication peers.
///
/// Features are encoded as "N octets of flags", but currently typically use 1 byte.
/// (Only the first 4 bits have been specified so far)
///
/// Ref <https://www.rfc-editor.org/rfc/rfc9580.html#name-features>
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Features {
    /// Handles the first byte.
    /// Can be None to encode Features subpackets that are 0 byte long.
    first: Option<KnownFeatures>,

    /// Any additional features bytes.
    /// (Must be empty if "known" is None.)
    rest: Vec<u8>,
}

impl Default for Features {
    fn default() -> Self {
        Self {
            first: Some(KnownFeatures::default()),
            rest: vec![],
        }
    }
}

impl From<&[u8]> for Features {
    fn from(value: &[u8]) -> Self {
        match value.len() {
            0 => Self {
                first: None,
                rest: vec![],
            },
            _ => Self {
                first: Some(KnownFeatures(value[0])),
                rest: value[1..].to_vec(),
            },
        }
    }
}

impl From<&Features> for Vec<u8> {
    fn from(value: &Features) -> Self {
        let mut v = vec![];
        value.to_writer(&mut v).expect("vec");
        v
    }
}

impl From<KnownFeatures> for Features {
    fn from(value: KnownFeatures) -> Self {
        Self {
            first: Some(value),
            rest: vec![],
        }
    }
}

impl Features {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn seipd_v1(&self) -> bool {
        match self.first {
            Some(k) => k.seipd_v1(),
            None => false,
        }
    }

    pub fn set_seipd_v1(&mut self, val: bool) {
        if self.first.is_none() {
            self.first = Some(KnownFeatures::default());
        }

        // Should always be Some!
        if let Some(k) = self.first.as_mut() {
            k.set_seipd_v1(val);
        }
    }

    pub fn seipd_v2(&self) -> bool {
        match self.first {
            Some(k) => k.seipd_v2(),
            None => false,
        }
    }

    pub fn set_seipd_v2(&mut self, val: bool) {
        if self.first.is_none() {
            self.first = Some(KnownFeatures::default());
        }

        // Should always be Some!
        if let Some(k) = self.first.as_mut() {
            k.set_seipd_v2(val);
        }
    }
}

impl Serialize for Features {
    fn to_writer<W: std::io::Write>(&self, writer: &mut W) -> Result<()> {
        if let Some(k) = self.first {
            writer.write_u8(k.0)?;
            writer.write_all(&self.rest)?;
        }

        Ok(())
    }

    fn write_len(&self) -> usize {
        if self.first.is_none() {
            0
        } else {
            1 + self.rest.len()
        }
    }
}

/// Encodes the first byte of a [`Features`].
///
/// Ref <https://www.rfc-editor.org/rfc/rfc9580.html#name-features>
#[bitfield(u8)]
#[derive(PartialEq, Eq, Copy, Clone)]
pub struct KnownFeatures {
    /// Support for "Version 1 Symmetrically Encrypted and Integrity Protected Data packet"
    #[bits(1)]
    seipd_v1: bool,

    /// Not standardized in OpenPGP, but used in the LibrePGP fork.
    /// Signals support for GnuPG-specific "OCB" encryption packet format.
    #[bits(1)]
    _libre_ocb: u8,

    /// Not standardized in OpenPGP, but used in the LibrePGP fork.
    /// Semantics unclear.
    #[bits(1)]
    _libre_v5_keys: u8,

    /// Support for "Version 2 Symmetrically Encrypted and Integrity Protected Data packet"
    #[bits(1)]
    seipd_v2: bool,

    #[bits(4)]
    _padding: u8,
}

/// Notation Data signature subpacket
///
/// Used as the payload of a [`SubpacketData::Notation`].
///
/// This subpacket describes a "notation" on the signature that the issuer wishes to make.
/// The notation has a name and a value, each of which are strings of octets.
/// There may be more than one notation in a signature.
/// Notations can be used for any extension the issuer of the signature cares to make.
///
/// See <https://www.rfc-editor.org/rfc/rfc9580.html#name-notation-data>
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Notation {
    pub readable: bool,
    pub name: Bytes,
    pub value: Bytes,
}

/// Value of a [`SubpacketData::RevocationReason`] signature subpacket
///
/// See <https://www.rfc-editor.org/rfc/rfc9580.html#name-reason-for-revocation>
#[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive, IntoPrimitive)]
#[repr(u8)]
pub enum RevocationCode {
    /// No reason specified (key revocations or cert revocations)
    NoReason = 0,
    /// Key is superseded (key revocations)
    KeySuperseded = 1,
    /// Key material has been compromised (key revocations)
    KeyCompromised = 2,
    /// Key is retired and no longer used (key revocations)
    KeyRetired = 3,
    /// User ID information is no longer valid (cert revocations)
    CertUserIdInvalid = 32,

    /// Private Use range (from OpenPGP)
    Private100 = 100,
    Private101 = 101,
    Private102 = 102,
    Private103 = 103,
    Private104 = 104,
    Private105 = 105,
    Private106 = 106,
    Private107 = 107,
    Private108 = 108,
    Private109 = 109,
    Private110 = 110,

    /// Undefined code
    #[num_enum(catch_all)]
    Other(u8),
}

impl PacketTrait for Signature {
    fn packet_header(&self) -> &PacketHeader {
        &self.packet_header
    }
}

pub(super) fn serialize_for_hashing<K: KeyDetails + Serialize>(
    key: &K,
    hasher: &mut Box<dyn DynDigest + Send>,
) -> Result<()> {
    let key_len = key.write_len();

    let mut writer = WriteHasher(hasher);

    // old style packet header for the key
    match key.version() {
        KeyVersion::V2 | KeyVersion::V3 | KeyVersion::V4 => {
            // When a v4 signature is made over a key, the hash data starts with the octet 0x99,
            // followed by a two-octet length of the key, and then the body of the key packet.
            writer.write_u8(0x99)?;
            writer.write_u16::<BigEndian>(key_len.try_into()?)?;
        }

        KeyVersion::V6 => {
            // When a v6 signature is made over a key, the hash data starts with the salt
            // [NOTE: the salt is hashed in packet/signature/config.rs],

            // then octet 0x9B, followed by a four-octet length of the key,
            // and then the body of the key packet.
            writer.write_u8(0x9b)?;
            writer.write_u32::<BigEndian>(key_len.try_into()?)?;
        }

        v => unimplemented_err!("key version {:?}", v),
    }

    key.to_writer(&mut writer)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use bytes::BytesMut;

    use super::*;
    use crate::packet::SubpacketType;

    /// keyflags being all zeros..are special
    #[test]
    fn test_keyflags_crazy_versions() {
        for i in 0..1024 {
            println!("size {i}");
            // I write this with pain...
            let source = BytesMut::zeroed(i).freeze();
            let flags = KeyFlags::try_from_reader(&source[..]).unwrap();
            assert_eq!(&flags.to_bytes().unwrap(), &source);
        }
    }

    #[test]
    fn test_keyflags_1_byte() {
        let flags: KeyFlags = Default::default();
        assert_eq!(flags.to_bytes().unwrap(), vec![0x00]);

        let mut flags = KeyFlags::default();
        flags.set_certify(true);
        assert!(flags.certify());
        assert_eq!(flags.to_bytes().unwrap(), vec![0x01]);

        let mut flags = KeyFlags::default();
        flags.set_sign(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x02]);

        let mut flags = KeyFlags::default();
        flags.set_encrypt_comms(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x04]);

        let mut flags = KeyFlags::default();
        flags.set_encrypt_storage(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x08]);

        let mut flags = KeyFlags::default();
        flags.set_shared(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x10]);

        let mut flags = KeyFlags::default();
        flags.set_authentication(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x20]);

        let mut flags = KeyFlags::default();
        flags.set_group(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x80]);

        let mut flags = KeyFlags::default();
        flags.set_certify(true);
        flags.set_sign(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x03]);
    }

    #[test]
    fn test_keyflags_2_bytes() {
        let mut flags: KeyFlags = Default::default();
        flags.set_adsk(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x00, 0x04]);

        let mut flags: KeyFlags = Default::default();
        flags.set_timestamping(true);
        assert_eq!(flags.to_bytes().unwrap(), vec![0x00, 0x08]);

        let mut flags: KeyFlags = Default::default();
        flags.set_timestamping(true);
        flags.set_certify(true);
        flags.set_sign(true);

        assert_eq!(flags.to_bytes().unwrap(), vec![0x03, 0x08]);
    }

    #[test]
    fn test_features() {
        use crate::packet::Features;

        // deserialize/serialize, getters
        {
            let empty: Features = (&[][..]).into();
            assert_eq!(empty.seipd_v1(), false);
            assert_eq!(empty.seipd_v2(), false);

            assert_eq!(empty.write_len(), 0);
            let mut out = vec![];
            empty.to_writer(&mut out).expect("write");
            assert!(out.is_empty());
        }
        {
            let seipdv1: Features = (&[0x01][..]).into();
            assert_eq!(seipdv1.seipd_v1(), true);
            assert_eq!(seipdv1.seipd_v2(), false);

            assert_eq!(seipdv1.write_len(), 1);
            let mut out = vec![];
            seipdv1.to_writer(&mut out).expect("write");
            assert_eq!(out, vec![0x01]);
        }
        {
            let allbits: Features = (&[0xff][..]).into();
            assert_eq!(allbits.seipd_v1(), true);
            assert_eq!(allbits.seipd_v2(), true);

            assert_eq!(allbits.write_len(), 1);
            let mut out = vec![];
            allbits.to_writer(&mut out).expect("write");
            assert_eq!(out, vec![0xff]);
        }
        {
            let three_bytes: Features = (&[0x09, 0xaa, 0xbb][..]).into();
            assert_eq!(three_bytes.seipd_v1(), true);
            assert_eq!(three_bytes.seipd_v2(), true);

            assert_eq!(three_bytes.write_len(), 3);
            let mut out = vec![];
            three_bytes.to_writer(&mut out).expect("write");
            assert_eq!(out, vec![0x09, 0xaa, 0xbb]);
        }

        // setters
        {
            let mut empty: Features = (&[][..]).into();
            assert!(Vec::<u8>::from(&empty).is_empty());

            empty.set_seipd_v1(true);
            assert_eq!(Vec::<u8>::from(&empty), vec![0x01]);
        }
        {
            let mut default = Features::default();
            assert_eq!(Vec::<u8>::from(&default), vec![0x00]);

            default.set_seipd_v1(true);
            assert_eq!(Vec::<u8>::from(&default), vec![0x01]);

            default.set_seipd_v2(true);
            assert_eq!(Vec::<u8>::from(&default), vec![0x09]);
        }
        {
            let mut allbits: Features = (&[0xff][..]).into();

            allbits.set_seipd_v1(false);
            assert_eq!(Vec::<u8>::from(&allbits), vec![0xfe]);

            allbits.set_seipd_v2(false);
            assert_eq!(Vec::<u8>::from(&allbits), vec![0xf6]);
        }
        {
            let mut three_bytes: Features = (&[0x00, 0xaa, 0xbb][..]).into();
            three_bytes.set_seipd_v2(true);
            assert_eq!(Vec::<u8>::from(&three_bytes), vec![0x08, 0xaa, 0xbb]);
        }
    }

    #[test]
    fn test_critical() {
        use SubpacketType::*;
        let cases = [
            SignatureCreationTime,
            SignatureExpirationTime,
            ExportableCertification,
            TrustSignature,
            RegularExpression,
            Revocable,
            KeyExpirationTime,
            PreferredSymmetricAlgorithms,
            RevocationKey,
            IssuerKeyId,
            Notation,
            PreferredHashAlgorithms,
            PreferredCompressionAlgorithms,
            KeyServerPreferences,
            PreferredKeyServer,
            PrimaryUserId,
            PolicyURI,
            KeyFlags,
            SignersUserID,
            RevocationReason,
            Features,
            SignatureTarget,
            EmbeddedSignature,
            IssuerFingerprint,
            PreferredAead,
            Experimental(101),
            Other(95),
        ];
        for case in cases {
            assert_eq!(SubpacketType::from_u8(case.as_u8(false)), (case, false));
            assert_eq!(SubpacketType::from_u8(case.as_u8(true)), (case, true));
        }
    }

    use proptest::prelude::*;

    use crate::composed::DetachedSignature;

    impl Arbitrary for KeyFlags {
        type Parameters = ();
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
            proptest::collection::vec(0u8..255, 1..500)
                .prop_map(|v| KeyFlags::try_from_reader(&mut &v[..]).unwrap())
                .boxed()
        }
    }

    #[test]
    fn unhashed_area_modification() {
        fn subpacket_type_list(sig: &Signature) -> Vec<SubpacketType> {
            sig.config()
                .unwrap()
                .unhashed_subpackets
                .iter()
                .map(Subpacket::typ)
                .collect()
        }

        use crate::composed::Deserializable;

        let mut sig = DetachedSignature::from_armor_single(Cursor::new(
            "-----BEGIN PGP SIGNATURE-----

wpoEEBYIAEIFAmheZZEWIQT8Y2QNsPXIvVyHlK1LkdWvyoDDywIbAwIeAQQLCQgH
BhUOCgkMCAEWDScJAggCBwIJAQgBBwECGQEACgkQS5HVr8qAw8swhAD/RFBBueDN
ClWUWHgCj+FmHElqrUO4YVePdt2KRkniPJ4A/jtOCzD7vZJZs0yP4xQ78PEsUST0
pwsJtT3sJB2q5NoA
=XphF
-----END PGP SIGNATURE-----",
        ))
        .unwrap()
        .0
        .signature;

        assert_eq!(sig.packet_header.packet_length(), PacketLength::Fixed(154));

        sig.unhashed_subpacket_push(
            Subpacket::regular(SubpacketData::Notation(Notation {
                readable: true,
                name: "foo".into(),
                value: "bar".into(),
            }))
            .unwrap(),
        )
        .unwrap();
        assert_eq!(sig.packet_header.packet_length(), PacketLength::Fixed(170));
        assert_eq!(
            &subpacket_type_list(&sig),
            &[SubpacketType::IssuerKeyId, SubpacketType::Notation]
        );

        sig.unhashed_subpacket_insert(
            0,
            Subpacket::regular(SubpacketData::Notation(Notation {
                readable: true,
                name: "hello".into(),
                value: "world".into(),
            }))
            .unwrap(),
        )
        .unwrap();
        assert_eq!(sig.packet_header.packet_length(), PacketLength::Fixed(190));
        assert_eq!(
            &subpacket_type_list(&sig),
            &[
                SubpacketType::Notation,
                SubpacketType::IssuerKeyId,
                SubpacketType::Notation
            ]
        );

        sig.unhashed_subpackets_sort_by(|a, b| {
            a.typ()
                .as_u8(a.is_critical)
                .cmp(&b.typ().as_u8(b.is_critical))
        });
        assert_eq!(sig.packet_header.packet_length(), PacketLength::Fixed(190));
        assert_eq!(
            &subpacket_type_list(&sig),
            &[
                SubpacketType::IssuerKeyId,
                SubpacketType::Notation,
                SubpacketType::Notation
            ]
        );

        sig.unhashed_subpacket_remove(0).unwrap();
        assert_eq!(sig.packet_header.packet_length(), PacketLength::Fixed(180));
        assert_eq!(
            &subpacket_type_list(&sig),
            &[SubpacketType::Notation, SubpacketType::Notation]
        );
    }

    proptest! {
        #[test]
        fn keyflags_write_len(flags: KeyFlags) {
            let mut buf = Vec::new();
            flags.to_writer(&mut buf).unwrap();
            prop_assert_eq!(buf.len(), flags.write_len());
        }

        #[test]
        fn keyflags_packet_roundtrip(flags: KeyFlags) {
            let mut buf = Vec::new();
            flags.to_writer(&mut buf).unwrap();
            let new_flags = KeyFlags::try_from_reader(&mut &buf[..]).unwrap();
            prop_assert_eq!(flags, new_flags);
        }
    }
}