libvctrl_sha512 3.0.1

Zero-dependency SHA512, HMAC-SHA512, HKDF-SHA512, and optional SHA384
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
#![allow(clippy::inline_always)]
//! Pure Rust implementation of the SHA-512 cryptographic hash function.
//!
//! # Why this module exists
//!
//! This module provides a zero-dependency, `no_std`-compatible implementation
//! of SHA-512 as specified in FIPS 180-4. It is the foundational primitive
//! used by higher-level constructs such as HMAC and HKDF within this crate.
//!
//! The implementation emphasizes:
//! - **Incremental hashing** through the [`Hash`] state machine, allowing
//!   large inputs to be processed in chunks without loading everything into
//!   memory.
//! - **Constant-time verification** for comparing digests, mitigating timing
//!   side-channel attacks.
//! - **Zeroization** of sensitive state after use, preventing residual data
//!   from lingering in memory.
//!
//! # How it works
//!
//! SHA-512 follows the Merkle–Damgård construction with a 1024-bit block size
//! and a 512-bit output. The internal state consists of eight 64-bit working
//! variables (`a` through `h`) initialized with the first 64 bits of the
//! fractional parts of the square roots of the first eight prime numbers.
//!
//! For each 128-byte block, the message schedule expands 16 initial words into
//! 80 round words using bitwise rotations and modular additions. The
//! compression function then updates the working variables using the standard
//! SHA-512 logical functions (`Ch`, `Maj`, `Σ0`, `Σ1`, `σ0`, `σ1`) and
//! per-round constants derived from the cube roots of the first 80 primes.
//!
//! Padding appends a single `0x80` byte, zeros, and a 128-bit big-endian length
//! before finalization. The final digest is the concatenation of the eight
//! 64-bit state words in big-endian order.
//!
//! # Examples
//!
//! Compute the SHA-512 digest of `"abc"`:
//!
//! ```
//! use libvctrl_sha512::Hash;
//!
//! let digest = Hash::hash(b"abc");
//! let expected: [u8; 64] = [
//!     0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
//!     0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
//!     0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
//!     0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
//!     0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
//!     0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
//!     0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
//!     0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f,
//! ];
//! assert_eq!(digest, expected);
//! ```

use crate::utils::{load_be, store_be, verify};

/// Internal message schedule for the SHA-512 compression function.
///
/// This struct holds the 16 64-bit words of the current block. It provides
/// the logical functions and message expansion routine required by FIPS 180-4.
struct W([u64; 16]);

/// Internal state for SHA-512, consisting of eight 64-bit working variables.
///
/// The state is copied before processing each block so that the previous state
/// can be added after the compression function completes, per the Merkle–
/// Damgård construction.
#[derive(Copy, Clone)]
pub(crate) struct State(pub(crate) [u64; 8]);

impl W {
    /// Loads a 128-byte block into 16 big-endian 64-bit words.
    fn new(input: &[u8]) -> Self {
        let mut words = [0u64; 16];
        for (i, e) in words.iter_mut().enumerate() {
            *e = load_be(input, i * 8);
        }
        Self(words)
    }

    /// The `Ch(x, y, z)` logical function: `(x & y) ^ (!x & z)`.
    #[inline(always)]
    const fn ch(x: u64, y: u64, z: u64) -> u64 {
        (x & y) ^ (!x & z)
    }

    /// The `Maj(x, y, z)` logical function: `(x & y) ^ (x & z) ^ (y & z)`.
    #[inline(always)]
    const fn maj(x: u64, y: u64, z: u64) -> u64 {
        (x & y) ^ (x & z) ^ (y & z)
    }

