Skip to content

Commit

Permalink
use pki types in function that parse der
Browse files Browse the repository at this point in the history
  • Loading branch information
Tudyx committed Feb 12, 2024
1 parent 747b5d8 commit 8d9acc6
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 64 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ resolver = "2"

[workspace.dependencies]
pem = "3.0.2"
pki-types = { package = "rustls-pki-types", version = "1" }
rand = "0.8"
ring = "0.17"
x509-parser = "0.15.1"
Expand Down
6 changes: 3 additions & 3 deletions rcgen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,26 @@ pem = { workspace = true, optional = true }
time = { version = "0.3.6", default-features = false }
x509-parser = { workspace = true, features = ["verify"], optional = true }
zeroize = { version = "1.2", optional = true }
pki-types = { workspace = true }

[features]
default = ["crypto", "pem", "ring"]
crypto = []
aws_lc_rs = ["crypto", "dep:aws-lc-rs"]
ring = ["crypto", "dep:ring"]


[package.metadata.docs.rs]
features = ["x509-parser"]

[package.metadata.cargo_check_external_types]
allowed_external_types = [
"time::offset_date_time::OffsetDateTime",
"zeroize::Zeroize"
"zeroize::Zeroize",
"rustls_pki_types::*"
]

[dev-dependencies]
openssl = "0.10"
pki-types = { package = "rustls-pki-types", version = "1" }
x509-parser = { workspace = true, features = ["verify"] }
rustls-webpki = { version = "0.102", features = ["std"] }
botan = { version = "0.10", features = ["vendored"] }
Expand Down
4 changes: 3 additions & 1 deletion rcgen/examples/rsa-irc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ 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(pki_types::PrivatePkcs8KeyDer::from(
private_key_der.as_bytes(),
))?;

let cert = Certificate::generate_self_signed(params, &key_pair)?;
let pem_serialized = cert.pem();
Expand Down
67 changes: 33 additions & 34 deletions rcgen/src/key_pair.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#[cfg(feature = "pem")]
use pem::Pem;
#[cfg(feature = "crypto")]
use pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
#[cfg(feature = "crypto")]
use std::convert::TryFrom;
use std::fmt;
use yasna::DERWriter;
Expand Down Expand Up @@ -116,8 +118,8 @@ impl KeyPair {
///
/// Equivalent to using the [`TryFrom`] implementation.
#[cfg(feature = "crypto")]
pub fn from_der(der: &[u8]) -> Result<Self, Error> {
Ok(der.try_into()?)
pub fn from_der<'a>(der: impl Into<PrivateKeyDer<'a>>) -> Result<Self, Error> {
der.into().try_into()
}

/// Returns the key pair's signature algorithm
Expand All @@ -130,7 +132,7 @@ impl KeyPair {
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)._err()?;
let private_key_der: &[_] = private_key.contents();
Ok(private_key_der.try_into()?)
Self::from_der(PrivatePkcs8KeyDer::from(private_key_der))
}

/// Obtains the key pair from a raw public key and a remote private key
Expand All @@ -153,7 +155,10 @@ impl KeyPair {
) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)._err()?;
let private_key_der: &[_] = private_key.contents();
Ok(Self::from_der_and_sign_algo(private_key_der, alg)?)
Ok(Self::from_der_and_sign_algo(
PrivatePkcs8KeyDer::from(private_key_der),
alg,
)?)
}

/// Obtains the key pair from a DER formatted key
Expand All @@ -166,38 +171,42 @@ impl KeyPair {
/// same der key. In that instance, you can use this function to precisely
/// specify the `SignatureAlgorithm`.
#[cfg(feature = "crypto")]
pub fn from_der_and_sign_algo(
pkcs8: &[u8],
pub fn from_der_and_sign_algo<'a>(
der: impl Into<PrivateKeyDer<'a>>,
alg: &'static SignatureAlgorithm,
) -> Result<Self, Error> {
let rng = &SystemRandom::new();
let pkcs8_vec = pkcs8.to_vec();
let serialized_der = match &der.into() {
PrivateKeyDer::Pkcs8(private_key) => Ok(private_key.secret_pkcs8_der()),
_ => Err(Error::CouldNotParseKeyPair),
}?
.to_vec();

let kind = if alg == &PKCS_ED25519 {
KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)._err()?)
KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(&serialized_der)._err()?)
} else if alg == &PKCS_ECDSA_P256_SHA256 {
KeyPairKind::Ec(ecdsa_from_pkcs8(
&signature::ECDSA_P256_SHA256_ASN1_SIGNING,
pkcs8,
&serialized_der,
rng,
)?)
} else if alg == &PKCS_ECDSA_P384_SHA384 {
KeyPairKind::Ec(ecdsa_from_pkcs8(
&signature::ECDSA_P384_SHA384_ASN1_SIGNING,
pkcs8,
&serialized_der,
rng,
)?)
} else if alg == &PKCS_RSA_SHA256 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256)
} else if alg == &PKCS_RSA_SHA384 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA384)
} else if alg == &PKCS_RSA_SHA512 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA512)
} else if alg == &PKCS_RSA_PSS_SHA256 {
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
KeyPairKind::Rsa(rsakp, &signature::RSA_PSS_SHA256)
} else {
panic!("Unknown SignatureAlgorithm specified!");
Expand All @@ -206,14 +215,15 @@ impl KeyPair {
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8_vec,
serialized_der,
})
}

