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 (zeros for arrays). Prefer this over
343 /// [`new(value)`](Self::new) when minimizing stack residue matters
344 /// (long-lived keys, high-assurance environments).
345 ///
346 /// Requires [`FixedStorage`](crate::FixedStorage) and
347 /// [`SentinelValue`](crate::SentinelValue) on `T`. Arrays of a `Default`
348 /// element already have both; a custom inner type needs the same pair
349 /// `into_inner` already asks for.
350 ///
351 /// # `T` must be inferable at the call site
352 ///
353 /// This constructor is generic over `T`, so the closure's parameter type is
354 /// not known until `T` is. A return type alone does not resolve it in time:
355 /// `fn k() -> Fixed<[u8; 32]> { Fixed::new_with(|a| a.fill(1)) }` fails with
356 /// **E0282**, `type annotations needed for &mut _`, because the closure body
357 /// is checked before the expected return type reaches `T`. Name the type in
358 /// either position — both compile, pick whichever reads better:
359 ///
360 /// ```rust
361 /// use secure_gate::Fixed;
362 ///
363 /// // On the type:
364 /// let a = Fixed::<[u8; 32]>::new_with(|x| x.fill(1));
365 /// // Or on the closure parameter:
366 /// let b = Fixed::new_with(|x: &mut [u8; 32]| x.fill(1));
367 /// # let _ = (a, b);
368 /// ```
369 ///
370 /// Before 0.9.0-rc.10 this method was inherent to `Fixed<[u8; N]>`, where the
371 /// parameter was always a byte array and inference had nothing to resolve. A
372 /// newtype built by [`fixed_newtype!`](crate::fixed_newtype) is unaffected in
373 /// both arms: its generated `new_with` has a concrete parameter type.
374 ///
375 /// # Security rationale
376 ///
377 /// With [`Fixed::new(value)`](Self::new), the caller first builds `value` on
378 /// its own stack frame, then moves it into the wrapper. The compiler *may*
379 /// elide the copy, but this is not guaranteed — leaving a plaintext residue
380 /// on the stack. `new_with` avoids this by giving the closure a mutable
381 /// reference to the wrapper's *own* storage, so the secret is never placed
382 /// anywhere else.
383 ///
384 /// # Examples
385 ///
386 /// ```rust
387 /// use secure_gate::{Fixed, RevealSecret};
388 ///
389 /// // Fill from a closure — no intermediate stack copy.
390 /// let secret = Fixed::<[u8; 4]>::new_with(|arr| arr.fill(0xAB));
391 /// assert_eq!(secret.expose_secret(), &[0xAB; 4]);
392 ///
393 /// // Copy from an existing slice.
394 /// let src = [1u8, 2, 3, 4];
395 /// let secret = Fixed::<[u8; 4]>::new_with(|arr| arr.copy_from_slice(&src));
396 /// ```
397 ///
398 /// A non-byte array uses the same constructor:
399 ///
400 /// ```rust
401 /// use secure_gate::{Fixed, RevealSecret};
402 ///
403 /// let poly = Fixed::<[i16; 4]>::new_with(|c| c.fill(7));
404 /// assert_eq!(poly.expose_secret(), &[7i16; 4]);
405 /// ```
406 ///
407 /// # See also
408 ///
409 /// - [`try_new_with`](Self::try_new_with) — the same thing when the fill can
410 /// fail, rather than routing the error out through a captured local.
411 /// - [`Dynamic::new_with`](crate::Dynamic::new_with) — the heap-allocated
412 /// equivalent (requires `alloc`).
413 ///
414 /// If the secret will outlive the current function, prefer
415 /// [`Dynamic<T>`](crate::Dynamic) over moving `Fixed<T>` around — each
416 /// move-by-value leaves residue in the previous stack slot.
417 #[inline(always)]
418 pub fn new_with<F>(f: F) -> Self
419 where
420 T: crate::FixedStorage + crate::SentinelValue,
421 F: FnOnce(&mut T),
422 {
423 // Binding the unit-valued const is what forces it to be evaluated; clippy reads
424 // that as a pointless binding. Kept explicit because the 1.70 lint (the 0.8
425 // line's MSRV) fires on every spelling that still triggers the evaluation.
426 #[allow(clippy::let_unit_value)]
427 let () = Self::NON_ZERO_SIZED;
428 let mut this = Self {
429 inner: <T as crate::SentinelValue>::sentinel_value(),
430 };
431 f(&mut this.inner);
432 this
433 }
434
435 /// Writes directly into the wrapper's storage via a closure that may fail.
436 ///
437 /// The fallible sibling of [`new_with`](Self::new_with), and identical to it in
438 /// every respect but the closure's return type. Reach for it whenever filling the
439 /// secret can fail — reading from a file, a socket, a device — so that writing in
440 /// place and handling the error stay one expression.
441 ///
442 /// On `Err` the partially written slot is **zeroized before the error is
443 /// returned**: the wrapper exists for the whole of the closure's run, so
444 /// [`Drop`](Fixed#impl-Drop-for-Fixed<T>) wipes whatever the closure managed to
445 /// write. A failed fill leaves nothing behind, in memory or in the return value.
446 ///
447 /// Requires [`FixedStorage`](crate::FixedStorage) and
448 /// [`SentinelValue`](crate::SentinelValue) on `T`, exactly as `new_with` does.
449 ///
450 /// # Why `try_`, given the rest of this type
451 ///
452 /// Elsewhere here `try_` marks a constructor that *parses* untrusted input —
453 /// [`try_from_hex`](Self::try_from_hex), [`try_from_base32`](Self::try_from_base32),
454 /// `TryFrom<&[u8]>` — while [`from_rng`](Self::from_rng) is fallible and keeps
455 /// `from_`. This method widens the prefix to its ordinary Rust meaning, the one
456 /// `try_reserve` and `try_lock` carry: **`try_` marks a constructor that can fail**,
457 /// whether because it validates input or because the caller's fill can.
458 ///
459 /// # `T` must be inferable at the call site
460 ///
461 /// Generic over `T`, so the closure's parameter type is not known until `T` is —
462 /// the same constraint [`new_with`](Self::new_with) documents, with the same
463 /// **E0282** if nothing names it. A return type alone does not resolve it. Name
464 /// the type in either position:
465 ///
466 /// ```rust
467 /// use secure_gate::Fixed;
468 /// # #[derive(Debug)] struct ShortRead;
469 ///
470 /// // On the type:
471 /// let a = Fixed::<[u8; 32]>::try_new_with(|x| { x.fill(1); Ok::<(), ShortRead>(()) })?;
472 /// // Or on the closure parameter:
473 /// let b = Fixed::try_new_with(|x: &mut [u8; 32]| { x.fill(1); Ok::<(), ShortRead>(()) })?;
474 /// # let _ = (a, b);
475 /// # Ok::<(), ShortRead>(())
476 /// ```
477 ///
478 /// # Errors
479 ///
480 /// Returns whatever the closure returns. The error type is the caller's; this
481 /// method neither inspects nor wraps it.
482 ///
483 /// # Examples
484 ///
485 /// Filling from a reader, which is the case this exists for — the bytes land in
486 /// the wrapper's own storage and never occupy a caller-owned buffer:
487 ///
488 /// ```rust
489 /// # #[cfg(feature = "std")] {
490 /// use secure_gate::{Fixed, RevealSecret};
491 /// use std::io::Read;
492 ///
493 /// fn read_key<R: Read>(r: &mut R) -> std::io::Result<Fixed<[u8; 32]>> {
494 /// Fixed::<[u8; 32]>::try_new_with(|slot| r.read_exact(slot))
495 /// }
496 ///
497 /// let key = read_key(&mut [7u8; 32].as_slice()).unwrap();
498 /// assert_eq!(key.expose_secret(), &[7u8; 32]);
499 ///
500 /// // A short read fails, and yields no secret at all.
501 /// assert!(read_key(&mut [7u8; 8].as_slice()).is_err());
502 /// # }
503 /// ```
504 ///
505 /// # See also
506 ///
507 /// - [`new_with`](Self::new_with) — the infallible form; prefer it when the fill
508 /// cannot fail.
509 #[inline(always)]
510 pub fn try_new_with<F, E>(f: F) -> Result<Self, E>
511 where
512 T: crate::FixedStorage + crate::SentinelValue,
513 F: FnOnce(&mut T) -> Result<(), E>,
514 {
515 // Binding the unit-valued const is what forces it to be evaluated; clippy reads
516 // that as a pointless binding. Kept explicit because the 1.70 lint (the 0.8
517 // line's MSRV) fires on every spelling that still triggers the evaluation.
518 #[allow(clippy::let_unit_value)]
519 let () = Self::NON_ZERO_SIZED;
520 let mut this = Self {
521 inner: <T as crate::SentinelValue>::sentinel_value(),
522 };
523 // On the error path `this` is dropped here, so `Fixed::drop` zeroizes whatever
524 // the closure wrote before it gave up. That is the whole reason the wrapper is
525 // built before the fill rather than after it.
526 f(&mut this.inner)?;
527 Ok(this)
528 }
529}
530
531/// Converts a byte array into a [`Fixed`] wrapper (equivalent to [`Fixed::new`]).
532///
533/// # Examples
534///
535/// ```rust
536/// use secure_gate::Fixed;
537///
538/// let secret: Fixed<[u8; 4]> = [1u8, 2, 3, 4].into();
539/// ```
540impl<const N: usize> From<[u8; N]> for Fixed<[u8; N]> {
541 #[inline(always)]
542 fn from(arr: [u8; N]) -> Self {
543 Self::new(arr)
544 }
545}
546
547/// Converts a byte slice into `Fixed<[u8; N]>`, failing if the length does not
548/// match `N`.
549///
550/// Internally uses [`Fixed::new_with`] so the secret is written directly into
551/// the wrapper's storage.
552///
553/// # Errors
554///
555/// Returns [`FromSliceError::InvalidLength`](crate::error::FromSliceError) when
556/// `slice.len() != N`.
557///
558/// # Examples
559///
560/// ```rust
561/// use secure_gate::{Fixed, RevealSecret};
562///
563/// // Success — exact length.
564/// let data = [0xFFu8; 4];
565/// let secret = Fixed::<[u8; 4]>::try_from(data.as_slice()).unwrap();
566/// assert_eq!(secret.expose_secret()[0], 0xFF);
567///
568/// // Failure — wrong length.
569/// let short = [0u8; 2];
570/// assert!(Fixed::<[u8; 4]>::try_from(short.as_slice()).is_err());
571/// ```
572impl<const N: usize> core::convert::TryFrom<&[u8]> for Fixed<[u8; N]> {
573 type Error = crate::error::FromSliceError;
574
575 fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
576 if slice.len() != N {
577 return Err(crate::error::FromSliceError::InvalidLength {
578 expected: N,
579 got: slice.len(),
580 });
581 }
582 Ok(Self::new_with(|arr| arr.copy_from_slice(slice)))
583 }
584}
585
586/// Hex encoding and decoding for `Fixed<[u8; N]>`.
587///
588/// Encoding uses a constant-time backend (`base16ct`). Decoding works with or without
589/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
590/// `Zeroizing<[u8; N]>` stack buffer.
591#[cfg(feature = "encoding-hex")]
592impl<const N: usize> Fixed<[u8; N]> {
593 /// Decodes a hex string (lowercase, uppercase, or mixed) into `Fixed<[u8; N]>`.
594 ///
595 /// Uses a constant-time backend (`base16ct`) for both paths.
596 ///
597 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
598 /// The temporary heap buffer is zeroed on drop even if an error occurs.
599 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
600 /// No heap allocation occurs.
601 ///
602 /// # Errors
603 ///
604 /// - [`HexError::InvalidHex`](crate::HexError::InvalidHex) — non-hex characters or odd-length input.
605 /// - [`HexError::InvalidLength`](crate::HexError::InvalidLength) — decoded byte count does not equal `N`.
606 ///
607 /// # Examples
608 ///
609 /// ```rust
610 /// # #[cfg(feature = "encoding-hex")]
611 /// # {
612 /// use secure_gate::{Fixed, RevealSecret, ToHex};
613 ///
614 /// // Round-trip: encode then decode.
615 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
616 /// # #[cfg(feature = "alloc")]
617 /// # {
618 /// let hex_str = original.to_hex();
619 /// let decoded = Fixed::<[u8; 4]>::try_from_hex(&hex_str).unwrap();
620 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
621 /// # }
622 ///
623 /// // Wrong length fails.
624 /// assert!(Fixed::<[u8; 2]>::try_from_hex("deadbeef").is_err());
625 /// # }
626 /// ```
627 pub fn try_from_hex(hex: &str) -> Result<Self, crate::error::HexError> {
628 #[cfg(feature = "alloc")]
629 {
630 use zeroize::Zeroizing;
631 let bytes = Zeroizing::new(
632 base16ct::mixed::decode_vec(hex.as_bytes())
633 .map_err(|_| crate::error::HexError::InvalidHex)?,
634 );
635 if bytes.len() != N {
636 return Err(crate::error::HexError::InvalidLength {
637 expected: N,
638 got: bytes.len(),
639 });
640 }
641 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
642 }
643 #[cfg(not(feature = "alloc"))]
644 {
645 use zeroize::Zeroizing;
646 // no-alloc path: decode directly into a stack buffer; no heap allocation
647 // base16ct::mixed accepts upper, lower, and mixed-case hex
648 let mut buf = Zeroizing::new([0u8; N]);
649 let decoded = base16ct::mixed::decode(hex.as_bytes(), &mut *buf)
650 .map_err(|_| crate::error::HexError::InvalidHex)?;
651 if decoded.len() != N {
652 return Err(crate::error::HexError::InvalidLength {
653 expected: N,
654 got: decoded.len(),
655 });
656 }
657 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
658 // buf is zeroized on drop (both success and error paths)
659 }
660 }
661}
662
663/// Base32 encoding and decoding for `Fixed<[u8; N]>` (RFC 4648 §6, uppercase, unpadded).
664///
665/// Encoding uses a constant-time backend (`base32ct`). Decoding works with or without
666/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
667/// `Zeroizing<[u8; N]>` stack buffer.
668#[cfg(feature = "encoding-base32")]
669impl<const N: usize> Fixed<[u8; N]> {
670 /// Decodes an uppercase, unpadded Base32 string (RFC 4648 §6 alphabet) into
671 /// `Fixed<[u8; N]>`.
672 ///
673 /// Uses a constant-time backend (`base32ct`) on both paths.
674 ///
675 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
676 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
677 ///
678 /// Decoding is strict about the alphabet, case, padding and length, but lenient
679 /// about non-canonical trailing bits: unused bits in the final group are ignored
680 /// rather than rejected, so `"MZ"` and `"MY"` both decode to `[0x66]`. Decoding is
681 /// therefore not injective — two distinct strings can yield the same bytes, and
682 /// only encoder-produced strings are canonical. Do not use the decoded value to
683 /// decide that two encoded strings were equal.
684 ///
685 /// # Errors
686 ///
687 /// - [`Base32Error::InvalidBase32`](crate::Base32Error::InvalidBase32) — wrong alphabet
688 /// or case, `=` padding, or a length that is impossible for unpadded Base32. Without
689 /// `alloc` an input that decodes to *more* than `N` bytes also lands here rather than in
690 /// `InvalidLength`, because the fixed stack buffer cannot hold the overflow to measure it.
691 /// - [`Base32Error::InvalidLength`](crate::Base32Error::InvalidLength) — decoded byte
692 /// count does not equal `N`.
693 ///
694 /// # Examples
695 ///
696 /// ```rust
697 /// # #[cfg(feature = "encoding-base32")]
698 /// # {
699 /// use secure_gate::{Fixed, RevealSecret, ToBase32};
700 ///
701 /// # #[cfg(feature = "alloc")]
702 /// # {
703 /// // Round-trip.
704 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
705 /// let encoded = original.to_base32();
706 /// assert_eq!(&*encoded, "32W353Y");
707 /// let decoded = Fixed::<[u8; 4]>::try_from_base32(&encoded).unwrap();
708 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
709 /// # }
710 /// # }
711 /// ```
712 pub fn try_from_base32(s: &str) -> Result<Self, crate::error::Base32Error> {
713 #[cfg(feature = "alloc")]
714 {
715 use base32ct::{Base32UpperUnpadded, Encoding};
716 use zeroize::Zeroizing;
717 let bytes = Zeroizing::new(
718 Base32UpperUnpadded::decode_vec(s)
719 .map_err(|_| crate::error::Base32Error::InvalidBase32)?,
720 );
721 if bytes.len() != N {
722 return Err(crate::error::Base32Error::InvalidLength {
723 expected: N,
724 got: bytes.len(),
725 });
726 }
727 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
728 }
729 #[cfg(not(feature = "alloc"))]
730 {
731 use base32ct::{Base32UpperUnpadded, Encoding};
732 use zeroize::Zeroizing;
733 let mut buf = Zeroizing::new([0u8; N]);
734 let decoded = Base32UpperUnpadded::decode(s, &mut *buf)
735 .map_err(|_| crate::error::Base32Error::InvalidBase32)?;
736 if decoded.len() != N {
737 return Err(crate::error::Base32Error::InvalidLength {
738 expected: N,
739 got: decoded.len(),
740 });
741 }
742 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
743 // buf is zeroized on drop (both success and error paths)
744 }
745 }
746}
747
748/// Base64url encoding and decoding for `Fixed<[u8; N]>`.
749///
750/// Encoding uses a constant-time backend (`base64ct`). Decoding works with or without
751/// the `alloc` feature — on no-alloc targets the bytes are decoded directly into a
752/// `Zeroizing<[u8; N]>` stack buffer.
753#[cfg(feature = "encoding-base64")]
754impl<const N: usize> Fixed<[u8; N]> {
755 /// Decodes an unpadded Base64url string (RFC 4648, URL-safe alphabet) into
756 /// `Fixed<[u8; N]>`.
757 ///
758 /// Uses a constant-time backend (`base64ct`) on both paths.
759 ///
760 /// - **With `alloc`**: decodes into a `Zeroizing<Vec<u8>>` then copies onto the stack.
761 /// - **Without `alloc`**: decodes directly into a `Zeroizing<[u8; N]>` stack buffer.
762 ///
763 /// # Errors
764 ///
765 /// - [`Base64Error::InvalidBase64`](crate::Base64Error::InvalidBase64) — non-base64 characters or invalid padding.
766 /// - [`Base64Error::InvalidLength`](crate::Base64Error::InvalidLength) — decoded byte count does not equal `N`.
767 ///
768 /// # Examples
769 ///
770 /// ```rust
771 /// # #[cfg(feature = "encoding-base64")]
772 /// # {
773 /// use secure_gate::{Fixed, RevealSecret, ToBase64Url};
774 ///
775 /// # #[cfg(feature = "alloc")]
776 /// # {
777 /// // Round-trip.
778 /// let original = Fixed::new([0xDE, 0xAD, 0xBE, 0xEF]);
779 /// let encoded = original.to_base64url();
780 /// let decoded = Fixed::<[u8; 4]>::try_from_base64url(&encoded).unwrap();
781 /// assert_eq!(decoded.expose_secret(), &[0xDE, 0xAD, 0xBE, 0xEF]);
782 /// # }
783 /// # }
784 /// ```
785 pub fn try_from_base64url(s: &str) -> Result<Self, crate::error::Base64Error> {
786 #[cfg(feature = "alloc")]
787 {
788 use base64ct::{Base64UrlUnpadded, Encoding};
789 use zeroize::Zeroizing;
790 let bytes = Zeroizing::new(
791 Base64UrlUnpadded::decode_vec(s)
792 .map_err(|_| crate::error::Base64Error::InvalidBase64)?,
793 );
794 if bytes.len() != N {
795 return Err(crate::error::Base64Error::InvalidLength {
796 expected: N,
797 got: bytes.len(),
798 });
799 }
800 Ok(Self::new_with(|arr| arr.copy_from_slice(&bytes)))
801 }
802 #[cfg(not(feature = "alloc"))]
803 {
804 use base64ct::{Base64UrlUnpadded, Encoding};
805 use zeroize::Zeroizing;
806 let mut buf = Zeroizing::new([0u8; N]);
807 let decoded = Base64UrlUnpadded::decode(s, &mut *buf)
808 .map_err(|_| crate::error::Base64Error::InvalidBase64)?;
809 if decoded.len() != N {
810 return Err(crate::error::Base64Error::InvalidLength {
811 expected: N,
812 got: decoded.len(),
813 });
814 }
815 Ok(Self::new_with(|arr| arr.copy_from_slice(decoded)))
816 // buf is zeroized on drop (both success and error paths)
817 }
818 }
819}
820
821/// Bech32 (BIP-173) encoding and decoding for `Fixed<[u8; N]>`.
822///
823/// The plain constructors accept strings up to
824/// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH); the `_sized::<C>` constructors
825/// take the code length as a parameter for larger payloads. For Bitcoin address formats
826/// use `ToBech32m` and stay within BIP-173's 90-character convention.
827#[cfg(feature = "encoding-bech32")]
828impl<const N: usize> Fixed<[u8; N]> {
829 /// Decodes a Bech32 (BIP-173) string into `Fixed<[u8; N]>`, validating that the HRP
830 /// matches `expected_hrp` (case-insensitive).
831 ///
832 /// HRP comparison is non-constant-time — this is intentional, as the HRP is public
833 /// metadata, not secret material. Timing leaks on HRP mismatch are acceptable because
834 /// the HRP is not secret. Prefer this over
835 /// [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked) to prevent
836 /// cross-protocol confusion attacks.
837 ///
838 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
839 pub fn try_from_bech32(s: &str, expected_hrp: &str) -> Result<Self, crate::error::Bech32Error> {
840 Self::try_from_bech32_sized::<{ crate::BECH32_CODE_LENGTH }>(s, expected_hrp)
841 }
842
843 /// Like [`try_from_bech32`](Self::try_from_bech32), accepting strings up to `C`
844 /// characters.
845 ///
846 /// `C` is the bech32 *code length* -- the cap on the whole encoded string -- and is
847 /// independent of `N`, the decoded byte count this wrapper holds. Pass the `C` the
848 /// string was encoded with, or any larger value. See
849 /// [`Bech32Sized`](crate::Bech32Sized) for what `C` above
850 /// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH) costs.
851 ///
852 /// Works without `alloc` -- decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
853 pub fn try_from_bech32_sized<const C: usize>(
854 s: &str,
855 expected_hrp: &str,
856 ) -> Result<Self, crate::error::Bech32Error> {
857 use crate::traits::encoding::bech32::Bech32Sized;
858 use bech32::primitives::decode::CheckedHrpstring;
859 let checked = CheckedHrpstring::new::<Bech32Sized<C>>(s)
860 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
861 // HRP check before any payload byte is materialized (case-insensitive
862 // comparison — timing leak is acceptable since HRP is public metadata)
863 if !checked.hrp().as_str().eq_ignore_ascii_case(expected_hrp) {
864 return Err(crate::error::Bech32Error::UnexpectedHrp);
865 }
866 let buf = drain_bech32_payload::<N>(&checked)?;
867 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
868 // buf is zeroized on drop
869 }
870
871 /// Decodes a Bech32 (BIP-173) string into `Fixed<[u8; N]>` without validating the HRP.
872 ///
873 /// Any valid HRP is accepted as long as the checksum is valid and the payload length
874 /// equals `N`. Use [`try_from_bech32`](Self::try_from_bech32) in security-critical code
875 /// to prevent cross-protocol confusion attacks.
876 ///
877 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
878 pub fn try_from_bech32_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
879 Self::try_from_bech32_unchecked_sized::<{ crate::BECH32_CODE_LENGTH }>(s)
880 }
881
882 /// Like [`try_from_bech32_unchecked`](Self::try_from_bech32_unchecked), accepting
883 /// strings up to `C` characters.
884 pub fn try_from_bech32_unchecked_sized<const C: usize>(
885 s: &str,
886 ) -> Result<Self, crate::error::Bech32Error> {
887 use crate::traits::encoding::bech32::Bech32Sized;
888 use bech32::primitives::decode::CheckedHrpstring;
889 let checked = CheckedHrpstring::new::<Bech32Sized<C>>(s)
890 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
891 let buf = drain_bech32_payload::<N>(&checked)?;
892 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
893 // buf is zeroized on drop
894 }
895}
896
897/// Bech32m (BIP-350) encoding and decoding for `Fixed<[u8; N]>`.
898///
899/// The plain constructors accept strings up to
900/// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH); the `_sized::<C>` constructors
901/// take the code length as a parameter. Bitcoin address tooling expects BIP-173's
902/// 90-character cap, which is narrower than either and is the caller's to respect.
903#[cfg(feature = "encoding-bech32")]
904impl<const N: usize> Fixed<[u8; N]> {
905 /// Decodes a Bech32m (BIP-350) string into `Fixed<[u8; N]>`, validating that the HRP
906 /// matches `expected_hrp` (case-insensitive).
907 ///
908 /// HRP comparison is non-constant-time — this is intentional, as the HRP is public
909 /// metadata, not secret material. Timing leaks on HRP mismatch are acceptable because
910 /// the HRP is not secret. Prefer this over
911 /// [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked) to prevent
912 /// cross-protocol confusion attacks.
913 ///
914 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
915 pub fn try_from_bech32m(
916 s: &str,
917 expected_hrp: &str,
918 ) -> Result<Self, crate::error::Bech32Error> {
919 Self::try_from_bech32m_sized::<{ crate::BECH32_CODE_LENGTH }>(s, expected_hrp)
920 }
921
922 /// Like [`try_from_bech32m`](Self::try_from_bech32m), accepting strings up to `C`
923 /// characters.
924 ///
925 /// `C` is the bech32m *code length*, independent of `N`, the decoded byte count.
926 /// See [`Bech32mSized`](crate::Bech32mSized) for what `C` above
927 /// [`BECH32_CODE_LENGTH`](crate::BECH32_CODE_LENGTH) costs.
928 ///
929 /// Works without `alloc` -- decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
930 pub fn try_from_bech32m_sized<const C: usize>(
931 s: &str,
932 expected_hrp: &str,
933 ) -> Result<Self, crate::error::Bech32Error> {
934 use crate::traits::encoding::bech32m::Bech32mSized;
935 use bech32::primitives::decode::CheckedHrpstring;
936 let checked = CheckedHrpstring::new::<Bech32mSized<C>>(s)
937 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
938 // HRP check before any payload byte is materialized (case-insensitive
939 // comparison — timing leak is acceptable since HRP is public metadata)
940 if !checked.hrp().as_str().eq_ignore_ascii_case(expected_hrp) {
941 return Err(crate::error::Bech32Error::UnexpectedHrp);
942 }
943 let buf = drain_bech32_payload::<N>(&checked)?;
944 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
945 // buf is zeroized on drop
946 }
947
948 /// Decodes a Bech32m (BIP-350) string into `Fixed<[u8; N]>` without validating the HRP.
949 ///
950 /// Any valid HRP is accepted as long as the checksum is valid and the payload length
951 /// equals `N`. Use [`try_from_bech32m`](Self::try_from_bech32m) in security-critical
952 /// code to prevent cross-protocol confusion attacks.
953 ///
954 /// Works without `alloc` — decodes into a stack-allocated `Zeroizing<[u8; N]>` buffer.
955 pub fn try_from_bech32m_unchecked(s: &str) -> Result<Self, crate::error::Bech32Error> {
956 Self::try_from_bech32m_unchecked_sized::<{ crate::BECH32_CODE_LENGTH }>(s)
957 }
958
959 /// Like [`try_from_bech32m_unchecked`](Self::try_from_bech32m_unchecked), accepting
960 /// strings up to `C` characters.
961 pub fn try_from_bech32m_unchecked_sized<const C: usize>(
962 s: &str,
963 ) -> Result<Self, crate::error::Bech32Error> {
964 use crate::traits::encoding::bech32m::Bech32mSized;
965 use bech32::primitives::decode::CheckedHrpstring;
966 let checked = CheckedHrpstring::new::<Bech32mSized<C>>(s)
967 .map_err(|_| crate::error::Bech32Error::OperationFailed)?;
968 let buf = drain_bech32_payload::<N>(&checked)?;
969 Ok(Self::new_with(|arr| arr.copy_from_slice(&*buf)))
970 // buf is zeroized on drop
971 }
972}
973
974/// Hex encoding for `Fixed<[u8; N]>` — same constant-time backend as the
975/// [`ToHex`] blanket impl on the inner bytes; delegates via `with_secret`.
976///
977/// Bring the trait into scope to call these: `use secure_gate::ToHex;`.
978///
979/// ```rust
980/// use secure_gate::{Fixed, ToHex};
981///
982/// let key = Fixed::new([0xABu8; 4]);
983/// assert_eq!(&*key.to_hex(), "abababab");
984/// assert_eq!(&*key.to_hex_upper(), "ABABABAB");
985/// // Both return an `EncodedSecret` — the encoded form wipes itself on drop.
986/// ```
987#[cfg(all(feature = "encoding-hex", feature = "alloc"))]
988impl<const N: usize> ToHex for Fixed<[u8; N]> {
989 #[inline]
990 fn to_hex(&self) -> crate::EncodedSecret {
991 self.with_secret(|s| s.to_hex())
992 }
993
994 #[inline]
995 fn to_hex_upper(&self) -> crate::EncodedSecret {
996 self.with_secret(|s| s.to_hex_upper())
997 }
998}
999
1000/// Base32 encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1001///
1002/// Bring the trait into scope to call these: `use secure_gate::ToBase32;`.
1003///
1004/// ```rust
1005/// use secure_gate::{Fixed, ToBase32};
1006///
1007/// let key = Fixed::new([0xABu8; 4]);
1008/// assert_eq!(&*key.to_base32(), "VOV2XKY");
1009/// ```
1010#[cfg(all(feature = "encoding-base32", feature = "alloc"))]
1011impl<const N: usize> ToBase32 for Fixed<[u8; N]> {
1012 #[inline]
1013 fn to_base32(&self) -> crate::EncodedSecret {
1014 self.with_secret(|s| s.to_base32())
1015 }
1016}
1017
1018/// Base64url encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1019///
1020/// Bring the trait into scope to call these: `use secure_gate::ToBase64Url;`.
1021///
1022/// ```rust
1023/// use secure_gate::{Fixed, ToBase64Url};
1024///
1025/// let key = Fixed::new([0xABu8; 4]);
1026/// assert_eq!(&*key.to_base64url(), "q6urqw");
1027/// ```
1028#[cfg(all(feature = "encoding-base64", feature = "alloc"))]
1029impl<const N: usize> ToBase64Url for Fixed<[u8; N]> {
1030 #[inline]
1031 fn to_base64url(&self) -> crate::EncodedSecret {
1032 self.with_secret(|s| s.to_base64url())
1033 }
1034}
1035
1036/// Bech32 encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1037///
1038/// Bring the trait into scope to call these: `use secure_gate::ToBech32;`.
1039#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
1040impl<const N: usize> ToBech32 for Fixed<[u8; N]> {
1041 #[inline]
1042 fn try_to_bech32(
1043 &self,
1044 hrp: &str,
1045 case: crate::Case,
1046 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1047 self.with_secret(|s| s.try_to_bech32(hrp, case))
1048 }
1049
1050 #[inline]
1051 fn try_to_bech32_sized<const C: usize>(
1052 &self,
1053 hrp: &str,
1054 case: crate::Case,
1055 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1056 self.with_secret(|s| s.try_to_bech32_sized::<C>(hrp, case))
1057 }
1058}
1059
1060/// Bech32m encoding for `Fixed<[u8; N]>`; delegates via `with_secret`.
1061///
1062/// Bring the trait into scope to call these: `use secure_gate::ToBech32m;`.
1063#[cfg(all(feature = "encoding-bech32", feature = "alloc"))]
1064impl<const N: usize> ToBech32m for Fixed<[u8; N]> {
1065 #[inline]
1066 fn try_to_bech32m(
1067 &self,
1068 hrp: &str,
1069 case: crate::Case,
1070 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1071 self.with_secret(|s| s.try_to_bech32m(hrp, case))
1072 }
1073
1074 #[inline]
1075 fn try_to_bech32m_sized<const C: usize>(
1076 &self,
1077 hrp: &str,
1078 case: crate::Case,
1079 ) -> Result<crate::EncodedSecret, crate::error::Bech32Error> {
1080 self.with_secret(|s| s.try_to_bech32m_sized::<C>(hrp, case))
1081 }
1082}
1083
1084/// Explicit access to immutable [`Fixed<[T; N]>`] contents.
1085impl<T: zeroize::Zeroize> RevealSecret for Fixed<T> {
1086 type Inner = T;
1087
1088 #[inline(always)]
1089 fn with_secret<F, R>(&self, f: F) -> R
1090 where
1091 F: FnOnce(&T) -> R,
1092 {
1093 f(&self.inner)
1094 }
1095
1096 #[inline(always)]
1097 fn expose_secret(&self) -> &T {
1098 &self.inner
1099 }
1100
1101 /// Consumes `self` and transfers ownership of the plain `[T; N]`.
1102 ///
1103 /// Zero cost — no allocation. The sentinel placed in `self.inner` is
1104 /// `[T::default(); N]` via [`crate::SentinelValue`] (already zeroed for `u8`),
1105 /// so `Fixed::drop` zeroizes an already-zero array — a harmless no-op.
1106 /// Works for **any** array length `N` (not limited to 32 like `Default`).
1107 ///
1108 /// See [`RevealSecret::into_inner`] for the full contract, including the
1109 /// `SentinelValue` bound rationale. Protection ends at this call: the array you
1110 /// get back is plain — not wiped on drop, and its `Debug` is not redacted.
1111 #[inline(always)]
1112 fn into_inner(mut self) -> T
1113 where
1114 Self: Sized,
1115 Self::Inner: Sized + crate::SentinelValue + zeroize::Zeroize,
1116 {
1117 // Replace inner with the sentinel so Fixed::drop zeroizes a harmless
1118 // placeholder while the caller receives the real secret. The secret is stored
1119 // inline, so this transfers the bytes rather than handing over an allocation;
1120 // what the sentinel guarantees is that no second copy is left behind here.
1121 core::mem::replace(&mut self.inner, crate::SentinelValue::sentinel_value())
1122 }
1123}
1124
1125/// Length is only meaningful for array-shaped secrets.
1126impl<const N: usize, T: zeroize::Zeroize> crate::SecretLen for Fixed<[T; N]> {
1127 #[inline(always)]
1128 fn len(&self) -> usize {
1129 N
1130 }
1131
1132 #[inline(always)]
1133 fn byte_len(&self) -> usize {
1134 N * core::mem::size_of::<T>()
1135 }
1136}
1137
1138/// Explicit access to mutable [`Fixed<[T; N]>`] contents.
1139impl<T: zeroize::Zeroize> RevealSecretMut for Fixed<T> {
1140 #[inline(always)]
1141 fn with_secret_mut<F, R>(&mut self, f: F) -> R
1142 where
1143 F: FnOnce(&mut T) -> R,
1144 {
1145 f(&mut self.inner)
1146 }
1147
1148 #[inline(always)]
1149 fn expose_secret_mut(&mut self) -> &mut T {
1150 &mut self.inner
1151 }
1152}
1153
1154#[cfg(feature = "rand")]
1155impl<const N: usize> Fixed<[u8; N]> {
1156 /// Fills a new `[u8; N]` with cryptographically secure random bytes and wraps it.
1157 ///
1158 /// Uses the system RNG ([`SysRng`](rand::rngs::SysRng)). Requires the `rand` feature.
1159 /// Heap-free and works in `no_std` / `no_alloc` builds.
1160 ///
1161 /// # Panics
1162 ///
1163 /// Panics if the system RNG fails to provide bytes ([`TryRng::try_fill_bytes`](rand::TryRng::try_fill_bytes)
1164 /// returns `Err`). This is treated as a fatal environment error.
1165 ///
1166 /// # Examples
1167 ///
1168 /// ```rust
1169 /// # #[cfg(feature = "rand")]
1170 /// use secure_gate::{Fixed, RevealSecret, SecretLen};
1171 ///
1172 /// # #[cfg(feature = "rand")]
1173 /// # {
1174 /// let key: Fixed<[u8; 32]> = Fixed::from_random();
1175 /// assert_eq!(key.len(), 32);
1176 /// # }
1177 /// ```
1178 #[inline]
1179 pub fn from_random() -> Self {
1180 Self::new_with(|arr| {
1181 SysRng
1182 .try_fill_bytes(arr)
1183 .expect("SysRng failure is a program error");
1184 })
1185 }
1186
1187 /// Fills a new `[u8; N]` from `rng` and wraps it.
1188 ///
1189 /// Accepts any [`TryCryptoRng`](rand::TryCryptoRng) + [`TryRng`](rand::TryRng) — for example,
1190 /// a seeded `StdRng` for deterministic tests. Requires the `rand`
1191 /// feature. Heap-free.
1192 ///
1193 /// # Errors
1194 ///
1195 /// Returns `R::Error` if [`try_fill_bytes`](rand::TryRng::try_fill_bytes) fails.
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```rust
1200 /// # #[cfg(feature = "rand")]
1201 /// # {
1202 /// use rand::rngs::StdRng;
1203 /// use rand::SeedableRng;
1204 /// use secure_gate::Fixed;
1205 ///
1206 /// let mut rng = StdRng::from_seed([1u8; 32]);
1207 /// let key: Fixed<[u8; 16]> = Fixed::from_rng(&mut rng).expect("rng fill");
1208 /// # }
1209 /// ```
1210 #[inline]
1211 pub fn from_rng<R: TryRng + TryCryptoRng>(rng: &mut R) -> Result<Self, R::Error> {
1212 // This body was the captured-local workaround `try_new_with` exists to retire:
1213 // `new_with` could not report failure, so the error was written to a local and
1214 // checked afterwards. Same behaviour, one expression.
1215 Self::try_new_with(|arr| rng.try_fill_bytes(arr))
1216 }
1217}
1218
1219/// Constant-time equality for `Fixed<T>` — routes through [`expose_secret()`](crate::RevealSecret::expose_secret).
1220///
1221/// `==` is **deliberately not implemented** on `Fixed`. Always use `ct_eq`.
1222///
1223/// ```rust
1224/// # #[cfg(feature = "ct-eq")]
1225/// # {
1226/// use secure_gate::{Fixed, ConstantTimeEq};
1227///
1228/// let a = Fixed::new([1u8; 4]);
1229/// let b = Fixed::new([1u8; 4]);
1230/// let c = Fixed::new([2u8; 4]);
1231/// assert!(a.ct_eq(&b));
1232/// assert!(!a.ct_eq(&c));
1233/// # }
1234/// ```
1235#[cfg(feature = "ct-eq")]
1236impl<T: zeroize::Zeroize> crate::ConstantTimeEq for Fixed<T>
1237where
1238 T: crate::ConstantTimeEq,
1239 Self: crate::RevealSecret<Inner = T>,
1240{
1241 fn ct_eq(&self, other: &Self) -> bool {
1242 self.expose_secret().ct_eq(other.expose_secret())
1243 }
1244}
1245
1246/// Always prints `[REDACTED]` — secrets never appear in debug output.
1247///
1248/// ```rust
1249/// use secure_gate::Fixed;
1250///
1251/// let key = Fixed::new([0xABu8; 32]);
1252/// assert_eq!(format!("{:?}", key), "[REDACTED]");
1253/// ```
1254impl<T: zeroize::Zeroize> core::fmt::Debug for Fixed<T> {
1255 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1256 f.write_str("[REDACTED]")
1257 }
1258}
1259
1260/// Opt-in cloning — requires `cloneable` feature and [`CloneableSecret`](crate::CloneableSecret)
1261/// marker on the inner type. Each clone is independently zeroized on drop, but cloning
1262/// increases the in-memory exposure surface. Use sparingly.
1263#[cfg(feature = "cloneable")]
1264impl<T: zeroize::Zeroize + crate::CloneableSecret + crate::FixedStorage> Clone for Fixed<T> {
1265 fn clone(&self) -> Self {
1266 Self::new(self.inner.clone())
1267 }
1268}
1269
1270/// Opt-in serialization — requires `serde-serialize` feature and
1271/// [`SerializableSecret`](crate::SerializableSecret) marker on the inner type.
1272/// Serialization exposes the full secret — audit every impl.
1273#[cfg(feature = "serde-serialize")]
1274impl<T: zeroize::Zeroize + crate::SerializableSecret> serde::Serialize for Fixed<T> {
1275 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1276 where
1277 S: serde::Serializer,
1278 {
1279 self.inner.serialize(serializer)
1280 }
1281}
1282
1283/// Deserialization uses `Zeroizing`-wrapped temporary buffers — zeroized even on rejection.
1284///
1285/// The sequence buffer is pre-allocated to exactly `N` bytes and **never grows**: an
1286/// input sequence longer than `N` is rejected before the element that would trigger a
1287/// reallocation is stored. This matters because a `Vec` reallocation frees the old
1288/// buffer — which would already hold `N` secret bytes — without zeroizing it.
1289///
1290/// The entry point is `deserialize_seq` (unchanged wire format for non-self-describing
1291/// formats such as postcard), but the visitor also accepts byte strings via
1292/// `visit_bytes` / `visit_byte_buf`, so self-describing formats that encode byte
1293/// arrays as byte strings (e.g. CBOR) round-trip too. Owned buffers handed over
1294/// through `visit_byte_buf` are zeroized after the copy.
1295#[cfg(feature = "serde-deserialize")]
1296impl<'de, const N: usize> serde::Deserialize<'de> for Fixed<[u8; N]> {
1297 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1298 where
1299 D: serde::Deserializer<'de>,
1300 {
1301 use core::fmt;
1302 use serde::de::Visitor;
1303 struct FixedVisitor<const M: usize>;
1304 impl<'de, const M: usize> Visitor<'de> for FixedVisitor<M> {
1305 type Value = Fixed<[u8; M]>;
1306 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1307 write!(formatter, "a byte array of length {}", M)
1308 }
1309 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1310 where
1311 A: serde::de::SeqAccess<'de>,
1312 {
1313 let mut vec: zeroize::Zeroizing<alloc::vec::Vec<u8>> =
1314 zeroize::Zeroizing::new(alloc::vec::Vec::with_capacity(M));
1315 while let Some(value) = seq.next_element()? {
1316 // Reject over-length input *before* pushing past the reserved
1317 // capacity: growing would realloc and free the old buffer
1318 // (already holding M secret bytes) without zeroization.
1319 if vec.len() == M {
1320 return Err(serde::de::Error::invalid_length(M + 1, &self));
1321 }
1322 vec.push(value);
1323 }
1324 if vec.len() != M {
1325 return Err(serde::de::Error::invalid_length(vec.len(), &self));
1326 }
1327 Ok(Fixed::<[u8; M]>::new_with(|arr| arr.copy_from_slice(&vec)))
1328 }
1329 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1330 where
1331 E: serde::de::Error,
1332 {
1333 if v.len() != M {
1334 return Err(serde::de::Error::invalid_length(v.len(), &self));
1335 }
1336 Ok(Fixed::<[u8; M]>::new_with(|arr| arr.copy_from_slice(v)))
1337 }
1338 fn visit_byte_buf<E>(self, v: alloc::vec::Vec<u8>) -> Result<Self::Value, E>
1339 where
1340 E: serde::de::Error,
1341 {
1342 // Take ownership under Zeroizing so the deserializer-provided
1343 // buffer is wiped after the copy — the default forwarding impl
1344 // would drop it unzeroized.
1345 let v = zeroize::Zeroizing::new(v);
1346 self.visit_bytes(&v)
1347 }
1348 }
1349 deserializer.deserialize_seq(FixedVisitor::<N>)
1350 }
1351}
1352
1353/// Zeroizes the inner value. Called automatically by [`Drop`].
1354///
1355/// **Warning:** zeroization does not run for `static` items or under `panic = "abort"`.
1356impl<T: zeroize::Zeroize> zeroize::Zeroize for Fixed<T> {
1357 fn zeroize(&mut self) {
1358 self.inner.zeroize();
1359 }
1360}
1361
1362/// Unconditionally zeroizes the inner value when the wrapper is dropped.
1363///
1364/// **Warning:** `Drop` does not run for `static` items or under `panic = "abort"`.
1365impl<T: zeroize::Zeroize> Drop for Fixed<T> {
1366 fn drop(&mut self) {
1367 self.zeroize();
1368 }
1369}
1370
1371/// Marker confirming that `Fixed<T>` always zeroizes on drop.
1372impl<T: zeroize::Zeroize> zeroize::ZeroizeOnDrop for Fixed<T> {}