at-cryptoauth 0.6.0

Driver for ATECC608 Crypto Authentication secure elements
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
//! Compressed certificate format for ATECC608 devices
//!
//! This module implements the ATECC-specific 72-byte compressed certificate format
//! as defined in Microchip's Application Note (Atmel-8974).
//!
//! The compressed format stores only the dynamic parts of a certificate:
//! - Signature (64 bytes: R + S)
//! - Encoded date (3 bytes)
//! - Signer ID (2 bytes)
//! - Template ID (1 byte)
//! - Chain ID (1 byte)
//! - Serial number source (1 byte)

use der::{DateTime, asn1::GeneralizedTime};
use p256::ecdsa::DerSignature;

use crate::{
    PublicKey,
    command::Serial,
    error::{Error, ErrorKind},
    memory::{Slot, SlotAddress},
};

use super::time::{Time, Validity};

/// 3-byte date encoding per Microchip format
///
/// Layout (24 bits total, little-endian):
/// - Bits 0-4: Year (years since `BASE_YEAR`, valid 0-31 = 2025-2056)
/// - Bits 5-8: Month (1-12)
/// - Bits 9-13: Day (1-31)
/// - Bits 14-18: Hour (0-23)
/// - Bits 19-23: Expire years (0-31 years validity)
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CompressedDate(u32);

impl CompressedDate {
    // Bit field masks and offsets
    const YEAR_MASK: u32 = 0x1F; // 5 bits
    const YEAR_OFFSET: u32 = 0;
    const MONTH_MASK: u32 = 0x0F; // 4 bits
    const MONTH_OFFSET: u32 = 5;
    const DAY_MASK: u32 = 0x1F; // 5 bits
    const DAY_OFFSET: u32 = 9;
    const HOUR_MASK: u32 = 0x1F; // 5 bits
    const HOUR_OFFSET: u32 = 14;
    const EXPIRE_MASK: u32 = 0x1F; // 5 bits
    const EXPIRE_OFFSET: u32 = 19;

    /// Create a new CompressedDate with all fields set to 0
    pub const fn new() -> Self {
        Self(0)
    }

    /// Get the year offset from [`Self::BASE_YEAR`] (0-31)
    pub const fn year(&self) -> u8 {
        ((self.0 >> Self::YEAR_OFFSET) & Self::YEAR_MASK) as u8
    }

    /// Set the year offset and return self (builder pattern)
    pub const fn with_year(self, year: u8) -> Self {
        let cleared = self.0 & !(Self::YEAR_MASK << Self::YEAR_OFFSET);
        Self(cleared | (((year as u32) & Self::YEAR_MASK) << Self::YEAR_OFFSET))
    }

    /// Get the month (1-12)
    pub const fn month(&self) -> u8 {
        ((self.0 >> Self::MONTH_OFFSET) & Self::MONTH_MASK) as u8
    }

    /// Set the month and return self (builder pattern)
    pub const fn with_month(self, month: u8) -> Self {
        let cleared = self.0 & !(Self::MONTH_MASK << Self::MONTH_OFFSET);
        Self(cleared | (((month as u32) & Self::MONTH_MASK) << Self::MONTH_OFFSET))
    }

    /// Get the day of month (1-31)
    pub const fn day(&self) -> u8 {
        ((self.0 >> Self::DAY_OFFSET) & Self::DAY_MASK) as u8
    }

    /// Set the day and return self (builder pattern)
    pub const fn with_day(self, day: u8) -> Self {
        let cleared = self.0 & !(Self::DAY_MASK << Self::DAY_OFFSET);
        Self(cleared | (((day as u32) & Self::DAY_MASK) << Self::DAY_OFFSET))
    }

    /// Get the hour (0-23)
    pub const fn hour(&self) -> u8 {
        ((self.0 >> Self::HOUR_OFFSET) & Self::HOUR_MASK) as u8
    }

    /// Set the hour and return self (builder pattern)
    pub const fn with_hour(self, hour: u8) -> Self {
        let cleared = self.0 & !(Self::HOUR_MASK << Self::HOUR_OFFSET);
        Self(cleared | (((hour as u32) & Self::HOUR_MASK) << Self::HOUR_OFFSET))
    }

    /// Get the certificate validity in years (0-31)
    pub const fn expire_years(&self) -> u8 {
        ((self.0 >> Self::EXPIRE_OFFSET) & Self::EXPIRE_MASK) as u8
    }

    /// Set the expire years and return self (builder pattern)
    pub const fn with_expire_years(self, years: u8) -> Self {
        let cleared = self.0 & !(Self::EXPIRE_MASK << Self::EXPIRE_OFFSET);
        Self(cleared | (((years as u32) & Self::EXPIRE_MASK) << Self::EXPIRE_OFFSET))
    }

    /// Set month with validation (1-12)
    pub fn with_month_checked(self, month: u8) -> Result<Self, Error> {
        if !(1..=12).contains(&month) {
            return Err(ErrorKind::BadParam.into());
        }
        Ok(self.with_month(month))
    }

    /// Set day with validation (1-31)
    pub fn with_day_checked(self, day: u8) -> Result<Self, Error> {
        if !(1..=31).contains(&day) {
            return Err(ErrorKind::BadParam.into());
        }
        Ok(self.with_day(day))
    }

    /// Set hour with validation (0-23)
    pub fn with_hour_checked(self, hour: u8) -> Result<Self, Error> {
        if hour > 23 {
            return Err(ErrorKind::BadParam.into());
        }
        Ok(self.with_hour(hour))
    }
}

