wecanencrypt 0.3.0

Simple Rust OpenPGP library for encryption, signing, and key management (includes rpgp).
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
use std::io::Read;

use byteorder::{BigEndian, ByteOrder};
use digest::DynDigest;
use log::debug;
use rand::{CryptoRng, Rng};

use crate::pgp::{
    crypto::{
        hash::{HashAlgorithm, WriteHasher},
        public_key::PublicKeyAlgorithm,
    },
    errors::{bail, ensure, unimplemented_err, unsupported_err, Result},
    packet::{
        types::serialize_for_hashing, Signature, SignatureType, SignatureVersion, Subpacket,
        SubpacketData, SubpacketType,
    },
    ser::Serialize,
    types::{Fingerprint, KeyDetails, KeyId, KeyVersion, Password, SigningKey, Tag, Timestamp},
    util::NormalizingHasher,
};

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SignatureConfig {
    pub typ: SignatureType,
    pub pub_alg: PublicKeyAlgorithm,
    pub hash_alg: HashAlgorithm,

    pub unhashed_subpackets: Vec<Subpacket>,
    pub hashed_subpackets: Vec<Subpacket>,

    pub version_specific: SignatureVersionSpecific,
}

#[derive(Clone, PartialEq, Eq, derive_more::Debug)]
pub enum SignatureVersionSpecific {
    V2 {
        created: Timestamp,
        issuer_key_id: KeyId,
    },
    V3 {
        created: Timestamp,
        issuer_key_id: KeyId,
    },
    V4,
    V6 {
        #[debug("{}", hex::encode(salt))]
        salt: Vec<u8>,
    },
}

impl From<&SignatureVersionSpecific> for SignatureVersion {
    fn from(value: &SignatureVersionSpecific) -> Self {
        match value {
            SignatureVersionSpecific::V2 { .. } => SignatureVersion::V2,
            SignatureVersionSpecific::V3 { .. } => SignatureVersion::V3,
            SignatureVersionSpecific::V4 => SignatureVersion::V4,
            SignatureVersionSpecific::V6 { .. } => SignatureVersion::V6,
        }
    }
}

impl SignatureConfig {
    pub fn from_key<R: CryptoRng + Rng, S: SigningKey>(
        mut rng: R,
        key: &S,
        typ: SignatureType,
    ) -> Result<Self> {
        match key.version() {
            KeyVersion::V4 => Ok(SignatureConfig::v4(typ, key.algorithm(), key.hash_alg())),
            KeyVersion::V6 => SignatureConfig::v6(&mut rng, typ, key.algorithm(), key.hash_alg()),
            v => unsupported_err!("unsupported key version: {:?}", v),
        }
    }

    /// Constructor for a v2 SignatureConfig (which represents the data of a v2 OpenPGP signature packet)
    ///
    /// OpenPGP v2 Signatures are historical and not used anymore.
    pub fn v2(
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        created: Timestamp,
        issuer_key_id: KeyId,
    ) -> Self {
        Self {
            typ,
            pub_alg,
            hash_alg,
            hashed_subpackets: Vec::new(),
            unhashed_subpackets: Vec::new(),
            version_specific: SignatureVersionSpecific::V2 {
                created,
                issuer_key_id,
            },
        }
    }

    /// Constructor for a v3 SignatureConfig (which represents the data of a v3 OpenPGP signature packet)
    ///
    /// OpenPGP v3 Signatures are historical and not used anymore.
    pub fn v3(
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        created: Timestamp,
        issuer_key_id: KeyId,
    ) -> Self {
        Self {
            typ,
            pub_alg,
            hash_alg,
            hashed_subpackets: Vec::new(),
            unhashed_subpackets: Vec::new(),
            version_specific: SignatureVersionSpecific::V3 {
                created,
                issuer_key_id,
            },
        }
    }

    /// Constructor for a v4 SignatureConfig (which represents the data of a v4 OpenPGP signature packet)
    ///
    /// OpenPGP v4 signatures were first specified in RFC 2440, and are commonly produced by
    /// OpenPGP v4 keys.
    pub fn v4(typ: SignatureType, pub_alg: PublicKeyAlgorithm, hash_alg: HashAlgorithm) -> Self {
        Self {
            typ,
            pub_alg,
            hash_alg,
            unhashed_subpackets: vec![],
            hashed_subpackets: vec![],
            version_specific: SignatureVersionSpecific::V4,
        }
    }

