Zeroize Secret Buffer
Wrap credentials in a type that wipes memory on drop, redacts itself in debug output, and zeroes temporary buffers explicitly.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.