entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! HMAC (Hash-based Message Authentication Code) per RFC 2104.
//!
//! Provides `HmacSha1`, `HmacSha256` and `HmacSha512`, keyed hash functions
//! used for message authentication throughout the crate (JWT/token signing,
//! webhook signatures, TOTP).
//!
//! # Security
//!
//! The [`verify`](HmacSha256::verify) methods use constant-time comparison
//! (`constant_time_eq`) to prevent timing side-channel attacks. **Never**
//! compare HMAC outputs with `==`; always use the provided `verify` method.
//!
//! The three types are written out explicitly rather than generated by a
//! macro. The duplication is shallow and mechanical (it varies only by block
//! size and digest width), and for security-critical code the explicit,
//! greppable form is deliberately preferred over a macro that would obscure
//! the construction during audit.

use core::fmt;

use crate::crypto::constant_time::constant_time_eq;
use crate::crypto::sha1::Sha1;
use crate::crypto::sha2::{Sha256, Sha512};

// ---------------------------------------------------------------------------
// HMAC-SHA-1
// ---------------------------------------------------------------------------

/// SHA-1 block size in bytes. SHA-1 processes input in 64-byte (512-bit)
/// blocks, so HMAC key padding is aligned to this width.
const SHA1_BLOCK_SIZE: usize = 64;

/// HMAC-SHA-1 (RFC 2104 instantiated with SHA-1).
///
/// Produces a 160-bit (20-byte) authentication tag. API mirrors
/// [`HmacSha256`] — see its documentation for usage patterns.
///
/// # Security
///
/// **SHA-1 is cryptographically broken for collision resistance.** However,
/// HMAC-SHA-1 remains secure as a PRF and is required by TOTP (RFC 6238).
/// For new HMAC-only uses, prefer [`HmacSha256`] or [`HmacSha512`].
#[derive(Clone)]
pub struct HmacSha1 {
    /// Inner hash — initialized with (key XOR ipad) as the first block.
    inner: Sha1,
    /// Outer hash — initialized with (key XOR opad) as the first block.
    outer: Sha1,
}

impl HmacSha1 {
    /// Creates a new HMAC-SHA-1 instance with the given `key`.
    ///
    /// Keys longer than 64 bytes are hashed with SHA-1 first (RFC 2104 §2).
    /// Shorter keys are zero-padded to the block size.
    #[must_use]
    pub fn new(key: &[u8]) -> Self {
        // Hash oversized keys down to 20 bytes so the XOR with ipad/opad
        // operates on a block-sized value.
        let mut key_block: [u8; SHA1_BLOCK_SIZE] = if key.len() > SHA1_BLOCK_SIZE {
            let mut hashed = Sha1::digest(key);
            let mut block = [0u8; SHA1_BLOCK_SIZE];
            block[..20].copy_from_slice(&hashed);
            // SECURITY: H(key) is the effective HMAC key (RFC 2104 §2); scrub
            // the intermediate digest from the stack like key_block/ipad/opad.
            crate::crypto::zeroize::zeroize(&mut hashed);
            block
        } else {
            let mut block = [0u8; SHA1_BLOCK_SIZE];
            block[..key.len()].copy_from_slice(key);
            block
        };

        let mut ipad = [0x36u8; SHA1_BLOCK_SIZE];
        let mut opad = [0x5cu8; SHA1_BLOCK_SIZE];

        for i in 0..SHA1_BLOCK_SIZE {
            ipad[i] ^= key_block[i];
            opad[i] ^= key_block[i];
        }

        let mut inner = Sha1::new();
        inner.update(&ipad);

        let mut outer = Sha1::new();
        outer.update(&opad);

        // SECURITY: Zeroize key material from the stack (see HmacSha256::new).
        crate::crypto::zeroize::zeroize(&mut key_block);
        crate::crypto::zeroize::zeroize(&mut ipad);
        crate::crypto::zeroize::zeroize(&mut opad);

        Self { inner, outer }
    }

