Secure wrappers for secrets with explicit access and mandatory zeroization — a no_std-compatible library with audit-friendly access patterns.
Warning
Security Notice: This crate has not undergone independent audit. Review the code and SECURITY.md before production use.
secure-gate stops the ordinary mistakes: a secret printed by {:?}, compared with ==,
left in freed memory, or handed out as a plain Vec. It cannot stop someone who decides
to copy a secret out; a secret nobody can read is useless. So:
- The easy path is safe. The obvious way to hold, decode, encode or compare a secret keeps it wrapped, wiped and redacted.
- Reaching it is named. Every way to the secret, from the scoped
with_secretto the exits (expose_secret,into_inner,into_zeroizing,as_reader), is a call you can grep for and a reviewer can see.
Don't route around it with .to_vec(), *bytes or .to_string(); name the exit instead.
[dependencies]
secure-gate = "0.10" # default: heap on (`alloc`)
# secure-gate = { version = "0.10", default-features = false } # heap off: `Fixed` only
# secure-gate = { version = "0.10", features = ["full"] } # batteries includedOn Rust older than 1.87, use secure-gate = "0.8.0" (the release/0.8 line, MSRV 1.70).
use secure_gate::{ConstantTimeEq, Dynamic, RevealSecret, RevealSecretMut, ToHex};
use secure_gate::{dynamic_newtype, fixed_newtype};
// A secret type is a visibility, a name, a size (or an inner type), and a doc string.
fixed_newtype!(pub EncKey, 32, "AES-256 key. Never used for authentication.");
fixed_newtype!(pub MacKey, 32, "HMAC key. Never used for encryption.");
dynamic_newtype!(pub Password, String, "User password.");
// A plain alias gives the same protection when there is no role to confuse it with.
pub type ApiToken = Dynamic<String>;
// EncKey and MacKey are different types: a MacKey cannot be passed where an EncKey belongs.
fn seal(_enc: &EncKey, _mac: &MacKey) {}
let mut key = EncKey::from_random(); // system RNG (`rand`)
let pw: Password = "hunter2".into(); // copies the literal; the original is never wiped
let token: ApiToken = "tok_live_123".into();
seal(&key, &MacKey::from_random());
// Nothing prints by accident, and a held secret has no `Deref`. (The one `Deref` in the
// crate is on `EncodedSecret`, the encoded copy you asked for; see Where protection stops.)
assert_eq!(format!("{key:?}"), "[REDACTED]");
// Scoped access, preferred: the borrow ends with the closure, so return a verdict, not the bytes.
assert!(!pw.with_secret(|s| s.len() >= 8));
assert!(token.with_secret(|t| t.starts_with("tok_")));
// The auditable escape hatch, for FFI and third-party APIs.
assert_eq!(pw.expose_secret(), "hunter2");
// Encode and decode without leaving a wrapper (`encoding-hex`). `hex` wipes itself on drop.
let hex = key.to_hex();
let restored = EncKey::try_from_hex(&hex).expect("valid hex");
// Compare in constant time (`ct-eq`). There is no `==` on a secret.
assert!(key.ct_eq(&restored));
// An RNG you supply fills the key in place; this needs no secure-gate feature.
// (`StdRng` with a fixed seed is for the example only. Seed a real one from the system.)
use rand::{SeedableRng, TryRng};
let mut rng = rand::rngs::StdRng::from_seed([7u8; 32]);
let fresh = EncKey::try_new_with(|bytes| rng.try_fill_bytes(bytes)).expect("rng fill");
// Rotate in place: the old key is overwritten and never leaves the wrapper.
fresh.with_secret(|new| key.with_secret_mut(|old| old.copy_from_slice(new)));
assert!(!key.ct_eq(&restored));
// Take the plain value when ownership must transfer. Protection ends at this call.
let _raw: [u8; 32] = restored.into_inner();
// Everything still wrapped is zeroized when it drops.The example needs rand, ct-eq and encoding-hex, all in full. The custom-RNG lines use
your own rand = "0.10" dependency; any RNG that can fill a byte slice works.
| You have | Use | Why |
|---|---|---|
| A key or other fixed-size secret | fixed_newtype!(pub Name, 32, "…") |
On the stack, no_std, and a distinct type per role |
| A password, token or other variable-length secret | dynamic_newtype!(pub Name, String, "…") |
On the heap (alloc); spare capacity is wiped too |
| A secret with no role to confuse it with | pub type Name = Fixed<[u8; 32]>; or pub type Name = Dynamic<String>; |
Same protection; an alias is interchangeable with its base type |
| A long-lived key in a process that may be read while it idles | sealed_fixed_newtype!(pub Name, Role, "…"), or SealedFixed<32> when there is no role (sealed) |
Held encrypted in RAM, opened for one closure call at a time |
| A long-lived password or other variable-length secret, likewise | sealed_dynamic_newtype!(pub Name, Role, "…"), or SealedDynamic<String> / SealedDynamic<Vec<u8>> when there is no role (sealed) |
The same, on the heap |
| Feature | Adds |
|---|---|
alloc (default) |
Dynamic<T>, including wiping Vec / String spare capacity |
std |
std::io::Write for Dynamic<Vec<u8>> and SlotWriter, and Dynamic::as_reader() (std::io::Read). Implies alloc |
rand |
from_random() (system RNG); heap-free for Fixed. For an RNG you supply, use try_new_with(|b| rng.try_fill_bytes(b)), which needs no feature |
ct-eq |
ConstantTimeEq via subtle |
encoding |
All of encoding-hex, -base32, -base64, -bech32; see Encoding |
serde |
serde-deserialize (1 MiB default limit) and serde-serialize (opt-in per type via SerializableSecret) |
cloneable |
Opt-in cloning via CloneableSecret |
sealed |
SealedFixed, SealedDynamic, sealed_fixed_newtype!, sealed_dynamic_newtype! and Prekey (implies std, rand; adds chacha20poly1305, sha2, guarded-block, and poly1305 and ctutils only to turn on a feature and set a version floor) |
full |
Everything except std and sealed |
There is no no_std feature. The crate is no_std whenever std is off, which it is by
default, and two features decide how much of the standard library it uses:
In Cargo.toml |
Uses | You get |
|---|---|---|
default-features = false |
core only: no heap, no OS |
Fixed and its decoders |
nothing (the default, alloc) |
core + alloc: a heap, still no OS |
adds Dynamic, the string encoders and serde |
features = ["std"] |
all of std |
adds std::io::Write on Dynamic<Vec<u8>> and SlotWriter, and Dynamic::as_reader() |
alloc is the only default feature, so turning the defaults off is how you turn the heap off.
List what you still want after it:
secure-gate = { version = "0.10", default-features = false, features = ["ct-eq", "encoding-hex"] }rand,ct-eq,cloneableand theencoding-*features work withoutalloc. The encodings then decode into aFixed; producing an encoded string needsalloc.serde,serde-serialize,serde-deserializeandfullturnallocon.sealedturnsstdon, andstdturnsallocon.- Cargo features only add. If any crate in your build enables
allocorstdonsecure-gate, it is on for the whole build. - No wipe gets weaker or stronger with the tier.
allocbringsVecandStringinto the crate together with the wiping of their spare capacity.stdchanges nothing that exists without it; itsio::WriteonDynamic<Vec<u8>>wipes each buffer it outgrows, which makes it the way to build a secret whose length is not known up front (see SECURITY.md).
Each format sits behind its own feature; encoding turns on all four.
| Format | Encode | Decode into Fixed / Dynamic |
Feature |
|---|---|---|---|
| Hex | ToHex |
try_from_hex |
encoding-hex |
| Base32 (RFC 4648 §6) | ToBase32 |
try_from_base32 |
encoding-base32 |
| Base64url | ToBase64Url |
try_from_base64url |
encoding-base64 |
| Bech32 (BIP-173) | ToBech32 |
try_from_bech32(s, hrp) |
encoding-bech32 |
| Bech32m (BIP-350) | ToBech32m |
try_from_bech32m(s, hrp) |
encoding-bech32 |
Every encoder returns EncodedSecret, which wipes itself on drop and has no Display.
Every decoder is fallible and decodes into a staging Zeroizing buffer, as in the Quick
start. Dynamic<Vec<u8>> takes that buffer over without a copy. Fixed and
Dynamic<[u8]> copy the bytes out of it into the wrapper (for Dynamic<[u8]>, a box of
exactly their length), and the staging buffer is wiped.
With the sealed feature, a key is held encrypted while it idles, under a pre-key
locked in RAM between guard pages. Each access costs about 7–11 µs for a 32-byte key, so it
is for long-held keys, not hot loops, and needs about 32 KiB of free stack (mind small
thread stacks; a fixed key above about 10 KiB needs about three times its size, and in a
debug build one above about 3 KiB needs about ten times). Prekey::new() asks to lock the pre-key against swap; if the system
refuses, sealing still works and nothing fails, so check Prekey::lock_status(), which
returns the refusal. In containers RLIMIT_MEMLOCK is often 0, and every lock is refused. Where Windows crash dumps matter more than swap, Prekey::new_idle_noaccess() keeps
an idle pre-key out of a user-mode dump, but cannot keep it locked there. What it covers
and what it does not:
sealed.
| Sealed type | Seals | Opens as |
|---|---|---|
SealedFixed<N> |
Fixed<[u8; N]> |
&[u8; N] |
sealed_fixed_newtype!(pub Name, Role, "…") |
a fixed_newtype! role, and only that role |
&Role (with_role) or its bytes (with_secret) |
SealedDynamic<String> / SealedDynamic<Vec<u8>> |
Dynamic<String> / Dynamic<Vec<u8>> |
&String / &Vec<u8> |
sealed_dynamic_newtype!(pub Name, Role, "…") |
a dynamic_newtype! String or Vec<u8> role, and only that role |
&Role (with_role) or its &String / &Vec<u8> (with_secret) |
All four share one Prekey, are opened only through closures (there is no expose_secret),
and give the plain wrapper or role back with unseal(). The two dynamic ones change a secret
in place through &mut str / &mut [u8], so its length is fixed while sealed and no
reallocation can leave a copy behind; that is also why the dynamic macro has no
with_role_mut.
#[cfg(feature = "sealed")]
{
use secure_gate::{
Dynamic, Fixed, Prekey, RevealSecret, SealedDynamic, SealedFixed, dynamic_newtype,
fixed_newtype, sealed_dynamic_newtype, sealed_fixed_newtype,
};
let prekey = Prekey::new(); // one per session; check `lock_status()`
// Fixed size, no role.
let key = SealedFixed::seal(Fixed::new([7u8; 32]), &prekey);
key.with_secret(|k| assert_eq!(k[0], 7)); // decrypted for this call only
// Fixed size, with a role the compiler keeps apart from other 32-byte keys.
fixed_newtype!(pub AppKey, 32, "The app key.");
sealed_fixed_newtype!(pub SealedAppKey, AppKey, "The app key, sealed while idle.");
let app_key = SealedAppKey::seal(AppKey::new([9u8; 32]), &prekey);
app_key.with_role(|k: &AppKey| k.with_secret(|b| assert_eq!(b[0], 9)));
// Variable length, no role.
let token = SealedDynamic::seal(Dynamic::<String>::new("hunter2".to_string()), &prekey);
token.with_secret(|t| assert_eq!(t.len(), 7));
// Variable length, with a role.
dynamic_newtype!(pub Password, String, "A login password.");
sealed_dynamic_newtype!(pub SealedPassword, Password, "A login password, sealed while idle.");
let password = SealedPassword::seal(Password::from("hunter2"), &prekey);
password.with_role(|p: &Password| p.with_secret(|s| assert_eq!(s.len(), 7)));
}The crate wipes the buffers it owns and stops at a line you can point to. Every handoff is a call you can grep for:
| Handoff | What you hold | Protection after it |
|---|---|---|
with_secret / with_secret_mut |
A borrow that ends with the closure | The wrapper still wipes its own copy. A copy you make inside the closure is yours to wipe, and no lint catches it |
expose_secret / expose_secret_mut |
A reference for as long as you keep it | The wrapper still wipes; anything you copy from the reference is yours |
into_inner (also on EncodedSecret) |
The plain value | None: not wiped, not redacted |
to_hex and the other encoders |
An EncodedSecret |
Wiped on drop, Debug redacted. It derefs to str on purpose, to hand the text to APIs that take &str; .to_string() or &*enc makes a copy nothing tracks |
EncodedSecret::into_zeroizing |
A Zeroizing<String> |
Wiped on drop, but it derefs to String |
as_reader, serde Serialize |
Bytes in a buffer you or another library own | None |
What you pass in ("…".into(), try_from_hex(&s), From<&[u8]>) |
Your original input | Never wrapped: only the wrapper's copy is wiped |
Changing a Dynamic<Vec<u8>> / Dynamic<String>'s capacity through with_secret_mut or expose_secret_mut (push, reserve, write!, shrink_to_fit) |
The same wrapper, in a new buffer | Each reallocation frees the old buffer unwiped. Pre-size, write a Dynamic<Vec<u8>> through its own io::Write (std), or use Dynamic<[u8]> (SECURITY.md §2) |
Beyond the handoffs:
- No unsafe code (
#![forbid(unsafe_code)]) in this crate. Thesealedguard pages live in the separateguarded-blockcrate, which usesunsafefor its operating-system calls and is outside this claim. - Not covered: a process that can be read (a debugger, code running in it),
panic = "abort"and hard crashes, andstaticsecrets. - Inherent limits no wrapper removes: stack-move residue, heap-reallocation residue, and swap or core dumps. Each has a mitigation in SECURITY.md.
SECURITY.md has the rule that draws the line, the full threat model, and the call sites to audit.
The public API follows semantic versioning within each minor line (0.10.x, as 0.9.x
before it): a patch release adds, and does not remove or change. Breaking changes ship
only as a new minor version, with a migration list in CHANGELOG.md. The promise covers the items exported from the crate
root and from traits, sealed and scoped, the input grammar of the macros, and each
feature's name and what it enables. Import from the crate root: the deeper module paths
under traits (such as traits::reveal_secret::RevealSecret) compile, and are not covered.
Nor are items under secure_gate::__private, which only the macros use.
One exception: a security fix. A patch release may restrict an API that lets code reach
a secret or skip a documented guarantee, even though that stops some code compiling. The
changelog says so, with the code that breaks. 0.9.1 is the example: the hidden role
conversions in __private could be called from safe code without derive: [FromWrapper],
and 0.9.1 made them take a token only the crate can build.
- Features.
fullstays as listed above. It will not grow to includestdorsealed, so it remains usable onno_stdtargets. - MSRV. The minimum supported Rust version rises only in a minor release (0.9 to 0.10), never in a patch release.
- The 0.8 line.
release/0.8exists for Rust older than 1.87 and stays on 0.8.x for good. A 0.8.x release is a fix or an addition and never a breaking change, so"0.8"in aCargo.tomlis safe to leave. It has nosealedfeature. Breaking changes ship only as a new minor version on main (0.9 to 0.10). - Yanked versions. Every version before 0.8 is yanked on purpose, on 2026-03-17 UTC
except 0.6.0, yanked on 2025-12-08 when 0.6.1 replaced it. 0.5.0
through 0.7.0-rc.14 (rc.15 was tagged but never published) did not zeroize on drop,
fixed in 0.8.0-rc.1 (RUSTSEC-2026-0590;
SECURITY.md, Past Advisory). 0.1.0 to 0.4.3 did wipe; they were yanked as early wrappers oversecrecy, superseded by the current design, not for that flaw. The 0.8 and 0.9 release candidates are yanked too, replaced by 0.8.0 and 0.9.0, except 0.9.0-rc.6, which is still listed because a downstream user is pinned to it. Use a stable release. - Traits. The public traits can be implemented outside this crate, and the newtype macros
do so, except the sealed ones (
DynamicBytes,SealedPayload), which name the shapes this crate builds. A method added to an open trait in a patch release always comes with a default body, so existing implementations keep compiling. - Dependencies in the API. Only
zeroizeandserde, both 1.x, appear in public signatures.bech32,rand,subtleand the other dependencies are private and can be upgraded without a breaking release.
- API docs: every type, trait and feature, with examples.
fixed_newtype!anddynamic_newtype!:generic Tinner types and opt-in conversions to and from the base wrapper.Fixed: running RustCrypto ciphers in place inside the wrapper, and the zero-size compile error.- SECURITY.md: threat model and measurements.
- CHANGELOG.md: changes per release, including breaking ones.
Contributing. MSRV is 1.87; regenerate Cargo.lock with cargo +1.87 update. What CI
checks is in .github/workflows/.
Tests go in tests/. A test lives inline in src/ only when it has to read private state
(a sealed value's ciphertext, a private checksum type), and its module says so in one line.
Private state is not exposed through a hidden hook to move a test out.
MIT OR Apache-2.0