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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! SHA-256 and SHA-512 hash functions (FIPS 180-4).
//!
//! Self-contained implementations of the SHA-2 family used throughout the
//! authentication crate for HMAC, JWT signing, and token fingerprinting.
//! Both algorithms follow FIPS 180-4 exactly, including the padding scheme,
//! message schedule expansion, and compression rounds.
//!
//! # Security
//!
//! These are hand-written implementations — not wrappers around a vetted
//! C library. They are validated against every NIST CAVP test vector
//! listed in the specification, plus the one-million-character stress
//! test, but they have **not** undergone a formal third-party audit.
//! Use them for authentication workloads (HMAC, JWT signing) where
//! correctness is critical but throughput is modest.

use core::fmt;

// ---------------------------------------------------------------------------
// SHA-256 constants
// ---------------------------------------------------------------------------

/// Initial hash values for SHA-256 (FIPS 180-4 §5.3.3).
///
/// These are the first 32 bits of the fractional parts of the square roots
/// of the first 8 prime numbers (2, 3, 5, 7, 11, 13, 17, 19).
#[allow(clippy::unreadable_literal)]
const H256: [u32; 8] = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];

/// Round constants for SHA-256 (FIPS 180-4 §4.2.2).
///
/// First 32 bits of the fractional parts of the cube roots of the first
/// 64 prime numbers.
#[allow(clippy::unreadable_literal)]
const K256: [u32; 64] = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

// ---------------------------------------------------------------------------
// SHA-512 constants
// ---------------------------------------------------------------------------

/// Initial hash values for SHA-512 (FIPS 180-4 §5.3.5).
///
/// First 64 bits of the fractional parts of the square roots of the
/// first 8 prime numbers.
#[allow(clippy::unreadable_literal)]
const H512: [u64; 8] = [
    0x6a09e667f3bcc908,
    0xbb67ae8584caa73b,
    0x3c6ef372fe94f82b,
    0xa54ff53a5f1d36f1,
    0x510e527fade682d1,
    0x9b05688c2b3e6c1f,
    0x1f83d9abfb41bd6b,
    0x5be0cd19137e2179,
];

/// Round constants for SHA-512 (FIPS 180-4 §4.2.3).
///
/// First 64 bits of the fractional parts of the cube roots of the first
/// 80 prime numbers.
#[allow(clippy::unreadable_literal)]
const K512: [u64; 80] = [
    0x428a2f98d728ae22,
    0x7137449123ef65cd,
    0xb5c0fbcfec4d3b2f,
    0xe9b5dba58189dbbc,
    0x3956c25bf348b538,
    0x59f111f1b605d019,
    0x923f82a4af194f9b,
    0xab1c5ed5da6d8118,
    0xd807aa98a3030242,
    0x12835b0145706fbe,
    0x243185be4ee4b28c,
    0x550c7dc3d5ffb4e2,
    0x72be5d74f27b896f,
    0x80deb1fe3b1696b1,
    0x9bdc06a725c71235,
    0xc19bf174cf692694,
    0xe49b69c19ef14ad2,
    0xefbe4786384f25e3,
    0x0fc19dc68b8cd5b5,
    0x240ca1cc77ac9c65,
    0x2de92c6f592b0275,
    0x4a7484aa6ea6e483,
    0x5cb0a9dcbd41fbd4,
    0x76f988da831153b5,
    0x983e5152ee66dfab,
    0xa831c66d2db43210,
    0xb00327c898fb213f,
    0xbf597fc7beef0ee4,
    0xc6e00bf33da88fc2,
    0xd5a79147930aa725,
    0x06ca6351e003826f,
    0x142929670a0e6e70,
    0x27b70a8546d22ffc,
    0x2e1b21385c26c926,
    0x4d2c6dfc5ac42aed,
    0x53380d139d95b3df,
    0x650a73548baf63de,
    0x766a0abb3c77b2a8,
    0x81c2c92e47edaee6,
    0x92722c851482353b,
    0xa2bfe8a14cf10364,
    0xa81a664bbc423001,
    0xc24b8b70d0f89791,
    0xc76c51a30654be30,
    0xd192e819d6ef5218,
    0xd69906245565a910,
    0xf40e35855771202a,
    0x106aa07032bbd1b8,
    0x19a4c116b8d2d0c8,
    0x1e376c085141ab53,
    0x2748774cdf8eeb99,
    0x34b0bcb5e19b48a8,
    0x391c0cb3c5c95a63,
    0x4ed8aa4ae3418acb,
    0x5b9cca4f7763e373,
    0x682e6ff3d6b2b8a3,
    0x748f82ee5defb2fc,
    0x78a5636f43172f60,
    0x84c87814a1f0ab72,
    0x8cc702081a6439ec,
    0x90befffa23631e28,
    0xa4506cebde82bde9,
    0xbef9a3f7b2c67915,
    0xc67178f2e372532b,
    0xca273eceea26619c,
    0xd186b8c721c0c207,
    0xeada7dd6cde0eb1e,
    0xf57d4f7fee6ed178,
    0x06f067aa72176fba,
    0x0a637dc5a2c898a6,
    0x113f9804bef90dae,
    0x1b710b35131c471b,
    0x28db77f523047d84,
    0x32caab7b40c72493,
    0x3c9ebe0a15c9bebc,
    0x431d67c49c100d4c,
    0x4cc5d4becb3e42b6,
    0x597f299cfc657e2a,
    0x5fcb6fab3ad6faec,
    0x6c44198c4a475817,
];

