synta-certificate 0.2.6

X.509 certificate structures for synta ASN.1 library
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
//! Symmetric crypto traits and constant-time comparison.

use super::errors::{NoCryptoError, PrivateKeyError};

// ── HKDF output-length helper ─────────────────────────────────────────────────

/// Return the HMAC output length in bytes for a named digest algorithm.
///
/// Returns `None` for unknown algorithm names.  Used internally by
/// [`hkdf_extract`] and [`hkdf_expand`] to size the default salt and to
/// bound the number of expand rounds.
pub fn hmac_output_len(algorithm: &str) -> Option<usize> {
    match algorithm {
        "md5" => Some(16),
        "sha1" => Some(20),
        "sha224" => Some(28),
        "sha256" => Some(32),
        "sha384" => Some(48),
        "sha512" => Some(64),
        _ => None,
    }
}

// ── Constant-time comparison ──────────────────────────────────────────────────

/// Constant-time byte comparison.  Prevents timing side-channels.
///
/// XOR-accumulates all byte differences without any branch or early exit.
/// A backend-aware implementation is available through
/// [`HmacProvider::constant_time_eq`]; this free function is for callers
/// that do not have a backend instance.
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter()
        .zip(b.iter())
        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
        == 0
}

// ── Symmetric crypto traits ───────────────────────────────────────────────────

/// Hash arbitrary data with a named digest algorithm.
pub trait DataHasher {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Hash `data` using the algorithm named by `algorithm` (e.g. `"sha256"`).
    ///
    /// Returns the raw digest bytes on success.
    fn hash_data(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, Self::Error>;
}

/// HMAC computation and constant-time verification.
pub trait HmacProvider {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Compute HMAC of `data` under `key` using the given `algorithm`
    /// (e.g. `"sha256"`).  Returns the MAC bytes.
    fn hmac_compute(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, Self::Error>;

    /// Verify that HMAC of `data` under `key` equals `expected`.
    ///
    /// Implementations must compare in constant time to prevent timing attacks.
    /// Returns `Ok(())` if the MAC matches, or an error otherwise.
    fn hmac_verify(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), Self::Error>;

    /// Constant-time comparison of two byte slices.
    ///
    /// Returns `true` iff `a` and `b` have equal length and identical bytes,
    /// without leaking information through execution time.
    ///
    /// The default implementation uses XOR accumulation.  Backends may
    /// override with a formally-verified or hardware-accelerated alternative
    /// (e.g. `openssl::memcmp::eq`).
    fn constant_time_eq(&self, a: &[u8], b: &[u8]) -> bool {
        constant_time_eq(a, b)
    }
}

/// PBKDF2 (RFC 8018 §5.2) key derivation with HMAC-based PRF.
pub trait Pbkdf2Provider {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Derive `length` bytes from `password` and `salt` using PBKDF2-HMAC
    /// with the named `algorithm` (e.g. `"sha256"`) and `iterations` rounds.
    ///
    /// Returns the derived key bytes.
    fn pbkdf2_hmac(
        &self,
        algorithm: &str,
        password: &[u8],
        salt: &[u8],
        iterations: usize,
        length: usize,
    ) -> Result<Vec<u8>, Self::Error>;
}

/// AES-CBC, AES-GCM, and Triple-DES-CBC block-cipher encryption and decryption.
pub trait BlockCipherProvider {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Encrypt `plaintext` with AES-CBC under `key` and `iv`.
    ///
    /// When `pad` is `true` the plaintext is PKCS#7-padded to a block
    /// boundary before encryption.
    fn aes_cbc_encrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        plaintext: &[u8],
        pad: bool,
    ) -> Result<Vec<u8>, Self::Error>;

    /// Decrypt `ciphertext` with AES-CBC under `key` and `iv`.
    ///
    /// When `unpad` is `true` trailing PKCS#7 padding is stripped after
    /// decryption.
    fn aes_cbc_decrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        ciphertext: &[u8],
        unpad: bool,
    ) -> Result<Vec<u8>, Self::Error>;

