quantaegis_core/
secret.rs1use core::fmt;
4
5use crate::ct::{Choice, ct_eq_slice};
6use crate::zeroize::Zeroize;
7
8pub struct SecretBytes<const N: usize>([u8; N]);
16
17impl<const N: usize> SecretBytes<N> {
18 #[inline]
20 pub const fn new(bytes: [u8; N]) -> Self {
21 Self(bytes)
22 }
23
24 #[inline]
26 pub const fn expose_secret(&self) -> &[u8; N] {
27 &self.0
28 }
29
30 #[inline]
32 pub fn expose_secret_mut(&mut self) -> &mut [u8; N] {
33 &mut self.0
34 }
35
36 #[inline]
38 pub fn ct_eq(&self, other: &Self) -> Choice {
39 ct_eq_slice(&self.0, &other.0)
40 }
41}
42
43impl<const N: usize> Zeroize for SecretBytes<N> {
44 #[inline]
45 fn zeroize(&mut self) {
46 self.0.zeroize();
47 }
48}
49
50impl<const N: usize> Drop for SecretBytes<N> {
51 #[inline]
52 fn drop(&mut self) {
53 self.zeroize();
54 }
55}
56
57impl<const N: usize> fmt::Debug for SecretBytes<N> {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "SecretBytes([REDACTED; {N}])")
60 }
61}
62
63pub type SharedSecret = SecretBytes<32>;
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn secret_bytes_ct_eq_and_explicit_zeroize() {
72 let mut s1 = SecretBytes::new([0x42u8; 32]);
73 let s2 = SecretBytes::new([0x42u8; 32]);
74 let s3 = SecretBytes::new([0x43u8; 32]);
75
76 assert!(s1.ct_eq(&s2).into_bool());
77 assert!(!s1.ct_eq(&s3).into_bool());
78
79 s1.zeroize();
80 assert_eq!(s1.expose_secret(), &[0u8; 32]);
81 }
82}