impl CompressedDate {
    /// Base year for compressed date encoding.
    ///
    /// The 5-bit year field encodes an offset 0-31, giving issue years
    /// `BASE_YEAR..=BASE_YEAR + 31`. The base is *not* stored in the 72-byte
    /// compressed cert — it is implicit in this constant on both the issuer and
    /// the device, so a cert compressed under one base would reconstruct to a
    /// different date (and thus a different, unverifiable TBS) under another.
    /// It can only be changed before any device holds a compressed cert.
    pub const BASE_YEAR: u16 = 2025;

    /// Maximum year offset (5 bits)
    pub const MAX_YEAR_OFFSET: u8 = 31;

    /// Maximum expire years (5 bits)
    pub const MAX_EXPIRE_YEARS: u8 = 31;

    /// Convert from X.509 Validity to compressed date format
    pub fn from_validity(validity: &Validity) -> Result<Self, Error> {
        let issue_date = validity.not_before.to_date_time();
        let expire_date = validity.not_after.to_date_time();

        // Validate notBefore < notAfter
        if issue_date >= expire_date {
            return Err(ErrorKind::BadParam.into());
        }

        // Calculate year offset from BASE_YEAR
        let year_offset = issue_date
            .year()
            .checked_sub(Self::BASE_YEAR)
            .ok_or(ErrorKind::BadParam)?;

        if year_offset > Self::MAX_YEAR_OFFSET as u16 {
            return Err(ErrorKind::BadParam.into());
        }

        // Calculate validity period in years
        let expire_years = expire_date
            .year()
            .checked_sub(issue_date.year())
            .ok_or(ErrorKind::BadParam)?;

        if expire_years > Self::MAX_EXPIRE_YEARS as u16 {
            return Err(ErrorKind::BadParam.into());
        }

        Ok(Self::new()
            .with_year(year_offset as u8)
            .with_month(issue_date.month())
            .with_day(issue_date.day())
            .with_hour(issue_date.hour())
            .with_expire_years(expire_years as u8))
    }

    /// Convert compressed date to X.509 Validity
    pub fn to_validity(&self) -> Result<Validity, Error> {
        let issue_year = Self::BASE_YEAR + self.year() as u16;
        let expire_year = issue_year + self.expire_years() as u16;

        // Create issue date (second and nanosecond are 0)
        let issue_datetime = DateTime::new(issue_year, self.month(), self.day(), self.hour(), 0, 0)
            .map_err(|_| ErrorKind::BadParam)?;

        // Create expire date (same month/day/hour, different year)
        let expire_datetime =
            DateTime::new(expire_year, self.month(), self.day(), self.hour(), 0, 0)
                .map_err(|_| ErrorKind::BadParam)?;

        // Convert to Time (use GeneralizedTime for years >= 2050, UTCTime otherwise)
        let not_before = if issue_year >= 2050 {
            Time::GeneralTime(GeneralizedTime::from_date_time(issue_datetime))
        } else {
            Time::UtcTime(
                der::asn1::UtcTime::from_date_time(issue_datetime)
                    .map_err(|_| ErrorKind::BadParam)?,
            )
        };

        let not_after = if expire_year >= 2050 {
            Time::GeneralTime(GeneralizedTime::from_date_time(expire_datetime))
        } else {
            Time::UtcTime(
                der::asn1::UtcTime::from_date_time(expire_datetime)
                    .map_err(|_| ErrorKind::BadParam)?,
            )
        };

        Ok(Validity {
            not_before,
            not_after,
        })
    }

    /// Convert to 3-byte array for storage
    pub fn to_bytes(&self) -> [u8; 3] {
        let raw = self.0.to_le_bytes();
        [raw[0], raw[1], raw[2]]
    }

    /// Create from 3-byte array
    pub fn from_bytes(bytes: [u8; 3]) -> Self {
        let raw = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]);
        Self(raw)
    }
}

/// Source of certificate serial number
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SerialSource {
    /// Serial is stored in a Data08 block on the device
    Stored(SlotAddress),
    /// Serial is 0x40 | device_sn[0..9] (device certificates only)
    DeviceSerial,
    /// Serial is 0x40 | signer_id[0..2] (signer certificates only)
    SignerId,
    /// Serial is SHA256(subject public key + encoded dates) with upper 2 bits = 01
    PubKeyHash,
    /// Serial is SHA256(device SN + encoded dates) with upper 2 bits = 01
    DeviceSerialHash,
}

impl SerialSource {
    /// Tag byte stored in CompressedCertificate byte 71
    pub fn to_tag(&self) -> u8 {
        match self {
            SerialSource::Stored(_) => 0x00,
            SerialSource::DeviceSerial => 0x01,
            SerialSource::SignerId => 0x02,
            SerialSource::PubKeyHash => 0x03,
            SerialSource::DeviceSerialHash => 0x04,
        }
    }

    /// Generate serial number into provided buffer.
    ///
    /// Returns the slice of the buffer containing the serial number.
    /// `Stored` variants cannot be generated — they are read from the
    /// device by `Memory::read_certificate` transparently.
    pub fn generate<'a>(
        &self,
        device_serial: &Serial,
        signer_id: u16,
        output: &'a mut [u8; 16],
    ) -> Result<&'a [u8], Error> {
        match self {
            SerialSource::Stored(_) => {
                // Handled by Memory::read_certificate, not here
                Err(ErrorKind::BadParam.into())
            }
            SerialSource::DeviceSerial => {
                // 0x40 | device_sn[0..9] = 10 bytes total
                output[0] = 0x40;
                output[1..10].copy_from_slice(device_serial.as_ref());
                Ok(&output[..10])
            }
            SerialSource::SignerId => {
                // 0x40 | signer_id[0..2] = 3 bytes total
                output[0] = 0x40;
                output[1..3].copy_from_slice(&signer_id.to_be_bytes());
                Ok(&output[..3])
            }
            SerialSource::PubKeyHash | SerialSource::DeviceSerialHash => {
                Err(ErrorKind::Unimplemented.into())
            }
        }
    }
}

