rscrypto 0.1.1

Pure Rust cryptography, hardware-accelerated: BLAKE3, SHA-2/3, AES-GCM, ChaCha20-Poly1305, Ed25519, X25519, HMAC, HKDF, Argon2, CRC. no_std, WASM, ten CPU architectures.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! HMAC-SHA2 family (RFC 2104, FIPS 198-1).

use crate::{
  hashes::crypto::{
    Sha256, Sha384, Sha512,
    dispatch_util::len_hint_from_u64,
    sha256::{H0 as SHA256_H0, Sha256Prefix, dispatch as sha256_dispatch},
    sha384::{H0 as SHA384_H0, Sha384Prefix, dispatch as sha384_dispatch},
    sha512::{H0 as SHA512_H0, Sha512Prefix, dispatch as sha512_dispatch},
  },
  traits::{Digest, Mac, VerificationError, ct},
};

const SHA256_BLOCK_SIZE: usize = 64;
const SHA256_TAG_SIZE: usize = 32;
const SHA512_FAMILY_BLOCK_SIZE: usize = 128;
const SHA384_TAG_SIZE: usize = 48;
const SHA512_TAG_SIZE: usize = 64;

#[inline]
pub(crate) fn hmac_prefix_state<const BLOCK_SIZE: usize, T>(
  key_block: &mut [u8; BLOCK_SIZE],
  build: impl FnOnce(&[u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]) -> T,
) -> T {
  let mut ipad = [0x36u8; BLOCK_SIZE];
  let mut opad = [0x5Cu8; BLOCK_SIZE];
  for ((ipad_byte, opad_byte), key_byte) in ipad.iter_mut().zip(opad.iter_mut()).zip(key_block.iter().copied()) {
    *ipad_byte ^= key_byte;
    *opad_byte ^= key_byte;
  }

  let result = build(&ipad, &opad);

  ct::zeroize(key_block);
  ct::zeroize(&mut ipad);
  ct::zeroize(&mut opad);

  result
}

/// HMAC-SHA256 authentication state.
///
/// # Examples
///
/// ```rust
/// use rscrypto::{HmacSha256, Mac};
///
/// let key = b"shared-secret";
/// let data = b"auth message";
///
/// let tag = HmacSha256::mac(key, data);
///
/// let mut mac = HmacSha256::new(key);
/// mac.update(b"auth ");
/// mac.update(b"message");
/// assert_eq!(mac.finalize(), tag);
/// assert!(mac.verify(&tag).is_ok());
/// ```
#[derive(Clone)]
pub struct HmacSha256 {
  inner: Sha256,
  inner_init: Sha256Prefix,
  outer_init: Sha256Prefix,
}

impl core::fmt::Debug for HmacSha256 {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("HmacSha256").finish_non_exhaustive()
  }
}

impl HmacSha256 {
  /// HMAC-SHA256 block size in bytes.
  pub const BLOCK_SIZE: usize = SHA256_BLOCK_SIZE;

  /// HMAC-SHA256 tag size in bytes.
  pub const TAG_SIZE: usize = SHA256_TAG_SIZE;

  /// Compute the HMAC tag of `data` in one shot.
  #[inline]
  #[must_use]
  pub fn mac(key: &[u8], data: &[u8]) -> [u8; SHA256_TAG_SIZE] {
    <Self as Mac>::mac(key, data)
  }

  /// Verify `expected` against the HMAC tag of `data` in constant time.
  #[inline]
  #[must_use = "HMAC verification must be checked; a dropped Result silently accepts a forged tag"]
  pub fn verify_tag(key: &[u8], data: &[u8], expected: &[u8; SHA256_TAG_SIZE]) -> Result<(), VerificationError> {
    <Self as Mac>::verify_tag(key, data, expected)
  }
}

impl Mac for HmacSha256 {
  const TAG_SIZE: usize = SHA256_TAG_SIZE;
  type Tag = [u8; SHA256_TAG_SIZE];

