use std::fmt;
use anyhow::{Result, anyhow};
use rand::TryRngCore;
use rand::rngs::OsRng;
use zeroize::{Zeroize, ZeroizeOnDrop};
pub struct KeyGuard<T: Zeroize>(Box<T>);
impl<T: Zeroize> KeyGuard<T> {
pub fn new(secret: T) -> Self {
Self(Box::new(secret))
}
pub fn expose(&self) -> &T {
&self.0
}
pub fn expose_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<const N: usize> KeyGuard<[u8; N]> {
pub fn random() -> Result<Self> {
let mut guard = Self(Box::new([0u8; N]));
OsRng
.try_fill_bytes(&mut guard.0[..])
.map_err(|e| anyhow!("reading OS randomness: {e}"))?;
Ok(guard)
}
}
impl<T: Zeroize> Drop for KeyGuard<T> {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl<T: Zeroize> ZeroizeOnDrop for KeyGuard<T> {}
impl<T: Zeroize> fmt::Debug for KeyGuard<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("KeyGuard(..)")
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
struct Probe {
bytes: [u8; 4],
wiped: Arc<AtomicBool>,
}
impl Zeroize for Probe {
fn zeroize(&mut self) {
self.bytes.zeroize();
self.wiped.store(true, Ordering::SeqCst);
}
}
#[test]
fn dropping_a_guard_zeroizes_its_secret() {
let wiped = Arc::new(AtomicBool::new(false));
let guard = KeyGuard::new(Probe {
bytes: [7; 4],
wiped: wiped.clone(),
});
assert_eq!(guard.expose().bytes, [7; 4]);
assert!(!wiped.load(Ordering::SeqCst));
drop(guard);
assert!(wiped.load(Ordering::SeqCst));
}
#[test]
fn debug_output_hides_the_secret() {
let guard = KeyGuard::new([0xabu8; 32]);
let shown = format!("{guard:?}");
assert_eq!(shown, "KeyGuard(..)");
}
#[test]
fn random_guards_differ() {
let a = KeyGuard::<[u8; 32]>::random().unwrap();
let b = KeyGuard::<[u8; 32]>::random().unwrap();
assert_ne!(a.expose(), b.expose());
assert_ne!(a.expose(), &[0u8; 32]);
}
}