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

rustsnippet
31 lines
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());
}

How the snippet works

Count the functions new, expose, fmt and main as the entire surface area of Zeroize Secret Buffer.

What to watch for

  • Requires zeroize:: as a package; the snippet will not run without it.

Applying it

The primary signature is fn new(raw: impl Into<String>) -> Self

The demo output is labeled (length:, zeroized is empty:), so every printed line maps back to its originating operation.

Treat main as the orchestrator calling new and expose in a fixed order.

Statements that matter

fn new(raw: impl Into<String>) -> Self {
Self(raw.into())
}
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ApiKey([REDACTED])")
}
fn expose(&self) -> &str {
&self.0
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `zeroize::` must be present in the project or the import fails at load time.