  fn new(key: &[u8]) -> Self {
    let mut key_block = [0u8; SHA256_BLOCK_SIZE];
    if key.len() > SHA256_BLOCK_SIZE {
      let digest = Sha256::digest(key);
      for (dst, src) in key_block.iter_mut().zip(digest.iter()) {
        *dst = *src;
      }
    } else {
      for (dst, src) in key_block.iter_mut().zip(key.iter()) {
        *dst = *src;
      }
    }

    let (inner_init, inner_init_prefix, outer_init_prefix) = hmac_prefix_state(&mut key_block, |ipad, opad| {
      let mut inner_init = Sha256::new();
      inner_init.update(ipad);

      let mut outer_init = Sha256::new();
      outer_init.update(opad);

      let inner_init_prefix = inner_init.aligned_prefix();
      let outer_init_prefix = outer_init.aligned_prefix();

      (inner_init, inner_init_prefix, outer_init_prefix)
    });

    Self {
      inner: inner_init,
      inner_init: inner_init_prefix,
      outer_init: outer_init_prefix,
    }
  }

  #[inline]
  fn update(&mut self, data: &[u8]) {
    self.inner.update(data);
  }

  #[inline]
  fn finalize(&self) -> Self::Tag {
    let inner_hash = self.inner.finalize();
    let mut outer = Sha256::from_aligned_prefix(self.outer_init);
    outer.update(&inner_hash);
    outer.finalize()
  }

  #[inline]
  fn reset(&mut self) {
    self.inner.reset_to_aligned_prefix(self.inner_init);
  }

  /// Oneshot HMAC-SHA256: merges compress calls for small inputs and batches
  /// zeroization under a single compiler fence.
  ///
  /// For data <= 256 B the entire padded inner message is built on the stack
  /// and compressed in one call, eliminating per-call overhead (function-pointer
  /// dispatch, state save/restore) that dominates on fast SHA2-CE cores.
  /// The outer hash is always merged into a single 128-byte (2-block) call.
  #[inline]
  #[allow(clippy::indexing_slicing)] // All indices bounded by prior length checks + fixed-size arrays.
  fn mac(key: &[u8], data: &[u8]) -> Self::Tag {
    let mut ipad = [0x36u8; SHA256_BLOCK_SIZE];
    if key.len() > SHA256_BLOCK_SIZE {
      let digest = Sha256::digest(key);
      for (ip, &kb) in ipad[..SHA256_TAG_SIZE].iter_mut().zip(digest.iter()) {
        *ip = kb ^ 0x36;
      }
    } else {
      for (ip, &kb) in ipad[..key.len()].iter_mut().zip(key.iter()) {
        *ip = kb ^ 0x36;
      }
    }

    let total_inner = (SHA256_BLOCK_SIZE as u64).strict_add(data.len() as u64);
    let compress = sha256_dispatch::compress_dispatch().select(len_hint_from_u64(total_inner));
    let total_inner_bits = total_inner.strict_mul(8);

    let mut state = SHA256_H0;

    const INLINE_DATA_MAX: usize = 256;

    if data.len() <= INLINE_DATA_MAX {
      let data_end = SHA256_BLOCK_SIZE.strict_add(data.len());
      let padded = data_end.strict_add(9).strict_add(63).strict_div(64).strict_mul(64);

      macro_rules! compress_inline_inner {
        ($len:expr) => {{
          let mut inner_buf = [0u8; $len];
          inner_buf[..SHA256_BLOCK_SIZE].copy_from_slice(&ipad);
          inner_buf[SHA256_BLOCK_SIZE..data_end].copy_from_slice(data);
          inner_buf[data_end] = 0x80;
          inner_buf[padded.strict_sub(8)..padded].copy_from_slice(&total_inner_bits.to_be_bytes());
          compress(&mut state, &inner_buf);
          ct::zeroize_no_fence(&mut inner_buf);
        }};
      }

      match padded {
        128 => compress_inline_inner!(128),
        192 => compress_inline_inner!(192),
        256 => compress_inline_inner!(256),
        320 => compress_inline_inner!(320),
        384 => compress_inline_inner!(384),
        _ => unreachable!("HMAC-SHA256 inline inner padding is bounded to 128..=384 bytes"),
      }
    } else {
      compress(&mut state, &ipad);

      let full_len = data.len().strict_sub(data.len() % SHA256_BLOCK_SIZE);
      if full_len != 0 {
        compress(&mut state, &data[..full_len]);
      }
      let rest = &data[full_len..];

      let mut inner_buf = [0u8; SHA256_BLOCK_SIZE];
      inner_buf[..rest.len()].copy_from_slice(rest);
      inner_buf[rest.len()] = 0x80;
      if rest.len() >= 56 {
        compress(&mut state, &inner_buf[..SHA256_BLOCK_SIZE]);
        inner_buf[..SHA256_BLOCK_SIZE].fill(0);
      }
      inner_buf[56..SHA256_BLOCK_SIZE].copy_from_slice(&total_inner_bits.to_be_bytes());
      compress(&mut state, &inner_buf[..SHA256_BLOCK_SIZE]);
      ct::zeroize_no_fence(&mut inner_buf);
    }

    let mut outer = [0u8; 128];
    for (o, &ip) in outer[..SHA256_BLOCK_SIZE].iter_mut().zip(ipad.iter()) {
      *o = ip ^ 0x6a;
    }
    for (i, &word) in state.iter().enumerate() {
      let off = SHA256_BLOCK_SIZE.strict_add(i.strict_mul(4));
      outer[off..off.strict_add(4)].copy_from_slice(&word.to_be_bytes());
    }
    outer[SHA256_BLOCK_SIZE.strict_add(SHA256_TAG_SIZE)] = 0x80;
    outer[120..128].copy_from_slice(&768u64.to_be_bytes());

    state = SHA256_H0;
    compress(&mut state, &outer);

    let mut tag = [0u8; SHA256_TAG_SIZE];
    for (chunk, &word) in tag.chunks_exact_mut(4).zip(state.iter()) {
      chunk.copy_from_slice(&word.to_be_bytes());
    }

    ct::zeroize_no_fence(&mut ipad);
    ct::zeroize_no_fence(&mut outer);
    for word in state.iter_mut() {
      // SAFETY: word is a valid, aligned, dereferenceable pointer to initialized memory.
      unsafe { core::ptr::write_volatile(word, 0) };
    }
    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);

