use std::convert::{From, TryFrom}; use std::fmt; use std::str::FromStr; use serde_with::{DeserializeFromStr, SerializeDisplay}; #[derive(Debug, Clone, PartialEq, DeserializeFromStr, SerializeDisplay)] /// DER-encoded ASN.1 in either PKCS#8, PKCS#1, or Sec1 format, like rustls::PrivateKey. pub struct PrivateKey(Vec); impl PrivateKey { #[allow(clippy::new_without_default)] pub fn new() -> PrivateKey { acme2::gen_rsa_private_key(4096) .expect("RSA private key generated") .as_ref() .try_into() .expect("RSA private key converted to internal representation") } } impl FromStr for PrivateKey { type Err = pem::PemError; fn from_str(s: &str) -> Result { Ok(PrivateKey(pem::parse(s)?.into_contents())) } } impl fmt::Display for PrivateKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { pem::Pem::new("PRIVATE KEY", self.0.clone()).fmt(f) } } impl TryFrom<&openssl::pkey::PKeyRef> for PrivateKey { type Error = openssl::error::ErrorStack; fn try_from(k: &openssl::pkey::PKeyRef) -> Result { Ok(PrivateKey(k.private_key_to_der()?)) } } impl TryFrom<&PrivateKey> for openssl::pkey::PKey { type Error = openssl::error::ErrorStack; fn try_from(k: &PrivateKey) -> Result { openssl::pkey::PKey::private_key_from_der(&k.0) } } impl From for rustls::PrivateKey { fn from(k: PrivateKey) -> Self { rustls::PrivateKey(k.0) } }