    /// Generate v6 signature salt with the appropriate length for `hash_alg`
    /// https://www.rfc-editor.org/rfc/rfc9580.html#name-hash-algorithms
    fn v6_salt_for<R: CryptoRng + Rng>(mut rng: R, hash_alg: HashAlgorithm) -> Result<Vec<u8>> {
        let Some(salt_len) = hash_alg.salt_len() else {
            bail!("Unknown v6 signature salt length for hash algorithm {hash_alg:?}");
        };

        let mut salt = vec![0; salt_len];
        rng.fill_bytes(&mut salt);

        Ok(salt)
    }

    /// Constructor for a v6 SignatureConfig (which represents the data of a v6 OpenPGP signature packet).
    /// Generates a new salt via `rng`.
    ///
    /// OpenPGP v6 signatures are specified in RFC 9580, they are produced by OpenPGP v6 keys.
    pub fn v6<R: CryptoRng + Rng>(
        rng: R,
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
    ) -> Result<Self> {
        Ok(Self::v6_with_salt(
            typ,
            pub_alg,
            hash_alg,
            Self::v6_salt_for(rng, hash_alg)?,
        ))
    }

    /// Constructor for a v6 SignatureConfig (which represents the data of a v6 OpenPGP signature packet).
    ///
    /// OpenPGP v6 signatures are specified in RFC 9580, they are produced by OpenPGP v6 keys.
    pub fn v6_with_salt(
        typ: SignatureType,
        pub_alg: PublicKeyAlgorithm,
        hash_alg: HashAlgorithm,
        salt: Vec<u8>,
    ) -> Self {
        Self {
            typ,
            pub_alg,
            hash_alg,
            unhashed_subpackets: Vec::new(),
            hashed_subpackets: Vec::new(),
            version_specific: SignatureVersionSpecific::V6 { salt },
        }
    }

    pub fn version(&self) -> SignatureVersion {
        (&self.version_specific).into()
    }

    /// Sign the given data.
    pub fn sign<R>(self, key: &impl SigningKey, key_pw: &Password, mut data: R) -> Result<Signature>
    where
        R: Read,
    {
        let mut hasher = self.into_hasher()?;
        std::io::copy(&mut data, &mut hasher)?;

        hasher.sign(key, key_pw)
    }

    pub fn into_hasher(self) -> Result<SignatureHasher> {
        let mut hasher = self.hash_alg.new_hasher()?;

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

        let text_mode = self.typ == SignatureType::Text;
        let norm_hasher = NormalizingHasher::new(hasher, text_mode);

        Ok(SignatureHasher {
            norm_hasher,
            config: self,
        })
    }

    /// Create a certification self-signature.
    pub fn sign_certification<S, K>(
        self,
        key: &S,
        pub_key: &K,
        key_pw: &Password,
        tag: Tag,
        id: &impl Serialize,
    ) -> Result<Signature>
    where
        S: SigningKey,
        K: KeyDetails + Serialize,
    {
        self.sign_certification_third_party(key, key_pw, pub_key, tag, id)
    }

    /// Create a certification third-party signature.
    pub fn sign_certification_third_party<K>(
        self,
        signer: &impl SigningKey,
        signer_pw: &Password,
        signee: &K,
        tag: Tag,
        id: &impl Serialize,
    ) -> Result<Signature>
    where
        K: KeyDetails + Serialize,
    {
        ensure!(
            (self.version() == SignatureVersion::V4 && signer.version() == KeyVersion::V4)
                || (self.version() == SignatureVersion::V6 && signer.version() == KeyVersion::V6),
            "signature version {:?} not allowed for signer key version {:?}",
            self.version(),
            signer.version()
        );
        ensure!(
            self.is_certification(),
            "can not sign non certification as certification"
        );

        debug!("signing certification {:#?}", self.typ);

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

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

        serialize_for_hashing(signee, &mut hasher)?;

        let mut packet_buf = Vec::new();
        id.to_writer(&mut packet_buf)?;

        match self.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 signature: {:?}", tag),
                };

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

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

        // the packet content
        hasher.update(&packet_buf);

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

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

        let signed_hash_value = [hash[0], hash[1]];
        let signature = signer.sign(signer_pw, self.hash_alg, hash)?;

