Skip to main content

quantaegis_core/
secret.rs

1//! Type-safe secret wrappers that automatically zeroize on drop and redact debug output.
2
3use core::fmt;
4
5use crate::ct::{Choice, ct_eq_slice};
6use crate::zeroize::Zeroize;
7
8/// Fixed-size secret byte container.
9///
10/// # Security Properties
11/// - **Automatic zeroization**: Memory is overwritten with zeros when dropped.
12/// - **Redacted formatting**: [`fmt::Debug`] never prints the underlying secret bytes.
13/// - **No implicit `Copy` or `Clone`**: Prevents accidental silent duplication on the stack.
14/// - **Constant-time comparison**: [`SecretBytes::ct_eq`] compares without short-circuiting.
15pub struct SecretBytes<const N: usize>([u8; N]);
16
17impl<const N: usize> SecretBytes<N> {
18    /// Wraps a raw secret byte array.
19    #[inline]
20    pub const fn new(bytes: [u8; N]) -> Self {
21        Self(bytes)
22    }
23
24    /// Explicitly borrows the underlying secret bytes.
25    #[inline]
26    pub const fn expose_secret(&self) -> &[u8; N] {
27        &self.0
28    }
29
30    /// Explicitly borrows the underlying secret bytes mutably.
31    #[inline]
32    pub fn expose_secret_mut(&mut self) -> &mut [u8; N] {
33        &mut self.0
34    }
35
36    /// Compares two secret values in constant time.
37    #[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
63/// A 32-byte shared secret established by a KEM (such as ML-KEM or X25519MLKEM768).
64pub 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}