xml-sec 0.1.14

Pure Rust XML Security: XMLDSig, XMLEnc, C14N. Drop-in replacement for libxmlsec1.
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
//! Public XMLEnc data structures and errors.

use std::{fmt, sync::Arc};

use rsa::RsaPublicKey;

/// XML Encryption 1.0 namespace.
pub const XMLENC_NS: &str = "http://www.w3.org/2001/04/xmlenc#";
/// XML Encryption 1.1 namespace.
pub const XMLENC11_NS: &str = "http://www.w3.org/2009/xmlenc11#";
/// XML Signature namespace, used by OAEP parameter elements.
pub const XMLDSIG_NS: &str = "http://www.w3.org/2000/09/xmldsig#";

/// Maximum normalized base64 text accepted from a `CipherValue`.
pub const MAX_CIPHER_VALUE_BASE64_LEN: usize =
    crate::hard_limits::ENCRYPTION_CIPHER_VALUE_BASE64_BYTE_CEILING;
/// The `Type` attribute on an `EncryptedData` element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EncryptedDataType {
    /// The plaintext contains one complete XML element.
    Element,
    /// The plaintext contains the encrypted element's child content.
    Content,
    /// An application-defined or empty type hint whose plaintext remains opaque.
    Other(String),
}

/// Supported content-encryption algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataEncryptionAlgorithm {
    /// AES-128 in CBC mode with XMLEnc padding.
    Aes128Cbc,
    /// AES-256 in CBC mode with XMLEnc padding.
    Aes256Cbc,
    /// AES-128 in GCM mode.
    Aes128Gcm,
    /// AES-256 in GCM mode.
    Aes256Gcm,
}

impl DataEncryptionAlgorithm {
    /// Parse a supported XMLEnc content-encryption URI.
    pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
        match uri {
            "http://www.w3.org/2001/04/xmlenc#aes128-cbc" => Ok(Self::Aes128Cbc),
            "http://www.w3.org/2001/04/xmlenc#aes256-cbc" => Ok(Self::Aes256Cbc),
            "http://www.w3.org/2009/xmlenc11#aes128-gcm" => Ok(Self::Aes128Gcm),
            "http://www.w3.org/2009/xmlenc11#aes256-gcm" => Ok(Self::Aes256Gcm),
            _ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
        }
    }

    /// Required symmetric key length in bytes.
    pub const fn key_len(self) -> usize {
        match self {
            Self::Aes128Cbc | Self::Aes128Gcm => 16,
            Self::Aes256Cbc | Self::Aes256Gcm => 32,
        }
    }

    /// Return the standard XMLEnc algorithm URI.
    pub const fn uri(self) -> &'static str {
        match self {
            Self::Aes128Cbc => "http://www.w3.org/2001/04/xmlenc#aes128-cbc",
            Self::Aes256Cbc => "http://www.w3.org/2001/04/xmlenc#aes256-cbc",
            Self::Aes128Gcm => "http://www.w3.org/2009/xmlenc11#aes128-gcm",
            Self::Aes256Gcm => "http://www.w3.org/2009/xmlenc11#aes256-gcm",
        }
    }

    /// Minimum standard wire length for ciphertext produced by this algorithm.
    pub(crate) const fn minimum_ciphertext_len(self) -> usize {
        match self {
            Self::Aes128Cbc | Self::Aes256Cbc => 32,
            Self::Aes128Gcm | Self::Aes256Gcm => 28,
        }
    }

    /// Exact wire length produced when encrypting the given plaintext length.
    pub(crate) fn ciphertext_len_for_plaintext(self, plaintext_len: usize) -> Option<usize> {
        match self {
            Self::Aes128Cbc | Self::Aes256Cbc => (plaintext_len / 16)
                .checked_add(1)?
                .checked_mul(16)?
                .checked_add(16),
            Self::Aes128Gcm | Self::Aes256Gcm => plaintext_len.checked_add(28),
        }
    }
}