    /// Feeds `data` into the HMAC computation.
    pub fn update(&mut self, data: &[u8]) {
        self.inner.update(data);
    }

    /// Consumes the HMAC instance and returns the 20-byte authentication tag.
    #[must_use]
    pub fn finalize(self) -> [u8; 20] {
        let mut inner_hash = self.inner.finalize();

        let mut outer = self.outer;
        outer.update(&inner_hash);
        // Scrub the key-derived intermediate H(ipad || message) from the
        // stack, matching the ipad/opad/key_block zeroization in `new`.
        crate::crypto::zeroize::zeroize(&mut inner_hash);
        outer.finalize()
    }

    /// Convenience: computes HMAC-SHA-1 in a single call.
    #[must_use]
    pub fn mac(key: &[u8], data: &[u8]) -> [u8; 20] {
        let mut hmac = Self::new(key);
        hmac.update(data);
        hmac.finalize()
    }

    /// Verifies that `expected` matches the HMAC-SHA-1 of `data` under `key`.
    ///
    /// Returns `true` only when `expected` has the correct length (20 bytes)
    /// and every byte matches; the comparison is constant-time. See
    /// [`HmacSha256::verify`] for the detailed timing-safety rationale.
    #[must_use]
    pub fn verify(key: &[u8], data: &[u8], expected: &[u8]) -> bool {
        let computed = Self::mac(key, data);
        constant_time_eq(&computed, expected)
    }
}

impl fmt::Debug for HmacSha1 {
    /// SECURITY: Redact hasher state which contains key-derived material.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HmacSha1").finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// HMAC-SHA-256
// ---------------------------------------------------------------------------

/// SHA-256 block size in bytes. SHA-256 processes input in 64-byte (512-bit)
/// blocks, so HMAC key padding is aligned to this width.
const SHA256_BLOCK_SIZE: usize = 64;

/// HMAC-SHA-256 (RFC 2104 instantiated with SHA-256).
///
/// Produces a 256-bit (32-byte) authentication tag. Supports incremental
/// feeding via [`update`](Self::update) or one-shot computation via
/// [`mac`](Self::mac).
///
/// # Examples
///
/// ```
/// use entropy_auth::crypto::HmacSha256;
///
/// let tag = HmacSha256::mac(b"secret-key", b"message");
/// assert!(HmacSha256::verify(b"secret-key", b"message", &tag));
/// ```
#[derive(Clone)]
pub struct HmacSha256 {
    /// Inner hash — initialized with (key XOR ipad) as the first block.
    /// Message data is fed into this hasher via `update`.
    inner: Sha256,
    /// Outer hash — initialized with (key XOR opad) as the first block.
    /// After the inner hash is finalized, its digest is fed into this hasher
    /// to produce the final HMAC output.
    outer: Sha256,
}

impl HmacSha256 {
    /// Creates a new HMAC-SHA-256 instance with the given `key`.
    ///
    /// If the key is longer than the hash block size (64 bytes), it is first
    /// hashed with SHA-256 to reduce it to 32 bytes. This is required by
    /// RFC 2104 §2 — a long key must be compressed to the hash output length
    /// so that the XOR with ipad/opad operates on a block-sized value.
    ///
    /// If the key is shorter than the block size it is implicitly zero-padded
    /// on the right (the pad arrays are initialized to zero before the key
    /// bytes are XOR-ed in).
    #[must_use]
    pub fn new(key: &[u8]) -> Self {
        // If the key exceeds the block size, hash it down to 32 bytes.
        // This ensures we always XOR a block-sized quantity with ipad/opad.
        let mut key_block: [u8; SHA256_BLOCK_SIZE] = if key.len() > SHA256_BLOCK_SIZE {
            let mut hashed = Sha256::digest(key);
            let mut block = [0u8; SHA256_BLOCK_SIZE];
            block[..32].copy_from_slice(&hashed);
            // SECURITY: H(key) is the effective HMAC key (RFC 2104 §2); scrub
            // the intermediate digest from the stack like key_block/ipad/opad.
            crate::crypto::zeroize::zeroize(&mut hashed);
            block
        } else {
            let mut block = [0u8; SHA256_BLOCK_SIZE];
            block[..key.len()].copy_from_slice(key);
            block
        };

        // ipad = key XOR 0x36 (repeated for each byte of the block)
        let mut ipad = [0x36u8; SHA256_BLOCK_SIZE];
        // opad = key XOR 0x5c (repeated for each byte of the block)
        let mut opad = [0x5cu8; SHA256_BLOCK_SIZE];

        for i in 0..SHA256_BLOCK_SIZE {
            ipad[i] ^= key_block[i];
            opad[i] ^= key_block[i];
        }

        // HMAC = H(opad || H(ipad || message))
        // Start the inner hash with ipad as its first block.
        let mut inner = Sha256::new();
        inner.update(&ipad);

        // Start the outer hash with opad as its first block. The inner hash
        // digest will be appended after finalization.
        let mut outer = Sha256::new();
        outer.update(&opad);

        // SECURITY: Zeroize key material from the stack. The pads and key
        // block contain secret-derived data that should not persist in memory
        // after being consumed by the hashers.
        crate::crypto::zeroize::zeroize(&mut key_block);
        crate::crypto::zeroize::zeroize(&mut ipad);
        crate::crypto::zeroize::zeroize(&mut opad);

        Self { inner, outer }
    }

