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