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 27, 2024
1 parent 3c3e984 commit db6b565
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 59 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.3.0" }
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
8 changes: 5 additions & 3 deletions rcgen/src/csr.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[cfg(feature = "x509-parser")]
use crate::{DistinguishedName, Error, SanType};
#[cfg(feature = "x509-parser")]
use pki_types::CertificateSigningRequestDer;
use std::hash::Hash;

use crate::{CertificateParams, PublicKeyData, SignatureAlgorithm};
Expand Down Expand Up @@ -36,17 +38,17 @@ impl CertificateSigningRequestParams {
#[cfg(all(feature = "pem", feature = "x509-parser"))]
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let csr = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificationRequest))?;
Self::from_der(csr.contents())
Self::from_der(&csr.contents().into())
}

/// Parse a certificate signing request from DER-encoded bytes
///
/// Currently, this only supports the `Subject Alternative Name` extension.
/// On encountering other extensions, this function will return an error.
#[cfg(feature = "x509-parser")]
pub fn from_der(csr: &[u8]) -> Result<Self, Error> {
pub fn from_der(csr: &CertificateSigningRequestDer<'_>) -> Result<Self, Error> {
use x509_parser::prelude::FromDer;
let csr = x509_parser::certification_request::X509CertificationRequest::from_der(csr)
let csr = x509_parser::certification_request::X509CertificationRequest::from_der(&csr)
.map_err(|_| Error::CouldNotParseCertificationRequest)?
.1;
csr.verify_signature().map_err(|_| Error::RingUnspecified)?;
Expand Down
60 changes: 36 additions & 24 deletions rcgen/src/key_pair.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[cfg(feature = "pem")]
use pem::Pem;
#[cfg(feature = "crypto")]
use pki_types::PrivatePkcs8KeyDer;
use std::fmt;
use yasna::DERWriter;

Expand Down Expand Up @@ -114,8 +116,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(der: &PrivatePkcs8KeyDer<'_>) -> Result<Self, Error> {
der.try_into()
}

/// Returns the key pair's signature algorithm
Expand All @@ -124,11 +126,15 @@ impl KeyPair {
}

/// Parses the key pair from the ASCII PEM format
///
/// The key must be a DER-encoded plaintext private key; as specified in PKCS #8/RFC 5958;
///
/// Appears as "PRIVATE KEY" in PEM files
#[cfg(all(feature = "pem", feature = "crypto"))]
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 @@ -143,6 +149,9 @@ impl KeyPair {
/// Obtains the key pair from a DER formatted key
/// using the specified [`SignatureAlgorithm`]
///
/// The key must be a DER-encoded plaintext private key; as specified in PKCS #8/RFC 5958;
///
/// Appears as "PRIVATE KEY" in PEM files
/// Same as [from_pem_and_sign_algo](Self::from_pem_and_sign_algo).
#[cfg(all(feature = "pem", feature = "crypto"))]
pub fn from_pem_and_sign_algo(
Expand All @@ -151,7 +160,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 @@ -165,37 +177,36 @@ impl KeyPair {
/// specify the `SignatureAlgorithm`.
#[cfg(feature = "crypto")]
pub fn from_der_and_sign_algo(
pkcs8: &[u8],
der: &PrivatePkcs8KeyDer<'_>,
alg: &'static SignatureAlgorithm,
) -> Result<Self, Error> {
let rng = &SystemRandom::new();
let pkcs8_vec = pkcs8.to_vec();

let serialized_der = der.secret_pkcs8_der().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 @@ -204,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 @@ -350,29 +362,29 @@ impl KeyPair {
}

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

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

#[cfg(feature = "crypto")]
impl TryFrom<Vec<u8>> for KeyPair {
impl TryFrom<PrivatePkcs8KeyDer<'_>> 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: PrivatePkcs8KeyDer<'_>) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(&private_key)?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8,
serialized_der: private_key.secret_pkcs8_der().into(),
})
}
}
Expand Down
24 changes: 15 additions & 9 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, CertificateSigningRequestDer};
#[cfg(feature = "crypto")]
use ring_like::digest;
use std::collections::HashMap;
Expand Down Expand Up @@ -82,7 +83,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 @@ -663,7 +664,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(&certificate.contents().into())
}

/// Parses an existing ca certificate from the DER format.
Expand All @@ -681,8 +682,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 @@ -1251,7 +1252,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 @@ -1270,6 +1271,7 @@ impl CertificateParams {
Ok(())
})
})
.map(CertificateDer::from)
}
}

Expand Down Expand Up @@ -1691,13 +1693,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<'static> {
&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 All @@ -1709,7 +1711,10 @@ impl Certificate {
/// should not call `serialize_request_der` and then `serialize_request_pem`. This will
/// result in two different CSRs. Instead call only `serialize_request_pem` and base64
/// decode the inner content to get the DER encoded CSR using a library like `pem`.
pub fn serialize_request_der(&self, subject_key: &KeyPair) -> Result<Vec<u8>, Error> {
pub fn serialize_request_der(
&self,
subject_key: &KeyPair,
) -> Result<CertificateSigningRequestDer<'static>, Error> {
yasna::try_construct_der(|writer| {
writer.write_sequence(|writer| {
let cert_data = yasna::try_construct_der(|writer| {
Expand All @@ -1726,6 +1731,7 @@ impl Certificate {
Ok(())
})
})
.map(CertificateSigningRequestDer::from)
}
/// Generate and serialize a certificate signing request (CSR) in binary DER format.
///
Expand All @@ -1740,7 +1746,7 @@ impl Certificate {
#[cfg(feature = "pem")]
pub fn serialize_request_pem(&self, subject_key: &KeyPair) -> Result<String, Error> {
let contents = self.serialize_request_der(subject_key)?;
let p = Pem::new("CERTIFICATE REQUEST", contents);
let p = Pem::new("CERTIFICATE REQUEST", contents.to_vec());
Ok(pem::encode_config(&p, ENCODE_CONFIG))
}
}
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
Loading

0 comments on commit db6b565

Please sign in to comment.