x509-cert 0.3.0

Pure Rust implementation of the X.509 Public Key Infrastructure Certificate format as described in RFC 5280
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! X509 Certificate builder

use alloc::vec;
use core::fmt;
use der::{Encode, asn1::BitString, referenced::OwnedToRef};
use signature::{
    AsyncRandomizedSigner, AsyncSigner, Keypair, RandomizedSigner, Signer, rand_core::CryptoRng,
};
use spki::{
    DynSignatureAlgorithmIdentifier, EncodePublicKey, ObjectIdentifier, SignatureBitStringEncoding,
};

use crate::{
    AlgorithmIdentifier, SubjectPublicKeyInfo,
    certificate::{self, Certificate, TbsCertificate, Version},
    crl::{CertificateList, RevokedCert, TbsCertList},
    ext::{
        Extensions, ToExtension,
        pkix::{AuthorityKeyIdentifier, CrlNumber, SubjectKeyIdentifier},
    },
    serial_number::SerialNumber,
    time::{Time, Validity},
};

pub mod profile;

use self::profile::BuilderProfile;

#[deprecated(
    since = "0.3.0",
    note = "please use `x509_cert::builder::profile::BuilderProfile` instead"
)]
pub use self::profile::BuilderProfile as Profile;

#[deprecated(
    since = "0.3.0",
    note = "please use `x509_cert::request::RequestBuilder` instead"
)]
pub use crate::request::RequestBuilder;

pub(crate) const NULL_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("0.0.0");

/// Error type
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// ASN.1 DER-related errors.
    Asn1(der::Error),

    /// Public key errors propagated from the [`spki::Error`] type.
    PublicKey(spki::Error),

    /// Signing error propagated for the [`signature::Error`] type.
    Signature(signature::Error),

    /// Each RelativeDistinguishedName MUST contain exactly one AttributeTypeAndValue.
    NonUniqueRdn,

    /// Each Name MUST NOT contain more than one instance of a given
    /// AttributeTypeAndValue across all RelativeDistinguishedNames unless explicitly
    /// allowed in these Requirements
    NonUniqueATV,

    /// Non-ordered attribute or invalid attribute
    InvalidAttribute {
        /// Offending [`ObjectIdentifier`]
        oid: ObjectIdentifier,
    },

    /// Not all required elements were specified
    MissingAttributes,
}

impl core::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Asn1(err) => write!(f, "ASN.1 error: {err}"),
            Error::PublicKey(err) => write!(f, "public key error: {err}"),
            Error::Signature(err) => write!(f, "signature error: {err}"),
            Error::NonUniqueRdn => write!(
                f,
                "Each RelativeDistinguishedName MUST contain exactly one AttributeTypeAndValue."
            ),
            Error::NonUniqueATV => write!(
                f,
                "Each Name MUST NOT contain more than one instance of a given AttributeTypeAndValue"
            ),
            Error::InvalidAttribute { oid } => write!(
                f,
                "Non-ordered attribute or invalid attribute found (oid={oid})"
            ),
            Error::MissingAttributes => write!(f, "Not all required elements were specified"),
        }
    }
}

impl From<der::Error> for Error {
    fn from(err: der::Error) -> Error {
        Error::Asn1(err)
    }
}

impl From<spki::Error> for Error {
    fn from(err: spki::Error) -> Error {
        Error::PublicKey(err)
    }
}

impl From<signature::Error> for Error {
    fn from(err: signature::Error) -> Error {
        Error::Signature(err)
    }
}

/// Result type
pub type Result<T> = core::result::Result<T, Error>;