// ---------------------------------------------------------------------------
// SHA-256 helper functions (FIPS 180-4 §4.1.2)
// ---------------------------------------------------------------------------

/// Choice function: for each bit position, selects from `y` where `x` is 1,
/// from `z` where `x` is 0.
#[inline]
const fn ch32(x: u32, y: u32, z: u32) -> u32 {
    (x & y) ^ (!x & z)
}

/// Majority function: for each bit position, returns the majority value of
/// the three inputs.
#[inline]
const fn maj32(x: u32, y: u32, z: u32) -> u32 {
    (x & y) ^ (x & z) ^ (y & z)
}

/// Upper-case `Sigma_0` for SHA-256: ROTR(2) ^ ROTR(13) ^ ROTR(22).
#[inline]
const fn big_sigma0_32(x: u32) -> u32 {
    x.rotate_right(2) ^ x.rotate_right(13) ^ x.rotate_right(22)
}

/// Upper-case `Sigma_1` for SHA-256: ROTR(6) ^ ROTR(11) ^ ROTR(25).
#[inline]
const fn big_sigma1_32(x: u32) -> u32 {
    x.rotate_right(6) ^ x.rotate_right(11) ^ x.rotate_right(25)
}

/// Lower-case `sigma_0` for SHA-256 message schedule: ROTR(7) ^ ROTR(18) ^ SHR(3).
#[inline]
const fn small_sigma0_32(x: u32) -> u32 {
    x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3)
}

/// Lower-case `sigma_1` for SHA-256 message schedule: ROTR(17) ^ ROTR(19) ^ SHR(10).
#[inline]
const fn small_sigma1_32(x: u32) -> u32 {
    x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10)
}

// ---------------------------------------------------------------------------
// SHA-512 helper functions (FIPS 180-4 §4.1.3)
// ---------------------------------------------------------------------------

/// Choice function for 64-bit words.
#[inline]
const fn ch64(x: u64, y: u64, z: u64) -> u64 {
    (x & y) ^ (!x & z)
}

/// Majority function for 64-bit words.
#[inline]
const fn maj64(x: u64, y: u64, z: u64) -> u64 {
    (x & y) ^ (x & z) ^ (y & z)
}

/// Upper-case `Sigma_0` for SHA-512: ROTR(28) ^ ROTR(34) ^ ROTR(39).
#[inline]
const fn big_sigma0_64(x: u64) -> u64 {
    x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39)
}

/// Upper-case `Sigma_1` for SHA-512: ROTR(14) ^ ROTR(18) ^ ROTR(41).
#[inline]
const fn big_sigma1_64(x: u64) -> u64 {
    x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41)
}

/// Lower-case `sigma_0` for SHA-512 message schedule: ROTR(1) ^ ROTR(8) ^ SHR(7).
#[inline]
const fn small_sigma0_64(x: u64) -> u64 {
    x.rotate_right(1) ^ x.rotate_right(8) ^ (x >> 7)
}

/// Lower-case `sigma_1` for SHA-512 message schedule: ROTR(19) ^ ROTR(61) ^ SHR(6).
#[inline]
const fn small_sigma1_64(x: u64) -> u64 {
    x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6)
}

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