/// Source of the certificate subject value (e.g. a per-device common name).
///
/// Mirrors [`SerialSource`]: the subject is not stored in the compressed
/// certificate, so one shared template can serve many devices and the
/// per-device value is resolved at reconstruction time. The library stays
/// agnostic to any device-identity convention — derivations live in the caller
/// via [`SubjectSource::FromSerial`].
#[derive(Clone, Copy, Debug)]
pub enum SubjectSource<'a> {
    /// Subject is fully fixed in the template; nothing is injected.
    Template,
    /// Inject these exact bytes at the subject element.
    Provided(&'a [u8]),
    /// Derive the subject from the device serial at reconstruction time.
    ///
    /// The function writes the value into the buffer and returns its length,
    /// or `None` on failure. Lets the caller keep its own identity convention
    /// (UUID format, etc.) without this library encoding it.
    FromSerial(fn(&Serial, &mut [u8]) -> Option<usize>),
}

/// 72-byte compressed certificate stored on device
///
/// Layout:
/// - Bytes 0-31: Signature R component
/// - Bytes 32-63: Signature S component
/// - Bytes 64-66: Compressed date (3 bytes)
/// - Bytes 67-68: Signer ID (2 bytes, big-endian)
/// - Byte 69: Template ID
/// - Byte 70: Chain ID
/// - Byte 71: Serial number source
#[derive(Clone, Debug)]
pub struct CompressedCertificate {
    data: [u8; Self::SIZE],
}

impl CompressedCertificate {
    /// Total size of compressed certificate in bytes
    pub const SIZE: usize = 72;

    /// Offset of signature R component
    const SIG_R_OFFSET: usize = 0;
    /// Offset of signature S component
    const SIG_S_OFFSET: usize = 32;
    /// Offset of compressed date
    const DATE_OFFSET: usize = 64;
    /// Offset of signer ID
    const SIGNER_ID_OFFSET: usize = 67;
    /// Offset of template ID
    const TEMPLATE_ID_OFFSET: usize = 69;
    /// Offset of chain ID
    const CHAIN_ID_OFFSET: usize = 70;
    /// Offset of serial source
    const SERIAL_SOURCE_OFFSET: usize = 71;

    /// Create a new compressed certificate from raw data
    pub fn new(data: [u8; Self::SIZE]) -> Self {
        Self { data }
    }

    /// Create a zeroed compressed certificate
    pub fn zeroed() -> Self {
        Self {
            data: [0u8; Self::SIZE],
        }
    }

    /// Get the signature R component (32 bytes)
    pub fn signature_r(&self) -> &[u8; 32] {
        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET]
            .try_into()
            .unwrap()
    }

    /// Get the signature S component (32 bytes)
    pub fn signature_s(&self) -> &[u8; 32] {
        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET]
            .try_into()
            .unwrap()
    }

    /// Set the signature from R and S components
    pub fn set_signature(&mut self, r: &[u8; 32], s: &[u8; 32]) {
        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET].copy_from_slice(r);
        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET].copy_from_slice(s);
    }

    /// Convert the stored signature to a DER-encoded signature
    pub fn to_der_signature(&self) -> Result<DerSignature, Error> {
        // Combine R and S into a fixed-size signature
        let mut sig_bytes = [0u8; 64];
        sig_bytes[..32].copy_from_slice(self.signature_r());
        sig_bytes[32..].copy_from_slice(self.signature_s());

        // Convert to p256 Signature first, then to DER
        let signature =
            p256::ecdsa::Signature::from_slice(&sig_bytes).map_err(|_| ErrorKind::BadParam)?;

        Ok(signature.to_der())
    }

    /// Set the signature from a DER-encoded signature
    pub fn set_signature_from_der(&mut self, sig: &DerSignature) -> Result<(), Error> {
        // Convert DER to fixed-size format
        let signature =
            p256::ecdsa::Signature::from_der(sig.as_bytes()).map_err(|_| ErrorKind::BadParam)?;

        let bytes = signature.to_bytes();
        self.data[Self::SIG_R_OFFSET..Self::SIG_S_OFFSET].copy_from_slice(&bytes[..32]);
        self.data[Self::SIG_S_OFFSET..Self::DATE_OFFSET].copy_from_slice(&bytes[32..]);

        Ok(())
    }

    /// Get the encoded date
    pub fn encoded_date(&self) -> CompressedDate {
        let bytes: [u8; 3] = self.data[Self::DATE_OFFSET..Self::SIGNER_ID_OFFSET]
            .try_into()
            .unwrap();
        CompressedDate::from_bytes(bytes)
    }

    /// Set the encoded date
    pub fn set_encoded_date(&mut self, date: CompressedDate) {
        let bytes = date.to_bytes();
        self.data[Self::DATE_OFFSET..Self::SIGNER_ID_OFFSET].copy_from_slice(&bytes);
    }

    /// Get the signer ID (big-endian)
    pub fn signer_id(&self) -> u16 {
        u16::from_be_bytes(
            self.data[Self::SIGNER_ID_OFFSET..Self::TEMPLATE_ID_OFFSET]
                .try_into()
                .unwrap(),
        )
    }

    /// Set the signer ID
    pub fn set_signer_id(&mut self, id: u16) {
        self.data[Self::SIGNER_ID_OFFSET..Self::TEMPLATE_ID_OFFSET]
            .copy_from_slice(&id.to_be_bytes());
    }

    /// Get the template ID
    pub fn template_id(&self) -> u8 {
        self.data[Self::TEMPLATE_ID_OFFSET]
    }

    /// Set the template ID
    pub fn set_template_id(&mut self, id: u8) {
        self.data[Self::TEMPLATE_ID_OFFSET] = id;
    }

    /// Get the chain ID
    pub fn chain_id(&self) -> u8 {
        self.data[Self::CHAIN_ID_OFFSET]
    }

    /// Set the chain ID
    pub fn set_chain_id(&mut self, id: u8) {
        self.data[Self::CHAIN_ID_OFFSET] = id;
    }

    /// Get the serial number source
    pub fn serial_source(&self) -> u8 {
        self.data[Self::SERIAL_SOURCE_OFFSET]
    }

    /// Set the serial number source
    pub fn set_serial_source(&mut self, source: &SerialSource) {
        self.data[Self::SERIAL_SOURCE_OFFSET] = source.to_tag();
    }

    /// Get the raw bytes
    pub fn as_bytes(&self) -> &[u8; Self::SIZE] {
        &self.data
    }

    /// Get mutable access to the raw bytes
    pub fn as_bytes_mut(&mut self) -> &mut [u8; Self::SIZE] {
        &mut self.data
    }
}