    tag
  }

  #[inline]
  fn verify(&self, expected: &Self::Tag) -> Result<(), VerificationError> {
    if ct::constant_time_eq(&self.finalize(), expected) {
      Ok(())
    } else {
      Err(VerificationError::new())
    }
  }
}

impl Drop for HmacSha256 {
  fn drop(&mut self) {
    self.inner_init.zeroize();
    self.outer_init.zeroize();
  }
}

/// HMAC-SHA384 authentication state.
///
/// # Examples
///
/// ```rust
/// use rscrypto::{HmacSha384, Mac};
///
/// let key = b"shared-secret";
/// let data = b"auth message";
///
/// let tag = HmacSha384::mac(key, data);
///
/// let mut mac = HmacSha384::new(key);
/// mac.update(b"auth ");
/// mac.update(b"message");
/// assert_eq!(mac.finalize(), tag);
/// assert!(HmacSha384::verify_tag(key, data, &tag).is_ok());
/// ```
#[derive(Clone)]
pub struct HmacSha384 {
  inner: Sha384,
  inner_init: Sha384Prefix,
  outer_init: Sha384Prefix,
}

impl core::fmt::Debug for HmacSha384 {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("HmacSha384").finish_non_exhaustive()
  }
}

impl HmacSha384 {
  /// HMAC-SHA384 block size in bytes.
  pub const BLOCK_SIZE: usize = SHA512_FAMILY_BLOCK_SIZE;

  /// HMAC-SHA384 tag size in bytes.
  pub const TAG_SIZE: usize = SHA384_TAG_SIZE;

  /// Compute the HMAC tag of `data` in one shot.
  #[inline]
  #[must_use]
  pub fn mac(key: &[u8], data: &[u8]) -> [u8; SHA384_TAG_SIZE] {
    <Self as Mac>::mac(key, data)
  }

  /// Verify `expected` against the HMAC tag of `data` in constant time.
  #[inline]
  #[must_use = "HMAC verification must be checked; a dropped Result silently accepts a forged tag"]
  pub fn verify_tag(key: &[u8], data: &[u8], expected: &[u8; SHA384_TAG_SIZE]) -> Result<(), VerificationError> {
    <Self as Mac>::verify_tag(key, data, expected)
  }

  #[cfg(test)]
  pub(crate) fn new_with_compress_for_test(
    key: &[u8],
    compress: crate::hashes::crypto::sha384::kernels::CompressBlocksFn,
  ) -> Self {
    let mut key_block = [0u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha384::digest(key);
      key_block[..SHA384_TAG_SIZE].copy_from_slice(&digest);
    } else {
      key_block[..key.len()].copy_from_slice(key);
    }

    let (inner, inner_init, outer_init) = hmac_prefix_state(&mut key_block, |ipad, opad| {
      let mut inner = Sha384::new_with_compress_for_test(compress);
      inner.update(ipad);
      let inner_init = inner.aligned_prefix();

      let mut outer = Sha384::new_with_compress_for_test(compress);
      outer.update(opad);
      let outer_init = outer.aligned_prefix();

      (inner, inner_init, outer_init)
    });

    Self {
      inner,
      inner_init,
      outer_init,
    }
  }

