Skip to main content

SecretBytes

Struct SecretBytes 

Source
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>

Source

pub const fn zeroed() -> Self

Create an all-zero secret buffer.

Source

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.

Source

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.

Source

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.

Source

pub const fn len(&self) -> usize

Number of bytes stored in this secret.

Source

pub const fn is_empty(&self) -> bool

Returns true when the secret has zero length.

Source

pub fn copy_from_slice(&mut self, source: &[u8]) -> Result<(), LengthError>

Replace all bytes from a same-length slice.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn write_byte(&mut self, index: usize, value: u8) -> Result<(), LengthError>

Replace one byte.

Source

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;
Source

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.

Source

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.

Source

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.

Source

pub fn secure_clear(&mut self)

Clear all bytes now. This is also called from Drop.

Source

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.

Source

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.

Source

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>

Source§

fn conditional_select(left: &Self, right: &Self, choice: Choice) -> Self

Return left when choice is false and right when it is true.
Source§

impl<const N: usize> ConstantTimeEq for SecretBytes<N>

Source§

fn ct_eq(&self, other: &Self) -> Choice

Compare without secret-dependent early exit.
Source§

fn ct_ne(&self, other: &Rhs) -> Choice

Source§

impl<const N: usize> ConstantTimeEq for SecretBytes<N>

Source§

fn ct_eq(&self, other: &Self) -> Choice

Determine if two items are equal. Read more
Source§

fn ct_ne(&self, other: &Self) -> Choice

Determine if two items are NOT equal. Read more
Source§

impl<const N: usize> ConstantTimeEq<[u8]> for SecretBytes<N>

Source§

fn ct_eq(&self, other: &[u8]) -> Choice

Compare without secret-dependent early exit.
Source§

fn ct_ne(&self, other: &Rhs) -> Choice

Source§

impl<const N: usize> Debug for SecretBytes<N>

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const N: usize> Default for SecretBytes<N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, const N: usize> Deserialize<'de> for SecretBytes<N>

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<const N: usize> Drop for SecretBytes<N>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<const N: usize> SecureSanitize for SecretBytes<N>

Source§

fn secure_sanitize(&mut self)

Clear the sensitive bytes owned by this value.
Source§

impl<const N: usize> Serialize for SecretBytes<N>

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<const N: usize> StableMutableSecretStorage for SecretBytes<N>

Source§

impl<const N: usize> StableSharedSecretStorage for SecretBytes<N>

Source§

impl<const N: usize> Zeroize for SecretBytes<N>

Source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.
Source§

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>
where [u8; N]: Freeze,

§

impl<const N: usize> Move for SecretBytes<N>

§

impl<const N: usize> RefUnwindSafe for SecretBytes<N>
where [u8; N]: RefUnwindSafe,

§

impl<const N: usize> Send for SecretBytes<N>
where [u8; N]: Send,

§

impl<const N: usize> Sync for SecretBytes<N>
where [u8; N]: Sync,

§

impl<const N: usize> Unpin for SecretBytes<N>
where [u8; N]: Unpin,

§

impl<const N: usize> UnsafeUnpin for SecretBytes<N>
where [u8; N]: UnsafeUnpin,

§

impl<const N: usize> UnwindSafe for SecretBytes<N>
where [u8; N]: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ConditionallyAssignable for T

Source§

fn conditional_assign(&mut self, other: &Self, choice: Choice)

Assign other to self when choice is true.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.