pub(crate) fn validate_ciphertext_framing(
    algorithm: DataEncryptionAlgorithm,
    ciphertext_len: usize,
) -> Result<(), XmlEncError> {
    let minimum = algorithm.minimum_ciphertext_len();
    if ciphertext_len < minimum {
        let algorithm_name = match algorithm {
            DataEncryptionAlgorithm::Aes128Cbc | DataEncryptionAlgorithm::Aes256Cbc => "AES-CBC",
            DataEncryptionAlgorithm::Aes128Gcm | DataEncryptionAlgorithm::Aes256Gcm => "AES-GCM",
        };
        return Err(XmlEncError::DataTooShort {
            algorithm: algorithm_name,
            minimum,
            actual: ciphertext_len,
        });
    }
    if matches!(
        algorithm,
        DataEncryptionAlgorithm::Aes128Cbc | DataEncryptionAlgorithm::Aes256Cbc
    ) && !(ciphertext_len - 16).is_multiple_of(16)
    {
        return Err(XmlEncError::InvalidCbcCiphertextLength(ciphertext_len - 16));
    }
    Ok(())
}

impl KeyTransportAlgorithm {
    /// Parse a supported XMLEnc key-transport URI.
    pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
        match uri {
            "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" => Ok(Self::RsaOaepMgf1p),
            "http://www.w3.org/2009/xmlenc11#rsa-oaep" => Ok(Self::RsaOaep11),
            _ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
        }
    }

    /// Return the standard XMLEnc key-transport URI.
    pub const fn uri(self) -> &'static str {
        match self {
            Self::RsaOaepMgf1p => "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p",
            Self::RsaOaep11 => "http://www.w3.org/2009/xmlenc11#rsa-oaep",
        }
    }
}

impl KeyWrapAlgorithm {
    /// Parse a supported XMLEnc symmetric key-wrap URI.
    pub fn from_uri(uri: &str) -> Result<Self, XmlEncError> {
        match uri {
            "http://www.w3.org/2001/04/xmlenc#kw-aes128" => Ok(Self::AesKw128),
            "http://www.w3.org/2001/04/xmlenc#kw-aes256" => Ok(Self::AesKw256),
            _ => Err(XmlEncError::UnsupportedAlgorithm(uri.to_owned())),
        }
    }

    /// Required key-encryption-key length in bytes.
    pub const fn key_len(self) -> usize {
        match self {
            Self::AesKw128 => 16,
            Self::AesKw256 => 32,
        }
    }

    /// Return the standard XMLEnc key-wrap URI.
    pub const fn uri(self) -> &'static str {
        match self {
            Self::AesKw128 => "http://www.w3.org/2001/04/xmlenc#kw-aes128",
            Self::AesKw256 => "http://www.w3.org/2001/04/xmlenc#kw-aes256",
        }
    }
}

/// Supported asymmetric session-key transport algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyTransportAlgorithm {
    /// XML Encryption 1.0 OAEP with SHA-1 and MGF1-SHA-1.
    RsaOaepMgf1p,
    /// XML Encryption 1.1 OAEP with explicitly parsed digest and MGF settings.
    RsaOaep11,
}

/// Supported symmetric key-wrap algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyWrapAlgorithm {
    /// RFC 3394 AES key wrap with a 128-bit KEK.
    AesKw128,
    /// RFC 3394 AES key wrap with a 256-bit KEK.
    AesKw256,
}

/// Digest algorithms accepted by RSA-OAEP encryption.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OaepDigestAlgorithm {
    /// SHA-1, retained for legacy XMLEnc OAEP interoperability.
    Sha1,
    /// SHA-256.
    Sha256,
    /// SHA-384.
    Sha384,
    /// SHA-512.
    Sha512,
}

impl OaepDigestAlgorithm {
    /// Parse a digest URI accepted by XML Encryption and libxmlsec1.
    pub fn from_uri(uri: &str) -> Option<Self> {
        match uri {
            "http://www.w3.org/2000/09/xmldsig#sha1" => Some(Self::Sha1),
            "http://www.w3.org/2001/04/xmlenc#sha256" => Some(Self::Sha256),
            "http://www.w3.org/2001/04/xmlenc#sha384"
            | "http://www.w3.org/2001/04/xmldsig-more#sha384" => Some(Self::Sha384),
            "http://www.w3.org/2001/04/xmlenc#sha512" => Some(Self::Sha512),
            _ => None,
        }
    }

