From 369f87f657778822337ac8be88987b702fbc58c5 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sat, 25 Apr 2026 09:51:40 -0600 Subject: [PATCH] pkcs8: impl `Decode`/`EncodePrivateKey` for `PrivateKeyInfoOwned` --- pkcs8/src/lib.rs | 2 +- pkcs8/src/private_key_info.rs | 42 ++++++++++++++++++++++++++++------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/pkcs8/src/lib.rs b/pkcs8/src/lib.rs index 0ebde2cd0..6153e67dd 100644 --- a/pkcs8/src/lib.rs +++ b/pkcs8/src/lib.rs @@ -89,7 +89,7 @@ pub use spki::{ #[cfg(feature = "alloc")] pub use { - crate::{private_key_info::PrivateKeyInfoOwned, traits::EncodePrivateKey}, + crate::{private_key_info::allocating::PrivateKeyInfoOwned, traits::EncodePrivateKey}, der::{Document, SecretDocument}, spki::EncodePublicKey, }; diff --git a/pkcs8/src/private_key_info.rs b/pkcs8/src/private_key_info.rs index 6b68e3524..09d96045f 100644 --- a/pkcs8/src/private_key_info.rs +++ b/pkcs8/src/private_key_info.rs @@ -377,10 +377,6 @@ where /// [`PrivateKeyInfo`] with [`AnyRef`] algorithm parameters, and `&[u8]` key. pub type PrivateKeyInfoRef<'a> = PrivateKeyInfo, &'a OctetStringRef, BitStringRef<'a>>; -/// [`PrivateKeyInfo`] with [`Any`] algorithm parameters, and `Box<[u8]>` key. -#[cfg(feature = "alloc")] -pub type PrivateKeyInfoOwned = PrivateKeyInfo; - /// [`BitStringLike`] marks object that will act like a `BitString`. /// /// It will allow to get a [`BitStringRef`] that points back to the underlying bytes. @@ -396,15 +392,39 @@ impl BitStringLike for BitStringRef<'_> { } #[cfg(feature = "alloc")] -mod allocating { +pub(crate) mod allocating { use super::*; + use crate::{DecodePrivateKey, EncodePrivateKey}; use alloc::borrow::ToOwned; use core::borrow::Borrow; use der::referenced::*; - impl BitStringLike for BitString { - fn as_bit_string(&self) -> BitStringRef<'_> { - BitStringRef::from(self) + #[cfg(feature = "pem")] + use der::DecodePem; + + /// [`PrivateKeyInfo`] with [`Any`] algorithm parameters, and `Box<[u8]>` key. + pub type PrivateKeyInfoOwned = PrivateKeyInfo; + + impl DecodePrivateKey for PrivateKeyInfoOwned { + fn from_pkcs8_der(bytes: &[u8]) -> Result { + Ok(Self::from_der(bytes)?) + } + + #[cfg(feature = "pem")] + fn from_pkcs8_pem(pem: &str) -> Result { + Ok(Self::from_pem(pem)?) + } + } + + impl EncodePrivateKey for PrivateKeyInfoOwned { + fn to_pkcs8_der(&self) -> Result { + self.try_into() + } + } + + impl EncodePrivateKey for PrivateKeyInfoRef<'_> { + fn to_pkcs8_der(&self) -> Result { + self.try_into() } } @@ -429,4 +449,10 @@ mod allocating { } } } + + impl BitStringLike for BitString { + fn as_bit_string(&self) -> BitStringRef<'_> { + BitStringRef::from(self) + } + } }