Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor KeyPair constructor #170

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
## Unreleased

- Rename `RcGenError` to `Error` to avoid stuttering when used fully-qualified via `rcgen::`.
- Remove `TryFrom<[u8]>` and `TryFrom<Vec<u8>>` for `KeyPair` in favor of the more descriptive `KeyPair::from_der`.

## Release 0.11.3 - October 1, 2023

Expand Down
2 changes: 1 addition & 1 deletion examples/rsa-irc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let bits = 2048;
let private_key = RsaPrivateKey::new(&mut rng, bits)?;
let private_key_der = private_key.to_pkcs8_der()?;
let key_pair = rcgen::KeyPair::try_from(private_key_der.as_bytes()).unwrap();
let key_pair = rcgen::KeyPair::from_der(private_key_der.as_bytes()).unwrap();
params.key_pair = Some(key_pair);

let cert = Certificate::from_params(params)?;
Expand Down
178 changes: 98 additions & 80 deletions src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use pem::Pem;
use ring::rand::SystemRandom;
use ring::signature::KeyPair as RingKeyPair;
use ring::signature::{self, EcdsaKeyPair, Ed25519KeyPair, RsaEncoding, RsaKeyPair};
use std::convert::TryFrom;
use std::fmt;
use yasna::DERWriter;

Expand Down Expand Up @@ -56,7 +55,7 @@ impl KeyPair {
///
/// Equivalent to using the [`TryFrom`] implementation.
pub fn from_der(der: &[u8]) -> Result<Self, Error> {
Ok(der.try_into()?)
Ok(KeyPair::guess_kind_from_der(der)?)
}
/// Returns the key pair's signature algorithm
pub fn algorithm(&self) -> &'static SignatureAlgorithm {
Expand All @@ -67,7 +66,7 @@ impl KeyPair {
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)?;
let private_key_der: &[_] = private_key.contents();
Ok(private_key_der.try_into()?)
Ok(KeyPair::guess_kind_from_der(private_key_der)?)
}

/// Obtains the key pair from a raw public key and a remote private key
Expand Down Expand Up @@ -106,65 +105,110 @@ impl KeyPair {
pkcs8: &[u8],
alg: &'static SignatureAlgorithm,
) -> Result<Self, Error> {
let pkcs8_vec = pkcs8.to_vec();
if alg == &PKCS_ED25519 {
return Ok(Self::pkcs_ed25519(pkcs8)?);
}
if alg == &PKCS_ECDSA_P256_SHA256 {
return Ok(Self::pkcs_ecdsa_p256_sha256(pkcs8)?);
}
if alg == &PKCS_ECDSA_P384_SHA384 {
return Ok(Self::pkcs_ecdsa_p384_sha384(pkcs8)?);
}
if alg == &PKCS_RSA_SHA256 {
return Ok(Self::pkcs_rsa_sha256(pkcs8)?);
}
if alg == &PKCS_RSA_SHA384 {
return Ok(Self::pkcs_rsa_sha384(pkcs8)?);
}
if alg == &PKCS_RSA_SHA512 {
return Ok(Self::pkcs_rsa_sha512(pkcs8)?);
}
if alg == &PKCS_RSA_PSS_SHA256 {
return Ok(Self::pkcs_rsa_pss_sha256(pkcs8)?);
}

let kind = if alg == &PKCS_ED25519 {
KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)?)
} else if alg == &PKCS_ECDSA_P256_SHA256 {
KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(
panic!("Unknown SignatureAlgorithm specified!")
}

pub(crate) fn guess_kind_from_der(der: &[u8]) -> Result<KeyPair, Error> {
if let Ok(kp) = Self::pkcs_ed25519(der) {
return Ok(kp);
}

if let Ok(kp) = Self::pkcs_ecdsa_p256_sha256(der) {
return Ok(kp);
}

if let Ok(kp) = Self::pkcs_ecdsa_p384_sha384(der) {
return Ok(kp);
}

if let Ok(kp) = Self::pkcs_rsa_sha256(der) {
return Ok(kp);
}

return Err(Error::CouldNotParseKeyPair);
}

fn pkcs_ed25519(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(der)?),
alg: &PKCS_ED25519,
serialized_der: der.to_vec(),
})
}

fn pkcs_ecdsa_p256_sha256(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(
&signature::ECDSA_P256_SHA256_ASN1_SIGNING,
pkcs8,
)?)
} else if alg == &PKCS_ECDSA_P384_SHA384 {
KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(
der,
)?),
alg: &PKCS_ECDSA_P256_SHA256,
serialized_der: der.to_vec(),
})
}

fn pkcs_ecdsa_p384_sha384(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(
&signature::ECDSA_P384_SHA384_ASN1_SIGNING,
pkcs8,
)?)
} else if alg == &PKCS_RSA_SHA256 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256)
} else if alg == &PKCS_RSA_SHA384 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA384)
} else if alg == &PKCS_RSA_SHA512 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA512)
} else if alg == &PKCS_RSA_PSS_SHA256 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PSS_SHA256)
} else {
panic!("Unknown SignatureAlgorithm specified!");
};
der,
)?),
alg: &PKCS_ECDSA_P384_SHA384,
serialized_der: der.to_vec(),
})
}

