rcgen/
lib.rs

1/*!
2Rust X.509 certificate generation utility
3
4This crate provides a way to generate self signed X.509 certificates.
5
6The most simple way of using this crate is by calling the
7[`generate_simple_self_signed`] function.
8For more customization abilities, we provide the lower level
9[`Certificate::from_params`] function.
10
11## Example
12
13```
14extern crate rcgen;
15use rcgen::generate_simple_self_signed;
16# fn main () {
17// Generate a certificate that's valid for "localhost" and "hello.world.example"
18let subject_alt_names = vec!["hello.world.example".to_string(),
19	"localhost".to_string()];
20
21let cert = generate_simple_self_signed(subject_alt_names).unwrap();
22println!("{}", cert.serialize_pem().unwrap());
23println!("{}", cert.serialize_private_key_pem());
24# }
25```
26*/
27
28#![forbid(unsafe_code)]
29#![forbid(non_ascii_idents)]
30#![deny(missing_docs)]
31#![allow(clippy::complexity, clippy::style, clippy::pedantic)]
32
33use yasna::Tag;
34use yasna::models::ObjectIdentifier;
35#[cfg(feature = "pem")]
36use pem::Pem;
37use std::convert::TryInto;
38use ring::digest;
39use ring::signature::{EcdsaKeyPair, Ed25519KeyPair, RsaKeyPair, RsaEncoding};
40use ring::rand::SystemRandom;
41use ring::signature::KeyPair as RingKeyPair;
42use ring::signature::{self, EcdsaSigningAlgorithm, EdDSAParameters};
43use yasna::DERWriter;
44use yasna::models::{GeneralizedTime, UTCTime};
45use yasna::tags::{TAG_BMPSTRING, TAG_TELETEXSTRING, TAG_UNIVERSALSTRING};
46use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
47use std::collections::HashMap;
48use std::fmt;
49use std::convert::TryFrom;
50use std::error::Error;
51use std::net::IpAddr;
52use std::str::FromStr;
53use std::hash::{Hash, Hasher};
54
55/// A self signed certificate together with signing keys
56pub struct Certificate {
57	params :CertificateParams,
58	key_pair :KeyPair,
59}
60
61
62/**
63KISS function to generate a self signed certificate
64
65Given a set of domain names you want your certificate to be valid for,
66this function fills in the other generation parameters with
67reasonable defaults and generates a self signed certificate
68as output.
69
70## Example
71
72```
73extern crate rcgen;
74use rcgen::generate_simple_self_signed;
75# fn main () {
76let subject_alt_names :&[_] = &["hello.world.example".to_string(),
77	"localhost".to_string()];
78
79let cert = generate_simple_self_signed(subject_alt_names).unwrap();
80// The certificate is now valid for localhost and the domain "hello.world.example"
81println!("{}", cert.serialize_pem().unwrap());
82println!("{}", cert.serialize_private_key_pem());
83# }
84```
85*/
86pub fn generate_simple_self_signed(subject_alt_names :impl Into<Vec<String>>) -> Result<Certificate, RcgenError> {
87	Certificate::from_params(CertificateParams::new(subject_alt_names))
88}
89
90// https://tools.ietf.org/html/rfc5280#section-4.1.1
91
92// Example certs usable as reference:
93// Uses ECDSA: https://crt.sh/?asn1=607203242
94
95/// pkcs-9-at-extensionRequest in RFC 2985
96const OID_PKCS_9_AT_EXTENSION_REQUEST :&[u64] = &[1, 2, 840, 113549, 1, 9, 14];
97
98/// id-at-countryName in RFC 5280
99const OID_COUNTRY_NAME :&[u64] = &[2, 5, 4, 6];
100/// id-at-localityName in RFC 5280
101const OID_LOCALITY_NAME :&[u64] = &[2, 5, 4, 7];
102/// id-at-stateOrProvinceName in RFC 5280
103const OID_STATE_OR_PROVINCE_NAME :&[u64] = &[2, 5, 4, 8];
104/// id-at-organizationName in RFC 5280
105const OID_ORG_NAME :&[u64] = &[2, 5, 4, 10];
106/// id-at-organizationalUnitName in RFC 5280
107const OID_ORG_UNIT_NAME :&[u64] = &[2, 5, 4, 11];
108/// id-at-commonName in RFC 5280
109const OID_COMMON_NAME :&[u64] = &[2, 5, 4, 3];
110
111// https://tools.ietf.org/html/rfc5480#section-2.1.1
112const OID_EC_PUBLIC_KEY :&[u64] = &[1, 2, 840, 10045, 2, 1];
113const OID_EC_SECP_256_R1 :&[u64] = &[1, 2, 840, 10045, 3, 1, 7];
114const OID_EC_SECP_384_R1 :&[u64] = &[1, 3, 132, 0, 34];
115
116// rsaEncryption in RFC 4055
117const OID_RSA_ENCRYPTION :&[u64] = &[1, 2, 840, 113549, 1, 1, 1];
118
119// id-RSASSA-PSS in RFC 4055
120const OID_RSASSA_PSS :&[u64] = &[1, 2, 840, 113549, 1, 1, 10];
121
122// https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3
123const OID_KEY_USAGE :&[u64] = &[2, 5, 29, 15];
124
125// https://tools.ietf.org/html/rfc5280#appendix-A.2
126// https://tools.ietf.org/html/rfc5280#section-4.2.1.6
127const OID_SUBJECT_ALT_NAME :&[u64] = &[2, 5, 29, 17];
128
129// https://tools.ietf.org/html/rfc5280#section-4.2.1.9
130const OID_BASIC_CONSTRAINTS :&[u64] = &[2, 5, 29, 19];
131
132// https://tools.ietf.org/html/rfc5280#section-4.2.1.2
133const OID_SUBJECT_KEY_IDENTIFIER :&[u64] = &[2, 5, 29, 14];
134
135// https://tools.ietf.org/html/rfc5280#section-4.2.1.1
136const OID_AUTHORITY_KEY_IDENTIFIER :&[u64] = &[2, 5, 29, 35];
137
138// id-ce-extKeyUsage in
139// https://tools.ietf.org/html/rfc5280#section-4.2.1.12
140const OID_EXT_KEY_USAGE :&[u64] = &[2, 5, 29, 37];
141
142// id-ce-nameConstraints in
143/// https://tools.ietf.org/html/rfc5280#section-4.2.1.10
144const OID_NAME_CONSTRAINTS :&[u64] = &[2, 5, 29, 30];
145
146// id-pe-acmeIdentifier in
147// https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.1
148const OID_PE_ACME :&[u64] = &[1, 3, 6, 1, 5, 5, 7, 1, 31];
149
150#[derive(Debug, PartialEq, Eq, Hash, Clone)]
151#[allow(missing_docs)]
152#[non_exhaustive]
153/// The type of subject alt name
154pub enum SanType {
155	/// Also known as E-Mail address
156	Rfc822Name(String),
157	DnsName(String),
158	URI(String),
159	IpAddress(IpAddr),
160}
161
162impl SanType {
163	#[cfg(feature = "x509-parser")]
164	fn try_from_general(name :&x509_parser::extensions::GeneralName<'_>) -> Result<Self, RcgenError> {
165		Ok(match name {
166			x509_parser::extensions::GeneralName::RFC822Name(name) => {
167				SanType::Rfc822Name((*name).into())
168			}
169			x509_parser::extensions::GeneralName::DNSName(name) => {
170				SanType::DnsName((*name).into())
171			}
172			x509_parser::extensions::GeneralName::URI(name) => {
173				SanType::URI((*name).into())
174			}
175			_ => return Err(RcgenError::InvalidNameType),
176		})
177	}
178
179	fn tag(&self) -> u64 {
180		// Defined in the GeneralName list in
181		// https://tools.ietf.org/html/rfc5280#page-38
182		const TAG_RFC822_NAME :u64 = 1;
183		const TAG_DNS_NAME :u64 = 2;
184		const TAG_URI :u64 = 6;
185		const TAG_IP_ADDRESS :u64 = 7;
186
187		match self {
188			SanType::Rfc822Name(_name) => TAG_RFC822_NAME,
189			SanType::DnsName(_name) => TAG_DNS_NAME,
190			SanType::URI(_name) => TAG_URI,
191			SanType::IpAddress(_addr) => TAG_IP_ADDRESS,
192		}
193	}
194}
195
196#[derive(Debug, PartialEq, Eq, Clone)]
197#[allow(missing_docs)]
198#[non_exhaustive]
199/// General Subtree type.
200///
201/// This type has similarities to the [`SanType`] enum but is not equal.
202/// For example, `GeneralSubtree` has CIDR subnets for ip addresses
203/// while [`SanType`] has IP addresses.
204pub enum GeneralSubtree {
205	/// Also known as E-Mail address
206	Rfc822Name(String),
207	DnsName(String),
208	DirectoryName(DistinguishedName),
209	IpAddress(CidrSubnet),
210}
211
212impl GeneralSubtree {
213	fn tag(&self) -> u64 {
214		// Defined in the GeneralName list in
215		// https://tools.ietf.org/html/rfc5280#page-38
216		const TAG_RFC822_NAME :u64 = 1;
217		const TAG_DNS_NAME :u64 = 2;
218		const TAG_DIRECTORY_NAME :u64 = 4;
219		const TAG_IP_ADDRESS :u64 = 7;
220
221		match self {
222			GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME,
223			GeneralSubtree::DnsName(_name) => TAG_DNS_NAME,
224			GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME,
225			GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS,
226		}
227	}
228}
229
230#[derive(Debug, PartialEq, Eq, Hash, Clone)]
231#[allow(missing_docs)]
232/// CIDR subnet, as per [RFC 4632](https://tools.ietf.org/html/rfc4632)
233///
234/// You might know CIDR subnets better by their textual representation
235/// where they consist of an ip address followed by a slash and a prefix
236/// number, for example `192.168.99.0/24`.
237///
238/// The first field in the enum is the address, the second is the mask.
239/// Both are specified in network byte order.
240pub enum CidrSubnet {
241	V4([u8; 4], [u8; 4]),
242	V6([u8; 16], [u8; 16]),
243}
244
245macro_rules! mask {
246	($t:ty, $d:expr) => {{
247		let v = <$t>::max_value();
248		let v = v.checked_shr($d as u32).unwrap_or(0);
249		(!v).to_be_bytes()
250	}};
251}
252
253impl CidrSubnet {
254	/// Obtains the CidrSubnet from the well-known
255	/// addr/prefix notation.
256	/// ```
257	/// # use std::str::FromStr;
258	/// # use rcgen::CidrSubnet;
259	/// // The "192.0.2.0/24" example from
260	/// // https://tools.ietf.org/html/rfc5280#page-42
261	/// let subnet = CidrSubnet::from_str("192.0.2.0/24").unwrap();
262	/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
263	/// ```
264	pub fn from_str(s :&str) -> Result<Self, ()> {
265		let mut iter = s.split('/');
266		if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) {
267			let addr = IpAddr::from_str(addr_s).map_err(|_| ())?;
268			let prefix = u8::from_str(prefix_s).map_err(|_| ())?;
269			Ok(Self::from_addr_prefix(addr, prefix))
270		} else {
271			Err(())
272		}
273	}
274	/// Obtains the CidrSubnet from an ip address
275	/// as well as the specified prefix number.
276	///
277	/// ```
278	/// # use std::net::IpAddr;
279	/// # use std::str::FromStr;
280	/// # use rcgen::CidrSubnet;
281	/// // The "192.0.2.0/24" example from
282	/// // https://tools.ietf.org/html/rfc5280#page-42
283	/// let addr = IpAddr::from_str("192.0.2.0").unwrap();
284	/// let subnet = CidrSubnet::from_addr_prefix(addr, 24);
285	/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
286	/// ```
287	pub fn from_addr_prefix(addr :IpAddr, prefix :u8) -> Self {
288		match addr {
289			IpAddr::V4(addr) => {
290				Self::from_v4_prefix(addr.octets(), prefix)
291			},
292			IpAddr::V6(addr) => {
293				Self::from_v6_prefix(addr.octets(), prefix)
294			},
295		}
296	}
297	/// Obtains the CidrSubnet from an IPv4 address in network byte order
298	/// as well as the specified prefix.
299	pub fn from_v4_prefix(addr :[u8; 4], prefix :u8) -> Self {
300		CidrSubnet::V4(addr, mask!(u32, prefix))
301	}
302	/// Obtains the CidrSubnet from an IPv6 address in network byte order
303	/// as well as the specified prefix.
304	pub fn from_v6_prefix(addr :[u8; 16], prefix :u8) -> Self {
305		CidrSubnet::V6(addr, mask!(u128, prefix))
306	}
307	fn to_bytes(&self) -> Vec<u8> {
308		let mut res = Vec::new();
309		match self {
310			CidrSubnet::V4(addr, mask) => {
311				res.extend_from_slice(addr);
312				res.extend_from_slice(mask);
313			},
314			CidrSubnet::V6(addr, mask) => {
315				res.extend_from_slice(addr);
316				res.extend_from_slice(mask);
317			},
318		}
319		res
320	}
321}
322
323#[derive(Debug, PartialEq, Eq, Hash, Clone)]
324#[non_exhaustive]
325/// The attribute type of a distinguished name entry
326pub enum DnType {
327	/// X520countryName
328	CountryName,
329	/// X520LocalityName
330	LocalityName,
331	/// X520StateOrProvinceName
332	StateOrProvinceName,
333	/// X520OrganizationName
334	OrganizationName,
335	/// X520OrganizationalUnitName
336	OrganizationalUnitName,
337	/// X520CommonName
338	CommonName,
339	/// Custom distinguished name type
340	CustomDnType(Vec<u64>),
341}
342
343impl DnType {
344	fn to_oid(&self) -> ObjectIdentifier {
345		let sl = match self {
346			DnType::CountryName => OID_COUNTRY_NAME,
347			DnType::LocalityName => OID_LOCALITY_NAME,
348			DnType::StateOrProvinceName => OID_STATE_OR_PROVINCE_NAME,
349			DnType::OrganizationName => OID_ORG_NAME,
350			DnType::OrganizationalUnitName => OID_ORG_UNIT_NAME,
351			DnType::CommonName => OID_COMMON_NAME,
352			DnType::CustomDnType(ref oid) => oid.as_slice(),
353		};
354		ObjectIdentifier::from_slice(sl)
355	}
356
357	/// Generate a DnType for the provided OID
358	pub fn from_oid(slice :&[u64]) -> Self {
359		match slice {
360			OID_COUNTRY_NAME => DnType::CountryName,
361			OID_LOCALITY_NAME => DnType::LocalityName,
362			OID_STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName,
363			OID_ORG_NAME => DnType::OrganizationName,
364			OID_ORG_UNIT_NAME => DnType::OrganizationalUnitName,
365			OID_COMMON_NAME => DnType::CommonName,
366			oid => DnType::CustomDnType(oid.into())
367		}
368	}
369}
370
371/// A distinguished name entry
372#[derive(Debug, PartialEq, Eq, Hash, Clone)]
373#[non_exhaustive]
374pub enum DnValue {
375	/// A string of characters from the T.61 character set
376	TeletexString(Vec<u8>),
377	/// An ASCII string containing only A-Z, a-z, 0-9, '()+,-./:=? and <SPACE>
378	PrintableString(String),
379	/// A string encoded using UTF-32
380	UniversalString(Vec<u8>),
381	/// A string encoded using UTF-8
382	Utf8String(String),
383	/// A string encoded using UCS-2
384	BmpString(Vec<u8>),
385}
386
387impl<T> From<T> for DnValue
388where
389	T :Into<String>
390{
391	fn from(t :T) -> Self {
392		DnValue::Utf8String(t.into())
393	}
394}
395
396#[derive(Debug, PartialEq, Eq, Clone)]
397/**
398Distinguished name used e.g. for the issuer and subject fields of a certificate
399
400A distinguished name is a set of (attribute type, attribute value) tuples.
401
402This datastructure keeps them ordered by insertion order.
403
404See also the RFC 5280 sections on the [issuer](https://tools.ietf.org/html/rfc5280#section-4.1.2.4)
405and [subject](https://tools.ietf.org/html/rfc5280#section-4.1.2.6) fields.
406*/
407pub struct DistinguishedName {
408	entries :HashMap<DnType, DnValue>,
409	order :Vec<DnType>,
410}
411
412impl DistinguishedName {
413	/// Creates a new, empty distinguished name
414	pub fn new() -> Self {
415		Self {
416			entries : HashMap::new(),
417			order : Vec::new(),
418		}
419	}
420	/// Obtains the attribute value for the given attribute type
421	pub fn get(&self, ty :&DnType) -> Option<&DnValue> {
422		self.entries.get(ty)
423	}
424	/// Removes the attribute with the specified DnType
425	///
426	/// Returns true when an actual removal happened, false
427	/// when no attribute with the specified DnType was
428	/// found.
429	pub fn remove(&mut self, ty :DnType) -> bool {
430		let removed = self.entries.remove(&ty).is_some();
431		if removed {
432			self.order.retain(|ty_o| &ty != ty_o);
433		}
434		removed
435	}
436	/// Inserts or updates an attribute that consists of type and name
437	///
438	/// ```
439	/// # use rcgen::{DistinguishedName, DnType, DnValue};
440	/// let mut dn = DistinguishedName::new();
441	/// dn.push(DnType::OrganizationName, "Crab widgits SE");
442	/// dn.push(DnType::CommonName, DnValue::PrintableString("Master Cert".to_string()));
443	/// assert_eq!(dn.get(&DnType::OrganizationName), Some(&DnValue::Utf8String("Crab widgits SE".to_string())));
444	/// assert_eq!(dn.get(&DnType::CommonName), Some(&DnValue::PrintableString("Master Cert".to_string())));
445	/// ```
446	pub fn push(&mut self, ty :DnType, s :impl Into<DnValue>) {
447		if !self.entries.contains_key(&ty) {
448			self.order.push(ty.clone());
449		}
450		self.entries.insert(ty, s.into());
451	}
452	/// Iterate over the entries
453	pub fn iter(&self) -> DistinguishedNameIterator<'_> {
454		DistinguishedNameIterator {
455			distinguished_name :self,
456			iter :self.order.iter()
457		}
458	}
459
460	#[cfg(feature = "x509-parser")]
461	fn from_name(name :&x509_parser::x509::X509Name) -> Result<Self, RcgenError> {
462		use x509_parser::der_parser::asn1_rs::Tag;
463
464		let mut dn = DistinguishedName::new();
465		for rdn in name.iter() {
466			let mut rdn_iter = rdn.iter();
467			let dn_opt = rdn_iter.next();
468			let attr = if let Some(dn) = dn_opt {
469				if rdn_iter.next().is_some() {
470					// no support for distinguished names with more than one attribute
471					return Err(RcgenError::CouldNotParseCertificate);
472				} else {
473					dn
474				}
475			} else {
476				panic!("x509-parser distinguished name set is empty");
477			};
478
479			let attr_type_oid = attr.attr_type().iter()
480				.ok_or(RcgenError::CouldNotParseCertificate)?;
481			let dn_type = DnType::from_oid(&attr_type_oid.collect::<Vec<_>>());
482			let data = attr.attr_value().data;
483			let dn_value = match attr.attr_value().header.tag() {
484				Tag::T61String => DnValue::TeletexString(data.into()),
485				Tag::PrintableString => {
486					let data = std::str::from_utf8(data)
487						.map_err(|_| RcgenError::CouldNotParseCertificate)?;
488					DnValue::PrintableString(data.to_owned())
489				},
490				Tag::UniversalString => DnValue::UniversalString(data.into()),
491				Tag::Utf8String => {
492					let data = std::str::from_utf8(data)
493						.map_err(|_| RcgenError::CouldNotParseCertificate)?;
494					DnValue::Utf8String(data.to_owned())
495				},
496				Tag::BmpString => DnValue::BmpString(data.into()),
497				_ => return Err(RcgenError::CouldNotParseCertificate),
498			};
499
500			dn.push(dn_type, dn_value);
501		}
502		Ok(dn)
503	}
504}
505
506/**
507Iterator over [`DistinguishedName`] entries
508*/
509pub struct DistinguishedNameIterator<'a> {
510	distinguished_name :&'a DistinguishedName,
511	iter :std::slice::Iter<'a, DnType>,
512}
513
514impl <'a> Iterator for DistinguishedNameIterator<'a> {
515	type Item = (&'a DnType, &'a DnValue);
516
517	fn next(&mut self) -> Option<Self::Item> {
518		self.iter.next()
519			.and_then(|ty| {
520				self.distinguished_name.entries.get(ty).map(|v| (ty, v))
521			})
522	}
523}
524
525
526/// A public key, extracted from a CSR
527#[derive(Debug, PartialEq, Eq, Hash)]
528pub struct PublicKey {
529	raw: Vec<u8>,
530	alg: &'static SignatureAlgorithm,
531}
532
533impl PublicKeyData for PublicKey {
534	fn alg(&self) -> &SignatureAlgorithm {
535		self.alg
536	}
537
538	fn raw_bytes(&self) -> &[u8] {
539		&self.raw
540	}
541}
542
543/// Data for a certificate signing request
544#[allow(missing_docs)]
545pub struct CertificateSigningRequest {
546	pub params :CertificateParams,
547	pub public_key :PublicKey,
548}
549
550impl CertificateSigningRequest {
551	/// Parse a certificate signing request from the ASCII PEM format
552	///
553	/// See [`from_der`](Self::from_der) for more details.
554	#[cfg(all(feature = "pem", feature = "x509-parser"))]
555	pub fn from_pem(pem_str :&str) -> Result<Self, RcgenError> {
556		let csr = pem::parse(pem_str)
557			.or(Err(RcgenError::CouldNotParseCertificationRequest))?;
558		Self::from_der(&csr.contents)
559	}
560
561	/// Parse a certificate signing request from DER-encoded bytes
562	///
563	/// Currently, this only supports the `Subject Alternative Name` extension.
564	/// On encountering other extensions, this function will return an error.
565	#[cfg(feature = "x509-parser")]
566	pub fn from_der(csr :&[u8]) -> Result<Self, RcgenError> {
567		use x509_parser::prelude::FromDer;
568		let csr = x509_parser::certification_request::X509CertificationRequest::from_der(csr)
569			.map_err(|_| RcgenError::CouldNotParseCertificationRequest)?.1;
570		csr.verify_signature().map_err(|_| RcgenError::RingUnspecified)?;
571		let alg_oid = csr.signature_algorithm.algorithm.iter()
572			.ok_or(RcgenError::CouldNotParseCertificationRequest)?
573			.collect::<Vec<_>>();
574		let alg = SignatureAlgorithm::from_oid(&alg_oid)?;
575
576		let info = &csr.certification_request_info;
577		let mut params = CertificateParams::default();
578		params.alg = alg;
579		params.distinguished_name = DistinguishedName::from_name(&info.subject)?;
580		let raw = info.subject_pki.subject_public_key.data.to_vec();
581
582		if let Some(extensions) = csr.requested_extensions() {
583			for ext in extensions {
584				match ext {
585					x509_parser::extensions::ParsedExtension::SubjectAlternativeName(san) => {
586						for name in &san.general_names {
587							params.subject_alt_names.push(SanType::try_from_general(name)?);
588						}
589					}
590					_ => return Err(RcgenError::UnsupportedExtension),
591				}
592			}
593		}
594
595		// Not yet handled:
596		// * is_ca
597		// * extended_key_usages
598		// * name_constraints
599		// and any other extensions.
600
601		Ok(Self {
602			params,
603			public_key: PublicKey { alg, raw },
604		})
605	}
606	/// Serializes the requested certificate, signed with another certificate's key, in binary DER format
607	pub fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
608		self.params.serialize_der_with_signer(&self.public_key, ca)
609	}
610	/// Serializes the requested certificate, signed with another certificate's key, to the ASCII PEM format
611	///
612	/// *This function is only available if rcgen is built with the "pem" feature*
613	#[cfg(feature = "pem")]
614	pub fn serialize_pem_with_signer(&self, ca :&Certificate) -> Result<String, RcgenError> {
615		let p = Pem {
616			tag : "CERTIFICATE".to_string(),
617			contents : self.params.serialize_der_with_signer(&self.public_key, ca)?,
618		};
619		Ok(pem::encode(&p))
620	}
621}
622
623/// Parameters used for certificate generation
624#[allow(missing_docs)]
625#[non_exhaustive]
626pub struct CertificateParams {
627	pub alg :&'static SignatureAlgorithm,
628	pub not_before :OffsetDateTime,
629	pub not_after :OffsetDateTime,
630	pub serial_number :Option<u64>,
631	pub subject_alt_names :Vec<SanType>,
632	pub distinguished_name :DistinguishedName,
633	pub is_ca :IsCa,
634	pub key_usages :Vec<KeyUsagePurpose>,
635	pub extended_key_usages :Vec<ExtendedKeyUsagePurpose>,
636	pub name_constraints :Option<NameConstraints>,
637	pub custom_extensions :Vec<CustomExtension>,
638	/// The certificate's key pair, a new random key pair will be generated if this is `None`
639	pub key_pair :Option<KeyPair>,
640	/// If `true` (and not self-signed), the 'Authority Key Identifier' extension will be added to the generated cert
641	pub use_authority_key_identifier_extension :bool,
642	/// Method to generate key identifiers from public keys
643	///
644	/// Defaults to SHA-256.
645	pub key_identifier_method :KeyIdMethod,
646}
647
648impl Default for CertificateParams {
649	fn default() -> Self {
650		// not_before and not_after set to reasonably long dates
651		let not_before = date_time_ymd(1975, 01, 01);
652		let not_after = date_time_ymd(4096, 01, 01);
653		let mut distinguished_name = DistinguishedName::new();
654		distinguished_name.push(DnType::CommonName, "rcgen self signed cert");
655		CertificateParams {
656			alg : &PKCS_ECDSA_P256_SHA256,
657			not_before,
658			not_after,
659			serial_number : None,
660			subject_alt_names : Vec::new(),
661			distinguished_name,
662			is_ca : IsCa::NoCa,
663			key_usages : Vec::new(),
664			extended_key_usages : Vec::new(),
665			name_constraints : None,
666			custom_extensions : Vec::new(),
667			key_pair : None,
668			use_authority_key_identifier_extension : false,
669			key_identifier_method : KeyIdMethod::Sha256,
670		}
671	}
672}
673
674impl CertificateParams {
675	/// Parses a ca certificate from the ASCII PEM format for signing
676	///
677	/// See [`from_ca_cert_der`](Self::from_ca_cert_der) for more details.
678	///
679	/// *This constructor is only available if rcgen is built with the "pem" and "x509-parser" features*
680	#[cfg(all(feature = "pem", feature = "x509-parser"))]
681	pub fn from_ca_cert_pem(pem_str :&str, key_pair :KeyPair) -> Result<Self, RcgenError> {
682		let certificate = pem::parse(pem_str)
683			.or(Err(RcgenError::CouldNotParseCertificate))?;
684		Self::from_ca_cert_der(&certificate.contents, key_pair)
685	}
686
687	/// Parses a ca certificate from the DER format for signing
688	///
689	/// This function is only of use if you have an existing ca certificate with
690	/// which you want to sign a certificate newly generated by `rcgen` using the
691	/// [`serialize_der_with_signer`](Certificate::serialize_der_with_signer) or
692	/// [`serialize_pem_with_signer`](Certificate::serialize_pem_with_signer)
693	/// functions.
694	///
695	/// This function only extracts from the given ca cert the informations
696	/// needed for signing. Any information beyond that is not extracted
697	/// and left to defaults.
698	///
699	/// Will not check if certificate is a ca certificate!
700	///
701	/// *This constructor is only available if rcgen is built with the "x509-parser" feature*
702	#[cfg(feature = "x509-parser")]
703	pub fn from_ca_cert_der(ca_cert :&[u8], key_pair :KeyPair) -> Result<Self, RcgenError> {
704		let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
705			.or(Err(RcgenError::CouldNotParseCertificate))?;
706
707		let alg_oid = x509.signature_algorithm.algorithm.iter()
708			.ok_or(RcgenError::CouldNotParseCertificate)?;
709		let alg = SignatureAlgorithm::from_oid(&alg_oid.collect::<Vec<_>>())?;
710
711		let dn = DistinguishedName::from_name(&x509.tbs_certificate.subject)?;
712		Ok(
713			CertificateParams {
714				alg,
715				distinguished_name : dn,
716				key_pair : Some(key_pair),
717				.. Default::default()
718			}
719		)
720	}
721	fn write_subject_alt_names(&self, writer :DERWriter) {
722		Self::write_extension(writer, OID_SUBJECT_ALT_NAME, false, |writer| {
723			writer.write_sequence(|writer| {
724				for san in self.subject_alt_names.iter() {
725					writer.next().write_tagged_implicit(Tag::context(san.tag()), |writer| {
726						match san {
727							SanType::Rfc822Name(name) |
728							SanType::DnsName(name) |
729							SanType::URI(name) => writer.write_ia5_string(name),
730							SanType::IpAddress(IpAddr::V4(addr)) => writer.write_bytes(&addr.octets()),
731							SanType::IpAddress(IpAddr::V6(addr)) => writer.write_bytes(&addr.octets()),
732						}
733					});
734				}
735			});
736		});
737	}
738	fn write_request<K: PublicKeyData>(&self, pub_key: &K, writer :DERWriter) {
739		writer.write_sequence(|writer| {
740			// Write version
741			writer.next().write_u8(0);
742			// Write issuer
743			writer.next().write_sequence(|writer| {
744				for (ty, content) in self.distinguished_name.iter() {
745					writer.next().write_set(|writer| {
746						writer.next().write_sequence(|writer| {
747							writer.next().write_oid(&ty.to_oid());
748							match content {
749								DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
750									writer.write_bytes(s)
751								}),
752								DnValue::PrintableString(s) => writer.next().write_printable_string(s),
753								DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
754									writer.write_bytes(s)
755								}),
756								DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
757								DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
758									writer.write_bytes(s)
759								}),
760							}
761						});
762					});
763				}
764			});
765			// Write subjectPublicKeyInfo
766			pub_key.serialize_public_key_der(writer.next());
767			// Write extensions
768			// According to the spec in RFC 2986, even if attributes are empty we need the empty attribute tag
769			writer.next().write_tagged(Tag::context(0), |writer| {
770				if !self.subject_alt_names.is_empty() {
771					writer.write_sequence(|writer| {
772						let oid = ObjectIdentifier::from_slice(OID_PKCS_9_AT_EXTENSION_REQUEST);
773						writer.next().write_oid(&oid);
774						writer.next().write_set(|writer| {
775							writer.next().write_sequence(|writer| {
776								// Write subject_alt_names
777								self.write_subject_alt_names(writer.next());
778							});
779						});
780					});
781				}
782			});
783
784		});
785	}
786	fn write_cert<K: PublicKeyData>(&self, writer :DERWriter, pub_key: &K, ca :&Certificate) -> Result<(), RcgenError> {
787		writer.write_sequence(|writer| {
788			// Write version
789			writer.next().write_tagged(Tag::context(0), |writer| {
790				writer.write_u8(2);
791			});
792			// Write serialNumber
793			let serial = self.serial_number.unwrap_or_else(|| {
794				let hash = digest::digest(&digest::SHA256, pub_key.raw_bytes());
795				let bytes: [u8; 8] = hash.as_ref()[0..8].try_into().unwrap();
796				u64::from_le_bytes(bytes)
797			});
798			writer.next().write_u64(serial);
799			// Write signature
800			ca.params.alg.write_alg_ident(writer.next());
801			// Write issuer
802			write_distinguished_name(writer.next(), &ca.params.distinguished_name);
803			// Write validity
804			writer.next().write_sequence(|writer| {
805				// Not before
806				write_dt_utc_or_generalized(writer.next(), self.not_before);
807				// Not after
808				write_dt_utc_or_generalized(writer.next(), self.not_after);
809				Ok::<(), RcgenError>(())
810			})?;
811			// Write subject
812			write_distinguished_name(writer.next(), &self.distinguished_name);
813			// Write subjectPublicKeyInfo
814			pub_key.serialize_public_key_der(writer.next());
815			// write extensions
816			let not_self_signed = ca.key_pair.public_key_raw() != pub_key.raw_bytes();
817			let should_write_exts = (not_self_signed && self.use_authority_key_identifier_extension) ||
818				!self.subject_alt_names.is_empty() ||
819				!self.extended_key_usages.is_empty() ||
820				self.name_constraints.iter().any(|c| !c.is_empty()) ||
821				matches!(self.is_ca, IsCa::ExplicitNoCa) ||
822				matches!(self.is_ca, IsCa::Ca(_)) ||
823				!self.custom_extensions.is_empty();
824			if should_write_exts {
825				writer.next().write_tagged(Tag::context(3), |writer| {
826					writer.write_sequence(|writer| {
827						if not_self_signed && self.use_authority_key_identifier_extension {
828							// Write Authority Key Identifier (when issued by a CA)
829							// RFC 5280 states:
830							//   'The keyIdentifier field of the authorityKeyIdentifier extension MUST
831							//    be included in all certificates generated by conforming CAs to
832							//    facilitate certification path construction.  There is one exception;
833							//    where a CA distributes its public key in the form of a "self-signed"
834							//    certificate, the authority key identifier MAY be omitted.'
835							Self::write_extension(writer.next(), OID_AUTHORITY_KEY_IDENTIFIER, false, |writer| {
836								writer.write_sequence(|writer| {
837									writer.next().write_tagged_implicit(Tag::context(0), |writer| {
838										writer.write_bytes(ca.get_key_identifier().as_ref())
839									})
840								});
841							});
842						}
843						// Write subject_alt_names
844						if !self.subject_alt_names.is_empty() {
845							self.write_subject_alt_names(writer.next());
846						}
847
848						// Write standard key usage
849						if !self.key_usages.is_empty() {
850							writer.next().write_sequence(|writer| {
851
852								let oid = ObjectIdentifier::from_slice(OID_KEY_USAGE);
853								writer.next().write_oid(&oid);
854								writer.next().write_bool(true);
855
856								let mut bits :u16 = 0;
857
858								for entry in self.key_usages.iter() {
859									// Map the index to a value
860									let index = match entry {
861										KeyUsagePurpose::DigitalSignature => 0,
862										KeyUsagePurpose::ContentCommitment => 1,
863										KeyUsagePurpose::KeyEncipherment => 2,
864										KeyUsagePurpose::DataEncipherment => 3,
865										KeyUsagePurpose::KeyAgreement => 4,
866										KeyUsagePurpose::KeyCertSign => 5,
867										KeyUsagePurpose::CrlSign => 6,
868										KeyUsagePurpose::EncipherOnly => 7,
869										KeyUsagePurpose::DecipherOnly => 8,
870									};
871
872									bits |= 1 << index;
873								}
874
875								// Compute the 1-based most significant bit
876								let msb = 16 - bits.leading_zeros();
877								let nb = if msb <= 8 {
878									1
879								} else {
880									2
881								};
882
883								let bits = bits.reverse_bits().to_be_bytes();
884
885								// Finally take only the bytes != 0
886								let bits = &bits[..nb];
887
888								let der = yasna::construct_der(|writer| {
889									writer.write_bitvec_bytes(&bits, msb as usize)
890								});
891
892								// Write them
893								writer.next().write_bytes(&der);
894
895							});
896						}
897
898						// Write extended key usage
899						if !self.extended_key_usages.is_empty() {
900							Self::write_extension(writer.next(), OID_EXT_KEY_USAGE, false, |writer| {
901								writer.write_sequence(|writer| {
902									for usage in self.extended_key_usages.iter() {
903										let oid = ObjectIdentifier::from_slice(usage.oid());
904										writer.next().write_oid(&oid);
905									}
906								});
907							});
908						}
909						if let Some(name_constraints) = &self.name_constraints {
910							// If both trees are empty, the extension must be omitted.
911							if !name_constraints.is_empty() {
912								Self::write_extension(writer.next(), OID_NAME_CONSTRAINTS, true, |writer| {
913									writer.write_sequence(|writer| {
914										if !name_constraints.permitted_subtrees.is_empty() {
915											write_general_subtrees(writer.next(), 0, &name_constraints.permitted_subtrees);
916										}
917										if !name_constraints.excluded_subtrees.is_empty() {
918											write_general_subtrees(writer.next(), 1, &name_constraints.excluded_subtrees);
919										}
920									});
921								});
922							}
923						}
924						match self.is_ca {
925							IsCa::Ca(ref constraint) => {
926								// Write subject_key_identifier
927								Self::write_extension(writer.next(), OID_SUBJECT_KEY_IDENTIFIER, false, |writer| {
928									let key_identifier = self.key_identifier(pub_key);
929									writer.write_bytes(key_identifier.as_ref());
930								});
931								// Write basic_constraints
932								Self::write_extension(writer.next(), OID_BASIC_CONSTRAINTS, true, |writer| {
933									writer.write_sequence(|writer| {
934										writer.next().write_bool(true); // cA flag
935										if let BasicConstraints::Constrained(path_len_constraint) = constraint {
936											writer.next().write_u8(*path_len_constraint);
937										}
938									});
939								});
940							}
941							IsCa::ExplicitNoCa => {
942								// Write subject_key_identifier
943								Self::write_extension(writer.next(), OID_SUBJECT_KEY_IDENTIFIER, false, |writer| {
944									let key_identifier = self.key_identifier(pub_key);
945									writer.write_bytes(key_identifier.as_ref());
946								});
947								// Write basic_constraints
948								Self::write_extension(writer.next(), OID_BASIC_CONSTRAINTS, true, |writer| {
949									writer.write_sequence(|writer| {
950										writer.next().write_bool(false); // cA flag
951									});
952								});
953							}
954							IsCa::NoCa => {}
955						}
956
957						// Write the custom extensions
958						for ext in &self.custom_extensions {
959							writer.next().write_sequence(|writer| {
960								let oid = ObjectIdentifier::from_slice(&ext.oid);
961								writer.next().write_oid(&oid);
962								// If the extension is critical, we should signal this.
963								// It's false by default so we don't need to write anything
964								// if the extension is not critical.
965								if ext.critical {
966									writer.next().write_bool(true);
967								}
968								writer.next().write_bytes(&ext.content);
969							});
970						}
971					});
972				});
973			}
974			Ok(())
975		})
976	}
977	/// Serializes an X.509v3 extension according to RFC 5280
978	fn write_extension(writer :DERWriter, extension_oid :&[u64], is_critical :bool, value_serializer :impl FnOnce(DERWriter)) {
979		// Extension specification:
980		//    Extension  ::=  SEQUENCE  {
981		//         extnID      OBJECT IDENTIFIER,
982		//         critical    BOOLEAN DEFAULT FALSE,
983		//         extnValue   OCTET STRING
984		//                     -- contains the DER encoding of an ASN.1 value
985		//                     -- corresponding to the extension type identified
986		//                     -- by extnID
987		//         }
988
989		writer.write_sequence(|writer| {
990			let oid = ObjectIdentifier::from_slice(extension_oid);
991			writer.next().write_oid(&oid);
992			if is_critical {
993				writer.next().write_bool(true);
994			}
995			let bytes = yasna::construct_der(value_serializer);
996			writer.next().write_bytes(&bytes);
997		})
998	}
999	/// Calculates a subject key identifier for the certificate subject's public key.
1000	/// This key identifier is used in the SubjectKeyIdentifier X.509v3 extension.
1001	fn key_identifier<K: PublicKeyData>(&self, pub_key: &K) -> Vec<u8> {
1002		// Decide which method from RFC 7093 to use
1003		let digest_method = match self.key_identifier_method {
1004			KeyIdMethod::Sha256 => &digest::SHA256,
1005			KeyIdMethod::Sha384 => &digest::SHA384,
1006			KeyIdMethod::Sha512 => &digest::SHA512,
1007		};
1008		let digest = digest::digest(digest_method, pub_key.raw_bytes());
1009		let truncated_digest = &digest.as_ref()[0..20];
1010		truncated_digest.to_vec()
1011	}
1012	fn serialize_der_with_signer<K: PublicKeyData>(&self, pub_key: &K, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
1013		yasna::try_construct_der(|writer| {
1014			writer.write_sequence(|writer| {
1015
1016				let tbs_cert_list_serialized = yasna::try_construct_der(|writer| {
1017					self.write_cert(writer, pub_key, ca)?;
1018					Ok::<(), RcgenError>(())
1019				})?;
1020				// Write tbsCertList
1021				writer.next().write_der(&tbs_cert_list_serialized);
1022
1023				// Write signatureAlgorithm
1024				ca.params.alg.write_alg_ident(writer.next());
1025
1026				// Write signature
1027				ca.key_pair.sign(&tbs_cert_list_serialized, writer.next())?;
1028
1029				Ok(())
1030			})
1031		})
1032	}
1033}
1034
1035/// Whether the certificate is allowed to sign other certificates
1036#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1037pub enum IsCa {
1038	/// The certificate can only sign itself
1039	NoCa,
1040	/// The certificate can only sign itself, adding the extension and `CA:FALSE`
1041	ExplicitNoCa,
1042	/// The certificate may be used to sign other certificates
1043	Ca(BasicConstraints),
1044}
1045
1046/// The path length constraint (only relevant for CA certificates)
1047///
1048/// Sets an optional upper limit on the length of the intermediate certificate chain
1049/// length allowed for this CA certificate (not including the end entity certificate).
1050#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1051pub enum BasicConstraints {
1052	/// No constraint
1053	Unconstrained,
1054	/// Constrain to the contained number of intermediate certificates
1055	Constrained(u8),
1056}
1057
1058impl CertificateParams {
1059	/// Generate certificate parameters with reasonable defaults
1060	pub fn new(subject_alt_names :impl Into<Vec<String>>) -> Self {
1061		let subject_alt_names = subject_alt_names.into()
1062			.into_iter()
1063			.map(|s| SanType::DnsName(s))
1064			.collect::<Vec<_>>();
1065		CertificateParams {
1066			subject_alt_names,
1067			.. Default::default()
1068		}
1069	}
1070}
1071
1072/// The [NameConstraints extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.10)
1073/// (only relevant for CA certificates)
1074#[derive(Debug, PartialEq, Eq, Clone)]
1075pub struct NameConstraints {
1076	/// If non-empty, a whitelist of subtrees that the
1077	/// domain has to match.
1078	pub permitted_subtrees :Vec<GeneralSubtree>,
1079	/// A list of excluded subtrees.
1080	///
1081	/// Any name matching an excluded subtree is invalid
1082	/// even if it also matches a permitted subtree.
1083	pub excluded_subtrees :Vec<GeneralSubtree>,
1084}
1085
1086impl NameConstraints {
1087	fn is_empty(&self) -> bool {
1088		self.permitted_subtrees.is_empty() && self.excluded_subtrees.is_empty()
1089	}
1090}
1091
1092/// One of the purposes contained in the [key usage](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3) extension
1093#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1094pub enum KeyUsagePurpose {
1095	/// digitalSignature
1096	DigitalSignature,
1097	/// contentCommitment / nonRepudiation
1098	ContentCommitment,
1099	/// keyEncipherment
1100	KeyEncipherment,
1101	/// dataEncipherment
1102	DataEncipherment,
1103	/// keyAgreement
1104	KeyAgreement,
1105	/// keyCertSign
1106	KeyCertSign,
1107	/// cRLSign
1108	CrlSign,
1109	/// encipherOnly
1110	EncipherOnly,
1111	/// decipherOnly
1112	DecipherOnly,
1113}
1114
1115#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1116/// One of the purposes contained in the [extended key usage extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.12)
1117pub enum ExtendedKeyUsagePurpose {
1118	/// anyExtendedKeyUsage
1119	Any,
1120	/// id-kp-serverAuth
1121	ServerAuth,
1122	/// id-kp-clientAuth
1123	ClientAuth,
1124	/// id-kp-codeSigning
1125	CodeSigning,
1126	/// id-kp-emailProtection
1127	EmailProtection,
1128	/// id-kp-timeStamping
1129	TimeStamping,
1130	/// id-kp-OCSPSigning
1131	OcspSigning,
1132}
1133
1134impl ExtendedKeyUsagePurpose {
1135	fn oid(&self) -> &'static [u64] {
1136		use ExtendedKeyUsagePurpose::*;
1137		match self {
1138			// anyExtendedKeyUsage
1139			Any => &[2, 5, 29, 37],
1140			// id-kp-*
1141			ServerAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 1],
1142			ClientAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 2],
1143			CodeSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 3],
1144			EmailProtection => &[1, 3, 6, 1, 5, 5, 7, 3, 4],
1145			TimeStamping => &[1, 3, 6, 1, 5, 5, 7, 3, 8],
1146			OcspSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 9],
1147		}
1148	}
1149}
1150
1151/// A custom extension of a certificate, as specified in
1152/// [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2)
1153#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1154pub struct CustomExtension {
1155	oid :Vec<u64>,
1156	critical :bool,
1157
1158	/// The content must be DER-encoded
1159	content :Vec<u8>,
1160}
1161
1162impl CustomExtension {
1163	/// Creates a new acmeIdentifier extension for ACME TLS-ALPN-01
1164	/// as specified in [RFC 8737](https://tools.ietf.org/html/rfc8737#section-3)
1165	///
1166	/// Panics if the passed `sha_digest` parameter doesn't hold 32 bytes (256 bits).
1167	pub fn new_acme_identifier(sha_digest :&[u8]) -> Self {
1168		assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest");
1169		let content = yasna::construct_der(|writer| {
1170			writer.write_bytes(sha_digest);
1171		});
1172		Self {
1173			oid : OID_PE_ACME.to_owned(),
1174			critical : true,
1175			content,
1176		}
1177	}
1178	/// Create a new custom extension with the specified content
1179	pub fn from_oid_content(oid :&[u64], content :Vec<u8>) -> Self {
1180		Self {
1181			oid : oid.to_owned(),
1182			critical : false,
1183			content,
1184		}
1185	}
1186	/// Sets the criticality flag of the extension.
1187	pub fn set_criticality(&mut self, criticality :bool) {
1188		self.critical = criticality;
1189	}
1190	/// Obtains the criticality flag of the extension.
1191	pub fn criticality(&self) -> bool {
1192		self.critical
1193	}
1194	/// Obtains the content of the extension.
1195	pub fn content(&self) -> &[u8] {
1196		&self.content
1197	}
1198	/// Obtains the OID components of the extensions, as u64 pieces
1199	pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ {
1200		self.oid.iter().copied()
1201	}
1202}
1203
1204/// Method to generate key identifiers from public keys.
1205///
1206/// This allows choice over methods to generate key identifiers
1207/// as specified in RFC 7093 section 2.
1208#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1209#[non_exhaustive]
1210pub enum KeyIdMethod {
1211	/// RFC 7093 method 1
1212	Sha256,
1213	/// RFC 7093 method 2
1214	Sha384,
1215	/// RFC 7093 method 3
1216	Sha512,
1217}
1218
1219/// Helper to obtain an `OffsetDateTime` from year, month, day values
1220///
1221/// The year, month, day values are assumed to be in UTC.
1222///
1223/// This helper function serves two purposes: first, so that you don't
1224/// have to import the time crate yourself in order to specify date
1225/// information, second so that users don't have to type unproportionately
1226/// long code just to generate an instance of [`OffsetDateTime`].
1227pub fn date_time_ymd(year :i32, month :u8, day :u8) -> OffsetDateTime {
1228	let month = Month::try_from(month).expect("out-of-range month");
1229	let primitive_dt = PrimitiveDateTime::new(
1230		Date::from_calendar_date(year, month, day).expect("invalid or out-of-range date"),
1231		Time::MIDNIGHT
1232	);
1233	primitive_dt.assume_utc()
1234}
1235
1236fn dt_strip_nanos(dt :OffsetDateTime) -> OffsetDateTime {
1237	// Set nanoseconds to zero
1238	// This is needed because the GeneralizedTime serializer would otherwise
1239	// output fractional values which RFC 5280 explicitly forbode [1].
1240	// UTCTime cannot express fractional seconds or leap seconds
1241	// therefore, it needs to be stripped of nanoseconds fully.
1242	// [1]: https://tools.ietf.org/html/rfc5280#section-4.1.2.5.2
1243	// TODO: handle leap seconds if dt becomes leap second aware
1244	let time = Time::from_hms(dt.hour(), dt.minute(), dt.second())
1245		.expect("invalid or out-of-range time");
1246	dt.replace_time(time)
1247}
1248
1249fn dt_to_generalized(dt :OffsetDateTime) -> GeneralizedTime {
1250	let date_time = dt_strip_nanos(dt);
1251	GeneralizedTime::from_datetime(date_time)
1252}
1253
1254fn write_dt_utc_or_generalized(writer :DERWriter, dt :OffsetDateTime) {
1255	// RFC 5280 requires CAs to write certificate validity dates
1256	// below 2050 as UTCTime, and anything starting from 2050
1257	// as GeneralizedTime [1]. The RFC doesn't say anything
1258	// about dates before 1950, but as UTCTime can't represent
1259	// them, we have to use GeneralizedTime if we want to or not.
1260	// [1]: https://tools.ietf.org/html/rfc5280#section-4.1.2.5
1261	if (1950..2050).contains(&dt.year()) {
1262		let date_time = dt_strip_nanos(dt);
1263		let ut = UTCTime::from_datetime(date_time);
1264		writer.write_utctime(&ut);
1265	} else {
1266		let gt = dt_to_generalized(dt);
1267		writer.write_generalized_time(&gt);
1268	}
1269}
1270
1271fn write_distinguished_name(writer :DERWriter, dn :&DistinguishedName) {
1272		writer.write_sequence(|writer| {
1273			for (ty, content) in dn.iter() {
1274				writer.next().write_set(|writer| {
1275					writer.next().write_sequence(|writer| {
1276						writer.next().write_oid(&ty.to_oid());
1277						match content {
1278							DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
1279								writer.write_bytes(s)
1280							}),
1281							DnValue::PrintableString(s) => writer.next().write_printable_string(s),
1282							DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
1283								writer.write_bytes(s)
1284							}),
1285							DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
1286							DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
1287								writer.write_bytes(s)
1288							}),
1289						}
1290					});
1291				});
1292			}
1293		});
1294}
1295
1296fn write_general_subtrees(writer :DERWriter, tag :u64, general_subtrees :&[GeneralSubtree]) {
1297	writer.write_tagged_implicit(Tag::context(tag), |writer| {
1298		writer.write_sequence(|writer| {
1299			for subtree in general_subtrees.iter() {
1300				writer.next().write_sequence(|writer| {
1301					writer.next().write_tagged_implicit(Tag::context(subtree.tag()), |writer| {
1302						match subtree {
1303							GeneralSubtree::Rfc822Name(name) |
1304							GeneralSubtree::DnsName(name) => writer.write_ia5_string(name),
1305							GeneralSubtree::DirectoryName(name) => write_distinguished_name(writer, name),
1306							GeneralSubtree::IpAddress(subnet) => writer.write_bytes(&subnet.to_bytes()),
1307						}
1308					});
1309					// minimum must be 0 (the default) and maximum must be absent
1310				});
1311			}
1312		});
1313	});
1314}
1315
1316impl Certificate {
1317	/// Generates a new certificate from the given parameters
1318	pub fn from_params(mut params :CertificateParams) -> Result<Self, RcgenError> {
1319		let key_pair = if let Some(key_pair) = params.key_pair.take() {
1320			if !key_pair.is_compatible(&params.alg) {
1321				return Err(RcgenError::CertificateKeyPairMismatch);
1322			}
1323			key_pair
1324		} else {
1325			KeyPair::generate(&params.alg)?
1326		};
1327
1328		Ok(Certificate {
1329			params,
1330			key_pair,
1331		})
1332	}
1333	/// Calculates a subject key identifier for the certificate subject's public key.
1334	/// This key identifier is used in the SubjectKeyIdentifier X.509v3 extension.
1335	pub fn get_key_identifier(&self) -> Vec<u8> {
1336		self.params.key_identifier(&self.key_pair)
1337	}
1338	/// Serializes the certificate to the binary DER format
1339	pub fn serialize_der(&self) -> Result<Vec<u8>, RcgenError> {
1340		self.serialize_der_with_signer(&self)
1341	}
1342	/// Serializes the certificate, signed with another certificate's key, in binary DER format
1343	pub fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
1344		self.params.serialize_der_with_signer(&self.key_pair, ca)
1345	}
1346	/// Serializes a certificate signing request in binary DER format
1347	pub fn serialize_request_der(&self) -> Result<Vec<u8>, RcgenError> {
1348		yasna::try_construct_der(|writer| {
1349			writer.write_sequence(|writer| {
1350				let cert_data = yasna::construct_der(|writer| {
1351					self.params.write_request(&self.key_pair, writer);
1352				});
1353				writer.next().write_der(&cert_data);
1354
1355				// Write signatureAlgorithm
1356				self.params.alg.write_alg_ident(writer.next());
1357
1358				// Write signature
1359				self.key_pair.sign(&cert_data, writer.next())?;
1360
1361				Ok(())
1362			})
1363		})
1364	}
1365	/// Return the certificate's key pair
1366	pub fn get_key_pair(&self) -> &KeyPair {
1367		&self.key_pair
1368	}
1369	/// Serializes the certificate to the ASCII PEM format
1370	///
1371	/// *This function is only available if rcgen is built with the "pem" feature*
1372	#[cfg(feature = "pem")]
1373	pub fn serialize_pem(&self) -> Result<String, RcgenError> {
1374		let p = Pem {
1375			tag : "CERTIFICATE".to_string(),
1376			contents : self.serialize_der()?,
1377		};
1378		Ok(pem::encode(&p))
1379	}
1380	/// Serializes the certificate, signed with another certificate's key, to the ASCII PEM format
1381	///
1382	/// *This function is only available if rcgen is built with the "pem" feature*
1383	#[cfg(feature = "pem")]
1384	pub fn serialize_pem_with_signer(&self, ca :&Certificate) -> Result<String, RcgenError> {
1385		let p = Pem {
1386			tag : "CERTIFICATE".to_string(),
1387			contents : self.serialize_der_with_signer(ca)?,
1388		};
1389		Ok(pem::encode(&p))
1390	}
1391	/// Serializes the certificate signing request to the ASCII PEM format
1392	///
1393	/// *This function is only available if rcgen is built with the "pem" feature*
1394	#[cfg(feature = "pem")]
1395	pub fn serialize_request_pem(&self) -> Result<String, RcgenError> {
1396		let p = Pem {
1397			tag : "CERTIFICATE REQUEST".to_string(),
1398			contents : self.serialize_request_der()?,
1399		};
1400		Ok(pem::encode(&p))
1401	}
1402	/// Serializes the private key in PKCS#8 format
1403	///
1404	/// Panics if called on a remote key pair.
1405	pub fn serialize_private_key_der(&self) -> Vec<u8> {
1406		self.key_pair.serialize_der()
1407	}
1408	/// Serializes the private key in PEM format
1409	///
1410	/// Panics if called on a remote key pair.
1411	///
1412	/// *This function is only available if rcgen is built with the "pem" feature*
1413	#[cfg(feature = "pem")]
1414	pub fn serialize_private_key_pem(&self) -> String {
1415		self.key_pair.serialize_pem()
1416	}
1417}
1418
1419enum SignAlgo {
1420	EcDsa(&'static EcdsaSigningAlgorithm),
1421	EdDsa(&'static EdDSAParameters),
1422	Rsa(),
1423}
1424
1425/// A key pair vairant
1426#[allow(clippy::large_enum_variant)]
1427enum KeyPairKind {
1428	/// A Ecdsa key pair
1429	Ec(EcdsaKeyPair),
1430	/// A Ed25519 key pair
1431	Ed(Ed25519KeyPair),
1432	/// A RSA key pair
1433	Rsa(RsaKeyPair, &'static dyn RsaEncoding),
1434	/// A remote key pair
1435	Remote(Box<dyn RemoteKeyPair + Send + Sync>),
1436}
1437
1438impl fmt::Debug for KeyPairKind {
1439	fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1440		match self {
1441			Self::Ec(key_pair) => write!(f, "{:?}", key_pair),
1442			Self::Ed(key_pair) => write!(f, "{:?}", key_pair),
1443			Self::Rsa(key_pair, _) => write!(f, "{:?}", key_pair),
1444			Self::Remote(_) => write!(f, "Box<dyn RemotePrivateKey>"),
1445		}
1446	}
1447}
1448
1449/// A key pair used to sign certificates and CSRs
1450///
1451/// Note that ring, the underlying library to handle RSA keys
1452/// requires them to be in a special format, meaning that
1453/// `openssl genrsa` doesn't work. See ring's [documentation](ring::signature::RsaKeyPair::from_pkcs8)
1454/// for how to generate RSA keys in the wanted format
1455/// and conversion between the formats.
1456#[derive(Debug)]
1457pub struct KeyPair {
1458	kind :KeyPairKind,
1459	alg :&'static SignatureAlgorithm,
1460	serialized_der :Vec<u8>,
1461}
1462
1463impl KeyPair {
1464	/// Parses the key pair from the DER format
1465	///
1466	/// Equivalent to using the [`TryFrom`] implementation.
1467	pub fn from_der(der :&[u8]) -> Result<Self, RcgenError> {
1468		Ok(der.try_into()?)
1469	}
1470	/// Parses the key pair from the ASCII PEM format
1471	///
1472	/// *This constructor is only available if rcgen is built with the "pem" feature*
1473	#[cfg(feature = "pem")]
1474	pub fn from_pem(pem_str :&str) -> Result<Self, RcgenError> {
1475		let private_key = pem::parse(pem_str)?;
1476		let private_key_der :&[_] = &private_key.contents;
1477		Ok(private_key_der.try_into()?)
1478	}
1479
1480	/// Obtains the key pair from a raw public key and a remote private key
1481	pub fn from_remote(key_pair :Box<dyn RemoteKeyPair + Send + Sync>) -> Result<Self, RcgenError> {
1482		Ok(Self {
1483			alg : key_pair.algorithm(),
1484			kind : KeyPairKind::Remote(key_pair),
1485			serialized_der : Vec::new(),
1486		})
1487	}
1488
1489
1490	/// Obtains the key pair from a DER formatted key
1491	/// using the specified [`SignatureAlgorithm`](SignatureAlgorithm)
1492	///
1493	/// Same as [from_pem_and_sign_algo](Self::from_pem_and_sign_algo).
1494	///
1495	/// *This constructor is only available if rcgen is built with the "pem" feature*
1496	#[cfg(feature = "pem")]
1497	pub fn from_pem_and_sign_algo(pem_str :&str, alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1498		let private_key = pem::parse(pem_str)?;
1499		let private_key_der :&[_] = &private_key.contents;
1500		Ok(Self::from_der_and_sign_algo(private_key_der, alg)?)
1501	}
1502
1503	/// Obtains the key pair from a DER formatted key
1504	/// using the specified [`SignatureAlgorithm`](SignatureAlgorithm)
1505	///
1506	/// Usually, calling this function is not neccessary and you can just call
1507	/// [`from_der`](Self::from_der) instead. That function will try to figure
1508	/// out a fitting [`SignatureAlgorithm`](SignatureAlgorithm) for the given
1509	/// key pair. However sometimes multiple signature algorithms fit for the
1510	/// same der key. In that instance, you can use this function to precisely
1511	/// specify the `SignatureAlgorithm`.
1512	pub fn from_der_and_sign_algo(pkcs8 :&[u8], alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1513		let pkcs8_vec = pkcs8.to_vec();
1514
1515		let kind = if alg == &PKCS_ED25519 {
1516			KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)?)
1517		} else if alg == &PKCS_ECDSA_P256_SHA256 {
1518			KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8)?)
1519		} else if alg == &PKCS_ECDSA_P384_SHA384 {
1520			KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, pkcs8)?)
1521		} else if alg == &PKCS_RSA_SHA256 {
1522			let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1523			KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256)
1524		} else if alg == &PKCS_RSA_SHA384 {
1525			let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1526			KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA384)
1527		} else if alg == &PKCS_RSA_SHA512 {
1528			let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1529			KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA512)
1530		} else if alg == &PKCS_RSA_PSS_SHA256 {
1531			let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1532			KeyPairKind::Rsa(rsakp, &signature::RSA_PSS_SHA256)
1533		} else {
1534			panic!("Unknown SignatureAlgorithm specified!");
1535		};
1536
1537		Ok(KeyPair {
1538			kind,
1539			alg,
1540			serialized_der : pkcs8_vec,
1541		})
1542	}
1543
1544	fn from_raw(pkcs8: &[u8]) -> Result<(KeyPairKind, &'static SignatureAlgorithm), RcgenError> {
1545		let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
1546			(KeyPairKind::Ed(edkp), &PKCS_ED25519)
1547		} else if let Ok(eckp) = EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8) {
1548			(KeyPairKind::Ec(eckp), &PKCS_ECDSA_P256_SHA256)
1549		} else if let Ok(eckp) = EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, pkcs8) {
1550			(KeyPairKind::Ec(eckp), &PKCS_ECDSA_P384_SHA384)
1551		} else if let Ok(rsakp) = RsaKeyPair::from_pkcs8(pkcs8) {
1552			(KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256), &PKCS_RSA_SHA256)
1553		} else {
1554			return Err(RcgenError::CouldNotParseKeyPair);
1555		};
1556		Ok((kind, alg))
1557	}
1558}
1559
1560/// A private key that is not directly accessible, but can be used to sign messages
1561///
1562/// Trait objects based on this trait can be passed to the [`KeyPair::from_remote`] function to generating certificates
1563/// from a remote and raw private key, for example an HSM.
1564pub trait RemoteKeyPair {
1565	/// Returns the public key of this key pair in the binary format as in [`KeyPair::public_key_raw`]
1566	fn public_key(&self) -> &[u8];
1567
1568	/// Signs `msg` using the selected algorithm
1569	fn sign(&self, msg :&[u8]) -> Result<Vec<u8>, RcgenError>;
1570
1571	/// Reveals which algorithm will be used when you call `sign()`
1572	fn algorithm(&self) -> &'static SignatureAlgorithm;
1573}
1574
1575#[derive(Debug, PartialEq, Eq)]
1576#[non_exhaustive]
1577/// The error type of the rcgen crate
1578pub enum RcgenError {
1579	/// The given certificate couldn't be parsed
1580	CouldNotParseCertificate,
1581	/// The given certificate signing request couldn't be parsed
1582	CouldNotParseCertificationRequest,
1583	/// The given key pair couldn't be parsed
1584	CouldNotParseKeyPair,
1585	#[cfg(feature = "x509-parser")]
1586	/// Invalid subject alternative name type
1587	InvalidNameType,
1588	/// There is no support for generating
1589	/// keys for the given algorithm
1590	KeyGenerationUnavailable,
1591	#[cfg(feature = "x509-parser")]
1592	/// Unsupported extension requested in CSR
1593	UnsupportedExtension,
1594	/// The requested signature algorithm is not supported
1595	UnsupportedSignatureAlgorithm,
1596	/// Unspecified `ring` error
1597	RingUnspecified,
1598	/// The `ring` library rejected the key upon loading
1599	RingKeyRejected(&'static str),
1600	/// The provided certificate's signature algorithm
1601	/// is incompatible with the given key pair
1602	CertificateKeyPairMismatch,
1603	/// Time conversion related errors
1604	Time,
1605	#[cfg(feature = "pem")]
1606	/// Error from the pem crate
1607	///
1608	/// *This variant is only available if rcgen is built with the "pem" feature*
1609	PemError(pem::PemError),
1610	/// Error generated by a remote key operation
1611	RemoteKeyError,
1612}
1613
1614impl fmt::Display for RcgenError {
1615	fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1616		use self::RcgenError::*;
1617		match self {
1618			CouldNotParseCertificate => write!(f, "Could not parse certificate")?,
1619			CouldNotParseCertificationRequest => write!(f, "Could not parse certificate signing \
1620				request")?,
1621			CouldNotParseKeyPair => write!(f, "Could not parse key pair")?,
1622			#[cfg(feature = "x509-parser")]
1623			InvalidNameType => write!(f, "Invalid subject alternative name type")?,
1624			KeyGenerationUnavailable => write!(f, "There is no support for generating \
1625				keys for the given algorithm")?,
1626			UnsupportedSignatureAlgorithm => write!(f, "The requested signature algorithm \
1627				is not supported")?,
1628			#[cfg(feature = "x509-parser")]
1629			UnsupportedExtension => write!(f, "Unsupported extension requested in CSR")?,
1630			RingUnspecified => write!(f, "Unspecified ring error")?,
1631			RingKeyRejected(e) => write!(f, "Key rejected by ring: {}", e)?,
1632			CertificateKeyPairMismatch => write!(f, "The provided certificate's signature \
1633				algorithm is incompatible with the given key pair")?,
1634
1635			Time => write!(f, "Time error")?,
1636			RemoteKeyError => write!(f, "Remote key error")?,
1637			#[cfg(feature = "pem")]
1638			PemError(e) => write!(f, "PEM error: {}", e)?,
1639		};
1640		Ok(())
1641	}
1642}
1643
1644impl Error for RcgenError {}
1645
1646impl From<ring::error::Unspecified> for RcgenError {
1647	fn from(_unspecified :ring::error::Unspecified) -> Self {
1648		RcgenError::RingUnspecified
1649	}
1650}
1651
1652impl From<ring::error::KeyRejected> for RcgenError {
1653	fn from(err :ring::error::KeyRejected) -> Self {
1654		RcgenError::RingKeyRejected(err.description_())
1655	}
1656}
1657
1658#[cfg(feature = "pem")]
1659impl From<pem::PemError> for RcgenError {
1660	fn from(e :pem::PemError) -> Self {
1661		RcgenError::PemError(e)
1662	}
1663}
1664
1665impl TryFrom<&[u8]> for KeyPair {
1666	type Error = RcgenError;
1667
1668	fn try_from(pkcs8: &[u8]) -> Result<KeyPair, RcgenError> {
1669		let (kind, alg) = KeyPair::from_raw(pkcs8)?;
1670		Ok(KeyPair {
1671			kind,
1672			alg,
1673			serialized_der: pkcs8.to_vec(),
1674		})
1675	}
1676}
1677
1678impl TryFrom<Vec<u8>> for KeyPair {
1679	type Error = RcgenError;
1680
1681	fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, RcgenError> {
1682		let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
1683		Ok(KeyPair {
1684			kind,
1685			alg,
1686			serialized_der: pkcs8,
1687		})
1688	}
1689}
1690
1691impl KeyPair {
1692	/// Generate a new random key pair for the specified signature algorithm
1693	pub fn generate(alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1694		let system_random = SystemRandom::new();
1695		match alg.sign_alg {
1696			SignAlgo::EcDsa(sign_alg) => {
1697				let key_pair_doc = EcdsaKeyPair::generate_pkcs8(sign_alg, &system_random)?;
1698				let key_pair_serialized = key_pair_doc.as_ref().to_vec();
1699
1700				let key_pair = EcdsaKeyPair::from_pkcs8(&sign_alg, &&key_pair_doc.as_ref()).unwrap();
1701				Ok(KeyPair {
1702					kind : KeyPairKind::Ec(key_pair),
1703					alg,
1704					serialized_der : key_pair_serialized,
1705				})
1706			},
1707			SignAlgo::EdDsa(_sign_alg) => {
1708				let key_pair_doc = Ed25519KeyPair::generate_pkcs8(&system_random)?;
1709				let key_pair_serialized = key_pair_doc.as_ref().to_vec();
1710
1711				let key_pair = Ed25519KeyPair::from_pkcs8(&&key_pair_doc.as_ref()).unwrap();
1712				Ok(KeyPair {
1713					kind : KeyPairKind::Ed(key_pair),
1714					alg,
1715					serialized_der : key_pair_serialized,
1716				})
1717			},
1718			// Ring doesn't have RSA key generation yet:
1719			// https://github.com/briansmith/ring/issues/219
1720			// https://github.com/briansmith/ring/pull/733
1721			SignAlgo::Rsa() => Err(RcgenError::KeyGenerationUnavailable),
1722		}
1723	}
1724	/// Get the raw public key of this key pair
1725	///
1726	/// The key is in raw format, as how [`ring::signature::KeyPair::public_key`]
1727	/// would output, and how [`ring::signature::UnparsedPublicKey::verify`]
1728	/// would accept.
1729	pub fn public_key_raw(&self) -> &[u8] {
1730		self.raw_bytes()
1731	}
1732	/// Check if this key pair can be used with the given signature algorithm
1733	pub fn is_compatible(&self, signature_algorithm :&SignatureAlgorithm) -> bool {
1734		self.alg == signature_algorithm
1735	}
1736	/// Returns (possibly multiple) compatible [`SignatureAlgorithm`]'s
1737	/// that the key can be used with
1738	pub fn compatible_algs(&self)
1739			-> impl Iterator<Item=&'static SignatureAlgorithm> {
1740		std::iter::once(self.alg)
1741	}
1742	fn sign(&self, msg :&[u8], writer :DERWriter) -> Result<(), RcgenError> {
1743		match &self.kind {
1744			KeyPairKind::Ec(kp) => {
1745				let system_random = SystemRandom::new();
1746				let signature = kp.sign(&system_random, msg)?;
1747				let sig = &signature.as_ref();
1748				writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1749			},
1750			KeyPairKind::Ed(kp) => {
1751				let signature = kp.sign(msg);
1752				let sig = &signature.as_ref();
1753				writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1754			},
1755			KeyPairKind::Rsa(kp, padding_alg) => {
1756				let system_random = SystemRandom::new();
1757				let mut signature = vec![0; kp.public_modulus_len()];
1758				kp.sign(*padding_alg, &system_random,
1759					msg, &mut signature)?;
1760				let sig = &signature.as_ref();
1761				writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1762			},
1763			KeyPairKind::Remote(kp) => {
1764				let signature = kp.sign(msg)?;
1765				writer.write_bitvec_bytes(&signature, &signature.len() * 8);
1766			},
1767		}
1768		Ok(())
1769	}
1770	/// Return the key pair's public key in DER format
1771	///
1772	/// The key is formatted according to the SubjectPublicKeyInfo struct of
1773	/// X.509.
1774	/// See [RFC 5280 section 4.1](https://tools.ietf.org/html/rfc5280#section-4.1).
1775	pub fn public_key_der(&self) -> Vec<u8> {
1776		yasna::construct_der(|writer| self.serialize_public_key_der(writer))
1777	}
1778	/// Return the key pair's public key in PEM format
1779	///
1780	/// The returned string can be interpreted with `openssl pkey --inform PEM -pubout -pubin -text`
1781	///
1782	/// *This function is only available if rcgen is built with the "pem" feature*
1783	#[cfg(feature = "pem")]
1784	pub fn public_key_pem(&self) -> String {
1785		let p = Pem {
1786			tag : "PUBLIC KEY".to_string(),
1787			contents : self.public_key_der(),
1788		};
1789		pem::encode(&p)
1790	}
1791	/// Serializes the key pair (including the private key) in PKCS#8 format in DER
1792	///
1793	/// Panics if called on a remote key pair.
1794	pub fn serialize_der(&self) -> Vec<u8> {
1795		if let KeyPairKind::Remote(_) = self.kind {
1796			panic!("Serializing a remote key pair is not supported")
1797		}
1798
1799		self.serialized_der.clone()
1800	}
1801
1802	/// Returns a reference to the serialized key pair (including the private key)
1803	/// in PKCS#8 format in DER
1804	///
1805	/// Panics if called on a remote key pair.
1806	pub fn serialized_der(&self) -> &[u8] {
1807		if let KeyPairKind::Remote(_) = self.kind {
1808			panic!("Serializing a remote key pair is not supported")
1809		}
1810
1811		&self.serialized_der
1812	}
1813
1814	/// Serializes the key pair (including the private key) in PKCS#8 format in PEM
1815	///
1816	/// *This function is only available if rcgen is built with the "pem" feature*
1817	#[cfg(feature = "pem")]
1818	pub fn serialize_pem(&self) -> String {
1819		let p = Pem {
1820			tag : "PRIVATE KEY".to_string(),
1821			contents : self.serialize_der(),
1822		};
1823		pem::encode(&p)
1824	}
1825}
1826
1827impl PublicKeyData for KeyPair {
1828	fn alg(&self) -> &SignatureAlgorithm {
1829		self.alg
1830	}
1831	fn raw_bytes(&self) -> &[u8] {
1832		match &self.kind {
1833			KeyPairKind::Ec(kp) => kp.public_key().as_ref(),
1834			KeyPairKind::Ed(kp) => kp.public_key().as_ref(),
1835			KeyPairKind::Rsa(kp, _) => kp.public_key().as_ref(),
1836			KeyPairKind::Remote(kp) => kp.public_key(),
1837		}
1838	}
1839}
1840
1841trait PublicKeyData {
1842	fn alg(&self) -> &SignatureAlgorithm;
1843	fn raw_bytes(&self) -> &[u8];
1844	fn serialize_public_key_der(&self, writer :DERWriter) {
1845		writer.write_sequence(|writer| {
1846			self.alg().write_oids_sign_alg(writer.next());
1847			let pk = self.raw_bytes();
1848			writer.next().write_bitvec_bytes(&pk, pk.len() * 8);
1849		})
1850	}
1851}
1852
1853#[derive(PartialEq, Eq)]
1854enum SignatureAlgorithmParams {
1855	/// Omit the parameters
1856	None,
1857	/// Write null parameters
1858	Null,
1859	/// RSASSA-PSS-params as per RFC 4055
1860	RsaPss {
1861		hash_algorithm :&'static [u64],
1862		salt_length :u64,
1863	},
1864}
1865
1866/// Signature algorithm type
1867pub struct SignatureAlgorithm {
1868	oids_sign_alg :&'static [&'static [u64]],
1869	sign_alg :SignAlgo,
1870	oid_components :&'static [u64],
1871	params :SignatureAlgorithmParams,
1872}
1873
1874impl fmt::Debug for SignatureAlgorithm {
1875	fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1876		if self == &PKCS_RSA_SHA256 {
1877			write!(f, "PKCS_RSA_SHA256")
1878		} else if self == &PKCS_RSA_SHA384 {
1879			write!(f, "PKCS_RSA_SHA384")
1880		} else if self == &PKCS_RSA_SHA512 {
1881			write!(f, "PKCS_RSA_SHA512")
1882		} else if self == &PKCS_RSA_PSS_SHA256 {
1883			write!(f, "PKCS_RSA_PSS_SHA256")
1884		} else if self == &PKCS_ECDSA_P256_SHA256 {
1885			write!(f, "PKCS_ECDSA_P256_SHA256")
1886		} else if self == &PKCS_ECDSA_P384_SHA384 {
1887			write!(f, "PKCS_ECDSA_P384_SHA384")
1888		} else if self == &PKCS_ED25519 {
1889			write!(f, "PKCS_ED25519")
1890		} else {
1891			write!(f, "Unknown")
1892		}
1893	}
1894}
1895
1896impl PartialEq for SignatureAlgorithm {
1897	fn eq(&self, other :&Self) -> bool {
1898		(self.oids_sign_alg, self.oid_components) == (other.oids_sign_alg, other.oid_components)
1899	}
1900}
1901
1902impl Eq for SignatureAlgorithm {}
1903
1904/// The `Hash` trait is not derived, but implemented according to impl of the `PartialEq` trait
1905impl Hash for SignatureAlgorithm {
1906	fn hash<H: Hasher>(&self, state: &mut H) {
1907		// see SignatureAlgorithm::eq(), just this field is compared
1908		self.oids_sign_alg.hash(state);
1909	}
1910}
1911
1912impl SignatureAlgorithm {
1913	fn iter() -> std::slice::Iter<'static, &'static SignatureAlgorithm> {
1914		static ALGORITHMS :&[&SignatureAlgorithm] = &[
1915			&PKCS_RSA_SHA256,
1916			&PKCS_RSA_SHA384,
1917			&PKCS_RSA_SHA512,
1918			//&PKCS_RSA_PSS_SHA256,
1919			&PKCS_ECDSA_P256_SHA256,
1920			&PKCS_ECDSA_P384_SHA384,
1921			&PKCS_ED25519
1922		];
1923		ALGORITHMS.iter()
1924	}
1925
1926	/// Retrieve the SignatureAlgorithm for the provided OID
1927	pub fn from_oid(oid :&[u64]) -> Result<&'static SignatureAlgorithm, RcgenError> {
1928		for algo in Self::iter() {
1929			if algo.oid_components == oid {
1930				return Ok(algo);
1931			}
1932		}
1933		Err(RcgenError::UnsupportedSignatureAlgorithm)
1934	}
1935}
1936
1937
1938/// RSA signing with PKCS#1 1.5 padding and SHA-256 hashing as per [RFC 4055](https://tools.ietf.org/html/rfc4055)
1939pub static PKCS_RSA_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1940	oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1941	sign_alg :SignAlgo::Rsa(),
1942	// sha256WithRSAEncryption in RFC 4055
1943	oid_components : &[1, 2, 840, 113549, 1, 1, 11],
1944	params : SignatureAlgorithmParams::Null,
1945};
1946
1947/// RSA signing with PKCS#1 1.5 padding and SHA-256 hashing as per [RFC 4055](https://tools.ietf.org/html/rfc4055)
1948pub static PKCS_RSA_SHA384 :SignatureAlgorithm = SignatureAlgorithm {
1949	oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1950	sign_alg :SignAlgo::Rsa(),
1951	// sha384WithRSAEncryption in RFC 4055
1952	oid_components : &[1, 2, 840, 113549, 1, 1, 12],
1953	params : SignatureAlgorithmParams::Null,
1954};
1955
1956/// RSA signing with PKCS#1 1.5 padding and SHA-512 hashing as per [RFC 4055](https://tools.ietf.org/html/rfc4055)
1957pub static PKCS_RSA_SHA512 :SignatureAlgorithm = SignatureAlgorithm {
1958	oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1959	sign_alg :SignAlgo::Rsa(),
1960	// sha512WithRSAEncryption in RFC 4055
1961	oid_components : &[1, 2, 840, 113549, 1, 1, 13],
1962	params : SignatureAlgorithmParams::Null,
1963};
1964
1965// TODO: not really sure whether the certs we generate actually work.
1966// Both openssl and webpki reject them. It *might* be possible that openssl
1967// accepts the certificate if the key is a proper RSA-PSS key, but ring doesn't
1968// support those: https://github.com/briansmith/ring/issues/1353
1969//
1970/// RSA signing with PKCS#1 2.1 RSASSA-PSS padding and SHA-256 hashing as per [RFC 4055](https://tools.ietf.org/html/rfc4055)
1971static PKCS_RSA_PSS_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1972	// We could also use OID_RSA_ENCRYPTION here, but it's recommended
1973	// to use ID-RSASSA-PSS if possible.
1974	oids_sign_alg :&[&OID_RSASSA_PSS],
1975	sign_alg :SignAlgo::Rsa(),
1976	oid_components : &OID_RSASSA_PSS,//&[1, 2, 840, 113549, 1, 1, 13],
1977	// rSASSA-PSS-SHA256-Params in RFC 4055
1978	params : SignatureAlgorithmParams::RsaPss {
1979		// id-sha256 in https://datatracker.ietf.org/doc/html/rfc4055#section-2.1
1980		hash_algorithm : &[2, 16, 840, 1, 101, 3, 4, 2, 1],
1981		salt_length : 20,
1982	},
1983};
1984
1985/// ECDSA signing using the P-256 curves and SHA-256 hashing as per [RFC 5758](https://tools.ietf.org/html/rfc5758#section-3.2)
1986pub static PKCS_ECDSA_P256_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1987	oids_sign_alg :&[&OID_EC_PUBLIC_KEY, &OID_EC_SECP_256_R1],
1988	sign_alg :SignAlgo::EcDsa(&signature::ECDSA_P256_SHA256_ASN1_SIGNING),
1989	/// ecdsa-with-SHA256 in RFC 5758
1990	oid_components : &[1, 2, 840, 10045, 4, 3, 2],
1991	params : SignatureAlgorithmParams::None,
1992};
1993
1994/// ECDSA signing using the P-384 curves and SHA-384 hashing as per [RFC 5758](https://tools.ietf.org/html/rfc5758#section-3.2)
1995pub static PKCS_ECDSA_P384_SHA384 :SignatureAlgorithm = SignatureAlgorithm {
1996	oids_sign_alg :&[&OID_EC_PUBLIC_KEY, &OID_EC_SECP_384_R1],
1997	sign_alg :SignAlgo::EcDsa(&signature::ECDSA_P384_SHA384_ASN1_SIGNING),
1998	/// ecdsa-with-SHA384 in RFC 5758
1999	oid_components : &[1, 2, 840, 10045, 4, 3, 3],
2000	params : SignatureAlgorithmParams::None,
2001};
2002
2003// TODO PKCS_ECDSA_P521_SHA512 https://github.com/briansmith/ring/issues/824
2004
2005/// ED25519 curve signing as per [RFC 8410](https://tools.ietf.org/html/rfc8410)
2006pub static PKCS_ED25519 :SignatureAlgorithm = SignatureAlgorithm {
2007	/// id-Ed25519 in RFC 8410
2008	oids_sign_alg :&[&[1, 3, 101, 112]],
2009	sign_alg :SignAlgo::EdDsa(&signature::ED25519),
2010	/// id-Ed25519 in RFC 8410
2011	oid_components : &[1, 3, 101, 112],
2012	params : SignatureAlgorithmParams::None,
2013};
2014
2015// Signature algorithm IDs as per https://tools.ietf.org/html/rfc4055
2016impl SignatureAlgorithm {
2017	fn alg_ident_oid(&self) -> ObjectIdentifier {
2018		ObjectIdentifier::from_slice(self.oid_components)
2019	}
2020	fn write_params(&self, writer :&mut yasna::DERWriterSeq) {
2021		match self.params {
2022			SignatureAlgorithmParams::None => (),
2023			SignatureAlgorithmParams::Null => {
2024				writer.next().write_null();
2025			},
2026			SignatureAlgorithmParams::RsaPss {
2027				hash_algorithm, salt_length,
2028			} => {
2029				writer.next().write_sequence(|writer| {
2030					// https://datatracker.ietf.org/doc/html/rfc4055#section-3.1
2031
2032					let oid = ObjectIdentifier::from_slice(hash_algorithm);
2033					// hashAlgorithm
2034					writer.next().write_tagged(Tag::context(0), |writer| {
2035						writer.write_sequence(|writer| {
2036							writer.next().write_oid(&oid);
2037						});
2038					});
2039					// maskGenAlgorithm
2040					writer.next().write_tagged(Tag::context(1), |writer| {
2041						writer.write_sequence(|writer| {
2042							// id-mgf1 in RFC 4055
2043							const ID_MGF1 :&[u64] = &[1, 2, 840, 113549, 1, 1, 8];
2044							let oid = ObjectIdentifier::from_slice(ID_MGF1);
2045							writer.next().write_oid(&oid);
2046							writer.next().write_sequence(|writer| {
2047								let oid = ObjectIdentifier::from_slice(hash_algorithm);
2048								writer.next().write_oid(&oid);
2049								writer.next().write_null();
2050							});
2051						});
2052					});
2053					// saltLength
2054					writer.next().write_tagged(Tag::context(2), |writer| {
2055						writer.write_u64(salt_length);
2056					});
2057					// We *must* omit the trailerField element as per RFC 4055 section 3.1
2058				})
2059			},
2060		}
2061	}
2062	/// Writes the algorithm identifier as it appears inside a signature
2063	fn write_alg_ident(&self, writer :DERWriter) {
2064		writer.write_sequence(|writer| {
2065			writer.next().write_oid(&self.alg_ident_oid());
2066			self.write_params(writer);
2067		});
2068	}
2069	/// Writes the algorithm identifier as it appears inside subjectPublicKeyInfo
2070	fn write_oids_sign_alg(&self, writer :DERWriter) {
2071		writer.write_sequence(|writer| {
2072			for oid in self.oids_sign_alg {
2073				let oid = ObjectIdentifier::from_slice(oid);
2074				writer.next().write_oid(&oid);
2075			}
2076			self.write_params(writer);
2077		});
2078	}
2079}
2080
2081#[cfg(feature = "zeroize")]
2082impl zeroize::Zeroize for KeyPair {
2083	fn zeroize(&mut self) {
2084		self.serialized_der.zeroize();
2085	}
2086}
2087
2088#[cfg(feature = "zeroize")]
2089impl zeroize::Zeroize for Certificate {
2090	fn zeroize(&mut self) {
2091		self.params.zeroize();
2092		self.key_pair.zeroize();
2093	}
2094}
2095
2096#[cfg(feature = "zeroize")]
2097impl zeroize::Zeroize for CertificateSigningRequest {
2098	fn zeroize(&mut self) {
2099		self.params.zeroize();
2100	}
2101}
2102
2103#[cfg(feature = "zeroize")]
2104impl zeroize::Zeroize for CertificateParams {
2105	fn zeroize(&mut self) {
2106		self.key_pair.zeroize();
2107	}
2108}
2109
2110#[cfg(test)]
2111mod tests {
2112	use super::*;
2113
2114	use std::panic::catch_unwind;
2115
2116	fn get_times() -> [OffsetDateTime; 2] {
2117		let dt_nanos = {
2118			let date = Date::from_calendar_date(2020, Month::December, 3).unwrap();
2119			let time = Time::from_hms_nano(0, 0, 1, 444).unwrap();
2120			PrimitiveDateTime::new(date, time).assume_utc()
2121		};
2122		let dt_zero = {
2123			let date = Date::from_calendar_date(2020, Month::December, 3).unwrap();
2124			let time = Time::from_hms_nano(0, 0, 1, 0).unwrap();
2125			PrimitiveDateTime::new(date, time).assume_utc()
2126		};
2127		// TODO: include leap seconds if time becomes leap second aware
2128		[dt_nanos, dt_zero]
2129	}
2130
2131	#[test]
2132	fn test_dt_utc_strip_nanos() {
2133		let times = get_times();
2134
2135		// No stripping - OffsetDateTime with nanos
2136		let res = catch_unwind(|| UTCTime::from_datetime(times[0]));
2137		assert!(res.is_err());
2138
2139		// Stripping
2140		for dt in times {
2141			let date_time = dt_strip_nanos(dt);
2142			assert_eq!(date_time.time().nanosecond(), 0);
2143			let _ut = UTCTime::from_datetime(date_time);
2144		}
2145	}
2146
2147	#[test]
2148	fn test_dt_to_generalized() {
2149		let times = get_times();
2150
2151		for dt in times {
2152			let _gt = dt_to_generalized(dt);
2153		}
2154	}
2155
2156	#[test]
2157	fn test_with_key_usages() {
2158		let mut params: CertificateParams = Default::default();
2159
2160		// Set key_usages
2161		params.key_usages = vec![
2162			KeyUsagePurpose::DigitalSignature,
2163			KeyUsagePurpose::KeyEncipherment,
2164			KeyUsagePurpose::ContentCommitment,
2165		];
2166
2167		// This can sign things!
2168		params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
2169
2170		// Make the cert
2171		let cert = Certificate::from_params(params).unwrap();
2172
2173		// Serialize it
2174		let der = cert.serialize_der().unwrap();
2175
2176		// Parse it
2177		let (_rem, cert) = x509_parser::parse_x509_certificate(&der).unwrap();
2178
2179		// Check oid
2180		let key_usage_oid_str= "2.5.29.15";
2181
2182		// Found flag
2183		let mut found = false;
2184
2185		for ext in cert.extensions() {
2186			if key_usage_oid_str == ext.oid.to_id_string() {
2187				match ext.parsed_extension() {
2188					x509_parser::extensions::ParsedExtension::KeyUsage(usage) =>{
2189						assert!(usage.flags == 7);
2190						found = true;
2191					}
2192					_ => {}
2193				}
2194			}
2195		}
2196
2197		assert!(found);
2198	}
2199
2200	#[test]
2201	fn test_with_key_usages_decipheronly_only() {
2202		let mut params: CertificateParams = Default::default();
2203
2204		// Set key_usages
2205		params.key_usages = vec![KeyUsagePurpose::DecipherOnly];
2206
2207		// This can sign things!
2208		params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
2209
2210		// Make the cert
2211		let cert = Certificate::from_params(params).unwrap();
2212
2213		// Serialize it
2214		let der = cert.serialize_der().unwrap();
2215
2216		// Parse it
2217		let (_rem, cert) = x509_parser::parse_x509_certificate(&der).unwrap();
2218
2219		// Check oid
2220		let key_usage_oid_str= "2.5.29.15";
2221
2222		// Found flag
2223		let mut found = false;
2224
2225		for ext in cert.extensions() {
2226			if key_usage_oid_str == ext.oid.to_id_string() {
2227				match ext.parsed_extension() {
2228					x509_parser::extensions::ParsedExtension::KeyUsage(usage) =>{
2229						assert!(usage.flags == 256);
2230						found = true;
2231					}
2232					_ => {}
2233				}
2234			}
2235		}
2236
2237		assert!(found);
2238	}
2239
2240	#[test]
2241	fn signature_algos_different() {
2242		// TODO unify this with test_key_params_mismatch.
2243		// Note that that test doesn't have a full list of signature
2244		// algorithms, as it has no access to the iter function.
2245		for (i, alg_i) in SignatureAlgorithm::iter().enumerate() {
2246			for (j, alg_j) in SignatureAlgorithm::iter().enumerate() {
2247				assert_eq!(alg_i == alg_j, i == j,
2248					"Algorighm relationship mismatch for algorithm index pair {} and {}", i, j);
2249			}
2250		}
2251	}
2252}