    /// Encrypt `plaintext` with Triple-DES-EDE-CBC under `key` and `iv`.
    ///
    /// When `pad` is `true` the plaintext is PKCS#7-padded before encryption.
    fn des3_cbc_encrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        plaintext: &[u8],
        pad: bool,
    ) -> Result<Vec<u8>, Self::Error>;

    /// Decrypt `ciphertext` with Triple-DES-EDE-CBC under `key` and `iv`.
    ///
    /// When `unpad` is `true` trailing PKCS#7 padding is stripped after
    /// decryption.
    fn des3_cbc_decrypt(
        &self,
        key: &[u8],
        iv: &[u8],
        ciphertext: &[u8],
        unpad: bool,
    ) -> Result<Vec<u8>, Self::Error>;

    /// Encrypt `plaintext` with AES-GCM under `key` and `nonce`.
    ///
    /// `key` must be 16, 24, or 32 bytes; `nonce` must be 12 bytes.
    /// `aad` is additional authenticated data and may be empty.
    /// Returns `ciphertext ‖ tag` where the tag is 16 bytes.
    fn aes_gcm_encrypt(
        &self,
        key: &[u8],
        nonce: &[u8],
        plaintext: &[u8],
        aad: &[u8],
    ) -> Result<Vec<u8>, Self::Error>;

    /// Decrypt and verify `ciphertext_with_tag` with AES-GCM.
    ///
    /// The last 16 bytes of `ciphertext_with_tag` are the authentication tag.
    /// Returns `Err` if the tag does not match or the inputs are invalid.
    fn aes_gcm_decrypt(
        &self,
        key: &[u8],
        nonce: &[u8],
        ciphertext_with_tag: &[u8],
        aad: &[u8],
    ) -> Result<Vec<u8>, Self::Error>;
}

/// Cryptographically secure pseudo-random byte generation.
pub trait SecureRandom {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Fill `out` with cryptographically secure random bytes.
    fn rand_bytes(&self, out: &mut [u8]) -> Result<(), Self::Error>;
}

// ── StreamingHasher ───────────────────────────────────────────────────────────

/// A live streaming hash computation.
///
/// Created by [`StreamingHasher::new_hash`]; data is fed in with
/// [`update`]; the final digest is produced by [`finalize_boxed`].
///
/// `finalize_boxed` takes `Box<Self>` rather than `self` so that the trait is
/// object-safe and the state can be stored behind `Box<dyn HashState>`.
///
/// [`update`]: HashState::update
/// [`finalize_boxed`]: HashState::finalize_boxed
pub trait HashState: Send {
    /// Feed `data` into the running hash.
    fn update(&mut self, data: &[u8]);

    /// Consume the state and return the digest bytes.
    fn finalize_boxed(self: Box<Self>) -> Vec<u8>;
}

/// Create streaming hash states for a named digest algorithm.
pub trait StreamingHasher {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Begin a new incremental hash computation for `algorithm`
    /// (e.g. `"sha256"`, `"sha384"`, `"sha512"`).
    ///
    /// Returns a heap-allocated [`HashState`] that accepts further data via
    /// [`HashState::update`] and produces the digest via
    /// [`HashState::finalize_boxed`].
    fn new_hash(&self, algorithm: &str) -> Result<Box<dyn HashState>, Self::Error>;
}

// ── ErasedStreamingHasher ─────────────────────────────────────────────────────

/// Object-safe [`StreamingHasher`] variant with a type-erased error.
///
/// Used as the return type of [`default_streaming_hasher`] so that callers
/// receive a `Box<dyn ErasedStreamingHasher>` without naming the backend type.
/// The boxed value implements [`StreamingHasher`] directly via the blanket impl
/// below.
///
/// [`default_streaming_hasher`]: crate::default_streaming_hasher
pub trait ErasedStreamingHasher {
    /// Begin a new streaming hash; returns [`PrivateKeyError`] on failure.
    fn new_hash_erased(&self, algorithm: &str) -> Result<Box<dyn HashState>, PrivateKeyError>;
}

/// Blanket impl: `&dyn ErasedStreamingHasher` implements [`StreamingHasher`].
impl StreamingHasher for dyn ErasedStreamingHasher + '_ {
    type Error = PrivateKeyError;

    fn new_hash(&self, algorithm: &str) -> Result<Box<dyn HashState>, PrivateKeyError> {
        self.new_hash_erased(algorithm)
    }
}

/// Blanket impl: `Box<dyn ErasedStreamingHasher>` implements [`StreamingHasher`].
///
/// Allows the value returned by [`default_streaming_hasher`] to be used
/// directly wherever `impl StreamingHasher` is accepted.
///
/// [`default_streaming_hasher`]: crate::default_streaming_hasher
impl StreamingHasher for Box<dyn ErasedStreamingHasher> {
    type Error = PrivateKeyError;

    fn new_hash(&self, algorithm: &str) -> Result<Box<dyn HashState>, PrivateKeyError> {
        self.as_ref().new_hash_erased(algorithm)
    }
}

// ── ErasedDataHasher ──────────────────────────────────────────────────────────