impl Default for CompressedCertificate {
    fn default() -> Self {
        Self::zeroed()
    }
}

impl AsRef<[u8]> for CompressedCertificate {
    fn as_ref(&self) -> &[u8] {
        &self.data
    }
}

impl AsMut<[u8]> for CompressedCertificate {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}

impl TryFrom<&[u8]> for CompressedCertificate {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        if bytes.len() != Self::SIZE {
            return Err(ErrorKind::InvalidSize.into());
        }
        let mut data = [0u8; Self::SIZE];
        data.copy_from_slice(bytes);
        Ok(Self { data })
    }
}

/// Location of a dynamic element in the DER template
#[derive(Clone, Copy, Debug, Default)]
pub struct CertElement {
    /// Offset from start of template
    pub offset: u16,
    /// Number of bytes to copy
    pub count: u8,
}

impl CertElement {
    /// Create a new certificate element location
    pub const fn new(offset: u16, count: u8) -> Self {
        Self { offset, count }
    }
}

/// Template-based certificate definition
///
/// This structure defines how to reconstruct a full X.509 certificate
/// from a compressed certificate and a DER template.
pub struct CertificateDefinition<'a> {
    /// DER template with static content
    pub template: &'a [u8],
    /// Where to insert signature
    pub signature: CertElement,
    /// Where to insert public key X coordinate
    pub public_key_x: CertElement,
    /// Where to insert public key Y coordinate
    pub public_key_y: CertElement,
    /// Where to insert issue date
    pub issue_date: CertElement,
    /// Where to insert expire date
    pub expire_date: CertElement,
    /// Where to insert serial number
    pub serial_number: CertElement,
    /// Where to insert the subject value (e.g. a per-device common name)
    ///
    /// The subject is not stored in the compressed certificate, but the
    /// signature still covers it. Set `count = 0` when the subject is fully
    /// fixed in the template; otherwise the value is produced by
    /// [`Self::subject_source`].
    pub subject: CertElement,
    /// How to produce the subject value (see [`SubjectSource`])
    pub subject_source: SubjectSource<'a>,
    /// How to generate serial number
    pub serial_source: SerialSource,
    /// Slot where compressed certificate is stored
    pub compressed_slot: Slot,
    /// Slot where public key is stored (or generated from)
    pub public_key_slot: Slot,
}