    /// Feeds `data` into the HMAC computation.
    ///
    /// Can be called any number of times. The final tag is the same regardless
    /// of how the input is partitioned across calls.
    pub fn update(&mut self, data: &[u8]) {
        self.inner.update(data);
    }

    /// Consumes the HMAC instance and returns the 32-byte authentication tag.
    #[must_use]
    pub fn finalize(self) -> [u8; 32] {
        // inner_hash = H(ipad || message)
        let mut inner_hash = self.inner.finalize();

        // HMAC = H(opad || inner_hash)
        let mut outer = self.outer;
        outer.update(&inner_hash);
        // Scrub the key-derived intermediate from the stack, matching the
        // ipad/opad/key_block zeroization in `new`.
        crate::crypto::zeroize::zeroize(&mut inner_hash);
        outer.finalize()
    }

    /// Convenience: computes HMAC-SHA-256 in a single call.
    #[must_use]
    pub fn mac(key: &[u8], data: &[u8]) -> [u8; 32] {
        let mut hmac = Self::new(key);
        hmac.update(data);
        hmac.finalize()
    }

    /// Verifies that `expected` matches the HMAC-SHA-256 of `data` under `key`.
    ///
    /// Returns `true` only when the expected tag has the correct length (32
    /// bytes) and every byte matches the computed tag.
    // SECURITY: Uses constant-time comparison to prevent timing side-channel
    // attacks. An attacker observing response latency must not be able to
    // determine how many leading bytes of their forged tag are correct.
    #[must_use]
    pub fn verify(key: &[u8], data: &[u8], expected: &[u8]) -> bool {
        let computed = Self::mac(key, data);
        // SECURITY: constant_time_eq iterates over all bytes regardless of
        // mismatch position, and its accumulator is wrapped in black_box to
        // prevent the compiler from reintroducing an early exit. A length
        // mismatch (expected.len() != 32) returns false immediately, which
        // is safe because the tag length is not secret.
        constant_time_eq(&computed, expected)
    }
}

impl fmt::Debug for HmacSha256 {
    /// SECURITY: Redact hasher state which contains key-derived material.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HmacSha256").finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// HMAC-SHA-512
// ---------------------------------------------------------------------------

/// SHA-512 block size in bytes. SHA-512 processes input in 128-byte
/// (1024-bit) blocks.
const SHA512_BLOCK_SIZE: usize = 128;

/// HMAC-SHA-512 (RFC 2104 instantiated with SHA-512).
///
/// Produces a 512-bit (64-byte) authentication tag. API mirrors
/// [`HmacSha256`] — see its documentation for usage patterns.
#[derive(Clone)]
pub struct HmacSha512 {
    /// Inner hash — initialized with (key XOR ipad) as the first block.
    inner: Sha512,
    /// Outer hash — initialized with (key XOR opad) as the first block.
    outer: Sha512,
}

impl HmacSha512 {
    /// Creates a new HMAC-SHA-512 instance with the given `key`.
    ///
    /// Keys longer than 128 bytes are hashed with SHA-512 first (RFC 2104 §2).
    /// Shorter keys are zero-padded to the block size.
    #[must_use]
    pub fn new(key: &[u8]) -> Self {
        // Hash oversized keys down to 64 bytes so the XOR with ipad/opad
        // operates on a block-sized value.
        let mut key_block: [u8; SHA512_BLOCK_SIZE] = if key.len() > SHA512_BLOCK_SIZE {
            let mut hashed = Sha512::digest(key);
            let mut block = [0u8; SHA512_BLOCK_SIZE];
            block[..64].copy_from_slice(&hashed);
            // SECURITY: H(key) is the effective HMAC key (RFC 2104 §2); scrub
            // the intermediate digest from the stack like key_block/ipad/opad.
            crate::crypto::zeroize::zeroize(&mut hashed);
            block
        } else {
            let mut block = [0u8; SHA512_BLOCK_SIZE];
            block[..key.len()].copy_from_slice(key);
            block
        };

        let mut ipad = [0x36u8; SHA512_BLOCK_SIZE];
        let mut opad = [0x5cu8; SHA512_BLOCK_SIZE];

        for i in 0..SHA512_BLOCK_SIZE {
            ipad[i] ^= key_block[i];
            opad[i] ^= key_block[i];
        }

        let mut inner = Sha512::new();
        inner.update(&ipad);

        let mut outer = Sha512::new();
        outer.update(&opad);

        // SECURITY: Zeroize key material from the stack (see HmacSha256::new).
        crate::crypto::zeroize::zeroize(&mut key_block);
        crate::crypto::zeroize::zeroize(&mut ipad);
        crate::crypto::zeroize::zeroize(&mut opad);

        Self { inner, outer }
    }

