diff --git a/Cargo.toml b/Cargo.toml index fc645d1..4dbc6d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,10 +12,13 @@ categories = ["network-programming", "data-structures", "cryptography"] [features] default = ["alloc"] -alloc = [] +alloc = ["dep:zeroize"] std = ["alloc"] web = ["web-time"] +[dependencies] +zeroize = { version = "1", optional = true } + [target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dev-dependencies] crabgrind = "=0.1.9" # compatible with valgrind package on GHA ubuntu-latest diff --git a/src/lib.rs b/src/lib.rs index 04237f7..c062f10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -131,6 +131,17 @@ pub enum PrivateKeyDer<'a> { Pkcs8(PrivatePkcs8KeyDer<'a>), } +#[cfg(feature = "alloc")] +impl zeroize::Zeroize for PrivateKeyDer<'static> { + fn zeroize(&mut self) { + match self { + Self::Pkcs1(key) => key.zeroize(), + Self::Sec1(key) => key.zeroize(), + Self::Pkcs8(key) => key.zeroize(), + } + } +} + impl PrivateKeyDer<'_> { /// Clone the private key to a `'static` value #[cfg(feature = "alloc")] @@ -313,6 +324,13 @@ impl PrivatePkcs1KeyDer<'_> { } } +#[cfg(feature = "alloc")] +impl zeroize::Zeroize for PrivatePkcs1KeyDer<'static> { + fn zeroize(&mut self) { + self.0 .0.zeroize() + } +} + #[cfg(feature = "alloc")] impl PemObjectFilter for PrivatePkcs1KeyDer<'static> { const KIND: SectionKind = SectionKind::RsaPrivateKey; @@ -373,6 +391,13 @@ impl PrivateSec1KeyDer<'_> { } } +#[cfg(feature = "alloc")] +impl zeroize::Zeroize for PrivateSec1KeyDer<'static> { + fn zeroize(&mut self) { + self.0 .0.zeroize() + } +} + #[cfg(feature = "alloc")] impl PemObjectFilter for PrivateSec1KeyDer<'static> { const KIND: SectionKind = SectionKind::EcPrivateKey; @@ -434,6 +459,13 @@ impl PrivatePkcs8KeyDer<'_> { } } +#[cfg(feature = "alloc")] +impl zeroize::Zeroize for PrivatePkcs8KeyDer<'static> { + fn zeroize(&mut self) { + self.0 .0.zeroize() + } +} + #[cfg(feature = "alloc")] impl PemObjectFilter for PrivatePkcs8KeyDer<'static> { const KIND: SectionKind = SectionKind::PrivateKey; @@ -1002,6 +1034,16 @@ impl BytesInner<'_> { } } +#[cfg(feature = "alloc")] +impl zeroize::Zeroize for BytesInner<'static> { + fn zeroize(&mut self) { + match self { + BytesInner::Owned(vec) => vec.zeroize(), + BytesInner::Borrowed(_) => (), + } + } +} + impl AsRef<[u8]> for BytesInner<'_> { fn as_ref(&self) -> &[u8] { match &self {