impl<'a> CertificateDefinition<'a> {
    /// Extract the serial number bytes from a DER certificate
    pub fn extract_serial<'b>(&self, der_cert: &'b [u8]) -> &'b [u8] {
        let offset = self.serial_number.offset as usize;
        let count = self.serial_number.count as usize;
        &der_cert[offset..offset + count]
    }

    /// Compress a DER certificate into the 72-byte ATECC format
    ///
    /// Extracts signature (R,S), validity dates, and metadata from the DER
    /// certificate at the offsets defined by this CertificateDefinition.
    /// This is the inverse of [`reconstruct()`].
    pub fn compress(&self, der_cert: &[u8]) -> Result<CompressedCertificate, Error> {
        let mut cc = CompressedCertificate::zeroed();

        // Extract signature from DER and convert to R,S. The signature is a
        // DER SEQUENCE whose encoded length varies with the R/S values (P-256
        // signatures are 70-72 bytes), so read its real length from the header
        // rather than trusting the template's `count`.
        if self.signature.count > 0 {
            let offset = self.signature.offset as usize;
            if offset >= der_cert.len() || der_cert[offset] != DER_SEQUENCE {
                return Err(ErrorKind::BadParam.into());
            }
            let (content, hdr) = read_definite_len(der_cert, offset + 1)?;
            let total = 1 + hdr + content;
            if offset + total > der_cert.len() {
                return Err(ErrorKind::BadParam.into());
            }
            let sig_bytes = &der_cert[offset..offset + total];
            let signature =
                p256::ecdsa::Signature::from_der(sig_bytes).map_err(|_| ErrorKind::BadParam)?;
            let fixed = signature.to_bytes();
            cc.set_signature(
                fixed[..32].try_into().unwrap(),
                fixed[32..].try_into().unwrap(),
            );
        }

        // Extract and compress validity dates
        if self.issue_date.count > 0 && self.expire_date.count > 0 {
            let issue_offset = self.issue_date.offset as usize;
            let issue_count = self.issue_date.count as usize;
            let expire_offset = self.expire_date.offset as usize;
            let expire_count = self.expire_date.count as usize;

            if issue_offset + issue_count > der_cert.len()
                || expire_offset + expire_count > der_cert.len()
            {
                return Err(ErrorKind::BadParam.into());
            }

            let issue_bytes = &der_cert[issue_offset..issue_offset + issue_count];
            let expire_bytes = &der_cert[expire_offset..expire_offset + expire_count];

            let not_before = parse_time(issue_bytes)?;
            let not_after = parse_time(expire_bytes)?;
            let validity = Validity {
                not_before,
                not_after,
            };
            cc.set_encoded_date(CompressedDate::from_validity(&validity)?);
        }

        // Set serial source tag
        cc.set_serial_source(&self.serial_source);

        Ok(cc)
    }

    /// Reconstruct full DER certificate from compressed cert + template
    ///
    /// # Arguments
    /// * `compressed` - The compressed certificate data
    /// * `public_key` - The subject's public key
    /// * `serial` - Pre-generated serial number bytes
    /// * `subject` - Subject bytes to inject at `self.subject` (e.g. a
    ///   per-device common name). Ignored when `self.subject.count == 0`. When
    ///   a subject element is declared but `None` is passed, the template's
    ///   bytes are left in place — the caller is responsible for supplying the
    ///   value that was signed.
    /// * `output` - Buffer to write the reconstructed DER certificate
    ///
    /// # Returns
    /// The number of bytes written to output, or an error
    pub fn reconstruct(
        &self,
        compressed: &CompressedCertificate,
        public_key: &PublicKey,
        serial: &[u8],
        subject: Option<&[u8]>,
        output: &mut [u8],
    ) -> Result<usize, Error> {
        // Verify output buffer is large enough
        if output.len() < self.template.len() {
            return Err(ErrorKind::SmallBuffer.into());
        }

        // Copy template to output
        let mut len = self.template.len();
        output[..len].copy_from_slice(self.template);

        // Insert caller-supplied subject (e.g. a per-device common name). The
        // library only places the bytes; the domain layer owns how they are
        // derived and is responsible for matching what the CA signed.
        if self.subject.count > 0
            && let Some(subject) = subject
        {
            let offset = self.subject.offset as usize;
            let count = self.subject.count as usize;
            if offset + count > len || count > subject.len() {
                return Err(ErrorKind::BadParam.into());
            }
            output[offset..offset + count].copy_from_slice(&subject[..count]);
        }

        // Insert public key X coordinate
        if self.public_key_x.count > 0 {
            let offset = self.public_key_x.offset as usize;
            let count = self.public_key_x.count as usize;
            if offset + count > len || count > 32 {
                return Err(ErrorKind::BadParam.into());
            }
            output[offset..offset + count].copy_from_slice(&public_key.as_ref()[..count]);
        }

        // Insert public key Y coordinate
        if self.public_key_y.count > 0 {
            let offset = self.public_key_y.offset as usize;
            let count = self.public_key_y.count as usize;
            if offset + count > len || count > 32 {
                return Err(ErrorKind::BadParam.into());
            }
            output[offset..offset + count].copy_from_slice(&public_key.as_ref()[32..32 + count]);
        }

        // Insert serial number
        if self.serial_number.count > 0 {
            let offset = self.serial_number.offset as usize;
            let count = self.serial_number.count as usize;
            if offset + count > len || count > serial.len() {
                return Err(ErrorKind::BadParam.into());
            }
            output[offset..offset + count].copy_from_slice(&serial[..count]);
        }

        // Get validity from compressed date and encode it
        let validity = compressed.encoded_date().to_validity()?;

        // Insert issue date (as ASN.1 UTCTime or GeneralizedTime)
        if self.issue_date.count > 0 {
            let offset = self.issue_date.offset as usize;
            let count = self.issue_date.count as usize;
            if offset + count > len {
                return Err(ErrorKind::BadParam.into());
            }
            let date_bytes = encode_time(&validity.not_before)?;
            if count <= date_bytes.len() {
                output[offset..offset + count].copy_from_slice(&date_bytes[..count]);
            }
        }

        // Insert expire date
        if self.expire_date.count > 0 {
            let offset = self.expire_date.offset as usize;
            let count = self.expire_date.count as usize;
            if offset + count > len {
                return Err(ErrorKind::BadParam.into());
            }
            let date_bytes = encode_time(&validity.not_after)?;
            if count <= date_bytes.len() {
                output[offset..offset + count].copy_from_slice(&date_bytes[..count]);
            }
        }

        // Insert signature (DER SEQUENCE { INTEGER r, INTEGER s }). It is the
        // final, outermost element and lies outside the signed TBSCertificate,
        // so its encoded length may differ from the template (P-256 signatures
        // are 70-72 bytes depending on the high bit of R and S). Write the
        // actual bytes and fix up the two enclosing length fields — the
        // signatureValue BIT STRING and the outer Certificate SEQUENCE — so the
        // certificate stays well-formed regardless of the signature's length.
        if self.signature.count > 0 {
            let offset = self.signature.offset as usize;
            let template_len = self.signature.count as usize;
            let der_sig = compressed.to_der_signature()?;
            let sig_bytes = der_sig.as_bytes();
            let actual = sig_bytes.len();
            if offset < 3 || offset + actual > output.len() {
                return Err(ErrorKind::SmallBuffer.into());
            }
            output[offset..offset + actual].copy_from_slice(sig_bytes);
            if actual != template_len {
                let delta = actual as isize - template_len as isize;
                // signatureValue BIT STRING: its length octet sits two bytes
                // before the SEQUENCE (BIT STRING tag, length, unused-bits).
                adjust_definite_len(output, offset - 2, delta)?;
                // Outer Certificate SEQUENCE: length octet(s) follow byte 0.
                adjust_definite_len(output, 1, delta)?;
                len = offset + actual;
            }
        }

        Ok(len)
    }
}

