Skip to main content

at_cryptoauth/cert/
request.rs

1//! PKCS#10 Certification Request types
2
3use crate::PublicKey;
4
5use super::{attr::Attributes, name::Name};
6
7use der::{
8    Decode, DecodeValue, EncodeValue, Enumerated, FixedTag, Header, Length, Reader, Sequence,
9    Writer,
10};
11use p256::{EncodedPoint, ecdsa::DerSignature};
12use spki::{AlgorithmIdentifierRef, ObjectIdentifier};
13
14/// Version identifier for certification request information.
15///
16/// (RFC 2986 designates `0` as the only valid version)
17#[derive(Clone, Debug, Copy, PartialEq, Eq, Enumerated, Default)]
18#[asn1(type = "INTEGER")]
19#[repr(u8)]
20pub enum Version {
21    /// Denotes PKCS#8 v1
22    #[default]
23    V1 = 0,
24}
25
26/// PKCS#10 `CertificationRequestInfo` as defined in [RFC 2986 Section 4].
27///
28/// ```text
29/// CertificationRequestInfo ::= SEQUENCE {
30///     version       INTEGER { v1(0) } (v1,...),
31///     subject       Name,
32///     subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
33///     attributes    [0] Attributes{{ CRIAttributes }}
34/// }
35/// ```
36///
37/// [RFC 2986 Section 4]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
38#[derive(Clone, Debug, Sequence)]
39pub struct CertReqInfo<'a> {
40    /// Certification request version.
41    pub version: Version,
42
43    /// Subject name.
44    pub subject: Name<'a>,
45
46    /// Subject public key info.
47    pub public_key: spki::SubjectPublicKeyInfo<ObjectIdentifier, PublicKeyBitString>,
48
49    /// Request attributes.
50    #[asn1(context_specific = "0", tag_mode = "IMPLICIT")]
51    pub attributes: Attributes<'a>,
52}
53
54/// PKCS#10 `CertificationRequest` as defined in [RFC 2986 Section 4].
55///
56/// ```text
57/// CertificationRequest ::= SEQUENCE {
58///     certificationRequestInfo CertificationRequestInfo,
59///     signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
60///     signature          BIT STRING
61/// }
62/// ```
63///
64/// [RFC 2986 Section 4]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
65#[derive(Clone, Debug, Sequence)]
66pub struct CertReq<'a> {
67    /// Certification request information.
68    pub info: CertReqInfo<'a>,
69
70    /// Signature algorithm identifier.
71    pub algorithm: AlgorithmIdentifierRef<'a>,
72
73    /// Signature.
74    pub signature: SignatureBitString,
75}
76
77#[cfg(feature = "pem")]
78impl<'a> CertReq<'a> {
79    pub fn to_pem_slice(
80        &self,
81        buf: &mut [u8],
82        line_ending: pem_rfc7468::LineEnding,
83    ) -> der::Result<usize> {
84        use super::pem::PemWriter;
85        use der::Encode;
86        use pem_rfc7468::PemLabel;
87
88        let der_len = usize::try_from(self.encoded_len()?)?;
89        let pem_len = pem_rfc7468::encapsulated_len(Self::PEM_LABEL, line_ending, der_len)
90            .map_err(|_| der::ErrorKind::Failed)?;
91
92        if buf.len() < pem_len {
93            return Err(der::ErrorKind::Overflow.into());
94        }
95
96        let mut writer = PemWriter::new(Self::PEM_LABEL, line_ending, buf)?;
97        self.encode(&mut writer)?;
98
99        writer.finish()
100    }
101}
102
103#[derive(Clone)]
104pub struct SignatureBitString(pub DerSignature);
105
106impl core::fmt::Debug for SignatureBitString {
107    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108        f.debug_struct("BitString")
109            .field("unused_bites", &0u8)
110            .field("bit_length", &((self.0.len()) * 8))
111            .field("inner", &self.0.as_bytes())
112            .finish()
113    }
114}
115
116impl FixedTag for SignatureBitString {
117    const TAG: der::Tag = der::Tag::BitString;
118}
119
120impl<'a> DecodeValue<'a> for SignatureBitString {
121    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
122        let inner_len = (header.length - Length::ONE)?;
123        let unused_bits = reader.read_byte()?;
124
125        // BIT STRING must have 0 unused bits for a valid DER signature
126        if unused_bits != 0 {
127            return Err(der::Tag::BitString.value_error());
128        }
129
130        // Read the DER-encoded signature bytes
131        let mut sig_bytes = [0u8; 128]; // Max DER signature size for P-256
132        let len = usize::try_from(inner_len)?;
133        if len > sig_bytes.len() {
134            return Err(der::ErrorKind::Length {
135                tag: der::Tag::BitString,
136            }
137            .into());
138        }
139        reader.read_into(&mut sig_bytes[..len])?;
140
141        // Parse as DER signature
142        let signature = DerSignature::from_der(&sig_bytes[..len])
143            .map_err(|_| der::Tag::BitString.value_error())?;
144
145        Ok(Self(signature))
146    }
147}
148
149impl EncodeValue for SignatureBitString {
150    fn value_len(&self) -> der::Result<Length> {
151        Length::ONE + Length::try_from(self.0.len())?
152    }
153
154    fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
155        writer.write(&[0u8])?;
156        writer.write(self.0.as_bytes())
157    }
158}
159
160#[derive(Clone)]
161pub struct PublicKeyBitString(pub PublicKey);
162
163impl core::fmt::Debug for PublicKeyBitString {
164    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
165        f.debug_struct("BitString")
166            .field("unused_bites", &0u8)
167            .field("bit_length", &((self.0.as_ref().len()) * 8))
168            .field("inner", &self.0.as_ref())
169            .finish()
170    }
171}
172
173impl FixedTag for PublicKeyBitString {
174    const TAG: der::Tag = der::Tag::BitString;
175}
176
177impl<'a> DecodeValue<'a> for PublicKeyBitString {
178    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
179        let inner_len = (header.length - Length::ONE)?;
180        let unused_bits = reader.read_byte()?;
181
182        // BIT STRING must have 0 unused bits for a valid public key
183        if unused_bits != 0 {
184            return Err(der::Tag::BitString.value_error());
185        }
186
187        // Read the SEC1-encoded public key bytes (uncompressed: 0x04 || X || Y)
188        let len = usize::try_from(inner_len)?;
189        let mut point_bytes = [0u8; 65]; // 1 byte tag + 32 bytes X + 32 bytes Y
190        if len > point_bytes.len() {
191            return Err(der::ErrorKind::Length {
192                tag: der::Tag::BitString,
193            }
194            .into());
195        }
196        reader.read_into(&mut point_bytes[..len])?;
197
198        // Parse SEC1 encoded point
199        let point = EncodedPoint::from_bytes(&point_bytes[..len])
200            .map_err(|_| der::Tag::BitString.value_error())?;
201
202        // Extract X and Y coordinates into PublicKey
203        let x = point.x().ok_or_else(|| der::Tag::BitString.value_error())?;
204        let y = point.y().ok_or_else(|| der::Tag::BitString.value_error())?;
205
206        let mut pubkey = PublicKey::default();
207        pubkey.as_mut()[..32].copy_from_slice(x.as_slice());
208        pubkey.as_mut()[32..].copy_from_slice(y.as_slice());
209
210        Ok(Self(pubkey))
211    }
212}
213
214impl EncodeValue for PublicKeyBitString {
215    fn value_len(&self) -> der::Result<Length> {
216        let point = EncodedPoint::from_untagged_bytes(&self.0.value);
217
218        Length::ONE + Length::try_from(point.as_bytes().len())?
219    }
220
221    fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
222        let point = EncodedPoint::from_untagged_bytes(&self.0.value);
223
224        writer.write(&[0u8])?;
225        writer.write(point.as_bytes())
226    }
227}
228
229#[cfg(feature = "pem")]
230impl<'a> pem_rfc7468::PemLabel for CertReq<'a> {
231    const PEM_LABEL: &'static str = "CERTIFICATE REQUEST";
232}
233
234impl<'a> TryFrom<&'a [u8]> for CertReq<'a> {
235    type Error = der::Error;
236
237    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
238        Self::from_der(bytes)
239    }
240}