From 46bf6260b97a2fc723c5f284005aca786c91db4b Mon Sep 17 00:00:00 2001 From: Roman Lebedev Date: Wed, 24 Dec 2025 20:55:21 +0300 Subject: [PATCH] Implement `From for PrivateKeyDer<'static>` The "obvious" and safe way to go from `KeyPair` to `PrivateKeyDer` seems to round-tripping via PEM: ``` rustls::pki_types::PrivateKeyDer::from_pem_slice( signing_key.serialize_pem().as_bytes(), ) ``` But `rcgen::key_pair::KeyPair::serialized_der()` is ``` /// Returns a reference to the serialized key pair (including the private key) /// in PKCS#8 format in DER ``` and `PrivateKeyDer` can be constructed from such a input. This avoids memory allocation and PEM roundtripping, both of which are optional features anyways, and this conversion is non-failing. --- rcgen/src/key_pair.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/rcgen/src/key_pair.rs b/rcgen/src/key_pair.rs index 839b049a..a1bc1a48 100644 --- a/rcgen/src/key_pair.rs +++ b/rcgen/src/key_pair.rs @@ -595,6 +595,20 @@ impl TryFrom<&PrivateKeyDer<'_>> for KeyPair { } } +#[cfg(feature = "crypto")] +impl From for PrivatePkcs8KeyDer<'static> { + fn from(val: KeyPair) -> Self { + val.serialize_der().into() + } +} + +#[cfg(feature = "crypto")] +impl From for PrivateKeyDer<'static> { + fn from(val: KeyPair) -> Self { + Self::from(PrivatePkcs8KeyDer::from(val)) + } +} + /// The key size used for RSA key generation #[cfg(all(feature = "crypto", feature = "aws_lc_rs"))] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]