        Signature::from_config(self, signed_hash_value, signature)
    }

    /// Sign a subkey binding that associates a subkey with a primary key.
    ///
    /// The primary key is expected as `signer`, the subkey as `signee`.
    ///
    /// Produces a "Subkey Binding Signature (type ID 0x18)"
    pub fn sign_subkey_binding<S, K1, K2>(
        self,
        signer: &S,
        signer_pub: &K1,
        signer_pw: &Password,
        signee: &K2,
    ) -> Result<Signature>
    where
        S: SigningKey,
        K1: KeyDetails + Serialize,
        K2: KeyDetails + Serialize,
    {
        ensure!(
            (self.version() == SignatureVersion::V4 && signer.version() == KeyVersion::V4)
                || (self.version() == SignatureVersion::V6 && signer.version() == KeyVersion::V6),
            "signature version {:?} not allowed for signer key version {:?}",
            self.version(),
            signer.version()
        );
        debug!("signing subkey binding: {self:#?} - {signer:#?} - {signee:#?}");

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

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

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

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

        let hash = &hasher.finalize()[..];
        let signed_hash_value = [hash[0], hash[1]];
        let signature = signer.sign(signer_pw, self.hash_alg, hash)?;

        Signature::from_config(self, signed_hash_value, signature)
    }

    /// Sign a primary key binding, or "back signature"
    /// (with this signature, the subkey signals that it wants to be associated with the primary).
    ///
    /// The subkey is expected as `signer`, the primary key as `signee`.
    ///
    /// Produces a "Primary Key Binding Signature (type ID 0x19)"
    pub fn sign_primary_key_binding<S, K1, K2>(
        self,
        signer: &S,
        signer_pub: &K1,
        signer_pw: &Password,
        signee: &K2,
    ) -> Result<Signature>
    where
        S: SigningKey,
        K1: KeyDetails + Serialize,
        K2: KeyDetails + Serialize,
    {
        ensure!(
            (self.version() == SignatureVersion::V4 && signer.version() == KeyVersion::V4)
                || (self.version() == SignatureVersion::V6 && signer.version() == KeyVersion::V6),
            "signature version {:?} not allowed for signer key version {:?}",
            self.version(),
            signer.version()
        );
        debug!("signing primary key binding: {self:#?} - {signer:#?} - {signee:#?}");

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

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

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

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

        let hash = &hasher.finalize()[..];
        let signed_hash_value = [hash[0], hash[1]];
        let signature = signer.sign(signer_pw, self.hash_alg, hash)?;

        Signature::from_config(self, signed_hash_value, signature)
    }

    /// Signs a direct key signature or a revocation.
    pub fn sign_key<S, K>(self, signing_key: &S, key_pw: &Password, key: &K) -> Result<Signature>
    where
        S: SigningKey,
        K: KeyDetails + Serialize,
    {
        ensure!(
            (self.version() == SignatureVersion::V4 && signing_key.version() == KeyVersion::V4)
                || (self.version() == SignatureVersion::V6
                    && signing_key.version() == KeyVersion::V6),
            "signature version {:?} not allowed for signer key version {:?}",
            self.version(),
            signing_key.version()
        );
        debug!("signing key ({:?}): {self:#?} - {key:#?}", self.typ);

        ensure!(
            [SignatureType::Key, SignatureType::KeyRevocation].contains(&self.typ),
            "signature type must be suitable for direct signatures"
        );

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

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

        serialize_for_hashing(key, &mut hasher)?;

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

        let hash = &hasher.finalize()[..];
        let signed_hash_value = [hash[0], hash[1]];
        let signature = signing_key.sign(key_pw, self.hash_alg, hash)?;

        Signature::from_config(self, signed_hash_value, signature)
    }

    /// Returns what kind of signature this is.
    pub fn typ(&self) -> SignatureType {
        self.typ
    }

    /// Calculate the serialized version of this packet, but only the part relevant for hashing.
    pub fn hash_signature_data(&self, hasher: &mut Box<dyn DynDigest + Send>) -> Result<usize> {
        match self.version() {
            SignatureVersion::V2 | SignatureVersion::V3 => {
                let created = {
                    if let SignatureVersionSpecific::V2 { created, .. }
                    | SignatureVersionSpecific::V3 { created, .. } = self.version_specific
                    {
                        created
                    } else {
                        bail!("must exist for a v2/3 signature")
                    }
                };

                let mut buf = [0u8; 5];
                buf[0] = self.typ.into();
                BigEndian::write_u32(&mut buf[1..], created.as_secs());

                hasher.update(&buf);

                // no trailer
                Ok(0)
            }
            SignatureVersion::V4 | SignatureVersion::V6 => {
                // TODO: reduce duplication with serialization code

                let mut res = vec![
                    // the signature version
                    self.version().into(),
                    // the signature type
                    self.typ.into(),
                    // the public-key algorithm
                    self.pub_alg.into(),
                    // the hash algorithm
                    self.hash_alg.into(),
                ];

                // hashed subpackets
                let mut hashed_subpackets = Vec::new();
                for packet in &self.hashed_subpackets {
                    debug!("hashing {packet:#?}");

                    // If a subpacket is encountered that is marked critical but is unknown to the
                    // evaluating implementation, the evaluator SHOULD consider the signature to be
                    // in error.
                    //
                    // (See https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.7-6)
                    if packet.is_critical && matches!(packet.typ(), SubpacketType::Other(_)) {
                        // "[..] The purpose of the critical bit is to allow the signer to tell an
                        // evaluator that it would prefer a new, unknown feature to generate an
                        // error rather than being ignored."
                        //
                        // (See https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.7-8:)

                        bail!("Unknown critical subpacket {:?}", packet);
                    }

                    // If the version octet does not match the signature version, the receiving
                    // implementation MUST treat it as a malformed signature
                    //
                    // (See https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.35-3)
                    if let SubpacketData::IssuerFingerprint(fp) = &packet.data {
                        match (self.version(), fp.version()) {
                            (SignatureVersion::V6, Some(KeyVersion::V6)) => {}
                            (SignatureVersion::V4, Some(KeyVersion::V4)) => {}
                            _ => bail!(
                                "IntendedRecipientFingerprint {:?} doesn't match signature version {:?}",
                                fp,
                                self.version()
                            ),
                        }
                    }

                    packet.to_writer(&mut hashed_subpackets)?;
                }

                // append hashed area length, as u16 for v4, and u32 for v6
                if self.version() == SignatureVersion::V4 {
                    res.extend(u16::try_from(hashed_subpackets.len())?.to_be_bytes());
                } else if self.version() == SignatureVersion::V6 {
                    res.extend(u32::try_from(hashed_subpackets.len())?.to_be_bytes());
                }

                res.extend(hashed_subpackets);

                hasher.update(&res);

                Ok(res.len())
            }
            SignatureVersion::V5 => {
                bail!("v5 signature unsupported hash data")
            }
            SignatureVersion::Other(version) => {
                bail!("unsupported signature version {}", version)
            }
        }
    }

    pub fn hash_data_to_sign<R>(
        &self,
        hasher: &mut Box<dyn DynDigest + Send>,
        mut data: R,
    ) -> Result<usize>
    where
        R: Read,
    {
        match self.typ {
            SignatureType::Text |
                // assumes that the passed in text was already valid utf8 and normalized
            SignatureType::Binary => {
                let written = std::io::copy(&mut data, &mut WriteHasher(hasher))?;
                Ok(written.try_into()?)
            }
            SignatureType::Timestamp |
            SignatureType::Standalone => {
                let mut val = [0u8;1];
                data.read_exact(&mut val[..])?;
                hasher.update(&val[..]);
                Ok(1)
            }
            SignatureType::CertGeneric
            | SignatureType::CertPersona
            | SignatureType::CertCasual
            | SignatureType::CertPositive
            | SignatureType::CertRevocation => {
                unimplemented_err!("{:?}", self.typ);
            }
            SignatureType::SubkeyBinding
            | SignatureType::SubkeyRevocation
            | SignatureType::KeyBinding
            | SignatureType::Key => {
                unimplemented_err!("{:?}", self.typ);
            }
            SignatureType::KeyRevocation => unimplemented_err!("KeyRevocation"),
            SignatureType::ThirdParty => unimplemented_err!("signing ThirdParty"),

            SignatureType::Other(id) => unimplemented_err!("Other ({})", id),
        }
    }

    pub fn trailer(&self, len: usize) -> Result<Vec<u8>> {
        match self.version() {
            SignatureVersion::V2 | SignatureVersion::V3 => {
                // Nothing to do
                Ok(Vec::new())
            }
            SignatureVersion::V4 | SignatureVersion::V6 => {
                let mut trailer = vec![self.version().into(), 0xFF, 0, 0, 0, 0];
                BigEndian::write_u32(&mut trailer[2..], len.try_into()?);
                Ok(trailer)
            }
            SignatureVersion::V5 => {
                bail!("v5 signature unsupported")
            }
            SignatureVersion::Other(version) => {
                bail!("unsupported signature version {}", version)
            }
        }
    }

    /// Returns an iterator of all subpackets in the signature: all subpackets in the hashed area
    /// followed by all subpackets in the unhashed area.
    #[deprecated(
        note = "Usually only hashed_subpackets should be used. unhashed_subpackets are only safe and useful to access in rare circumstances. When they are needed, unhashed_subpackets should be explicitly called."
    )]
    pub fn subpackets(&self) -> impl Iterator<Item = &Subpacket> {
        self.hashed_subpackets().chain(self.unhashed_subpackets())
    }

    /// Returns an iterator over the hashed subpackets of this signature.
    pub fn hashed_subpackets(&self) -> impl Iterator<Item = &Subpacket> {
        self.hashed_subpackets.iter()
    }

    /// Returns an iterator over the unhashed subpackets of this signature.
    pub fn unhashed_subpackets(&self) -> impl Iterator<Item = &Subpacket> {
        self.unhashed_subpackets.iter()
    }

    /// Returns if the signature is a certification or not.
    pub fn is_certification(&self) -> bool {
        matches!(
            self.typ,
            SignatureType::CertGeneric
                | SignatureType::CertPersona
                | SignatureType::CertCasual
                | SignatureType::CertPositive
                | SignatureType::CertRevocation
        )
    }

    /// Signature Creation Time.
    ///
    /// The time the signature was made.
    /// MUST be present in the hashed area.
    ///
    /// <https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-creation-time>
    ///
    /// Returns the first Signature Creation Time subpacket, only from the hashed area.
    pub fn created(&self) -> Option<Timestamp> {
        if let SignatureVersionSpecific::V2 { created, .. }
        | SignatureVersionSpecific::V3 { created, .. } = &self.version_specific
        {
            return Some(*created);
        }

        self.hashed_subpackets().find_map(|p| match p.data {
            SubpacketData::SignatureCreationTime(d) => Some(d),
            _ => None,
        })
    }

    /// Issuer Key ID.
    ///
    /// The OpenPGP Key ID of the key issuing the signature.
    ///
    /// <https://www.rfc-editor.org/rfc/rfc9580.html#name-issuer-key-id>
    ///
    /// Returns Issuer subpacket data from both the hashed and unhashed area.
    pub fn issuer_key_id(&self) -> Vec<&KeyId> {
        // legacy v2/v3 signatures have an explicit "issuer" field
        if let SignatureVersionSpecific::V2 { issuer_key_id, .. }
        | SignatureVersionSpecific::V3 { issuer_key_id, .. } = &self.version_specific
        {
            return vec![issuer_key_id];
        }

        // v4+ signatures use subpackets
        //
        // We consider data from both the hashed and unhashed area here, because the issuer Key ID
        // only acts as a hint. The signature will be cryptographically checked using the purported
        // issuer's key material. An attacker cannot successfully claim an issuer Key ID that they
        // can't produce a cryptographically valid signature for.
        self.hashed_subpackets()
            .chain(self.unhashed_subpackets())
            .filter_map(|sp| match sp.data {
                SubpacketData::IssuerKeyId(ref id) => Some(id),
                _ => None,
            })
            .collect()
    }

    /// Issuer Fingerprint.
    ///
    /// The OpenPGP Key fingerprint of the key issuing the signature.
    ///
    /// <https://www.rfc-editor.org/rfc/rfc9580.html#name-issuer-fingerprint>
    ///
    /// Returns Issuer Fingerprint subpacket data from both the hashed and unhashed area.
    pub fn issuer_fingerprint(&self) -> Vec<&Fingerprint> {
        self.hashed_subpackets()
            .chain(self.unhashed_subpackets())
            .filter_map(|sp| match &sp.data {
                SubpacketData::IssuerFingerprint(fp) => Some(fp),
                _ => None,
            })
            .collect()
    }
}