    /// Feeds `data` into the HMAC computation.
    pub fn update(&mut self, data: &[u8]) {
        self.inner.update(data);
    }

    /// Consumes the HMAC instance and returns the 64-byte authentication tag.
    #[must_use]
    pub fn finalize(self) -> [u8; 64] {
        let mut inner_hash = self.inner.finalize();

        let mut outer = self.outer;
        outer.update(&inner_hash);
        // Scrub the key-derived intermediate H(ipad || message) from the
        // stack, matching the ipad/opad/key_block zeroization in `new`.
        crate::crypto::zeroize::zeroize(&mut inner_hash);
        outer.finalize()
    }

    /// Convenience: computes HMAC-SHA-512 in a single call.
    #[must_use]
    pub fn mac(key: &[u8], data: &[u8]) -> [u8; 64] {
        let mut hmac = Self::new(key);
        hmac.update(data);
        hmac.finalize()
    }

    /// Verifies that `expected` matches the HMAC-SHA-512 of `data` under `key`.
    ///
    /// Returns `true` only when `expected` has the correct length (64 bytes)
    /// and every byte matches; the comparison is constant-time. See
    /// [`HmacSha256::verify`] for the detailed timing-safety rationale.
    #[must_use]
    pub fn verify(key: &[u8], data: &[u8], expected: &[u8]) -> bool {
        let computed = Self::mac(key, data);
        constant_time_eq(&computed, expected)
    }
}

impl fmt::Debug for HmacSha512 {
    /// SECURITY: Redact hasher state which contains key-derived material.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HmacSha512").finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// Tests — RFC 4231 Test Vectors
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoding::{hex_decode, hex_encode};

    // -----------------------------------------------------------------------
    // RFC 2202 Test Case 1 (HMAC-SHA-1)
    //
    // Key  = 0x0b repeated 20 times
    // Data = "Hi There"
    // -----------------------------------------------------------------------