/// X509 Certificate builder
///
#[cfg_attr(feature = "std", doc = "```")]
#[cfg_attr(not(feature = "std"), doc = "```ignore")]
/// use der::Decode;
/// use x509_cert::spki::SubjectPublicKeyInfo;
/// use x509_cert::builder::{CertificateBuilder, Builder, profile};
/// use x509_cert::name::Name;
/// use x509_cert::serial_number::SerialNumber;
/// use x509_cert::time::Validity;
/// use std::str::FromStr;
///
/// # const RSA_2048_DER: &[u8] = include_bytes!("../tests/examples/rsa2048-pub.der");
/// # const RSA_2048_PRIV_DER: &[u8] = include_bytes!("../tests/examples/rsa2048-priv.der");
/// # use rsa::{pkcs1v15::SigningKey, pkcs1::DecodeRsaPrivateKey};
/// # use sha2::Sha256;
/// # use std::time::Duration;
/// # use der::referenced::RefToOwned;
/// # fn rsa_signer() -> SigningKey<Sha256> {
/// #     let private_key = rsa::RsaPrivateKey::from_pkcs1_der(RSA_2048_PRIV_DER).unwrap();
/// #     let signing_key = SigningKey::<Sha256>::new(private_key);
/// #     signing_key
/// # }
///
/// let serial_number = SerialNumber::from(42u32);
/// let validity = Validity::from_now(Duration::new(5, 0)).unwrap();
/// let subject = Name::from_str("CN=World domination corporation,O=World domination Inc,C=US").unwrap();
/// let profile = profile::cabf::Root::new(false,subject).expect("Create root profile");
///
/// let pub_key = SubjectPublicKeyInfo::try_from(RSA_2048_DER).expect("get rsa pub key");
///
/// let mut signer = rsa_signer();
/// let mut builder = CertificateBuilder::new(
///     profile,
///     serial_number,
///     validity,
///     pub_key,
/// )
/// .expect("Create certificate builder");
///
/// let cert = builder.build(&signer).expect("Create certificate");
/// ```
pub struct CertificateBuilder<P> {
    tbs: TbsCertificate,
    extensions: Extensions,
    profile: P,
}

impl<P> CertificateBuilder<P>
where
    P: BuilderProfile,
{
    /// Creates a new certificate builder
    pub fn new(
        profile: P,
        serial_number: SerialNumber,
        mut validity: Validity,
        subject_public_key_info: SubjectPublicKeyInfo,
    ) -> Result<Self> {
        let signature_alg = AlgorithmIdentifier {
            oid: NULL_OID,
            parameters: None,
        };

        let subject = profile.get_subject();
        let issuer = profile.get_issuer(&subject);

        validity.not_before.rfc5280_adjust_utc_time()?;
        validity.not_after.rfc5280_adjust_utc_time()?;

        let tbs = TbsCertificate {
            version: Version::V3,
            serial_number,
            signature: signature_alg,
            issuer,
            validity,
            subject,
            subject_public_key_info,
            extensions: None,

            // We will not generate unique identifier because as per RFC5280 Section 4.1.2.8:
            //   CAs conforming to this profile MUST NOT generate
            //   certificates with unique identifiers.
            //
            // https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.8
            issuer_unique_id: None,
            subject_unique_id: None,
        };

        let extensions = Extensions::default();
        Ok(Self {
            tbs,
            extensions,
            profile,
        })
    }

    /// Add an extension to this certificate
    ///
    /// Extensions need to implement [`ToExtension`], examples may be found in
    /// in [`ToExtension` documentation](../ext/trait.ToExtension.html#examples) or
    /// [the implementors](../ext/trait.ToExtension.html#implementors).
    pub fn add_extension<E: ToExtension>(
        &mut self,
        extension: E,
    ) -> core::result::Result<(), E::Error> {
        let ext = extension.to_extension(&self.tbs.subject, &self.extensions)?;
        self.extensions.push(ext);
        Ok(())
    }
}

/// Trait for X509 builders
///
/// This trait defines the interface between builder and the signers.
pub trait Builder: Sized {
    /// Type built by this builder
    type Output: Sized;

    /// Assemble the final object from signature.
    fn assemble<S>(self, signature: BitString, signer: &S) -> Result<Self::Output>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey;

    /// Finalize and return a serialization of the object for signature.
    fn finalize<S>(&mut self, signer: &S) -> Result<vec::Vec<u8>>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey;

    /// Run the object through the signer and build it.
    ///
    /// # Notes
    ///
    /// When using ECDSA signers, the `Signature` parameter will need to be explicit
    /// as multiple implementation of [`signature::Signer`] with various signature
    /// are available.
    ///
    /// This would look like:
    #[cfg_attr(feature = "std", doc = "```no_run")]
    #[cfg_attr(not(feature = "std"), doc = "```ignore")]
    /// # use p256::elliptic_curve::Generate;
    /// # use rand::rng;
    /// # use std::{
    /// #     str::FromStr,
    /// #     time::Duration
    /// # };
    /// # use x509_cert::{
    /// #     builder::{self, CertificateBuilder, Builder},
    /// #     name::Name,
    /// #     serial_number::SerialNumber,
    /// #     spki::SubjectPublicKeyInfo,
    /// #     time::Validity
    /// # };
    /// #
    /// # let mut rng = rng();
    /// # let signer = p256::ecdsa::SigningKey::generate_from_rng(&mut rng);
    /// # let builder = CertificateBuilder::new(
    /// #     builder::profile::cabf::Root::new(
    /// #         false,
    /// #         Name::from_str("CN=World domination corporation").unwrap()
    /// #     ).unwrap(),
    /// #     SerialNumber::from(42u32),
    /// #     Validity::from_now(Duration::new(5, 0)).unwrap(),
    /// #     SubjectPublicKeyInfo::from_key(signer.verifying_key()).unwrap()
    /// # ).unwrap();
    /// let certificate = builder.build::<_, ecdsa::der::Signature<_>>(&signer).unwrap();
    /// ```
    fn build<S, Signature>(mut self, signer: &S) -> Result<Self::Output>
    where
        S: Signer<Signature>,
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
        Signature: SignatureBitStringEncoding,
    {
        let blob = self.finalize(signer)?;

        let signature = signer.try_sign(&blob)?.to_bitstring()?;

        self.assemble(signature, signer)
    }