    /// Parse an XML Encryption 1.1 MGF1 URI.
    pub fn from_mgf_uri(uri: &str) -> Option<Self> {
        match uri {
            "http://www.w3.org/2009/xmlenc11#mgf1sha1" => Some(Self::Sha1),
            "http://www.w3.org/2009/xmlenc11#mgf1sha256" => Some(Self::Sha256),
            "http://www.w3.org/2009/xmlenc11#mgf1sha384" => Some(Self::Sha384),
            "http://www.w3.org/2009/xmlenc11#mgf1sha512" => Some(Self::Sha512),
            _ => None,
        }
    }

    /// Return the standard digest URI.
    pub const fn uri(self) -> &'static str {
        match self {
            Self::Sha1 => "http://www.w3.org/2000/09/xmldsig#sha1",
            Self::Sha256 => "http://www.w3.org/2001/04/xmlenc#sha256",
            Self::Sha384 => "http://www.w3.org/2001/04/xmlenc#sha384",
            Self::Sha512 => "http://www.w3.org/2001/04/xmlenc#sha512",
        }
    }

    /// Return the XML Encryption 1.1 MGF URI for this digest.
    pub const fn mgf_uri(self) -> &'static str {
        match self {
            Self::Sha1 => "http://www.w3.org/2009/xmlenc11#mgf1sha1",
            Self::Sha256 => "http://www.w3.org/2009/xmlenc11#mgf1sha256",
            Self::Sha384 => "http://www.w3.org/2009/xmlenc11#mgf1sha384",
            Self::Sha512 => "http://www.w3.org/2009/xmlenc11#mgf1sha512",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::OaepDigestAlgorithm;

    #[test]
    fn oaep_sha384_accepts_both_interoperable_digest_uris() {
        // The canonical XML Encryption spelling and libxmlsec1's XMLDSig-more
        // spelling identify the same OAEP digest algorithm.
        for uri in [
            "http://www.w3.org/2001/04/xmlenc#sha384",
            "http://www.w3.org/2001/04/xmldsig-more#sha384",
        ] {
            assert_eq!(
                OaepDigestAlgorithm::from_uri(uri),
                Some(OaepDigestAlgorithm::Sha384)
            );
        }
    }

    #[test]
    fn oaep_mgf_uris_round_trip() {
        for algorithm in [
            OaepDigestAlgorithm::Sha1,
            OaepDigestAlgorithm::Sha256,
            OaepDigestAlgorithm::Sha384,
            OaepDigestAlgorithm::Sha512,
        ] {
            assert_eq!(
                OaepDigestAlgorithm::from_mgf_uri(algorithm.mgf_uri()),
                Some(algorithm)
            );
        }
        assert_eq!(
            OaepDigestAlgorithm::from_mgf_uri("urn:unsupported-mgf"),
            None
        );
    }
}

/// RSA-OAEP parameters emitted in an `EncryptedKey`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RsaOaepParameters {
    /// XMLEnc 1.0 legacy OAEP or XMLEnc 1.1 configurable OAEP.
    pub algorithm: KeyTransportAlgorithm,
    /// Digest used by OAEP.
    pub digest: OaepDigestAlgorithm,
    /// Digest used by MGF1.
    pub mgf_digest: OaepDigestAlgorithm,
    /// Optional OAEP label bytes.
    pub label: Vec<u8>,
}

impl RsaOaepParameters {
    /// Create legacy OAEP parameters with SHA-1 and MGF1-SHA-1.
    pub fn legacy() -> Self {
        Self {
            algorithm: KeyTransportAlgorithm::RsaOaepMgf1p,
            digest: OaepDigestAlgorithm::Sha1,
            mgf_digest: OaepDigestAlgorithm::Sha1,
            label: Vec::new(),
        }
    }

