Skip to main content

at_cryptoauth/cert/
builder.rs

1//! X509 Certificate builder
2
3// use async_signature::{AsyncRandomizedSigner, AsyncSigner};
4use const_oid::db::rfc5912::{ECDSA_WITH_SHA_256, ID_EC_PUBLIC_KEY, SECP_256_R_1};
5use core::fmt;
6use der::Encode;
7use p256::ecdsa::DerSignature;
8use signature::{Keypair, RandomizedSigner, Signer, rand_core::CryptoRngCore};
9use spki::{AlgorithmIdentifier, AlgorithmIdentifierWithOid, ObjectIdentifier};
10
11use crate::PublicKey;
12
13use super::{
14    name::Name,
15    request::{CertReq, CertReqInfo, PublicKeyBitString, SignatureBitString},
16};
17
18const NULL_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("0.0.0");
19
20/// Error type
21#[derive(Debug)]
22#[non_exhaustive]
23pub enum Error {
24    /// ASN.1 DER-related errors.
25    Asn1(der::Error),
26
27    /// Public key errors propagated from the [`spki::Error`] type.
28    PublicKey(spki::Error),
29
30    /// Signing error propagated for the [`signature::Error`] type.
31    Signature(signature::Error),
32
33    Device(crate::error::Error),
34}
35
36impl fmt::Display for Error {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Error::Asn1(err) => write!(f, "ASN.1 error: {}", err),
40            Error::PublicKey(err) => write!(f, "public key error: {}", err),
41            Error::Signature(err) => write!(f, "signature error: {}", err),
42            Error::Device(err) => write!(f, "device error: {}", err),
43        }
44    }
45}
46
47impl From<der::Error> for Error {
48    fn from(err: der::Error) -> Error {
49        Error::Asn1(err)
50    }
51}
52
53impl From<spki::Error> for Error {
54    fn from(err: spki::Error) -> Error {
55        Error::PublicKey(err)
56    }
57}
58
59impl From<signature::Error> for Error {
60    fn from(err: signature::Error) -> Error {
61        Error::Signature(err)
62    }
63}
64
65impl From<crate::error::Error> for Error {
66    fn from(err: crate::error::Error) -> Error {
67        Error::Device(err)
68    }
69}
70
71/// Result type
72pub type Result<T> = core::result::Result<T, Error>;
73
74use super::{
75    certificate::{TbsCertificate, Version},
76    ext::Extensions,
77    serial_number::SerialNumber,
78    time::Validity,
79};
80use der::asn1::BitStringRef;
81use spki::SubjectPublicKeyInfoRef;
82
83/// X509 Certificate builder
84///
85/// This builder creates X.509 certificates using borrowed types for no_std/no_alloc
86/// compatibility. The builder accumulates certificate parameters and then signs
87/// the TBS (To-Be-Signed) certificate using a provided signer.
88///
89/// Unlike `RequestBuilder`, this builder outputs the DER-encoded certificate directly
90/// to a buffer rather than returning a parsed structure. This avoids lifetime issues
91/// with borrowed signature data.
92///
93/// # Example
94///
95/// ```ignore
96/// let builder = CertificateBuilder::new(
97///     serial_number,
98///     validity,
99///     issuer,
100///     subject,
101///     subject_public_key_info,
102/// )?;
103///
104/// let cert_len = builder.build_to_slice(&mut buf, &signer)?;
105/// let cert_der = &buf[..cert_len];
106/// ```
107pub struct CertificateBuilder<'a> {
108    serial_number: SerialNumber<'a>,
109    validity: Validity,
110    issuer: Name<'a>,
111    subject: Name<'a>,
112    subject_public_key_info: SubjectPublicKeyInfoRef<'a>,
113    extensions: Option<Extensions<'a, 5>>,
114}
115
116impl<'a> CertificateBuilder<'a> {
117    /// Creates a new certificate builder
118    ///
119    /// # Arguments
120    ///
121    /// * `serial_number` - Unique serial number for the certificate
122    /// * `validity` - Not before and not after times
123    /// * `issuer` - Distinguished name of the issuer
124    /// * `subject` - Distinguished name of the subject
125    /// * `subject_public_key_info` - Subject's public key info
126    pub fn new(
127        serial_number: SerialNumber<'a>,
128        validity: Validity,
129        issuer: Name<'a>,
130        subject: Name<'a>,
131        subject_public_key_info: SubjectPublicKeyInfoRef<'a>,
132    ) -> Result<Self> {
133        Ok(Self {
134            serial_number,
135            validity,
136            issuer,
137            subject,
138            subject_public_key_info,
139            extensions: None,
140        })
141    }
142
143    /// Creates a self-signed certificate builder (issuer = subject)
144    pub fn new_self_signed(
145        serial_number: SerialNumber<'a>,
146        validity: Validity,
147        subject: Name<'a>,
148        subject_public_key_info: SubjectPublicKeyInfoRef<'a>,
149    ) -> Result<Self> {
150        Ok(Self {
151            serial_number,
152            validity,
153            issuer: subject.clone(),
154            subject,
155            subject_public_key_info,
156            extensions: None,
157        })
158    }
159
160    /// Set the certificate extensions
161    pub fn with_extensions(mut self, extensions: Extensions<'a, 5>) -> Self {
162        self.extensions = Some(extensions);
163        self
164    }
165
166    /// Build the TBS certificate structure
167    fn build_tbs(&self) -> TbsCertificate<'a> {
168        let version = if self.extensions.is_some() {
169            Version::V3
170        } else {
171            Version::V1
172        };
173
174        TbsCertificate {
175            version,
176            serial_number: self.serial_number.clone(),
177            signature: AlgorithmIdentifier {
178                oid: ECDSA_WITH_SHA_256,
179                parameters: None,
180            },
181            issuer: self.issuer.clone(),
182            validity: self.validity,
183            subject: self.subject.clone(),
184            subject_public_key_info: self.subject_public_key_info.clone(),
185            issuer_unique_id: None,
186            subject_unique_id: None,
187            extensions: self.extensions.clone(),
188        }
189    }
190
191    /// Build and sign the certificate, encoding directly to DER in the provided buffer
192    ///
193    /// This method:
194    /// 1. Builds the TBS certificate
195    /// 2. Signs it using the provided signer
196    /// 3. Encodes the complete certificate as DER into the buffer
197    ///
198    /// # Arguments
199    ///
200    /// * `buf` - Buffer to write the DER-encoded certificate
201    /// * `signer` - Signer implementing `Signer<DerSignature>` and `Keypair`
202    ///
203    /// # Returns
204    ///
205    /// The number of bytes written to the buffer
206    pub fn build_to_slice<S>(self, buf: &mut [u8], signer: &S) -> Result<usize>
207    where
208        S: Signer<DerSignature>,
209        S: Keypair,
210        S: Keypair<VerifyingKey = PublicKey>,
211    {
212        use der::Encode;
213
214        // Build the TBS certificate
215        let tbs = self.build_tbs();
216
217        // Encode TBS to get bytes for signing
218        // We need a temporary buffer for the TBS encoding
219        let mut tbs_buf = [0u8; 512];
220        let tbs_der = tbs.encode_to_slice(&mut tbs_buf).map_err(Error::from)?;
221
222        // Sign the TBS certificate
223        let signature = signer.try_sign(tbs_der)?;
224
225        // Build the full certificate manually
226        // Certificate ::= SEQUENCE {
227        //     tbsCertificate       TBSCertificate,
228        //     signatureAlgorithm   AlgorithmIdentifier,
229        //     signatureValue       BIT STRING
230        // }
231
232        let sig_algorithm: AlgorithmIdentifier<()> = AlgorithmIdentifier {
233            oid: ECDSA_WITH_SHA_256,
234            parameters: None,
235        };
236
237        // Create BitStringRef from signature bytes (0 unused bits)
238        let sig_bits = BitStringRef::new(0, signature.as_bytes())
239            .map_err(|_| Error::Asn1(der::Tag::BitString.value_error()))?;
240
241        // Calculate total length
242        let tbs_len = tbs.encoded_len().map_err(Error::from)?;
243        let alg_len = sig_algorithm.encoded_len().map_err(Error::from)?;
244        let sig_len = sig_bits.encoded_len().map_err(Error::from)?;
245        let inner_len = (tbs_len + alg_len + sig_len).map_err(Error::from)?;
246
247        // Encode as SEQUENCE
248        let header = der::Header::new(der::Tag::Sequence, inner_len).map_err(Error::from)?;
249
250        let mut writer = der::SliceWriter::new(buf);
251        header.encode(&mut writer).map_err(Error::from)?;
252        tbs.encode(&mut writer).map_err(Error::from)?;
253        sig_algorithm.encode(&mut writer).map_err(Error::from)?;
254        sig_bits.encode(&mut writer).map_err(Error::from)?;
255
256        Ok(writer.finish().map_err(Error::from)?.len())
257    }
258}
259
260/// Builder for X509 Certificate Requests
261pub struct RequestBuilder<'a> {
262    info: CertReqInfo<'a>,
263}
264
265impl<'a> RequestBuilder<'a> {
266    /// Creates a new certificate request builder
267    pub fn new(subject: Name<'a>) -> Result<Self> {
268        let version = Default::default();
269
270        let algorithm = AlgorithmIdentifier {
271            oid: NULL_OID,
272            parameters: None,
273        };
274        let public_key = spki::SubjectPublicKeyInfo {
275            algorithm,
276            subject_public_key: PublicKeyBitString(PublicKey::default()),
277        };
278
279        let attributes = Default::default();
280
281        Ok(Self {
282            info: CertReqInfo {
283                version,
284                subject,
285                public_key,
286                attributes,
287            },
288        })
289    }
290}
291
292/// Trait for X509 builders
293///
294/// This trait defines the interface between builder and the signers.
295pub trait Builder: Sized {
296    /// Type built by this builder
297    type Output: Sized;
298
299    /// Assemble the final object from signature.
300    fn assemble(self, signature: DerSignature) -> Result<Self::Output>;
301
302    /// Finalize and return a serialization of the object for signature.
303    fn finalize<S>(&mut self, buf: &mut [u8], signer: &S) -> Result<usize>
304    where
305        S: Keypair,
306        S: Keypair<VerifyingKey = PublicKey>;
307
308    /// Run the object through the signer and build it.
309    fn build<S>(mut self, buf: &mut [u8], signer: &S) -> Result<Self::Output>
310    where
311        S: Signer<DerSignature>,
312        S: Keypair,
313        S: Keypair<VerifyingKey = PublicKey>,
314    {
315        let len = self.finalize(buf, signer)?;
316        let signature = signer.try_sign(&buf[..len])?;
317
318        self.assemble(signature)
319    }
320
321    /// Run the object through the signer and build it.
322    fn build_with_rng<S>(
323        mut self,
324        buf: &mut [u8],
325        signer: &S,
326        rng: &mut impl CryptoRngCore,
327    ) -> Result<Self::Output>
328    where
329        S: RandomizedSigner<DerSignature>,
330        S: Keypair,
331        S: Keypair<VerifyingKey = PublicKey>,
332    {
333        let len = self.finalize(buf, signer)?;
334        let signature = signer.try_sign_with_rng(rng, &buf[..len])?;
335
336        self.assemble(signature)
337    }
338}
339
340impl<'a> Builder for RequestBuilder<'a> {
341    type Output = CertReq<'a>;
342
343    fn finalize<S>(&mut self, buf: &mut [u8], signer: &S) -> Result<usize>
344    where
345        S: Keypair<VerifyingKey = PublicKey>,
346    {
347        self.info.public_key = spki::SubjectPublicKeyInfo {
348            algorithm: AlgorithmIdentifierWithOid {
349                oid: ID_EC_PUBLIC_KEY,
350                parameters: Some(SECP_256_R_1),
351            },
352            subject_public_key: PublicKeyBitString(signer.verifying_key()),
353        };
354
355        let res = self.info.encode_to_slice(buf).map_err(Error::from)?;
356        Ok(res.len())
357    }
358
359    fn assemble(self, signature: DerSignature) -> Result<Self::Output> {
360        Ok(CertReq {
361            info: self.info,
362            algorithm: AlgorithmIdentifier {
363                oid: ECDSA_WITH_SHA_256,
364                parameters: None,
365            },
366            signature: SignatureBitString(signature),
367        })
368    }
369}
370
371// /// Trait for async X509 builders
372// ///
373// /// This trait defines the interface between builder and the signers.
374// ///
375// /// This is the async counterpart of [`Builder`].
376// #[allow(async_fn_in_trait)]
377// pub trait AsyncBuilder: Sized {
378//     /// Type built by this builder
379//     type Output: Sized;
380
381//     /// Assemble the final object from signature.
382//     fn assemble(self, signature: DerSignature) -> Result<Self::Output>;
383
384//     /// Finalize and return a serialization of the object for signature.
385//     fn finalize<S>(&mut self, buf: &mut [u8], signer: &S) -> Result<usize>
386//     where
387//         S: Keypair,
388//         S: Keypair<VerifyingKey = PublicKey>;
389
390//     /// Run the object through the signer and build it.
391//     async fn build_async<S>(mut self, buf: &mut [u8], signer: &S) -> Result<Self::Output>
392//     where
393//         S: AsyncSigner<DerSignature>,
394//         S: Keypair,
395//         S: Keypair<VerifyingKey = PublicKey>,
396//     {
397//         let len = self.finalize(buf, signer)?;
398
399//         let signature = signer.sign_async(&buf[..len]).await?;
400
401//         self.assemble(signature)
402//     }
403
404//     /// Run the object through the signer and build it.
405//     async fn build_with_rng_async<S>(
406//         mut self,
407//         buf: &mut [u8],
408//         signer: &S,
409//         rng: &mut impl CryptoRngCore,
410//     ) -> Result<Self::Output>
411//     where
412//         S: AsyncRandomizedSigner<DerSignature>,
413//         S: Keypair,
414//         S: Keypair<VerifyingKey = PublicKey>,
415//     {
416//         let len = self.finalize(buf, signer)?;
417
418//         let signature = signer.try_sign_with_rng_async(rng, &buf[..len]).await?;
419
420//         self.assemble(signature)
421//     }
422// }
423
424// impl<T> AsyncBuilder for T
425// where
426//     T: Builder,
427// {
428//     type Output = <T as Builder>::Output;
429
430//     fn assemble(self, signature: DerSignature) -> Result<Self::Output> {
431//         <T as Builder>::assemble(self, signature)
432//     }
433
434//     fn finalize<S>(&mut self, buf: &mut [u8], signer: &S) -> Result<usize>
435//     where
436//         S: Keypair,
437//         S: Keypair<VerifyingKey = PublicKey>,
438//     {
439//         <T as Builder>::finalize(self, buf, signer)
440//     }
441// }