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
use std::{io::BufRead, str};

use bytes::Buf;
use log::{debug, warn};
use smallvec::SmallVec;

use super::{KeyFlags, Signature, SignatureType, SignatureVersion};
use crate::pgp::{
    crypto::{
        aead::AeadAlgorithm, hash::HashAlgorithm, public_key::PublicKeyAlgorithm,
        sym::SymmetricKeyAlgorithm,
    },
    errors::{bail, ensure, format_err, unsupported_err, Result},
    packet::{
        Notation, PacketHeader, RevocationCode, Subpacket, SubpacketData, SubpacketLength,
        SubpacketType,
    },
    parsing_reader::BufReadParsing,
    types::{
        CompressionAlgorithm, Fingerprint, KeyId, KeyVersion, Mpi, PacketHeaderVersion,
        PacketLength, RevocationKey, SignatureBytes, Tag,
    },
};

impl Signature {
    /// Parses a `Signature` packet from the given buffer
    ///
    /// Ref: <https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-packet-type-id-2>
    pub fn try_from_reader<B: BufRead>(packet_header: PacketHeader, mut i: B) -> Result<Self> {
        let version = i.read_u8().map(SignatureVersion::from)?;

        let signature = match version {
            SignatureVersion::V2 | SignatureVersion::V3 => v3_parser(packet_header, version, i)?,
            SignatureVersion::V4 => v4_parser(packet_header, version, i)?,
            SignatureVersion::V6 => v6_parser(packet_header, i)?,
            _ => {
                let rest = i.rest()?.freeze();
                Signature::unknown(packet_header, version, rest)
            }
        };

        Ok(signature)
    }
}

/// Parse a v2 or v3 signature packet
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-version-3-signature-packet-
fn v3_parser<B: BufRead>(
    packet_header: PacketHeader,
    version: SignatureVersion,
    mut i: B,
) -> Result<Signature> {
    // One-octet length of following hashed material. MUST be 5.
    i.read_tag(&[5])?;
    // One-octet signature type.
    let typ = i.read_u8().map(SignatureType::from)?;
    // Four-octet creation time.
    let created = i.read_timestamp()?;

    // Eight-octet Key ID of signer.
    let issuer = i.read_array::<8>().map(KeyId::from)?;
    // One-octet public-key algorithm.
    let pub_alg = i.read_u8().map(PublicKeyAlgorithm::from)?;
    // One-octet hash algorithm.
    let hash_alg = i.read_u8().map(HashAlgorithm::from)?;
    // Two-octet field holding left 16 bits of signed hash value.
    let ls_hash = i.read_array::<2>()?;

    // The SignatureBytes comprising the signature.
    let sig = actual_signature(&pub_alg, &mut i)?;
    debug!("signature data {sig:?}");

    match version {
        SignatureVersion::V2 => Ok(Signature::v2(
            packet_header,
            typ,
            pub_alg,
            hash_alg,
            created,
            issuer,
            ls_hash,
            sig,
        )),
        SignatureVersion::V3 => Ok(Signature::v3(
            packet_header,
            typ,
            pub_alg,
            hash_alg,
            created,
            issuer,
            ls_hash,
            sig,
        )),
        _ => unreachable!("must only be called for V2/V3"),
    }
}

