reddb_server/storage/encryption/
key.rs1use std::ptr;
7
8pub struct SecureKey {
10 data: Box<[u8]>,
11}
12
13impl SecureKey {
14 pub fn new(data: &[u8]) -> Self {
16 Self { data: data.into() }
17 }
18
19 pub fn as_bytes(&self) -> &[u8] {
21 &self.data
22 }
23}
24
25impl Drop for SecureKey {
26 fn drop(&mut self) {
27 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 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 }
62}