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