pub struct SignatureHasher {
    norm_hasher: NormalizingHasher,
    config: SignatureConfig,
}

impl SignatureHasher {
    /// Finalizes the signature.
    pub fn sign<S>(self, key: &S, key_pw: &Password) -> Result<Signature>
    where
        S: SigningKey + ?Sized,
    {
        let Self {
            config,
            norm_hasher,
        } = self;

        let mut hasher = norm_hasher.done();

        ensure!(
            (config.version() == SignatureVersion::V4 && key.version() == KeyVersion::V4)
                || (config.version() == SignatureVersion::V6 && key.version() == KeyVersion::V6),
            "signature version {:?} not allowed for signer key version {:?}",
            config.version(),
            key.version()
        );
        ensure!(
            matches!(config.typ, SignatureType::Binary | SignatureType::Text),
            "incompatible signature type {:?}",
            config.typ
        );

        Signature::check_signature_hash_strength(&config)?;

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

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

        let signed_hash_value = [hash[0], hash[1]];
        let signature = key.sign(key_pw, config.hash_alg, hash)?;

        Signature::from_config(config, signed_hash_value, signature)
    }

    /// Update the internal hasher.
    ///
    /// Normalize line-endings on the fly for SignatureType::Text
    pub(crate) fn update(&mut self, buf: &[u8]) {
        self.norm_hasher.hash_buf(buf);
    }
}