    /// Create XMLEnc 1.1 OAEP parameters.
    pub fn xmlenc11(digest: OaepDigestAlgorithm, mgf_digest: OaepDigestAlgorithm) -> Self {
        Self {
            algorithm: KeyTransportAlgorithm::RsaOaep11,
            digest,
            mgf_digest,
            label: Vec::new(),
        }
    }

    /// Set the OAEP label bytes.
    pub fn label(mut self, label: impl Into<Vec<u8>>) -> Self {
        self.label = label.into();
        self
    }
}

impl Default for RsaOaepParameters {
    fn default() -> Self {
        Self::xmlenc11(OaepDigestAlgorithm::Sha256, OaepDigestAlgorithm::Sha256)
    }
}

/// One recipient of a generated content-encryption key.
#[derive(Clone)]
pub enum EncryptionRecipient {
    /// Wrap the content key with an RSA public key and OAEP.
    RsaOaep {
        /// Opaque recipient public-key handle.
        public_key: Arc<dyn crate::provider::KeyTransportKey>,
        /// OAEP algorithm parameters.
        parameters: RsaOaepParameters,
        /// Optional `Recipient` attribute.
        recipient: Option<String>,
        /// Optional key hint inside the encrypted key's `KeyInfo`.
        key_name: Option<String>,
    },
    /// Wrap the content key with a pre-shared AES KEK.
    AesKeyWrap {
        /// AES key-encryption key.
        kek: Vec<u8>,
        /// RFC 3394 key-wrap variant.
        algorithm: KeyWrapAlgorithm,
        /// Optional `Recipient` attribute.
        recipient: Option<String>,
        /// Optional key hint inside the encrypted key's `KeyInfo`.
        key_name: Option<String>,
    },
}

impl fmt::Debug for EncryptionRecipient {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RsaOaep {
                parameters,
                recipient,
                key_name,
                ..
            } => formatter
                .debug_struct("EncryptionRecipient::RsaOaep")
                .field("public_key", &"[PUBLIC KEY]")
                .field("parameters", parameters)
                .field("recipient", recipient)
                .field("key_name", key_name)
                .finish(),
            Self::AesKeyWrap {
                algorithm,
                recipient,
                key_name,
                ..
            } => formatter
                .debug_struct("EncryptionRecipient::AesKeyWrap")
                .field("kek", &"[REDACTED]")
                .field("algorithm", algorithm)
                .field("recipient", recipient)
                .field("key_name", key_name)
                .finish(),
        }
    }
}

impl EncryptionRecipient {
    /// Create an RSA-OAEP recipient using SHA-256 and MGF1-SHA-256.
    ///
    /// XMLEnc 1.1 assigns SHA-1 and MGF1-SHA-1 when these parameters are
    /// omitted. Serialized keys therefore include both algorithm values
    /// explicitly instead of relying on the specification's legacy defaults.
    pub fn rsa_oaep(public_key: RsaPublicKey) -> Self {
        Self::provider_key_transport(Arc::new(crate::provider::RustCryptoRsaPublicKey::new(
            public_key,
        )))
    }

    /// Create an RSA-OAEP recipient from an opaque provider key handle.
    pub fn provider_key_transport(public_key: Arc<dyn crate::provider::KeyTransportKey>) -> Self {
        Self::RsaOaep {
            public_key,
            parameters: RsaOaepParameters::default(),
            recipient: None,
            key_name: None,
        }
    }

    /// Create an AES Key Wrap recipient.
    pub fn aes_key_wrap(kek: impl Into<Vec<u8>>, algorithm: KeyWrapAlgorithm) -> Self {
        Self::AesKeyWrap {
            kek: kek.into(),
            algorithm,
            recipient: None,
            key_name: None,
        }
    }

    /// Override RSA-OAEP parameters.
    pub fn oaep_parameters(mut self, parameters: RsaOaepParameters) -> Self {
        if let Self::RsaOaep {
            parameters: current,
            ..
        } = &mut self
        {
            *current = parameters;
        }
        self
    }

