pub struct SecretBytes<const N: usize> { /* private fields */ }Expand description
Fixed-size secret byte storage with automatic sanitization on drop.
Bytes are stored in a plain [u8; N] and all clearing routes through the
crate’s internal volatile wipe backend. This gives the same clearing behavior
on targets with and without native byte atomics.
§Platform Notes
This type is Sync because it contains only plain bytes. Mutating and
clearing operations require &mut self to prevent partially-cleared
multi-byte observations through shared references.
SecretBytes<N> stores N bytes inline. SecretBytes::expose_secret
borrows that storage directly and does not intentionally construct a
full-size temporary array. SecretBytes::export_secret_copy is the
explicit copy-based alternative.
The type deliberately does not implement Clone, Copy, Deref,
AsRef<[u8]>, PartialEq, or secret-printing Debug.
Implementations§
Source§impl<const N: usize> SecretBytes<N>
impl<const N: usize> SecretBytes<N>
Sourcepub fn from_array(bytes: [u8; N]) -> Self
pub fn from_array(bytes: [u8; N]) -> Self
Create a secret from an array, then volatile-clear the input array.
For the strongest move hygiene, prefer SecretBytes::from_fn or
SecretBytes::copy_from_slice so callers can avoid building a normal
byte array first.
Sourcepub fn from_fn(make_byte: impl FnMut(usize) -> u8) -> Self
pub fn from_fn(make_byte: impl FnMut(usize) -> u8) -> Self
Create a secret by producing each byte directly.
This avoids requiring a full temporary [u8; N] at the call boundary.
Sourcepub fn try_from_fn<E>(
make_byte: impl FnMut(usize) -> Result<u8, E>,
) -> Result<Self, E>
pub fn try_from_fn<E>( make_byte: impl FnMut(usize) -> Result<u8, E>, ) -> Result<Self, E>
Create a secret by producing each byte directly with a fallible generator.
If make_byte returns an error, any bytes generated before the error
are cleared before the error is returned.
Sourcepub fn copy_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError>
pub fn copy_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError>
Replace all bytes from a same-length slice.
Sourcepub fn replace_from_array(&mut self, bytes: [u8; N])
pub fn replace_from_array(&mut self, bytes: [u8; N])
Replace all bytes from an owned array, then volatile-clear that input array.
Prefer this over SecretBytes::copy_from_slice when the caller has an
owned [u8; N] that should be wiped after rotation.
Sourcepub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8)
pub fn replace_from_fn(&mut self, make_byte: impl FnMut(usize) -> u8)
Replace all bytes with generated bytes.
The new bytes are generated into a fresh clear-on-drop value before the
old value is cleared and replaced. If make_byte panics, the old value
remains unchanged and partial generated bytes are cleared during
unwinding.
Sourcepub fn try_replace_from_fn<E>(
&mut self,
make_byte: impl FnMut(usize) -> Result<u8, E>,
) -> Result<(), E>
pub fn try_replace_from_fn<E>( &mut self, make_byte: impl FnMut(usize) -> Result<u8, E>, ) -> Result<(), E>
Replace all bytes with generated bytes from a fallible generator.
The new bytes are generated into a fresh clear-on-drop value before the
old value is cleared and replaced. If make_byte returns an error, the
old value remains unchanged and partial generated bytes are cleared
before the error is returned.
Sourcepub fn transform(&mut self, edit: impl FnOnce(&mut [u8; N]))
pub fn transform(&mut self, edit: impl FnOnce(&mut [u8; N]))
Mutate the secret bytes in place.
The closure receives direct mutable access to the fixed-size storage owned by this container. It can still intentionally copy bytes elsewhere, so keep this API at cryptographic transformation boundaries such as key derivation, masking, or protocol-specific normalization.
Sourcepub fn try_transform<E>(
&mut self,
edit: impl FnOnce(&mut [u8; N]) -> Result<(), E>,
) -> Result<(), E>
pub fn try_transform<E>( &mut self, edit: impl FnOnce(&mut [u8; N]) -> Result<(), E>, ) -> Result<(), E>
Fallible variant of SecretBytes::transform.
If the closure returns an error after partially mutating the value,
those mutations remain in place. Use SecretBytes::try_replace_from_fn
when the old value must remain unchanged on error.
Sourcepub fn derive<const M: usize>(
&self,
derive: impl FnOnce(&[u8; N], &mut [u8; M]),
) -> SecretBytes<M>
pub fn derive<const M: usize>( &self, derive: impl FnOnce(&[u8; N], &mut [u8; M]), ) -> SecretBytes<M>
Derive a new fixed-size secret without exposing either buffer through a temporary stack copy.
The closure receives read-only access to this secret’s storage and mutable access to the new output secret’s storage. This is intended for KDFs, key hierarchy expansion, and similar operations where the output should be written directly into a clear-on-drop container.
Sourcepub fn try_derive<const M: usize, E>(
&self,
derive: impl FnOnce(&[u8; N], &mut [u8; M]) -> Result<(), E>,
) -> Result<SecretBytes<M>, E>
pub fn try_derive<const M: usize, E>( &self, derive: impl FnOnce(&[u8; N], &mut [u8; M]) -> Result<(), E>, ) -> Result<SecretBytes<M>, E>
Fallible variant of SecretBytes::derive.
If derivation fails, the partially written output is dropped and volatile-cleared before the error is returned.
Sourcepub fn export_to_slice(
&self,
reason: &'static str,
destination: &mut [u8],
) -> Result<(), LengthError>
pub fn export_to_slice( &self, reason: &'static str, destination: &mut [u8], ) -> Result<(), LengthError>
Export a temporary copy into caller-owned storage.
The destination is outside this container’s clearing guarantee. The
caller must clear it. reason is an audit label identifying why this
copy is allowed to cross the secret-container boundary.
Sourcepub fn export_byte(&self, reason: &'static str, index: usize) -> Option<u8>
pub fn export_byte(&self, reason: &'static str, index: usize) -> Option<u8>
Export one byte from the secret.
The returned scalar is an unmanaged copy that may remain in registers or
compiler temporaries. reason is an audit label identifying the public
boundary that permits this extraction.
Sourcepub fn write_byte(&mut self, index: usize, value: u8) -> Result<(), LengthError>
pub fn write_byte(&mut self, index: usize, value: u8) -> Result<(), LengthError>
Replace one byte.
Sourcepub fn expose_secret<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R
pub fn expose_secret<R>(&self, inspect: impl FnOnce(&[u8; N]) -> R) -> R
Call a closure with direct shared access to the owned fixed-size bytes.
This method does not intentionally construct an additional [u8; N]
temporary. The closure can still cause compiler spills or deliberately
copy bytes elsewhere, so use it only at reviewed cryptographic or
protocol boundaries.
The returned value cannot borrow the secret:
use sanitization::SecretBytes;
let secret = SecretBytes::<4>::from_array([1, 2, 3, 4]);
let escaped = secret.expose_secret(|bytes| bytes);
let _ = escaped;Sourcepub fn export_secret_copy<R>(
&self,
reason: &'static str,
inspect: impl FnOnce(&[u8; N]) -> R,
) -> R
pub fn export_secret_copy<R>( &self, reason: &'static str, inspect: impl FnOnce(&[u8; N]) -> R, ) -> R
Call a closure with a temporary array copy, then volatile-clear it.
This explicitly creates an additional N-byte stack array. The copy is
cleared eagerly on normal return and by an RAII guard during unwinding.
It cannot be cleared if the process aborts, including under
panic = "abort".
Prefer SecretBytes::expose_secret unless the callee must receive
storage that is independent from the secret container.
Sourcepub fn constant_time_eq(&self, other: &[u8]) -> bool
pub fn constant_time_eq(&self, other: &[u8]) -> bool
Compare against a slice without early exit for equal-length inputs.
Length mismatch returns immediately because the provided slice length is treated as public metadata. Prefer fixed-size inputs where possible.
The portable fallback is intended to avoid data-dependent early exit, but
it is not a formal hardware-level constant-time guarantee. On x86_64,
enable asm-compare for a stronger compiler boundary. Use a dedicated
constant-time comparison crate if your protocol requires externally
audited timing guarantees.
Sourcepub fn constant_time_eq_secret(&self, other: &Self) -> bool
pub fn constant_time_eq_secret(&self, other: &Self) -> bool
Compare against another secret without early exit.
See SecretBytes::constant_time_eq for the portable fallback timing
limits.
Sourcepub fn secure_clear(&mut self)
pub fn secure_clear(&mut self)
Clear all bytes now. This is also called from Drop.
Sourcepub fn secure_clear_multi_pass(&mut self)
pub fn secure_clear_multi_pass(&mut self)
Clear all bytes now with an explicit three-pass volatile pattern.
Available with the multi-pass-clear feature. This is intended for
policy or audit compatibility; for volatile RAM, the default
SecretBytes::secure_clear remains the normal security boundary.
Sourcepub fn into_cleared(self)
pub fn into_cleared(self)
Consume this value after first clearing the fixed-size storage.
Drop still runs after this method returns, so the storage is cleared a second time on the normal path.
Sourcepub fn secure_clear_and_flush(
&mut self,
) -> Result<CacheFlushReport, CacheFlushError>
pub fn secure_clear_and_flush( &mut self, ) -> Result<CacheFlushReport, CacheFlushError>
Clear all bytes now with volatile writes, then flush the cache lines covering the fixed-size storage.
Trait Implementations§
Source§impl<const N: usize> ConditionallySelectable for SecretBytes<N>
impl<const N: usize> ConditionallySelectable for SecretBytes<N>
Source§fn conditional_select(left: &Self, right: &Self, choice: Choice) -> Self
fn conditional_select(left: &Self, right: &Self, choice: Choice) -> Self
left when choice is false and right when it is true.Source§impl<const N: usize> ConstantTimeEq for SecretBytes<N>
impl<const N: usize> ConstantTimeEq for SecretBytes<N>
Source§impl<const N: usize> ConstantTimeEq for SecretBytes<N>
impl<const N: usize> ConstantTimeEq for SecretBytes<N>
Source§impl<const N: usize> ConstantTimeEq<[u8]> for SecretBytes<N>
impl<const N: usize> ConstantTimeEq<[u8]> for SecretBytes<N>
Source§impl<const N: usize> Debug for SecretBytes<N>
impl<const N: usize> Debug for SecretBytes<N>
Source§impl<const N: usize> Default for SecretBytes<N>
impl<const N: usize> Default for SecretBytes<N>
Source§impl<'de, const N: usize> Deserialize<'de> for SecretBytes<N>
impl<'de, const N: usize> Deserialize<'de> for SecretBytes<N>
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Source§impl<const N: usize> Drop for SecretBytes<N>
impl<const N: usize> Drop for SecretBytes<N>
Source§impl<const N: usize> SecureSanitize for SecretBytes<N>
impl<const N: usize> SecureSanitize for SecretBytes<N>
Source§fn secure_sanitize(&mut self)
fn secure_sanitize(&mut self)
Source§impl<const N: usize> Serialize for SecretBytes<N>
impl<const N: usize> Serialize for SecretBytes<N>
impl<const N: usize> StableMutableSecretStorage for SecretBytes<N>
Source§impl<const N: usize> Zeroize for SecretBytes<N>
impl<const N: usize> Zeroize for SecretBytes<N>
impl<const N: usize> ZeroizeOnDrop for SecretBytes<N>
Auto Trait Implementations§
impl<const N: usize> Forget for SecretBytes<N>
impl<const N: usize> Freeze for SecretBytes<N>
impl<const N: usize> Move for SecretBytes<N>
impl<const N: usize> RefUnwindSafe for SecretBytes<N>
impl<const N: usize> Send for SecretBytes<N>
impl<const N: usize> Sync for SecretBytes<N>
impl<const N: usize> Unpin for SecretBytes<N>
impl<const N: usize> UnsafeUnpin for SecretBytes<N>
impl<const N: usize> UnwindSafe for SecretBytes<N>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> ConditionallyAssignable for Twhere
T: ConditionallySelectable,
impl<T> ConditionallyAssignable for Twhere
T: ConditionallySelectable,
Source§fn conditional_assign(&mut self, other: &Self, choice: Choice)
fn conditional_assign(&mut self, other: &Self, choice: Choice)
other to self when choice is true.