Skip to main content

rcgen/
certificate.rs

1use std::net::IpAddr;
2use std::str::FromStr;
3
4#[cfg(feature = "pem")]
5use pem::Pem;
6use pki_types::{CertificateDer, CertificateSigningRequestDer};
7use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
8use yasna::models::ObjectIdentifier;
9use yasna::{DERWriter, DERWriterSeq, Tag};
10
11use crate::crl::CrlDistributionPoint;
12use crate::csr::CertificateSigningRequest;
13use crate::key_pair::{serialize_public_key_der, sign_der, PublicKeyData};
14#[cfg(feature = "crypto")]
15use crate::ring_like::digest;
16#[cfg(feature = "pem")]
17use crate::ENCODE_CONFIG;
18use crate::{
19	oid, write_distinguished_name, write_dt_utc_or_generalized,
20	write_x509_authority_key_identifier, write_x509_extension, DistinguishedName, Error, Issuer,
21	KeyIdMethod, KeyUsagePurpose, SanType, SerialNumber, SigningKey,
22};
23
24/// An issued certificate
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Certificate {
27	pub(crate) der: CertificateDer<'static>,
28}
29
30impl Certificate {
31	/// Get the certificate in DER encoded format.
32	///
33	/// [`CertificateDer`] implements `Deref<Target = [u8]>` and `AsRef<[u8]>`, so you can easily
34	/// extract the DER bytes from the return value.
35	pub fn der(&self) -> &CertificateDer<'static> {
36		&self.der
37	}
38
39	/// Get the certificate in PEM encoded format.
40	#[cfg(feature = "pem")]
41	pub fn pem(&self) -> String {
42		pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG)
43	}
44}
45
46impl From<Certificate> for CertificateDer<'static> {
47	fn from(cert: Certificate) -> Self {
48		cert.der
49	}
50}
51
52/// Parameters used for certificate generation
53#[allow(missing_docs)]
54#[non_exhaustive]
55#[derive(Debug, PartialEq, Eq, Clone)]
56pub struct CertificateParams {
57	pub not_before: OffsetDateTime,
58	pub not_after: OffsetDateTime,
59	pub serial_number: Option<SerialNumber>,
60	pub subject_alt_names: Vec<SanType>,
61	pub distinguished_name: DistinguishedName,
62	pub is_ca: IsCa,
63	pub key_usages: Vec<KeyUsagePurpose>,
64	pub extended_key_usages: Vec<ExtendedKeyUsagePurpose>,
65	pub name_constraints: Option<NameConstraints>,
66	/// An optional list of certificate revocation list (CRL) distribution points as described
67	/// in RFC 5280 Section 4.2.1.13[^1]. Each distribution point contains one or more URIs where
68	/// an up-to-date CRL with scope including this certificate can be retrieved.
69	///
70	/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.13>
71	pub crl_distribution_points: Vec<CrlDistributionPoint>,
72	pub custom_extensions: Vec<CustomExtension>,
73	/// If `true`, the 'Authority Key Identifier' extension will be added to the generated cert
74	pub use_authority_key_identifier_extension: bool,
75	/// Method to generate key identifiers from public keys
76	///
77	/// Defaults to a truncated SHA-256 digest. See [`KeyIdMethod`] for more information.
78	pub key_identifier_method: KeyIdMethod,
79}
80
81impl Default for CertificateParams {
82	fn default() -> Self {
83		// not_before and not_after set to reasonably long dates
84		let not_before = date_time_ymd(1975, 1, 1);
85		let not_after = date_time_ymd(4096, 1, 1);
86		let mut distinguished_name = DistinguishedName::new();
87		distinguished_name.push(DnType::CommonName, "rcgen self signed cert");
88		CertificateParams {
89			not_before,
90			not_after,
91			serial_number: None,
92			subject_alt_names: Vec::new(),
93			distinguished_name,
94			is_ca: IsCa::NoCa,
95			key_usages: Vec::new(),
96			extended_key_usages: Vec::new(),
97			name_constraints: None,
98			crl_distribution_points: Vec::new(),
99			custom_extensions: Vec::new(),
100			use_authority_key_identifier_extension: false,
101			#[cfg(feature = "crypto")]
102			key_identifier_method: KeyIdMethod::Sha256,
103			#[cfg(not(feature = "crypto"))]
104			key_identifier_method: KeyIdMethod::PreSpecified(Vec::new()),
105		}
106	}
107}
108
109impl CertificateParams {
110	/// Generate certificate parameters with reasonable defaults
111	pub fn new(subject_alt_names: impl Into<Vec<String>>) -> Result<Self, Error> {
112		let subject_alt_names = subject_alt_names
113			.into()
114			.into_iter()
115			.map(|s| {
116				Ok(match IpAddr::from_str(&s) {
117					Ok(ip) => SanType::IpAddress(ip),
118					Err(_) => SanType::DnsName(s.try_into()?),
119				})
120			})
121			.collect::<Result<Vec<_>, _>>()?;
122		Ok(CertificateParams {
123			subject_alt_names,
124			..Default::default()
125		})
126	}
127
128	/// Generate a new certificate from the given parameters, signed by the provided issuer.
129	///
130	/// The returned certificate will have its issuer field set to the subject of the
131	/// provided `issuer`, and the authority key identifier extension will be populated using
132	/// the subject public key of `issuer` (typically either a [`CertificateParams`] or
133	/// [`Certificate`]). It will be signed by `issuer_key`.
134	///
135	/// Note that no validation of the `issuer` certificate is performed. Rcgen will not require
136	/// the certificate to be a CA certificate, or have key usage extensions that allow signing.
137	///
138	/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
139	/// [`Certificate::pem`].
140	pub fn signed_by(
141		&self,
142		public_key: &impl PublicKeyData,
143		issuer: &Issuer<'_, impl SigningKey>,
144	) -> Result<Certificate, Error> {
145		Ok(Certificate {
146			der: self.serialize_der_with_signer(public_key, issuer)?,
147		})
148	}
149
150	/// Generates a new self-signed certificate from the given parameters.
151	///
152	/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
153	/// [`Certificate::pem`].
154	pub fn self_signed(&self, signing_key: &impl SigningKey) -> Result<Certificate, Error> {
155		let issuer = Issuer::from_params(self, signing_key);
156		Ok(Certificate {
157			der: self.serialize_der_with_signer(signing_key, &issuer)?,
158		})
159	}
160
161	/// Calculates a subject key identifier for the certificate subject's public key.
162	/// This key identifier is used in the SubjectKeyIdentifier X.509v3 extension.
163	pub fn key_identifier(&self, key: &impl PublicKeyData) -> Vec<u8> {
164		self.key_identifier_method
165			.derive(key.subject_public_key_info())
166	}
167
168	#[cfg(all(test, feature = "x509-parser"))]
169	pub(crate) fn from_ca_cert_der(ca_cert: &CertificateDer<'_>) -> Result<Self, Error> {
170		let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
171			.map_err(|_| Error::CouldNotParseCertificate)?;
172
173		Ok(CertificateParams {
174			is_ca: IsCa::from_x509(&x509)?,
175			subject_alt_names: SanType::from_x509(&x509)?,
176			key_usages: KeyUsagePurpose::from_x509(&x509)?,
177			extended_key_usages: ExtendedKeyUsagePurpose::from_x509(&x509)?,
178			name_constraints: NameConstraints::from_x509(&x509)?,
179			serial_number: Some(x509.serial.to_bytes_be().into()),
180			key_identifier_method: KeyIdMethod::from_x509(&x509)?,
181			distinguished_name: DistinguishedName::from_name(&x509.tbs_certificate.subject)?,
182			not_before: x509.validity().not_before.to_datetime(),
183			not_after: x509.validity().not_after.to_datetime(),
184			..Default::default()
185		})
186	}
187
188	/// Write a CSR extension request attribute as defined in [RFC 2985].
189	///
190	/// [RFC 2985]: <https://datatracker.ietf.org/doc/html/rfc2985>
191	fn write_extension_request_attribute(&self, writer: DERWriter) {
192		writer.write_sequence(|writer| {
193			writer.next().write_oid(&ObjectIdentifier::from_slice(
194				oid::PKCS_9_AT_EXTENSION_REQUEST,
195			));
196			writer.next().write_set(|writer| {
197				writer.next().write_sequence(|writer| {
198					// Write key_usage
199					self.write_key_usage(writer.next());
200					// Write subject_alt_names
201					self.write_subject_alt_names(writer.next());
202					self.write_extended_key_usage(writer.next());
203					// Write is_ca
204					self.write_is_ca(writer.next());
205
206					// Write custom extensions
207					for ext in &self.custom_extensions {
208						write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
209							writer.write_der(ext.content())
210						});
211					}
212				});
213			});
214		});
215	}
216
217	/// Write a certificate's KeyUsage as defined in RFC 5280.
218	fn write_key_usage(&self, writer: DERWriter) {
219		if self.key_usages.is_empty() {
220			return;
221		}
222
223		// "When present, conforming CAs SHOULD mark this extension as critical."
224		write_x509_extension(writer, oid::KEY_USAGE, true, |writer| {
225			// u16 is large enough to encode the largest possible key usage (two-bytes)
226			let bit_string = self.key_usages.iter().fold(0u16, |bit_string, key_usage| {
227				bit_string | key_usage.to_u16()
228			});
229
230			match u16::BITS - bit_string.trailing_zeros() {
231				bits @ 0..=8 => {
232					writer.write_bitvec_bytes(&bit_string.to_be_bytes()[..1], bits as usize)
233				},
234				bits @ 9..=16 => {
235					writer.write_bitvec_bytes(&bit_string.to_be_bytes(), bits as usize)
236				},
237				_ => unreachable!(),
238			}
239		});
240	}
241
242	fn write_extended_key_usage(&self, writer: DERWriter) {
243		if !self.extended_key_usages.is_empty() {
244			write_x509_extension(writer, oid::EXT_KEY_USAGE, false, |writer| {
245				writer.write_sequence(|writer| {
246					for usage in &self.extended_key_usages {
247						writer
248							.next()
249							.write_oid(&ObjectIdentifier::from_slice(usage.oid()));
250					}
251				});
252			});
253		}
254	}
255
256	/// Write a certificate's BasicConstraints as defined in RFC 5280.
257	fn write_is_ca(&self, writer: DERWriter) {
258		let is_ca = match &self.is_ca {
259			IsCa::Ca(bc) => Some(bc),
260			IsCa::ExplicitNoCa => None,
261			IsCa::NoCa => return,
262		};
263
264		// Write basic_constraints
265		write_x509_extension(writer, oid::BASIC_CONSTRAINTS, true, |writer| {
266			writer.write_sequence(|writer| {
267				writer.next().write_bool(is_ca.is_some()); // cA flag
268				if let Some(BasicConstraints::Constrained(path_len_constraint)) = is_ca {
269					writer.next().write_u8(*path_len_constraint); // pathLenConstraint integer
270				}
271			});
272		});
273	}
274
275	fn write_subject_alt_names(&self, writer: DERWriter) {
276		if self.subject_alt_names.is_empty() {
277			return;
278		}
279
280		// Per https://tools.ietf.org/html/rfc5280#section-4.1.2.6, SAN must be marked
281		// as critical if subject is empty.
282		let critical = self.distinguished_name.entries.is_empty();
283		write_x509_extension(writer, oid::SUBJECT_ALT_NAME, critical, |writer| {
284			writer.write_sequence(|writer| {
285				for san in self.subject_alt_names.iter() {
286					writer.next().write_tagged_implicit(
287						Tag::context(san.tag()),
288						|writer| match san {
289							SanType::Rfc822Name(name)
290							| SanType::DnsName(name)
291							| SanType::URI(name) => writer.write_ia5_string(name.as_str()),
292							SanType::IpAddress(IpAddr::V4(addr)) => {
293								writer.write_bytes(&addr.octets())
294							},
295							SanType::IpAddress(IpAddr::V6(addr)) => {
296								writer.write_bytes(&addr.octets())
297							},
298							SanType::OtherName((oid, value)) => {
299								// otherName SEQUENCE { OID, [0] explicit any defined by oid }
300								// https://datatracker.ietf.org/doc/html/rfc5280#page-38
301								writer.write_sequence(|writer| {
302									writer.next().write_oid(&ObjectIdentifier::from_slice(oid));
303									value.write_der(writer.next());
304								});
305							},
306						},
307					);
308				}
309			});
310		});
311	}
312
313	/// Generate and serialize a certificate signing request (CSR).
314	///
315	/// The constructed CSR will contain attributes based on the certificate parameters,
316	/// and include the subject public key information from `subject_key`. Additionally,
317	/// the CSR will be signed using the subject key.
318	///
319	/// Note that subsequent invocations of `serialize_request()` will not produce the exact
320	/// same output.
321	pub fn serialize_request(
322		&self,
323		subject_key: &impl SigningKey,
324	) -> Result<CertificateSigningRequest, Error> {
325		self.serialize_request_with_attributes(subject_key, Vec::new())
326	}
327
328	/// Generate and serialize a certificate signing request (CSR) with custom PKCS #10 attributes.
329	/// as defined in [RFC 2986].
330	///
331	/// The constructed CSR will contain attributes based on the certificate parameters,
332	/// and include the subject public key information from `subject_key`. Additionally,
333	/// the CSR will be self-signed using the subject key.
334	///
335	/// Note that subsequent invocations of `serialize_request_with_attributes()` will not produce the exact
336	/// same output.
337	///
338	/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
339	pub fn serialize_request_with_attributes(
340		&self,
341		subject_key: &impl SigningKey,
342		attrs: Vec<Attribute>,
343	) -> Result<CertificateSigningRequest, Error> {
344		// No .. pattern, we use this to ensure every field is used
345		#[deny(unused)]
346		let Self {
347			not_before,
348			not_after,
349			serial_number,
350			subject_alt_names,
351			distinguished_name,
352			is_ca,
353			key_usages,
354			extended_key_usages,
355			name_constraints,
356			crl_distribution_points,
357			custom_extensions,
358			use_authority_key_identifier_extension,
359			key_identifier_method,
360		} = self;
361		// - subject_key will be used by the caller
362		// - not_before and not_after cannot be put in a CSR
363		// - key_identifier_method is here because self.write_extended_key_usage uses it
364		// - There might be a use case for specifying the key identifier
365		// in the CSR, but in the current API it can't be distinguished
366		// from the defaults so this is left for a later version if
367		// needed.
368		let _ = (
369			not_before,
370			not_after,
371			key_identifier_method,
372			extended_key_usages,
373		);
374		if serial_number.is_some()
375			|| name_constraints.is_some()
376			|| !crl_distribution_points.is_empty()
377			|| *use_authority_key_identifier_extension
378		{
379			return Err(Error::UnsupportedInCsr);
380		}
381
382		// Whether or not to write an extension request attribute
383		let write_extension_request = !key_usages.is_empty()
384			|| !subject_alt_names.is_empty()
385			|| !extended_key_usages.is_empty()
386			|| !custom_extensions.is_empty()
387			|| matches!(is_ca, IsCa::ExplicitNoCa | IsCa::Ca(_));
388
389		let der = sign_der(subject_key, |writer| {
390			// Write version
391			writer.next().write_u8(0);
392			write_distinguished_name(writer.next(), distinguished_name);
393			serialize_public_key_der(subject_key, writer.next());
394
395			// According to the spec in RFC 2986, even if attributes are empty we need the empty attribute tag
396			writer
397				.next()
398				.write_tagged_implicit(Tag::context(0), |writer| {
399					// RFC 2986 specifies that attributes are a SET OF Attribute
400					writer.write_set_of(|writer| {
401						if write_extension_request {
402							self.write_extension_request_attribute(writer.next());
403						}
404
405						for Attribute { oid, values } in attrs {
406							writer.next().write_sequence(|writer| {
407								writer.next().write_oid(&ObjectIdentifier::from_slice(oid));
408								writer.next().write_der(&values);
409							});
410						}
411					});
412				});
413
414			Ok(())
415		})?;
416
417		Ok(CertificateSigningRequest {
418			der: CertificateSigningRequestDer::from(der),
419		})
420	}
421
422	pub(crate) fn serialize_der_with_signer<K: PublicKeyData>(
423		&self,
424		pub_key: &K,
425		issuer: &Issuer<'_, impl SigningKey>,
426	) -> Result<CertificateDer<'static>, Error> {
427		let der = sign_der(&issuer.signing_key, |writer| {
428			let pub_key_spki = pub_key.subject_public_key_info();
429			// Write version
430			writer.next().write_tagged(Tag::context(0), |writer| {
431				writer.write_u8(2);
432			});
433			// Write serialNumber
434			if let Some(ref serial) = self.serial_number {
435				writer.next().write_bigint_bytes(serial.as_ref(), true);
436			} else {
437				#[cfg(feature = "crypto")]
438				{
439					let hash = digest::digest(&digest::SHA256, pub_key.der_bytes());
440					// RFC 5280 specifies at most 20 bytes for a serial number
441					let mut sl = hash.as_ref()[0..20].to_vec();
442					sl[0] &= 0x7f; // MSB must be 0 to ensure encoding bignum in 20 bytes
443					writer.next().write_bigint_bytes(&sl, true);
444				}
445				#[cfg(not(feature = "crypto"))]
446				if self.serial_number.is_none() {
447					return Err(Error::MissingSerialNumber);
448				}
449			};
450			// Write signature algorithm
451			issuer
452				.signing_key
453				.algorithm()
454				.write_alg_ident(writer.next());
455			// Write issuer name
456			write_distinguished_name(writer.next(), issuer.distinguished_name.as_ref());
457			// Write validity
458			writer.next().write_sequence(|writer| {
459				// Not before
460				write_dt_utc_or_generalized(writer.next(), self.not_before);
461				// Not after
462				write_dt_utc_or_generalized(writer.next(), self.not_after);
463				Ok::<(), Error>(())
464			})?;
465			// Write subject
466			write_distinguished_name(writer.next(), &self.distinguished_name);
467			// Write subjectPublicKeyInfo
468			serialize_public_key_der(pub_key, writer.next());
469			// write extensions
470			let should_write_exts = self.use_authority_key_identifier_extension
471				|| !self.subject_alt_names.is_empty()
472				|| !self.extended_key_usages.is_empty()
473				|| self.name_constraints.iter().any(|c| !c.is_empty())
474				|| matches!(self.is_ca, IsCa::ExplicitNoCa)
475				|| matches!(self.is_ca, IsCa::Ca(_))
476				|| !self.custom_extensions.is_empty();
477			if !should_write_exts {
478				return Ok(());
479			}
480
481			writer.next().write_tagged(Tag::context(3), |writer| {
482				writer.write_sequence(|writer| self.write_extensions(writer, &pub_key_spki, issuer))
483			})?;
484
485			Ok(())
486		})?;
487
488		Ok(der.into())
489	}
490
491	fn write_extensions(
492		&self,
493		writer: &mut DERWriterSeq,
494		pub_key_spki: &[u8],
495		issuer: &Issuer<'_, impl SigningKey>,
496	) -> Result<(), Error> {
497		if self.use_authority_key_identifier_extension {
498			write_x509_authority_key_identifier(
499				writer.next(),
500				match issuer.key_identifier_method.as_ref() {
501					KeyIdMethod::PreSpecified(aki) => aki.clone(),
502					#[cfg(feature = "crypto")]
503					_ => issuer
504						.key_identifier_method
505						.derive(issuer.signing_key.subject_public_key_info()),
506				},
507			);
508		}
509
510		// Write subject_alt_names
511		self.write_subject_alt_names(writer.next());
512
513		// Write standard key usage
514		self.write_key_usage(writer.next());
515
516		// Write extended key usage
517		if !self.extended_key_usages.is_empty() {
518			write_x509_extension(writer.next(), oid::EXT_KEY_USAGE, false, |writer| {
519				writer.write_sequence(|writer| {
520					for usage in self.extended_key_usages.iter() {
521						let oid = ObjectIdentifier::from_slice(usage.oid());
522						writer.next().write_oid(&oid);
523					}
524				});
525			});
526		}
527
528		if let Some(name_constraints) = &self.name_constraints {
529			// If both trees are empty, the extension must be omitted.
530			if !name_constraints.is_empty() {
531				write_x509_extension(writer.next(), oid::NAME_CONSTRAINTS, true, |writer| {
532					writer.write_sequence(|writer| {
533						if !name_constraints.permitted_subtrees.is_empty() {
534							write_general_subtrees(
535								writer.next(),
536								0,
537								&name_constraints.permitted_subtrees,
538							);
539						}
540						if !name_constraints.excluded_subtrees.is_empty() {
541							write_general_subtrees(
542								writer.next(),
543								1,
544								&name_constraints.excluded_subtrees,
545							);
546						}
547					});
548				});
549			}
550		}
551
552		if !self.crl_distribution_points.is_empty() {
553			write_x509_extension(
554				writer.next(),
555				oid::CRL_DISTRIBUTION_POINTS,
556				false,
557				|writer| {
558					writer.write_sequence(|writer| {
559						for distribution_point in &self.crl_distribution_points {
560							distribution_point.write_der(writer.next());
561						}
562					})
563				},
564			);
565		}
566
567		match self.is_ca {
568			IsCa::Ca(ref constraint) => {
569				// Write subject_key_identifier
570				write_x509_extension(
571					writer.next(),
572					oid::SUBJECT_KEY_IDENTIFIER,
573					false,
574					|writer| {
575						writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki));
576					},
577				);
578				// Write basic_constraints
579				write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| {
580					writer.write_sequence(|writer| {
581						writer.next().write_bool(true); // cA flag
582						if let BasicConstraints::Constrained(path_len_constraint) = constraint {
583							writer.next().write_u8(*path_len_constraint);
584						}
585					});
586				});
587			},
588			IsCa::ExplicitNoCa => {
589				// Write subject_key_identifier
590				write_x509_extension(
591					writer.next(),
592					oid::SUBJECT_KEY_IDENTIFIER,
593					false,
594					|writer| {
595						writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki));
596					},
597				);
598				// Write basic_constraints
599				write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| {
600					writer.write_sequence(|writer| {
601						writer.next().write_bool(false); // cA flag
602					});
603				});
604			},
605			IsCa::NoCa => {},
606		}
607
608		// Write the custom extensions
609		for ext in &self.custom_extensions {
610			write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
611				writer.write_der(ext.content())
612			});
613		}
614
615		Ok(())
616	}
617
618	/// Insert an extended key usage (EKU) into the parameters if it does not already exist
619	pub fn insert_extended_key_usage(&mut self, eku: ExtendedKeyUsagePurpose) {
620		if !self.extended_key_usages.contains(&eku) {
621			self.extended_key_usages.push(eku);
622		}
623	}
624}
625
626impl AsRef<CertificateParams> for CertificateParams {
627	fn as_ref(&self) -> &CertificateParams {
628		self
629	}
630}
631
632fn write_general_subtrees(writer: DERWriter, tag: u64, general_subtrees: &[GeneralSubtree]) {
633	writer.write_tagged_implicit(Tag::context(tag), |writer| {
634		writer.write_sequence(|writer| {
635			for subtree in general_subtrees.iter() {
636				writer.next().write_sequence(|writer| {
637					let writer = writer.next();
638					let tag = Tag::context(subtree.tag());
639					match subtree {
640						GeneralSubtree::Rfc822Name(name) | GeneralSubtree::DnsName(name) => writer
641							.write_tagged_implicit(tag, |writer| writer.write_ia5_string(name)),
642						// `Name` is a CHOICE, so X.680 ยง31.2.7 requires explicit tagging.
643						GeneralSubtree::DirectoryName(name) => writer
644							.write_tagged(tag, |writer| write_distinguished_name(writer, name)),
645						GeneralSubtree::IpAddress(subnet) => writer
646							.write_tagged_implicit(tag, |writer| {
647								writer.write_bytes(&subnet.to_bytes())
648							}),
649					}
650					// minimum must be 0 (the default) and maximum must be absent
651				});
652			}
653		});
654	});
655}
656
657/// A PKCS #10 CSR attribute, as defined in [RFC 5280] and constrained
658/// by [RFC 2986].
659///
660/// [RFC 5280]: <https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1>
661/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
662#[derive(Debug, PartialEq, Eq, Hash, Clone)]
663pub struct Attribute {
664	/// `AttributeType` of the `Attribute`, defined as an `OBJECT IDENTIFIER`.
665	pub oid: &'static [u64],
666	/// DER-encoded values of the `Attribute`, defined by [RFC 2986] as:
667	///
668	/// ```text
669	/// SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
670	/// ```
671	///
672	/// [RFC 2986]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
673	pub values: Vec<u8>,
674}
675
676/// A custom extension of a certificate, as specified in
677/// [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2)
678#[derive(Debug, PartialEq, Eq, Hash, Clone)]
679pub struct CustomExtension {
680	oid: Vec<u64>,
681	critical: bool,
682
683	/// The content must be DER-encoded
684	content: Vec<u8>,
685}
686
687impl CustomExtension {
688	/// Creates a new acmeIdentifier extension for ACME TLS-ALPN-01
689	/// as specified in [RFC 8737](https://tools.ietf.org/html/rfc8737#section-3)
690	///
691	/// Panics if the passed `sha_digest` parameter doesn't hold 32 bytes (256 bits).
692	pub fn new_acme_identifier(sha_digest: &[u8]) -> Self {
693		assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest");
694		let content = yasna::construct_der(|writer| {
695			writer.write_bytes(sha_digest);
696		});
697		Self {
698			oid: oid::PE_ACME.to_owned(),
699			critical: true,
700			content,
701		}
702	}
703	/// Create a new custom extension with the specified content
704	pub fn from_oid_content(oid: &[u64], content: Vec<u8>) -> Self {
705		Self {
706			oid: oid.to_owned(),
707			critical: false,
708			content,
709		}
710	}
711	/// Sets the criticality flag of the extension.
712	pub fn set_criticality(&mut self, criticality: bool) {
713		self.critical = criticality;
714	}
715	/// Obtains the criticality flag of the extension.
716	pub fn criticality(&self) -> bool {
717		self.critical
718	}
719	/// Obtains the content of the extension.
720	pub fn content(&self) -> &[u8] {
721		&self.content
722	}
723	/// Obtains the OID components of the extensions, as u64 pieces
724	pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ {
725		self.oid.iter().copied()
726	}
727}
728
729#[derive(Debug, PartialEq, Eq, Hash, Clone)]
730#[non_exhaustive]
731/// The attribute type of a distinguished name entry
732pub enum DnType {
733	/// X520countryName
734	CountryName,
735	/// X520LocalityName
736	LocalityName,
737	/// X520StateOrProvinceName
738	StateOrProvinceName,
739	/// X520OrganizationName
740	OrganizationName,
741	/// X520OrganizationalUnitName
742	OrganizationalUnitName,
743	/// X520CommonName
744	CommonName,
745	/// Custom distinguished name type
746	CustomDnType(Vec<u64>),
747}
748
749impl DnType {
750	pub(crate) fn to_oid(&self) -> ObjectIdentifier {
751		let sl = match self {
752			DnType::CountryName => oid::COUNTRY_NAME,
753			DnType::LocalityName => oid::LOCALITY_NAME,
754			DnType::StateOrProvinceName => oid::STATE_OR_PROVINCE_NAME,
755			DnType::OrganizationName => oid::ORG_NAME,
756			DnType::OrganizationalUnitName => oid::ORG_UNIT_NAME,
757			DnType::CommonName => oid::COMMON_NAME,
758			DnType::CustomDnType(ref oid) => oid.as_slice(),
759		};
760		ObjectIdentifier::from_slice(sl)
761	}
762
763	/// Generate a DnType for the provided OID
764	pub fn from_oid(slice: &[u64]) -> Self {
765		match slice {
766			oid::COUNTRY_NAME => DnType::CountryName,
767			oid::LOCALITY_NAME => DnType::LocalityName,
768			oid::STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName,
769			oid::ORG_NAME => DnType::OrganizationName,
770			oid::ORG_UNIT_NAME => DnType::OrganizationalUnitName,
771			oid::COMMON_NAME => DnType::CommonName,
772			oid => DnType::CustomDnType(oid.into()),
773		}
774	}
775}
776
777#[derive(Debug, PartialEq, Eq, Hash, Clone)]
778/// One of the purposes contained in the [extended key usage extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.12)
779pub enum ExtendedKeyUsagePurpose {
780	/// anyExtendedKeyUsage
781	Any,
782	/// id-kp-serverAuth
783	ServerAuth,
784	/// id-kp-clientAuth
785	ClientAuth,
786	/// id-kp-codeSigning
787	CodeSigning,
788	/// id-kp-emailProtection
789	EmailProtection,
790	/// id-kp-timeStamping
791	TimeStamping,
792	/// id-kp-OCSPSigning
793	OcspSigning,
794	/// A custom purpose not from the pre-specified list of purposes
795	Other(Vec<u64>),
796}
797
798impl ExtendedKeyUsagePurpose {
799	#[cfg(all(test, feature = "x509-parser"))]
800	fn from_x509(x509: &x509_parser::certificate::X509Certificate<'_>) -> Result<Vec<Self>, Error> {
801		let extended_key_usage = x509
802			.extended_key_usage()
803			.map_err(|_| Error::CouldNotParseCertificate)?
804			.map(|ext| ext.value);
805
806		let mut extended_key_usages = Vec::new();
807		if let Some(extended_key_usage) = extended_key_usage {
808			if extended_key_usage.any {
809				extended_key_usages.push(Self::Any);
810			}
811			if extended_key_usage.server_auth {
812				extended_key_usages.push(Self::ServerAuth);
813			}
814			if extended_key_usage.client_auth {
815				extended_key_usages.push(Self::ClientAuth);
816			}
817			if extended_key_usage.code_signing {
818				extended_key_usages.push(Self::CodeSigning);
819			}
820			if extended_key_usage.email_protection {
821				extended_key_usages.push(Self::EmailProtection);
822			}
823			if extended_key_usage.time_stamping {
824				extended_key_usages.push(Self::TimeStamping);
825			}
826			if extended_key_usage.ocsp_signing {
827				extended_key_usages.push(Self::OcspSigning);
828			}
829		}
830
831		Ok(extended_key_usages)
832	}
833
834	fn oid(&self) -> &[u64] {
835		use ExtendedKeyUsagePurpose::*;
836		match self {
837			// anyExtendedKeyUsage
838			Any => &[2, 5, 29, 37, 0],
839			// id-kp-*
840			ServerAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 1],
841			ClientAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 2],
842			CodeSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 3],
843			EmailProtection => &[1, 3, 6, 1, 5, 5, 7, 3, 4],
844			TimeStamping => &[1, 3, 6, 1, 5, 5, 7, 3, 8],
845			OcspSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 9],
846			Other(oid) => oid,
847		}
848	}
849}
850
851/// The [NameConstraints extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.10)
852/// (only relevant for CA certificates)
853#[derive(Debug, PartialEq, Eq, Clone)]
854pub struct NameConstraints {
855	/// A list of subtrees that the domain has to match.
856	pub permitted_subtrees: Vec<GeneralSubtree>,
857	/// A list of subtrees that the domain must not match.
858	///
859	/// Any name matching an excluded subtree is invalid even if it also matches a permitted subtree.
860	pub excluded_subtrees: Vec<GeneralSubtree>,
861}
862
863impl NameConstraints {
864	#[cfg(all(test, feature = "x509-parser"))]
865	fn from_x509(
866		x509: &x509_parser::certificate::X509Certificate<'_>,
867	) -> Result<Option<Self>, Error> {
868		let constraints = x509
869			.name_constraints()
870			.map_err(|_| Error::CouldNotParseCertificate)?
871			.map(|ext| ext.value);
872
873		let Some(constraints) = constraints else {
874			return Ok(None);
875		};
876
877		let permitted_subtrees = if let Some(permitted) = &constraints.permitted_subtrees {
878			GeneralSubtree::from_x509(permitted)?
879		} else {
880			Vec::new()
881		};
882
883		let excluded_subtrees = if let Some(excluded) = &constraints.excluded_subtrees {
884			GeneralSubtree::from_x509(excluded)?
885		} else {
886			Vec::new()
887		};
888
889		Ok(Some(Self {
890			permitted_subtrees,
891			excluded_subtrees,
892		}))
893	}
894
895	fn is_empty(&self) -> bool {
896		self.permitted_subtrees.is_empty() && self.excluded_subtrees.is_empty()
897	}
898}
899
900#[derive(Debug, PartialEq, Eq, Clone)]
901#[allow(missing_docs)]
902#[non_exhaustive]
903/// General Subtree type.
904///
905/// This type has similarities to the [`SanType`] enum but is not equal.
906/// For example, `GeneralSubtree` has CIDR subnets for ip addresses
907/// while [`SanType`] has IP addresses.
908pub enum GeneralSubtree {
909	/// Also known as E-Mail address
910	Rfc822Name(String),
911	DnsName(String),
912	DirectoryName(DistinguishedName),
913	IpAddress(CidrSubnet),
914}
915
916impl GeneralSubtree {
917	#[cfg(all(test, feature = "x509-parser"))]
918	fn from_x509(
919		subtrees: &[x509_parser::extensions::GeneralSubtree<'_>],
920	) -> Result<Vec<Self>, Error> {
921		use x509_parser::extensions::GeneralName;
922
923		let mut result = Vec::new();
924		for subtree in subtrees {
925			let subtree = match &subtree.base {
926				GeneralName::RFC822Name(s) => Self::Rfc822Name(s.to_string()),
927				GeneralName::DNSName(s) => Self::DnsName(s.to_string()),
928				GeneralName::DirectoryName(n) => {
929					Self::DirectoryName(DistinguishedName::from_name(n)?)
930				},
931				GeneralName::IPAddress(bytes) if bytes.len() == 8 => {
932					let addr: [u8; 4] = bytes[..4].try_into().unwrap();
933					let mask: [u8; 4] = bytes[4..].try_into().unwrap();
934					Self::IpAddress(CidrSubnet::V4(addr, mask))
935				},
936				GeneralName::IPAddress(bytes) if bytes.len() == 32 => {
937					let addr: [u8; 16] = bytes[..16].try_into().unwrap();
938					let mask: [u8; 16] = bytes[16..].try_into().unwrap();
939					Self::IpAddress(CidrSubnet::V6(addr, mask))
940				},
941				_ => continue,
942			};
943			result.push(subtree);
944		}
945
946		Ok(result)
947	}
948
949	fn tag(&self) -> u64 {
950		// Defined in the GeneralName list in
951		// https://tools.ietf.org/html/rfc5280#page-38
952		const TAG_RFC822_NAME: u64 = 1;
953		const TAG_DNS_NAME: u64 = 2;
954		const TAG_DIRECTORY_NAME: u64 = 4;
955		const TAG_IP_ADDRESS: u64 = 7;
956
957		match self {
958			GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME,
959			GeneralSubtree::DnsName(_name) => TAG_DNS_NAME,
960			GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME,
961			GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS,
962		}
963	}
964}
965
966#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
967#[allow(missing_docs)]
968/// CIDR subnet, as per [RFC 4632](https://tools.ietf.org/html/rfc4632)
969///
970/// You might know CIDR subnets better by their textual representation
971/// where they consist of an ip address followed by a slash and a prefix
972/// number, for example `192.168.99.0/24`.
973///
974/// The first field in the enum is the address, the second is the mask.
975/// Both are specified in network byte order.
976pub enum CidrSubnet {
977	V4([u8; 4], [u8; 4]),
978	V6([u8; 16], [u8; 16]),
979}
980
981macro_rules! mask {
982	($t:ty, $d:expr) => {{
983		let v = <$t>::MAX;
984		let v = v.checked_shr($d as u32).unwrap_or(0);
985		(!v).to_be_bytes()
986	}};
987}
988
989impl CidrSubnet {
990	/// Obtains the CidrSubnet from an ip address
991	/// as well as the specified prefix number.
992	///
993	/// ```
994	/// # use std::net::IpAddr;
995	/// # use std::str::FromStr;
996	/// # use rcgen::CidrSubnet;
997	/// // The "192.0.2.0/24" example from
998	/// // https://tools.ietf.org/html/rfc5280#page-42
999	/// let addr = IpAddr::from_str("192.0.2.0").unwrap();
1000	/// let subnet = CidrSubnet::from_addr_prefix(addr, 24);
1001	/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
1002	/// ```
1003	pub fn from_addr_prefix(addr: IpAddr, prefix: u8) -> Self {
1004		match addr {
1005			IpAddr::V4(addr) => Self::from_v4_prefix(addr.octets(), prefix),
1006			IpAddr::V6(addr) => Self::from_v6_prefix(addr.octets(), prefix),
1007		}
1008	}
1009	/// Obtains the CidrSubnet from an IPv4 address in network byte order
1010	/// as well as the specified prefix.
1011	pub fn from_v4_prefix(addr: [u8; 4], prefix: u8) -> Self {
1012		CidrSubnet::V4(addr, mask!(u32, prefix))
1013	}
1014	/// Obtains the CidrSubnet from an IPv6 address in network byte order
1015	/// as well as the specified prefix.
1016	pub fn from_v6_prefix(addr: [u8; 16], prefix: u8) -> Self {
1017		CidrSubnet::V6(addr, mask!(u128, prefix))
1018	}
1019	fn to_bytes(self) -> Vec<u8> {
1020		let mut res = Vec::new();
1021		match self {
1022			CidrSubnet::V4(addr, mask) => {
1023				res.extend_from_slice(&addr);
1024				res.extend_from_slice(&mask);
1025			},
1026			CidrSubnet::V6(addr, mask) => {
1027				res.extend_from_slice(&addr);
1028				res.extend_from_slice(&mask);
1029			},
1030		}
1031		res
1032	}
1033}
1034
1035/// Obtains the CidrSubnet from the well-known
1036/// addr/prefix notation.
1037/// ```
1038/// # use std::str::FromStr;
1039/// # use rcgen::CidrSubnet;
1040/// // The "192.0.2.0/24" example from
1041/// // https://tools.ietf.org/html/rfc5280#page-42
1042/// let subnet = CidrSubnet::from_str("192.0.2.0/24").unwrap();
1043/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
1044/// ```
1045impl FromStr for CidrSubnet {
1046	type Err = ();
1047
1048	fn from_str(s: &str) -> Result<Self, Self::Err> {
1049		let mut iter = s.split('/');
1050		if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) {
1051			let addr = IpAddr::from_str(addr_s).map_err(|_| ())?;
1052			let prefix = u8::from_str(prefix_s).map_err(|_| ())?;
1053			Ok(Self::from_addr_prefix(addr, prefix))
1054		} else {
1055			Err(())
1056		}
1057	}
1058}
1059
1060/// Helper to obtain an `OffsetDateTime` from year, month, day values
1061///
1062/// The year, month, day values are assumed to be in UTC.
1063///
1064/// This helper function serves two purposes: first, so that you don't
1065/// have to import the time crate yourself in order to specify date
1066/// information, second so that users don't have to type unproportionately
1067/// long code just to generate an instance of [`OffsetDateTime`].
1068pub fn date_time_ymd(year: i32, month: u8, day: u8) -> OffsetDateTime {
1069	let month = Month::try_from(month).expect("out-of-range month");
1070	let primitive_dt = PrimitiveDateTime::new(
1071		Date::from_calendar_date(year, month, day).expect("invalid or out-of-range date"),
1072		Time::MIDNIGHT,
1073	);
1074	primitive_dt.assume_utc()
1075}
1076
1077/// Whether the certificate is allowed to sign other certificates
1078#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1079pub enum IsCa {
1080	/// The certificate can only sign itself
1081	NoCa,
1082	/// The certificate can only sign itself, adding the extension and `CA:FALSE`
1083	ExplicitNoCa,
1084	/// The certificate may be used to sign other certificates
1085	Ca(BasicConstraints),
1086}
1087
1088impl IsCa {
1089	#[cfg(all(test, feature = "x509-parser"))]
1090	fn from_x509(x509: &x509_parser::certificate::X509Certificate<'_>) -> Result<Self, Error> {
1091		let basic_constraints = x509
1092			.basic_constraints()
1093			.map_err(|_| Error::CouldNotParseCertificate)?
1094			.map(|ext| ext.value);
1095
1096		match basic_constraints {
1097			Some(bc) => Self::from_basic_constraints(bc),
1098			None => Ok(Self::NoCa),
1099		}
1100	}
1101
1102	#[cfg(feature = "x509-parser")]
1103	pub(crate) fn from_basic_constraints(
1104		basic_constraints: &x509_parser::extensions::BasicConstraints,
1105	) -> Result<Self, Error> {
1106		use x509_parser::extensions::BasicConstraints as B;
1107
1108		Ok(match basic_constraints {
1109			B {
1110				ca: true,
1111				path_len_constraint: Some(n),
1112			} if *n <= u8::MAX as u32 => Self::Ca(BasicConstraints::Constrained(*n as u8)),
1113			B {
1114				ca: true,
1115				path_len_constraint: Some(_),
1116			} => return Err(Error::CouldNotParseCertificate),
1117			B {
1118				ca: true,
1119				path_len_constraint: None,
1120			} => Self::Ca(BasicConstraints::Unconstrained),
1121			B { ca: false, .. } => Self::ExplicitNoCa,
1122		})
1123	}
1124}
1125
1126/// The path length constraint (only relevant for CA certificates)
1127///
1128/// Sets an optional upper limit on the length of the intermediate certificate chain
1129/// length allowed for this CA certificate (not including the end entity certificate).
1130#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1131pub enum BasicConstraints {
1132	/// No constraint
1133	Unconstrained,
1134	/// Constrain to the contained number of intermediate certificates
1135	Constrained(u8),
1136}
1137
1138#[cfg(test)]
1139mod tests {
1140	#[cfg(feature = "x509-parser")]
1141	use std::net::Ipv4Addr;
1142
1143	#[cfg(feature = "x509-parser")]
1144	use pki_types::pem::PemObject;
1145
1146	#[cfg(feature = "pem")]
1147	use super::*;
1148	#[cfg(feature = "x509-parser")]
1149	use crate::DnValue;
1150	#[cfg(feature = "crypto")]
1151	use crate::KeyPair;
1152
1153	#[cfg(feature = "crypto")]
1154	#[test]
1155	fn test_with_key_usages() {
1156		let params = CertificateParams {
1157			// Set key usages
1158			key_usages: vec![
1159				KeyUsagePurpose::DigitalSignature,
1160				KeyUsagePurpose::KeyEncipherment,
1161				KeyUsagePurpose::ContentCommitment,
1162			],
1163			// This can sign things!
1164			is_ca: IsCa::Ca(BasicConstraints::Constrained(0)),
1165			..CertificateParams::default()
1166		};
1167
1168		// Make the cert
1169		let key_pair = KeyPair::generate().unwrap();
1170		let cert = params.self_signed(&key_pair).unwrap();
1171
1172		// Parse it
1173		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1174
1175		// Check oid
1176		let key_usage_oid_str = "2.5.29.15";
1177
1178		// Found flag
1179		let mut found = false;
1180
1181		for ext in cert.extensions() {
1182			if key_usage_oid_str == ext.oid.to_id_string() {
1183				// should have the minimal number of octets, and no extra trailing zero bytes
1184				// ref. https://github.com/rustls/rcgen/issues/368
1185				assert_eq!(ext.value, vec![0x03, 0x02, 0x05, 0xe0]);
1186				if let x509_parser::extensions::ParsedExtension::KeyUsage(usage) =
1187					ext.parsed_extension()
1188				{
1189					assert!(usage.flags == 7);
1190					found = true;
1191				}
1192			}
1193		}
1194
1195		assert!(found);
1196	}
1197
1198	#[cfg(feature = "crypto")]
1199	#[test]
1200	fn test_with_key_usages_decipheronly_only() {
1201		let params = CertificateParams {
1202			// Set key usages
1203			key_usages: vec![KeyUsagePurpose::DecipherOnly],
1204			// This can sign things!
1205			is_ca: IsCa::Ca(BasicConstraints::Constrained(0)),
1206			..CertificateParams::default()
1207		};
1208
1209		// Make the cert
1210		let key_pair = KeyPair::generate().unwrap();
1211		let cert = params.self_signed(&key_pair).unwrap();
1212
1213		// Parse it
1214		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1215
1216		// Check oid
1217		let key_usage_oid_str = "2.5.29.15";
1218
1219		// Found flag
1220		let mut found = false;
1221
1222		for ext in cert.extensions() {
1223			if key_usage_oid_str == ext.oid.to_id_string() {
1224				if let x509_parser::extensions::ParsedExtension::KeyUsage(usage) =
1225					ext.parsed_extension()
1226				{
1227					assert!(usage.flags == 256);
1228					found = true;
1229				}
1230			}
1231		}
1232
1233		assert!(found);
1234	}
1235
1236	#[cfg(feature = "crypto")]
1237	#[test]
1238	fn test_with_extended_key_usages_any() {
1239		let params = CertificateParams {
1240			extended_key_usages: vec![ExtendedKeyUsagePurpose::Any],
1241			..CertificateParams::default()
1242		};
1243
1244		// Make the cert
1245		let key_pair = KeyPair::generate().unwrap();
1246		let cert = params.self_signed(&key_pair).unwrap();
1247
1248		// Parse it
1249		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1250
1251		// Ensure we found it.
1252		let maybe_extension = cert.extended_key_usage().unwrap();
1253		let extension = maybe_extension.unwrap();
1254		assert!(extension.value.any);
1255	}
1256
1257	#[cfg(feature = "crypto")]
1258	#[test]
1259	fn test_with_extended_key_usages_other() {
1260		use x509_parser::der_parser::asn1_rs::Oid;
1261		const OID_1: &[u64] = &[1, 2, 3, 4];
1262		const OID_2: &[u64] = &[1, 2, 3, 4, 5, 6];
1263
1264		let params = CertificateParams {
1265			extended_key_usages: vec![
1266				ExtendedKeyUsagePurpose::Other(Vec::from(OID_1)),
1267				ExtendedKeyUsagePurpose::Other(Vec::from(OID_2)),
1268			],
1269			..CertificateParams::default()
1270		};
1271
1272		// Make the cert
1273		let key_pair = KeyPair::generate().unwrap();
1274		let cert = params.self_signed(&key_pair).unwrap();
1275
1276		// Parse it
1277		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1278
1279		// Ensure we found it.
1280		let maybe_extension = cert.extended_key_usage().unwrap();
1281		let extension = maybe_extension.unwrap();
1282
1283		let expected_oids = vec![Oid::from(OID_1).unwrap(), Oid::from(OID_2).unwrap()];
1284		assert_eq!(extension.value.other, expected_oids);
1285	}
1286
1287	#[cfg(feature = "pem")]
1288	mod test_pem_serialization {
1289		use super::*;
1290
1291		#[test]
1292		#[cfg(windows)]
1293		fn test_windows_line_endings() {
1294			let key_pair = KeyPair::generate().unwrap();
1295			let cert = CertificateParams::default().self_signed(&key_pair).unwrap();
1296			assert!(cert.pem().contains("\r\n"));
1297		}
1298
1299		#[test]
1300		#[cfg(not(windows))]
1301		fn test_not_windows_line_endings() {
1302			let key_pair = KeyPair::generate().unwrap();
1303			let cert = CertificateParams::default().self_signed(&key_pair).unwrap();
1304			assert!(!cert.pem().contains('\r'));
1305		}
1306	}
1307
1308	#[cfg(feature = "x509-parser")]
1309	#[test]
1310	fn parse_other_name_alt_name() {
1311		// Create and serialize a certificate with an alternative name containing an "OtherName".
1312		let mut params = CertificateParams::default();
1313		let other_name = SanType::OtherName((vec![1, 2, 3, 4], "Foo".into()));
1314		params.subject_alt_names.push(other_name.clone());
1315		let key_pair = KeyPair::generate().unwrap();
1316		let cert = params.self_signed(&key_pair).unwrap();
1317
1318		// We should be able to parse the certificate with x509-parser.
1319		assert!(x509_parser::parse_x509_certificate(cert.der()).is_ok());
1320
1321		// We should be able to reconstitute params from the DER using x509-parser.
1322		let params_from_cert = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1323
1324		// We should find the expected distinguished name in the reconstituted params.
1325		let expected_alt_names = &[&other_name];
1326		let subject_alt_names = params_from_cert
1327			.subject_alt_names
1328			.iter()
1329			.collect::<Vec<_>>();
1330		assert_eq!(subject_alt_names, expected_alt_names);
1331	}
1332
1333	#[cfg(feature = "x509-parser")]
1334	#[test]
1335	fn parse_ia5string_subject() {
1336		// Create and serialize a certificate with a subject containing an IA5String email address.
1337		let email_address_dn_type = DnType::CustomDnType(vec![1, 2, 840, 113549, 1, 9, 1]); // id-emailAddress
1338		let email_address_dn_value = DnValue::Ia5String("[email protected]".try_into().unwrap());
1339		let mut params = CertificateParams::new(vec!["crabs".to_owned()]).unwrap();
1340		params.distinguished_name = DistinguishedName::new();
1341		params.distinguished_name.push(
1342			email_address_dn_type.clone(),
1343			email_address_dn_value.clone(),
1344		);
1345		let key_pair = KeyPair::generate().unwrap();
1346		let cert = params.self_signed(&key_pair).unwrap();
1347
1348		// We should be able to parse the certificate with x509-parser.
1349		assert!(x509_parser::parse_x509_certificate(cert.der()).is_ok());
1350
1351		// We should be able to reconstitute params from the DER using x509-parser.
1352		let params_from_cert = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1353
1354		// We should find the expected distinguished name in the reconstituted params.
1355		let expected_names = &[(&email_address_dn_type, &email_address_dn_value)];
1356		let names = params_from_cert
1357			.distinguished_name
1358			.iter()
1359			.collect::<Vec<(_, _)>>();
1360		assert_eq!(names, expected_names);
1361	}
1362
1363	#[cfg(feature = "x509-parser")]
1364	#[test]
1365	fn converts_from_ip() {
1366		let ip = Ipv4Addr::new(2, 4, 6, 8);
1367		let ip_san = SanType::IpAddress(IpAddr::V4(ip));
1368
1369		let mut params = CertificateParams::new(vec!["crabs".to_owned()]).unwrap();
1370		let ca_key = KeyPair::generate().unwrap();
1371
1372		// Add the SAN we want to test the parsing for
1373		params.subject_alt_names.push(ip_san.clone());
1374
1375		// Because we're using a function for CA certificates
1376		params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1377
1378		// Serialize our cert that has our chosen san, so we can testing parsing/deserializing it.
1379		let cert = params.self_signed(&ca_key).unwrap();
1380
1381		let actual = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1382		assert!(actual.subject_alt_names.contains(&ip_san));
1383	}
1384
1385	#[cfg(feature = "x509-parser")]
1386	mod test_key_identifier_from_ca {
1387		use super::*;
1388
1389		#[test]
1390		fn load_ca_and_sign_cert() {
1391			let ca_cert = r#"-----BEGIN CERTIFICATE-----
1392MIIFDTCCAvWgAwIBAgIUVuDfDt/BUVfObGOHsM+L5/qPZfIwDQYJKoZIhvcNAQEL
1393BQ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XbUuylky0+/nbkN6hhecj+Zwt5x5R8k4saXUZ8xkMfP8RaRxyZ3rUOIC
1410BZhZm1XbQzaWIQjpjyPUWDDa9P0lGsUyrEIQaLjg1J5jYPOD132bmdIuhZtzldTV
1411zeE/4sKdrkj6HZxe1jxAhx2IWm6W+pEAcq1Ld9SmJGOxBVRRKyGsMMw6hCdWfQHv
1412Z8qRIhn3FU6ZKW2jvTGJBIXoK4u454qi6DVxkFZ0OK9VwWVuDLvs2Es95TiZPTq+
1413KJmRHWHF/Ic78XFgxVq0tVaJAs7qoOMjDkehPG1V8eewanlpcaE6rPx0eiPq+nHE
1414gCf0KmKGVM8lQe63obzprkdLKL3T4UDN19K2wqscJcPKK++27OYx2hJaJKmYzF23
14154WhIRzdALTs/2fbB68nVSz7kBtHvsHHS33Q57zEdQq5YeyUaTtCvJJobt70dy9vN
1416YolzLWoY/itEPFtbBAdnJxXlctI3bw4Mzw1d66Wt+//R45+cIe6cJdUIqMHDhsGf
1417U8EuffvDcTJuUzIkyzbyOI15r1TMbRt8vFR0jzagZBCG73lVacH/bYEb2j4Z1ORi
1418L2Fl4tgIQ5tyaTpu9gpJZvPU0VZ/j+1Jdk1c9PJ6xhCjof4nzI9YsLbI8lPtu8K/
1419Ng==
1420-----END CERTIFICATE-----"#;
1421
1422			let ca_key = r#"-----BEGIN PRIVATE KEY-----
1423MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQCl8mbL+2cHpPcn
1424OeCF1owpDMFOHgzM/VMNOlhExYWbWrsA6OLrAnmCWv+8fEWWxnCPfbP7zjB4yHVc
14252OoPaeXOqkvuxFAYVwEWFQe+M11BsIFRrLO5YMPtHTcYUPBdDNrJgV1D/RZSSYya
1426W1nlPvd4spxsvj01xbWDJzqFSOBu2CrBuZV9MwSVDWGbJRM+iqfHkWLuxQHXHFNL
1427uW5oNNmtVolzmCXjdfgIn1G0TczSJ2QqjAhYKB3M29A7ylN0F/8a3AcX6/0jST6s
1428ZXnFL7K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Odlu/hzjVvmcTS9d0UPc1VwTyHcaBA2Rb8yM16bvOu8580SgzR
1461LpsUrVJi64X95a9u2MeyjF8quyWTh4s900wTzW0CggEAJrGNHMTKtJmfXAp4OoHv
1462CHNs8Fd3a6zdIFQuulqxKGKgmyfyj0ZVmHmizLEm+GSnpqKk73u4u7jNSgF2w85u
14632teg6BH23VN/roe/hRrWV5czegzOAj5ZSZjmWlmZYXJEyKwKdG89ZOhit7RkVe0x
1464xBeyjWPDwoP0d1WbQGwyboflaEmcO8kOX8ITa9CMNokMkrScGvSlWYRlBiz1LzIE
1465E0i3Uj90pFtoCpKv6JsAF88bnHHrltOjnK3oTdAontTLZNuFjbsOBGmWd9XK5tGd
1466yPaor0EknPNpW9OYsssDq9vVvqXHc+GERTkS+RsBW7JKyoCuqKlhdVmkFoAmgppS
1467VwKCAQB7nOsjguXliXXpayr1ojg1T5gk+R+JJMbOw7fuhexavVLi2I/yGqAq9gfQ
1468KoumYrd8EYb0WddqK0rdfjZyPmiqCNr72w3QKiEDx8o3FHUajSL1+eXpJJ03shee
1469BqN6QWlRz8fu7MAZ0oqv06Cln+3MZRUvc6vtMHAEzD7y65HV+Do7z61YmvwVZ2N2
1470+30kckNnDVdggOklBmlSk5duej+RVoAKP8U5wV3Z/bS5J0OI75fxhuzybPcVfkwE
1471JiY98T5oN1X0C/qAXxJfSvklbru9fipwGt3dho5Tm6Ee3cYf+plnk4WZhSnqyef4
1472PITGdT9dgN88nHPCle0B1+OY+OZ5
1473-----END PRIVATE KEY-----"#;
1474
1475			let ca_kp = KeyPair::from_pem(ca_key).unwrap();
1476			let ca = Issuer::from_ca_cert_pem(ca_cert, ca_kp).unwrap();
1477			let ca_ski = vec![
1478				0x97, 0xD4, 0x76, 0xA1, 0x9B, 0x1A, 0x71, 0x35, 0x2A, 0xC7, 0xF4, 0xA1, 0x84, 0x12,
1479				0x56, 0x06, 0xBA, 0x5D, 0x61, 0x84,
1480			];
1481
1482			assert_eq!(
1483				&KeyIdMethod::PreSpecified(ca_ski.clone()),
1484				ca.key_identifier_method.as_ref()
1485			);
1486
1487			let ca_cert_der = CertificateDer::from_pem_slice(ca_cert.as_bytes()).unwrap();
1488			let (_, x509_ca) = x509_parser::parse_x509_certificate(ca_cert_der.as_ref()).unwrap();
1489			assert_eq!(
1490				&ca_ski,
1491				&x509_ca
1492					.iter_extensions()
1493					.find_map(|ext| match ext.parsed_extension() {
1494						x509_parser::extensions::ParsedExtension::SubjectKeyIdentifier(key_id) => {
1495							Some(key_id.0.to_vec())
1496						},
1497						_ => None,
1498					})
1499					.unwrap()
1500			);
1501
1502			let ee_key = KeyPair::generate().unwrap();
1503			let ee_params = CertificateParams {
1504				use_authority_key_identifier_extension: true,
1505				..CertificateParams::default()
1506			};
1507			let ee_cert = ee_params.signed_by(&ee_key, &ca).unwrap();
1508
1509			let (_, x509_ee) = x509_parser::parse_x509_certificate(ee_cert.der()).unwrap();
1510			assert_eq!(
1511				&ca_ski,
1512				&x509_ee
1513					.iter_extensions()
1514					.find_map(|ext| match ext.parsed_extension() {
1515						x509_parser::extensions::ParsedExtension::AuthorityKeyIdentifier(aki) => {
1516							aki.key_identifier.as_ref().map(|ki| ki.0.to_vec())
1517						},
1518						_ => None,
1519					})
1520					.unwrap()
1521			);
1522		}
1523	}
1524}