Skip to content

Commit

Permalink
Add support for the zeroize crate
Browse files Browse the repository at this point in the history
  • Loading branch information
jarhodes314 committed Feb 5, 2025
1 parent be3a4c4 commit e7c38ac
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
42 changes: 42 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit e7c38ac

Please sign in to comment.