    /// The `Σ0(x)` function: right rotations of 28, 34, and 39 bits XORed.
    #[inline(always)]
    const fn big_sigma0(x: u64) -> u64 {
        x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39)
    }

    /// The `Σ1(x)` function: right rotations of 14, 18, and 41 bits XORed.
    #[inline(always)]
    const fn big_sigma1(x: u64) -> u64 {
        x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41)
    }

    /// The `σ0(x)` function: right rotations of 1 and 8 bits XORed with a
    /// logical right shift of 7 bits.
    #[inline(always)]
    const fn small_sigma0(x: u64) -> u64 {
        x.rotate_right(1) ^ x.rotate_right(8) ^ (x >> 7)
    }

    /// The `σ1(x)` function: right rotations of 19 and 61 bits XORed with a
    /// logical right shift of 6 bits.
    #[inline(always)]
    const fn small_sigma1(x: u64) -> u64 {
        x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6)
    }

    /// Computes one word of the message schedule.
    ///
    /// The new word at index `dest` is derived from the existing words at
    /// indices `src_b`, `src_c`, and `src_d` according to the SHA-512 message
    /// expansion recurrence.
    #[cfg_attr(feature = "opt_size", inline(never))]
    #[cfg_attr(not(feature = "opt_size"), inline(always))]
    #[allow(clippy::many_single_char_names, clippy::missing_const_for_fn)]
    fn m(&mut self, dest: usize, src_b: usize, src_c: usize, src_d: usize) {
        let words = &mut self.0;
        words[dest] = words[dest]
            .wrapping_add(Self::small_sigma1(words[src_b]))
            .wrapping_add(words[src_c])
            .wrapping_add(Self::small_sigma0(words[src_d]));
    }

    /// Expands the first 16 words into the full 80-word message schedule.
    ///
    /// The expansion is performed in-place, overwriting the initial words with
    /// the newly computed schedule entries.
    #[inline]
    fn expand(&mut self) {
        self.m(0, 14, 9, 1);
        self.m(1, 15, 10, 2);
        self.m(2, 0, 11, 3);
        self.m(3, 1, 12, 4);
        self.m(4, 2, 13, 5);
        self.m(5, 3, 14, 6);
        self.m(6, 4, 15, 7);
        self.m(7, 5, 0, 8);
        self.m(8, 6, 1, 9);
        self.m(9, 7, 2, 10);
        self.m(10, 8, 3, 11);
        self.m(11, 9, 4, 12);
        self.m(12, 10, 5, 13);
        self.m(13, 11, 6, 14);
        self.m(14, 12, 7, 15);
        self.m(15, 13, 8, 0);
    }

    /// The SHA-512 compression function.
    ///
    /// This method applies the round function `f` for round index `i` using the
    /// round constant `k`. It updates the eight working variables in-place.
    #[cfg_attr(feature = "opt_size", inline(never))]
    #[cfg_attr(not(feature = "opt_size"), inline(always))]
    #[allow(clippy::missing_const_for_fn)]
    fn f(&self, state: &mut State, i: usize, k: u64) {
        let t = &mut state.0;
        t[(16 - i + 7) & 7] = t[(16 - i + 7) & 7]
            .wrapping_add(Self::big_sigma1(t[(16 - i + 4) & 7]))
            .wrapping_add(Self::ch(
                t[(16 - i + 4) & 7],
                t[(16 - i + 5) & 7],
                t[(16 - i + 6) & 7],
            ))
            .wrapping_add(k)
            .wrapping_add(self.0[i]);
        t[(16 - i + 3) & 7] = t[(16 - i + 3) & 7].wrapping_add(t[(16 - i + 7) & 7]);
        t[(16 - i + 7) & 7] = t[(16 - i + 7) & 7]
            .wrapping_add(Self::big_sigma0(t[(16 - i) & 7]))
            .wrapping_add(Self::maj(
                t[(16 - i) & 7],
                t[(16 - i + 1) & 7],
                t[(16 - i + 2) & 7],
            ));
    }

    /// Applies 16 rounds of the compression function using one group of round
    /// constants.
    ///
    /// The `s` parameter selects which group of 16 constants (out of five) to
    /// use. This design improves code reuse while maintaining performance.
    #[allow(clippy::unreadable_literal)]
    fn g(&self, state: &mut State, s: usize) {
        const ROUND_CONSTANTS: [u64; 80] = [
            0x428a_2f98_d728_ae22,
            0x7137_4491_23ef_65cd,
            0xb5c0_fbcf_ec4d_3b2f,
            0xe9b5_dba5_8189_dbbc,
            0x3956_c25b_f348_b538,
            0x59f1_11f1_b605_d019,
            0x923f_82a4_af19_4f9b,
            0xab1c_5ed5_da6d_8118,
            0xd807_aa98_a303_0242,
            0x1283_5b01_4570_6fbe,
            0x2431_85be_4ee4_b28c,
            0x550c_7dc3_d5ff_b4e2,
            0x72be_5d74_f27b_896f,
            0x80de_b1fe_3b16_96b1,
            0x9bdc_06a7_25c7_1235,
            0xc19b_f174_cf69_2694,
            0xe49b_69c1_9ef1_4ad2,
            0xefbe_4786_384f_25e3,
            0x0fc1_9dc6_8b8c_d5b5,
            0x240c_a1cc_77ac_9c65,
            0x2de9_2c6f_592b_0275,
            0x4a74_84aa_6ea6_e483,
            0x5cb0_a9dc_bd41_fbd4,
            0x76f9_88da_8311_53b5,
            0x983e_5152_ee66_dfab,
            0xa831_c66d_2db4_3210,
            0xb003_27c8_98fb_213f,
            0xbf59_7fc7_beef_0ee4,
            0xc6e0_0bf3_3da8_8fc2,
            0xd5a7_9147_930a_a725,
            0x06ca_6351_e003_826f,
            0x1429_2967_0a0e_6e70,
            0x27b7_0a85_46d2_2ffc,
            0x2e1b_2138_5c26_c926,
            0x4d2c_6dfc_5ac4_2aed,
            0x5338_0d13_9d95_b3df,
            0x650a_7354_8baf_63de,
            0x766a_0abb_3c77_b2a8,
            0x81c2_c92e_47ed_aee6,
            0x9272_2c85_1482_353b,
            0xa2bf_e8a1_4cf1_0364,
            0xa81a_664b_bc42_3001,
            0xc24b_8b70_d0f8_9791,
            0xc76c_51a3_0654_be30,
            0xd192_e819_d6ef_5218,
            0xd699_0624_5565_a910,
            0xf40e_3585_5771_202a,
            0x106a_a070_32bb_d1b8,
            0x19a4_c116_b8d2_d0c8,
            0x1e37_6c08_5141_ab53,
            0x2748_774c_df8e_eb99,
            0x34b0_bcb5_e19b_48a8,
            0x391c_0cb3_c5c9_5a63,
            0x4ed8_aa4a_e341_8acb,
            0x5b9c_ca4f_7763_e373,
            0x682e_6ff3_d6b2_b8a3,
            0x748f_82ee_5def_b2fc,
            0x78a5_636f_4317_2f60,
            0x84c8_7814_a1f0_ab72,
            0x8cc7_0208_1a64_39ec,
            0x90be_fffa_2363_1e28,
            0xa450_6ceb_de82_bde9,
            0xbef9_a3f7_b2c6_7915,
            0xc671_78f2_e372_532b,
            0xca27_3ece_ea26_619c,
            0xd186_b8c7_21c0_c207,
            0xeada_7dd6_cde0_eb1e,
            0xf57d_4f7f_ee6e_d178,
            0x06f0_67aa_7217_6fba,
            0x0a63_7dc5_a2c8_98a6,
            0x113f_9804_bef9_0dae,
            0x1b71_0b35_131c_471b,
            0x28db_77f5_2304_7d84,
            0x32ca_ab7b_40c7_2493,
            0x3c9e_be0a_15c9_bebc,
            0x431d_67c4_9c10_0d4c,
            0x4cc5_d4be_cb3e_42b6,
            0x597f_299c_fc65_7e2a,
            0x5fcb_6fab_3ad6_faec,
            0x6c44_198c_4a47_5817,
        ];
        let rc = &ROUND_CONSTANTS[s * 16..];
        self.f(state, 0, rc[0]);
        self.f(state, 1, rc[1]);
        self.f(state, 2, rc[2]);
        self.f(state, 3, rc[3]);
        self.f(state, 4, rc[4]);
        self.f(state, 5, rc[5]);
        self.f(state, 6, rc[6]);
        self.f(state, 7, rc[7]);
        self.f(state, 8, rc[8]);
        self.f(state, 9, rc[9]);
        self.f(state, 10, rc[10]);
        self.f(state, 11, rc[11]);
        self.f(state, 12, rc[12]);
        self.f(state, 13, rc[13]);
        self.f(state, 14, rc[14]);
        self.f(state, 15, rc[15]);
    }
}