/// SHA-256 hasher (FIPS 180-4).
///
/// Produces a 256-bit (32-byte) digest. Supports incremental feeding via
/// [`update`](Sha256::update) or one-shot hashing via [`digest`](Sha256::digest).
///
/// # Examples
///
/// ```
/// use entropy_auth::crypto::Sha256;
///
/// let hash = Sha256::digest(b"hello");
/// assert_eq!(hash.len(), 32);
/// ```
#[derive(Clone)]
pub struct Sha256 {
    /// Running hash state — eight 32-bit words (H0..H7).
    state: [u32; 8],
    /// Partial block buffer. Data is accumulated here until a full 64-byte
    /// block is available for compression.
    buffer: [u8; 64],
    /// Number of valid bytes currently in `buffer`.
    buf_len: usize,
    /// Total number of bytes fed into the hasher, used to compute the
    /// padding length field.
    total_len: u64,
}

impl Sha256 {
    /// Creates a new SHA-256 hasher initialised with the standard IV.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: H256,
            buffer: [0u8; 64],
            buf_len: 0,
            total_len: 0,
        }
    }

    /// Feeds `data` into the hasher.
    ///
    /// Can be called any number of times with arbitrarily sized slices. The
    /// final digest is the same regardless of how the input is partitioned.
    #[allow(clippy::missing_panics_doc)]
    pub fn update(&mut self, data: &[u8]) {
        self.total_len = self.total_len.wrapping_add(data.len() as u64);
        let mut offset = 0;

        // If the buffer has leftover bytes, try to fill it to a full block.
        if self.buf_len > 0 {
            let need = 64 - self.buf_len;
            let take = need.min(data.len());
            self.buffer[self.buf_len..self.buf_len + take].copy_from_slice(&data[..take]);
            self.buf_len += take;
            offset = take;

            if self.buf_len == 64 {
                // Buffer is full — compress it and reset.
                let block: [u8; 64] = self.buffer;
                Self::compress(&mut self.state, &block);
                self.buf_len = 0;
            } else {
                // Still not enough data for a full block; nothing more to do.
                return;
            }
        }

        // Process as many full 64-byte blocks as possible directly from `data`.
        while offset + 64 <= data.len() {
            let block: [u8; 64] = data[offset..offset + 64].try_into().unwrap();
            Self::compress(&mut self.state, &block);
            offset += 64;
        }

        // Buffer any remaining bytes (less than a full block).
        let remaining = data.len() - offset;
        if remaining > 0 {
            self.buffer[..remaining].copy_from_slice(&data[offset..]);
            self.buf_len = remaining;
        }
    }

    /// Consumes the hasher and returns the 32-byte digest.
    ///
    /// Applies the FIPS 180-4 padding (0x80, zero-fill, 64-bit big-endian
    /// bit length) before the final compression.
    #[must_use]
    pub fn finalize(mut self) -> [u8; 32] {
        // Padding: append a 1-bit (0x80 byte), then enough zero bytes so
        // that the total padded message length ≡ 56 (mod 64), followed by
        // the 64-bit big-endian bit count.
        let bit_len = self.total_len.wrapping_mul(8);

        // Append 0x80.
        self.buffer[self.buf_len] = 0x80;
        self.buf_len += 1;

        // If there isn't room for the 8-byte length field in this block,
        // pad the current block with zeros, compress it, and start a fresh
        // padding block.
        if self.buf_len > 56 {
            // Zero-fill the rest of this block and compress.
            self.buffer[self.buf_len..64].fill(0);
            let block: [u8; 64] = self.buffer;
            Self::compress(&mut self.state, &block);
            self.buf_len = 0;
        }

        // Zero-fill up to byte 56, then write the 64-bit bit length.
        self.buffer[self.buf_len..56].fill(0);
        self.buffer[56..64].copy_from_slice(&bit_len.to_be_bytes());
        let block: [u8; 64] = self.buffer;
        Self::compress(&mut self.state, &block);

        // Serialize state to big-endian bytes.
        let mut out = [0u8; 32];
        for (i, word) in self.state.iter().enumerate() {
            out[i * 4..(i + 1) * 4].copy_from_slice(&word.to_be_bytes());
        }
        out
    }

    /// Convenience: hashes `data` in a single call.
    #[must_use]
    #[inline]
    pub fn digest(data: &[u8]) -> [u8; 32] {
        let mut hasher = Self::new();
        hasher.update(data);
        hasher.finalize()
    }

    /// SHA-256 compression function.
    ///
    /// Processes one 64-byte block: expands the 16-word message schedule to
    /// 64 words, then runs 64 rounds of the compression function, updating
    /// `state` in place.
    #[allow(clippy::many_single_char_names, unsafe_code)]
    fn compress(state: &mut [u32; 8], block: &[u8; 64]) {
        // Parse the block into 16 big-endian 32-bit words, then expand to 64.
        let mut w = [0u32; 64];
        for i in 0..16 {
            w[i] = u32::from_be_bytes(block[i * 4..(i + 1) * 4].try_into().unwrap());
        }
        for i in 16..64 {
            w[i] = small_sigma1_32(w[i - 2])
                .wrapping_add(w[i - 7])
                .wrapping_add(small_sigma0_32(w[i - 15]))
                .wrapping_add(w[i - 16]);
        }

        // Initialize working variables from current hash state.
        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state;

        // 64 compression rounds.
        for i in 0..64 {
            let t1 = h
                .wrapping_add(big_sigma1_32(e))
                .wrapping_add(ch32(e, f, g))
                .wrapping_add(K256[i])
                .wrapping_add(w[i]);
            let t2 = big_sigma0_32(a).wrapping_add(maj32(a, b, c));

            h = g;
            g = f;
            f = e;
            e = d.wrapping_add(t1);
            d = c;
            c = b;
            b = a;
            a = t1.wrapping_add(t2);
        }

        // Add the compressed chunk's hash to the running state.
        state[0] = state[0].wrapping_add(a);
        state[1] = state[1].wrapping_add(b);
        state[2] = state[2].wrapping_add(c);
        state[3] = state[3].wrapping_add(d);
        state[4] = state[4].wrapping_add(e);
        state[5] = state[5].wrapping_add(f);
        state[6] = state[6].wrapping_add(g);
        state[7] = state[7].wrapping_add(h);

        // SECURITY: the message schedule and working variables hold the block
        // plaintext and derived state — for HmacSha256 that includes the
        // key-derived ipad/opad block. `new`/`finalize` and `Drop` already
        // scrub the key block, state, and buffer; without this the same
        // material simply survives on the stack instead.
        zeroize_u32_slice(&mut w);
        for v in [
            &mut a, &mut b, &mut c, &mut d, &mut e, &mut f, &mut g, &mut h,
        ] {
            // SAFETY: `v` is a valid, aligned, dereferenceable pointer to a
            // live local. `write_volatile` keeps the store from being elided.
            unsafe { core::ptr::write_volatile(v, 0) };
        }
    }
}