/// Object-safe [`DataHasher`] variant with a type-erased error.
///
/// Used as the return type of [`default_data_hasher`] so that callers receive a
/// `Box<dyn ErasedDataHasher>` without naming the backend type.  The boxed value
/// implements [`DataHasher`] directly via the blanket impls below, so it can be
/// passed to any function that accepts `impl DataHasher` or `&dyn DataHasher`.
///
/// [`default_data_hasher`]: crate::default_data_hasher
pub trait ErasedDataHasher {
    /// Hash `data` with the named `algorithm` (e.g. `"sha256"`);
    /// returns [`PrivateKeyError`] on failure.
    fn hash_data_erased(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, PrivateKeyError>;
}

/// Blanket impl: `&dyn ErasedDataHasher` implements [`DataHasher`].
impl DataHasher for dyn ErasedDataHasher + '_ {
    type Error = PrivateKeyError;

    fn hash_data(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        self.hash_data_erased(algorithm, data)
    }
}

/// Blanket impl: `Box<dyn ErasedDataHasher>` implements [`DataHasher`].
///
/// Allows the value returned by [`default_data_hasher`] to be used directly
/// wherever `impl DataHasher` is accepted, without calling `.as_ref()`.
///
/// [`default_data_hasher`]: crate::default_data_hasher
impl DataHasher for Box<dyn ErasedDataHasher> {
    type Error = PrivateKeyError;

    fn hash_data(&self, algorithm: &str, data: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        self.as_ref().hash_data_erased(algorithm, data)
    }
}

// ── ErasedHmacProvider ────────────────────────────────────────────────────────

/// Object-safe [`HmacProvider`] variant with a type-erased error.
///
/// Used as the return type of [`default_hmac_provider`] so that callers receive
/// a `Box<dyn ErasedHmacProvider>` without naming the backend type.  The boxed
/// value implements [`HmacProvider`] directly via the blanket impls below.
///
/// [`default_hmac_provider`]: crate::default_hmac_provider
pub trait ErasedHmacProvider {
    /// Compute HMAC of `data` under `key` with the named `algorithm`;
    /// returns [`PrivateKeyError`] on failure.
    fn hmac_compute_erased(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, PrivateKeyError>;

    /// Verify that HMAC of `data` under `key` equals `expected` in constant
    /// time; returns [`PrivateKeyError`] on mismatch or backend error.
    fn hmac_verify_erased(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), PrivateKeyError>;
}

/// Blanket impl: `&dyn ErasedHmacProvider` implements [`HmacProvider`].
impl HmacProvider for dyn ErasedHmacProvider + '_ {
    type Error = PrivateKeyError;

    fn hmac_compute(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, PrivateKeyError> {
        self.hmac_compute_erased(algorithm, key, data)
    }

    fn hmac_verify(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), PrivateKeyError> {
        self.hmac_verify_erased(algorithm, key, data, expected)
    }
}

/// Blanket impl: `Box<dyn ErasedHmacProvider>` implements [`HmacProvider`].
///
/// Allows the value returned by [`default_hmac_provider`] to be used directly
/// wherever `impl HmacProvider` is accepted, without calling `.as_ref()`.
///
/// [`default_hmac_provider`]: crate::default_hmac_provider
impl HmacProvider for Box<dyn ErasedHmacProvider> {
    type Error = PrivateKeyError;

    fn hmac_compute(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
    ) -> Result<Vec<u8>, PrivateKeyError> {
        self.as_ref().hmac_compute_erased(algorithm, key, data)
    }