    /// Set the recipient identifier emitted on `EncryptedKey`.
    pub fn recipient(mut self, value: impl Into<String>) -> Self {
        match &mut self {
            Self::RsaOaep { recipient, .. } | Self::AesKeyWrap { recipient, .. } => {
                *recipient = Some(value.into());
            }
        }
        self
    }

    /// Set the key name emitted inside the encrypted key's `KeyInfo`.
    pub fn key_name(mut self, value: impl Into<String>) -> Self {
        match &mut self {
            Self::RsaOaep { key_name, .. } | Self::AesKeyWrap { key_name, .. } => {
                *key_name = Some(value.into());
            }
        }
        self
    }
}

/// How generated `EncryptedData` replaces caller-owned XML.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplacementMode {
    /// Replace the selected element, including its start and end tags.
    ReplaceElement,
    /// Replace only the selected element's child content.
    ReplaceContent,
}

/// Result returned after encrypting bytes or XML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionResult {
    /// Complete `EncryptedData` XML fragment.
    pub encrypted_data_xml: String,
    /// Required caller-owned document replacement operation.
    pub replacement: ReplacementMode,
}

/// Caller-owned target selection for document encryption.
#[derive(Debug, Clone, Copy, Default)]
pub struct DocumentEncryptionOptions<'a> {
    /// Select an element by `Id`, `ID`, or `id`; `None` selects the document root.
    pub element_id: Option<&'a str>,
}

/// Parsed `EncryptionMethod` data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionMethod {
    /// Algorithm URI from the mandatory `Algorithm` attribute.
    pub algorithm: String,
    /// Optional explicit key size in bits.
    pub key_size_bits: Option<usize>,
    /// Digest URI used by XML Encryption 1.1 OAEP.
    pub oaep_digest: Option<String>,
    /// MGF URI used by XML Encryption 1.1 OAEP.
    pub mgf_algorithm: Option<String>,
    /// Decoded OAEP label bytes.
    pub oaep_params: Option<Vec<u8>>,
}

impl EncryptionMethod {
    /// Validate invariants imposed by the selected algorithm URI.
    ///
    /// Parsed XML and caller-constructed typed values share this check so the
    /// public typed API cannot express wire structures that XML parsing rejects.
    pub(crate) fn validate_structure(&self) -> Result<(), XmlEncError> {
        if self.key_size_bits == Some(0) {
            return Err(XmlEncError::InvalidStructure(
                "KeySize must be a positive integer".into(),
            ));
        }
        let is_legacy_oaep = self.algorithm == KeyTransportAlgorithm::RsaOaepMgf1p.uri();
        let is_oaep11 = self.algorithm == KeyTransportAlgorithm::RsaOaep11.uri();
        if (self.oaep_params.is_some()
            || self.oaep_digest.is_some()
            || self.mgf_algorithm.is_some())
            && !is_legacy_oaep
            && !is_oaep11
        {
            return Err(XmlEncError::InvalidStructure(
                "OAEP parameters are only valid for RSA-OAEP EncryptionMethod".into(),
            ));
        }
        if self.mgf_algorithm.is_some() && !is_oaep11 {
            return Err(XmlEncError::InvalidStructure(
                "MGF is only valid for XML Encryption 1.1 RSA-OAEP".into(),
            ));
        }
        if let (Some(actual), Some(expected)) =
            (self.key_size_bits, fixed_aes_key_size(&self.algorithm))
            && actual != expected
        {
            return Err(XmlEncError::InvalidStructure(format!(
                "EncryptionMethod {} requires KeySize {expected}, got {actual}",
                self.algorithm
            )));
        }
        Ok(())
    }
}

fn fixed_aes_key_size(algorithm: &str) -> Option<usize> {
    let key_len = DataEncryptionAlgorithm::from_uri(algorithm)
        .map(DataEncryptionAlgorithm::key_len)
        .or_else(|_| KeyWrapAlgorithm::from_uri(algorithm).map(KeyWrapAlgorithm::key_len))
        .ok()?;
    Some(key_len * 8)
}

/// Inline ciphertext data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CipherData {
    /// Whitespace-normalized base64 text from `CipherValue`.
    pub value: String,
}

