Skip to content

Commit 0c5da82

Browse files
committed
use pki types to represent der encoded struct
1 parent f1f89ae commit 0c5da82

File tree

9 files changed

+116
-41
lines changed

9 files changed

+116
-41
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ resolver = "2"
44

55
[workspace.dependencies]
66
pem = "3.0.2"
7+
pki-types = { package = "rustls-pki-types", version = "1.3.0" }
78
rand = "0.8"
89
ring = "0.17"
910
x509-parser = "0.16"

rcgen/Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ aws-lc-rs = { version = "1.6.0", optional = true }
3030
yasna = { version = "0.5.2", features = ["time", "std"] }
3131
ring = { workspace = true, optional = true }
3232
pem = { workspace = true, optional = true }
33+
pki-types = { workspace = true }
3334
time = { version = "0.3.6", default-features = false }
3435
x509-parser = { workspace = true, features = ["verify"], optional = true }
3536
zeroize = { version = "1.2", optional = true }
@@ -48,7 +49,8 @@ features = ["x509-parser"]
4849
[package.metadata.cargo_check_external_types]
4950
allowed_external_types = [
5051
"time::offset_date_time::OffsetDateTime",
51-
"zeroize::Zeroize"
52+
"zeroize::Zeroize",
53+
"rustls_pki_types::*"
5254
]
5355

5456
[dev-dependencies]

rcgen/src/certificate.rs

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::str::FromStr;
33