  #[cfg(test)]
  pub(crate) fn mac_with_compress_for_test(
    key: &[u8],
    data: &[u8],
    compress: crate::hashes::crypto::sha384::kernels::CompressBlocksFn,
  ) -> [u8; SHA384_TAG_SIZE] {
    let mut mac = Self::new_with_compress_for_test(key, compress);
    mac.update(data);
    mac.finalize()
  }
}

impl Mac for HmacSha384 {
  const TAG_SIZE: usize = SHA384_TAG_SIZE;
  type Tag = [u8; SHA384_TAG_SIZE];

  fn new(key: &[u8]) -> Self {
    let mut key_block = [0u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha384::digest(key);
      for (dst, src) in key_block.iter_mut().zip(digest.iter()) {
        *dst = *src;
      }
    } else {
      for (dst, src) in key_block.iter_mut().zip(key.iter()) {
        *dst = *src;
      }
    }

    let (inner_init, inner_init_prefix, outer_init_prefix) = hmac_prefix_state(&mut key_block, |ipad, opad| {
      let mut inner_init = Sha384::new();
      inner_init.update(ipad);

      let mut outer_init = Sha384::new();
      outer_init.update(opad);

      let inner_init_prefix = inner_init.aligned_prefix();
      let outer_init_prefix = outer_init.aligned_prefix();

      (inner_init, inner_init_prefix, outer_init_prefix)
    });

    Self {
      inner: inner_init,
      inner_init: inner_init_prefix,
      outer_init: outer_init_prefix,
    }
  }

  #[inline]
  fn update(&mut self, data: &[u8]) {
    self.inner.update(data);
  }

  #[inline]
  fn finalize(&self) -> Self::Tag {
    let inner_hash = self.inner.finalize();
    let mut outer = Sha384::from_aligned_prefix(self.outer_init);
    outer.update(&inner_hash);
    outer.finalize()
  }

  #[inline]
  fn reset(&mut self) {
    self.inner.reset_to_aligned_prefix(self.inner_init);
  }