impl State {
    /// Creates a new state initialized with the SHA-512 initial hash values.
    ///
    /// The initial values are the first 64 bits of the fractional parts of the
    /// square roots of the first eight primes.
    pub(crate) fn new() -> Self {
        const IV: [u8; 64] = [
            0x6a, 0x09, 0xe6, 0x67, 0xf3, 0xbc, 0xc9, 0x08, 0xbb, 0x67, 0xae, 0x85, 0x84, 0xca,
            0xa7, 0x3b, 0x3c, 0x6e, 0xf3, 0x72, 0xfe, 0x94, 0xf8, 0x2b, 0xa5, 0x4f, 0xf5, 0x3a,
            0x5f, 0x1d, 0x36, 0xf1, 0x51, 0x0e, 0x52, 0x7f, 0xad, 0xe6, 0x82, 0xd1, 0x9b, 0x05,
            0x68, 0x8c, 0x2b, 0x3e, 0x6c, 0x1f, 0x1f, 0x83, 0xd9, 0xab, 0xfb, 0x41, 0xbd, 0x6b,
            0x5b, 0xe0, 0xcd, 0x19, 0x13, 0x7e, 0x21, 0x79,
        ];
        let mut t = [0u64; 8];
        for (i, e) in t.iter_mut().enumerate() {
            *e = load_be(&IV, i * 8);
        }
        Self(t)
    }