/// Parsed embedded `EncryptedKey` used to recover a content-encryption key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedKey {
    /// Optional XML identifier.
    pub id: Option<String>,
    /// Optional recipient hint.
    pub recipient: Option<String>,
    /// Optional direct `ds:KeyName` hint from the key's `KeyInfo`.
    pub key_name: Option<String>,
    /// Method which wrapped the session key.
    pub encryption_method: EncryptionMethod,
    /// Wrapped session-key bytes in base64 form.
    pub cipher_data: CipherData,
    /// Optional references identifying data or keys associated with this key.
    pub reference_list: Option<ReferenceList>,
    /// Optional name associated with the transported plaintext key.
    pub carried_key_name: Option<String>,
}

/// References associated with an `EncryptedKey`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReferenceList {
    /// URI references to `EncryptedData` elements encrypted with this key.
    pub data_references: Vec<String>,
    /// URI references to other `EncryptedKey` elements encrypted with this key.
    pub key_references: Vec<String>,
}

/// Parsed `EncryptedData` document fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedData {
    /// Optional XML identifier.
    pub id: Option<String>,
    /// Optional plaintext representation hint.
    pub encrypted_type: Option<EncryptedDataType>,
    /// Optional direct `ds:KeyName` hint from `KeyInfo`.
    pub key_name: Option<String>,
    /// Content-encryption method.
    pub encryption_method: EncryptionMethod,
    /// Embedded recipient session keys in `KeyInfo` document order.
    pub encrypted_keys: Vec<EncryptedKey>,
    /// Content ciphertext in base64 form.
    pub cipher_data: CipherData,
}

/// Plaintext returned from XMLEnc decryption.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecryptedContent {
    /// XML plaintext for `Element` and `Content` encrypted data.
    Xml(String),
    /// Binary plaintext when the encrypted data has no standard XML type hint.
    Bytes(Vec<u8>),
}