  #[inline]
  #[allow(clippy::indexing_slicing)] // All indices bounded by prior length checks + fixed-size arrays.
  fn mac(key: &[u8], data: &[u8]) -> Self::Tag {
    const INLINE_DATA_MAX: usize = 256;

    let mut ipad = [0x36u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha384::digest(key);
      for (ip, &kb) in ipad[..SHA384_TAG_SIZE].iter_mut().zip(digest.iter()) {
        *ip = kb ^ 0x36;
      }
    } else {
      for (ip, &kb) in ipad[..key.len()].iter_mut().zip(key.iter()) {
        *ip = kb ^ 0x36;
      }
    }

    let total_inner = (SHA512_FAMILY_BLOCK_SIZE as u64).strict_add(data.len() as u64);
    let compress = sha384_dispatch::compress_dispatch().select(len_hint_from_u64(total_inner));
    let total_inner_bits = total_inner.strict_mul(8);

    let mut state = SHA384_H0;

    if data.len() <= INLINE_DATA_MAX {
      let data_end = SHA512_FAMILY_BLOCK_SIZE.strict_add(data.len());
      let padded = data_end.strict_add(17).strict_add(127).strict_div(128).strict_mul(128);

      macro_rules! compress_inline_inner {
        ($len:expr) => {{
          let mut inner_buf = [0u8; $len];
          inner_buf[..SHA512_FAMILY_BLOCK_SIZE].copy_from_slice(&ipad);
          inner_buf[SHA512_FAMILY_BLOCK_SIZE..data_end].copy_from_slice(data);
          inner_buf[data_end] = 0x80;
          inner_buf[padded.strict_sub(8)..padded].copy_from_slice(&total_inner_bits.to_be_bytes());
          compress(&mut state, &inner_buf);
          ct::zeroize_no_fence(&mut inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
        }};
      }

      match padded {
        256 => compress_inline_inner!(256),
        384 => compress_inline_inner!(384),
        512 => compress_inline_inner!(512),
        _ => unreachable!("HMAC-SHA384 inline inner padding is bounded to 256..=512 bytes"),
      }
    } else {
      compress(&mut state, &ipad);

      let full_len = data.len().strict_sub(data.len() % SHA512_FAMILY_BLOCK_SIZE);
      if full_len != 0 {
        compress(&mut state, &data[..full_len]);
      }
      let rest = &data[full_len..];

      let mut inner_buf = [0u8; SHA512_FAMILY_BLOCK_SIZE];
      inner_buf[..rest.len()].copy_from_slice(rest);
      inner_buf[rest.len()] = 0x80;
      if rest.len() >= 112 {
        compress(&mut state, &inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
        inner_buf[..SHA512_FAMILY_BLOCK_SIZE].fill(0);
      }
      inner_buf[120..SHA512_FAMILY_BLOCK_SIZE].copy_from_slice(&total_inner_bits.to_be_bytes());
      compress(&mut state, &inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
      ct::zeroize_no_fence(&mut inner_buf);
    }

    let mut outer = [0u8; 256];
    for (o, &ip) in outer[..SHA512_FAMILY_BLOCK_SIZE].iter_mut().zip(ipad.iter()) {
      *o = ip ^ 0x6a;
    }
    for (i, &word) in state.iter().take(6).enumerate() {
      let off = SHA512_FAMILY_BLOCK_SIZE.strict_add(i.strict_mul(8));
      outer[off..off.strict_add(8)].copy_from_slice(&word.to_be_bytes());
    }
    outer[SHA512_FAMILY_BLOCK_SIZE.strict_add(SHA384_TAG_SIZE)] = 0x80;
    outer[248..256].copy_from_slice(&1408u64.to_be_bytes());

    state = SHA384_H0;
    compress(&mut state, &outer);

    let mut tag = [0u8; SHA384_TAG_SIZE];
    for (chunk, &word) in tag.chunks_exact_mut(8).zip(state.iter()) {
      chunk.copy_from_slice(&word.to_be_bytes());
    }

    ct::zeroize_no_fence(&mut ipad);
    ct::zeroize_no_fence(&mut outer[..SHA512_FAMILY_BLOCK_SIZE]);
    for word in state.iter_mut() {
      // SAFETY: word is a valid, aligned, dereferenceable pointer to initialized memory.
      unsafe { core::ptr::write_volatile(word, 0) };
    }
    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);

    tag
  }

  #[inline]
  fn verify(&self, expected: &Self::Tag) -> Result<(), VerificationError> {
    if ct::constant_time_eq(self.finalize().as_ref(), expected.as_ref()) {
      Ok(())
    } else {
      Err(VerificationError::new())
    }
  }
}

impl Drop for HmacSha384 {
  fn drop(&mut self) {
    self.inner_init.zeroize();
    self.outer_init.zeroize();
  }
}

/// HMAC-SHA512 authentication state.
///
/// # Examples
///
/// ```rust
/// use rscrypto::{HmacSha512, Mac};
///
/// let key = b"shared-secret";
/// let data = b"auth message";
///
/// let tag = HmacSha512::mac(key, data);
///
/// let mut mac = HmacSha512::new(key);
/// mac.update(b"auth ");
/// mac.update(b"message");
/// assert_eq!(mac.finalize(), tag);
/// assert!(HmacSha512::verify_tag(key, data, &tag).is_ok());
/// ```
#[derive(Clone)]
pub struct HmacSha512 {
  inner: Sha512,
  inner_init: Sha512Prefix,
  outer_init: Sha512Prefix,
}

impl core::fmt::Debug for HmacSha512 {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("HmacSha512").finish_non_exhaustive()
  }
}

impl HmacSha512 {
  /// HMAC-SHA512 block size in bytes.
  pub const BLOCK_SIZE: usize = SHA512_FAMILY_BLOCK_SIZE;

  /// HMAC-SHA512 tag size in bytes.
  pub const TAG_SIZE: usize = SHA512_TAG_SIZE;

  /// Compute the HMAC tag of `data` in one shot.
  #[inline]
  #[must_use]
  pub fn mac(key: &[u8], data: &[u8]) -> [u8; SHA512_TAG_SIZE] {
    <Self as Mac>::mac(key, data)
  }

  /// Verify `expected` against the HMAC tag of `data` in constant time.
  #[inline]
  #[must_use = "HMAC verification must be checked; a dropped Result silently accepts a forged tag"]
  pub fn verify_tag(key: &[u8], data: &[u8], expected: &[u8; SHA512_TAG_SIZE]) -> Result<(), VerificationError> {
    <Self as Mac>::verify_tag(key, data, expected)
  }