    /// Run the object through the signer and build it.
    ///
    /// # Notes
    ///
    /// When using ECDSA signers, the `Signature` parameter will need to be explicit
    /// as multiple implementation of [`signature::Signer`] with various signature
    /// are available.
    ///
    /// This would look like:
    #[cfg_attr(feature = "std", doc = "```no_run")]
    #[cfg_attr(not(feature = "std"), doc = "```ignore")]
    /// # use p256::elliptic_curve::Generate;
    /// # use rand::rng;
    /// # use std::{
    /// #     str::FromStr,
    /// #     time::Duration
    /// # };
    /// # use x509_cert::{
    /// #     builder::{self, CertificateBuilder, Builder},
    /// #     name::Name,
    /// #     serial_number::SerialNumber,
    /// #     spki::SubjectPublicKeyInfo,
    /// #     time::Validity
    /// # };
    /// #
    /// # let mut rng = rng();
    /// # let signer = p256::ecdsa::SigningKey::generate_from_rng(&mut rng);
    /// # let builder = CertificateBuilder::new(
    /// #     builder::profile::cabf::Root::new(
    /// #         false,
    /// #         Name::from_str("CN=World domination corporation").unwrap()
    /// #     ).unwrap(),
    /// #     SerialNumber::from(42u32),
    /// #     Validity::from_now(Duration::new(5, 0)).unwrap(),
    /// #     SubjectPublicKeyInfo::from_key(signer.verifying_key()).unwrap()
    /// # ).unwrap();
    /// let certificate = builder.build_with_rng::<_, ecdsa::der::Signature<_>, _>(
    ///     &signer,
    ///     &mut rng
    /// ).unwrap();
    /// ```
    fn build_with_rng<S, Signature, R>(mut self, signer: &S, rng: &mut R) -> Result<Self::Output>
    where
        S: RandomizedSigner<Signature>,
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
        Signature: SignatureBitStringEncoding,
        R: CryptoRng + ?Sized,
    {
        let blob = self.finalize(signer)?;

        let signature = signer.try_sign_with_rng(rng, &blob)?.to_bitstring()?;

        self.assemble(signature, signer)
    }
}

impl<P> Builder for CertificateBuilder<P>
where
    P: BuilderProfile,
{
    type Output = Certificate;

    fn finalize<S>(&mut self, cert_signer: &S) -> Result<vec::Vec<u8>>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        let verifying_key = cert_signer.verifying_key();
        let signer_pub = SubjectPublicKeyInfo::from_key(&verifying_key)?;

        self.tbs.signature = cert_signer.signature_algorithm_identifier()?;

        let mut default_extensions = self.profile.build_extensions(
            self.tbs.subject_public_key_info.owned_to_ref(),
            signer_pub.owned_to_ref(),
            &self.tbs,
        )?;

        self.extensions.append(&mut default_extensions);

        if !self.extensions.is_empty() {
            self.tbs.extensions = Some(self.extensions.clone());
        }

        if self.tbs.extensions.is_none() {
            if self.tbs.issuer_unique_id.is_some() || self.tbs.subject_unique_id.is_some() {
                self.tbs.version = Version::V2;
            } else {
                self.tbs.version = Version::V1;
            }
        }

        self.tbs.to_der().map_err(Error::from)
    }

    fn assemble<S>(self, signature: BitString, _signer: &S) -> Result<Self::Output>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        let signature_algorithm = self.tbs.signature.clone();

        Ok(Certificate {
            tbs_certificate: self.tbs,
            signature_algorithm,
            signature,
        })
    }
}

