Skip to main content

reddb_server/storage/encryption/
key.rs

1//! Key Management for RedDB Encryption
2//!
3//! Handles secure storage and derivation of encryption keys.
4//! Ensures keys are zeroed out from memory when dropped.
5
6use std::ptr;
7
8/// A securely managed encryption key
9pub struct SecureKey {
10    data: Box<[u8]>,
11}
12
13impl SecureKey {
14    /// Create a new secure key from raw bytes
15    pub fn new(data: &[u8]) -> Self {
16        Self { data: data.into() }
17    }
18
19    /// Access the raw key bytes
20    pub fn as_bytes(&self) -> &[u8] {
21        &self.data
22    }
23}
24
25impl Drop for SecureKey {
26    fn drop(&mut self) {
27        // Volatile zeroing to prevent compiler optimization
28        unsafe {
29            ptr::write_volatile(self.data.as_mut_ptr(), 0);
30            for i in 1..self.data.len() {
31                ptr::write_volatile(self.data.as_mut_ptr().add(i), 0);
32            }
33        }
34        // Memory fence to ensure writes happen before deallocation
35        std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
36    }
37}
38
39impl Clone for SecureKey {
40    fn clone(&self) -> Self {
41        Self::new(&self.data)
42    }
43}
44
45impl std::fmt::Debug for SecureKey {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "SecureKey(***)")
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_secure_key_zeroing() {
57        let key = SecureKey::new(b"secret");
58        drop(key);
59        // Can't easily check memory after drop safely in Rust tests without UB,
60        // but we trust the implementation logic.
61    }
62}