/// Volatile-zero a `u32` scratch buffer (the SHA-256 message schedule).
///
/// `crypto::zeroize::zeroize` only takes `&mut [u8]`; transmuting the schedule
/// to bytes would need `unsafe` at every call site, so the word-wise volatile
/// write is factored out here instead.
#[allow(unsafe_code)]
fn zeroize_u32_slice(buf: &mut [u32]) {
    for word in buf.iter_mut() {
        // SAFETY: `word` is a valid, aligned, dereferenceable pointer from a
        // mutable slice. `write_volatile` guarantees the store survives
        // optimisation.
        unsafe { core::ptr::write_volatile(word, 0) };
    }
}

/// Volatile-zero a `u64` scratch buffer (the SHA-512 message schedule).
#[allow(unsafe_code)]
fn zeroize_u64_slice(buf: &mut [u64]) {
    for word in buf.iter_mut() {
        // SAFETY: as `zeroize_u32_slice`.
        unsafe { core::ptr::write_volatile(word, 0) };
    }
}

impl fmt::Debug for Sha256 {
    /// SECURITY: Redact internal hash state to prevent accidental exposure
    /// of in-progress digests in logs or error messages.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Sha256")
            .field("total_len", &self.total_len)
            .finish_non_exhaustive()
    }
}

