dcrypt_internal/
zeroing.rs

1//! Secure memory zeroing utilities
2
3use zeroize::Zeroize;
4
5/// Securely zero a slice of memory
6///
7/// This function ensures that the contents of the slice are securely
8/// zeroed, even if the compiler would otherwise optimize the operation away.
9pub fn secure_zero(data: &mut [u8]) {
10    data.zeroize();
11}
12
13/// Securely clone a slice, zeroing the source afterwards
14///
15/// This function clones the contents of the slice and then securely
16/// zeroes the original slice.
17pub fn secure_clone_and_zero(data: &mut [u8]) -> Vec<u8> {
18    let result = data.to_vec();
19    secure_zero(data);
20    result
21}
22
23/// Guard that zeroes memory when dropped
24///
25/// This struct provides a way to ensure that memory is zeroed when
26/// it goes out of scope, by automatically zeroing the contained
27/// buffer when the `ZeroGuard` is dropped.
28pub struct ZeroGuard<'a>(&'a mut [u8]);
29
30impl<'a> ZeroGuard<'a> {
31    /// Create a new guard that will zero the given data when dropped
32    pub fn new(data: &'a mut [u8]) -> Self {
33        Self(data)
34    }
35
36    /// Get a reference to the protected data
37    pub fn data(&self) -> &[u8] {
38        self.0
39    }
40
41    /// Get a mutable reference to the protected data
42    pub fn data_mut(&mut self) -> &mut [u8] {
43        self.0
44    }
45}
46
47impl Drop for ZeroGuard<'_> {
48    fn drop(&mut self) {
49        secure_zero(self.0);
50    }
51}