/// Parse a v4 signature packet
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-versions-4-and-6-signature-
fn v4_parser<B: BufRead>(
    packet_header: PacketHeader,
    version: SignatureVersion,
    mut i: B,
) -> Result<Signature> {
    debug_assert_eq!(version, SignatureVersion::V4);

    // One-octet signature type.
    let typ = i.read_u8().map(SignatureType::from)?;
    // One-octet public-key algorithm.
    let pub_alg = i.read_u8().map(PublicKeyAlgorithm::from)?;
    // One-octet hash algorithm.
    let hash_alg = i.read_u8().map(HashAlgorithm::from)?;

    // Two-octet scalar octet count for following hashed subpacket data.
    // Hashed subpacket data set (zero or more subpackets).
    let hsub_len: usize = i.read_be_u16()?.into();
    let hsub_raw = i.read_take(hsub_len);
    let hsub = subpackets(packet_header.version(), hsub_len, hsub_raw)?;
    debug!(
        "found {} hashed subpackets in {} bytes",
        hsub.len(),
        hsub_len
    );

    // Two-octet scalar octet count for the following unhashed subpacket data.
    // Unhashed subpacket data set (zero or more subpackets).
    let usub_len: usize = i.read_be_u16()?.into();
    let usub_raw = i.read_take(usub_len);
    let usub = subpackets(packet_header.version(), usub_len, usub_raw)?;
    debug!(
        "found {} unhashed subpackets in {} bytes",
        usub.len(),
        usub_len
    );
    // Two-octet field holding the left 16 bits of the signed hash value.
    let ls_hash = i.read_array::<2>()?;

    // The SignatureBytes comprising the signature.
    let sig = actual_signature(&pub_alg, i)?;
    debug!("signature data {sig:?}");

    Ok(Signature::v4(
        packet_header,
        typ,
        pub_alg,
        hash_alg,
        ls_hash,
        sig,
        hsub,
        usub,
    ))
}

/// Parse a v6 signature packet
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-versions-4-and-6-signature-
fn v6_parser<B: BufRead>(packet_header: PacketHeader, mut i: B) -> Result<Signature> {
    // One-octet signature type.
    let typ = i.read_u8().map(SignatureType::from)?;
    // One-octet public-key algorithm.
    let pub_alg = i.read_u8().map(PublicKeyAlgorithm::from)?;
    // One-octet hash algorithm.
    let hash_alg = i.read_u8().map(HashAlgorithm::from)?;

    // Four-octet scalar octet count for following hashed subpacket data.
    // Hashed subpacket data set (zero or more subpackets).
    let hsub_len: usize = i.read_be_u32()?.try_into()?;
    let hsub_raw = i.read_take(hsub_len);
    let hsub = subpackets(packet_header.version(), hsub_len, hsub_raw)?;
    debug!(
        "found {} hashed subpackets in {} bytes",
        hsub.len(),
        hsub_len
    );

    // Four-octet scalar octet count for the following unhashed subpacket data.
    // Unhashed subpacket data set (zero or more subpackets).
    let usub_len: usize = i.read_be_u32()?.try_into()?;
    let usub_raw = i.read_take(usub_len);
    let usub = subpackets(packet_header.version(), usub_len, usub_raw)?;
    debug!(
        "found {} unhashed subpackets in {} bytes",
        usub.len(),
        usub_len
    );

    // Two-octet field holding the left 16 bits of the signed hash value.
    let ls_hash = i.read_array::<2>()?;

    // A variable-length field containing:
    // A one-octet salt size. The value MUST match the value defined for the hash algorithm as specified in Table 23.
    // The salt; a random value of the specified size.
    let salt_len = i.read_u8()?;
    let salt = i.take_bytes(salt_len.into())?;

    if hash_alg.salt_len() != Some(salt.len()) {
        bail!(
            "Illegal salt length {} found for {:?}",
            salt.len(),
            hash_alg
        );
    }

    // The SignatureBytes comprising the signature.
    let sig = actual_signature(&pub_alg, i)?;
    debug!("signature data {sig:?}");
    Ok(Signature::v6(
        packet_header,
        typ,
        pub_alg,
        hash_alg,
        ls_hash,
        sig,
        hsub,
        usub,
        salt.to_vec(),
    ))
}

fn subpackets<B: BufRead>(
    packet_version: PacketHeaderVersion,
    len: usize,
    mut i: B,
) -> Result<Vec<Subpacket>> {
    let mut packets = Vec::with_capacity(len.min(32));

    while i.has_remaining()? {
        // the subpacket length (1, 2, or 5 octets)
        let packet_len = SubpacketLength::try_from_reader(&mut i)?;
        ensure!(!packet_len.is_empty(), "empty subpacket is not allowed");
        // the subpacket type (1 octet)
        let (typ, is_critical) = i.read_u8().map(SubpacketType::from_u8)?;
        let len = packet_len.len() - 1;
        debug!("reading subpacket {typ:?}: critical? {is_critical}, len: {len}");

        let mut body = i.read_take(len);
        let packet = subpacket(typ, is_critical, packet_len, packet_version, &mut body)?;
        debug!("found subpacket {packet:?}");

        if !body.rest()?.is_empty() {
            warn!("failed to fully process subpacket: {typ:?}");
            if is_critical {
                bail!("invalid subpacket: {:?}", typ);
            }
        }
        packets.push(packet);
    }
    Ok(packets)
}