44
#[cfg(feature = "pem")]
55
use pem::Pem;
6+
use pki_types::{CertificateDer, CertificateSigningRequestDer};
67
use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
78
use yasna::models::ObjectIdentifier;
89
use yasna::{DERWriter, Tag};
@@ -24,7 +25,7 @@ use crate::{
2425
pub struct Certificate {
2526
pub(crate) params: CertificateParams,
2627
subject_public_key_info: Vec<u8>,
27-
der: Vec<u8>,
28+
der: CertificateDer<'static>,
2829
}
2930

3031
impl Certificate {
@@ -117,13 +118,16 @@ impl Certificate {
117118
.derive(&self.subject_public_key_info)
118119
}
119120
/// Get the certificate in DER encoded format.
120-
pub fn der(&self) -> &[u8] {
121+
///
122+
/// As the return type implements `Deref<Target = [u8]>`, in can easily be saved
123+
/// to a file like a byte slice.
124+
pub fn der(&self) -> &CertificateDer<'static> {
121125
&self.der
122126
}
123127
/// Get the certificate in PEM encoded format.
124128
#[cfg(feature = "pem")]
125129
pub fn pem(&self) -> String {
126-
pem::encode_config(&Pem::new("CERTIFICATE", self.der()), ENCODE_CONFIG)
130+
pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG)
127131
}
128132
/// Generate and serialize a certificate signing request (CSR) in binary DER format.
129133
///
@@ -135,7 +139,13 @@ impl Certificate {
135139
/// should not call `serialize_request_der` and then `serialize_request_pem`. This will
136140
/// result in two different CSRs. Instead call only `serialize_request_pem` and base64
137141
/// decode the inner content to get the DER encoded CSR using a library like `pem`.
138-
pub fn serialize_request_der(&self, subject_key: &KeyPair) -> Result<Vec<u8>, Error> {
142+
///
143+
/// As the return type implements `Deref<Target = [u8]>`, in can easily be saved
144+
/// to a file like a byte slice.
145+
pub fn serialize_request_der(
146+
&self,
147+
subject_key: &KeyPair,
148+
) -> Result<CertificateSigningRequestDer<'static>, Error> {
139149
yasna::try_construct_der(|writer| {
140150
writer.write_sequence(|writer| {
141151
let cert_data = yasna::try_construct_der(|writer| {
@@ -152,6 +162,7 @@ impl Certificate {
152162
Ok(())
153163
})
154164
})
165+
.map(CertificateSigningRequestDer::from)
155166
}
156167
/// Generate and serialize a certificate signing request (CSR) in binary DER format.
157168
///
@@ -166,7 +177,7 @@ impl Certificate {
166177
#[cfg(feature = "pem")]
167178
pub fn serialize_request_pem(&self, subject_key: &KeyPair) -> Result<String, Error> {
168179
let contents = self.serialize_request_der(subject_key)?;
169-
let p = Pem::new("CERTIFICATE REQUEST", contents);
180+
let p = Pem::new("CERTIFICATE REQUEST", contents.to_vec());
170181
Ok(pem::encode_config(&p, ENCODE_CONFIG))
171182
}
172183
}
@@ -252,7 +263,7 @@ impl CertificateParams {
252263
#[cfg(all(feature = "pem", feature = "x509-parser"))]
253264
pub fn from_ca_cert_pem(pem_str: &str) -> Result<Self, Error> {
254265
let certificate = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificate))?;
255-
Self::from_ca_cert_der(certificate.contents())
266+
Self::from_ca_cert_der(&certificate.contents().into())
256267
}
257268

258269
/// Parses an existing ca certificate from the DER format.
@@ -269,8 +280,14 @@ impl CertificateParams {
269280
/// This function assumes the provided certificate is a CA. It will not check
270281
/// for the presence of the `BasicConstraints` extension, or perform any other
271282
/// validation.
283+
///
284+
/// You can use [`rustls_pemfile::certs`] to get the `ca_cert` input. If
285+
/// you have already a byte slice, just calling `into()` and take a reference
286+
/// will convert it to [`CertificateDer`].
287+
///
288+
/// [`rustls_pemfile::certs`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.certs.html
272289
#[cfg(feature = "x509-parser")]
273-
pub fn from_ca_cert_der(ca_cert: &[u8]) -> Result<Self, Error> {
290+
pub fn from_ca_cert_der(ca_cert: &CertificateDer<'_>) -> Result<Self, Error> {
274291
let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
275292
.or(Err(Error::CouldNotParseCertificate))?;
276293

@@ -835,12 +852,17 @@ impl CertificateParams {
835852
Ok(())
836853
})
837854
}
855+
856+
/// Generate and serialize a certificate signed by the given issuer.
857+
///
858+
/// As the return type implements `Deref<Target = [u8]>`, in can easily be saved
859+
/// to a file like a byte slice.
838860
pub(crate) fn serialize_der_with_signer<K: PublicKeyData>(
839861
&self,
840862
pub_key: &K,
841863
issuer: &KeyPair,
842864
issuer_name: &DistinguishedName,
843-
) -> Result<Vec<u8>, Error> {
865+
) -> Result<CertificateDer<'static>, Error> {
844866
yasna::try_construct_der(|writer| {
845867
writer.write_sequence(|writer| {
846868
let tbs_cert_list_serialized = yasna::try_construct_der(|writer| {
@@ -859,6 +881,7 @@ impl CertificateParams {
859881
Ok(())
860882
})
861883
})
884+
.map(CertificateDer::from)
862885
}
863886
}
864887

rcgen/src/csr.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#[cfg(feature = "x509-parser")]
22
use crate::{DistinguishedName, Error, SanType};
3+
#[cfg(feature = "x509-parser")]
4+
use pki_types::CertificateSigningRequestDer;
35
use std::hash::Hash;
46

57
use crate::{CertificateParams, PublicKeyData, SignatureAlgorithm};
@@ -36,15 +38,21 @@ impl CertificateSigningRequestParams {
3638
#[cfg(all(feature = "pem", feature = "x509-parser"))]
3739
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
3840
let csr = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificationRequest))?;
39-
Self::from_der(csr.contents())
41+
Self::from_der(&csr.contents().into())
4042
}
4143

4244
/// Parse a certificate signing request from DER-encoded bytes
4345
///
4446
/// Currently, this only supports the `Subject Alternative Name` extension.
4547
/// On encountering other extensions, this function will return an error.
48+
///
49+
/// You can use [`rustls_pemfile::csr`] to get the `csr` input. If
50+
/// you have already a byte slice, just calling `into()` and take a reference
51+
/// will convert it to [`CertificateSigningRequestDer`].
52+
///
53+
/// [`rustls_pemfile::csr`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.csr.html
4654
#[cfg(feature = "x509-parser")]
47-
pub fn from_der(csr: &[u8]) -> Result<Self, Error> {
55+
pub fn from_der(csr: &CertificateSigningRequestDer<'_>) -> Result<Self, Error> {
4856
use x509_parser::prelude::FromDer;
4957
let csr = x509_parser::certification_request::X509CertificationRequest::from_der(csr)
5058
.map_err(|_| Error::CouldNotParseCertificationRequest)?

rcgen/src/key_pair.rs

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#[cfg(feature = "pem")]
22
use pem::Pem;
3+
#[cfg(feature = "crypto")]
4+
use pki_types::PrivatePkcs8KeyDer;
35
use std::fmt;
46
use yasna::DERWriter;
57

@@ -158,8 +160,14 @@ impl KeyPair {
158160
/// Parses the key pair from the DER format
159161
///
160162
/// Equivalent to using the [`TryFrom`] implementation.
163+
///
164+
/// You can use [`rustls_pemfile::private_key`] to get the `der` input. If
165+
/// you have already a byte slice, just calling `into()` and take a reference
166+
/// will convert it to a [`PrivatePkcs8KeyDer`].
167+
///
168+
/// [`rustls_pemfile::private_key`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.private_key.html
161169
#[cfg(feature = "crypto")]
162-
pub fn from_der(der: &[u8]) -> Result<Self, Error> {
170+
pub fn from_der(der: &PrivatePkcs8KeyDer<'_>) -> Result<Self, Error> {
163171
der.try_into()
164172
}
165173

@@ -169,11 +177,15 @@ impl KeyPair {
169177
}
170178

171179
/// Parses the key pair from the ASCII PEM format
180+
///
181+
/// The key must be a DER-encoded plaintext private key; as specified in PKCS #8/RFC 5958;
182+
///
183+
/// Appears as "PRIVATE KEY" in PEM files.
172184
#[cfg(all(feature = "pem", feature = "crypto"))]
173185
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
174186
let private_key = pem::parse(pem_str)._err()?;
175187
let private_key_der: &[_] = private_key.contents();
176-
private_key_der.try_into()
188+
Self::from_der(&private_key_der.into())
177189
}
178190

179191
/// Obtains the key pair from a raw public key and a remote private key
@@ -188,6 +200,9 @@ impl KeyPair {
188200
/// Obtains the key pair from a DER formatted key
189201
/// using the specified [`SignatureAlgorithm`]
190202
///
203+
/// The key must be a DER-encoded plaintext private key; as specified in PKCS #8/RFC 5958;
204+
///
205+
/// Appears as "PRIVATE KEY" in PEM files
191206
/// Same as [from_pem_and_sign_algo](Self::from_pem_and_sign_algo).
192207
#[cfg(all(feature = "pem", feature = "crypto"))]
193208
pub fn from_pem_and_sign_algo(
@@ -196,7 +211,7 @@ impl KeyPair {
196211
) -> Result<Self, Error> {
197212
let private_key = pem::parse(pem_str)._err()?;
198213
let private_key_der: &[_] = private_key.contents();
199-
Self::from_der_and_sign_algo(private_key_der, alg)
214+
Self::from_der_and_sign_algo(&PrivatePkcs8KeyDer::from(private_key_der), alg)
200215
}
201216

202217
/// Obtains the key pair from a DER formatted key
@@ -208,39 +223,45 @@ impl KeyPair {
208223
/// key pair. However, sometimes multiple signature algorithms fit for the
209224
/// same der key. In that instance, you can use this function to precisely
210225
/// specify the `SignatureAlgorithm`.
226+
///
227+
/// You can use [`rustls_pemfile::private_key`] to get the `pkcs8` input. If
228+
/// you have already a byte slice, just calling `into()` and take a reference
229+
/// will convert it to a [`PrivatePkcs8KeyDer`].
230+
///
231+
/// [`rustls_pemfile::private_key`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.private_key.html
211232
#[cfg(feature = "crypto")]
212233
pub fn from_der_and_sign_algo(
213-
pkcs8: &[u8],
234+
pkcs8: &PrivatePkcs8KeyDer<'_>,
214235
alg: &'static SignatureAlgorithm,
215236
) -> Result<Self, Error> {
216237
let rng = &SystemRandom::new();
217-
let pkcs8_vec = pkcs8.to_vec();
238+
let serialized_der = pkcs8.secret_pkcs8_der().to_vec();
218239

219240
let kind = if alg == &PKCS_ED25519 {
220-
KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)._err()?)
241+
KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(&serialized_der)._err()?)
221242
} else if alg == &PKCS_ECDSA_P256_SHA256 {
222243
KeyPairKind::Ec(ecdsa_from_pkcs8(
223244
&signature::ECDSA_P256_SHA256_ASN1_SIGNING,
224-
pkcs8,
245+
&serialized_der,
225246
rng,
226247
)?)
227248
} else if alg == &PKCS_ECDSA_P384_SHA384 {
228249
KeyPairKind::Ec(ecdsa_from_pkcs8(
229250
&signature::ECDSA_P384_SHA384_ASN1_SIGNING,
230-
pkcs8,
251+
&serialized_der,
231252
rng,
232253
)?)
233254
} else if alg == &PKCS_RSA_SHA256 {
234-
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
255+
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
235256
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256)
236257
} else if alg == &PKCS_RSA_SHA384 {
237-
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
258+
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
238259
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA384)
239260
} else if alg == &PKCS_RSA_SHA512 {
240-
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
261+
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
241262
KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA512)
242263
} else if alg == &PKCS_RSA_PSS_SHA256 {
243-
let rsakp = RsaKeyPair::from_pkcs8(pkcs8)._err()?;
264+
let rsakp = RsaKeyPair::from_pkcs8(&serialized_der)._err()?;
244265
KeyPairKind::Rsa(rsakp, &signature::RSA_PSS_SHA256)
245266
} else {
246267
panic!("Unknown SignatureAlgorithm specified!");
@@ -249,14 +270,22 @@ impl KeyPair {
249270
Ok(KeyPair {
250271
kind,
251272
alg,
252-
serialized_der: pkcs8_vec,
273+
serialized_der,
253274
})
254275
}
255276

277+
/// Parses the key pair from the DER format
278+
///
279+
/// You can use [`rustls_pemfile::private_key`] to get the `pkcs8` input. If
280+
/// you have already a byte slice, just calling `into()` and take a reference
281+
/// will convert it to a [`PrivatePkcs8KeyDer`].
282+
///
283+
/// [`rustls_pemfile::private_key`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.private_key.html
256284
#[cfg(feature = "crypto")]
257285
pub(crate) fn from_raw(
258-
pkcs8: &[u8],
286+
pkcs8: &PrivatePkcs8KeyDer,
259287
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), Error> {
288+
let pkcs8 = pkcs8.secret_pkcs8_der();
260289
let rng = SystemRandom::new();
261290
let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
262291
(KeyPairKind::Ed(edkp), &PKCS_ED25519)
@@ -399,7 +428,7 @@ impl TryFrom<&[u8]> for KeyPair {
399428
type Error = Error;
400429

401430
fn try_from(pkcs8: &[u8]) -> Result<KeyPair, Error> {
402-
let (kind, alg) = KeyPair::from_raw(pkcs8)?;
431+
let (kind, alg) = KeyPair::from_raw(&pkcs8.into())?;
403432
Ok(KeyPair {
404433
kind,
405434
alg,
@@ -413,7 +442,7 @@ impl TryFrom<Vec<u8>> for KeyPair {
413442
type Error = Error;
414443

415444
fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, Error> {
416-
let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
445+
let (kind, alg) = KeyPair::from_raw(&pkcs8.as_slice().into())?;
417446
Ok(KeyPair {
418447
kind,
419448
alg,
@@ -422,6 +451,20 @@ impl TryFrom<Vec<u8>> for KeyPair {
422451
}
423452
}
424453

454+
#[cfg(feature = "crypto")]
455+
impl TryFrom<&PrivatePkcs8KeyDer<'_>> for KeyPair {
456+
type Error = Error;
457+
458+
fn try_from(pkcs8: &PrivatePkcs8KeyDer) -> Result<KeyPair, Error> {
459+
let (kind, alg) = KeyPair::from_raw(pkcs8)?;
460+
Ok(KeyPair {
461+
kind,
462+
alg,
463+
serialized_der: pkcs8.secret_pkcs8_der().into(),
464+
})
465+
}
466+
}
467+
425468
/// The key size used for RSA key generation
426469
#[cfg(all(feature = "crypto", feature = "aws_lc_rs", not(feature = "ring")))]
427470
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]

0 commit comments

Comments
 (0)