  #[cfg(test)]
  pub(crate) fn new_with_compress_for_test(
    key: &[u8],
    compress: crate::hashes::crypto::sha512::kernels::CompressBlocksFn,
  ) -> Self {
    let mut key_block = [0u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha512::digest(key);
      key_block[..SHA512_TAG_SIZE].copy_from_slice(&digest);
    } else {
      key_block[..key.len()].copy_from_slice(key);
    }

    let (inner, inner_init, outer_init) = hmac_prefix_state(&mut key_block, |ipad, opad| {
      let mut inner = Sha512::new_with_compress_for_test(compress);
      inner.update(ipad);
      let inner_init = inner.aligned_prefix();

      let mut outer = Sha512::new_with_compress_for_test(compress);
      outer.update(opad);
      let outer_init = outer.aligned_prefix();

      (inner, inner_init, outer_init)
    });

    Self {
      inner,
      inner_init,
      outer_init,
    }
  }

  #[cfg(test)]
  pub(crate) fn mac_with_compress_for_test(
    key: &[u8],
    data: &[u8],
    compress: crate::hashes::crypto::sha512::kernels::CompressBlocksFn,
  ) -> [u8; SHA512_TAG_SIZE] {
    let mut mac = Self::new_with_compress_for_test(key, compress);
    mac.update(data);
    mac.finalize()
  }
}

impl Mac for HmacSha512 {
  const TAG_SIZE: usize = SHA512_TAG_SIZE;
  type Tag = [u8; SHA512_TAG_SIZE];

  fn new(key: &[u8]) -> Self {
    let mut key_block = [0u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha512::digest(key);
      for (dst, src) in key_block.iter_mut().zip(digest.iter()) {
        *dst = *src;
      }
    } else {
      for (dst, src) in key_block.iter_mut().zip(key.iter()) {
        *dst = *src;
      }
    }

    let (inner_init, inner_init_prefix, outer_init_prefix) = hmac_prefix_state(&mut key_block, |ipad, opad| {
      let mut inner_init = Sha512::new();
      inner_init.update(ipad);

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

      let inner_init_prefix = inner_init.aligned_prefix();
      let outer_init_prefix = outer_init.aligned_prefix();

      (inner_init, inner_init_prefix, outer_init_prefix)
    });

    Self {
      inner: inner_init,
      inner_init: inner_init_prefix,
      outer_init: outer_init_prefix,
    }
  }

  #[inline]
  fn update(&mut self, data: &[u8]) {
    self.inner.update(data);
  }

  #[inline]
  fn finalize(&self) -> Self::Tag {
    let inner_hash = self.inner.finalize();
    let mut outer = Sha512::from_aligned_prefix(self.outer_init);
    outer.update(&inner_hash);
    outer.finalize()
  }

  #[inline]
  fn reset(&mut self) {
    self.inner.reset_to_aligned_prefix(self.inner_init);
  }