/// DER tag for a SEQUENCE (used to sanity-check the signature element).
const DER_SEQUENCE: u8 = 0x30;

/// Reads a DER definite-form length at `buf[pos]` (the length octet(s) that
/// follow a tag). Returns `(content_length, number_of_length_octets)`.
fn read_definite_len(buf: &[u8], pos: usize) -> Result<(usize, usize), Error> {
    if pos >= buf.len() {
        return Err(ErrorKind::BadParam.into());
    }
    let first = buf[pos];
    if first < 0x80 {
        return Ok((first as usize, 1)); // short form
    }
    let n = (first & 0x7f) as usize; // long form: number of length octets
    if n == 0 || n > 4 || pos + n >= buf.len() {
        return Err(ErrorKind::BadParam.into());
    }
    let mut v = 0usize;
    for i in 0..n {
        v = (v << 8) | buf[pos + 1 + i] as usize;
    }
    Ok((v, 1 + n))
}

/// Adjusts the definite-form length value at `buf[pos]` by `delta`, preserving
/// the number of length octets. Errors if the change would require a different
/// length form, which cannot happen for the +/-2-byte P-256 signature spread.
fn adjust_definite_len(buf: &mut [u8], pos: usize, delta: isize) -> Result<(), Error> {
    let (val, n) = read_definite_len(buf, pos)?;
    let new = val as isize + delta;
    if new < 0 {
        return Err(ErrorKind::BadParam.into());
    }
    let new = new as usize;
    if n == 1 {
        if new > 0x7f {
            return Err(ErrorKind::BadParam.into()); // would need long form
        }
        buf[pos] = new as u8;
    } else {
        let octets = n - 1;
        if new >> (8 * octets) != 0 {
            return Err(ErrorKind::BadParam.into()); // would not fit the form
        }
        for i in 0..octets {
            buf[pos + 1 + i] = (new >> (8 * (octets - 1 - i))) as u8;
        }
    }
    Ok(())
}

/// Parse an ASN.1 time string (UTCTime or GeneralizedTime) into a Time value
fn parse_time(bytes: &[u8]) -> Result<Time, Error> {
    // UTCTime: YYMMDDHHmmssZ (13 bytes)
    // GeneralizedTime: YYYYMMDDHHmmssZ (15 bytes)
    let (year, rest) = if bytes.len() == 13 {
        let yy = (bytes[0] - b'0') as u16 * 10 + (bytes[1] - b'0') as u16;
        let year = if yy >= 50 { 1900 + yy } else { 2000 + yy };
        (year, &bytes[2..])
    } else if bytes.len() == 15 {
        let year = (bytes[0] - b'0') as u16 * 1000
            + (bytes[1] - b'0') as u16 * 100
            + (bytes[2] - b'0') as u16 * 10
            + (bytes[3] - b'0') as u16;
        (year, &bytes[4..])
    } else {
        return Err(ErrorKind::BadParam.into());
    };

    let month = (rest[0] - b'0') * 10 + (rest[1] - b'0');
    let day = (rest[2] - b'0') * 10 + (rest[3] - b'0');
    let hour = (rest[4] - b'0') * 10 + (rest[5] - b'0');
    let min = (rest[6] - b'0') * 10 + (rest[7] - b'0');
    let sec = (rest[8] - b'0') * 10 + (rest[9] - b'0');

    let dt =
        der::DateTime::new(year, month, day, hour, min, sec).map_err(|_| ErrorKind::BadParam)?;

    if year >= 2050 {
        Ok(Time::GeneralTime(
            der::asn1::GeneralizedTime::from_date_time(dt),
        ))
    } else {
        Ok(Time::UtcTime(
            der::asn1::UtcTime::from_date_time(dt).map_err(|_| ErrorKind::BadParam)?,
        ))
    }
}

/// Encode a Time value to bytes (simplified - just the date portion)
fn encode_time(time: &Time) -> Result<[u8; 15], Error> {
    let dt = time.to_date_time();
    let mut buf = [0u8; 15];

    // Format as YYMMDDHHmmssZ (UTCTime) or YYYYMMDDHHmmssZ (GeneralizedTime)
    match time {
        Time::UtcTime(_) => {
            // YYMMDDHHmmssZ (13 bytes)
            let year = dt.year() % 100;
            buf[0] = b'0' + (year / 10) as u8;
            buf[1] = b'0' + (year % 10) as u8;
            buf[2] = b'0' + (dt.month() / 10);
            buf[3] = b'0' + (dt.month() % 10);
            buf[4] = b'0' + (dt.day() / 10);
            buf[5] = b'0' + (dt.day() % 10);
            buf[6] = b'0' + (dt.hour() / 10);
            buf[7] = b'0' + (dt.hour() % 10);
            buf[8] = b'0' + (dt.minutes() / 10);
            buf[9] = b'0' + (dt.minutes() % 10);
            buf[10] = b'0' + (dt.seconds() / 10);
            buf[11] = b'0' + (dt.seconds() % 10);
            buf[12] = b'Z';
        }
        Time::GeneralTime(_) => {
            // YYYYMMDDHHmmssZ (15 bytes)
            let year = dt.year();
            buf[0] = b'0' + (year / 1000) as u8;
            buf[1] = b'0' + ((year / 100) % 10) as u8;
            buf[2] = b'0' + ((year / 10) % 10) as u8;
            buf[3] = b'0' + (year % 10) as u8;
            buf[4] = b'0' + (dt.month() / 10);
            buf[5] = b'0' + (dt.month() % 10);
            buf[6] = b'0' + (dt.day() / 10);
            buf[7] = b'0' + (dt.day() % 10);
            buf[8] = b'0' + (dt.hour() / 10);
            buf[9] = b'0' + (dt.hour() % 10);
            buf[10] = b'0' + (dt.minutes() / 10);
            buf[11] = b'0' + (dt.minutes() % 10);
            buf[12] = b'0' + (dt.seconds() / 10);
            buf[13] = b'0' + (dt.seconds() % 10);
            buf[14] = b'Z';
        }
    }

    Ok(buf)
}

