memguard-rs
Secure memory handling primitives for Rust.
- Zeroization on drop — volatile-write memory clearing the compiler cannot optimize away
- Memory locking —
mlock/VirtualLockto prevent secrets from being written to swap - Constant-time comparison — timing side-channel resistant equality checks for secrets
- Compile-time guarded regions — const-generic memory regions with type-level size enforcement
no_stdcompatible — core primitives work without an allocator- Zero dependencies — no transitive dependency surface to audit
Quick start
Add to your Cargo.toml:
[]
= "0.1"
Wrapping a secret
use Secret;
let mut key = new;
// Access the secret only within a closure
key.expose;
// Modify in place
key.expose_mut;
// When `key` goes out of scope, its memory is zeroized via volatile writes
Locking memory with mlock
use Secret;
// Lock the secret's memory to prevent it from being written to swap
let key = new.lock.unwrap;
assert!;
// Memory is unlocked and zeroized when `key` is dropped
Guarded memory regions
use GuardedRegion;
// Create a 64-byte locked, zeroized-on-drop region
let mut region = new.unwrap;
// Write sensitive data
region.as_mut_slice.copy_from_slice;
// Read it back
assert_eq!;
// When `region` drops, memory is zeroized and unlocked
Constant-time comparison
use ct_eq;
let stored_mac = ;
let received_mac = ;
// Compare without leaking timing information
if ct_eq
Features
| Feature | Default | Description |
|---|---|---|
std |
✓ | Enables std support (implies alloc) |
alloc |
(via std) |
Enables heap-allocated types (SecretBox) |
lock |
✓ | Enables mlock/VirtualLock memory locking |
no_std usage
use ;
Safety
This crate uses unsafe in the following places:
- Volatile writes in
zeroize—core::ptr::write_volatileis used to zero memory. The pointers are always valid, aligned, and within bounds. - FFI calls in
mlock— directextern "C"/extern "system"declarations formlock/munlock(Unix) andVirtualLock/VirtualUnlock(Windows). These are standard system calls with well-defined semantics. - ManuallyDrop in
secret— used to control the drop order: zeroize first, then drop the value. This prevents double-drops if zeroization panics.
No unsafe is exposed in the public API. All unsafe code is internal and encapsulated behind safe abstractions.
MSRV
Minimum Supported Rust Version: 1.65
The MSRV may be bumped in minor version releases. Pin a specific version in your Cargo.toml if you need a stable MSRV.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome. Please see CONTRIBUTING.md for guidelines.
Help wanted
We have several issues tagged good first issue suitable for new contributors:
All contributions are dual-licensed under the MIT and Apache 2.0 licenses.