← Back to section · Tutorials & Labs
Erase Keys When Done: Managing Secret Memory in Rust with zeroize
Why does assigning zero to a key variable so often fail to erase it? This article explains how compiler dead-store elimination defeats manual wiping, covers zeroize's Zeroize, ZeroizeOnDrop and Zeroizing trio, and shows how it pairs with secrecy.
The Risk Is Not the Moment a Key Is Stolen, but the Memory It Has Been In
Key lifecycle management has a frequently overlooked stage: what happens after use. Freed memory does not vanish immediately — a later allocation in the same process may read the residue; a core dump writes process memory to disk verbatim; swap may hold copies of paged-out pages; debugging and crash-reporting tools may carry memory fragments off the machine. For long-lived processes (servers, daemons), every extra hour a session key lies in memory is an extra hour of exposure window. The consensus in cryptographic engineering is: erase a secret’s memory copies as soon as possible after use. In Rust, the standard tool for this is the zeroize crate.
Why “Assign Zero” So Often Erases Nothing
The most natural beginner’s approach is:
let mut key = [0x42u8; 32];
// ... use key ...
key = [0u8; 32]; // believed erased
The problem is dead-store elimination: if a memory write is never read afterwards, the optimizer is entitled to delete the write entirely — since “nobody will observe it,” deleting it does not change the program’s observable behavior. So your carefully written wiping code may simply not exist in a release build. Worse, this class of bug is invisible in code review, behaves correctly in debug builds, and only silently fails under optimization.
zeroize solves this by using writes the compiler may not casually eliminate: internally it performs volatile writes combined with a compiler fence, telling the optimizer explicitly “this write has a side effect; do not remove it.” This is exactly why you should not hand-roll wiping logic and should use a dedicated crate instead.
The zeroize Trio
The Zeroize trait is the core interface, providing a zeroize() method that overwrites the value with zeros. The crate ships implementations for common types: fixed-size arrays, Vec<u8>, String, boxed slices and more can be wiped directly. For custom structs you can implement it manually, or enable the derive feature and let the derive macro generate it.
ZeroizeOnDrop is a marker trait: implement it for a type (together with the corresponding Drop logic) and the value is wiped automatically when it goes out of scope and is destroyed. Many key types in the RustCrypto ecosystem implement this trait pair, which makes it a worthwhile item to check during selection.
Zeroizing<T> is the most convenient entry point: a wrapper type whose contents are wiped automatically when the wrapper is dropped. When temporarily holding a secret, wrap it in Zeroizing:
use zeroize::Zeroizing;
fn derive_session_key() -> Zeroizing<Vec<u8>> {
let mut buf = Zeroizing::new(vec![0u8; 32]);
// ... write the derived key into buf ...
buf // ownership moves out; the caller keeps holding it; erased on scope exit
}
Through dereferencing you can read and write it just like the inner value. Note the return of Zeroizing rather than a bare Vec: the type itself reminds every handler “this is a secret; do not copy it carelessly.”
Pairing with secrecy: Erasure Is Only Half the Story
Erasure handles “leave it clean when it goes,” but how a secret is accessed while it lives is the other half of the problem. The secrecy crate’s approach is to put secrets in a Secret<T> wrapper: by default it provides no Debug output (preventing accidental logging), does not offer casual cloning, and reading the contents requires an explicit expose_secret() call. This makes code review practical — search the codebase for expose_secret and you have the list of every place a secret is “unsealed.” The two crates are commonly paired: Secret governs access discipline, zeroize governs destruction and erasure, and many RustCrypto key types integrate both sets of traits.
An Engineering Checklist: Making Erasure Part of the Routine
Turn the principles above into a checklist a team can execute. First, key types erase by default: any struct of your own that holds key material implements ZeroizeOnDrop (the derive macro can do it), so “forgetting to erase” becomes an exception you must deliberately work around. Second, limit the copy points of secrets: secret types do not implement Clone; when a copy is genuinely needed, write an explicit method and justify it in review; when serializing secrets, catch intermediate buffers in Zeroizing. Third, redact logs and error messages: secret types do not implement Debug, or print only a masked form; error paths must never splice key material into error text. Fourth, process-level companions: in production deployments, disable core dumps (for example systemd’s LimitCORE=0 or equivalent configuration), and consider locking memory pages for sensitive processes so they are never swapped out. Fifth, test the erasure itself: unit tests can verify that after an object is dropped its memory (observed through a pre-obtained read-only handle, or in a test-only build) really is zeroed, so that a refactor which quietly drops a derive macro does not go unnoticed. The list is short; its value is that every item can be checked in code review.
The Post-Quantum Connection
The post-quantum era makes the erasure problem bigger, not smaller: an ML-KEM decapsulation private key is on the order of 2400 bytes, and ML-DSA private keys and signing intermediates are not small either, so key material occupies far more memory than classical algorithms did; at the same time these keys are often long-term identity keys (especially signing keys) with lifetimes measured in years. The good news is that mainstream implementations have built erasure into their type designs: RustCrypto key types generally implement ZeroizeOnDrop, and liboqs’s safe wrappers also wipe on destruction (see discipline two in the FFI article). What the user must do is confirm that the version they selected really enables the relevant features, and re-apply this article’s checklist at every seam where a key is exported to bytes, written into a hardware security module, or passed across a language boundary — erasure bugs never live inside the algorithm; they live at the seams.
The Limits of Erasure: An Honest View
Finally, a splash of cold water: memory erasure cannot be made complete. During computation, secrets flow through registers and caches, produce stack copies across function calls, get serialized into protocol buffers, and get copied transiently by string formatting. What zeroize guarantees is that the storage you explicitly manage is wiped — not that every trace of the key’s existence in memory is eliminated. The correct positioning is therefore one layer of defense in depth: combine it with minimizing secret lifetimes, reducing copy counts, disabling core dumps, locking memory pages, and other system-level measures, rather than treating erasure as universal insurance. Stating the limits clearly serves security engineering better than overselling the effect.
Tags: RustzeroizeMemory SafetyKey Management