fn subpacket<B: BufRead>(
    typ: SubpacketType,
    is_critical: bool,
    packet_len: SubpacketLength,
    packet_version: PacketHeaderVersion,
    mut body: B,
) -> Result<Subpacket> {
    use super::subpacket::SubpacketType::*;

    debug!("parsing subpacket: {typ:?}");

    let res = match typ {
        SignatureCreationTime => signature_creation_time(body),
        SignatureExpirationTime => signature_expiration_time(body),
        ExportableCertification => exportable_certification(body),
        TrustSignature => trust_signature(body),
        RegularExpression => regular_expression(body),
        Revocable => revocable(body),
        KeyExpirationTime => key_expiration(body),
        PreferredSymmetricAlgorithms => pref_sym_alg(body),
        RevocationKey => revocation_key(body),
        IssuerKeyId => issuer(body),
        Notation => notation_data(body),
        PreferredHashAlgorithms => pref_hash_alg(body),
        PreferredCompressionAlgorithms => pref_com_alg(body),
        KeyServerPreferences => key_server_prefs(body),
        PreferredKeyServer => preferred_key_server(body),
        PrimaryUserId => primary_userid(body),
        PolicyURI => policy_uri(body),
        KeyFlags => key_flags(body),
        SignersUserID => signers_userid(body),
        RevocationReason => rev_reason(body),
        Features => features(body),
        SignatureTarget => sig_target(body),
        EmbeddedSignature => embedded_sig(packet_version, body),
        IssuerFingerprint => issuer_fingerprint(body),
        PreferredEncryptionModes => preferred_encryption_modes(body),
        IntendedRecipientFingerprint => intended_recipient_fingerprint(body),
        PreferredAead => pref_aead_alg(body),
        Experimental(n) => Ok(SubpacketData::Experimental(n, body.rest()?.freeze())),
        Other(n) => Ok(SubpacketData::Other(n, body.rest()?.freeze())),
    };

    let res = res.map(|data| Subpacket {
        is_critical,
        data,
        len: packet_len,
    });

    if res.is_err() {
        warn!("invalid subpacket: {typ:?} {res:?}");
    }

    res
}

fn actual_signature<B: BufRead>(typ: &PublicKeyAlgorithm, mut i: B) -> Result<SignatureBytes> {
    match typ {
        PublicKeyAlgorithm::RSA | &PublicKeyAlgorithm::RSASign => {
            let v = Mpi::try_from_reader(&mut i)?;
            Ok(SignatureBytes::Mpis(vec![v]))
        }
        PublicKeyAlgorithm::DSA | PublicKeyAlgorithm::ECDSA | &PublicKeyAlgorithm::EdDSALegacy => {
            let a = Mpi::try_from_reader(&mut i)?;
            let b = Mpi::try_from_reader(&mut i)?;

            Ok(SignatureBytes::Mpis(vec![a, b]))
        }

        &PublicKeyAlgorithm::Ed25519 => {
            let sig = i.take_bytes(64)?;
            Ok(SignatureBytes::Native(sig.freeze()))
        }

        &PublicKeyAlgorithm::Elgamal => {
            let a = Mpi::try_from_reader(&mut i)?;
            let b = Mpi::try_from_reader(&mut i)?;
            Ok(SignatureBytes::Mpis(vec![a, b]))
        }
        &PublicKeyAlgorithm::Private100
        | &PublicKeyAlgorithm::Private101
        | &PublicKeyAlgorithm::Private102
        | &PublicKeyAlgorithm::Private103
        | &PublicKeyAlgorithm::Private104
        | &PublicKeyAlgorithm::Private105
        | &PublicKeyAlgorithm::Private106
        | &PublicKeyAlgorithm::Private107
        | &PublicKeyAlgorithm::Private108
        | &PublicKeyAlgorithm::Private109
        | &PublicKeyAlgorithm::Private110 => {
            let v = Mpi::try_from_reader(&mut i)?;
            Ok(SignatureBytes::Mpis(vec![v]))
        }
        PublicKeyAlgorithm::ElgamalEncrypt => {
            bail!("invalid signature algorithm, encryption only elgamal");
        }
        #[cfg(feature = "draft-pqc")]
        &PublicKeyAlgorithm::MlKem768X25519 | &PublicKeyAlgorithm::MlKem1024X448 => {
            bail!("invalid signature algorithm, ML KEM is encryption only");
        }
        _ => {
            // don't assume format, could be non-MPI
            let rest = i.rest()?.freeze();
            Ok(SignatureBytes::Native(rest))
        }
    }
}