impl Drop for Sha256 {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        // SECURITY: Zeroize internal state and buffer to prevent secret
        // material from lingering in memory after the hasher is dropped.
        for word in &mut self.state {
            // SAFETY: `word` is a valid, aligned, dereferenceable pointer.
            // `write_volatile` guarantees the store is not optimised away.
            unsafe { core::ptr::write_volatile(word, 0) };
        }
        crate::crypto::zeroize::zeroize(&mut self.buffer);
    }
}

impl Default for Sha256 {
    fn default() -> Self {
        Self::new()
    }
}

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

/// SHA-512 hasher (FIPS 180-4).
///
/// Produces a 512-bit (64-byte) digest. Supports incremental feeding via
/// [`update`](Sha512::update) or one-shot hashing via [`digest`](Sha512::digest).
///
/// # Examples
///
/// ```
/// use entropy_auth::crypto::Sha512;
///
/// let hash = Sha512::digest(b"hello");
/// assert_eq!(hash.len(), 64);
/// ```
#[derive(Clone)]
pub struct Sha512 {
    /// Running hash state — eight 64-bit words (H0..H7).
    state: [u64; 8],
    /// Partial block buffer. SHA-512 uses 128-byte blocks, double SHA-256.
    buffer: [u8; 128],
    /// Number of valid bytes currently in `buffer`.
    buf_len: usize,
    /// Total number of bytes fed into the hasher.
    ///
    /// Stored as a `u128` because SHA-512 encodes the bit length as a
    /// 128-bit big-endian integer in the padding, supporting messages up
    /// to 2^128 - 1 bits. In practice we will never approach that limit.
    total_len: u128,
}

impl Sha512 {
    /// Creates a new SHA-512 hasher initialised with the standard IV.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: H512,
            buffer: [0u8; 128],
            buf_len: 0,
            total_len: 0,
        }
    }

    /// Feeds `data` into the hasher.
    #[allow(clippy::missing_panics_doc)]
    pub fn update(&mut self, data: &[u8]) {
        self.total_len = self.total_len.wrapping_add(data.len() as u128);
        let mut offset = 0;

        // Fill partial buffer first.
        if self.buf_len > 0 {
            let need = 128 - self.buf_len;
            let take = need.min(data.len());
            self.buffer[self.buf_len..self.buf_len + take].copy_from_slice(&data[..take]);
            self.buf_len += take;
            offset = take;

            if self.buf_len == 128 {
                let block: [u8; 128] = self.buffer;
                Self::compress(&mut self.state, &block);
                self.buf_len = 0;
            } else {
                return;
            }
        }

        // Process full blocks directly from `data`.
        while offset + 128 <= data.len() {
            let block: [u8; 128] = data[offset..offset + 128].try_into().unwrap();
            Self::compress(&mut self.state, &block);
            offset += 128;
        }

        // Buffer remainder.
        let remaining = data.len() - offset;
        if remaining > 0 {
            self.buffer[..remaining].copy_from_slice(&data[offset..]);
            self.buf_len = remaining;
        }
    }

    /// Consumes the hasher and returns the 64-byte digest.
    #[must_use]
    pub fn finalize(mut self) -> [u8; 64] {
        // SHA-512 padding: 0x80, zeros, then 128-bit big-endian bit count.
        // The length field occupies the last 16 bytes of the final block.
        let bit_len = self.total_len.wrapping_mul(8);

        self.buffer[self.buf_len] = 0x80;
        self.buf_len += 1;

        // Need 16 bytes for the length field (128 - 16 = 112).
        if self.buf_len > 112 {
            self.buffer[self.buf_len..128].fill(0);
            let block: [u8; 128] = self.buffer;
            Self::compress(&mut self.state, &block);
            self.buf_len = 0;
        }

        self.buffer[self.buf_len..112].fill(0);
        self.buffer[112..128].copy_from_slice(&bit_len.to_be_bytes());
        let block: [u8; 128] = self.buffer;
        Self::compress(&mut self.state, &block);

        let mut out = [0u8; 64];
        for (i, word) in self.state.iter().enumerate() {
            out[i * 8..(i + 1) * 8].copy_from_slice(&word.to_be_bytes());
        }
        out
    }

    /// Convenience: hashes `data` in a single call.
    #[must_use]
    #[inline]
    pub fn digest(data: &[u8]) -> [u8; 64] {
        let mut hasher = Self::new();
        hasher.update(data);
        hasher.finalize()
    }

    /// SHA-512 compression function.
    ///
    /// Identical structure to SHA-256 but operates on 64-bit words with
    /// different rotation amounts and 80 rounds instead of 64.
    #[allow(clippy::many_single_char_names, unsafe_code)]
    fn compress(state: &mut [u64; 8], block: &[u8; 128]) {
        let mut w = [0u64; 80];
        for i in 0..16 {
            w[i] = u64::from_be_bytes(block[i * 8..(i + 1) * 8].try_into().unwrap());
        }
        for i in 16..80 {
            w[i] = small_sigma1_64(w[i - 2])
                .wrapping_add(w[i - 7])
                .wrapping_add(small_sigma0_64(w[i - 15]))
                .wrapping_add(w[i - 16]);
        }

        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state;

        for i in 0..80 {
            let t1 = h
                .wrapping_add(big_sigma1_64(e))
                .wrapping_add(ch64(e, f, g))
                .wrapping_add(K512[i])
                .wrapping_add(w[i]);
            let t2 = big_sigma0_64(a).wrapping_add(maj64(a, b, c));

            h = g;
            g = f;
            f = e;
            e = d.wrapping_add(t1);
            d = c;
            c = b;
            b = a;
            a = t1.wrapping_add(t2);
        }

        state[0] = state[0].wrapping_add(a);
        state[1] = state[1].wrapping_add(b);
        state[2] = state[2].wrapping_add(c);
        state[3] = state[3].wrapping_add(d);
        state[4] = state[4].wrapping_add(e);
        state[5] = state[5].wrapping_add(f);
        state[6] = state[6].wrapping_add(g);
        state[7] = state[7].wrapping_add(h);

        // Same rationale as the SHA-256 compression function above.
        zeroize_u64_slice(&mut w);
        for v in [
            &mut a, &mut b, &mut c, &mut d, &mut e, &mut f, &mut g, &mut h,
        ] {
            // SAFETY: as above — a live, aligned local.
            unsafe { core::ptr::write_volatile(v, 0) };
        }
    }
}

