pub struct SecureArray<T, const LENGTH: usize>where
T: Zeroize,{ /* private fields */ }
Expand description
A fixed-size array allocated in a secure memory region.
§Security Model
When compiled with the std
feature (the default), it provides several layers of protection:
- Zeroization on Drop: The memory is zeroized when the array is dropped.
- Memory Locking: The underlying memory pages are locked using
mlock
&madvise
for (Unix) orVirtualLock
&VirtualProtect
for (Windows) to prevent the OS from memory-dump/swap to disk or other processes accessing the memory. - Memory Encryption: On Windows, the memory is also encrypted using
CryptProtectMemory
.
In a no_std
environment, it falls back to providing only the zeroization-on-drop guarantee.
§Program Termination
Direct indexing (e.g., array[0]
) on a locked array will cause the operating system
to terminate the process with an access violation error. Always use the provided
scope methods (unlock
, unlock_mut
) for safe access.
§Notes
If you return a new allocated [T; LENGTH]
from one of the unlock methods you are responsible for zeroizing the memory.
§Example
use secure_types::{SecureArray, Zeroize};
let exposed_key: &mut [u8; 32] = &mut [1u8; 32];
let secure_key: SecureArray<u8, 32> = SecureArray::from_slice_mut(exposed_key).unwrap();
secure_key.unlock(|unlocked_slice| {
assert_eq!(unlocked_slice.len(), 32);
assert_eq!(unlocked_slice[0], 1);
});
// Not recommended but if you allocate a new [u8; LENGTH] make sure to zeroize it
let mut exposed = secure_key.unlock(|unlocked_slice| {
[unlocked_slice[0], unlocked_slice[1], unlocked_slice[2]]
});
// Do what you need to to do with the new array
// When you are done with it, zeroize it
exposed.zeroize();
Implementations§
Source§impl<T, const LENGTH: usize> SecureArray<T, LENGTH>where
T: Zeroize,
impl<T, const LENGTH: usize> SecureArray<T, LENGTH>where
T: Zeroize,
Sourcepub fn empty() -> Result<Self, Error>
pub fn empty() -> Result<Self, Error>
Creates an empty (but allocated) SecureArray.
The memory is allocated but not initialized, and it’s the caller’s responsibility to fill it.
Sourcepub fn from_slice_mut(content: &mut [T; LENGTH]) -> Result<Self, Error>
pub fn from_slice_mut(content: &mut [T; LENGTH]) -> Result<Self, Error>
Creates a new SecureArray from a &mut [T; LENGTH]
.
The passed slice is zeroized afterwards
Sourcepub fn from_slice(content: &[T; LENGTH]) -> Result<Self, Error>
pub fn from_slice(content: &[T; LENGTH]) -> Result<Self, Error>
Creates a new SecureArray from a &[T; LENGTH]
.
The array is not zeroized, you are responsible for zeroizing it
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn as_ptr(&self) -> *const T
pub fn as_mut_ptr(&mut self) -> *mut u8
Sourcepub fn unlock_mut<F, R>(&mut self, f: F) -> R
pub fn unlock_mut<F, R>(&mut self, f: F) -> R
Mutable access to the array’s data as a &mut [T]