#[cfg(test)]
mod tests {
    use super::*;
    use der::asn1::UtcTime;

    #[test]
    fn test_compressed_date_roundtrip() {
        // Create a validity period: 2026-06-15 10:00 to 2031-06-15 10:00
        let not_before = Time::UtcTime(
            UtcTime::from_date_time(DateTime::new(2026, 6, 15, 10, 0, 0).unwrap()).unwrap(),
        );
        let not_after = Time::UtcTime(
            UtcTime::from_date_time(DateTime::new(2031, 6, 15, 10, 0, 0).unwrap()).unwrap(),
        );
        let validity = Validity {
            not_before,
            not_after,
        };

        // Convert to compressed date
        let compressed = CompressedDate::from_validity(&validity).unwrap();

        // Verify fields
        assert_eq!(compressed.year(), 1); // 2026 - BASE_YEAR (2025)
        assert_eq!(compressed.month(), 6);
        assert_eq!(compressed.day(), 15);
        assert_eq!(compressed.hour(), 10);
        assert_eq!(compressed.expire_years(), 5);

        // Convert back to validity
        let decoded = compressed.to_validity().unwrap();
        let decoded_issue = decoded.not_before.to_date_time();
        let decoded_expire = decoded.not_after.to_date_time();

        assert_eq!(decoded_issue.year(), 2026);
        assert_eq!(decoded_issue.month(), 6);
        assert_eq!(decoded_issue.day(), 15);
        assert_eq!(decoded_issue.hour(), 10);
        assert_eq!(decoded_expire.year(), 2031);
    }

    #[test]
    fn test_compressed_date_bytes() {
        let date = CompressedDate::new()
            .with_year(23)
            .with_month(6)
            .with_day(15)
            .with_hour(10)
            .with_expire_years(5);

        let bytes = date.to_bytes();
        let decoded = CompressedDate::from_bytes(bytes);

        assert_eq!(date, decoded);
    }

    #[test]
    fn test_compressed_certificate_signature() {
        let mut cert = CompressedCertificate::zeroed();

        let r = [1u8; 32];
        let s = [2u8; 32];
        cert.set_signature(&r, &s);

        assert_eq!(cert.signature_r(), &r);
        assert_eq!(cert.signature_s(), &s);
    }

    #[test]
    fn test_compressed_certificate_fields() {
        let mut cert = CompressedCertificate::zeroed();

        cert.set_signer_id(0x1234);
        assert_eq!(cert.signer_id(), 0x1234);

        cert.set_template_id(5);
        assert_eq!(cert.template_id(), 5);

        cert.set_chain_id(3);
        assert_eq!(cert.chain_id(), 3);

        cert.set_serial_source(&SerialSource::DeviceSerial);
        assert_eq!(cert.serial_source(), SerialSource::DeviceSerial.to_tag());
    }

    #[test]
    fn test_serial_source_device_serial() {
        let serial_bytes = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x12];
        let device_serial = Serial::new_for_test(&serial_bytes);

        let mut output = [0u8; 16];
        let result = SerialSource::DeviceSerial
            .generate(&device_serial, 0, &mut output)
            .unwrap();