impl fmt::Debug for Sha512 {
    /// SECURITY: Redact internal hash state to prevent accidental exposure
    /// of in-progress digests in logs or error messages.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Sha512")
            .field("total_len", &self.total_len)
            .finish_non_exhaustive()
    }
}

impl Drop for Sha512 {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        // SECURITY: Zeroize internal state and buffer to prevent secret
        // material from lingering in memory after the hasher is dropped.
        for word in &mut self.state {
            // SAFETY: `word` is a valid, aligned, dereferenceable pointer.
            // `write_volatile` guarantees the store is not optimised away.
            unsafe { core::ptr::write_volatile(word, 0) };
        }
        crate::crypto::zeroize::zeroize(&mut self.buffer);
    }
}

impl Default for Sha512 {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- SHA-256 Test Vectors ---
    //
    // Vectors from NIST CAVP / FIPS 180-4 examples.

    #[test]
    fn sha256_empty() {
        let digest = Sha256::digest(b"");
        assert_eq!(
            hex_encode(&digest),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        );
    }

    #[test]
    fn sha256_abc() {
        let digest = Sha256::digest(b"abc");
        assert_eq!(
            hex_encode(&digest),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );
    }

    #[test]
    fn sha256_448_bits() {
        // 448-bit message (56 bytes) — exactly one block minus the padding.
        // This exercises the boundary where padding must spill into a second
        // block (56 data bytes + 1 padding byte + 8 length bytes = 65 > 64).
        let msg = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
        assert_eq!(msg.len(), 56);
        let digest = Sha256::digest(msg);
        assert_eq!(
            hex_encode(&digest),
            "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
        );
    }

    #[test]
    fn sha256_896_bits() {
        // 896-bit message (112 bytes) — spans two blocks.
        let msg = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
        assert_eq!(msg.len(), 112);
        let digest = Sha256::digest(msg);
        assert_eq!(
            hex_encode(&digest),
            "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
        );
    }

    #[test]
    fn sha256_one_million_a() {
        // NIST test: SHA-256 of 1,000,000 repetitions of 'a'.
        let digest = Sha256::digest(&vec![b'a'; 1_000_000]);
        assert_eq!(
            hex_encode(&digest),
            "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
        );
    }

    // --- SHA-256 Incremental Update ---