impl std::io::Write for SignatureHasher {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.norm_hasher.hash_buf(buf); // FIXME: when is this used?
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use rand::SeedableRng;
    use rand_chacha::ChaCha8Rng;

    use crate::pgp::{
        composed::{ArmorOptions, KeyType, SecretKeyParamsBuilder, SignedPublicKey},
        packet::{SignatureConfig, SignatureType, Subpacket, SubpacketData},
        types::{KeyDetails, Password, Timestamp},
    };

    #[test]
    fn test_third_party_direct_key_signature() {
        // Create a third-party direct key signature, then verify it

        pretty_env_logger::try_init().ok();

        let mut rng = ChaCha8Rng::seed_from_u64(0);

        // initialize alice
        let mut key_params = SecretKeyParamsBuilder::default();
        key_params
            .key_type(KeyType::Ed25519Legacy)
            .can_certify(true)
            .primary_user_id("alice".into());
        let secret_key_params = key_params
            .build()
            .expect("Must be able to create secret key params");
        let alice = secret_key_params.generate(&mut rng).expect("generate");

        // initialize bob
        let mut key_params = SecretKeyParamsBuilder::default();
        key_params
            .key_type(KeyType::Ed25519Legacy)
            .can_certify(true)
            .primary_user_id("bob".into());
        let secret_key_params = key_params
            .build()
            .expect("Must be able to create secret key params");
        let mut bob = secret_key_params.generate(&mut rng).expect("generate");

        // alice makes a third party direct signature over bob's key
        let mut config =
            SignatureConfig::from_key(&mut rng, &alice.primary_key, SignatureType::Key)
                .expect("config");

        config.hashed_subpackets = vec![
            Subpacket::regular(SubpacketData::SignatureCreationTime(Timestamp::now())).unwrap(),
            Subpacket::regular(SubpacketData::IssuerFingerprint(
                alice.primary_key.fingerprint(),
            ))
            .unwrap(),
            Subpacket::regular(SubpacketData::TrustSignature(5, 120)).unwrap(),
        ];

        let dks = config
            .sign_key(
                &alice.primary_key,
                &Password::empty(),
                &bob.primary_key.public_key(),
            )
            .expect("sign key");

        bob.details.direct_signatures.push(dks.clone());

        // transform to public keys
        let alice_pub: SignedPublicKey = alice.into();
        let bob_pub: SignedPublicKey = bob.into();

        log::debug!(
            "alice:\n{}",
            alice_pub
                .to_armored_string(ArmorOptions::default())
                .unwrap()
        );
        log::debug!(
            "bob:\n{}",
            bob_pub.to_armored_string(ArmorOptions::default()).unwrap()
        );

        // verify dks signature packet over bob, check with alice's key
        dks.verify_key_third_party(&bob_pub.primary_key, &alice_pub.primary_key)
            .unwrap();
    }
}