use std::fmt;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
pub struct SecretVec(Zeroizing<Vec<u8>>);
impl Zeroize for SecretVec {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
impl ZeroizeOnDrop for SecretVec {}
impl SecretVec {
#[must_use]
pub fn new(bytes: Vec<u8>) -> Self {
Self(Zeroizing::new(bytes))
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn into_bytes(mut self) -> Vec<u8> {
std::mem::take(&mut *self.0)
}
}
impl AsRef<[u8]> for SecretVec {
fn as_ref(&self) -> &[u8] {
self.0.as_slice()
}
}
impl AsMut<[u8]> for SecretVec {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut_slice()
}
}
impl Clone for SecretVec {
fn clone(&self) -> Self {
Self::new(self.as_ref().to_vec())
}
}
impl fmt::Debug for SecretVec {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SecretVec")
.field("len", &self.len())
.field("bytes", &"[REDACTED]")
.finish()
}
}
impl From<Vec<u8>> for SecretVec {
fn from(value: Vec<u8>) -> Self {
Self::new(value)
}
}
const SCRUB_STACK_BYTES: usize = 32 * 1024;
#[inline(never)]
pub fn scrub_stack() {
let mut area = std::mem::MaybeUninit::<[u8; SCRUB_STACK_BYTES]>::uninit();
unsafe { std::ptr::write_bytes(area.as_mut_ptr().cast::<u8>(), 0, SCRUB_STACK_BYTES) };
std::hint::black_box(&mut area);
std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}