    /// Adds another state to this one using wrapping addition.
    ///
    /// This is used after the compression function to incorporate the previous
    /// hash value, per the Merkle–Damgård construction.
    #[inline(always)]
    #[allow(clippy::missing_const_for_fn)]
    pub(crate) fn add(&mut self, x: &Self) {
        let sx = &mut self.0;
        let ex = &x.0;
        sx[0] = sx[0].wrapping_add(ex[0]);
        sx[1] = sx[1].wrapping_add(ex[1]);
        sx[2] = sx[2].wrapping_add(ex[2]);
        sx[3] = sx[3].wrapping_add(ex[3]);
        sx[4] = sx[4].wrapping_add(ex[4]);
        sx[5] = sx[5].wrapping_add(ex[5]);
        sx[6] = sx[6].wrapping_add(ex[6]);
        sx[7] = sx[7].wrapping_add(ex[7]);
    }

    /// Writes the state as 64 bytes in big-endian order.
    pub(crate) fn store(&self, out: &mut [u8]) {
        for (i, &e) in self.0.iter().enumerate() {
            store_be(out, i * 8, e);
        }
    }

    /// Processes as many 128-byte blocks as possible from the input.
    ///
    /// Returns the number of bytes remaining that do not form a complete block.
    pub(crate) fn blocks(&mut self, mut input: &[u8]) -> usize {
        let mut t = *self;
        let mut inlen = input.len();
        while inlen >= 128 {
            let mut w = W::new(input);
            w.g(&mut t, 0);
            w.expand();
            w.g(&mut t, 1);
            w.expand();
            w.g(&mut t, 2);
            w.expand();
            w.g(&mut t, 3);
            w.expand();
            w.g(&mut t, 4);
            t.add(self);
            self.0 = t.0;
            input = &input[128..];
            inlen -= 128;
        }
        inlen
    }
}

/// SHA-512 hasher that supports incremental updates and finalization.
///
/// # Design rationale
///
/// The struct maintains internal state (`state`), a buffer for incomplete
/// blocks (`w`), the number of buffered bytes (`r`), and the total message
/// length in bytes (`len`). This design allows callers to feed data in
/// arbitrary chunk sizes without requiring the entire message to be present in
/// memory at once.
///
/// The struct is [`Clone`], enabling state duplication for HMAC and HKDF
/// implementations that need to compute multiple hashes from a common
/// intermediate state.
///
/// # Examples
///
/// Incrementally hash a message in two parts:
///
/// ```
/// use libvctrl_sha512::Hash;
///
/// let mut hasher = Hash::new();
/// hasher.update(b"hello ");
/// hasher.update(b"world");
/// let digest = hasher.finalize();
/// assert_eq!(digest, Hash::hash(b"hello world"));
/// ```
#[derive(Clone)]
pub struct Hash {
    /// Current eight 64-bit working variables.
    pub(crate) state: State,

    /// Buffer for incomplete blocks. Only the first `r` bytes are valid.
    pub(crate) w: [u8; 128],

    /// Number of bytes currently buffered in `w`.
    pub(crate) r: usize,

    /// Total length of input processed so far, in bytes.
    pub(crate) len: u128,
}