  #[inline]
  #[allow(clippy::indexing_slicing)] // All indices bounded by prior length checks + fixed-size arrays.
  fn mac(key: &[u8], data: &[u8]) -> Self::Tag {
    const INLINE_DATA_MAX: usize = 256;

    let mut ipad = [0x36u8; SHA512_FAMILY_BLOCK_SIZE];
    if key.len() > SHA512_FAMILY_BLOCK_SIZE {
      let digest = Sha512::digest(key);
      for (ip, &kb) in ipad[..SHA512_TAG_SIZE].iter_mut().zip(digest.iter()) {
        *ip = kb ^ 0x36;
      }
    } else {
      for (ip, &kb) in ipad[..key.len()].iter_mut().zip(key.iter()) {
        *ip = kb ^ 0x36;
      }
    }

    let total_inner = (SHA512_FAMILY_BLOCK_SIZE as u64).strict_add(data.len() as u64);
    let compress = sha512_dispatch::compress_dispatch().select(len_hint_from_u64(total_inner));
    let total_inner_bits = total_inner.strict_mul(8);

    let mut state = SHA512_H0;

    if data.len() <= INLINE_DATA_MAX {
      let data_end = SHA512_FAMILY_BLOCK_SIZE.strict_add(data.len());
      let padded = data_end.strict_add(17).strict_add(127).strict_div(128).strict_mul(128);

      macro_rules! compress_inline_inner {
        ($len:expr) => {{
          let mut inner_buf = [0u8; $len];
          inner_buf[..SHA512_FAMILY_BLOCK_SIZE].copy_from_slice(&ipad);
          inner_buf[SHA512_FAMILY_BLOCK_SIZE..data_end].copy_from_slice(data);
          inner_buf[data_end] = 0x80;
          inner_buf[padded.strict_sub(8)..padded].copy_from_slice(&total_inner_bits.to_be_bytes());
          compress(&mut state, &inner_buf);
          ct::zeroize_no_fence(&mut inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
        }};
      }

      match padded {
        256 => compress_inline_inner!(256),
        384 => compress_inline_inner!(384),
        512 => compress_inline_inner!(512),
        _ => unreachable!("HMAC-SHA512 inline inner padding is bounded to 256..=512 bytes"),
      }
    } else {
      compress(&mut state, &ipad);

      let full_len = data.len().strict_sub(data.len() % SHA512_FAMILY_BLOCK_SIZE);
      if full_len != 0 {
        compress(&mut state, &data[..full_len]);
      }
      let rest = &data[full_len..];

      let mut inner_buf = [0u8; SHA512_FAMILY_BLOCK_SIZE];
      inner_buf[..rest.len()].copy_from_slice(rest);
      inner_buf[rest.len()] = 0x80;
      if rest.len() >= 112 {
        compress(&mut state, &inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
        inner_buf[..SHA512_FAMILY_BLOCK_SIZE].fill(0);
      }
      inner_buf[120..SHA512_FAMILY_BLOCK_SIZE].copy_from_slice(&total_inner_bits.to_be_bytes());
      compress(&mut state, &inner_buf[..SHA512_FAMILY_BLOCK_SIZE]);
      ct::zeroize_no_fence(&mut inner_buf);
    }

    let mut outer = [0u8; 256];
    for (o, &ip) in outer[..SHA512_FAMILY_BLOCK_SIZE].iter_mut().zip(ipad.iter()) {
      *o = ip ^ 0x6a;
    }
    for (i, &word) in state.iter().enumerate() {
      let off = SHA512_FAMILY_BLOCK_SIZE.strict_add(i.strict_mul(8));
      outer[off..off.strict_add(8)].copy_from_slice(&word.to_be_bytes());
    }
    outer[SHA512_FAMILY_BLOCK_SIZE.strict_add(SHA512_TAG_SIZE)] = 0x80;
    outer[248..256].copy_from_slice(&1536u64.to_be_bytes());

    state = SHA512_H0;
    compress(&mut state, &outer);

    let mut tag = [0u8; SHA512_TAG_SIZE];
    for (chunk, &word) in tag.chunks_exact_mut(8).zip(state.iter()) {
      chunk.copy_from_slice(&word.to_be_bytes());
    }

    ct::zeroize_no_fence(&mut ipad);
    ct::zeroize_no_fence(&mut outer[..SHA512_FAMILY_BLOCK_SIZE]);
    for word in state.iter_mut() {
      // SAFETY: word is a valid, aligned, dereferenceable pointer to initialized memory.
      unsafe { core::ptr::write_volatile(word, 0) };
    }
    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);

    tag
  }

  #[inline]
  fn verify(&self, expected: &Self::Tag) -> Result<(), VerificationError> {
    if ct::constant_time_eq(self.finalize().as_ref(), expected.as_ref()) {
      Ok(())
    } else {
      Err(VerificationError::new())
    }
  }
}

impl Drop for HmacSha512 {
  fn drop(&mut self) {
    self.inner_init.zeroize();
    self.outer_init.zeroize();
  }
}

#[cfg(test)]
mod tests {
  use alloc::vec::Vec;

  use hmac::{Hmac, Mac as _, digest::KeyInit};

  use super::*;
  use crate::hashes::crypto::{
    sha384::kernels::{
      ALL as SHA384_KERNELS, Sha384KernelId, compress_blocks_fn as sha384_compress_blocks_fn,
      required_caps as sha384_required_caps,
    },
    sha512::kernels::{
      ALL as SHA512_KERNELS, Sha512KernelId, compress_blocks_fn as sha512_compress_blocks_fn,
      required_caps as sha512_required_caps,
    },
  };

  type RustCryptoHmacSha384 = Hmac<sha2::Sha384>;
  type RustCryptoHmacSha512 = Hmac<sha2::Sha512>;

  fn pattern(len: usize, mul: u8, add: u8) -> Vec<u8> {
    (0..len)
      .map(|i| {
        (i as u8)
          .wrapping_mul(mul)
          .wrapping_add(((i >> 3) as u8).wrapping_add(add))
      })
      .collect()
  }