        assert_eq!(result.len(), 10);
        assert_eq!(result[0], 0x40);
        assert_eq!(&result[1..], &serial_bytes);
    }

    #[test]
    fn test_serial_source_signer_id() {
        let serial_bytes = [0u8; 9];
        let device_serial = Serial::new_for_test(&serial_bytes);

        let mut output = [0u8; 16];
        let result = SerialSource::SignerId
            .generate(&device_serial, 0xABCD, &mut output)
            .unwrap();

        assert_eq!(result.len(), 3);
        assert_eq!(result[0], 0x40);
        assert_eq!(result[1], 0xAB);
        assert_eq!(result[2], 0xCD);
    }

    #[test]
    fn test_serial_source_stored_returns_error() {
        use crate::memory::SlotAddress;

        let serial_bytes = [0u8; 9];
        let device_serial = Serial::new_for_test(&serial_bytes);

        let mut output = [0u8; 16];
        // Stored cannot be generated — it must be read from device
        assert!(
            SerialSource::Stored(SlotAddress::Data08(0))
                .generate(&device_serial, 0, &mut output)
                .is_err()
        );
    }

    #[test]
    fn test_reconstruct_injects_subject() {
        // 40-byte template with a 4-byte CN placeholder at offset 10.
        let mut template = [0xAAu8; 40];
        template[10..14].copy_from_slice(b"____");

        let def = CertificateDefinition {
            template: &template,
            signature: CertElement::new(0, 0),
            public_key_x: CertElement::new(0, 0),
            public_key_y: CertElement::new(0, 0),
            issue_date: CertElement::new(0, 0),
            expire_date: CertElement::new(0, 0),
            serial_number: CertElement::new(0, 0),
            subject: CertElement::new(10, 4),
            subject_source: SubjectSource::Template,
            serial_source: SerialSource::DeviceSerial,
            compressed_slot: crate::memory::Slot::Certificate0c,
            public_key_slot: crate::memory::Slot::PrivateKey00,
        };

        // reconstruct() reads the validity unconditionally, so set a valid date.
        let mut cc = CompressedCertificate::zeroed();
        cc.set_encoded_date(
            CompressedDate::new()
                .with_year(26)
                .with_month(6)
                .with_day(2)
                .with_hour(5)
                .with_expire_years(30),
        );
        let pk = crate::command::PublicKey::default();

        // Caller-supplied subject is injected; template preserved elsewhere.
        let mut out = [0u8; 40];
        let n = def
            .reconstruct(&cc, &pk, &[], Some(b"WXYZ"), &mut out)
            .unwrap();
        assert_eq!(n, 40);
        assert_eq!(&out[10..14], b"WXYZ");
        assert_eq!(&out[..10], &template[..10]);
        assert_eq!(&out[14..], &template[14..]);

        // None leaves the template's placeholder untouched.
        let mut out_none = [0u8; 40];
        def.reconstruct(&cc, &pk, &[], None, &mut out_none).unwrap();
        assert_eq!(&out_none[10..14], b"____");

        // A subject shorter than the declared element is rejected.
        let mut out_short = [0u8; 40];
        assert!(
            def.reconstruct(&cc, &pk, &[], Some(b"XY"), &mut out_short)
                .is_err()
        );
    }

    #[test]
    fn test_reconstruct_variable_signature_length() {
        // Minimal cert-like container with a 2-byte outer SEQUENCE length (as
        // real X.509 certs use): SEQUENCE { [0xAA; 200] prefix, BIT STRING {
        // 0x00 unused-bits, <signature SEQUENCE> } }. The signature is the
        // final element, exactly as in a real certificate.
        const PREFIX: usize = 200;
        const SIG_OFFSET: usize = 4 + PREFIX + 3; // outer hdr + prefix + BIT STRING hdr

        fn build_template(sig: &[u8], buf: &mut [u8]) -> usize {
            let body = PREFIX + 3 + sig.len();
            buf[0] = 0x30;
            buf[1] = 0x82;
            buf[2] = (body >> 8) as u8;
            buf[3] = (body & 0xff) as u8;
            for b in buf[4..4 + PREFIX].iter_mut() {
                *b = 0xAA;
            }
            buf[4 + PREFIX] = 0x03; // BIT STRING
            buf[4 + PREFIX + 1] = (1 + sig.len()) as u8;
            buf[4 + PREFIX + 2] = 0x00; // unused bits
            buf[SIG_OFFSET..SIG_OFFSET + sig.len()].copy_from_slice(sig);
            4 + body
        }

        // A CompressedCertificate whose signature DER-encodes to `len` bytes
        // (70/71/72), driven by the high bit of R and S.
        fn cc_with_sig_len(len: usize) -> CompressedCertificate {
            let mut r = [0x11u8; 32];
            let mut s = [0x22u8; 32];
            if len >= 71 {
                r[0] = 0x80; // high bit set => INTEGER gains a 0x00 sign octet
            }
            if len >= 72 {
                s[0] = 0x80;
            }
            let mut cc = CompressedCertificate::zeroed();
            cc.set_signature(&r, &s);
            cc.set_encoded_date(
                CompressedDate::new()
                    .with_year(26)
                    .with_month(6)
                    .with_day(8)
                    .with_hour(13)
                    .with_expire_years(30),
            );
            cc
        }

        let pk = crate::command::PublicKey::default();

        // Template carries a 70-byte signature (both R and S high bit clear).
        let template_sig = cc_with_sig_len(70).to_der_signature().unwrap();
        let template_sig = template_sig.as_bytes();
        assert_eq!(template_sig.len(), 70);
        let mut template_buf = [0u8; 320];
        let tlen = build_template(template_sig, &mut template_buf);
        let template = &template_buf[..tlen];
        assert_eq!(template[SIG_OFFSET], DER_SEQUENCE);

        let def = CertificateDefinition {
            template,
            signature: CertElement::new(SIG_OFFSET as u16, 70),
            public_key_x: CertElement::new(0, 0),
            public_key_y: CertElement::new(0, 0),
            issue_date: CertElement::new(0, 0),
            expire_date: CertElement::new(0, 0),
            serial_number: CertElement::new(0, 0),
            subject: CertElement::new(0, 0),
            subject_source: SubjectSource::Template,
            serial_source: SerialSource::DeviceSerial,
            compressed_slot: crate::memory::Slot::Certificate0c,
            public_key_slot: crate::memory::Slot::PrivateKey00,
        };

        // The template's signature is 70 bytes; reconstruct 70/71/72-byte
        // signatures and confirm the enclosing length fields and the total
        // length track the actual signature, and that the result round-trips.
        for sig_len in [70usize, 71, 72] {
            let cc = cc_with_sig_len(sig_len);
            let mut out = [0u8; 320];
            let n = def.reconstruct(&cc, &pk, &[], None, &mut out).unwrap();

            let delta = sig_len as isize - 70;
            assert_eq!(
                n as isize,
                tlen as isize + delta,
                "total length ({sig_len})"
            );

            let outer = ((out[2] as usize) << 8) | out[3] as usize;
            assert_eq!(outer, n - 4, "outer SEQUENCE length ({sig_len})");
            assert_eq!(
                out[SIG_OFFSET - 2] as usize,
                1 + sig_len,
                "BIT STRING length ({sig_len})"
            );
            assert_eq!(out[SIG_OFFSET], DER_SEQUENCE);
            assert_eq!(
                2 + out[SIG_OFFSET + 1] as usize,
                sig_len,
                "signature SEQUENCE length ({sig_len})"
            );

            // Compressing the reconstructed cert recovers the same R and S.
            let back = def.compress(&out[..n]).unwrap();
            assert_eq!(
                back.signature_r(),
                cc.signature_r(),
                "round-trip R ({sig_len})"
            );
            assert_eq!(
                back.signature_s(),
                cc.signature_s(),
                "round-trip S ({sig_len})"
            );
        }
    }
}