xwt_cert_utils/
gen.rs

1//! Certificate generation facilities.
2
3/// The params for certificate generation.
4#[allow(missing_docs)]
5pub struct Params<'a> {
6    pub common_name: &'a str,
7    pub subject_alt_names: &'a [&'a str],
8    pub valid_days_before: u32,
9    pub valid_days_after: u32,
10}
11
12#[cfg(feature = "rcgen")]
13impl<'a> Params<'a> {
14    /// Convert params into [`rcgen::CertificateParams`].
15    pub fn into_rcgen_params(self, key_pair: rcgen::KeyPair) -> rcgen::CertificateParams {
16        let mut dname = rcgen::DistinguishedName::new();
17        dname.push(rcgen::DnType::CommonName, self.common_name);
18
19        let now = time::OffsetDateTime::now_utc();
20
21        let mut cert_params = rcgen::CertificateParams::default();
22
23        cert_params
24            .distinguished_name
25            .push(rcgen::DnType::CommonName, self.common_name);
26        cert_params
27            .subject_alt_names
28            .extend(self.subject_alt_names.iter().map(|&s| match s.parse() {
29                Ok(ip) => rcgen::SanType::IpAddress(ip),
30                Err(_) => rcgen::SanType::DnsName(s.to_owned()),
31            }));
32        cert_params.alg = key_pair.algorithm();
33        cert_params.key_pair = Some(key_pair);
34        cert_params.not_before = now
35            .checked_sub(time::Duration::days(self.valid_days_before.into()))
36            .unwrap();
37        cert_params.not_after = now
38            .checked_add(time::Duration::days(self.valid_days_after.into()))
39            .unwrap();
40
41        cert_params
42    }
43
44    /// Convert params into [`rcgen::Certificate`].
45    pub fn into_rcgen_cert(self, key_pair: rcgen::KeyPair) -> rcgen::Certificate {
46        // We `unwrap` here because the key always exists (and thus is
47        // not generated on the fly, which would be fallible) and is always
48        // compatible with the requested algorithm (because the algorithm
49        // is set from the keypair).
50        rcgen::Certificate::from_params(self.into_rcgen_params(key_pair)).unwrap()
51    }
52}