Skip to main content

secure_gate/
lib.rs

1// no_std by default; the `std` feature opts back into the standard library.
2// Verified in CI by cross-building for a bare-metal target.
3#![cfg_attr(not(feature = "std"), no_std)]
4// Forbid unsafe code unconditionally
5#![forbid(unsafe_code)]
6#![warn(missing_docs)]
7// `Cargo.toml` tells docs.rs to build with `--cfg docsrs`. This is what reads it:
8// `doc_cfg` annotates every feature-gated item with the feature that enables it, so
9// the docs people read say "Available on crate feature `encoding-hex`" instead of
10// leaving the reader to infer it. Nightly-only, which is fine — docs.rs builds on
11// nightly, and the only other build that sets `docsrs` is the CI step that exists to
12// catch this gate being renamed. It has been renamed before: `doc_auto_cfg` was the
13// spelling until 1.92 removed it and merged it into `doc_cfg`.
14#![cfg_attr(docsrs, feature(doc_cfg))]
15
16//! Secure wrappers for secrets with **explicit access** and **mandatory zeroization** — a
17//! `no_std`-compatible, zero-overhead library with audit-friendly access patterns.
18//!
19//! Secrets are **automatically zeroized on drop** (the inner type must implement
20//! [`Zeroize`](zeroize::Zeroize)). While a secret is held in [`Fixed`] or [`Dynamic`],
21//! there is no `Deref` and no `AsRef`: callers reach the inner secret only via
22//! [`RevealSecret`] / [`RevealSecretMut`], and `Debug` always prints `[REDACTED]`.
23//! Access has two shapes: **borrow** it, or **take** it.
24//! [`with_secret()`](RevealSecret::with_secret) and
25//! [`expose_secret()`](RevealSecret::expose_secret) lend you a reference while the
26//! wrapper keeps ownership and keeps wiping. [`into_inner()`](RevealSecret::into_inner)
27//! transfers ownership: you get the plain value and the protection ends with the call.
28//!
29//! Those two shapes are what the **3-tier access model** in `SECURITY.md` counts in
30//! threes: `with_secret` (Tier 1) and `expose_secret` (Tier 2) are both the borrow
31//! shape, differing only in how tightly the lifetime is pinned, and `into_inner`
32//! (Tier 3) is the take. Two shapes, three volumes — the tiers say how loudly you
33//! have to announce which one you picked, not how many protections there are.
34//!
35//! Extraction is a hand-off, not a third layer of protection. Encoding output is the
36//! one case that keeps a wrapper — [`EncodedSecret`] **does** implement `Deref`, because
37//! its job is to keep an encoded *copy* of the secret wiped until it drops. Ordinary
38//! copies you make of the derefed value (`.to_string()`) are not tracked. See
39//! [Where accident-prevention ends](#where-accident-prevention-ends).
40//!
41//! # Which type should I use?
42//!
43//! | Type | Allocation | Use case | Feature |
44//! |------|-----------|----------|---------|
45//! | [`Fixed<T>`] | Stack | Keys, nonces, tokens — compile-time-known size | Always available |
46//! | [`Dynamic<T>`] | Heap | Passwords, API keys, ciphertexts — variable length | `alloc` (default) |
47//!
48//! Both types share the same [`RevealSecret`] / [`RevealSecretMut`] access API.
49//!
50//! # Quick start
51//!
52//! ```rust
53//! use secure_gate::{Fixed, RevealSecret};
54//!
55//! // Wrap a 32-byte key
56//! let key = Fixed::new([0x42u8; 32]);
57//!
58//! // Tier 1 — scoped access (preferred): secret ref cannot escape the closure
59//! let first = key.with_secret(|bytes| bytes[0]);
60//! assert_eq!(first, 0x42);
61//!
62//! // Tier 2 — direct reference (escape hatch for FFI / third-party APIs)
63//! assert_eq!(key.expose_secret().len(), 32);
64//!
65//! // Debug is always redacted
66//! assert_eq!(format!("{:?}", key), "[REDACTED]");
67//! // key is zeroized when dropped
68//! ```
69//!
70//! ```rust
71//! # #[cfg(feature = "alloc")]
72//! # {
73//! use secure_gate::{Dynamic, RevealSecret};
74//!
75//! let password: Dynamic<String> = Dynamic::new(String::from("hunter2"));
76//! let len = password.with_secret(|s: &String| s.len());
77//! assert_eq!(len, 7);
78//! # }
79//! ```
80//!
81//! ```rust
82//! use secure_gate::{fixed_newtype, RevealSecret};
83//!
84//! fixed_newtype!(pub Aes256Key, 32);
85//!
86//! let key = Aes256Key::new([0xABu8; 32]);
87//! key.with_secret(|b| assert_eq!(b.len(), 32));
88//! ```
89//!
90//! # Module structure
91//!
92//! ```text
93//! secure_gate (lib.rs)
94//! ├── Fixed<T>              ← always available, stack-allocated
95//! ├── Dynamic<T>            ← requires `alloc`, heap-allocated
96//! ├── traits/
97//! │   ├── RevealSecret      ← immutable access (always available)
98//! │   ├── RevealSecretMut   ← mutable access (always available)
99//! │   ├── revealed_secrets/
100//! │   │   └── EncodedSecret     ← zeroizing encoded string wrapper (alloc)
101//! │   ├── ConstantTimeEq    ← ct-eq feature
102//! │   ├── CloneableSecret   ← cloneable feature
103//! │   ├── SerializableSecret← serde-serialize feature
104//! │   ├── encoding/         ← ToHex, ToBase32, ToBase64Url, ToBech32, ToBech32m
105//! │   └── decoding/         ← FromHexStr, FromBase32Str, FromBase64UrlStr, FromBech32Str, FromBech32mStr
106//! ├── macros/               ← fixed_newtype!, dynamic_newtype!
107//! └── error                 ← FromSliceError, HexError, Base32Error, Base64Error, Bech32Error
108//! ```
109//!
110//! All public items are re-exported at the crate root. Use `secure_gate::Fixed`,
111//! not `secure_gate::fixed::Fixed`.
112//!
113//! # Type taxonomy
114//!
115//! | Category | Types | `Deref` to secret? | Purpose |
116//! |----------|-------|-------------------|---------|
117//! | **Secret wrappers** | [`Fixed<T>`], [`Dynamic<T>`] | No — use [`RevealSecret`] | Hold live secrets; `Debug` → `[REDACTED]` |
118//! | **Output wrapper** | [`EncodedSecret`] | Yes — yields `&str`; copies you make are yours, the buffer stays the wrapper's | Holds encoded output, wiped on drop |
119//! | **Opt-in markers** | [`CloneableSecret`], [`SerializableSecret`] | — (no methods) | Implement on inner type `T` to unlock gated impls |
120//!
121//! `CloneableSecret` and `SerializableSecret` are implemented on the **inner type `T`**,
122//! not on `Fixed<T>` or `Dynamic<T>` directly. [`EncodedSecret`] is not a secret
123//! wrapper and does not interact with these markers.
124//!
125//! # Where accident-prevention ends
126//!
127//! This crate carries two separate obligations, and they end in different places.
128//!
129//! **Accidents must not compile.** This applies while the secret is held in
130//! [`Fixed`]/[`Dynamic`], and it ends at the named extraction. `into_inner` and
131//! `EncodedSecret::into_inner` are the exits that transfer ownership: you typed a
132//! name, the call site is grep-able, and the wrapper is consumed. `expose_secret` is
133//! a named *borrow* — the wrapper still owns the secret and still wipes it — but it
134//! hands out a reference with no lifetime bound to a call site, so it is audited
135//! alongside them.
136//!
137//! **Documented behavior must be accurate.** This never ends, and it is why the
138//! taxonomy table above says `Deref: Yes` for the output wrapper.
139//!
140//! What [`EncodedSecret`] still guarantees: the `String` it owns is zeroized on drop,
141//! and its `Debug` prints `[REDACTED]`. What it does not guarantee: copies you make
142//! through `Deref` are ordinary values. `str::to_string()` and `.to_owned()` both
143//! produce untracked plaintext. That is what extraction is for — the crate is not
144//! trying to follow the bytes into your TLS stack. `into_inner` gives up even the first
145//! guarantee, by design: it is the named end of protection.
146//!
147//! Two consequences worth knowing:
148//!
149//! - `format!("{:?}", &*encoded)` prints the encoded secret. Redaction lives on the
150//!   wrapper, not on `str`; dereferencing first opts out of it.
151//! - [`EncodedSecret::into_zeroizing`] returns a `Zeroizing<String>`, whose `Debug` is
152//!   **not** redacted. It is a deliberate hand-off to a foreign type, not an equivalent
153//!   wrapper.
154//!
155//! # Import paths
156//!
157//! ```rust
158//! // ✅ Correct — always import from the crate root
159//! use secure_gate::{Fixed, RevealSecret};
160//!
161//! // ❌ Wrong — these internal paths compile but are not the public API
162//! // use secure_gate::traits::reveal_secret::RevealSecret;
163//! // use secure_gate::traits::encoding::hex::ToHex;
164//! ```
165//!
166//! # Method resolution: wrapper methods vs trait methods
167//!
168//! Encoding methods exist at **two levels** — both produce identical results:
169//!
170//! | Call style | Example | Appears in audit sweep? |
171//! |-----------|---------|------------------------|
172//! | **Wrapper trait impl** (ergonomic) | `key.to_hex()` (needs `use secure_gate::ToHex`) | No — grep for `to_hex` directly |
173//! | **Trait via scoped access** (audit-friendly) | `key.with_secret(\|b\| b.to_hex())` | Yes — `with_secret` is grep-able |
174//!
175//! Both levels are impls of the **same** trait ([`ToHex`], [`ToBase32`], [`ToBase64Url`],
176//! [`ToBech32`], [`ToBech32m`]): a blanket impl covers the raw bytes inside
177//! `with_secret`, and per-wrapper impls on `Fixed<[u8; N]>` / `Dynamic<Vec<u8>>`
178//! delegate through `with_secret` internally. One trait also means one bound:
179//! `fn fingerprint<S: ToHex>(s: &S)` accepts wrappers and forwarding newtypes
180//! alike.
181//!
182//! # Feature flags
183//!
184//! | Feature | Default | Description |
185//! |---------|---------|-------------|
186//! | `alloc` | **yes** | Heap types ([`Dynamic<T>`]), `Vec`/`String` zeroization |
187//! | `std` | no | Full `std` support (implies `alloc`) |
188//! | | | **Cryptographic** |
189//! | `ct-eq` | no | [`ConstantTimeEq`] via `subtle` — timing-safe comparison |
190//! | `rand` | no | `from_random()` / `from_rng()` — `no_std` for [`Fixed`] |
191//! | | | **Serialization** |
192//! | `serde-serialize` | no | Serde `Serialize` (requires [`SerializableSecret`] marker) |
193//! | `serde-deserialize` | no | Serde `Deserialize` with 1 MiB default limit |
194//! | `serde` | no | Both directions |
195//! | | | **Encoding** |
196//! | `encoding-hex` | no | [`ToHex`] / [`FromHexStr`] via `base16ct` (constant-time) |
197//! | `encoding-base32` | no | [`ToBase32`] / [`FromBase32Str`] via `base32ct` (constant-time) |
198//! | `encoding-base64` | no | [`ToBase64Url`] / [`FromBase64UrlStr`] via `base64ct` (constant-time) |
199//! | `encoding-bech32` | no | [`ToBech32`] / [`FromBech32Str`] (BIP-173) **and** [`ToBech32m`] / [`FromBech32mStr`] (BIP-350); `_sized::<N>` for a caller-chosen code length |
200//! | `encoding` | no | All encoding features |
201//! | | | **Meta** |
202//! | `cloneable` | no | [`CloneableSecret`] opt-in cloning |
203//! | `full` | no | Everything except `std` |
204//!
205//! # What's available without `alloc`?
206//!
207//! With `default-features = false`:
208//! - [`Fixed<T>`], [`RevealSecret`], [`RevealSecretMut`]
209//! - [`Fixed::try_from_hex`](Fixed::try_from_hex), [`Fixed::try_from_base32`](Fixed::try_from_base32),
210//!   [`Fixed::try_from_base64url`](Fixed::try_from_base64url),
211//!   [`Fixed::try_from_bech32`](Fixed::try_from_bech32), [`Fixed::try_from_bech32m`](Fixed::try_from_bech32m)
212//!   (no-alloc stack-based decoding)
213//! - [`fixed_newtype!`] (distinct nominal types — two keys of the same size that
214//!   the compiler keeps apart); a plain `type` alias over [`Fixed<T>`] needs nothing
215//!   at all
216//! - [`FromSliceError`]
217//!
218//! **Not** available without `alloc`: [`Dynamic<T>`], [`EncodedSecret`],
219//! encoding traits ([`ToHex`], etc.), decoding traits ([`FromHexStr`], etc.),
220//! [`dynamic_newtype!`], serde support.
221//!
222//! # `no_std`
223//!
224//! `no_std` compatible (`#![no_std]` unless the `std` feature is enabled — verified in CI
225//! by cross-building for `thumbv7em-none-eabihf`). [`Fixed<T>`] works without `alloc`.
226//! Enable `alloc` (default) for [`Dynamic<T>`]. For pure stack / embedded builds, use
227//! `default-features = false`. MSRV: **1.85** (Rust edition 2024).
228//!
229//! One caveat: the `rand` feature compiles without `std` or `alloc`, but
230//! [`Fixed::from_random`] relies on `getrandom`, which needs a platform entropy backend.
231//! On bare-metal targets you must configure one (see the `getrandom` crate's
232//! "custom backend" documentation); without it, builds enabling `rand` fail at link
233//! time on such targets. [`Fixed::from_rng`] with a caller-supplied RNG has no such
234//! requirement.
235//!
236//! # Security
237//!
238//! This crate has **not** undergone an independent security audit. No unsafe code —
239//! enforced with `#![forbid(unsafe_code)]`. Prefer scoped access ([`RevealSecret::with_secret`])
240//! over direct references. Encoders return [`EncodedSecret`], which stays wiped until it
241//! drops; `EncodedSecret::into_inner` is the named call that ends that. See
242//! [SECURITY.md](https://github.com/Slurp9187/secure-gate/blob/main/secure-gate-core/SECURITY.md)
243//! for the full threat model.
244//!
245//! # Inherent Rust Limitations
246//!
247//! Three universal limits apply to any in-memory secret library in Rust (and in
248//! C, C++, and Go) — `secure-gate` documents them honestly rather than
249//! overclaiming:
250//!
251//! - **Stack-move residue**: moving a [`Fixed<T>`] by value leaves the prior stack
252//!   slot uncleared until a later frame overwrites it. Prefer
253//!   [`Fixed::new_with`](Fixed::new_with), pass by reference, or use
254//!   [`Dynamic<T>`] for long-lived secrets.
255//! - **Heap-reallocation residue**: `Vec` / `String` realloc frees the old buffer
256//!   unzeroed. Pre-size, use `Dynamic<[u8; N]>` (boxed array — no realloc surface),
257//!   or install a zero-on-dealloc global allocator such as `zeroizing-alloc` at
258//!   the binary level.
259//! - **Swap / core dumps**: process memory paged to disk or written on crash is
260//!   outside any in-process library's reach. Use OS facilities (`mlock`,
261//!   encrypted swap, disabled core dumps).
262//!
263//! Full discussion in
264//! [SECURITY.md § Inherent Rust Limitations](https://github.com/Slurp9187/secure-gate/blob/main/secure-gate-core/SECURITY.md#inherent-rust-limitations).
265//!
266//! See the [README](https://github.com/Slurp9187/secure-gate/blob/main/README.md) and
267//! [SECURITY.md](https://github.com/Slurp9187/secure-gate/blob/main/secure-gate-core/SECURITY.md) for full details.
268
269#[cfg(feature = "alloc")]
270extern crate alloc;
271
272#[cfg(feature = "alloc")]
273mod dynamic;
274
275/// Fixed-size secret wrapper types - always available with zero dependencies.
276/// These provide fundamental secure storage abstractions for fixed-size data.
277mod fixed;
278
279/// Centralized error types - always available.
280mod error;
281
282/// Core traits for wrapper polymorphism - always available.
283pub mod traits;
284
285/// Implementation detail of the `*_newtype!` macros — not a public API.
286///
287/// Generated code needs to name `Zeroize`, `serde` traits, and `alloc` types
288/// without requiring the caller to depend on those crates directly, and
289/// `::alloc::…` paths do not resolve in an ordinary `std` crate. Re-exporting
290/// them here keeps expansions self-contained via `$crate::__private::…`.
291///
292/// Semver-exempt: items here may change or disappear in any release.
293#[doc(hidden)]
294pub mod __private {
295    #[cfg(feature = "alloc")]
296    pub use alloc::{boxed::Box, string::String, vec::Vec};
297    #[cfg(feature = "rand")]
298    pub use rand::{TryCryptoRng, TryRng};
299    #[cfg(feature = "serde-deserialize")]
300    pub use serde::{Deserialize, Deserializer};
301    #[cfg(feature = "serde-serialize")]
302    pub use serde::{Serialize, Serializer};
303    pub use zeroize::{Zeroize, ZeroizeOnDrop};
304}
305
306/// Heap-allocated secret wrapper with explicit access and automatic zeroization on drop.
307///
308/// Variable-length secrets (passwords, API keys, ciphertexts). Inner type must implement
309/// `Zeroize`. Secret bytes live on the heap only — never on the stack. Requires `alloc`.
310///
311/// See [`Fixed<T>`] for the stack-allocated alternative.
312///
313/// ```rust
314/// # #[cfg(feature = "alloc")]
315/// # {
316/// use secure_gate::{Dynamic, RevealSecret};
317///
318/// let pw: Dynamic<String> = Dynamic::new(String::from("hunter2"));
319/// assert_eq!(pw.with_secret(|s: &String| s.len()), 7);
320/// assert_eq!(format!("{:?}", pw), "[REDACTED]");
321/// # }
322/// ```
323#[cfg(feature = "alloc")]
324pub use dynamic::Dynamic;
325
326/// Cursor-like reader over [`Dynamic<Vec<u8>>`] — see [`Dynamic::as_reader`].
327#[cfg(feature = "std")]
328pub use dynamic::DynamicReader;
329
330#[cfg(all(feature = "alloc", feature = "serde-deserialize"))]
331/// Default maximum byte length for `Dynamic<Vec<u8>>` / `Dynamic<String>` deserialization (1 MiB).
332///
333/// The standard `serde::Deserialize` impl for both types rejects payloads exceeding this value.
334/// Pass a custom ceiling to [`Dynamic::deserialize_with_limit`] when a different limit is needed.
335///
336/// **Important:** this limit is enforced *after* the upstream deserializer has fully
337/// materialized the payload. It is a **result-length acceptance bound**, not a
338/// pre-allocation DoS guard. For untrusted input, enforce size limits at the
339/// transport or parser layer upstream.
340pub use dynamic::MAX_DESERIALIZE_BYTES;
341
342/// Stack-allocated secret wrapper with explicit access and automatic zeroization on drop.
343///
344/// Fixed-size secrets (keys, nonces, tokens). Inner type must implement `Zeroize`.
345/// Always available — works without `alloc`. Prefer [`new_with`](Fixed::new_with) over
346/// [`new`](Fixed::new) when minimizing stack residue matters.
347///
348/// See [`Dynamic<T>`] for the heap-allocated alternative.
349///
350/// ```rust
351/// use secure_gate::{Fixed, RevealSecret};
352///
353/// let key = Fixed::new([0xABu8; 32]);
354/// key.with_secret(|b| assert_eq!(b[0], 0xAB));
355/// assert_eq!(format!("{:?}", key), "[REDACTED]");
356/// ```
357pub use fixed::Fixed;
358
359/// Marker trait that opts a secret type into cloning. No methods — gates the `Clone`
360/// impl on [`Fixed`] and [`Dynamic`]. Each clone is independently zeroized on drop,
361/// but increases the in-memory exposure surface. Requires `cloneable` feature.
362///
363/// Implement this on your inner type `T`; `Fixed<T>` and `Dynamic<T>` then gain the
364/// gated `Clone` impl automatically. **This marker is deliberately not implemented by
365/// default** on `Fixed<T>` or `Dynamic<T>` — cloning is an opt-in risk that must be
366/// explicitly enabled. Without the `cloneable` feature this type does not exist at all.
367///
368/// **Coherence note:** Rust's orphan rule prevents downstream crates from implementing
369/// this marker for foreign types such as `String`, `Vec<u8>`, or `[u8; N]` — so
370/// `Dynamic<String>` and `Fixed<[u8; N]>` themselves can never become `Clone`. To opt
371/// a secret into cloning, define a newtype inner type in your crate (deriving
372/// `Zeroize` and `Clone`) and implement the marker on it. This is intentional: it keeps
373/// every cloneable secret type visible in *your* code. See the trait-level docs for a
374/// worked example.
375///
376/// See also [`SerializableSecret`] (the other opt-in marker trait).
377#[cfg(feature = "cloneable")]
378pub use traits::CloneableSecret;
379
380/// Constant-time equality for secrets — prevents timing side-channel attacks.
381///
382/// Provides [`ct_eq()`](ConstantTimeEq::ct_eq) via the `subtle` crate. `==` is
383/// **deliberately not implemented** on [`Fixed`] / [`Dynamic`] — always use `ct_eq`.
384/// Requires `ct-eq` feature.
385///
386/// ```rust
387/// # #[cfg(feature = "ct-eq")]
388/// # {
389/// use secure_gate::{Fixed, ConstantTimeEq};
390///
391/// let a = Fixed::new([1u8; 32]);
392/// let b = Fixed::new([1u8; 32]);
393/// assert!(a.ct_eq(&b));
394/// # }
395/// ```
396#[cfg(feature = "ct-eq")]
397pub use traits::ConstantTimeEq;
398
399/// Explicit immutable access to secret contents (3-tier access model).
400///
401/// - **Tier 1** (preferred): [`with_secret()`](RevealSecret::with_secret) — scoped closure,
402///   borrow cannot escape.
403/// - **Tier 2** (escape hatch): [`expose_secret()`](RevealSecret::expose_secret) — direct
404///   `&T` reference for FFI / third-party APIs.
405/// - **Tier 3** (consumption): [`into_inner()`](RevealSecret::into_inner) — transfers
406///   ownership of the plain value; protection ends with the call.
407///
408/// Length metadata lives in the separate [`SecretLen`] trait. See
409/// [`RevealSecretMut`] for the mutable counterpart.
410// Kept as a separate `use` from `SecretLen` on purpose: rustdoc 1.70 (the 0.8
411// line's MSRV toolchain) ICEs resolving intra-doc links on a grouped
412// `pub use a::{B, C};` re-export, and the two lines share this file.
413pub use traits::RevealSecret;
414
415/// Length metadata for secrets whose inner type has a meaningful length.
416///
417/// [`len()`](SecretLen::len) / [`byte_len()`](SecretLen::byte_len) /
418/// [`is_empty()`](SecretLen::is_empty) do not expose contents, but length itself
419/// can be sensitive for variable-length secrets — see the trait's Security
420/// section. Implemented for `Fixed<[T; N]>`, `Dynamic<String>`, and
421/// `Dynamic<Vec<T>>`; deliberately not for custom inner types.
422pub use traits::SecretLen;
423
424/// Explicit mutable access to secret contents.
425///
426/// Extends [`RevealSecret`]. Prefer [`with_secret_mut()`](RevealSecretMut::with_secret_mut)
427/// (Tier 1) over [`expose_secret_mut()`](RevealSecretMut::expose_secret_mut) (Tier 2).
428/// Implemented by [`Fixed`], [`Dynamic`], and the generated newtypes. [`EncodedSecret`]
429/// implements neither this nor [`RevealSecret`] — it is an output wrapper, not a secret one.
430pub use traits::RevealSecretMut;
431
432/// Placeholder values left behind by [`RevealSecret::into_inner`] (Tier 3 access).
433///
434/// When `into_inner` moves the real secret out of a wrapper, it must leave *something*
435/// behind for the wrapper's `Drop` impl to zeroize. `SentinelValue::sentinel_value()`
436/// produces that inert placeholder (an all-default array, empty `String`, or empty
437/// `Vec`). Implemented for `[T; N]` (any `N`, `T: Default`), `String`, and `Vec<T>`.
438///
439/// Implement this for your own inner types to make `into_inner` available on wrappers
440/// around them. A sentinel must never contain secret material.
441///
442/// Leaving it unimplemented is a deliberate position, not a gap: `into_inner` is then
443/// uncallable for that inner type, so a secret with no safe inert placeholder simply
444/// cannot be extracted by ownership transfer. `with_secret` and `expose_secret` still
445/// work. That is the safe default rather than a missing feature.
446pub use traits::SentinelValue;
447
448/// Asserts that an inner type owns no heap allocation.
449///
450/// Required by [`Fixed::new`], which is what makes `SECURITY.md`'s claim that `Fixed<T>`
451/// "has no realloc surface" true rather than aspirational. Before this bound existed,
452/// `Fixed<Vec<u8>>`, `Fixed<String>` and `fixed_newtype!(pub Name, generic Vec<u8>)` all
453/// compiled, and measured, they abandoned an unwiped buffer holding the whole secret on
454/// any capacity change — the same weakness `Dynamic` documents, minus `Dynamic`'s
455/// safe-growth `std::io::Write` path.
456///
457/// Implemented for the primitives, `[T; N]` for any `N`, tuples up to four elements, and
458/// `Option<T>`. Nothing heap-owning is implemented: `Vec<T>`, `String` and `Box<[T]>` are
459/// all absent, because the residue does not need a capacity change — replacing the whole
460/// value abandons the allocation too, measured at 1024 of 1024 bytes through a
461/// `Fixed<Box<[u8]>>`. For a heap-backed secret use [`Dynamic`], which documents the
462/// residue and offers the one safe growth path.
463///
464/// A custom inner type writes `impl FixedStorage for MyKey {}`. Like [`CloneableSecret`],
465/// the compiler checks that you made the claim, not that it is true — see the trait docs
466/// for the test to apply and for why an assertion is the right trade here.
467pub use traits::FixedStorage;
468
469/// Encoded string **output wrapper** for zeroizing encoded output.
470///
471/// This is an **output wrapper** — it exists *only* to keep encoded data zeroized until
472/// it drops. It is **not** a secret wrapper like [`Fixed`]/[`Dynamic`] and does not
473/// accept [`CloneableSecret`] or [`SerializableSecret`] markers.
474///
475/// Returned by every encoding method (`to_hex`, `to_hex_upper`, `to_base32`,
476/// `to_base64url`, `try_to_bech32`, `try_to_bech32m`, and the `_sized::<N>` forms of
477/// the last two — only bech32 and bech32m take a code length).
478/// Wraps `Zeroizing<String>` with `Debug` → `[REDACTED]`. Its one accessor is
479/// `Deref<Target = str>`; there are deliberately no `AsRef` impls, because `Deref`
480/// already opens that door. Deliberately **no** `Display` either: `{}` on this type is
481/// a compile error, so `Debug` redaction cannot mislead a caller into logging the
482/// encoded secret. Write it out with `&*encoded`.
483///
484/// Use [`into_inner()`](EncodedSecret::into_inner) to extract a plain `String`
485/// (ends zeroization) or [`into_zeroizing()`](EncodedSecret::into_zeroizing) to keep
486/// the wiping. `into_zeroizing` is a partial downgrade: zeroize-on-drop survives, the
487/// redacted `Debug` does not, because `zeroize::Zeroizing` derives its own.
488///
489/// Requires `alloc` feature.
490#[cfg(feature = "alloc")]
491pub use traits::EncodedSecret;
492
493/// Marker trait that opts a secret type into Serde serialization. No methods — gates the
494/// `Serialize` impl on [`Fixed`] and [`Dynamic`]. Serialization exposes the full secret;
495/// audit every impl. Requires `serde-serialize` feature.
496///
497/// **`Deserialize` does NOT require this marker** — it is gated separately by the
498/// `serde-deserialize` feature with its own impls on the wrapper types directly. This
499/// marker controls `Serialize` only.
500///
501/// Implement this on your inner type `T`; `Fixed<T>` and `Dynamic<T>` then gain the
502/// gated `Serialize` impl automatically. **This marker is deliberately not implemented
503/// by default** on `Fixed<T>` or `Dynamic<T>` — serialization is an opt-in risk that
504/// must be explicitly enabled. Without the `serde-serialize` feature this type does not
505/// exist at all.
506///
507/// **Coherence note:** Rust's orphan rule prevents downstream crates from implementing
508/// this marker for foreign types such as `String`, `Vec<u8>`, or `[u8; N]` — so
509/// `Fixed<[u8; N]>` and `Dynamic<String>` themselves can never become `Serialize`. To
510/// opt a secret into serialization, define a newtype inner type in your crate (deriving
511/// `Zeroize` and `Serialize`) and implement the marker on it. This is intentional: it
512/// keeps every serializable secret type visible in *your* code. See the trait-level
513/// docs for a worked example.
514///
515/// See also [`CloneableSecret`] (the other opt-in marker trait).
516#[cfg(feature = "serde-serialize")]
517pub use traits::SerializableSecret;
518
519// Newtype macros (`dynamic_newtype!` needs `alloc`)
520mod macros;
521
522/// Decodes Base32 strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
523/// Requires `encoding-base32` + `alloc`. See [`ToBase32`] for the encoding counterpart.
524#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
525pub use traits::FromBase32Str;
526
527/// Decodes Base64url strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
528/// Requires `encoding-base64` + `alloc`. See [`ToBase64Url`] for the encoding counterpart.
529#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
530pub use traits::FromBase64UrlStr;
531
532/// Decodes Bech32 (BIP-173) strings to `Vec<u8>` with HRP validation.
533/// Requires `encoding-bech32` + `alloc`. See [`ToBech32`] for the encoding counterpart.
534#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
535pub use traits::FromBech32Str;
536
537/// Decodes Bech32m (BIP-350) strings to `Vec<u8>` with HRP validation.
538/// Requires `encoding-bech32` + `alloc`. See [`ToBech32m`] for the encoding counterpart.
539#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
540pub use traits::FromBech32mStr;
541
542/// Decodes hex strings (`&str`) to `Vec<u8>`. Blanket impl for `AsRef<str>`.
543/// Requires `encoding-hex` + `alloc`. See [`ToHex`] for the encoding counterpart.
544#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
545pub use traits::FromHexStr;
546
547/// Encodes byte data as Base32 strings (RFC 4648 §6, uppercase, no padding).
548/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Returns [`EncodedSecret`].
549/// Requires `encoding-base32` + `alloc`.
550/// See [`FromBase32Str`] for the decoding counterpart.
551#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
552pub use traits::ToBase32;
553
554/// Encodes byte data as Base64url strings (RFC 4648, URL-safe, no padding).
555/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Returns [`EncodedSecret`].
556/// Requires `encoding-base64` + `alloc`.
557/// See [`FromBase64UrlStr`] for the decoding counterpart.
558#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
559pub use traits::ToBase64Url;
560
561/// Encodes byte data as Bech32 (BIP-173) strings. Blanket impl for
562/// `AsRef<[u8]> + `[`EncodableBytes`]; returns `Result<`[`EncodedSecret`]`, _>`.
563/// The plain methods use [`BECH32_CODE_LENGTH`]; `try_to_bech32_sized::<N>` takes the
564/// code length as a parameter. Requires `encoding-bech32` + `alloc`.
565/// See [`FromBech32Str`] for the decoding counterpart.
566#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
567pub use traits::ToBech32;
568
569/// Encodes byte data as Bech32m (BIP-350) strings. Blanket impl for
570/// `AsRef<[u8]> + `[`EncodableBytes`]; returns `Result<`[`EncodedSecret`]`, _>`.
571/// The plain methods use [`BECH32_CODE_LENGTH`]; `try_to_bech32m_sized::<N>` takes the
572/// code length as a parameter. Requires `encoding-bech32` + `alloc`.
573/// See [`FromBech32mStr`] for the decoding counterpart.
574#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
575pub use traits::ToBech32m;
576
577/// Opt-in marker for byte-shaped encoding inputs. Every `To*` trait is blanket
578/// implemented for `AsRef<[u8]> + EncodableBytes`; the second bound keeps string-shaped
579/// types out, so an already-encoded value cannot be silently encoded again. Implement it
580/// for your own byte newtype to make it encodable.
581#[cfg(feature = "encoding-bech32")]
582pub use traits::Case;
583
584#[cfg(any(
585    feature = "encoding-hex",
586    feature = "encoding-base32",
587    feature = "encoding-base64",
588    feature = "encoding-bech32",
589))]
590pub use traits::EncodableBytes;
591
592/// Bech32 (BIP-173) checksum with a caller-chosen code length. `N` caps the length of
593/// the whole encoded string and never enters the checksum. Above [`BECH32_CODE_LENGTH`]
594/// the BCH error-detection guarantee no longer holds - see the type docs.
595#[cfg(feature = "encoding-bech32")]
596pub use traits::{Bech32Sized, Bech32Standard};
597
598/// Bech32m (BIP-350) checksum with a caller-chosen code length - the bech32m twin of
599/// [`Bech32Sized`], with the same rules and the same guarantee boundary.
600#[cfg(feature = "encoding-bech32")]
601pub use traits::{Bech32mSized, Bech32mStandard};
602
603/// The bech32 BCH code length (1023) used by every non-`_sized` method, and the helper
604/// that sizes an `N` from an HRP length and a payload byte count.
605#[cfg(feature = "encoding-bech32")]
606pub use traits::{BECH32_CODE_LENGTH, bech32_code_length};
607
608/// Encodes byte data as hexadecimal strings (constant-time via `base16ct`).
609/// Blanket impl for `AsRef<[u8]> + `[`EncodableBytes`]. Provides `to_hex()` and
610/// `to_hex_upper()`, both returning [`EncodedSecret`].
611/// Requires `encoding-hex` + `alloc`.
612/// See [`FromHexStr`] for the decoding counterpart.
613#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
614pub use traits::ToHex;
615
616/// Errors from Bech32 (BIP-173) and Bech32m (BIP-350) decoding.
617/// Variant shapes are identical in debug and release builds; no secret material
618/// (payload bytes, HRP strings) is ever carried in an error.
619#[cfg(feature = "encoding-bech32")]
620pub use error::Bech32Error;
621
622/// Errors from Base32 (RFC 4648 §6, uppercase, unpadded) decoding. Variant shapes are
623/// identical in debug and release builds; only numeric length metadata is carried.
624#[cfg(feature = "encoding-base32")]
625pub use error::Base32Error;
626
627/// Errors from Base64url decoding. Variant shapes are identical in debug and
628/// release builds; only numeric length metadata is carried.
629#[cfg(feature = "encoding-base64")]
630pub use error::Base64Error;
631
632/// Errors from hex decoding. Variant shapes are identical in debug and
633/// release builds; only numeric length metadata is carried.
634#[cfg(feature = "encoding-hex")]
635pub use error::HexError;
636
637/// Error returned when a byte slice cannot be converted to `Fixed<[u8; N]>` due to
638/// length mismatch. Produced by `Fixed::try_from(&[u8])`.
639pub use error::FromSliceError;
640
641// The README's examples are compiled and run by `cargo test --doc`, so they cannot
642// silently rot. `cfg(doctest)` is set only while rustdoc *collects doctests* — never
643// while it *builds documentation* — so this item never reaches docs.rs or `cargo doc`
644// output, and the README is not duplicated onto the crate page.
645//
646// Gated on `full` as well: the README documents the fully-featured crate, so its
647// examples use `alloc` and the encoding traits unconditionally. Without this gate the
648// `--no-default-features` doctest job in CI would fail on imports the README does not
649// feature-gate. CI's `--features full` and `--all-features` entries do run them.
650//
651// It must live at the end of the file: an item here would otherwise sit ahead of the
652// `//!` crate docs above, which is not allowed.
653#[cfg(all(doctest, feature = "full"))]
654#[doc = include_str!("../README.md")]
655pub struct ReadmeDoctests;