/// Trait for async X509 builders
///
/// This trait defines the interface between builder and the signers.
///
/// This is the async counterpart of [`Builder`].
#[allow(async_fn_in_trait)]
pub trait AsyncBuilder: Sized {
    /// Type built by this builder
    type Output: Sized;

    /// Assemble the final object from signature.
    fn assemble<S>(self, signature: BitString, signer: &S) -> Result<Self::Output>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey;

    /// Finalize and return a serialization of the object for signature.
    fn finalize<S>(&mut self, signer: &S) -> Result<vec::Vec<u8>>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey;

    /// Run the object through the signer and build it.
    ///
    /// # Notes
    ///
    /// When using ECDSA signers, the `Signature` parameter will need to be explicit
    /// as multiple implementation of [`signature::AsyncSigner`] with various signature
    /// are available.
    ///
    /// This would look like:
    #[cfg_attr(feature = "std", doc = "```no_run")]
    #[cfg_attr(not(feature = "std"), doc = "```ignore")]
    /// # use p256::elliptic_curve::Generate;
    /// # use rand::rng;
    /// # use std::{
    /// #     str::FromStr,
    /// #     time::Duration
    /// # };
    /// # use x509_cert::{
    /// #     builder::{self, CertificateBuilder, AsyncBuilder},
    /// #     name::Name,
    /// #     serial_number::SerialNumber,
    /// #     spki::SubjectPublicKeyInfo,
    /// #     time::Validity
    /// # };
    /// #
    /// # async fn build() -> builder::Result<()> {
    /// # let mut rng = rng();
    /// # let signer = p256::ecdsa::SigningKey::generate_from_rng(&mut rng);
    /// # let builder = CertificateBuilder::new(
    /// #     builder::profile::cabf::Root::new(
    /// #         false,
    /// #         Name::from_str("CN=World domination corporation").unwrap()
    /// #     ).unwrap(),
    /// #     SerialNumber::from(42u32),
    /// #     Validity::from_now(Duration::new(5, 0)).unwrap(),
    /// #     SubjectPublicKeyInfo::from_key(signer.verifying_key()).unwrap()
    /// # ).unwrap();
    /// let certificate = builder.build_async::<_, ecdsa::der::Signature<_>>(&signer).await?;
    /// # Ok(())
    /// # }
    /// ```
    async fn build_async<S, Signature>(mut self, signer: &S) -> Result<Self::Output>
    where
        S: AsyncSigner<Signature>,
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
        Signature: SignatureBitStringEncoding,
    {
        let blob = self.finalize(signer)?;

        let signature = signer.sign_async(&blob).await?.to_bitstring()?;

        self.assemble(signature, signer)
    }

    /// Run the object through the signer and build it.
    ///
    /// # Notes
    ///
    /// When using ECDSA signers, the `Signature` parameter will need to be explicit
    /// as multiple implementation of [`signature::AsyncSigner`] with various signature
    /// are available.
    ///
    /// This would look like:
    #[cfg_attr(feature = "std", doc = "```no_run")]
    #[cfg_attr(not(feature = "std"), doc = "```ignore")]
    /// # use p256::elliptic_curve::Generate;
    /// # use rand::rng;
    /// # use std::{
    /// #     str::FromStr,
    /// #     time::Duration
    /// # };
    /// # use x509_cert::{
    /// #     builder::{self, CertificateBuilder, AsyncBuilder},
    /// #     name::Name,
    /// #     serial_number::SerialNumber,
    /// #     spki::SubjectPublicKeyInfo,
    /// #     time::Validity
    /// # };
    /// #
    /// # async fn build() -> builder::Result<()> {
    /// # let mut rng = rng();
    /// # let signer = p256::ecdsa::SigningKey::generate_from_rng(&mut rng);
    /// # let builder = CertificateBuilder::new(
    /// #     builder::profile::cabf::Root::new(
    /// #         false,
    /// #         Name::from_str("CN=World domination corporation").unwrap()
    /// #     ).unwrap(),
    /// #     SerialNumber::from(42u32),
    /// #     Validity::from_now(Duration::new(5, 0)).unwrap(),
    /// #     SubjectPublicKeyInfo::from_key(signer.verifying_key()).unwrap()
    /// # ).unwrap();
    /// let certificate = builder.build_with_rng_async::<_, ecdsa::der::Signature<_>, _>(&signer, &mut rng).await?;
    /// # Ok(())
    /// # }
    /// ```
    async fn build_with_rng_async<S, Signature, R>(
        mut self,
        signer: &S,
        rng: &mut R,
    ) -> Result<Self::Output>
    where
        S: AsyncRandomizedSigner<Signature>,
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
        Signature: SignatureBitStringEncoding,
        R: CryptoRng + ?Sized,
    {
        let blob = self.finalize(signer)?;

        let signature = signer
            .try_sign_with_rng_async(rng, &blob)
            .await?
            .to_bitstring()?;

        self.assemble(signature, signer)
    }
}

