Skip to main content

at_cryptoauth/cert/
compressed.rs

1//! Compressed certificate format for ATECC608 devices
2//!
3//! This module implements the ATECC-specific 72-byte compressed certificate format
4//! as defined in Microchip's Application Note (Atmel-8974).
5//!
6//! The compressed format stores only the dynamic parts of a certificate:
7//! - Signature (64 bytes: R + S)
8//! - Encoded date (3 bytes)
9//! - Signer ID (2 bytes)
10//! - Template ID (1 byte)
11//! - Chain ID (1 byte)
12//! - Serial number source (1 byte)
13
14use der::{DateTime, asn1::GeneralizedTime};
15use p256::ecdsa::DerSignature;
16
17use crate::{
18    PublicKey,
19    command::Serial,
20    error::{Error, ErrorKind},
21    memory::{Slot, SlotAddress},
22};
23
24use super::time::{Time, Validity};
25
26/// 3-byte date encoding per Microchip format
27///
28/// Layout (24 bits total, little-endian):
29/// - Bits 0-4: Year (years since `BASE_YEAR`, valid 0-31 = 2025-2056)
30/// - Bits 5-8: Month (1-12)
31/// - Bits 9-13: Day (1-31)
32/// - Bits 14-18: Hour (0-23)
33/// - Bits 19-23: Expire years (0-31 years validity)
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct CompressedDate(u32);
36
37impl CompressedDate {
38    // Bit field masks and offsets
39    const YEAR_MASK: u32 = 0x1F; // 5 bits
40    const YEAR_OFFSET: u32 = 0;
41    const MONTH_MASK: u32 = 0x0F; // 4 bits
42    const MONTH_OFFSET: u32 = 5;
43    const DAY_MASK: u32 = 0x1F; // 5 bits
44    const DAY_OFFSET: u32 = 9;
45    const HOUR_MASK: u32 = 0x1F; // 5 bits
46    const HOUR_OFFSET: u32 = 14;
47    const EXPIRE_MASK: u32 = 0x1F; // 5 bits
48    const EXPIRE_OFFSET: u32 = 19;
49
50    /// Create a new CompressedDate with all fields set to 0
51    pub const fn new() -> Self {
52        Self(0)
53    }
54
55    /// Get the year offset from [`Self::BASE_YEAR`] (0-31)
56    pub const fn year(&self) -> u8 {
57        ((self.0 >> Self::YEAR_OFFSET) & Self::YEAR_MASK) as u8
58    }
59
60    /// Set the year offset and return self (builder pattern)
61    pub const fn with_year(self, year: u8) -> Self {
62        let cleared = self.0 & !(Self::YEAR_MASK << Self::YEAR_OFFSET);
63        Self(cleared | (((year as u32) & Self::YEAR_MASK) << Self::YEAR_OFFSET))
64    }
65
66    /// Get the month (1-12)
67    pub const fn month(&self) -> u8 {
68        ((self.0 >> Self::MONTH_OFFSET) & Self::MONTH_MASK) as u8
69    }
70
71    /// Set the month and return self (builder pattern)
72    pub const fn with_month(self, month: u8) -> Self {
73        let cleared = self.0 & !(Self::MONTH_MASK << Self::MONTH_OFFSET);
74        Self(cleared | (((month as u32) & Self::MONTH_MASK) << Self::MONTH_OFFSET))
75    }
76
77    /// Get the day of month (1-31)
78    pub const fn day(&self) -> u8 {
79        ((self.0 >> Self::DAY_OFFSET) & Self::DAY_MASK) as u8
80    }
81
82    /// Set the day and return self (builder pattern)
83    pub const fn with_day(self, day: u8) -> Self {
84        let cleared = self.0 & !(Self::DAY_MASK << Self::DAY_OFFSET);
85        Self(cleared | (((day as u32) & Self::DAY_MASK) << Self::DAY_OFFSET))
86    }
87
88    /// Get the hour (0-23)
89    pub const fn hour(&self) -> u8 {
90        ((self.0 >> Self::HOUR_OFFSET) & Self::HOUR_MASK) as u8
91    }
92
93    /// Set the hour and return self (builder pattern)
94    pub const fn with_hour(self, hour: u8) -> Self {
95        let cleared = self.0 & !(Self::HOUR_MASK << Self::HOUR_OFFSET);
96        Self(cleared | (((hour as u32) & Self::HOUR_MASK) << Self::HOUR_OFFSET))
97    }
98
99    /// Get the certificate validity in years (0-31)
100    pub const fn expire_years(&self) -> u8 {
101        ((self.0 >> Self::EXPIRE_OFFSET) & Self::EXPIRE_MASK) as u8
102    }
103
104    /// Set the expire years and return self (builder pattern)
105    pub const fn with_expire_years(self, years: u8) -> Self {
106        let cleared = self.0 & !(Self::EXPIRE_MASK << Self::EXPIRE_OFFSET);
107        Self(cleared | (((years as u32) & Self::EXPIRE_MASK) << Self::EXPIRE_OFFSET))
108    }
109
110    /// Set month with validation (1-12)
111    pub fn with_month_checked(self, month: u8) -> Result<Self, Error> {
112        if !(1..=12).contains(&month) {
113            return Err(ErrorKind::BadParam.into());
114        }
115        Ok(self.with_month(month))
116    }
117
118    /// Set day with validation (1-31)
119    pub fn with_day_checked(self, day: u8) -> Result<Self, Error> {
120        if !(1..=31).contains(&day) {
121            return Err(ErrorKind::BadParam.into());
122        }
123        Ok(self.with_day(day))
124    }
125
126    /// Set hour with validation (0-23)
127    pub fn with_hour_checked(self, hour: u8) -> Result<Self, Error> {
128        if hour > 23 {
129            return Err(ErrorKind::BadParam.into());
130        }
131        Ok(self.with_hour(hour))
132    }
133}
134
135impl CompressedDate {
136    /// Base year for compressed date encoding.
137    ///
138    /// The 5-bit year field encodes an offset 0-31, giving issue years
139    /// `BASE_YEAR..=BASE_YEAR + 31`. The base is *not* stored in the 72-byte
140    /// compressed cert — it is implicit in this constant on both the issuer and
141    /// the device, so a cert compressed under one base would reconstruct to a
142    /// different date (and thus a different, unverifiable TBS) under another.
143    /// It can only be changed before any device holds a compressed cert.
144    pub const BASE_YEAR: u16 = 2025;
145
146    /// Maximum year offset (5 bits)
147    pub const MAX_YEAR_OFFSET: u8 = 31;
148
149    /// Maximum expire years (5 bits)
150    pub const MAX_EXPIRE_YEARS: u8 = 31;
151
152    /// Convert from X.509 Validity to compressed date format
153    pub fn from_validity(validity: &Validity) -> Result<Self, Error> {
154        let issue_date = validity.not_before.to_date_time();
155        let expire_date = validity.not_after.to_date_time();
156
157        // Validate notBefore < notAfter
158        if issue_date >= expire_date {
159            return Err(ErrorKind::BadParam.into());
160        }
161
162        // Calculate year offset from BASE_YEAR
163        let year_offset = issue_date
164            .year()
165            .checked_sub(Self::BASE_YEAR)
166            .ok_or(ErrorKind::BadParam)?;
167
168        if year_offset > Self::MAX_YEAR_OFFSET as u16 {
169            return Err(ErrorKind::BadParam.into());
170        }
171
172        // Calculate validity period in years
173        let expire_years = expire_date
174            .year()
175            .checked_sub(issue_date.year())
176            .ok_or(ErrorKind::BadParam)?;
177
178        if expire_years > Self::MAX_EXPIRE_YEARS as u16 {
179            return Err(ErrorKind::BadParam.into());
180        }
181
182        Ok(Self::new()
183            .with_year(year_offset as u8)
184            .with_month(issue_date.month())
185            .with_day(issue_date.day())
186            .with_hour(issue_date.hour())
187            .with_expire_years(expire_years as u8))
188    }
189
190    /// Convert compressed date to X.509 Validity
191    pub fn to_validity(&self) -> Result<Validity, Error> {
192        let issue_year = Self::BASE_YEAR + self.year() as u16;
193        let expire_year = issue_year + self.expire_years() as u16;
194
195        // Create issue date (second and nanosecond are 0)
196        let issue_datetime = DateTime::new(issue_year, self.month(), self.day(), self.hour(), 0, 0)
197            .map_err(|_| ErrorKind::BadParam)?;
198
199        // Create expire date (same month/day/hour, different year)
200        let expire_datetime =
201            DateTime::new(expire_year, self.month(), self.day(), self.hour(), 0, 0)
202                .map_err(|_| ErrorKind::BadParam)?;
203
204        // Convert to Time (use GeneralizedTime for years >= 2050, UTCTime otherwise)
205        let not_before = if issue_year >= 2050 {
206            Time::GeneralTime(GeneralizedTime::from_date_time(issue_datetime))
207        } else {
208            Time::UtcTime(
209                der::asn1::UtcTime::from_date_time(issue_datetime)
210                    .map_err(|_| ErrorKind::BadParam)?,
211            )
212        };
213
214        let not_after = if expire_year >= 2050 {
215            Time::GeneralTime(GeneralizedTime::from_date_time(expire_datetime))
216        } else {
217            Time::UtcTime(
218                der::asn1::UtcTime::from_date_time(expire_datetime)
219                    .map_err(|_| ErrorKind::BadParam)?,
220            )
221        };
222
223        Ok(Validity {
224            not_before,
225            not_after,
226        })
227    }
228
229    /// Convert to 3-byte array for storage
230    pub fn to_bytes(&self) -> [u8; 3] {
231        let raw = self.0.to_le_bytes();
232        [raw[0], raw[1], raw[2]]
233    }
234
235    /// Create from 3-byte array
236    pub fn from_bytes(bytes: [u8; 3]) -> Self {
237        let raw = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]);
238        Self(raw)
239    }
240}
241
242/// Source of certificate serial number
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum SerialSource {
245    /// Serial is stored in a Data08 block on the device
246    Stored(SlotAddress),
247    /// Serial is 0x40 | device_sn[0..9] (device certificates only)
248    DeviceSerial,
249    /// Serial is 0x40 | signer_id[0..2] (signer certificates only)
250    SignerId,
251    /// Serial is SHA256(subject public key + encoded dates) with upper 2 bits = 01
252    PubKeyHash,
253    /// Serial is SHA256(device SN + encoded dates) with upper 2 bits = 01
254    DeviceSerialHash,
255}
256
257impl SerialSource {
258    /// Tag byte stored in CompressedCertificate byte 71
259    pub fn to_tag(&self) -> u8 {
260        match self {
261            SerialSource::Stored(_) => 0x00,
262            SerialSource::DeviceSerial => 0x01,
263            SerialSource::SignerId => 0x02,
264            SerialSource::PubKeyHash => 0x03,
265            SerialSource::DeviceSerialHash => 0x04,
266        }
267    }
268
269    /// Generate serial number into provided buffer.
270    ///
271    /// Returns the slice of the buffer containing the serial number.
272    /// `Stored` variants cannot be generated — they are read from the
273    /// device by `Memory::read_certificate` transparently.
274    pub fn generate<'a>(
275        &self,
276        device_serial: &Serial,
277        signer_id: u16,
278        output: &'a mut [u8; 16],
279    ) -> Result<&'a [u8], Error> {
280        match self {
281            SerialSource::Stored(_) => {
282                // Handled by Memory::read_certificate, not here
283                Err(ErrorKind::BadParam.into())
284            }
285            SerialSource::DeviceSerial => {
286                // 0x40 | device_sn[0..9] = 10 bytes total
287                output[0] = 0x40;
288                output[1..10].copy_from_slice(device_serial.as_ref());
289                Ok(&output[..10])
290            }
291            SerialSource::SignerId => {
292                // 0x40 | signer_id[0..2] = 3 bytes total
293                output[0] = 0x40;
294                output[1..3].copy_from_slice(&signer_id.to_be_bytes());
295                Ok(&output[..3])
296            }
297            SerialSource::PubKeyHash | SerialSource::DeviceSerialHash => {
298                Err(ErrorKind::Unimplemented.into())
299            }
300        }
301    }
302}
303
304/// Source of the certificate subject value (e.g. a per-device common name).
305///
306/// Mirrors [`SerialSource`]: the subject is not stored in the compressed
307/// certificate, so one shared template can serve many devices and the
308/// per-device value is resolved at reconstruction time. The library stays
309/// agnostic to any device-identity convention — derivations live in the caller
310/// via [`SubjectSource::FromSerial`].
311#[derive(Clone, Copy, Debug)]
312pub enum SubjectSource<'a> {
313    /// Subject is fully fixed in the template; nothing is injected.
314    Template,
315    /// Inject these exact bytes at the subject element.
316    Provided(&'a [u8]),
317    /// Derive the subject from the device serial at reconstruction time.
318    ///
319    /// The function writes the value into the buffer and returns its length,
320    /// or `None` on failure. Lets the caller keep its own identity convention
321    /// (UUID format, etc.) without this library encoding it.
322    FromSerial(fn(&Serial, &mut [u8]) -> Option<usize>),
323}
324
325/// 72-byte compressed certificate stored on device
326///
327/// Layout:
328/// - Bytes 0-31: Signature R component
329/// - Bytes 32-63: Signature S component
330/// - Bytes 64-66: Compressed date (3 bytes)
331/// - Bytes 67-68: Signer ID (2 bytes, big-endian)
332/// - Byte 69: Template ID
333/// - Byte 70: Chain ID
334/// - Byte 71: Serial number source
335#[derive(Clone, Debug)]
336pub struct CompressedCertificate {
337    data: [u8; Self::SIZE],
338}
339
340impl CompressedCertificate {
341    /// Total size of compressed certificate in bytes
342    pub const SIZE: usize = 72;
343
344    /// Offset of signature R component
345    const SIG_R_OFFSET: usize = 0;
346    /// Offset of signature S component
347    const SIG_S_OFFSET: usize = 32;
348    /// Offset of compressed date
349    const DATE_OFFSET: usize = 64;
350    /// Offset of signer ID
351    const SIGNER_ID_OFFSET: usize = 67;
352    /// Offset of template ID
353    const TEMPLATE_ID_OFFSET: usize = 69;
354    /// Offset of chain ID
355    const CHAIN_ID_OFFSET: usize = 70;
356    /// Offset of serial source
357    const SERIAL_SOURCE_OFFSET: usize = 71;
358
359    /// Create a new compressed certificate from raw data
360    pub fn new(data: [u8; Self::SIZE]) -> Self {
361        Self { data }
362    }
363
364    /// Create a zeroed compressed certificate
365    pub fn zeroed() -> Self {
366        Self {
367            data: [0u8; Self::SIZE],
368        }
369    }
370
371    /// Get the signature R component (32 bytes)
372    pub fn signature_r(&self) -> &[u8; 32] {
373        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET]
374            .try_into()
375            .unwrap()
376    }
377
378    /// Get the signature S component (32 bytes)
379    pub fn signature_s(&self) -> &[u8; 32] {
380        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET]
381            .try_into()
382            .unwrap()
383    }
384
385    /// Set the signature from R and S components
386    pub fn set_signature(&mut self, r: &[u8; 32], s: &[u8; 32]) {
387        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET].copy_from_slice(r);
388        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET].copy_from_slice(s);
389    }
390
391    /// Convert the stored signature to a DER-encoded signature
392    pub fn to_der_signature(&self) -> Result<DerSignature, Error> {
393        // Combine R and S into a fixed-size signature
394        let mut sig_bytes = [0u8; 64];
395        sig_bytes[..32].copy_from_slice(self.signature_r());
396        sig_bytes[32..].copy_from_slice(self.signature_s());
397
398        // Convert to p256 Signature first, then to DER
399        let signature =
400            p256::ecdsa::Signature::from_slice(&sig_bytes).map_err(|_| ErrorKind::BadParam)?;
401
402        Ok(signature.to_der())
403    }
404
405    /// Set the signature from a DER-encoded signature
406    pub fn set_signature_from_der(&mut self, sig: &DerSignature) -> Result<(), Error> {
407        // Convert DER to fixed-size format
408        let signature =
409            p256::ecdsa::Signature::from_der(sig.as_bytes()).map_err(|_| ErrorKind::BadParam)?;
410
411        let bytes = signature.to_bytes();
412        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET].copy_from_slice(&bytes[..32]);
413        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET].copy_from_slice(&bytes[32..]);
414
415        Ok(())
416    }
417
418    /// Get the encoded date
419    pub fn encoded_date(&self) -> CompressedDate {
420        let bytes: [u8; 3] = self.data[Self::DATE_OFFSET..Self::SIGNER_ID_OFFSET]
421            .try_into()
422            .unwrap();
423        CompressedDate::from_bytes(bytes)
424    }
425
426    /// Set the encoded date
427    pub fn set_encoded_date(&mut self, date: CompressedDate) {
428        let bytes = date.to_bytes();
429        self.data[Self::DATE_OFFSET..Self::SIGNER_ID_OFFSET].copy_from_slice(&bytes);
430    }
431
432    /// Get the signer ID (big-endian)
433    pub fn signer_id(&self) -> u16 {
434        u16::from_be_bytes(
435            self.data[Self::SIGNER_ID_OFFSET..Self::TEMPLATE_ID_OFFSET]
436                .try_into()
437                .unwrap(),
438        )
439    }
440
441    /// Set the signer ID
442    pub fn set_signer_id(&mut self, id: u16) {
443        self.data[Self::SIGNER_ID_OFFSET..Self::TEMPLATE_ID_OFFSET]
444            .copy_from_slice(&id.to_be_bytes());
445    }
446
447    /// Get the template ID
448    pub fn template_id(&self) -> u8 {
449        self.data[Self::TEMPLATE_ID_OFFSET]
450    }
451
452    /// Set the template ID
453    pub fn set_template_id(&mut self, id: u8) {
454        self.data[Self::TEMPLATE_ID_OFFSET] = id;
455    }
456
457    /// Get the chain ID
458    pub fn chain_id(&self) -> u8 {
459        self.data[Self::CHAIN_ID_OFFSET]
460    }
461
462    /// Set the chain ID
463    pub fn set_chain_id(&mut self, id: u8) {
464        self.data[Self::CHAIN_ID_OFFSET] = id;
465    }
466
467    /// Get the serial number source
468    pub fn serial_source(&self) -> u8 {
469        self.data[Self::SERIAL_SOURCE_OFFSET]
470    }
471
472    /// Set the serial number source
473    pub fn set_serial_source(&mut self, source: &SerialSource) {
474        self.data[Self::SERIAL_SOURCE_OFFSET] = source.to_tag();
475    }
476
477    /// Get the raw bytes
478    pub fn as_bytes(&self) -> &[u8; Self::SIZE] {
479        &self.data
480    }
481
482    /// Get mutable access to the raw bytes
483    pub fn as_bytes_mut(&mut self) -> &mut [u8; Self::SIZE] {
484        &mut self.data
485    }
486}
487
488impl Default for CompressedCertificate {
489    fn default() -> Self {
490        Self::zeroed()
491    }
492}
493
494impl AsRef<[u8]> for CompressedCertificate {
495    fn as_ref(&self) -> &[u8] {
496        &self.data
497    }
498}
499
500impl AsMut<[u8]> for CompressedCertificate {
501    fn as_mut(&mut self) -> &mut [u8] {
502        &mut self.data
503    }
504}
505
506impl TryFrom<&[u8]> for CompressedCertificate {
507    type Error = Error;
508
509    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
510        if bytes.len() != Self::SIZE {
511            return Err(ErrorKind::InvalidSize.into());
512        }
513        let mut data = [0u8; Self::SIZE];
514        data.copy_from_slice(bytes);
515        Ok(Self { data })
516    }
517}
518
519/// Location of a dynamic element in the DER template
520#[derive(Clone, Copy, Debug, Default)]
521pub struct CertElement {
522    /// Offset from start of template
523    pub offset: u16,
524    /// Number of bytes to copy
525    pub count: u8,
526}
527
528impl CertElement {
529    /// Create a new certificate element location
530    pub const fn new(offset: u16, count: u8) -> Self {
531        Self { offset, count }
532    }
533}
534
535/// Template-based certificate definition
536///
537/// This structure defines how to reconstruct a full X.509 certificate
538/// from a compressed certificate and a DER template.
539pub struct CertificateDefinition<'a> {
540    /// DER template with static content
541    pub template: &'a [u8],
542    /// Where to insert signature
543    pub signature: CertElement,
544    /// Where to insert public key X coordinate
545    pub public_key_x: CertElement,
546    /// Where to insert public key Y coordinate
547    pub public_key_y: CertElement,
548    /// Where to insert issue date
549    pub issue_date: CertElement,
550    /// Where to insert expire date
551    pub expire_date: CertElement,
552    /// Where to insert serial number
553    pub serial_number: CertElement,
554    /// Where to insert the subject value (e.g. a per-device common name)
555    ///
556    /// The subject is not stored in the compressed certificate, but the
557    /// signature still covers it. Set `count = 0` when the subject is fully
558    /// fixed in the template; otherwise the value is produced by
559    /// [`Self::subject_source`].
560    pub subject: CertElement,
561    /// How to produce the subject value (see [`SubjectSource`])
562    pub subject_source: SubjectSource<'a>,
563    /// How to generate serial number
564    pub serial_source: SerialSource,
565    /// Slot where compressed certificate is stored
566    pub compressed_slot: Slot,
567    /// Slot where public key is stored (or generated from)
568    pub public_key_slot: Slot,
569}
570
571impl<'a> CertificateDefinition<'a> {
572    /// Extract the serial number bytes from a DER certificate
573    pub fn extract_serial<'b>(&self, der_cert: &'b [u8]) -> &'b [u8] {
574        let offset = self.serial_number.offset as usize;
575        let count = self.serial_number.count as usize;
576        &der_cert[offset..offset + count]
577    }
578
579    /// Compress a DER certificate into the 72-byte ATECC format
580    ///
581    /// Extracts signature (R,S), validity dates, and metadata from the DER
582    /// certificate at the offsets defined by this CertificateDefinition.
583    /// This is the inverse of [`reconstruct()`].
584    pub fn compress(&self, der_cert: &[u8]) -> Result<CompressedCertificate, Error> {
585        let mut cc = CompressedCertificate::zeroed();
586
587        // Extract signature from DER and convert to R,S. The signature is a
588        // DER SEQUENCE whose encoded length varies with the R/S values (P-256
589        // signatures are 70-72 bytes), so read its real length from the header
590        // rather than trusting the template's `count`.
591        if self.signature.count > 0 {
592            let offset = self.signature.offset as usize;
593            if offset >= der_cert.len() || der_cert[offset] != DER_SEQUENCE {
594                return Err(ErrorKind::BadParam.into());
595            }
596            let (content, hdr) = read_definite_len(der_cert, offset + 1)?;
597            let total = 1 + hdr + content;
598            if offset + total > der_cert.len() {
599                return Err(ErrorKind::BadParam.into());
600            }
601            let sig_bytes = &der_cert[offset..offset + total];
602            let signature =
603                p256::ecdsa::Signature::from_der(sig_bytes).map_err(|_| ErrorKind::BadParam)?;
604            let fixed = signature.to_bytes();
605            cc.set_signature(
606                fixed[..32].try_into().unwrap(),
607                fixed[32..].try_into().unwrap(),
608            );
609        }
610
611        // Extract and compress validity dates
612        if self.issue_date.count > 0 && self.expire_date.count > 0 {
613            let issue_offset = self.issue_date.offset as usize;
614            let issue_count = self.issue_date.count as usize;
615            let expire_offset = self.expire_date.offset as usize;
616            let expire_count = self.expire_date.count as usize;
617
618            if issue_offset + issue_count > der_cert.len()
619                || expire_offset + expire_count > der_cert.len()
620            {
621                return Err(ErrorKind::BadParam.into());
622            }
623
624            let issue_bytes = &der_cert[issue_offset..issue_offset + issue_count];
625            let expire_bytes = &der_cert[expire_offset..expire_offset + expire_count];
626
627            let not_before = parse_time(issue_bytes)?;
628            let not_after = parse_time(expire_bytes)?;
629            let validity = Validity {
630                not_before,
631                not_after,
632            };
633            cc.set_encoded_date(CompressedDate::from_validity(&validity)?);
634        }
635
636        // Set serial source tag
637        cc.set_serial_source(&self.serial_source);
638
639        Ok(cc)
640    }
641
642    /// Reconstruct full DER certificate from compressed cert + template
643    ///
644    /// # Arguments
645    /// * `compressed` - The compressed certificate data
646    /// * `public_key` - The subject's public key
647    /// * `serial` - Pre-generated serial number bytes
648    /// * `subject` - Subject bytes to inject at `self.subject` (e.g. a
649    ///   per-device common name). Ignored when `self.subject.count == 0`. When
650    ///   a subject element is declared but `None` is passed, the template's
651    ///   bytes are left in place — the caller is responsible for supplying the
652    ///   value that was signed.
653    /// * `output` - Buffer to write the reconstructed DER certificate
654    ///
655    /// # Returns
656    /// The number of bytes written to output, or an error
657    pub fn reconstruct(
658        &self,
659        compressed: &CompressedCertificate,
660        public_key: &PublicKey,
661        serial: &[u8],
662        subject: Option<&[u8]>,
663        output: &mut [u8],
664    ) -> Result<usize, Error> {
665        // Verify output buffer is large enough
666        if output.len() < self.template.len() {
667            return Err(ErrorKind::SmallBuffer.into());
668        }
669
670        // Copy template to output
671        let mut len = self.template.len();
672        output[..len].copy_from_slice(self.template);
673
674        // Insert caller-supplied subject (e.g. a per-device common name). The
675        // library only places the bytes; the domain layer owns how they are
676        // derived and is responsible for matching what the CA signed.
677        if self.subject.count > 0
678            && let Some(subject) = subject
679        {
680            let offset = self.subject.offset as usize;
681            let count = self.subject.count as usize;
682            if offset + count > len || count > subject.len() {
683                return Err(ErrorKind::BadParam.into());
684            }
685            output[offset..offset + count].copy_from_slice(&subject[..count]);
686        }
687
688        // Insert public key X coordinate
689        if self.public_key_x.count > 0 {
690            let offset = self.public_key_x.offset as usize;
691            let count = self.public_key_x.count as usize;
692            if offset + count > len || count > 32 {
693                return Err(ErrorKind::BadParam.into());
694            }
695            output[offset..offset + count].copy_from_slice(&public_key.as_ref()[..count]);
696        }
697
698        // Insert public key Y coordinate
699        if self.public_key_y.count > 0 {
700            let offset = self.public_key_y.offset as usize;
701            let count = self.public_key_y.count as usize;
702            if offset + count > len || count > 32 {
703                return Err(ErrorKind::BadParam.into());
704            }
705            output[offset..offset + count].copy_from_slice(&public_key.as_ref()[32..32 + count]);
706        }
707
708        // Insert serial number
709        if self.serial_number.count > 0 {
710            let offset = self.serial_number.offset as usize;
711            let count = self.serial_number.count as usize;
712            if offset + count > len || count > serial.len() {
713                return Err(ErrorKind::BadParam.into());
714            }
715            output[offset..offset + count].copy_from_slice(&serial[..count]);
716        }
717
718        // Get validity from compressed date and encode it
719        let validity = compressed.encoded_date().to_validity()?;
720
721        // Insert issue date (as ASN.1 UTCTime or GeneralizedTime)
722        if self.issue_date.count > 0 {
723            let offset = self.issue_date.offset as usize;
724            let count = self.issue_date.count as usize;
725            if offset + count > len {
726                return Err(ErrorKind::BadParam.into());
727            }
728            let date_bytes = encode_time(&validity.not_before)?;
729            if count <= date_bytes.len() {
730                output[offset..offset + count].copy_from_slice(&date_bytes[..count]);
731            }
732        }
733
734        // Insert expire date
735        if self.expire_date.count > 0 {
736            let offset = self.expire_date.offset as usize;
737            let count = self.expire_date.count as usize;
738            if offset + count > len {
739                return Err(ErrorKind::BadParam.into());
740            }
741            let date_bytes = encode_time(&validity.not_after)?;
742            if count <= date_bytes.len() {
743                output[offset..offset + count].copy_from_slice(&date_bytes[..count]);
744            }
745        }
746
747        // Insert signature (DER SEQUENCE { INTEGER r, INTEGER s }). It is the
748        // final, outermost element and lies outside the signed TBSCertificate,
749        // so its encoded length may differ from the template (P-256 signatures
750        // are 70-72 bytes depending on the high bit of R and S). Write the
751        // actual bytes and fix up the two enclosing length fields — the
752        // signatureValue BIT STRING and the outer Certificate SEQUENCE — so the
753        // certificate stays well-formed regardless of the signature's length.
754        if self.signature.count > 0 {
755            let offset = self.signature.offset as usize;
756            let template_len = self.signature.count as usize;
757            let der_sig = compressed.to_der_signature()?;
758            let sig_bytes = der_sig.as_bytes();
759            let actual = sig_bytes.len();
760            if offset < 3 || offset + actual > output.len() {
761                return Err(ErrorKind::SmallBuffer.into());
762            }
763            output[offset..offset + actual].copy_from_slice(sig_bytes);
764            if actual != template_len {
765                let delta = actual as isize - template_len as isize;
766                // signatureValue BIT STRING: its length octet sits two bytes
767                // before the SEQUENCE (BIT STRING tag, length, unused-bits).
768                adjust_definite_len(output, offset - 2, delta)?;
769                // Outer Certificate SEQUENCE: length octet(s) follow byte 0.
770                adjust_definite_len(output, 1, delta)?;
771                len = offset + actual;
772            }
773        }
774
775        Ok(len)
776    }
777}
778
779/// DER tag for a SEQUENCE (used to sanity-check the signature element).
780const DER_SEQUENCE: u8 = 0x30;
781
782/// Reads a DER definite-form length at `buf[pos]` (the length octet(s) that
783/// follow a tag). Returns `(content_length, number_of_length_octets)`.
784fn read_definite_len(buf: &[u8], pos: usize) -> Result<(usize, usize), Error> {
785    if pos >= buf.len() {
786        return Err(ErrorKind::BadParam.into());
787    }
788    let first = buf[pos];
789    if first < 0x80 {
790        return Ok((first as usize, 1)); // short form
791    }
792    let n = (first & 0x7f) as usize; // long form: number of length octets
793    if n == 0 || n > 4 || pos + n >= buf.len() {
794        return Err(ErrorKind::BadParam.into());
795    }
796    let mut v = 0usize;
797    for i in 0..n {
798        v = (v << 8) | buf[pos + 1 + i] as usize;
799    }
800    Ok((v, 1 + n))
801}
802
803/// Adjusts the definite-form length value at `buf[pos]` by `delta`, preserving
804/// the number of length octets. Errors if the change would require a different
805/// length form, which cannot happen for the +/-2-byte P-256 signature spread.
806fn adjust_definite_len(buf: &mut [u8], pos: usize, delta: isize) -> Result<(), Error> {
807    let (val, n) = read_definite_len(buf, pos)?;
808    let new = val as isize + delta;
809    if new < 0 {
810        return Err(ErrorKind::BadParam.into());
811    }
812    let new = new as usize;
813    if n == 1 {
814        if new > 0x7f {
815            return Err(ErrorKind::BadParam.into()); // would need long form
816        }
817        buf[pos] = new as u8;
818    } else {
819        let octets = n - 1;
820        if new >> (8 * octets) != 0 {
821            return Err(ErrorKind::BadParam.into()); // would not fit the form
822        }
823        for i in 0..octets {
824            buf[pos + 1 + i] = (new >> (8 * (octets - 1 - i))) as u8;
825        }
826    }
827    Ok(())
828}
829
830/// Parse an ASN.1 time string (UTCTime or GeneralizedTime) into a Time value
831fn parse_time(bytes: &[u8]) -> Result<Time, Error> {
832    // UTCTime: YYMMDDHHmmssZ (13 bytes)
833    // GeneralizedTime: YYYYMMDDHHmmssZ (15 bytes)
834    let (year, rest) = if bytes.len() == 13 {
835        let yy = (bytes[0] - b'0') as u16 * 10 + (bytes[1] - b'0') as u16;
836        let year = if yy >= 50 { 1900 + yy } else { 2000 + yy };
837        (year, &bytes[2..])
838    } else if bytes.len() == 15 {
839        let year = (bytes[0] - b'0') as u16 * 1000
840            + (bytes[1] - b'0') as u16 * 100
841            + (bytes[2] - b'0') as u16 * 10
842            + (bytes[3] - b'0') as u16;
843        (year, &bytes[4..])
844    } else {
845        return Err(ErrorKind::BadParam.into());
846    };
847
848    let month = (rest[0] - b'0') * 10 + (rest[1] - b'0');
849    let day = (rest[2] - b'0') * 10 + (rest[3] - b'0');
850    let hour = (rest[4] - b'0') * 10 + (rest[5] - b'0');
851    let min = (rest[6] - b'0') * 10 + (rest[7] - b'0');
852    let sec = (rest[8] - b'0') * 10 + (rest[9] - b'0');
853
854    let dt =
855        der::DateTime::new(year, month, day, hour, min, sec).map_err(|_| ErrorKind::BadParam)?;
856
857    if year >= 2050 {
858        Ok(Time::GeneralTime(
859            der::asn1::GeneralizedTime::from_date_time(dt),
860        ))
861    } else {
862        Ok(Time::UtcTime(
863            der::asn1::UtcTime::from_date_time(dt).map_err(|_| ErrorKind::BadParam)?,
864        ))
865    }
866}
867
868/// Encode a Time value to bytes (simplified - just the date portion)
869fn encode_time(time: &Time) -> Result<[u8; 15], Error> {
870    let dt = time.to_date_time();
871    let mut buf = [0u8; 15];
872
873    // Format as YYMMDDHHmmssZ (UTCTime) or YYYYMMDDHHmmssZ (GeneralizedTime)
874    match time {
875        Time::UtcTime(_) => {
876            // YYMMDDHHmmssZ (13 bytes)
877            let year = dt.year() % 100;
878            buf[0] = b'0' + (year / 10) as u8;
879            buf[1] = b'0' + (year % 10) as u8;
880            buf[2] = b'0' + (dt.month() / 10);
881            buf[3] = b'0' + (dt.month() % 10);
882            buf[4] = b'0' + (dt.day() / 10);
883            buf[5] = b'0' + (dt.day() % 10);
884            buf[6] = b'0' + (dt.hour() / 10);
885            buf[7] = b'0' + (dt.hour() % 10);
886            buf[8] = b'0' + (dt.minutes() / 10);
887            buf[9] = b'0' + (dt.minutes() % 10);
888            buf[10] = b'0' + (dt.seconds() / 10);
889            buf[11] = b'0' + (dt.seconds() % 10);
890            buf[12] = b'Z';
891        }
892        Time::GeneralTime(_) => {
893            // YYYYMMDDHHmmssZ (15 bytes)
894            let year = dt.year();
895            buf[0] = b'0' + (year / 1000) as u8;
896            buf[1] = b'0' + ((year / 100) % 10) as u8;
897            buf[2] = b'0' + ((year / 10) % 10) as u8;
898            buf[3] = b'0' + (year % 10) as u8;
899            buf[4] = b'0' + (dt.month() / 10);
900            buf[5] = b'0' + (dt.month() % 10);
901            buf[6] = b'0' + (dt.day() / 10);
902            buf[7] = b'0' + (dt.day() % 10);
903            buf[8] = b'0' + (dt.hour() / 10);
904            buf[9] = b'0' + (dt.hour() % 10);
905            buf[10] = b'0' + (dt.minutes() / 10);
906            buf[11] = b'0' + (dt.minutes() % 10);
907            buf[12] = b'0' + (dt.seconds() / 10);
908            buf[13] = b'0' + (dt.seconds() % 10);
909            buf[14] = b'Z';
910        }
911    }
912
913    Ok(buf)
914}
915
916#[cfg(test)]
917mod tests {
918    use super::*;
919    use der::asn1::UtcTime;
920
921    #[test]
922    fn test_compressed_date_roundtrip() {
923        // Create a validity period: 2026-06-15 10:00 to 2031-06-15 10:00
924        let not_before = Time::UtcTime(
925            UtcTime::from_date_time(DateTime::new(2026, 6, 15, 10, 0, 0).unwrap()).unwrap(),
926        );
927        let not_after = Time::UtcTime(
928            UtcTime::from_date_time(DateTime::new(2031, 6, 15, 10, 0, 0).unwrap()).unwrap(),
929        );
930        let validity = Validity {
931            not_before,
932            not_after,
933        };
934
935        // Convert to compressed date
936        let compressed = CompressedDate::from_validity(&validity).unwrap();
937
938        // Verify fields
939        assert_eq!(compressed.year(), 1); // 2026 - BASE_YEAR (2025)
940        assert_eq!(compressed.month(), 6);
941        assert_eq!(compressed.day(), 15);
942        assert_eq!(compressed.hour(), 10);
943        assert_eq!(compressed.expire_years(), 5);
944
945        // Convert back to validity
946        let decoded = compressed.to_validity().unwrap();
947        let decoded_issue = decoded.not_before.to_date_time();
948        let decoded_expire = decoded.not_after.to_date_time();
949
950        assert_eq!(decoded_issue.year(), 2026);
951        assert_eq!(decoded_issue.month(), 6);
952        assert_eq!(decoded_issue.day(), 15);
953        assert_eq!(decoded_issue.hour(), 10);
954        assert_eq!(decoded_expire.year(), 2031);
955    }
956
957    #[test]
958    fn test_compressed_date_bytes() {
959        let date = CompressedDate::new()
960            .with_year(23)
961            .with_month(6)
962            .with_day(15)
963            .with_hour(10)
964            .with_expire_years(5);
965
966        let bytes = date.to_bytes();
967        let decoded = CompressedDate::from_bytes(bytes);
968
969        assert_eq!(date, decoded);
970    }
971
972    #[test]
973    fn test_compressed_certificate_signature() {
974        let mut cert = CompressedCertificate::zeroed();
975
976        let r = [1u8; 32];
977        let s = [2u8; 32];
978        cert.set_signature(&r, &s);
979
980        assert_eq!(cert.signature_r(), &r);
981        assert_eq!(cert.signature_s(), &s);
982    }
983
984    #[test]
985    fn test_compressed_certificate_fields() {
986        let mut cert = CompressedCertificate::zeroed();
987
988        cert.set_signer_id(0x1234);
989        assert_eq!(cert.signer_id(), 0x1234);
990
991        cert.set_template_id(5);
992        assert_eq!(cert.template_id(), 5);
993
994        cert.set_chain_id(3);
995        assert_eq!(cert.chain_id(), 3);
996
997        cert.set_serial_source(&SerialSource::DeviceSerial);
998        assert_eq!(cert.serial_source(), SerialSource::DeviceSerial.to_tag());
999    }
1000
1001    #[test]
1002    fn test_serial_source_device_serial() {
1003        let serial_bytes = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x12];
1004        let device_serial = Serial::new_for_test(&serial_bytes);
1005
1006        let mut output = [0u8; 16];
1007        let result = SerialSource::DeviceSerial
1008            .generate(&device_serial, 0, &mut output)
1009            .unwrap();
1010
1011        assert_eq!(result.len(), 10);
1012        assert_eq!(result[0], 0x40);
1013        assert_eq!(&result[1..], &serial_bytes);
1014    }
1015
1016    #[test]
1017    fn test_serial_source_signer_id() {
1018        let serial_bytes = [0u8; 9];
1019        let device_serial = Serial::new_for_test(&serial_bytes);
1020
1021        let mut output = [0u8; 16];
1022        let result = SerialSource::SignerId
1023            .generate(&device_serial, 0xABCD, &mut output)
1024            .unwrap();
1025
1026        assert_eq!(result.len(), 3);
1027        assert_eq!(result[0], 0x40);
1028        assert_eq!(result[1], 0xAB);
1029        assert_eq!(result[2], 0xCD);
1030    }
1031
1032    #[test]
1033    fn test_serial_source_stored_returns_error() {
1034        use crate::memory::SlotAddress;
1035
1036        let serial_bytes = [0u8; 9];
1037        let device_serial = Serial::new_for_test(&serial_bytes);
1038
1039        let mut output = [0u8; 16];
1040        // Stored cannot be generated — it must be read from device
1041        assert!(
1042            SerialSource::Stored(SlotAddress::Data08(0))
1043                .generate(&device_serial, 0, &mut output)
1044                .is_err()
1045        );
1046    }
1047
1048    #[test]
1049    fn test_reconstruct_injects_subject() {
1050        // 40-byte template with a 4-byte CN placeholder at offset 10.
1051        let mut template = [0xAAu8; 40];
1052        template[10..14].copy_from_slice(b"____");
1053
1054        let def = CertificateDefinition {
1055            template: &template,
1056            signature: CertElement::new(0, 0),
1057            public_key_x: CertElement::new(0, 0),
1058            public_key_y: CertElement::new(0, 0),
1059            issue_date: CertElement::new(0, 0),
1060            expire_date: CertElement::new(0, 0),
1061            serial_number: CertElement::new(0, 0),
1062            subject: CertElement::new(10, 4),
1063            subject_source: SubjectSource::Template,
1064            serial_source: SerialSource::DeviceSerial,
1065            compressed_slot: crate::memory::Slot::Certificate0c,
1066            public_key_slot: crate::memory::Slot::PrivateKey00,
1067        };
1068
1069        // reconstruct() reads the validity unconditionally, so set a valid date.
1070        let mut cc = CompressedCertificate::zeroed();
1071        cc.set_encoded_date(
1072            CompressedDate::new()
1073                .with_year(26)
1074                .with_month(6)
1075                .with_day(2)
1076                .with_hour(5)
1077                .with_expire_years(30),
1078        );
1079        let pk = crate::command::PublicKey::default();
1080
1081        // Caller-supplied subject is injected; template preserved elsewhere.
1082        let mut out = [0u8; 40];
1083        let n = def
1084            .reconstruct(&cc, &pk, &[], Some(b"WXYZ"), &mut out)
1085            .unwrap();
1086        assert_eq!(n, 40);
1087        assert_eq!(&out[10..14], b"WXYZ");
1088        assert_eq!(&out[..10], &template[..10]);
1089        assert_eq!(&out[14..], &template[14..]);
1090
1091        // None leaves the template's placeholder untouched.
1092        let mut out_none = [0u8; 40];
1093        def.reconstruct(&cc, &pk, &[], None, &mut out_none).unwrap();
1094        assert_eq!(&out_none[10..14], b"____");
1095
1096        // A subject shorter than the declared element is rejected.
1097        let mut out_short = [0u8; 40];
1098        assert!(
1099            def.reconstruct(&cc, &pk, &[], Some(b"XY"), &mut out_short)
1100                .is_err()
1101        );
1102    }
1103
1104    #[test]
1105    fn test_reconstruct_variable_signature_length() {
1106        // Minimal cert-like container with a 2-byte outer SEQUENCE length (as
1107        // real X.509 certs use): SEQUENCE { [0xAA; 200] prefix, BIT STRING {
1108        // 0x00 unused-bits, <signature SEQUENCE> } }. The signature is the
1109        // final element, exactly as in a real certificate.
1110        const PREFIX: usize = 200;
1111        const SIG_OFFSET: usize = 4 + PREFIX + 3; // outer hdr + prefix + BIT STRING hdr
1112
1113        fn build_template(sig: &[u8], buf: &mut [u8]) -> usize {
1114            let body = PREFIX + 3 + sig.len();
1115            buf[0] = 0x30;
1116            buf[1] = 0x82;
1117            buf[2] = (body >> 8) as u8;
1118            buf[3] = (body & 0xff) as u8;
1119            for b in buf[4..4 + PREFIX].iter_mut() {
1120                *b = 0xAA;
1121            }
1122            buf[4 + PREFIX] = 0x03; // BIT STRING
1123            buf[4 + PREFIX + 1] = (1 + sig.len()) as u8;
1124            buf[4 + PREFIX + 2] = 0x00; // unused bits
1125            buf[SIG_OFFSET..SIG_OFFSET + sig.len()].copy_from_slice(sig);
1126            4 + body
1127        }
1128
1129        // A CompressedCertificate whose signature DER-encodes to `len` bytes
1130        // (70/71/72), driven by the high bit of R and S.
1131        fn cc_with_sig_len(len: usize) -> CompressedCertificate {
1132            let mut r = [0x11u8; 32];
1133            let mut s = [0x22u8; 32];
1134            if len >= 71 {
1135                r[0] = 0x80; // high bit set => INTEGER gains a 0x00 sign octet
1136            }
1137            if len >= 72 {
1138                s[0] = 0x80;
1139            }
1140            let mut cc = CompressedCertificate::zeroed();
1141            cc.set_signature(&r, &s);
1142            cc.set_encoded_date(
1143                CompressedDate::new()
1144                    .with_year(26)
1145                    .with_month(6)
1146                    .with_day(8)
1147                    .with_hour(13)
1148                    .with_expire_years(30),
1149            );
1150            cc
1151        }
1152
1153        let pk = crate::command::PublicKey::default();
1154
1155        // Template carries a 70-byte signature (both R and S high bit clear).
1156        let template_sig = cc_with_sig_len(70).to_der_signature().unwrap();
1157        let template_sig = template_sig.as_bytes();
1158        assert_eq!(template_sig.len(), 70);
1159        let mut template_buf = [0u8; 320];
1160        let tlen = build_template(template_sig, &mut template_buf);
1161        let template = &template_buf[..tlen];
1162        assert_eq!(template[SIG_OFFSET], DER_SEQUENCE);
1163
1164        let def = CertificateDefinition {
1165            template,
1166            signature: CertElement::new(SIG_OFFSET as u16, 70),
1167            public_key_x: CertElement::new(0, 0),
1168            public_key_y: CertElement::new(0, 0),
1169            issue_date: CertElement::new(0, 0),
1170            expire_date: CertElement::new(0, 0),
1171            serial_number: CertElement::new(0, 0),
1172            subject: CertElement::new(0, 0),
1173            subject_source: SubjectSource::Template,
1174            serial_source: SerialSource::DeviceSerial,
1175            compressed_slot: crate::memory::Slot::Certificate0c,
1176            public_key_slot: crate::memory::Slot::PrivateKey00,
1177        };
1178
1179        // The template's signature is 70 bytes; reconstruct 70/71/72-byte
1180        // signatures and confirm the enclosing length fields and the total
1181        // length track the actual signature, and that the result round-trips.
1182        for sig_len in [70usize, 71, 72] {
1183            let cc = cc_with_sig_len(sig_len);
1184            let mut out = [0u8; 320];
1185            let n = def.reconstruct(&cc, &pk, &[], None, &mut out).unwrap();
1186
1187            let delta = sig_len as isize - 70;
1188            assert_eq!(
1189                n as isize,
1190                tlen as isize + delta,
1191                "total length ({sig_len})"
1192            );
1193
1194            let outer = ((out[2] as usize) << 8) | out[3] as usize;
1195            assert_eq!(outer, n - 4, "outer SEQUENCE length ({sig_len})");
1196            assert_eq!(
1197                out[SIG_OFFSET - 2] as usize,
1198                1 + sig_len,
1199                "BIT STRING length ({sig_len})"
1200            );
1201            assert_eq!(out[SIG_OFFSET], DER_SEQUENCE);
1202            assert_eq!(
1203                2 + out[SIG_OFFSET + 1] as usize,
1204                sig_len,
1205                "signature SEQUENCE length ({sig_len})"
1206            );
1207
1208            // Compressing the reconstructed cert recovers the same R and S.
1209            let back = def.compress(&out[..n]).unwrap();
1210            assert_eq!(
1211                back.signature_r(),
1212                cc.signature_r(),
1213                "round-trip R ({sig_len})"
1214            );
1215            assert_eq!(
1216                back.signature_s(),
1217                cc.signature_s(),
1218                "round-trip S ({sig_len})"
1219            );
1220        }
1221    }
1222}