  fn oracle_hmac_sha384(key: &[u8], data: &[u8]) -> [u8; SHA384_TAG_SIZE] {
    let mut mac = RustCryptoHmacSha384::new_from_slice(key).unwrap();
    mac.update(data);
    let bytes = mac.finalize().into_bytes();
    let mut tag = [0u8; SHA384_TAG_SIZE];
    tag.copy_from_slice(&bytes);
    tag
  }

  fn oracle_hmac_sha512(key: &[u8], data: &[u8]) -> [u8; SHA512_TAG_SIZE] {
    let mut mac = RustCryptoHmacSha512::new_from_slice(key).unwrap();
    mac.update(data);
    let bytes = mac.finalize().into_bytes();
    let mut tag = [0u8; SHA512_TAG_SIZE];
    tag.copy_from_slice(&bytes);
    tag
  }

  fn assert_hmac_sha384_kernel(id: Sha384KernelId) {
    let compress = sha384_compress_blocks_fn(id);
    let cases = [
      (0usize, 0usize, 1usize),
      (1, 1, 1),
      (16, 31, 7),
      (48, 127, 31),
      (80, 128, 64),
      (160, 129, 65),
      (256, 255, 128),
      (300, 1024, 257),
    ];

    for &(key_len, data_len, chunk_len) in &cases {
      let key = pattern(key_len, 17, 3);
      let data = pattern(data_len, 29, 11);
      let expected = oracle_hmac_sha384(&key, &data);

      assert_eq!(
        HmacSha384::mac(&key, &data),
        expected,
        "sha384 public oneshot mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );
      assert_eq!(
        HmacSha384::mac_with_compress_for_test(&key, &data, compress),
        expected,
        "sha384 forced oneshot mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );

      let mut streaming = HmacSha384::new_with_compress_for_test(&key, compress);
      for chunk in data.chunks(chunk_len) {
        streaming.update(chunk);
      }
      assert_eq!(
        streaming.finalize(),
        expected,
        "sha384 forced streaming mismatch kernel={} key_len={} data_len={} chunk_len={}",
        id.as_str(),
        key_len,
        data_len,
        chunk_len
      );

      streaming.reset();
      streaming.update(&data);
      assert_eq!(
        streaming.finalize(),
        expected,
        "sha384 forced reset mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );
    }
  }

  fn assert_hmac_sha512_kernel(id: Sha512KernelId) {
    let compress = sha512_compress_blocks_fn(id);
    let cases = [
      (0usize, 0usize, 1usize),
      (1, 1, 1),
      (32, 63, 7),
      (64, 127, 31),
      (96, 128, 64),
      (192, 129, 65),
      (256, 255, 128),
      (320, 1024, 257),
    ];

    for &(key_len, data_len, chunk_len) in &cases {
      let key = pattern(key_len, 23, 7);
      let data = pattern(data_len, 37, 13);
      let expected = oracle_hmac_sha512(&key, &data);

      assert_eq!(
        HmacSha512::mac(&key, &data),
        expected,
        "sha512 public oneshot mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );
      assert_eq!(
        HmacSha512::mac_with_compress_for_test(&key, &data, compress),
        expected,
        "sha512 forced oneshot mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );

      let mut streaming = HmacSha512::new_with_compress_for_test(&key, compress);
      for chunk in data.chunks(chunk_len) {
        streaming.update(chunk);
      }
      assert_eq!(
        streaming.finalize(),
        expected,
        "sha512 forced streaming mismatch kernel={} key_len={} data_len={} chunk_len={}",
        id.as_str(),
        key_len,
        data_len,
        chunk_len
      );

      streaming.reset();
      streaming.update(&data);
      assert_eq!(
        streaming.finalize(),
        expected,
        "sha512 forced reset mismatch kernel={} key_len={} data_len={}",
        id.as_str(),
        key_len,
        data_len
      );
    }
  }

  #[test]
  fn hmac_sha384_forced_kernels_match_oracle() {
    let caps = crate::platform::caps();
    for &id in SHA384_KERNELS {
      if caps.has(sha384_required_caps(id)) {
        assert_hmac_sha384_kernel(id);
      }
    }
  }

  #[test]
  fn hmac_sha512_forced_kernels_match_oracle() {
    let caps = crate::platform::caps();
    for &id in SHA512_KERNELS {
      if caps.has(sha512_required_caps(id)) {
        assert_hmac_sha512_kernel(id);
      }
    }
  }
}