/// Parse a Signature Creation Time subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-creation-time
fn signature_creation_time<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    // 4-octet time field
    let created = i.read_timestamp()?;

    Ok(SubpacketData::SignatureCreationTime(created))
}

/// Parse an Issuer Key ID subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-issuer-key-id
fn issuer<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let key_id = i.read_array::<8>().map(KeyId::from)?;

    Ok(SubpacketData::IssuerKeyId(key_id))
}

/// Parse a Key Expiration Time subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-key-expiration-time
fn key_expiration<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    // 4-octet time field
    let duration = i.read_duration()?;

    Ok(SubpacketData::KeyExpirationTime(duration))
}

/// Parse a Preferred Symmetric Ciphers for v1 SEIPD subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#preferred-v1-seipd
fn pref_sym_alg<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let mut list = SmallVec::<[SymmetricKeyAlgorithm; 8]>::new();
    while i.has_remaining()? {
        let alg = i.read_u8().map(SymmetricKeyAlgorithm::from)?;
        list.push(alg);
    }

    Ok(SubpacketData::PreferredSymmetricAlgorithms(list))
}

/// Parse a Preferred AEAD Ciphersuites subpacket (for SEIPD v2)
///
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-preferred-aead-ciphersuites
fn pref_aead_alg<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let mut list = SmallVec::<[(SymmetricKeyAlgorithm, AeadAlgorithm); 4]>::new();
    while i.has_remaining()? {
        let alg = i.read_u8().map(SymmetricKeyAlgorithm::from)?;
        let aead = i.read_u8().map(AeadAlgorithm::from)?;
        list.push((alg, aead));
    }

    Ok(SubpacketData::PreferredAeadAlgorithms(list))
}

/// Parse a Preferred Hash Algorithms subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-preferred-hash-algorithms
fn pref_hash_alg<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let mut list = SmallVec::<[HashAlgorithm; 8]>::new();
    while i.has_remaining()? {
        let alg = i.read_u8().map(HashAlgorithm::from)?;
        list.push(alg);
    }

    Ok(SubpacketData::PreferredHashAlgorithms(list))
}

/// Parse a Preferred Compression Algorithms subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-preferred-compression-algor
fn pref_com_alg<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let mut list = SmallVec::<[CompressionAlgorithm; 8]>::new();
    while i.has_remaining()? {
        let alg = i.read_u8().map(CompressionAlgorithm::from)?;
        list.push(alg);
    }

    Ok(SubpacketData::PreferredCompressionAlgorithms(list))
}

/// Parse a Signature Expiration Time subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-expiration-time
fn signature_expiration_time<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    // 4-octet time field
    let duration = i.read_duration()?;

    Ok(SubpacketData::SignatureExpirationTime(duration))
}

/// Parse an Exportable Certification subpacket.
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-exportable-certification
fn exportable_certification<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let is_exportable = i.read_u8()? == 1;

    Ok(SubpacketData::ExportableCertification(is_exportable))
}

/// Parse a Revocable subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-revocable
fn revocable<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let is_revocable = i.read_u8()? == 1;

    Ok(SubpacketData::Revocable(is_revocable))
}