impl<T> AsyncBuilder for T
where
    T: Builder,
{
    type Output = <T as Builder>::Output;

    fn assemble<S>(self, signature: BitString, signer: &S) -> Result<Self::Output>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        <T as Builder>::assemble(self, signature, signer)
    }

    fn finalize<S>(&mut self, signer: &S) -> Result<vec::Vec<u8>>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        <T as Builder>::finalize(self, signer)
    }
}

/// X.509 CRL builder
pub struct CrlBuilder<P = certificate::Rfc5280>
where
    P: certificate::Profile,
{
    tbs: TbsCertList<P>,
}

impl<P> CrlBuilder<P>
where
    P: certificate::Profile,
{
    /// Create a `CrlBuilder` with the given issuer and the given monotonic [`CrlNumber`]
    #[cfg(feature = "std")]
    pub fn new(issuer: &Certificate, crl_number: CrlNumber) -> der::Result<Self> {
        let this_update = Time::now()?;
        Self::new_with_this_update(issuer, crl_number, this_update)
    }

    /// Create a `CrlBuilder` with the given issuer, a given monotonic [`CrlNumber`], and valid
    /// from the given `this_update` start validity date.
    pub fn new_with_this_update(
        issuer: &Certificate,
        crl_number: CrlNumber,
        this_update: Time,
    ) -> der::Result<Self> {
        // Replaced later when the finalize is called
        let signature_alg = AlgorithmIdentifier {
            oid: NULL_OID,
            parameters: None,
        };

        let issuer_name = issuer.tbs_certificate.subject().clone();

        let mut crl_extensions = Extensions::new();
        crl_extensions.push(crl_number.to_extension(&issuer_name, &crl_extensions)?);
        let aki = match issuer
            .tbs_certificate
            .get_extension::<AuthorityKeyIdentifier>()?
        {
            Some((_, aki)) => aki,
            None => {
                let ski = SubjectKeyIdentifier::try_from(
                    issuer
                        .tbs_certificate
                        .subject_public_key_info()
                        .owned_to_ref(),
                )?;
                AuthorityKeyIdentifier {
                    // KeyIdentifier must be the same as subjectKeyIdentifier
                    key_identifier: Some(ski.0.clone()),
                    // other fields must not be present.
                    ..Default::default()
                }
            }
        };
        crl_extensions.push(aki.to_extension(&issuer_name, &crl_extensions)?);

        let tbs = TbsCertList {
            version: Version::V2,
            signature: signature_alg,
            issuer: issuer_name,
            this_update,
            next_update: None,
            revoked_certificates: None,
            crl_extensions: Some(crl_extensions),
        };

        Ok(Self { tbs })
    }

    /// Make the CRL valid until the given `next_update`
    pub fn with_next_update(mut self, next_update: Option<Time>) -> Self {
        self.tbs.next_update = next_update;
        self
    }

    /// Add certificates to the revocation list
    pub fn with_certificates<I>(mut self, revoked: I) -> Self
    where
        I: Iterator<Item = RevokedCert<P>>,
    {
        let certificates = self
            .tbs
            .revoked_certificates
            .get_or_insert_with(vec::Vec::new);

        let mut revoked: vec::Vec<RevokedCert<P>> = revoked.collect();
        certificates.append(&mut revoked);

        self
    }
}

impl<P> Builder for CrlBuilder<P>
where
    P: certificate::Profile,
{
    type Output = CertificateList<P>;

    fn finalize<S>(&mut self, cert_signer: &S) -> Result<vec::Vec<u8>>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        self.tbs.signature = cert_signer.signature_algorithm_identifier()?;

        self.tbs.to_der().map_err(Error::from)
    }

    fn assemble<S>(self, signature: BitString, _signer: &S) -> Result<Self::Output>
    where
        S: Keypair + DynSignatureAlgorithmIdentifier,
        S::VerifyingKey: EncodePublicKey,
    {
        let signature_algorithm = self.tbs.signature.clone();

        Ok(CertificateList {
            tbs_cert_list: self.tbs,
            signature_algorithm,
            signature,
        })
    }
}