use std::ptr;
pub struct SecureKey {
data: Box<[u8]>,
}
impl SecureKey {
pub fn new(data: &[u8]) -> Self {
Self { data: data.into() }
}
pub fn as_bytes(&self) -> &[u8] {
&self.data
}
}
impl Drop for SecureKey {
fn drop(&mut self) {
unsafe {
ptr::write_volatile(self.data.as_mut_ptr(), 0);
for i in 1..self.data.len() {
ptr::write_volatile(self.data.as_mut_ptr().add(i), 0);
}
}
std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}
}
impl Clone for SecureKey {
fn clone(&self) -> Self {
Self::new(&self.data)
}
}
impl std::fmt::Debug for SecureKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SecureKey(***)")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_secure_key_zeroing() {
let key = SecureKey::new(b"secret");
drop(key);
}
}