#[cfg(feature = "crypto")]
pub(crate) fn from_raw(
pkcs8: &[u8],
pkcs8: &PrivatePkcs8KeyDer,
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), Error> {
let pkcs8 = pkcs8.secret_pkcs8_der();
let rng = SystemRandom::new();
let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
(KeyPairKind::Ed(edkp), &PKCS_ED25519)
Expand Down Expand Up @@ -352,29 +362,18 @@ impl KeyPair {
}

#[cfg(feature = "crypto")]
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(),
})
}
}

#[cfg(feature = "crypto")]
impl TryFrom<Vec<u8>> for KeyPair {
impl TryFrom<PrivateKeyDer<'_>> for KeyPair {
type Error = Error;

fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
fn try_from(private_key: PrivateKeyDer) -> Result<KeyPair, Error> {
let (kind, alg) = match &private_key {
PrivateKeyDer::Pkcs8(private_key) => KeyPair::from_raw(private_key),
_ => Err(Error::CouldNotParseKeyPair),
}?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8,
serialized_der: private_key.secret_der().into(),
})
}
}
Expand Down
16 changes: 9 additions & 7 deletions rcgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ println!("{}", key_pair.serialize_pem());

#[cfg(feature = "pem")]
use pem::Pem;
use pki_types::CertificateDer;
#[cfg(feature = "crypto")]
use ring_like::digest;
use std::collections::HashMap;
Expand Down Expand Up @@ -83,7 +84,7 @@ pub struct CertifiedKey {
pub struct Certificate {
params: CertificateParams,
subject_public_key_info: Vec<u8>,
der: Vec<u8>,
der: CertificateDer<'static>,
}

/**
Expand Down Expand Up @@ -664,7 +665,7 @@ impl CertificateParams {
#[cfg(all(feature = "pem", feature = "x509-parser"))]
pub fn from_ca_cert_pem(pem_str: &str) -> Result<Self, Error> {
let certificate = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificate))?;
Self::from_ca_cert_der(certificate.contents())
Self::from_ca_cert_der(&CertificateDer::from(certificate.contents()))
}

/// Parses an existing ca certificate from the DER format.
Expand All @@ -682,8 +683,8 @@ impl CertificateParams {
/// for the presence of the `BasicConstraints` extension, or perform any other
/// validation.
#[cfg(feature = "x509-parser")]
pub fn from_ca_cert_der(ca_cert: &[u8]) -> Result<Self, Error> {
let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
pub fn from_ca_cert_der(ca_cert: &CertificateDer<'_>) -> Result<Self, Error> {
let (_remainder, x509) = x509_parser::parse_x509_certificate(&ca_cert)
.or(Err(Error::CouldNotParseCertificate))?;

let dn = DistinguishedName::from_name(&x509.tbs_certificate.subject)?;
Expand Down Expand Up @@ -1252,7 +1253,7 @@ impl CertificateParams {
pub_key: &K,
issuer: &KeyPair,
issuer_name: &DistinguishedName,
) -> Result<Vec<u8>, Error> {
) -> Result<CertificateDer<'static>, Error> {
yasna::try_construct_der(|writer| {
writer.write_sequence(|writer| {
let tbs_cert_list_serialized = yasna::try_construct_der(|writer| {
Expand All @@ -1271,6 +1272,7 @@ impl CertificateParams {
Ok(())
})
})
.map(CertificateDer::from)
}
}

Expand Down Expand Up @@ -1692,13 +1694,13 @@ impl Certificate {
.derive(&self.subject_public_key_info)
}
/// Get the certificate in DER encoded format.
pub fn der(&self) -> &[u8] {
pub fn der(&self) -> &CertificateDer {
&self.der
}
/// Get the certificate in PEM encoded format.
#[cfg(feature = "pem")]
pub fn pem(&self) -> String {
pem::encode_config(&Pem::new("CERTIFICATE", self.der()), ENCODE_CONFIG)
pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG)
}
/// Generate and serialize a certificate signing request (CSR) in binary DER format.
///
Expand Down
5 changes: 3 additions & 2 deletions rcgen/tests/botan.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![cfg(all(feature = "crypto", feature = "x509-parser"))]

use pki_types::CertificateDer;
use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa};
use rcgen::{
CertificateRevocationList, CertificateRevocationListParams, RevocationReason, RevokedCertParams,
Expand All @@ -17,12 +18,12 @@ fn default_params() -> (CertificateParams, KeyPair) {
(params, key_pair)
}

fn check_cert(cert_der: &[u8], cert: &Certificate) {
fn check_cert(cert_der: &CertificateDer<'_>, cert: &Certificate) {
println!("{}", cert.pem());
check_cert_ca(cert_der, cert, cert_der);
}

fn check_cert_ca(cert_der: &[u8], _cert: &Certificate, ca_der: &[u8]) {
fn check_cert_ca(cert_der: &CertificateDer<'_>, _cert: &Certificate, ca_der: &CertificateDer<'_>) {
println!(
"botan version: {}",
botan::Version::current().unwrap().string
Expand Down
18 changes: 7 additions & 11 deletions rcgen/tests/webpki.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fn sign_msg_rsa(key_pair: &KeyPair, msg: &[u8], encoding: &'static dyn RsaEncodi
}

fn check_cert<'a, 'b>(
cert_der: &[u8],
cert_der: &CertificateDer<'_>,
cert: &'a Certificate,
cert_key: &'a KeyPair,
alg: &dyn SignatureVerificationAlgorithm,
Expand All @@ -68,18 +68,16 @@ fn check_cert<'a, 'b>(
}

fn check_cert_ca<'a, 'b>(
cert_der: &[u8],
cert_der: &CertificateDer<'_>,
cert_key: &'a KeyPair,
ca_der: &[u8],
ca_der: &CertificateDer<'_>,
cert_alg: &dyn SignatureVerificationAlgorithm,
ca_alg: &dyn SignatureVerificationAlgorithm,
sign_fn: impl FnOnce(&'a KeyPair, &'b [u8]) -> Vec<u8>,
) {
let ca_der = CertificateDer::from(ca_der);
let trust_anchor = anchor_from_trusted_cert(&ca_der).unwrap();
let trust_anchor = anchor_from_trusted_cert(ca_der).unwrap();
let trust_anchor_list = &[trust_anchor];
let cert_der = CertificateDer::from(cert_der);
let end_entity_cert = EndEntityCert::try_from(&cert_der).unwrap();
let end_entity_cert = EndEntityCert::try_from(cert_der).unwrap();

// Set time to Jan 10, 2004
let time = UnixTime::since_unix_epoch(StdDuration::from_secs(0x40_00_00_00));
Expand Down Expand Up @@ -590,11 +588,9 @@ fn test_webpki_crl_revoke() {
let ee = Certificate::generate(ee, &ee_key, &issuer, &issuer_key).unwrap();

// Set up webpki's verification requirements.
let ca_der = CertificateDer::from(issuer.der());
let trust_anchor = anchor_from_trusted_cert(&ca_der).unwrap();
let trust_anchor = anchor_from_trusted_cert(issuer.der()).unwrap();
let trust_anchor_list = &[trust_anchor];
let ee_der = CertificateDer::from(ee.der());
let end_entity_cert = EndEntityCert::try_from(&ee_der).unwrap();
let end_entity_cert = EndEntityCert::try_from(ee.der()).unwrap();
let unix_time = 0x40_00_00_00;
let time = UnixTime::since_unix_epoch(StdDuration::from_secs(unix_time));

Expand Down
1 change: 1 addition & 0 deletions rustls-cert-gen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ bpaf = { version = "0.9.5", features = ["derive"] }
pem = { workspace = true }
ring = { workspace = true }
rand = { workspace = true }
pki-types = { workspace = true }
anyhow = "1.0.75"

[dev-dependencies]
Expand Down
Loading

0 comments on commit 8d9acc6

Please sign in to comment.