domani/src/domain/acme/private_key.rs
2023-05-20 14:34:45 +02:00

57 lines
1.6 KiB
Rust

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<u8>);
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<Self, Self::Err> {
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<openssl::pkey::Private>> for PrivateKey {
type Error = openssl::error::ErrorStack;
fn try_from(k: &openssl::pkey::PKeyRef<openssl::pkey::Private>) -> Result<Self, Self::Error> {
Ok(PrivateKey(k.private_key_to_der()?))
}
}
impl TryFrom<&PrivateKey> for openssl::pkey::PKey<openssl::pkey::Private> {
type Error = openssl::error::ErrorStack;
fn try_from(k: &PrivateKey) -> Result<Self, Self::Error> {
openssl::pkey::PKey::private_key_from_der(&k.0)
}
}
impl From<PrivateKey> for rustls::PrivateKey {
fn from(k: PrivateKey) -> Self {
rustls::PrivateKey(k.0)
}
}