    fn hmac_verify(
        &self,
        algorithm: &str,
        key: &[u8],
        data: &[u8],
        expected: &[u8],
    ) -> Result<(), PrivateKeyError> {
        self.as_ref()
            .hmac_verify_erased(algorithm, key, data, expected)
    }
}

// ── No-op sentinel ────────────────────────────────────────────────────────────

/// No-op symmetric crypto implementation when no backend is compiled in.
pub struct NoSymmetricCrypto;

impl DataHasher for NoSymmetricCrypto {
    type Error = NoCryptoError;
    fn hash_data(&self, _: &str, _: &[u8]) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
}

impl HmacProvider for NoSymmetricCrypto {
    type Error = NoCryptoError;
    fn hmac_compute(&self, _: &str, _: &[u8], _: &[u8]) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn hmac_verify(&self, _: &str, _: &[u8], _: &[u8], _: &[u8]) -> Result<(), NoCryptoError> {
        Err(NoCryptoError)
    }
}

impl Pbkdf2Provider for NoSymmetricCrypto {
    type Error = NoCryptoError;
    fn pbkdf2_hmac(
        &self,
        _: &str,
        _: &[u8],
        _: &[u8],
        _: usize,
        _: usize,
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
}

impl BlockCipherProvider for NoSymmetricCrypto {
    type Error = NoCryptoError;
    fn aes_cbc_encrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: bool,
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn aes_cbc_decrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: bool,
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn des3_cbc_encrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: bool,
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn des3_cbc_decrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: bool,
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn aes_gcm_encrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: &[u8],
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
    fn aes_gcm_decrypt(
        &self,
        _: &[u8],
        _: &[u8],
        _: &[u8],
        _: &[u8],
    ) -> Result<Vec<u8>, NoCryptoError> {
        Err(NoCryptoError)
    }
}

impl SecureRandom for NoSymmetricCrypto {
    type Error = NoCryptoError;
    fn rand_bytes(&self, _: &mut [u8]) -> Result<(), NoCryptoError> {
        Err(NoCryptoError)
    }
}

impl ErasedDataHasher for NoSymmetricCrypto {
    fn hash_data_erased(&self, _: &str, _: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoCryptoError))
    }
}

impl ErasedStreamingHasher for NoSymmetricCrypto {
    fn new_hash_erased(&self, _: &str) -> Result<Box<dyn HashState>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoCryptoError))
    }
}

impl ErasedHmacProvider for NoSymmetricCrypto {
    fn hmac_compute_erased(&self, _: &str, _: &[u8], _: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoCryptoError))
    }

    fn hmac_verify_erased(
        &self,
        _: &str,
        _: &[u8],
        _: &[u8],
        _: &[u8],
    ) -> Result<(), PrivateKeyError> {
        Err(PrivateKeyError::new(NoCryptoError))
    }
}

impl ErasedStreamingHmacProvider for NoSymmetricCrypto {
    fn new_hmac_erased(&self, _: &str, _: &[u8]) -> Result<Box<dyn HmacState>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoCryptoError))
    }
}

// ── HmacState ─────────────────────────────────────────────────────────────────

/// A live streaming HMAC computation.
///
/// Created by [`StreamingHmacProvider::new_hmac`]; data is fed in with
/// [`update`]; the final MAC is produced by [`finalize_boxed`].
///
/// `finalize_boxed` takes `Box<Self>` rather than `self` so that the trait is
/// object-safe and the state can be stored behind `Box<dyn HmacState>`.
///
/// [`update`]: HmacState::update
/// [`finalize_boxed`]: HmacState::finalize_boxed
pub trait HmacState: Send {
    /// Feed `data` into the running HMAC computation.
    fn update(&mut self, data: &[u8]);

    /// Consume the state and return the MAC bytes.
    fn finalize_boxed(self: Box<Self>) -> Vec<u8>;
}

// ── StreamingHmacProvider ─────────────────────────────────────────────────────

/// Create streaming HMAC states for a named digest algorithm.
///
/// Unlike the one-shot [`HmacProvider::hmac_compute`], this trait lets callers
/// feed data incrementally — useful for large messages or when the input is
/// produced in chunks.
pub trait StreamingHmacProvider {
    type Error: std::error::Error + Send + Sync + 'static;

    /// Begin a new incremental HMAC computation for `algorithm`
    /// (e.g. `"sha256"`, `"sha384"`, `"sha512"`) keyed with `key`.
    ///
    /// Returns a heap-allocated [`HmacState`] that accepts further data via
    /// [`HmacState::update`] and produces the MAC via
    /// [`HmacState::finalize_boxed`].
    fn new_hmac(&self, algorithm: &str, key: &[u8]) -> Result<Box<dyn HmacState>, Self::Error>;
}

// ── ErasedStreamingHmacProvider ───────────────────────────────────────────────

/// Object-safe [`StreamingHmacProvider`] variant with a type-erased error.
///
/// Used as the return type of [`default_streaming_hmac_provider`] so that
/// callers receive a `Box<dyn ErasedStreamingHmacProvider>` without naming
/// the backend type.  The boxed value implements [`StreamingHmacProvider`]
/// directly via the blanket impl below.
///
/// [`default_streaming_hmac_provider`]: crate::default_streaming_hmac_provider
pub trait ErasedStreamingHmacProvider {
    /// Begin a new streaming HMAC; returns [`PrivateKeyError`] on failure.
    fn new_hmac_erased(
        &self,
        algorithm: &str,
        key: &[u8],
    ) -> Result<Box<dyn HmacState>, PrivateKeyError>;
}