/// Parse a Trust Signature subpacket.
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-trust-signature
fn trust_signature<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let depth = i.read_u8()?;
    let value = i.read_u8()?;

    Ok(SubpacketData::TrustSignature(depth, value))
}

/// Parse a Regular Expression subpacket.
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-regular-expression
fn regular_expression<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let regex = i.rest()?.freeze();

    Ok(SubpacketData::RegularExpression(regex))
}

/// Parse a Revocation Key subpacket (Deprecated)
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-revocation-key-deprecated
fn revocation_key<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let class = i
        .read_u8()?
        .try_into()
        .map_err(|e| format_err!("invalid revocation class: {:?}", e))?;
    let algorithm = i.read_u8().map(PublicKeyAlgorithm::from)?;
    // TODO: V5 Keys have 32 octets here
    let fp = i.read_array::<20>()?;
    let key = RevocationKey::new(class, algorithm, &fp);

    Ok(SubpacketData::RevocationKey(key))
}

/// Parse a Notation Data subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-notation-data
fn notation_data<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    // Flags
    let readable = i.read_u8().map(|v| v == 0x80)?;
    i.read_tag(&[0, 0, 0])?;
    let name_len = i.read_be_u16()?;
    let value_len = i.read_be_u16()?;
    let name = i.take_bytes(name_len.into())?.freeze();
    let value = i.take_bytes(value_len.into())?.freeze();

    Ok(SubpacketData::Notation(Notation {
        readable,
        name,
        value,
    }))
}

/// Parse a Key Server Preferences subpacket
/// https://www.rfc-editor.org/rfc/rfc9580.html#name-key-server-preferences
fn key_server_prefs<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let prefs = SmallVec::from_slice(&i.rest()?);

    Ok(SubpacketData::KeyServerPreferences(prefs))
}

/// Parse a Preferred Key Server subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-preferred-key-server
fn preferred_key_server<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let body = i.rest()?;
    let body_str = str::from_utf8(&body)?;

    Ok(SubpacketData::PreferredKeyServer(body_str.to_string()))
}

/// Parse a Primary User ID subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-primary-user-id
fn primary_userid<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let is_primary = i.read_u8()? == 1;

    Ok(SubpacketData::IsPrimary(is_primary))
}

/// Parse a Policy URI subpacket.
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-policy-uri
fn policy_uri<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let body = i.rest()?;
    let body_str = str::from_utf8(&body)?;

    Ok(SubpacketData::PolicyURI(body_str.to_string()))
}

/// Parse a Key Flags subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-key-flags
fn key_flags<B: BufRead>(i: B) -> Result<SubpacketData> {
    let flags = KeyFlags::try_from_reader(i)?;

    Ok(SubpacketData::KeyFlags(flags))
}

/// Parse a Signer's User ID subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-key-flags
fn signers_userid<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let userid = i.rest()?.freeze();

    Ok(SubpacketData::SignersUserID(userid))
}

/// Parse a Reason for Revocation subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-key-flags
fn rev_reason<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let code = i.read_u8().map(RevocationCode::from)?;
    let reason = i.rest()?.freeze();

    Ok(SubpacketData::RevocationReason(code, reason))
}

/// Parse a Features subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-features
fn features<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let features = i.rest()?;

    Ok(SubpacketData::Features(features.as_ref().into()))
}

/// Parse a Signature Target subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-signature-target
fn sig_target<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let pub_alg = i.read_u8().map(PublicKeyAlgorithm::from)?;
    let hash_alg = i.read_u8().map(HashAlgorithm::from)?;
    let hash = i.rest()?.freeze();

    Ok(SubpacketData::SignatureTarget(pub_alg, hash_alg, hash))
}

