Answer#
When a String or Vec<u8> is dropped, its memory is freed but not cleared, so the bytes may stay readable in the process until something else overwrites them. The zeroize crate gives you a write the compiler is not allowed to optimize away, and wrappers that call it for you.
[dependencies]
zeroize = { version = "1.8", features = ["derive"] }use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
#[derive(Zeroize, ZeroizeOnDrop)]
struct SessionKey {
bytes: Vec<u8>,
}
fn main() {
// Zeroizing<T> wipes the value when it goes out of scope.
{
let password = Zeroizing::new(String::from("hunter2"));
println!("inside the scope: {} bytes", password.len());
}
// An explicit wipe: the buffer is cleared in a way the optimizer may not remove.
let mut buf = vec![1u8, 2, 3, 4];
buf.zeroize();
println!("after zeroize: {buf:?}");
// A struct that wipes its field on drop.
let key = SessionKey { bytes: vec![9; 16] };
println!("key holds {} bytes", key.bytes.len());
drop(key);
}inside the scope: 7 bytes
after zeroize: []
key holds 16 bytesZeroizing<T> wipes its content at the end of the scope. #[derive(Zeroize, ZeroizeOnDrop)] does the same for your own struct. Calling .zeroize() on a Vec<u8> wipes the bytes and empties the vector.
What it does not do#
Be honest about the limits, because they decide whether this is worth the effort:
- A
VecorStringthat grew may have left an older copy in memory it moved away from. Allocate the full size up front (Vec::with_capacity) for buffers that hold secrets. - Copies you made on the way (a
clone, a formatted message, a request body) are not wiped. - The operating system may have written the page to swap or to a crash dump.
- Anyone who can already read your process memory can usually read the secret while it is in use.
So treat it as defence in depth for long-running processes, not as a guarantee.
Common mistakes#
- Believing
drop(secret)clears memory. It only frees it. - Wiping a clone and keeping the original around.
- Using it as a reason to skip the basics: keep secrets out of logs and source first.
Related questions#
Does the secrecy crate do the same thing?#
It combines a wrapper that hides the value in Debug output with wiping on drop. See the thread on keeping secrets out of logs for the printing side.
Is it worth doing for every string?#
No. Use it for long-lived secrets such as keys, tokens and passwords held in memory for a while, and where your threat model includes memory disclosure. For everything else, the basics (no secrets in logs or source) matter more.
Sources#
zeroizedocumentation: https://docs.rs/zeroize/1.8.1/zeroize/- Rust standard library,
Drop: https://doc.rust-lang.org/std/ops/trait.Drop.html