Zeroize Secret Buffer

Wrap credentials in a type that wipes memory on drop, redacts itself in debug output, and zeroes temporary buffers explicitly.

RustSecurity Boundaries

Code

snippet
use std::fmt;
use zeroize::{Zeroize, ZeroizeOnDrop};

#[derive(Zeroize, ZeroizeOnDrop)]
struct ApiKey(String);

impl ApiKey {
    fn new(raw: impl Into<String>) -> Self {
        Self(raw.into())
    }

    fn expose(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for ApiKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ApiKey([REDACTED])")
    }
}

fn main() {
    let key = ApiKey::new("sk-live-example-123456");
    println!("{:?}", key);
    println!("length: {}", key.expose().len());

    let mut temporary = String::from("temporary-secret");
    temporary.zeroize();
    println!("zeroized is empty: {}", temporary.is_empty());
}