impl Hash {
    /// Creates a new SHA-512 hasher with the standard initial state.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let hasher = Hash::new();
    /// // The hasher is empty and ready to accept data.
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: State::new(),
            r: 0,
            w: [0u8; 128],
            len: 0,
        }
    }

    /// Internal method to feed data into the hasher without consuming self.
    ///
    /// This is used by both [`update`](Hash::update) and the HMAC/HKDF
    /// implementations.
    pub(crate) fn update_inner<T: AsRef<[u8]>>(&mut self, input: T) {
        let input = input.as_ref();
        let mut n = input.len();
        self.len += n as u128;
        let av = 128 - self.r;
        let tc = core::cmp::min(n, av);
        self.w[self.r..self.r + tc].copy_from_slice(&input[0..tc]);
        self.r += tc;
        n -= tc;
        let pos = tc;
        if self.r == 128 {
            self.state.blocks(&self.w);
            self.r = 0;
        }
        if self.r == 0 && n > 0 {
            let rb = self.state.blocks(&input[pos..]);
            if rb > 0 {
                self.w[..rb].copy_from_slice(&input[pos + n - rb..]);
                self.r = rb;
            }
        }
    }

    /// Feeds data into the hasher.
    ///
    /// This method may be called any number of times before
    /// [`finalize`](Hash::finalize). The input is buffered until a full
    /// 128-byte block is available, at which point the block is processed.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let mut hasher = Hash::new();
    /// hasher.update(b"a");
    /// hasher.update(b"b");
    /// hasher.update(b"c");
    /// assert_eq!(hasher.finalize(), Hash::hash(b"abc"));
    /// ```
    pub fn update<T: AsRef<[u8]>>(&mut self, input: T) {
        self.update_inner(input);
    }

    /// Finalizes the hash computation and returns the 64-byte digest.
    ///
    /// # How it works
    ///
    /// The method consumes the hasher. It applies the standard SHA-512 padding:
    /// appends a `0x80` byte, pads with zeros until the length is 112 bytes
    /// (mod 128), and appends the original message length as a 128-bit
    /// big-endian integer. The padded data is then processed, and the final
    /// state is serialized as the digest.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let digest = Hash::hash(b"abc");
    /// assert_eq!(digest.len(), 64);
    /// ```
    #[must_use]
    pub fn finalize(mut self) -> [u8; 64] {
        let mut padded = [0u8; 256];
        padded[..self.r].copy_from_slice(&self.w[..self.r]);
        padded[self.r] = 0x80;
        let r = if self.r < 112 { 128 } else { 256 };
        let total_bits: u128 = self.len * 8;
        let high = (total_bits >> 64) as u64;
        #[allow(clippy::cast_possible_truncation)]
        let low = total_bits as u64;
        store_be(&mut padded, r - 16, high);
        store_be(&mut padded, r - 8, low);

        self.state.blocks(&padded[..r]);
        let mut out = [0u8; 64];
        self.state.store(&mut out);
        out
    }

    /// One-shot SHA-512 hash of the given input.
    ///
    /// This convenience method creates a new [`Hash`], feeds the entire input,
    /// and finalizes it. It is equivalent to:
    ///
    /// ```no_compile
    /// let mut h = Hash::new();
    /// h.update(input);
    /// h.finalize()
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let digest = Hash::hash(b"");
    /// let expected: [u8; 64] = [
    ///     0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd,
    ///     0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07,
    ///     0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc,
    ///     0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce,
    ///     0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0,
    ///     0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f,
    ///     0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81,
    ///     0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e,
    /// ];
    /// assert_eq!(digest, expected);
    /// ```
    pub fn hash<T: AsRef<[u8]>>(input: T) -> [u8; 64] {
        let mut h = Self::new();
        h.update(input);
        h.finalize()
    }

    /// Verifies that the hash of this instance matches the expected digest.
    ///
    /// # How it works
    ///
    /// Finalizes the current state and compares the resulting digest with
    /// `expected` using a constant-time comparison algorithm. This prevents
    /// timing attacks when verifying authentication tags or integrity checks.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let mut hasher = Hash::new();
    /// hasher.update(b"abc");
    /// let expected = Hash::hash(b"abc");
    /// assert!(hasher.verify(&expected));
    /// ```
    #[must_use]
    pub fn verify(self, expected: &[u8; 64]) -> bool {
        let out = self.finalize();
        verify(&out, expected)
    }

    /// Zeroizes the internal state, buffer, and length counter.
    ///
    /// This method overwrites all sensitive internal data with zeros and
    /// inserts a compiler fence to prevent the optimizer from eliminating the
    /// writes. It is useful for security-sensitive applications that must
    /// ensure no residual hash state remains in memory after use.
    ///
    /// # Examples
    ///
    /// ```
    /// use libvctrl_sha512::Hash;
    ///
    /// let mut hasher = Hash::new();
    /// hasher.update(b"secret");
    /// hasher.zeroize();
    /// // The hasher is now in a clean state and can be reused if desired.
    /// ```
    pub fn zeroize(&mut self) {
        self.state.0.fill(0);
        self.w.fill(0);
        self.r = 0;
        self.len = 0;
        core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
    }
}

impl Default for Hash {
    /// Returns a new SHA-512 hasher with the default initial state.
    ///
    /// Equivalent to [`Hash::new`].
    fn default() -> Self {
        Self::new()
    }
}