xml-sec 0.1.16

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
//! Digest computation for XMLDSig `<Reference>` processing.
//!
//! Implements [XMLDSig §6.1](https://www.w3.org/TR/xmldsig-core1/#sec-DigestMethod):
//! compute message digests over transform output bytes using SHA-family algorithms.
//!
//! All digest computation uses RustCrypto hash implementations.

use subtle::ConstantTimeEq;

/// Digest algorithms supported by XMLDSig.
///
/// SHA-1 is disabled for signing by default and requires explicit policy opt-in.
/// SHA-256 is the recommended default for new signatures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DigestAlgorithm {
    /// SHA-1 (160-bit). Disabled for signing by default.
    Sha1,
    /// SHA-224 (224-bit), required by XMLDSig 1.1 interoperability profiles.
    Sha224,
    /// SHA-256 (256-bit). Default for SAML.
    Sha256,
    /// SHA-384 (384-bit).
    Sha384,
    /// SHA-512 (512-bit).
    Sha512,
}

impl DigestAlgorithm {
    /// Parse a digest algorithm from its XML namespace URI.
    ///
    /// Returns `None` for unrecognized URIs.
    ///
    /// # URIs
    ///
    /// | Algorithm | URI |
    /// |-----------|-----|
    /// | SHA-1 | `http://www.w3.org/2000/09/xmldsig#sha1` |
    /// | SHA-224 | `http://www.w3.org/2001/04/xmldsig-more#sha224` |
    /// | SHA-256 | `http://www.w3.org/2001/04/xmlenc#sha256` |
    /// | SHA-384 | `http://www.w3.org/2001/04/xmldsig-more#sha384` |
    /// | SHA-512 | `http://www.w3.org/2001/04/xmlenc#sha512` |
    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/xmldsig-more#sha224" => Some(Self::Sha224),
            "http://www.w3.org/2001/04/xmlenc#sha256" => Some(Self::Sha256),
            "http://www.w3.org/2001/04/xmldsig-more#sha384" => Some(Self::Sha384),
            "http://www.w3.org/2001/04/xmlenc#sha512" => Some(Self::Sha512),
            _ => None,
        }
    }

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

    /// Whether this algorithm is allowed for signing (not just verification).
    ///
    /// SHA-1 is deprecated and disabled by secure signing defaults. An explicit
    /// signing policy allowlist can enable it for a trusted compatibility boundary.
    pub fn signing_allowed(self) -> bool {
        !matches!(self, Self::Sha1)
    }

    /// The expected output length in bytes.
    pub fn output_len(self) -> usize {
        match self {
            Self::Sha1 => 20,
            Self::Sha224 => 28,
            Self::Sha256 => 32,
            Self::Sha384 => 48,
            Self::Sha512 => 64,
        }
    }
}

/// Compute the digest of `data` using the specified algorithm.
///
/// Returns the raw digest bytes (not base64-encoded).
pub fn compute_digest(algorithm: DigestAlgorithm, data: &[u8]) -> Vec<u8> {
    compute_digest_with_provider(crate::provider::default_provider(), algorithm, data)
        .expect("default provider advertises every XMLDSig digest")
}

/// Compute a digest with an explicitly selected provider.
pub fn compute_digest_with_provider(
    provider: &dyn crate::provider::CryptoProvider,
    algorithm: DigestAlgorithm,
    data: &[u8],
) -> Result<Vec<u8>, crate::provider::ProviderError> {
    provider.require_capability(crate::provider::ProviderCapability::Digest(algorithm))?;
    let digest = provider.digest(algorithm, data)?;
    let expected = algorithm.output_len();
    if digest.len() != expected {
        return Err(crate::provider::ProviderError::InvalidOutputSize {
            operation: crate::provider::ProviderOperation::Digest,
            expected,
            actual: digest.len(),
        });
    }
    Ok(digest)
}