    #[test]
    fn sha256_incremental_split() {
        // Split "abc" across two update() calls — must produce the same
        // digest as a single-shot hash.
        let mut hasher = Sha256::new();
        hasher.update(b"a");
        hasher.update(b"bc");
        assert_eq!(
            hex_encode(&hasher.finalize()),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );
    }

    #[test]
    fn sha256_single_byte_updates() {
        // Feed "abc" one byte at a time.
        let mut hasher = Sha256::new();
        for &byte in b"abc" {
            hasher.update(&[byte]);
        }
        assert_eq!(
            hex_encode(&hasher.finalize()),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );
    }

    #[test]
    fn sha256_incremental_two_block_message() {
        // Split the 112-byte (two-block) message at an awkward boundary.
        let msg = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
        let mut hasher = Sha256::new();
        hasher.update(&msg[..70]);
        hasher.update(&msg[70..]);
        assert_eq!(
            hex_encode(&hasher.finalize()),
            "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
        );
    }

    #[test]
    fn sha256_default_trait() {
        // Ensure `Default` produces the same initial state as `new()`.
        let a = Sha256::new().finalize();
        let b = Sha256::default().finalize();
        assert_eq!(a, b);
    }

    // --- SHA-512 Test Vectors ---
    //
    // Vectors from NIST CAVP / FIPS 180-4 examples.

    #[test]
    fn sha512_empty() {
        let digest = Sha512::digest(b"");
        assert_eq!(
            hex_encode(&digest),
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce\
             47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
        );
    }

    #[test]
    fn sha512_abc() {
        let digest = Sha512::digest(b"abc");
        assert_eq!(
            hex_encode(&digest),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
             2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
        );
    }

    #[test]
    fn sha512_two_block() {
        // The same 112-byte message used for the SHA-256 two-block test.
        // For SHA-512 this fits in a single 128-byte block, but the padding
        // spills into a second block.
        let msg = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
        let digest = Sha512::digest(msg);
        assert_eq!(
            hex_encode(&digest),
            "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018\
             501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909",
        );
    }

    // --- SHA-512 Incremental Update ---

    #[test]
    fn sha512_incremental_split() {
        let mut hasher = Sha512::new();
        hasher.update(b"a");
        hasher.update(b"bc");
        assert_eq!(
            hex_encode(&hasher.finalize()),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
             2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
        );
    }

    #[test]
    fn sha512_single_byte_updates() {
        let mut hasher = Sha512::new();
        for &byte in b"abc" {
            hasher.update(&[byte]);
        }
        assert_eq!(
            hex_encode(&hasher.finalize()),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
             2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
        );
    }

    #[test]
    fn sha512_default_trait() {
        let a = Sha512::new().finalize();
        let b = Sha512::default().finalize();
        assert_eq!(a, b);
    }

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

    #[test]
    fn sha256_debug_does_not_leak_state() {
        // SECURITY: The Debug output must not contain internal hash state.
        let mut hasher = Sha256::new();
        hasher.update(b"secret data that must not appear");
        let debug = format!("{hasher:?}");
        assert!(debug.contains("Sha256"), "should contain the type name");
        assert!(
            debug.contains("total_len"),
            "should contain total_len field"
        );
        // The internal state words (H256 IV after compression) must not leak.
        assert!(!debug.contains("state"), "must not expose state field");
        assert!(!debug.contains("buffer"), "must not expose buffer field");
        assert!(!debug.contains("buf_len"), "must not expose buf_len field");
        assert!(
            !debug.contains("6a09e667"),
            "must not expose SHA-256 IV words"
        );
    }

    #[test]
    fn sha512_debug_does_not_leak_state() {
        // SECURITY: The Debug output must not contain internal hash state.
        let mut hasher = Sha512::new();
        hasher.update(b"secret data that must not appear");
        let debug = format!("{hasher:?}");
        assert!(debug.contains("Sha512"), "should contain the type name");
        assert!(
            debug.contains("total_len"),
            "should contain total_len field"
        );
        assert!(!debug.contains("state"), "must not expose state field");
        assert!(!debug.contains("buffer"), "must not expose buffer field");
        assert!(!debug.contains("buf_len"), "must not expose buf_len field");
        assert!(
            !debug.contains("6a09e667f3bcc908"),
            "must not expose SHA-512 IV words"
        );
    }
}