    #[test]
    fn rfc2202_test_case_1_sha1() {
        let key = vec![0x0bu8; 20];
        let data = b"Hi There";
        assert_eq!(
            hex_encode(&HmacSha1::mac(&key, data)),
            "b617318655057264e28bc0b6fb378c8ef146be00",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 2202 Test Case 2 (HMAC-SHA-1)
    //
    // Key  = "Jefe"
    // Data = "what do ya want for nothing?"
    // -----------------------------------------------------------------------

    #[test]
    fn rfc2202_test_case_2_sha1() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";
        assert_eq!(
            hex_encode(&HmacSha1::mac(key, data)),
            "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 2202 Test Case 3 (HMAC-SHA-1)
    //
    // Key  = 0xaa repeated 20 times
    // Data = 0xdd repeated 50 times
    // -----------------------------------------------------------------------

    #[test]
    fn rfc2202_test_case_3_sha1() {
        let key = vec![0xaau8; 20];
        let data = vec![0xddu8; 50];
        assert_eq!(
            hex_encode(&HmacSha1::mac(&key, &data)),
            "125d7342b9ac11cd91a39af48aa17b4f63f175d3",
        );
    }

    // -----------------------------------------------------------------------
    // HMAC-SHA-1 verify and incremental tests
    // -----------------------------------------------------------------------

    #[test]
    fn verify_correct_sha1() {
        let key = b"secret";
        let data = b"payload";
        let tag = HmacSha1::mac(key, data);
        assert!(HmacSha1::verify(key, data, &tag));
    }

    #[test]
    fn verify_incorrect_sha1() {
        let key = b"secret";
        let data = b"payload";
        let mut tag = HmacSha1::mac(key, data);
        tag[0] ^= 0x01;
        assert!(!HmacSha1::verify(key, data, &tag));
    }

    #[test]
    fn verify_wrong_length_sha1() {
        let key = b"secret";
        let data = b"payload";
        let tag = HmacSha1::mac(key, data);
        assert!(!HmacSha1::verify(key, data, &tag[..19]));
        let mut extended = tag.to_vec();
        extended.push(0x00);
        assert!(!HmacSha1::verify(key, data, &extended));
    }

    #[test]
    fn incremental_update_sha1() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";

        let mut hmac = HmacSha1::new(key);
        hmac.update(&data[..10]);
        hmac.update(&data[10..]);
        let incremental = hmac.finalize();

        let one_shot = HmacSha1::mac(key, data);
        assert_eq!(incremental, one_shot);
    }

    #[test]
    fn hmac_sha1_debug_does_not_leak_state() {
        let hmac = HmacSha1::new(b"super-secret-key");
        let debug = format!("{hmac:?}");
        assert!(debug.contains("HmacSha1"), "should contain the type name");
        assert!(!debug.contains("inner"), "must not expose inner hasher");
        assert!(!debug.contains("outer"), "must not expose outer hasher");
        assert!(!debug.contains("secret"), "must not expose key material");
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 1
    //
    // Key  = 0x0b repeated 20 times
    // Data = "Hi There"
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_1_sha256() {
        let key = vec![0x0bu8; 20];
        let data = b"Hi There";
        assert_eq!(
            hex_encode(&HmacSha256::mac(&key, data)),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
        );
    }

    #[test]
    fn rfc4231_test_case_1_sha512() {
        let key = vec![0x0bu8; 20];
        let data = b"Hi There";
        assert_eq!(
            hex_encode(&HmacSha512::mac(&key, data)),
            "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde\
             daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 2
    //
    // Key  = "Jefe"
    // Data = "what do ya want for nothing?"
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_2_sha256() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";
        assert_eq!(
            hex_encode(&HmacSha256::mac(key, data)),
            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
        );
    }

    #[test]
    fn rfc4231_test_case_2_sha512() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";
        assert_eq!(
            hex_encode(&HmacSha512::mac(key, data)),
            "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
             9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 3
    //
    // Key  = 0xaa repeated 20 times
    // Data = 0xdd repeated 50 times
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_3_sha256() {
        let key = vec![0xaau8; 20];
        let data = vec![0xddu8; 50];
        assert_eq!(
            hex_encode(&HmacSha256::mac(&key, &data)),
            "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe",
        );
    }

    #[test]
    fn rfc4231_test_case_3_sha512() {
        let key = vec![0xaau8; 20];
        let data = vec![0xddu8; 50];
        assert_eq!(
            hex_encode(&HmacSha512::mac(&key, &data)),
            "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39\
             bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 4
    //
    // Key  = 0x0102..1819 (25 bytes)
    // Data = 0xcd repeated 50 times
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_4_sha256() {
        let key = hex_decode("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap();
        let data = vec![0xcdu8; 50];
        assert_eq!(
            hex_encode(&HmacSha256::mac(&key, &data)),
            "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b",
        );
    }

    #[test]
    fn rfc4231_test_case_4_sha512() {
        let key = hex_decode("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap();
        let data = vec![0xcdu8; 50];
        assert_eq!(
            hex_encode(&HmacSha512::mac(&key, &data)),
            "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db\
             a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 6 — long key (> block size)
    //
    // Key  = 0xaa repeated 131 times
    // Data = "Test Using Larger Than Block-Size Key - Hash Key First"
    //
    // This exercises the code path where the key exceeds the hash block size
    // and must be hashed before use.
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_6_sha256() {
        let key = vec![0xaau8; 131];
        let data = b"Test Using Larger Than Block-Size Key - Hash Key First";
        assert_eq!(
            hex_encode(&HmacSha256::mac(&key, data)),
            "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54",
        );
    }

    #[test]
    fn rfc4231_test_case_6_sha512() {
        let key = vec![0xaau8; 131];
        let data = b"Test Using Larger Than Block-Size Key - Hash Key First";
        assert_eq!(
            hex_encode(&HmacSha512::mac(&key, data)),
            "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352\
             6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598",
        );
    }

    // -----------------------------------------------------------------------
    // RFC 4231 Test Case 7 — long key + long data
    //
    // Key  = 0xaa repeated 131 times
    // Data = "This is a test using a larger than block-size key and a
    //         larger than block-size data. The key needs to be hashed
    //         before being used by the HMAC algorithm."
    // -----------------------------------------------------------------------

    #[test]
    fn rfc4231_test_case_7_sha256() {
        let key = vec![0xaau8; 131];
        let data = b"This is a test using a larger than block-size key and a larger \
                      than block-size data. The key needs to be hashed before being \
                      used by the HMAC algorithm.";
        assert_eq!(
            hex_encode(&HmacSha256::mac(&key, data)),
            "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2",
        );
    }

    #[test]
    fn rfc4231_test_case_7_sha512() {
        let key = vec![0xaau8; 131];
        let data = b"This is a test using a larger than block-size key and a larger \
                      than block-size data. The key needs to be hashed before being \
                      used by the HMAC algorithm.";
        assert_eq!(
            hex_encode(&HmacSha512::mac(&key, data)),
            "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944\
             b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58",
        );
    }

    // -----------------------------------------------------------------------
    // Verify — correct, incorrect, and wrong-length tags
    // -----------------------------------------------------------------------

    #[test]
    fn verify_correct_sha256() {
        let key = b"secret";
        let data = b"payload";
        let tag = HmacSha256::mac(key, data);
        assert!(HmacSha256::verify(key, data, &tag));
    }

    #[test]
    fn verify_correct_sha512() {
        let key = b"secret";
        let data = b"payload";
        let tag = HmacSha512::mac(key, data);
        assert!(HmacSha512::verify(key, data, &tag));
    }

    #[test]
    fn verify_incorrect_sha256() {
        let key = b"secret";
        let data = b"payload";
        let mut tag = HmacSha256::mac(key, data);
        // Flip one bit in the tag to simulate a forged MAC.
        tag[0] ^= 0x01;
        assert!(!HmacSha256::verify(key, data, &tag));
    }

    #[test]
    fn verify_incorrect_sha512() {
        let key = b"secret";
        let data = b"payload";
        let mut tag = HmacSha512::mac(key, data);
        tag[0] ^= 0x01;
        assert!(!HmacSha512::verify(key, data, &tag));
    }

    #[test]
    fn verify_wrong_length_sha256() {
        let key = b"secret";
        let data = b"payload";
        // A truncated tag (31 bytes instead of 32) must be rejected.
        let tag = HmacSha256::mac(key, data);
        assert!(!HmacSha256::verify(key, data, &tag[..31]));
        // An extended tag (33 bytes) must also be rejected.
        let mut extended = tag.to_vec();
        extended.push(0x00);
        assert!(!HmacSha256::verify(key, data, &extended));
    }

    #[test]
    fn verify_wrong_length_sha512() {
        let key = b"secret";
        let data = b"payload";
        let tag = HmacSha512::mac(key, data);
        assert!(!HmacSha512::verify(key, data, &tag[..63]));
        let mut extended = tag.to_vec();
        extended.push(0x00);
        assert!(!HmacSha512::verify(key, data, &extended));
    }

    // -----------------------------------------------------------------------
    // Incremental update — splitting data across multiple update() calls
    // must produce the same tag as a single-shot mac().
    // -----------------------------------------------------------------------

    #[test]
    fn incremental_update_sha256() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";

        // Split at an arbitrary boundary.
        let mut hmac = HmacSha256::new(key);
        hmac.update(&data[..10]);
        hmac.update(&data[10..]);
        let incremental = hmac.finalize();

        let one_shot = HmacSha256::mac(key, data);
        assert_eq!(incremental, one_shot);
    }

    #[test]
    fn incremental_update_sha512() {
        let key = b"Jefe";
        let data = b"what do ya want for nothing?";

        let mut hmac = HmacSha512::new(key);
        hmac.update(&data[..10]);
        hmac.update(&data[10..]);
        let incremental = hmac.finalize();

        let one_shot = HmacSha512::mac(key, data);
        assert_eq!(incremental, one_shot);
    }

    #[test]
    fn incremental_single_byte_updates_sha256() {
        let key = vec![0x0bu8; 20];
        let data = b"Hi There";

        let mut hmac = HmacSha256::new(&key);
        for &byte in data {
            hmac.update(&[byte]);
        }

        assert_eq!(
            hex_encode(&hmac.finalize()),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
        );
    }

    #[test]
    fn incremental_single_byte_updates_sha512() {
        let key = vec![0x0bu8; 20];
        let data = b"Hi There";

        let mut hmac = HmacSha512::new(&key);
        for &byte in data {
            hmac.update(&[byte]);
        }

        assert_eq!(
            hex_encode(&hmac.finalize()),
            "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde\
             daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854",
        );
    }

    // -----------------------------------------------------------------------
    // Debug redaction
    // -----------------------------------------------------------------------

    #[test]
    fn hmac_sha256_debug_does_not_leak_state() {
        // SECURITY: The Debug output must not contain key-derived material.
        let hmac = HmacSha256::new(b"super-secret-key");
        let debug = format!("{hmac:?}");
        assert!(debug.contains("HmacSha256"), "should contain the type name");
        assert!(!debug.contains("inner"), "must not expose inner hasher");
        assert!(!debug.contains("outer"), "must not expose outer hasher");
        assert!(!debug.contains("secret"), "must not expose key material");
    }

    #[test]
    fn hmac_sha512_debug_does_not_leak_state() {
        // SECURITY: The Debug output must not contain key-derived material.
        let hmac = HmacSha512::new(b"super-secret-key");
        let debug = format!("{hmac:?}");
        assert!(debug.contains("HmacSha512"), "should contain the type name");
        assert!(!debug.contains("inner"), "must not expose inner hasher");
        assert!(!debug.contains("outer"), "must not expose outer hasher");
        assert!(!debug.contains("secret"), "must not expose key material");
    }
}