/// Constant-time comparison of two byte slices.
///
/// Returns `true` if and only if `a` and `b` have equal length and identical
/// content. Execution time depends only on the length of the slices, not on
/// where they differ — preventing timing side-channel attacks on digest
/// comparison.
///
/// Uses `subtle` constant-time equality.
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.ct_eq(b).into()
}

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

    struct RejectingDigestProvider {
        output: Option<Vec<u8>>,
    }

    impl crate::provider::CryptoProvider for RejectingDigestProvider {
        fn name(&self) -> &'static str {
            "rejecting-digest"
        }

        fn supports(&self, capability: crate::provider::ProviderCapability<'_>) -> bool {
            if self.output.is_none()
                && matches!(capability, crate::provider::ProviderCapability::Digest(_))
            {
                return false;
            }
            crate::provider::default_provider().supports(capability)
        }

        fn fill_random(&self, output: &mut [u8]) -> Result<(), crate::provider::ProviderError> {
            crate::provider::default_provider().fill_random(output)
        }

        fn derive_key(
            &self,
            parameters: &crate::provider::KdfParameters<'_>,
            secret: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().derive_key(parameters, secret)
        }

        fn digest(
            &self,
            _algorithm: DigestAlgorithm,
            _data: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            if let Some(output) = &self.output {
                return Ok(output.clone());
            }
            panic!("an unavailable digest capability must not be dispatched")
        }

        fn sign(
            &self,
            key: &dyn super::super::SigningKey,
            algorithm: super::super::SignatureAlgorithm,
            data: &[u8],
        ) -> Result<Vec<u8>, super::super::SigningKeyError> {
            crate::provider::default_provider().sign(key, algorithm, data)
        }

        fn verify(
            &self,
            key: &dyn super::super::VerifyingKey,
            algorithm: super::super::SignatureAlgorithm,
            data: &[u8],
            signature: &[u8],
        ) -> Result<bool, super::super::DsigError> {
            crate::provider::default_provider().verify(key, algorithm, data, signature)
        }

        #[cfg(feature = "xmlenc")]
        fn encrypt_data(
            &self,
            algorithm: crate::xmlenc::DataEncryptionAlgorithm,
            key: &[u8],
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().encrypt_data(algorithm, key, plaintext)
        }

        #[cfg(feature = "xmlenc")]
        fn decrypt_data(
            &self,
            algorithm: crate::xmlenc::DataEncryptionAlgorithm,
            key: &[u8],
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().decrypt_data(algorithm, key, ciphertext)
        }

        #[cfg(feature = "xmlenc")]
        fn wrap_key(
            &self,
            algorithm: crate::xmlenc::KeyWrapAlgorithm,
            kek: &[u8],
            key: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().wrap_key(algorithm, kek, key)
        }

        #[cfg(feature = "xmlenc")]
        fn unwrap_key(
            &self,
            algorithm: crate::xmlenc::KeyWrapAlgorithm,
            kek: &[u8],
            wrapped: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().unwrap_key(algorithm, kek, wrapped)
        }

        #[cfg(feature = "xmlenc")]
        fn transport_key(
            &self,
            key: &dyn crate::provider::KeyTransportKey,
            parameters: &crate::xmlenc::RsaOaepParameters,
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().transport_key(key, parameters, plaintext)
        }

        #[cfg(feature = "xmlenc")]
        fn recover_key(
            &self,
            key: &dyn crate::provider::KeyRecoveryKey,
            parameters: &crate::xmlenc::RsaOaepParameters,
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().recover_key(key, parameters, ciphertext)
        }
    }

    #[test]
    fn explicit_provider_digest_failures_are_returned() {
        // A restricted provider is caller-controlled and must never turn an
        // unsupported document-selected digest into a process panic.
        assert!(matches!(
            compute_digest_with_provider(
                &RejectingDigestProvider { output: None },
                DigestAlgorithm::Sha256,
                b"x"
            ),
            Err(crate::provider::ProviderError::Unsupported { .. })
        ));
    }

    #[test]
    fn explicit_provider_digest_output_must_match_the_algorithm() {
        // The facade, rather than an interchangeable provider, owns the XMLDSig
        // algorithm contract and must reject bytes its own parser cannot accept.
        for actual in [0, 31, 33] {
            assert!(matches!(
                compute_digest_with_provider(
                    &RejectingDigestProvider {
                        output: Some(vec![0_u8; actual]),
                    },
                    DigestAlgorithm::Sha256,
                    b"x",
                ),
                Err(crate::provider::ProviderError::InvalidOutputSize {
                    operation: crate::provider::ProviderOperation::Digest,
                    expected: 32,
                    actual: output_len,
                }) if output_len == actual
            ));
        }

        assert_eq!(
            compute_digest_with_provider(
                &RejectingDigestProvider {
                    output: Some(vec![7_u8; 32]),
                },
                DigestAlgorithm::Sha256,
                b"x",
            ),
            Ok(vec![7_u8; 32]),
        );
    }

    // ── from_uri / uri round-trip ────────────────────────────────────

    #[test]
    fn from_uri_sha1() {
        let algo = DigestAlgorithm::from_uri("http://www.w3.org/2000/09/xmldsig#sha1");
        assert_eq!(algo, Some(DigestAlgorithm::Sha1));
    }

    #[test]
    fn from_uri_sha256() {
        let algo = DigestAlgorithm::from_uri("http://www.w3.org/2001/04/xmlenc#sha256");
        assert_eq!(algo, Some(DigestAlgorithm::Sha256));
    }

    #[test]
    fn from_uri_sha384() {
        let algo = DigestAlgorithm::from_uri("http://www.w3.org/2001/04/xmldsig-more#sha384");
        assert_eq!(algo, Some(DigestAlgorithm::Sha384));
    }

    #[test]
    fn from_uri_sha512() {
        let algo = DigestAlgorithm::from_uri("http://www.w3.org/2001/04/xmlenc#sha512");
        assert_eq!(algo, Some(DigestAlgorithm::Sha512));
    }

    #[test]
    fn from_uri_unknown() {
        assert_eq!(
            DigestAlgorithm::from_uri("http://example.com/unknown"),
            None
        );
    }

    #[test]
    fn uri_round_trip() {
        for algo in [
            DigestAlgorithm::Sha1,
            DigestAlgorithm::Sha256,
            DigestAlgorithm::Sha384,
            DigestAlgorithm::Sha512,
        ] {
            assert_eq!(
                DigestAlgorithm::from_uri(algo.uri()),
                Some(algo),
                "round-trip failed for {algo:?}"
            );
        }
    }

    // ── signing_allowed ──────────────────────────────────────────────

    #[test]
    fn sha1_verify_only() {
        assert!(!DigestAlgorithm::Sha1.signing_allowed());
    }

    #[test]
    fn sha256_signing_allowed() {
        assert!(DigestAlgorithm::Sha256.signing_allowed());
    }

    #[test]
    fn sha384_signing_allowed() {
        assert!(DigestAlgorithm::Sha384.signing_allowed());
    }

    #[test]
    fn sha512_signing_allowed() {
        assert!(DigestAlgorithm::Sha512.signing_allowed());
    }

    // ── output_len ───────────────────────────────────────────────────

    #[test]
    fn output_lengths() {
        assert_eq!(DigestAlgorithm::Sha1.output_len(), 20);
        assert_eq!(DigestAlgorithm::Sha256.output_len(), 32);
        assert_eq!(DigestAlgorithm::Sha384.output_len(), 48);
        assert_eq!(DigestAlgorithm::Sha512.output_len(), 64);
    }

    #[test]
    fn sha224_uri_round_trips_and_has_standard_width() {
        let algorithm = DigestAlgorithm::from_uri("http://www.w3.org/2001/04/xmldsig-more#sha224")
            .expect("XMLDSig 1.1 SHA-224 must be recognized");

        assert_eq!(
            algorithm.uri(),
            "http://www.w3.org/2001/04/xmldsig-more#sha224"
        );
        assert_eq!(algorithm.output_len(), 28);
        assert!(algorithm.signing_allowed());
    }

    // ── Known-answer tests (KAT) ────────────────────────────────────
    // Reference values computed with `echo -n "..." | openssl dgst -sha*`

    #[test]
    fn sha1_empty() {
        // SHA-1("") = da39a3ee5e6b4b0d3255bfef95601890afd80709
        let digest = compute_digest(DigestAlgorithm::Sha1, b"");
        assert_eq!(digest.len(), 20);
        assert_eq!(hex(&digest), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    }

    #[test]
    fn sha256_empty() {
        // SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
        let digest = compute_digest(DigestAlgorithm::Sha256, b"");
        assert_eq!(digest.len(), 32);
        assert_eq!(
            hex(&digest),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn sha224_empty() {
        let digest = compute_digest(
            DigestAlgorithm::from_uri("http://www.w3.org/2001/04/xmldsig-more#sha224")
                .expect("SHA-224 URI must be recognized"),
            b"",
        );
        assert_eq!(
            hex(&digest),
            "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f"
        );
    }

    #[test]
    fn sha384_empty() {
        // SHA-384("") = 38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b
        let digest = compute_digest(DigestAlgorithm::Sha384, b"");
        assert_eq!(digest.len(), 48);
        assert_eq!(
            hex(&digest),
            "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"
        );
    }

    #[test]
    fn sha512_empty() {
        // SHA-512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
        let digest = compute_digest(DigestAlgorithm::Sha512, b"");
        assert_eq!(digest.len(), 64);
        assert_eq!(
            hex(&digest),
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
        );
    }

    #[test]
    fn sha256_hello_world() {
        // SHA-256("hello world") = b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
        let digest = compute_digest(DigestAlgorithm::Sha256, b"hello world");
        assert_eq!(
            hex(&digest),
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );
    }

    #[test]
    fn sha1_abc() {
        // SHA-1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d
        let digest = compute_digest(DigestAlgorithm::Sha1, b"abc");
        assert_eq!(hex(&digest), "a9993e364706816aba3e25717850c26c9cd0d89d");
    }

    // ── constant_time_eq ─────────────────────────────────────────────

    #[test]
    fn constant_time_eq_identical() {
        let a = compute_digest(DigestAlgorithm::Sha256, b"test");
        let b = compute_digest(DigestAlgorithm::Sha256, b"test");
        assert!(constant_time_eq(&a, &b));
    }

    #[test]
    fn constant_time_eq_different_content() {
        let a = compute_digest(DigestAlgorithm::Sha256, b"test1");
        let b = compute_digest(DigestAlgorithm::Sha256, b"test2");
        assert!(!constant_time_eq(&a, &b));
    }

    #[test]
    fn constant_time_eq_different_lengths() {
        assert!(!constant_time_eq(&[1, 2, 3], &[1, 2]));
    }

    #[test]
    fn constant_time_eq_empty() {
        assert!(constant_time_eq(&[], &[]));
    }

    // ── Digest output matches expected length ────────────────────────

    #[test]
    fn digest_output_matches_declared_length() {
        let data = b"test data for length verification";
        for algo in [
            DigestAlgorithm::Sha1,
            DigestAlgorithm::Sha256,
            DigestAlgorithm::Sha384,
            DigestAlgorithm::Sha512,
        ] {
            let digest = compute_digest(algo, data);
            assert_eq!(
                digest.len(),
                algo.output_len(),
                "output length mismatch for {algo:?}"
            );
        }
    }

    /// Helper: format bytes as lowercase hex string.
    fn hex(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }
}