secure_gate/fixed.rs
1//! Stack-allocated wrapper for fixed-size secrets.
2//!
3//! [`Fixed<T>`] is a zero-cost wrapper that enforces explicit, auditable access to
4//! sensitive data stored inline on the stack. It is the primary secret type for
5//! fixed-length material such as cryptographic keys, nonces, and seeds.
6//!
7//! # Security invariants
8//!
9//! - **No `Deref`, `AsRef`, or `Copy`** — the inner value cannot leak through
10//! implicit conversions.
11//! - **`Debug` always prints `[REDACTED]`** — secrets never appear in logs or
12//! panic messages.
13//! - **Unconditional zeroization on drop** — the inner `T` is overwritten with
14//! zeroes when the wrapper is dropped, even on error paths.
15//! - **Opt-in `Clone`** — requires `T: CloneableSecret` and the `cloneable` feature.
16//! - **Opt-in `Serialize`** — requires the `SerializableSecret` marker and the
17//! `serde-serialize`/`serde-deserialize` features.
18//! - **Avoid move-by-value for long-lived secrets.** Each move of a `Fixed<T>`
19//! bitwise-copies the bytes to a new location and leaves the original stack
20//! slot uncleared until a later frame overwrites it. Pass `&Fixed<T>` /
21//! `&mut Fixed<T>` by reference, keep the wrapper short-scope, or use
22//! [`Dynamic<T>`](crate::Dynamic) for long-lived material (heap-only — no
23//! stack residue surface). See `SECURITY.md` § "Inherent Rust Limitations".
24//!
25//! # Construction
26//!
27//! | Constructor | Notes |
28//! |---|---|
29//! | [`Fixed::new(value)`](Fixed::new) | Ergonomic default; `const fn`. |
30//! | [`Fixed::new_with(f)`](Fixed::new_with) | Scoped — preferred for stack-residue minimization. |
31//! | [`Fixed::try_new_with(f)`](Fixed::try_new_with) | Scoped, for a fill that can fail; wipes on `Err`. |
32//!
33//! Prefer [`new_with`](Fixed::new_with) in high-assurance code: it writes directly
34//! into the wrapper's storage, avoiding the intermediate stack copy that `new` may
35//! produce.
36//!
37//! # 3-tier access model
38//!
39//! ```rust
40//! use secure_gate::{Fixed, RevealSecret, RevealSecretMut};
41//!
42//! let mut secret = Fixed::new([1u8, 2, 3, 4]);
43//!
44//! // Tier 1 — scoped (preferred): borrow is confined to the closure.
45//! let sum = secret.with_secret(|arr| arr.iter().sum::<u8>());
46//! assert_eq!(sum, 10);
47//!
48//! // Tier 2 — direct: returns a reference. Use as an escape hatch.
49//! let first: u8 = secret.expose_secret()[0];
50//! assert_eq!(first, 1);
51//!
52//! // Tier 1 mutable — scoped mutation (preferred over Tier 2 mutable).
53//! secret.with_secret_mut(|arr| arr[0] = 0xFF);
54//!
55//! // Tier 3 — owned: consumes the wrapper for final use.
56//! let owned = secret.into_inner();
57//! ```
58//!
59//! # Warning: no `static` secrets
60//!
61//! `Drop` does not run on `static` items. Placing a `Fixed` in a `static` or
62//! `lazy_static!` will **skip zeroization**. Always use stack or heap allocation.
63//!
64//! Also ensure your profile sets `panic = "unwind"` — `panic = "abort"` skips
65//! destructors and therefore skips zeroization.
66//!
67//! # Import path
68//!
69//! All public items are re-exported at the crate root. Use:
70//!
71//! ```rust
72//! use secure_gate::Fixed;
73//! ```
74//!
75//! Not `secure_gate::fixed::Fixed`.
76//!
77//! # See also
78//!
79//! - [`Dynamic<T>`](crate::Dynamic) — heap-allocated alternative for variable-length
80//! secrets (passwords, API keys, ciphertexts). Requires the `alloc` feature.
81//!
82//! # Examples
83//!
84//! ```rust
85//! use secure_gate::{Fixed, RevealSecret};
86//!
87//! let secret = Fixed::new([1u8, 2, 3, 4]);
88//! let sum = secret.with_secret(|arr| arr.iter().sum::<u8>());
89//! assert_eq!(sum, 10);
90//! ```
91
92use crate::RevealSecret;
93use crate::RevealSecretMut;
94
95#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
96use crate::traits::encoding::base32::ToBase32;
97#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
98use crate::traits::encoding::base64_url::ToBase64Url;
99#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
100use crate::traits::encoding::bech32::ToBech32;
101#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
102use crate::traits::encoding::bech32m::ToBech32m;
103#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
104use crate::traits::encoding::hex::ToHex;
105
106#[cfg(feature = "rand")]
107use rand::{TryCryptoRng, TryRng, rngs::SysRng};
108use zeroize::Zeroize;
109
110/// Drains a validated Bech32/Bech32m payload into a stack buffer.
111///
112/// Shared by the four `try_from_bech32*` constructors. Copies exactly `N`
113/// payload bytes into a `Zeroizing<[u8; N]>`; keeps counting (without storing)
114/// past `N` so the length-mismatch error reports the exact decoded length.
115/// The iteration count is bounded by the checksum-validated input string, so
116/// oversized inputs cost at most one bounded pass. Works without `alloc`.
117#[cfg(feature = "encoding-bech32")]
118fn drain_bech32_payload<const N: usize>(
119 checked: &bech32::primitives::decode::CheckedHrpstring<'_>,
120) -> Result<zeroize::Zeroizing<[u8; N]>, crate::error::Bech32Error> {
121 let mut buf = zeroize::Zeroizing::new([0u8; N]);
122 let mut count = 0usize;
123 for byte in checked.byte_iter() {
124 if count < N {
125 buf[count] = byte;
126 }
127 count += 1;
128 }
129 if count != N {
130 return Err(crate::error::Bech32Error::InvalidLength {
131 expected: N,
132 got: count,
133 });
134 }
135 Ok(buf)
136 // On the error path, buf is zeroized on drop.
137}
138
139/// Zero-cost stack-allocated wrapper for fixed-size secrets.
140///
141/// `Fixed<T>` stores a `T: Zeroize` value inline and unconditionally zeroizes it
142/// on drop. There is no `Deref`, `AsRef`, or `Copy` — every access is explicit
143/// through [`RevealSecret`] or [`RevealSecretMut`].
144///
145/// # Examples
146///
147/// ```rust
148/// use secure_gate::{Fixed, RevealSecret};
149///
150/// // Create a secret key.
151/// let key = Fixed::new([0xABu8; 32]);
152///
153/// // Scoped access — the borrow cannot escape the closure.
154/// let first = key.with_secret(|k| k[0]);
155/// assert_eq!(first, 0xAB);
156///
157/// // Debug is always redacted.
158/// assert_eq!(format!("{:?}", key), "[REDACTED]");
159/// ```
160///
161/// # Constructors
162///
163/// | Constructor | Feature | Notes |
164/// |---|---|---|
165/// | [`new(value)`](Self::new) | — | `const fn`, ergonomic default |
166/// | [`new_with(f)`](Self::new_with) | — | Scoped; preferred for stack-residue minimization |
167/// | [`try_new_with(f)`](Self::try_new_with) | — | Scoped, fallible fill; zeroizes the partial write on `Err` |
168/// | [`From<[u8; N]>`](#impl-From<%5Bu8;+N%5D>-for-Fixed<%5Bu8;+N%5D>) | — | Equivalent to `new` |
169/// | [`TryFrom<&[u8]>`](#impl-TryFrom<%26%5Bu8%5D>-for-Fixed<%5Bu8;+N%5D>) | — | Length-checked slice conversion |
170/// | [`try_from_hex`](Self::try_from_hex) | `encoding-hex` | Constant-time hex decoding |
171/// | [`try_from_base32`](Self::try_from_base32) | `encoding-base32` | Constant-time Base32 decoding |
172/// | [`try_from_base64url`](Self::try_from_base64url) | `encoding-base64` | Constant-time Base64url decoding |
173/// | [`try_from_bech32`](Self::try_from_bech32) | `encoding-bech32` | HRP-validated Bech32 decoding |
174/// | [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked) | `encoding-bech32` | Bech32 without HRP check |
175/// | [`try_from_bech32m`](Self::try_from_bech32m) | `encoding-bech32` | HRP-validated Bech32m decoding |
176/// | [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked) | `encoding-bech32` | Bech32m without HRP check |
177/// | [`from_random()`](Self::from_random) | `rand` | System RNG |
178/// | [`from_rng(rng)`](Self::from_rng) | `rand` | Custom RNG |
179///
180/// # What `T` may be
181///
182/// [`Fixed::new`] requires [`FixedStorage`](crate::FixedStorage) on the inner type: a
183/// type that owns no heap allocation. This is what makes the documented
184/// claim that `Fixed` has no reallocation surface true rather than aspirational. It used
185/// to be bounded only by `Zeroize`, so `Fixed<Vec<u8>>`, `Fixed<String>` and even
186/// `Fixed<[Vec<u8>; 2]>` compiled and abandoned an unwiped buffer holding the whole
187/// secret on any capacity change. Arrays, the primitives, tuples, `Option` and boxed
188/// slices satisfy the marker already; a custom inner type writes one line. For a
189/// growable payload use [`Dynamic`](crate::Dynamic), which documents the residue and
190/// offers one safe growth path.
191///
192/// The bound is on the constructor rather than on the struct, so naming
193/// `Fixed<Vec<u8>>` still compiles and no value of it can exist — the same shape as the
194/// zero-size guard below.
195///
196/// # Zero-size
197///
198/// A value of zero size has nothing to protect, so a `Fixed` cannot be built around
199/// one. [`new`](Self::new) and [`new_with`](Self::new_with) each assert a non-zero size
200/// in a `const`, and every other constructor in the table above funnels through those
201/// two, so `Fixed<[u8; 0]>` — and any other zero-sized inner type — is a compile error
202/// however it is reached. The assertion is evaluated at monomorphization rather than at
203/// the declaration, so it fires at the first concrete zero-sized construction, including
204/// one reached through generic code; generic code that is never instantiated with a
205/// zero-sized `T` is unaffected, and naming such a type without constructing one still
206/// compiles.
207///
208/// The diagnostic names the offending type in the failing constant's path — for example
209/// `Fixed::<[u8; 0]>::NON_ZERO_SIZED` — and a `while instantiating` note repeats the span of
210/// the `new` call the monomorphization reached — the error's own span is the assertion
211/// here, not in your code. The note does not name the instantiation that caused it: for a generic `fn build<const N: usize>()`, calling `build::<0>()` reports
212/// against the `Fixed::new` line inside `build`, and the `::<0>` call site appears nowhere.
213///
214/// **Two limits on when it fires, both measured.** It is raised during codegen, so
215/// `cargo check` does not report it. And it only fires for a *codegen root*: a non-generic
216/// `#[inline]` function in a library is not one, and every method the newtype macros
217/// generate carries an inline attribute, so a library whose only zero-sized constructions sit
218/// behind `#[inline]` or generic code builds, tests and publishes clean — the error then
219/// surfaces in each downstream crate that instantiates it, blaming this crate and the
220/// dependency's macro invocation rather than the consumer's call.
221///
222/// Root-ness is a property of the compiler and the profile, not of the attribute alone, so
223/// removing `#[inline]` does not reliably restore the error. Measured: on 1.85 a library
224/// exporting a plain non-generic `pub fn empty() -> Empty { Empty::new([]) }` fails
225/// `cargo build` and `cargo test` but passes `cargo build --release`, because the
226/// cross-crate-inlining heuristic added in 1.75 drops a small function from the exported
227/// root set in an optimized build; on 1.70 the same crate fails in both profiles. Treat
228/// instantiating the type in a test or a binary as the only reliable check.
229///
230/// Stated precisely: no *value* of a zero-sized `Fixed` can exist at runtime, because
231/// nothing can construct one, and a binary or test that tries fails to compile. The guard
232/// does not stop a library from exporting an unusable zero-sized API. Neither limit is a
233/// choice — a condition on a generic parameter has nothing to evaluate until that parameter
234/// is known, and nothing on stable Rust moves it earlier.
235///
236/// [`Dynamic`](crate::Dynamic) has no compile-time counterpart, for a reason about its
237/// payload rather than its own size: whether a `Vec` or `String` is empty is a runtime
238/// property, so there is nothing for a compile-time check to decide. A statically
239/// zero-sized inner type is the gap that leaves — `Dynamic<Zst>` constructs where
240/// `Fixed<Zst>` does not.
241///
242/// # RustCrypto integration
243///
244/// RustCrypto's `BlockEncrypt`/`BlockDecrypt` take `&mut GenericArray<u8, U16>`, and
245/// `GenericArray::from_mut_slice` **borrows** its argument instead of copying it. That
246/// is what lets a block cipher run *inside* the wrapper, so the plaintext never
247/// materializes in memory nothing is obliged to wipe:
248///
249/// ```rust
250/// use aes::cipher::{generic_array::GenericArray, BlockDecrypt, KeyInit};
251/// use aes::Aes128;
252/// use secure_gate::{Fixed, RevealSecretMut};
253///
254/// let cipher = Aes128::new(GenericArray::from_slice(&[0x42u8; 16]));
255/// let mut block: Fixed<[u8; 16]> = Fixed::new([0u8; 16]);
256///
257/// // `from_mut_slice` reborrows the wrapper's own storage, so zeroize-on-drop still
258/// // covers every path out of this scope — early returns and panics included.
259/// block.with_secret_mut(|b| cipher.decrypt_block(GenericArray::from_mut_slice(b)));
260/// ```
261///
262/// The shape type inference nudges you toward is the footgun. It compiles, it is the
263/// easy thing to reach for, and it defeats the wrapper:
264///
265/// ```rust
266/// # use aes::cipher::{generic_array::GenericArray, BlockDecrypt, KeyInit};
267/// # use aes::Aes128;
268/// # use secure_gate::{Fixed, RevealSecret};
269/// # let cipher = Aes128::new(GenericArray::from_slice(&[0x42u8; 16]));
270/// # let block: Fixed<[u8; 16]> = Fixed::new([0u8; 16]);
271/// // Copies the secret OUT. `copy` is an ordinary stack value: no zeroization on
272/// // drop, and it holds plaintext-equivalent bytes for the rest of the scope.
273/// let mut copy = block.with_secret(|b| aes::Block::from(*b));
274/// cipher.decrypt_block(&mut copy);
275/// ```
276///
277/// The same reasoning applies to [`Dynamic`](crate::Dynamic)`<Vec<u8>>` through
278/// [`with_secret_mut`](crate::RevealSecretMut::with_secret_mut), and to the
279/// slice-at-a-time APIs (`decrypt_blocks`, `apply_keystream`), which take
280/// `&mut [Block]` and `&mut [u8]` and so borrow just as well.
281///
282/// # See also
283///
284/// - [`RevealSecret`] / [`RevealSecretMut`] — the 3-tier access traits.
285/// - [`new_with`](Self::new_with) — scoped constructor preferred over [`new`](Self::new).
286///
287/// # Note
288///
289/// `const fn new` compiles in `static` position, but **must not** be used there
290/// because `Drop` does not run on statics, which means zeroization is skipped.
291#[must_use = "Fixed<T> holds secret material; dropping it on the floor usually indicates a bug — bind with `let _name = ...` or chain a method call"]
292pub struct Fixed<T: zeroize::Zeroize> {
293 inner: T,
294}
295
296impl<T: zeroize::Zeroize> Fixed<T> {
297 // Post-monomorphization guard: a zero-sized `T` has nothing to protect. Fires at the
298 // first concrete construction, never at the declaration. An associated `const` rather
299 // than an inline `const {}` block so the same hunk builds on the 0.8 line's MSRV 1.70.
300 const NON_ZERO_SIZED: () = assert!(
301 ::core::mem::size_of::<T>() > 0,
302 "secure-gate: Fixed<T> cannot hold a zero-sized value; there is nothing to protect"
303 );
304
305 /// Creates a new [`Fixed<T>`] by wrapping a value.
306 ///
307 /// This is a `const fn`, so it can be evaluated at compile time. However,
308 /// **do not** use it to initialize `static` items — `Drop` does not run on
309 /// statics, so zeroization would be skipped.
310 ///
311 /// Prefer [`new_with`](Fixed::new_with) when `T: `[`SentinelValue`](crate::SentinelValue)
312 /// and minimizing stack residue matters: `new` may leave an intermediate copy
313 /// of `value` on the caller's stack frame.
314 ///
315 /// A zero-sized `T` is rejected at compile time; see [Zero-size](#zero-size).
316 ///
317 /// # Examples
318 ///
319 /// ```rust
320 /// use secure_gate::{Fixed, RevealSecret, SecretLen};
321 ///
322 /// let secret = Fixed::new([0u8; 32]);
323 /// assert_eq!(secret.len(), 32);
324 /// ```
325 #[inline(always)]
326 pub const fn new(value: T) -> Self
327 where
328 T: crate::FixedStorage,
329 {
330 // Binding the unit-valued const is what forces it to be evaluated; clippy reads
331 // that as a pointless binding. Kept explicit because the 1.70 lint (the 0.8
332 // line's MSRV) fires on every spelling that still triggers the evaluation.
333 #[allow(clippy::let_unit_value)]
334 let () = Self::NON_ZERO_SIZED;
335 Fixed { inner: value }
336 }
337
338 /// Writes directly into the wrapper's storage via a user-supplied closure,
339 /// eliminating the intermediate stack copy that [`new`](Self::new) may produce.
340 ///
341 /// The slot is initialized to [`T::sentinel_value()`](crate::SentinelValue::sentinel_value)
342 /// before the closure runs. Prefer this over [`new(value)`](Self::new) when
343 /// minimizing stack residue matters (long-lived keys, high-assurance environments).
344 ///
345 /// # The slot's starting content is a contract, not an accident
346 ///
347 /// For `T = [E; N]` with `E: Default` — every array this crate ever hands you —
348 /// [`SentinelValue`](crate::SentinelValue)'s own contract fixes that starting value
349 /// at `[E::default(); N]`, all-zero for the byte and integer arrays this type is
350 /// built around. That is a promise `SentinelValue` makes on purpose (see its
351 /// "Provided implementations" contract), not a side effect of how the sentinel
352 /// happens to be built today, so a caller may depend on it exactly as it depends on
353 /// any other documented behavior.
354 ///
355 /// Concretely: a closure that writes fewer than `N` elements — a
356 /// [`SlotWriter`](crate::SlotWriter) doing RFC 9180-style concatenation that falls
357 /// short of the slot, a key derivation shorter than its buffer — leaves the
358 /// untouched tail at zero rather than at whatever bytes happened to be on the
359 /// stack. Code that treats that tail as zero-padding, instead of re-zeroing it
360 /// itself before returning, is relying on this guarantee; the
361 /// [`SlotWriter`](crate::SlotWriter) documentation's "40-bit key, zero-padded to
362 /// 16" example is exactly that reliance, asserted in a doctest.
363 ///
364 /// Requires [`FixedStorage`](crate::FixedStorage) and
365 /// [`SentinelValue`](crate::SentinelValue) on `T`. Arrays of a `Default`
366 /// element already have both; a custom inner type needs the same pair
367 /// `into_inner` already asks for.
368 ///
369 /// # `T` must be inferable at the call site
370 ///
371 /// This constructor is generic over `T`, so the closure's parameter type is
372 /// not known until `T` is. A return type alone does not resolve it in time:
373 /// `fn k() -> Fixed<[u8; 32]> { Fixed::new_with(|a| a.fill(1)) }` fails with
374 /// **E0282**, `type annotations needed for &mut _`, because the closure body
375 /// is checked before the expected return type reaches `T`. Name the type in
376 /// either position — both compile, pick whichever reads better:
377 ///
378 /// ```rust
379 /// use secure_gate::Fixed;
380 ///
381 /// // On the type:
382 /// let a = Fixed::<[u8; 32]>::new_with(|x| x.fill(1));
383 /// // Or on the closure parameter:
384 /// let b = Fixed::new_with(|x: &mut [u8; 32]| x.fill(1));
385 /// # let _ = (a, b);
386 /// ```
387 ///
388 /// Before 0.9.0-rc.10 this method was inherent to `Fixed<[u8; N]>`, where the
389 /// parameter was always a byte array and inference had nothing to resolve. A
390 /// newtype built by [`fixed_newtype!`](crate::fixed_newtype) is unaffected in
391 /// both arms: its generated `new_with` has a concrete parameter type.
392 ///
393 /// # Security rationale
394 ///
395 /// With [`Fixed::new(value)`](Self::new), the caller first builds `value` on
396 /// its own stack frame, then moves it into the wrapper. The compiler *may*
397 /// elide the copy, but this is not guaranteed — leaving a plaintext residue
398 /// on the stack. `new_with` avoids this by giving the closure a mutable
399 /// reference to the wrapper's *own* storage, so the secret is never placed
400 /// anywhere else.
401 ///
402 /// # Examples
403 ///
404 /// ```rust
405 /// use secure_gate::{Fixed, RevealSecret};
406 ///
407 /// // Fill from a closure — no intermediate stack copy.
408 /// let secret = Fixed::<[u8; 4]>::new_with(|arr| arr.fill(0xAB));
409 /// assert_eq!(secret.expose_secret(), &[0xAB; 4]);
410 ///
411 /// // Copy from an existing slice.
412 /// let src = [1u8, 2, 3, 4];
413 /// let secret = Fixed::<[u8; 4]>::new_with(|arr| arr.copy_from_slice(&src));
414 /// ```
415 ///
416 /// A non-byte array uses the same constructor:
417 ///
418 /// ```rust
419 /// use secure_gate::{Fixed, RevealSecret};
420 ///
421 /// let poly = Fixed::<[i16; 4]>::new_with(|c| c.fill(7));
422 /// assert_eq!(poly.expose_secret(), &[7i16; 4]);
423 /// ```
424 ///
425 /// # See also
426 ///
427 /// - [`try_new_with`](Self::try_new_with) — the same thing when the fill can
428 /// fail, rather than routing the error out through a captured local.
429 /// - [`Dynamic::new_with`](crate::Dynamic::new_with) — the heap-allocated
430 /// equivalent (requires `alloc`).
431 ///
432 /// If the secret will outlive the current function, prefer
433 /// [`Dynamic<T>`](crate::Dynamic) over moving `Fixed<T>` around — each
434 /// move-by-value leaves residue in the previous stack slot.
435 #[inline(always)]
436 pub fn new_with<F>(f: F) -> Self
437 where
438 T: crate::FixedStorage + crate::SentinelValue,
439 F: FnOnce(&mut T),
440 {
441 // Binding the unit-valued const is what forces it to be evaluated; clippy reads
442 // that as a pointless binding. Kept explicit because the 1.70 lint (the 0.8
443 // line's MSRV) fires on every spelling that still triggers the evaluation.
444 #[allow(clippy::let_unit_value)]
445 let () = Self::NON_ZERO_SIZED;
446 let mut this = Self {
447 inner: <T as crate::SentinelValue>::sentinel_value(),
448 };
449 f(&mut this.inner);
450 this
451 }
452
453 /// Writes directly into the wrapper's storage via a closure that may fail.
454 ///
455 /// The fallible sibling of [`new_with`](Self::new_with), and identical to it in
456 /// every respect but the closure's return type. Reach for it whenever filling the
457 /// secret can fail — reading from a file, a socket, a device — so that writing in
458 /// place and handling the error stay one expression.
459 ///
460 /// On `Err` the partially written slot is **zeroized before the error is
461 /// returned**: the wrapper exists for the whole of the closure's run, so
462 /// [`Drop`](Fixed#impl-Drop-for-Fixed<T>) wipes whatever the closure managed to
463 /// write. A failed fill leaves nothing behind, in memory or in the return value.
464 ///
465 /// On `Ok`, the slot the closure saw started at the same value
466 /// [`new_with`](Self::new_with)'s does —
467 /// [`T::sentinel_value()`](crate::SentinelValue::sentinel_value), which for `T =
468 /// [E; N]` with `E: Default` is `[E::default(); N]`, all-zero for the byte and
469 /// integer arrays this type is built around. That starting value is a contract of
470 /// [`SentinelValue`](crate::SentinelValue)'s, documented on `new_with` above, not an
471 /// incidental one — so a closure here that only partially fills the slot before
472 /// returning `Ok` leaves the same reliable zero tail behind, on the same guarantee.
473 ///
474 /// Requires [`FixedStorage`](crate::FixedStorage) and
475 /// [`SentinelValue`](crate::SentinelValue) on `T`, exactly as `new_with` does.
476 ///
477 /// # Why `try_`, given the rest of this type
478 ///
479 /// Elsewhere here `try_` marks a constructor that *parses* untrusted input —
480 /// [`try_from_hex`](Self::try_from_hex), [`try_from_base32`](Self::try_from_base32),
481 /// `TryFrom<&[u8]>` — while [`from_rng`](Self::from_rng) is fallible and keeps
482 /// `from_`. This method widens the prefix to its ordinary Rust meaning, the one
483 /// `try_reserve` and `try_lock` carry: **`try_` marks a constructor that can fail**,
484 /// whether because it validates input or because the caller's fill can.
485 ///
486 /// # `T` must be inferable at the call site
487 ///
488 /// Generic over `T`, so the closure's parameter type is not known until `T` is —
489 /// the same constraint [`new_with`](Self::new_with) documents, with the same
490 /// **E0282** if nothing names it. A return type alone does not resolve it. Name
491 /// the type in either position:
492 ///
493 /// ```rust
494 /// use secure_gate::Fixed;
495 /// # #[derive(Debug)] struct ShortRead;
496 ///
497 /// // On the type:
498 /// let a = Fixed::<[u8; 32]>::try_new_with(|x| { x.fill(1); Ok::<(), ShortRead>(()) })?;
499 /// // Or on the closure parameter:
500 /// let b = Fixed::try_new_with(|x: &mut [u8; 32]| { x.fill(1); Ok::<(), ShortRead>(()) })?;
501 /// # let _ = (a, b);
502 /// # Ok::<(), ShortRead>(())
503 /// ```
504 ///
505 /// # Errors
506 ///
507 /// Returns whatever the closure returns. The error type is the caller's; this
508 /// method neither inspects nor wraps it.
509 ///
510 /// # Examples
511 ///
512 /// Filling from a reader, which is the case this exists for — the bytes land in
513 /// the wrapper's own storage and never occupy a caller-owned buffer:
514 ///
515 /// ```rust
516 /// # #[cfg(feature = "std")] {
517 /// use secure_gate::{Fixed, RevealSecret};
518 /// use std::io::Read;
519 ///
520 /// fn read_key<R: Read>(r: &mut R) -> std::io::Result<Fixed<[u8; 32]>> {
521 /// Fixed::<[u8; 32]>::try_new_with(|slot| r.read_exact(slot))
522 /// }
523 ///
524 /// let key = read_key(&mut [7u8; 32].as_slice()).unwrap();
525 /// assert_eq!(key.expose_secret(), &[7u8; 32]);
526 ///
527 /// // A short read fails, and yields no secret at all.
528 /// assert!(read_key(&mut [7u8; 8].as_slice()).is_err());
529 /// # }
530 /// ```
531 ///
532 /// # See also
533 ///
534 /// - [`new_with`](Self::new_with) — the infallible form; prefer it when the fill
535 /// cannot fail.
536 #[inline(always)]
537 pub fn try_new_with<F, E>(f: F) -> Result<Self, E>
538 where
539 T: crate::FixedStorage + crate::SentinelValue,
540 F: FnOnce(&mut T) -> Result<(), E>,
541 {
542 // Binding the unit-valued const is what forces it to be evaluated; clippy reads
543 // that as a pointless binding. Kept explicit because the 1.70 lint (the 0.8
544 // line's MSRV) fires on every spelling that still triggers the evaluation.
545 #[allow(clippy::let_unit_value)]
546 let () = Self::NON_ZERO_SIZED;
547 let mut this = Self {
548 inner: <T as crate::SentinelValue>::sentinel_value(),
549 };
550 // On the error path `this` is dropped here, so `Fixed::drop` zeroizes whatever
551 // the closure wrote before it gave up. That is the whole reason the wrapper is
552 // built before the fill rather than after it.
553 f(&mut this.inner)?;
554 Ok(this)
555 }
556}
557
558/// Converts a byte array into a [`Fixed`] wrapper (equivalent to [`Fixed::new`]).
559///
560/// # Examples
561///
562/// ```rust
563/// use secure_gate::Fixed;
564///
565/// let secret: Fixed<[u8; 4]> = [1u8, 2, 3, 4].into();
566/// ```
567impl<const N: usize> From<[u8; N]> for Fixed<[u8; N]> {
568 #[inline(always)]
569 fn from(arr: [u8; N]) -> Self {
570 Self::new(arr)
571 }
572}
573
574/// Converts a byte slice into `Fixed<[u8; N]>`, failing if the length does not
575/// match `N`.
576///
577/// Internally uses [`Fixed::new_with`] so the secret is written directly into
578/// the wrapper's storage.
579///
580/// # Errors
581///
582/// Returns [`FromSliceError::InvalidLength`](crate::error::FromSliceError) when
583/// `slice.len() != N`.
584///
585/// # Examples
586///
587/// ```rust
588/// use secure_gate::{Fixed, RevealSecret};
589///
590/// // Success — exact length.
591/// let data = [0xFFu8; 4];
592/// let secret = Fixed::<[u8; 4]>::try_from(data.as_slice()).unwrap();
593/// assert_eq!(secret.expose_secret()[0], 0xFF);
594///
595/// // Failure — wrong length.
596/// let short = [0u8; 2];
597/// assert!(Fixed::<[u8; 4]>::try_from(short.as_slice()).is_err());
598/// ```
599impl<const N: usize> core::convert::TryFrom<&[u8]> for Fixed<[u8; N]> {
600 type Error = crate::error::FromSliceError;
601
602 fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
603 if slice.len() != N {
604 return Err(crate::error::FromSliceError::InvalidLength {
605 expected: N,
606 got: slice.len(),
607 });
608 }
609 Ok(Self::new_with(|arr| arr.copy_from_slice(slice)))
610 }
611}
612
613/// Hex encoding and decoding for `Fixed<[u8; N]>`.
614///
615/// Encoding uses a constant-time backend (`base16ct`). Decoding works with or without
616/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
617/// `Zeroizing<[u8; N]>` stack buffer.
618#[cfg(feature = "encoding-hex")]
619impl<const N: usize> Fixed<[u8; N]> {
620 /// Decodes a hex string (lowercase, uppercase, or mixed) into `Fixed<[u8; N]>`.
621 ///
622 /// Uses a constant-time backend (`base16ct`) for both paths.
623 ///
624 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
625 /// The temporary heap buffer is zeroed on drop even if an error occurs.
626 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
627 /// No heap allocation occurs.
628 ///
629 /// # Errors
630 ///
631 /// - [`HexError::InvalidHex`](crate::HexError::InvalidHex) — non-hex characters or odd-length input.
632 /// - [`HexError::InvalidLength`](crate::HexError::InvalidLength) — decoded byte count does not equal `N`.
633 ///
634 /// # Examples
635 ///
636 /// ```rust
637 /// # #[cfg(feature = "encoding-hex")]
638 /// # {
639 /// use secure_gate::{Fixed, RevealSecret, ToHex};
640 ///
641 /// // Round-trip: encode then decode.
642 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
643 /// # #[cfg(feature = "alloc")]
644 /// # {
645 /// let hex_str = original.to_hex();
646 /// let decoded = Fixed::<[u8; 4]>::try_from_hex(&hex_str).unwrap();
647 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
648 /// # }
649 ///
650 /// // Wrong length fails.
651 /// assert!(Fixed::<[u8; 2]>::try_from_hex("deadbeef").is_err());
652 /// # }
653 /// ```
654 pub fn try_from_hex(hex: &str) -> Result<Self, crate::error::HexError> {
655 #[cfg(feature = "alloc")]
656 {
657 use zeroize::Zeroizing;
658 let bytes = Zeroizing::new(
659 base16ct::mixed::decode_vec(hex.as_bytes())
660 .map_err(|_| crate::error::HexError::InvalidHex)?,
661 );
662 if bytes.len() != N {
663 return Err(crate::error::HexError::InvalidLength {
664 expected: N,
665 got: bytes.len(),
666 });
667 }
668 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
669 }
670 #[cfg(not(feature = "alloc"))]
671 {
672 use zeroize::Zeroizing;
673 // no-alloc path: decode directly into a stack buffer; no heap allocation
674 // base16ct::mixed accepts upper, lower, and mixed-case hex
675 let mut buf = Zeroizing::new([0u8; N]);
676 let decoded = base16ct::mixed::decode(hex.as_bytes(), &mut *buf)
677 .map_err(|_| crate::error::HexError::InvalidHex)?;
678 if decoded.len() != N {
679 return Err(crate::error::HexError::InvalidLength {
680 expected: N,
681 got: decoded.len(),
682 });
683 }
684 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
685 // buf is zeroized on drop (both success and error paths)
686 }
687 }
688}
689
690/// Base32 encoding and decoding for `Fixed<[u8; N]>` (RFC 4648 §6, uppercase, unpadded).
691///
692/// Encoding uses a constant-time backend (`base32ct`). Decoding works with or without
693/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
694/// `Zeroizing<[u8; N]>` stack buffer.
695#[cfg(feature = "encoding-base32")]
696impl<const N: usize> Fixed<[u8; N]> {
697 /// Decodes an uppercase, unpadded Base32 string (RFC 4648 §6 alphabet) into
698 /// `Fixed<[u8; N]>`.
699 ///
700 /// Uses a constant-time backend (`base32ct`) on both paths.
701 ///
702 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
703 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
704 ///
705 /// Decoding is strict about the alphabet, case, padding and length, but lenient
706 /// about non-canonical trailing bits: unused bits in the final group are ignored
707 /// rather than rejected, so `"MZ"` and `"MY"` both decode to `[0x66]`. Decoding is
708 /// therefore not injective — two distinct strings can yield the same bytes, and
709 /// only encoder-produced strings are canonical. Do not use the decoded value to
710 /// decide that two encoded strings were equal.
711 ///
712 /// # Errors
713 ///
714 /// - [`Base32Error::InvalidBase32`](crate::Base32Error::InvalidBase32) — wrong alphabet
715 /// or case, `=` padding, or a length that is impossible for unpadded Base32. Without
716 /// `alloc` an input that decodes to *more* than `N` bytes also lands here rather than in
717 /// `InvalidLength`, because the fixed stack buffer cannot hold the overflow to measure it.
718 /// - [`Base32Error::InvalidLength`](crate::Base32Error::InvalidLength) — decoded byte
719 /// count does not equal `N`.
720 ///
721 /// # Examples
722 ///
723 /// ```rust
724 /// # #[cfg(feature = "encoding-base32")]
725 /// # {
726 /// use secure_gate::{Fixed, RevealSecret, ToBase32};
727 ///
728 /// # #[cfg(feature = "alloc")]
729 /// # {
730 /// // Round-trip.
731 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
732 /// let encoded = original.to_base32();
733 /// assert_eq!(&*encoded, "32W353Y");
734 /// let decoded = Fixed::<[u8; 4]>::try_from_base32(&encoded).unwrap();
735 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
736 /// # }
737 /// # }
738 /// ```
739 pub fn try_from_base32(s: &str) -> Result<Self, crate::error::Base32Error> {
740 #[cfg(feature = "alloc")]
741 {
742 use base32ct::{Base32UpperUnpadded, Encoding};
743 use zeroize::Zeroizing;
744 let bytes = Zeroizing::new(
745 Base32UpperUnpadded::decode_vec(s)
746 .map_err(|_| crate::error::Base32Error::InvalidBase32)?,
747 );
748 if bytes.len() != N {
749 return Err(crate::error::Base32Error::InvalidLength {
750 expected: N,
751 got: bytes.len(),
752 });
753 }
754 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
755 }
756 #[cfg(not(feature = "alloc"))]
757 {
758 use base32ct::{Base32UpperUnpadded, Encoding};
759 use zeroize::Zeroizing;
760 let mut buf = Zeroizing::new([0u8; N]);
761 let decoded = Base32UpperUnpadded::decode(s, &mut *buf)
762 .map_err(|_| crate::error::Base32Error::InvalidBase32)?;
763 if decoded.len() != N {
764 return Err(crate::error::Base32Error::InvalidLength {
765 expected: N,
766 got: decoded.len(),
767 });
768 }
769 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
770 // buf is zeroized on drop (both success and error paths)
771 }
772 }
773}
774
775/// Base64url encoding and decoding for `Fixed<[u8; N]>`.
776///
777/// Encoding uses a constant-time backend (`base64ct`). Decoding works with or without
778/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
779/// `Zeroizing<[u8; N]>` stack buffer.
780#[cfg(feature = "encoding-base64")]
781impl<const N: usize> Fixed<[u8; N]> {
782 /// Decodes an unpadded Base64url string (RFC 4648, URL-safe alphabet) into
783 /// `Fixed<[u8; N]>`.
784 ///
785 /// Uses a constant-time backend (`base64ct`) on both paths.
786 ///
787 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
788 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
789 ///
790 /// # Errors
791 ///
792 /// - [`Base64Error::InvalidBase64`](crate::Base64Error::InvalidBase64) — non-base64 characters or invalid padding.
793 /// - [`Base64Error::InvalidLength`](crate::Base64Error::InvalidLength) — decoded byte count does not equal `N`.
794 ///
795 /// # Examples
796 ///
797 /// ```rust
798 /// # #[cfg(feature = "encoding-base64")]
799 /// # {
800 /// use secure_gate::{Fixed, RevealSecret, ToBase64Url};
801 ///
802 /// # #[cfg(feature = "alloc")]
803 /// # {
804 /// // Round-trip.
805 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
806 /// let encoded = original.to_base64url();
807 /// let decoded = Fixed::<[u8; 4]>::try_from_base64url(&encoded).unwrap();
808 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
809 /// # }
810 /// # }
811 /// ```
812 pub fn try_from_base64url(s: &str) -> Result<Self, crate::error::Base64Error> {
813 #[cfg(feature = "alloc")]
814 {
815 use base64ct::{Base64UrlUnpadded, Encoding};
816 use zeroize::Zeroizing;
817 let bytes = Zeroizing::new(
818 Base64UrlUnpadded::decode_vec(s)
819 .map_err(|_| crate::error::Base64Error::InvalidBase64)?,
820 );
821 if bytes.len() != N {
822 return Err(crate::error::Base64Error::InvalidLength {
823 expected: N,
824 got: bytes.len(),
825 });
826 }
827 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
828 }
829 #[cfg(not(feature = "alloc"))]
830 {
831 use base64ct::{Base64UrlUnpadded, Encoding};
832 use zeroize::Zeroizing;
833 let mut buf = Zeroizing::new([0u8; N]);
834 let decoded = Base64UrlUnpadded::decode(s, &mut *buf)
835 .map_err(|_| crate::error::Base64Error::InvalidBase64)?;
836 if decoded.len() != N {
837 return Err(crate::error::Base64Error::InvalidLength {
838 expected: N,
839 got: decoded.len(),
840 });
841 }
842 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
843 // buf is zeroized on drop (both success and error paths)
844 }
845 }
846}
847
848/// Bech32 (BIP-173) encoding and decoding for `Fixed<[u8; N]>`.
849///
850/// The plain constructors accept strings up to
851/// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH); the `_sized::<C>` constructors
852/// take the code length as a parameter for larger payloads. For Bitcoin address formats
853/// use `ToBech32m` and stay within BIP-173's 90-character convention.
854#[cfg(feature = "encoding-bech32")]
855impl<const N: usize> Fixed<[u8; N]> {
856 /// Decodes a Bech32 (BIP-173) string into `Fixed<[u8; N]>`, validating that the HRP
857 /// matches `expected_hrp` (case-insensitive).
858 ///
859 /// HRP comparison is non-constant-time — this is intentional, as the HRP is public
860 /// metadata, not secret material. Timing leaks on HRP mismatch are acceptable because
861 /// the HRP is not secret. Prefer this over
862 /// [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked) to prevent
863 /// cross-protocol confusion attacks.
864 ///
865 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
866 pub fn try_from_bech32(s: &str, expected_hrp: &str) -> Result<Self, crate::error::Bech32Error> {
867 Self::try_from_bech32_sized::<{ crate::BECH32_CODE_LENGTH }>(s, expected_hrp)
868 }
869
870 /// Like [`try_from_bech32`](Self::try_from_bech32), accepting strings up to `C`
871 /// characters.
872 ///
873 /// `C` is the bech32 *code length* -- the cap on the whole encoded string -- and is
874 /// independent of `N`, the decoded byte count this wrapper holds. Pass the `C` the
875 /// string was encoded with, or any larger value. See
876 /// [`Bech32Sized`](crate::Bech32Sized) for what `C` above
877 /// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH) costs.
878 ///
879 /// Works without `alloc` -- decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
880 pub fn try_from_bech32_sized<const C: usize>(
881 s: &str,
882 expected_hrp: &str,
883 ) -> Result<Self, crate::error::Bech32Error> {
884 use crate::traits::encoding::bech32::Bech32Sized;
885 use bech32::primitives::decode::CheckedHrpstring;
886 let checked = CheckedHrpstring::new::<Bech32Sized<C>>(s)
887 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
888 // HRP check before any payload byte is materialized (case-insensitive
889 // comparison — timing leak is acceptable since HRP is public metadata)
890 if !checked.hrp().as_str().eq_ignore_ascii_case(expected_hrp) {
891 return Err(crate::error::Bech32Error::UnexpectedHrp);
892 }
893 let buf = drain_bech32_payload::<N>(&checked)?;
894 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
895 // buf is zeroized on drop
896 }
897
898 /// Decodes a Bech32 (BIP-173) string into `Fixed<[u8; N]>` without validating the HRP.
899 ///
900 /// Any valid HRP is accepted as long as the checksum is valid and the payload length
901 /// equals `N`. Use [`try_from_bech32`](Self::try_from_bech32) in security-critical code
902 /// to prevent cross-protocol confusion attacks.
903 ///
904 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
905 pub fn try_from_bech32_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
906 Self::try_from_bech32_unchecked_sized::<{ crate::BECH32_CODE_LENGTH }>(s)
907 }
908
909 /// Like [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked), accepting
910 /// strings up to `C` characters.
911 pub fn try_from_bech32_unchecked_sized<const C: usize>(
912 s: &str,
913 ) -> Result<Self, crate::error::Bech32Error> {
914 use crate::traits::encoding::bech32::Bech32Sized;
915 use bech32::primitives::decode::CheckedHrpstring;
916 let checked = CheckedHrpstring::new::<Bech32Sized<C>>(s)
917 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
918 let buf = drain_bech32_payload::<N>(&checked)?;
919 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
920 // buf is zeroized on drop
921 }
922}
923
924/// Bech32m (BIP-350) encoding and decoding for `Fixed<[u8; N]>`.
925///
926/// The plain constructors accept strings up to
927/// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH); the `_sized::<C>` constructors
928/// take the code length as a parameter. Bitcoin address tooling expects BIP-173's
929/// 90-character cap, which is narrower than either and is the caller's to respect.
930#[cfg(feature = "encoding-bech32")]
931impl<const N: usize> Fixed<[u8; N]> {
932 /// Decodes a Bech32m (BIP-350) string into `Fixed<[u8; N]>`, validating that the HRP
933 /// matches `expected_hrp` (case-insensitive).
934 ///
935 /// HRP comparison is non-constant-time — this is intentional, as the HRP is public
936 /// metadata, not secret material. Timing leaks on HRP mismatch are acceptable because
937 /// the HRP is not secret. Prefer this over
938 /// [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked) to prevent
939 /// cross-protocol confusion attacks.
940 ///
941 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
942 pub fn try_from_bech32m(
943 s: &str,
944 expected_hrp: &str,
945 ) -> Result<Self, crate::error::Bech32Error> {
946 Self::try_from_bech32m_sized::<{ crate::BECH32_CODE_LENGTH }>(s, expected_hrp)
947 }
948
949 /// Like [`try_from_bech32m`](Self::try_from_bech32m), accepting strings up to `C`
950 /// characters.
951 ///
952 /// `C` is the bech32m *code length*, independent of `N`, the decoded byte count.
953 /// See [`Bech32mSized`](crate::Bech32mSized) for what `C` above
954 /// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH) costs.
955 ///
956 /// Works without `alloc` -- decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
957 pub fn try_from_bech32m_sized<const C: usize>(
958 s: &str,
959 expected_hrp: &str,
960 ) -> Result<Self, crate::error::Bech32Error> {
961 use crate::traits::encoding::bech32m::Bech32mSized;
962 use bech32::primitives::decode::CheckedHrpstring;
963 let checked = CheckedHrpstring::new::<Bech32mSized<C>>(s)
964 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
965 // HRP check before any payload byte is materialized (case-insensitive
966 // comparison — timing leak is acceptable since HRP is public metadata)
967 if !checked.hrp().as_str().eq_ignore_ascii_case(expected_hrp) {
968 return Err(crate::error::Bech32Error::UnexpectedHrp);
969 }
970 let buf = drain_bech32_payload::<N>(&checked)?;
971 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
972 // buf is zeroized on drop
973 }
974
975 /// Decodes a Bech32m (BIP-350) string into `Fixed<[u8; N]>` without validating the HRP.
976 ///
977 /// Any valid HRP is accepted as long as the checksum is valid and the payload length
978 /// equals `N`. Use [`try_from_bech32m`](Self::try_from_bech32m) in security-critical
979 /// code to prevent cross-protocol confusion attacks.
980 ///
981 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
982 pub fn try_from_bech32m_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
983 Self::try_from_bech32m_unchecked_sized::<{ crate::BECH32_CODE_LENGTH }>(s)
984 }
985
986 /// Like [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked), accepting
987 /// strings up to `C` characters.
988 pub fn try_from_bech32m_unchecked_sized<const C: usize>(
989 s: &str,
990 ) -> Result<Self, crate::error::Bech32Error> {
991 use crate::traits::encoding::bech32m::Bech32mSized;
992 use bech32::primitives::decode::CheckedHrpstring;
993 let checked = CheckedHrpstring::new::<Bech32mSized<C>>(s)
994 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
995 let buf = drain_bech32_payload::<N>(&checked)?;
996 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
997 // buf is zeroized on drop
998 }
999}
1000
1001/// Hex encoding for `Fixed<[u8; N]>` — same constant-time backend as the
1002/// [`ToHex`] blanket impl on the inner bytes; delegates via `with_secret`.
1003///
1004/// Bring the trait into scope to call these: `use secure_gate::ToHex;`.
1005///
1006/// ```rust
1007/// use secure_gate::{Fixed, ToHex};
1008///
1009/// let key = Fixed::new([0xABu8; 4]);
1010/// assert_eq!(&*key.to_hex(), "abababab");
1011/// assert_eq!(&*key.to_hex_upper(), "ABABABAB");
1012/// // Both return an `EncodedSecret` — the encoded form wipes itself on drop.
1013/// ```
1014#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
1015impl<const N: usize> ToHex for Fixed<[u8; N]> {
1016 #[inline]
1017 fn to_hex(&self) -> crate::EncodedSecret {
1018 self.with_secret(|s| s.to_hex())
1019 }
1020
1021 #[inline]
1022 fn to_hex_upper(&self) -> crate::EncodedSecret {
1023 self.with_secret(|s| s.to_hex_upper())
1024 }
1025}
1026
1027/// Base32 encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1028///
1029/// Bring the trait into scope to call these: `use secure_gate::ToBase32;`.
1030///
1031/// ```rust
1032/// use secure_gate::{Fixed, ToBase32};
1033///
1034/// let key = Fixed::new([0xABu8; 4]);
1035/// assert_eq!(&*key.to_base32(), "VOV2XKY");
1036/// ```
1037#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
1038impl<const N: usize> ToBase32 for Fixed<[u8; N]> {
1039 #[inline]
1040 fn to_base32(&self) -> crate::EncodedSecret {
1041 self.with_secret(|s| s.to_base32())
1042 }
1043}
1044
1045/// Base64url encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1046///
1047/// Bring the trait into scope to call these: `use secure_gate::ToBase64Url;`.
1048///
1049/// ```rust
1050/// use secure_gate::{Fixed, ToBase64Url};
1051///
1052/// let key = Fixed::new([0xABu8; 4]);
1053/// assert_eq!(&*key.to_base64url(), "q6urqw");
1054/// ```
1055#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
1056impl<const N: usize> ToBase64Url for Fixed<[u8; N]> {
1057 #[inline]
1058 fn to_base64url(&self) -> crate::EncodedSecret {
1059 self.with_secret(|s| s.to_base64url())
1060 }
1061}
1062
1063/// Bech32 encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1064///
1065/// Bring the trait into scope to call these: `use secure_gate::ToBech32;`.
1066#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
1067impl<const N: usize> ToBech32 for Fixed<[u8; N]> {
1068 #[inline]
1069 fn try_to_bech32(
1070 &self,
1071 hrp: &str,
1072 case: crate::Case,
1073 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1074 self.with_secret(|s| s.try_to_bech32(hrp, case))
1075 }
1076
1077 #[inline]
1078 fn try_to_bech32_sized<const C: usize>(
1079 &self,
1080 hrp: &str,
1081 case: crate::Case,
1082 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1083 self.with_secret(|s| s.try_to_bech32_sized::<C>(hrp, case))
1084 }
1085}
1086
1087/// Bech32m encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1088///
1089/// Bring the trait into scope to call these: `use secure_gate::ToBech32m;`.
1090#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
1091impl<const N: usize> ToBech32m for Fixed<[u8; N]> {
1092 #[inline]
1093 fn try_to_bech32m(
1094 &self,
1095 hrp: &str,
1096 case: crate::Case,
1097 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1098 self.with_secret(|s| s.try_to_bech32m(hrp, case))
1099 }
1100
1101 #[inline]
1102 fn try_to_bech32m_sized<const C: usize>(
1103 &self,
1104 hrp: &str,
1105 case: crate::Case,
1106 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1107 self.with_secret(|s| s.try_to_bech32m_sized::<C>(hrp, case))
1108 }
1109}
1110
1111/// Explicit access to immutable [`Fixed<[T; N]>`] contents.
1112impl<T: zeroize::Zeroize> RevealSecret for Fixed<T> {
1113 type Inner = T;
1114
1115 #[inline(always)]
1116 fn with_secret<F, R>(&self, f: F) -> R
1117 where
1118 F: FnOnce(&T) -> R,
1119 {
1120 f(&self.inner)
1121 }
1122
1123 #[inline(always)]
1124 fn expose_secret(&self) -> &T {
1125 &self.inner
1126 }
1127
1128 /// Consumes `self` and transfers ownership of the plain `[T; N]`.
1129 ///
1130 /// Zero cost — no allocation. The sentinel placed in `self.inner` is
1131 /// `[T::default(); N]` via [`crate::SentinelValue`] (already zeroed for `u8`),
1132 /// so `Fixed::drop` zeroizes an already-zero array — a harmless no-op.
1133 /// Works for **any** array length `N` (not limited to 32 like `Default`).
1134 ///
1135 /// See [`RevealSecret::into_inner`] for the full contract, including the
1136 /// `SentinelValue` bound rationale. Protection ends at this call: the array you
1137 /// get back is plain — not wiped on drop, and its `Debug` is not redacted.
1138 #[inline(always)]
1139 fn into_inner(mut self) -> T
1140 where
1141 Self: Sized,
1142 Self::Inner: Sized + crate::SentinelValue + zeroize::Zeroize,
1143 {
1144 // Replace inner with the sentinel so Fixed::drop zeroizes a harmless
1145 // placeholder while the caller receives the real secret. The secret is stored
1146 // inline, so this transfers the bytes rather than handing over an allocation;
1147 // what the sentinel guarantees is that no second copy is left behind here.
1148 core::mem::replace(&mut self.inner, crate::SentinelValue::sentinel_value())
1149 }
1150}
1151
1152/// Length is only meaningful for array-shaped secrets.
1153impl<const N: usize, T: zeroize::Zeroize> crate::SecretLen for Fixed<[T; N]> {
1154 #[inline(always)]
1155 fn len(&self) -> usize {
1156 N
1157 }
1158
1159 #[inline(always)]
1160 fn byte_len(&self) -> usize {
1161 N * core::mem::size_of::<T>()
1162 }
1163}
1164
1165/// Explicit access to mutable [`Fixed<[T; N]>`] contents.
1166impl<T: zeroize::Zeroize> RevealSecretMut for Fixed<T> {
1167 #[inline(always)]
1168 fn with_secret_mut<F, R>(&mut self, f: F) -> R
1169 where
1170 F: FnOnce(&mut T) -> R,
1171 {
1172 f(&mut self.inner)
1173 }
1174
1175 #[inline(always)]
1176 fn expose_secret_mut(&mut self) -> &mut T {
1177 &mut self.inner
1178 }
1179}
1180
1181#[cfg(feature = "rand")]
1182impl<const N: usize> Fixed<[u8; N]> {
1183 /// Fills a new `[u8; N]` with cryptographically secure random bytes and wraps it.
1184 ///
1185 /// Uses the system RNG ([`SysRng`](rand::rngs::SysRng)). Requires the `rand` feature.
1186 /// Heap-free and works in `no_std` / `no_alloc` builds.
1187 ///
1188 /// # Panics
1189 ///
1190 /// Panics if the system RNG fails to provide bytes ([`TryRng::try_fill_bytes`](rand::TryRng::try_fill_bytes)
1191 /// returns `Err`). This is treated as a fatal environment error.
1192 ///
1193 /// # Examples
1194 ///
1195 /// ```rust
1196 /// # #[cfg(feature = "rand")]
1197 /// use secure_gate::{Fixed, RevealSecret, SecretLen};
1198 ///
1199 /// # #[cfg(feature = "rand")]
1200 /// # {
1201 /// let key: Fixed<[u8; 32]> = Fixed::from_random();
1202 /// assert_eq!(key.len(), 32);
1203 /// # }
1204 /// ```
1205 #[inline]
1206 pub fn from_random() -> Self {
1207 Self::new_with(|arr| {
1208 SysRng
1209 .try_fill_bytes(arr)
1210 .expect("SysRng failure is a program error");
1211 })
1212 }
1213
1214 /// Fills a new `[u8; N]` from `rng` and wraps it.
1215 ///
1216 /// Accepts any [`TryCryptoRng`](rand::TryCryptoRng) + [`TryRng`](rand::TryRng) — for example,
1217 /// a seeded `StdRng` for deterministic tests. Requires the `rand`
1218 /// feature. Heap-free.
1219 ///
1220 /// # Errors
1221 ///
1222 /// Returns `R::Error` if [`try_fill_bytes`](rand::TryRng::try_fill_bytes) fails.
1223 ///
1224 /// # Examples
1225 ///
1226 /// ```rust
1227 /// # #[cfg(feature = "rand")]
1228 /// # {
1229 /// use rand::rngs::StdRng;
1230 /// use rand::SeedableRng;
1231 /// use secure_gate::Fixed;
1232 ///
1233 /// let mut rng = StdRng::from_seed([1u8; 32]);
1234 /// let key: Fixed<[u8; 16]> = Fixed::from_rng(&mut rng).expect("rng fill");
1235 /// # }
1236 /// ```
1237 #[inline]
1238 pub fn from_rng<R: TryRng + TryCryptoRng>(rng: &mut R) -> Result<Self, R::Error> {
1239 // This body was the captured-local workaround `try_new_with` exists to retire:
1240 // `new_with` could not report failure, so the error was written to a local and
1241 // checked afterwards. Same behaviour, one expression.
1242 Self::try_new_with(|arr| rng.try_fill_bytes(arr))
1243 }
1244}
1245
1246/// Constant-time equality for `Fixed<T>` — routes through [`expose_secret()`](crate::RevealSecret::expose_secret).
1247///
1248/// `==` is **deliberately not implemented** on `Fixed`. Always use `ct_eq`.
1249///
1250/// ```rust
1251/// # #[cfg(feature = "ct-eq")]
1252/// # {
1253/// use secure_gate::{Fixed, ConstantTimeEq};
1254///
1255/// let a = Fixed::new([1u8; 4]);
1256/// let b = Fixed::new([1u8; 4]);
1257/// let c = Fixed::new([2u8; 4]);
1258/// assert!(a.ct_eq(&b));
1259/// assert!(!a.ct_eq(&c));
1260/// # }
1261/// ```
1262#[cfg(feature = "ct-eq")]
1263impl<T: zeroize::Zeroize> crate::ConstantTimeEq for Fixed<T>
1264where
1265 T: crate::ConstantTimeEq,
1266 Self: crate::RevealSecret<Inner = T>,
1267{
1268 fn ct_eq(&self, other: &Self) -> bool {
1269 self.expose_secret().ct_eq(other.expose_secret())
1270 }
1271}
1272
1273/// Always prints `[REDACTED]` — secrets never appear in debug output.
1274///
1275/// ```rust
1276/// use secure_gate::Fixed;
1277///
1278/// let key = Fixed::new([0xABu8; 32]);
1279/// assert_eq!(format!("{:?}", key), "[REDACTED]");
1280/// ```
1281impl<T: zeroize::Zeroize> core::fmt::Debug for Fixed<T> {
1282 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1283 f.write_str("[REDACTED]")
1284 }
1285}
1286
1287/// Opt-in cloning — requires `cloneable` feature and [`CloneableSecret`](crate::CloneableSecret)
1288/// marker on the inner type. Each clone is independently zeroized on drop, but cloning
1289/// increases the in-memory exposure surface. Use sparingly.
1290#[cfg(feature = "cloneable")]
1291impl<T: zeroize::Zeroize + crate::CloneableSecret + crate::FixedStorage> Clone for Fixed<T> {
1292 fn clone(&self) -> Self {
1293 Self::new(self.inner.clone())
1294 }
1295}
1296
1297/// Opt-in serialization — requires `serde-serialize` feature and
1298/// [`SerializableSecret`](crate::SerializableSecret) marker on the inner type.
1299/// Serialization exposes the full secret — audit every impl.
1300#[cfg(feature = "serde-serialize")]
1301impl<T: zeroize::Zeroize + crate::SerializableSecret> serde::Serialize for Fixed<T> {
1302 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1303 where
1304 S: serde::Serializer,
1305 {
1306 self.inner.serialize(serializer)
1307 }
1308}
1309
1310/// Deserialization uses `Zeroizing`-wrapped temporary buffers — zeroized even on rejection.
1311///
1312/// The sequence buffer is pre-allocated to exactly `N` bytes and **never grows**: an
1313/// input sequence longer than `N` is rejected before the element that would trigger a
1314/// reallocation is stored. This matters because a `Vec` reallocation frees the old
1315/// buffer — which would already hold `N` secret bytes — without zeroizing it.
1316///
1317/// The entry point is `deserialize_seq` (unchanged wire format for non-self-describing
1318/// formats such as postcard), but the visitor also accepts byte strings via
1319/// `visit_bytes` / `visit_byte_buf`, so self-describing formats that encode byte
1320/// arrays as byte strings (e.g. CBOR) round-trip too. Owned buffers handed over
1321/// through `visit_byte_buf` are zeroized after the copy.
1322#[cfg(feature = "serde-deserialize")]
1323impl<'de, const N: usize> serde::Deserialize<'de> for Fixed<[u8; N]> {
1324 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1325 where
1326 D: serde::Deserializer<'de>,
1327 {
1328 use core::fmt;
1329 use serde::de::Visitor;
1330 struct FixedVisitor<const M: usize>;
1331 impl<'de, const M: usize> Visitor<'de> for FixedVisitor<M> {
1332 type Value = Fixed<[u8; M]>;
1333 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1334 write!(formatter, "a byte array of length {}", M)
1335 }
1336 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1337 where
1338 A: serde::de::SeqAccess<'de>,
1339 {
1340 let mut vec: zeroize::Zeroizing<alloc::vec::Vec<u8>> =
1341 zeroize::Zeroizing::new(alloc::vec::Vec::with_capacity(M));
1342 while let Some(value) = seq.next_element()? {
1343 // Reject over-length input *before* pushing past the reserved
1344 // capacity: growing would realloc and free the old buffer
1345 // (already holding M secret bytes) without zeroization.
1346 if vec.len() == M {
1347 return Err(serde::de::Error::invalid_length(M + 1, &self));
1348 }
1349 vec.push(value);
1350 }
1351 if vec.len() != M {
1352 return Err(serde::de::Error::invalid_length(vec.len(), &self));
1353 }
1354 Ok(Fixed::<[u8; M]>::new_with(|arr| arr.copy_from_slice(&vec)))
1355 }
1356 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1357 where
1358 E: serde::de::Error,
1359 {
1360 if v.len() != M {
1361 return Err(serde::de::Error::invalid_length(v.len(), &self));
1362 }
1363 Ok(Fixed::<[u8; M]>::new_with(|arr| arr.copy_from_slice(v)))
1364 }
1365 fn visit_byte_buf<E>(self, v: alloc::vec::Vec<u8>) -> Result<Self::Value, E>
1366 where
1367 E: serde::de::Error,
1368 {
1369 // Take ownership under Zeroizing so the deserializer-provided
1370 // buffer is wiped after the copy — the default forwarding impl
1371 // would drop it unzeroized.
1372 let v = zeroize::Zeroizing::new(v);
1373 self.visit_bytes(&v)
1374 }
1375 }
1376 deserializer.deserialize_seq(FixedVisitor::<N>)
1377 }
1378}
1379
1380/// Zeroizes the inner value. Called automatically by [`Drop`].
1381///
1382/// **Warning:** zeroization does not run for `static` items or under `panic = "abort"`.
1383impl<T: zeroize::Zeroize> zeroize::Zeroize for Fixed<T> {
1384 fn zeroize(&mut self) {
1385 self.inner.zeroize();
1386 }
1387}
1388
1389/// Unconditionally zeroizes the inner value when the wrapper is dropped.
1390///
1391/// **Warning:** `Drop` does not run for `static` items or under `panic = "abort"`.
1392impl<T: zeroize::Zeroize> Drop for Fixed<T> {
1393 fn drop(&mut self) {
1394 self.zeroize();
1395 }
1396}
1397
1398/// Marker confirming that `Fixed<T>` always zeroizes on drop.
1399impl<T: zeroize::Zeroize> zeroize::ZeroizeOnDrop for Fixed<T> {}