fn pkcs_rsa_sha256(der: &[u8]) -> Result<KeyPair, Error> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remove these functions in favour of the old state which assigned kind? This saved us a lot of repetitive code.

Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8_vec,
kind: KeyPairKind::Rsa(RsaKeyPair::from_pkcs8(der)?, &signature::RSA_PKCS1_SHA256),
alg: &PKCS_RSA_SHA256,
serialized_der: der.to_vec(),
})
}

pub(crate) fn from_raw(
pkcs8: &[u8],
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), Error> {
let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
(KeyPairKind::Ed(edkp), &PKCS_ED25519)
} else if let Ok(eckp) =
EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8)
{
(KeyPairKind::Ec(eckp), &PKCS_ECDSA_P256_SHA256)
} else if let Ok(eckp) =
EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, pkcs8)
{
(KeyPairKind::Ec(eckp), &PKCS_ECDSA_P384_SHA384)
} else if let Ok(rsakp) = RsaKeyPair::from_pkcs8(pkcs8) {
(
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256),
&PKCS_RSA_SHA256,
)
} else {
return Err(Error::CouldNotParseKeyPair);
};
Ok((kind, alg))
fn pkcs_rsa_pss_sha256(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Rsa(RsaKeyPair::from_pkcs8(der)?, &signature::RSA_PSS_SHA256),
alg: &PKCS_RSA_PSS_SHA256,
serialized_der: der.to_vec(),
})
}

fn pkcs_rsa_sha384(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Rsa(RsaKeyPair::from_pkcs8(der)?, &signature::RSA_PKCS1_SHA384),
alg: &PKCS_RSA_SHA384,
serialized_der: der.to_vec(),
})
}
fn pkcs_rsa_sha512(der: &[u8]) -> Result<KeyPair, Error> {
Ok(KeyPair {
kind: KeyPairKind::Rsa(RsaKeyPair::from_pkcs8(der)?, &signature::RSA_PKCS1_SHA512),
alg: &PKCS_RSA_SHA512,
serialized_der: der.to_vec(),
})
}
}

Expand All @@ -183,32 +227,6 @@ pub trait RemoteKeyPair {
fn algorithm(&self) -> &'static SignatureAlgorithm;
}

impl TryFrom<&[u8]> for KeyPair {
type Error = Error;

fn try_from(pkcs8: &[u8]) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8)?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8.to_vec(),
})
}
}

impl TryFrom<Vec<u8>> for KeyPair {
type Error = Error;

fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8,
})
}
}

impl KeyPair {
/// Generate a new random key pair for the specified signature algorithm
pub fn generate(alg: &'static SignatureAlgorithm) -> Result<Self, Error> {
Expand Down
8 changes: 3 additions & 5 deletions tests/botan.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#![cfg(feature = "x509-parser")]

use rcgen::DnValue;
use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa};
use rcgen::{
CertificateRevocationList, CertificateRevocationListParams, RevocationReason, RevokedCertParams,
};
use rcgen::{DnValue, KeyPair};
use rcgen::{KeyUsagePurpose, SerialNumber};
use time::{Duration, OffsetDateTime};

Expand Down Expand Up @@ -172,7 +172,6 @@ fn test_botan_separate_ca() {
#[cfg(feature = "x509-parser")]
#[test]
fn test_botan_imported_ca() {
use std::convert::TryInto;
let mut params = default_params();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca_cert = Certificate::from_params(params).unwrap();
Expand All @@ -182,7 +181,7 @@ fn test_botan_imported_ca() {
ca_cert.serialize_private_key_der(),
);

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let ca_key_pair = KeyPair::from_der(ca_key_der.as_slice()).unwrap();
let imported_ca_cert_params =
CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair).unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();
Expand All @@ -205,7 +204,6 @@ fn test_botan_imported_ca() {
#[cfg(feature = "x509-parser")]
#[test]
fn test_botan_imported_ca_with_printable_string() {
use std::convert::TryInto;
let mut params = default_params();
params.distinguished_name.push(
DnType::CountryName,
Expand All @@ -219,7 +217,7 @@ fn test_botan_imported_ca_with_printable_string() {
ca_cert.serialize_private_key_der(),
);

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let ca_key_pair = KeyPair::from_der(ca_key_der.as_slice()).unwrap();
let imported_ca_cert_params =
CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair).unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();
Expand Down
6 changes: 2 additions & 4 deletions tests/webpki.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,6 @@ fn test_webpki_separate_ca_name_constraints() {
#[cfg(feature = "x509-parser")]
#[test]
fn test_webpki_imported_ca() {
use std::convert::TryInto;
let mut params = util::default_params();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca_cert = Certificate::from_params(params).unwrap();
Expand All @@ -414,7 +413,7 @@ fn test_webpki_imported_ca() {
ca_cert.serialize_private_key_der(),
);

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let ca_key_pair = KeyPair::from_der(ca_key_der.as_slice()).unwrap();
let imported_ca_cert_params =
CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair).unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();
Expand Down Expand Up @@ -443,7 +442,6 @@ fn test_webpki_imported_ca() {
#[cfg(feature = "x509-parser")]
#[test]
fn test_webpki_imported_ca_with_printable_string() {
use std::convert::TryInto;
let mut params = util::default_params();
params.distinguished_name.push(
DnType::CountryName,
Expand All @@ -457,7 +455,7 @@ fn test_webpki_imported_ca_with_printable_string() {
ca_cert.serialize_private_key_der(),
);

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let ca_key_pair = KeyPair::from_der(ca_key_der.as_slice()).unwrap();
let imported_ca_cert_params =
CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair).unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();
Expand Down