/// Errors raised while parsing, encrypting, resolving, or decrypting XMLEnc data.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum XmlEncError {
    /// The compiled encryption or decryption policy rejected an operation input.
    #[error("XML Encryption policy violation: {0}")]
    Policy(#[from] crate::policy::PolicyViolation),

    /// The selected cryptographic provider rejected or failed an operation.
    #[error("cryptographic provider error: {0}")]
    Provider(#[from] crate::provider::ProviderError),

    /// XML document parsing failed.
    #[error("XML parsing error: {0}")]
    XmlParse(#[from] roxmltree::Error),
    /// The owned XML document boundary rejected an identity or mutation.
    #[error("XML document error: {0}")]
    Document(#[from] crate::document::XmlDocumentError),
    /// Required child element or attribute was absent.
    #[error("missing required {0}")]
    MissingRequired(&'static str),
    /// The XML element order or namespace is invalid for the XMLEnc profile.
    #[error("invalid encrypted structure: {0}")]
    InvalidStructure(String),
    /// The selected operation-start node ID is absent or resolves ambiguously.
    #[error("selected node ID is missing or ambiguous: {id}")]
    SelectedNodeUnavailable {
        /// Caller-supplied node identifier.
        id: String,
    },
    /// An algorithm URI is not supported by this build.
    #[error("unsupported encryption algorithm: {0}")]
    UnsupportedAlgorithm(String),
    /// Base64 input is invalid or exceeds the configured input bound.
    #[error("invalid base64 data: {0}")]
    Base64(String),
    /// A decoded cipher value is too short for its algorithm's framing.
    #[error("{algorithm} ciphertext is too short: need at least {minimum} bytes, got {actual}")]
    DataTooShort {
        /// Algorithm name.
        algorithm: &'static str,
        /// Minimum valid byte length.
        minimum: usize,
        /// Actual byte length.
        actual: usize,
    },
    /// CBC ciphertext is not a non-empty multiple of the AES block size.
    #[error("AES-CBC ciphertext length must be a non-zero multiple of 16 bytes, got {0}")]
    InvalidCbcCiphertextLength(usize),
    /// XMLEnc random padding is invalid.
    ///
    /// No decrypted padding details are exposed. This does not authenticate CBC
    /// ciphertexts or make success/failure safe to expose to an attacker.
    #[error("invalid XMLEnc padding")]
    InvalidPadding,
    /// GCM authentication failed.
    #[error("AES-GCM authentication failed")]
    AeadAuthenticationFailed,
    /// A supplied content key is not the expected size.
    #[error("{algorithm:?} requires a {expected}-byte key, got {actual}")]
    InvalidKeySize {
        /// Content algorithm requiring the key.
        algorithm: DataEncryptionAlgorithm,
        /// Expected key size.
        expected: usize,
        /// Actual key size.
        actual: usize,
    },
    /// An unauthenticated content algorithm cannot safely select among keys.
    #[error(
        "{algorithm:?} cannot safely select among {actual} unordered decryption key candidates"
    )]
    AmbiguousKeyCandidates {
        /// Unauthenticated algorithm for which key success is ambiguous.
        algorithm: DataEncryptionAlgorithm,
        /// Number of unresolved candidate keys.
        actual: usize,
    },
    /// A supplied AES key-encryption key is not the size declared by EncryptedKey.
    #[error("{algorithm:?} requires a {expected}-byte KEK, got {actual}")]
    InvalidKekSize {
        /// Key-wrap algorithm requiring the KEK.
        algorithm: KeyWrapAlgorithm,
        /// Expected KEK size.
        expected: usize,
        /// Actual KEK size.
        actual: usize,
    },
    /// A wrapped-key input or provider output has invalid algorithm framing.
    #[error("wrapped-key value must be {expected} bytes, got {actual}")]
    InvalidWrappedKeyLength {
        /// Exact wrapped length required by the algorithm and key context.
        expected: usize,
        /// Actual input or provider output length.
        actual: usize,
    },
    /// Encryption configuration is internally inconsistent.
    #[error("invalid encryption configuration: {0}")]
    InvalidEncryptionConfig(String),
    /// No caller-provided resolver could supply a usable key.
    #[error("no suitable decryption key was resolved")]
    KeyNotFound,
    /// No `EncryptedData` matched the requested document selection.
    #[error("no matching EncryptedData element was found")]
    EncryptedDataNotFound,
    /// More than one `EncryptedData` matched the requested document selection.
    #[error("more than one EncryptedData element matched; select one by Id")]
    AmbiguousEncryptedData,
    /// No source element matched the requested encryption target.
    #[error("no matching element was found for encryption")]
    EncryptionTargetNotFound,
    /// More than one source element matched the requested encryption target.
    #[error("more than one element matched the encryption target")]
    AmbiguousEncryptionTarget,
    /// Document replacement requires an XML `Type` declaration.
    #[error("EncryptedData must declare Element or Content Type for document replacement")]
    ReplacementRequiresXml,
    /// RSA-OAEP session-key recovery failed.
    #[error("RSA-OAEP key unwrap failed: {0}")]
    Rsa(String),
    /// RSA-OAEP session-key wrapping failed.
    #[error("RSA-OAEP key wrap failed: {0}")]
    RsaEncrypt(String),
    /// RFC 3394 integrity validation failed while unwrapping a key.
    #[error("AES key unwrap failed integrity validation")]
    KeyWrapIntegrity,
    /// Operating-system randomness was unavailable.
    #[error("operating-system random number generation failed: {0}")]
    Rng(String),
    /// Generated XML could not be serialized.
    #[error("XML encryption serialization failed: {0}")]
    XmlSerialize(String),
    /// XML-declared plaintext could not be decoded as UTF-8.
    #[error("decrypted XML is not valid UTF-8: {0}")]
    Utf8(#[from] std::string::FromUtf8Error),
}

impl fmt::Display for DataEncryptionAlgorithm {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Aes128Cbc => "AES-128-CBC",
            Self::Aes256Cbc => "AES-256-CBC",
            Self::Aes128Gcm => "AES-128-GCM",
            Self::Aes256Gcm => "AES-256-GCM",
        })
    }
}