/// Blanket impl: `&dyn ErasedStreamingHmacProvider` implements
/// [`StreamingHmacProvider`].
impl StreamingHmacProvider for dyn ErasedStreamingHmacProvider + '_ {
    type Error = PrivateKeyError;

    fn new_hmac(&self, algorithm: &str, key: &[u8]) -> Result<Box<dyn HmacState>, PrivateKeyError> {
        self.new_hmac_erased(algorithm, key)
    }
}

/// Blanket impl: `Box<dyn ErasedStreamingHmacProvider>` implements
/// [`StreamingHmacProvider`].
///
/// Allows the value returned by [`default_streaming_hmac_provider`] to be
/// used directly wherever `impl StreamingHmacProvider` is accepted.
///
/// [`default_streaming_hmac_provider`]: crate::default_streaming_hmac_provider
impl StreamingHmacProvider for Box<dyn ErasedStreamingHmacProvider> {
    type Error = PrivateKeyError;

    fn new_hmac(&self, algorithm: &str, key: &[u8]) -> Result<Box<dyn HmacState>, PrivateKeyError> {
        self.as_ref().new_hmac_erased(algorithm, key)
    }
}

// ── HKDF (RFC 5869) ───────────────────────────────────────────────────────────

/// HKDF-Extract (RFC 5869 §2.2).
///
/// Computes `PRK = HMAC-Hash(salt, IKM)` where `salt` defaults to a string
/// of `HashLen` zero bytes when `None`.  The returned pseudorandom key (PRK)
/// can be passed directly to [`hkdf_expand`].
///
/// # Arguments
///
/// * `hmac`      — any [`HmacProvider`] (use [`crate::default_hmac_provider`]
///   for the compiled-in backend).
/// * `algorithm` — hash name: `"sha256"`, `"sha384"`, `"sha512"`, etc.
/// * `salt`      — optional salt; `None` uses `HashLen` zero bytes.
/// * `ikm`       — input keying material.
///
/// # Errors
///
/// Returns the backend's error type if `algorithm` is unknown or the HMAC
/// computation fails.
pub fn hkdf_extract<P>(
    hmac: &P,
    algorithm: &str,
    salt: Option<&[u8]>,
    ikm: &[u8],
) -> Result<Vec<u8>, P::Error>
where
    P: HmacProvider,
{
    let hash_len = hmac_output_len(algorithm).unwrap_or(32);
    let default_salt: Vec<u8>;
    let effective_salt = match salt {
        Some(s) => s,
        None => {
            default_salt = vec![0u8; hash_len];
            &default_salt
        }
    };
    hmac.hmac_compute(algorithm, effective_salt, ikm)
}

/// HKDF-Expand (RFC 5869 §2.3).
///
/// Expands a pseudorandom key `prk` (from [`hkdf_extract`]) into `length`
/// bytes of output keying material (OKM) using `info` as a context label.
///
/// # Arguments
///
/// * `hmac`      — any [`HmacProvider`].
/// * `algorithm` — hash name: `"sha256"`, `"sha384"`, `"sha512"`, etc.
/// * `prk`       — pseudorandom key (output of HKDF-Extract or a strong key).
/// * `info`      — context and application-specific information (may be empty).
/// * `length`    — desired output length in bytes (≤ 255 × HashLen).
///
/// # Errors
///
/// Returns the backend's error type if `algorithm` is unknown, `length` is
/// too large (> 255 × HashLen), or the HMAC computation fails.
pub fn hkdf_expand<P>(
    hmac: &P,
    algorithm: &str,
    prk: &[u8],
    info: &[u8],
    length: usize,
) -> Result<Vec<u8>, P::Error>
where
    P: HmacProvider,
{
    if length == 0 {
        return Ok(Vec::new());
    }
    let hash_len = hmac_output_len(algorithm).unwrap_or(32);
    // Compute blocks needed (RFC 5869: N = ceil(L / HashLen), N ≤ 255)
    let n = length.div_ceil(hash_len);
    debug_assert!(n <= 255, "hkdf_expand: length too large for algorithm");

    let mut okm = Vec::with_capacity(length);
    let mut t: Vec<u8> = Vec::new(); // T(0) = empty string
    for i in 1u8..=(n as u8) {
        // T(i) = HMAC-Hash(PRK, T(i-1) || info || i)
        let mut input = Vec::with_capacity(t.len() + info.len() + 1);
        input.extend_from_slice(&t);
        input.extend_from_slice(info);
        input.push(i);
        t = hmac.hmac_compute(algorithm, prk, &input)?;
        okm.extend_from_slice(&t);
    }
    okm.truncate(length);
    Ok(okm)
}