/// Parse an Embedded Signature subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-embedded-signature
fn embedded_sig<B: BufRead>(
    packet_version: PacketHeaderVersion,
    mut i: B,
) -> Result<SubpacketData> {
    // copy to bytes, to avoid recursive type explosion
    let signature_bytes = i.rest()?.freeze();
    let header = PacketHeader::from_parts(
        packet_version,
        Tag::Signature,
        PacketLength::Fixed(signature_bytes.len().try_into()?),
    )?;
    let sig = Signature::try_from_reader(header, signature_bytes.reader())?;

    Ok(SubpacketData::EmbeddedSignature(Box::new(sig)))
}

/// Parse an Issuer Fingerprint subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-issuer-fingerprint
fn issuer_fingerprint<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let version = i.read_u8().map(KeyVersion::from)?;

    // This subpacket is only used for v4 and newer fingerprints
    if version != KeyVersion::V4 && version != KeyVersion::V5 && version != KeyVersion::V6 {
        unsupported_err!("invalid key version {version:?}");
    }

    if let Some(fingerprint_len) = version.fingerprint_len() {
        let fingerprint = i.take_bytes(fingerprint_len)?;
        let fp = Fingerprint::new(version, &fingerprint)?;

        return Ok(SubpacketData::IssuerFingerprint(fp));
    }
    unsupported_err!("invalid key version {version:?}");
}

/// Parse a preferred encryption modes subpacket (non-RFC subpacket for GnuPG "OCB" mode)
fn preferred_encryption_modes<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let mut list = SmallVec::<[AeadAlgorithm; 2]>::new();
    while i.has_remaining()? {
        let alg = i.read_u8().map(AeadAlgorithm::from)?;
        list.push(alg);
    }

    Ok(SubpacketData::PreferredEncryptionModes(list))
}

/// Parse an Intended Recipient Fingerprint subpacket
/// Ref: https://www.rfc-editor.org/rfc/rfc9580.html#name-intended-recipient-fingerpr
fn intended_recipient_fingerprint<B: BufRead>(mut i: B) -> Result<SubpacketData> {
    let version = i.read_u8().map(KeyVersion::from)?;

    // This subpacket is only used for v4 and newer fingerprints
    if version != KeyVersion::V4 && version != KeyVersion::V5 && version != KeyVersion::V6 {
        unsupported_err!("invalid key version {version:?}");
    }

    if let Some(fingerprint_len) = version.fingerprint_len() {
        let fingerprint = i.take_bytes(fingerprint_len)?.freeze();
        let fp = Fingerprint::new(version, &fingerprint)?;

        return Ok(SubpacketData::IntendedRecipientFingerprint(fp));
    }
    unsupported_err!("invalid key version {version:?}");
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;
    use crate::pgp::composed::{Deserializable, DetachedSignature};

    #[test]
    fn test_subpacket_pref_sym_alg() {
        let input = vec![9, 8, 7, 3, 2];
        let res = pref_sym_alg(input.as_slice()).unwrap();
        assert_eq!(
            res,
            SubpacketData::PreferredSymmetricAlgorithms(
                input
                    .iter()
                    .map(|i| SymmetricKeyAlgorithm::from(*i))
                    .collect()
            )
        );
    }

    #[test]
    fn test_unknown_revocation_code() {
        let revocation = "-----BEGIN PGP SIGNATURE-----

wsASBCAWCgCEBYJlrwiYCRACvMqAWdPpHUcUAAAAAAAeACBzYWx0QG5vdGF0aW9u
cy5zZXF1b2lhLXBncC5vcmfPfjVZJ9PXSt4854s05WU+Tj5QZwuhA5+LEHEUborP
PxQdQnJldm9jYXRpb24gbWVzc2FnZRYhBKfuT6/w5BLl1XTGUgK8yoBZ0+kdAABi
lQEAkpvZ3A2RGtRdCne/dOZtqoX7oCCZKCPyfZS9I9roc5oBAOj4aklEBejYuTKF
SW+kj0jFDKC2xb/o8hbkTpwPtsoI
=0ajX
-----END PGP SIGNATURE-----";

        let (sig, _) = DetachedSignature::from_armor_single(revocation.as_bytes()).unwrap();

        let rc = sig.signature.revocation_reason_code();

        assert!(rc.is_some());
        assert!(matches!(rc.unwrap(), RevocationCode::Other(0x42)));
    }
}