1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct CompressedDate(u32);
36
37impl CompressedDate {
38 const YEAR_MASK: u32 = 0x1F; const YEAR_OFFSET: u32 = 0;
41 const MONTH_MASK: u32 = 0x0F; const MONTH_OFFSET: u32 = 5;
43 const DAY_MASK: u32 = 0x1F; const DAY_OFFSET: u32 = 9;
45 const HOUR_MASK: u32 = 0x1F; const HOUR_OFFSET: u32 = 14;
47 const EXPIRE_MASK: u32 = 0x1F; const EXPIRE_OFFSET: u32 = 19;
49
50 pub const fn new() -> Self {
52 Self(0)
53 }
54
55 pub const fn year(&self) -> u8 {
57 ((self.0 >> Self::YEAR_OFFSET) & Self::YEAR_MASK) as u8
58 }
59
60 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 pub const fn month(&self) -> u8 {
68 ((self.0 >> Self::MONTH_OFFSET) & Self::MONTH_MASK) as u8
69 }
70
71 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 pub const fn day(&self) -> u8 {
79 ((self.0 >> Self::DAY_OFFSET) & Self::DAY_MASK) as u8
80 }
81
82 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 pub const fn hour(&self) -> u8 {
90 ((self.0 >> Self::HOUR_OFFSET) & Self::HOUR_MASK) as u8
91 }
92
93 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 pub const fn expire_years(&self) -> u8 {
101 ((self.0 >> Self::EXPIRE_OFFSET) & Self::EXPIRE_MASK) as u8
102 }
103
104 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 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 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 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 pub const BASE_YEAR: u16 = 2025;
145
146 pub const MAX_YEAR_OFFSET: u8 = 31;
148
149 pub const MAX_EXPIRE_YEARS: u8 = 31;
151
152 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 if issue_date >= expire_date {
159 return Err(ErrorKind::BadParam.into());
160 }
161
162 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 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 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 let issue_datetime = DateTime::new(issue_year, self.month(), self.day(), self.hour(), 0, 0)
197 .map_err(|_| ErrorKind::BadParam)?;
198
199 let expire_datetime =
201 DateTime::new(expire_year, self.month(), self.day(), self.hour(), 0, 0)
202 .map_err(|_| ErrorKind::BadParam)?;
203
204 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum SerialSource {
245 Stored(SlotAddress),
247 DeviceSerial,
249 SignerId,
251 PubKeyHash,
253 DeviceSerialHash,
255}
256
257impl SerialSource {
258 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 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 Err(ErrorKind::BadParam.into())
284 }
285 SerialSource::DeviceSerial => {
286 output[0] = 0x40;
288 output[1..10].copy_from_slice(device_serial.as_ref());
289 Ok(&output[..10])
290 }
291 SerialSource::SignerId => {
292 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#[derive(Clone, Copy, Debug)]
312pub enum SubjectSource<'a> {
313 Template,
315 Provided(&'a [u8]),
317 FromSerial(fn(&Serial, &mut [u8]) -> Option<usize>),
323}
324
325#[derive(Clone, Debug)]
336pub struct CompressedCertificate {
337 data: [u8; Self::SIZE],
338}
339
340impl CompressedCertificate {
341 pub const SIZE: usize = 72;
343
344 const SIG_R_OFFSET: usize = 0;
346 const SIG_S_OFFSET: usize = 32;
348 const DATE_OFFSET: usize = 64;
350 const SIGNER_ID_OFFSET: usize = 67;
352 const TEMPLATE_ID_OFFSET: usize = 69;
354 const CHAIN_ID_OFFSET: usize = 70;
356 const SERIAL_SOURCE_OFFSET: usize = 71;
358
359 pub fn new(data: [u8; Self::SIZE]) -> Self {
361 Self { data }
362 }
363
364 pub fn zeroed() -> Self {
366 Self {
367 data: [0u8; Self::SIZE],
368 }
369 }
370
371 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 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 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 pub fn to_der_signature(&self) -> Result<DerSignature, Error> {
393 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 let signature =
400 p256::ecdsa::Signature::from_slice(&sig_bytes).map_err(|_| ErrorKind::BadParam)?;
401
402 Ok(signature.to_der())
403 }
404
405 pub fn set_signature_from_der(&mut self, sig: &DerSignature) -> Result<(), Error> {
407 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 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 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 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 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 pub fn template_id(&self) -> u8 {
449 self.data[Self::TEMPLATE_ID_OFFSET]
450 }
451
452 pub fn set_template_id(&mut self, id: u8) {
454 self.data[Self::TEMPLATE_ID_OFFSET] = id;
455 }
456
457 pub fn chain_id(&self) -> u8 {
459 self.data[Self::CHAIN_ID_OFFSET]
460 }
461
462 pub fn set_chain_id(&mut self, id: u8) {
464 self.data[Self::CHAIN_ID_OFFSET] = id;
465 }
466
467 pub fn serial_source(&self) -> u8 {
469 self.data[Self::SERIAL_SOURCE_OFFSET]
470 }
471
472 pub fn set_serial_source(&mut self, source: &SerialSource) {
474 self.data[Self::SERIAL_SOURCE_OFFSET] = source.to_tag();
475 }
476
477 pub fn as_bytes(&self) -> &[u8; Self::SIZE] {
479 &self.data
480 }
481
482 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#[derive(Clone, Copy, Debug, Default)]
521pub struct CertElement {
522 pub offset: u16,
524 pub count: u8,
526}
527
528impl CertElement {
529 pub const fn new(offset: u16, count: u8) -> Self {
531 Self { offset, count }
532 }
533}
534
535pub struct CertificateDefinition<'a> {
540 pub template: &'a [u8],
542 pub signature: CertElement,
544 pub public_key_x: CertElement,
546 pub public_key_y: CertElement,
548 pub issue_date: CertElement,
550 pub expire_date: CertElement,
552 pub serial_number: CertElement,
554 pub subject: CertElement,
561 pub subject_source: SubjectSource<'a>,
563 pub serial_source: SerialSource,
565 pub compressed_slot: Slot,
567 pub public_key_slot: Slot,
569}
570
571impl<'a> CertificateDefinition<'a> {
572 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 pub fn compress(&self, der_cert: &[u8]) -> Result<CompressedCertificate, Error> {
585 let mut cc = CompressedCertificate::zeroed();
586
587 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 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 cc.set_serial_source(&self.serial_source);
638
639 Ok(cc)
640 }
641
642 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 if output.len() < self.template.len() {
667 return Err(ErrorKind::SmallBuffer.into());
668 }
669
670 let mut len = self.template.len();
672 output[..len].copy_from_slice(self.template);
673
674 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 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 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 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 let validity = compressed.encoded_date().to_validity()?;
720
721 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 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 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 adjust_definite_len(output, offset - 2, delta)?;
769 adjust_definite_len(output, 1, delta)?;
771 len = offset + actual;
772 }
773 }
774
775 Ok(len)
776 }
777}
778
779const DER_SEQUENCE: u8 = 0x30;
781
782fn 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)); }
792 let n = (first & 0x7f) as usize; 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
803fn 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()); }
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()); }
823 for i in 0..octets {
824 buf[pos + 1 + i] = (new >> (8 * (octets - 1 - i))) as u8;
825 }
826 }
827 Ok(())
828}
829
830fn parse_time(bytes: &[u8]) -> Result<Time, Error> {
832 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
868fn encode_time(time: &Time) -> Result<[u8; 15], Error> {
870 let dt = time.to_date_time();
871 let mut buf = [0u8; 15];
872
873 match time {
875 Time::UtcTime(_) => {
876 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 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 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 let compressed = CompressedDate::from_validity(&validity).unwrap();
937
938 assert_eq!(compressed.year(), 1); 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 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 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 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 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 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 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 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 const PREFIX: usize = 200;
1111 const SIG_OFFSET: usize = 4 + PREFIX + 3; 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; buf[4 + PREFIX + 1] = (1 + sig.len()) as u8;
1124 buf[4 + PREFIX + 2] = 0x00; buf[SIG_OFFSET..SIG_OFFSET + sig.len()].copy_from_slice(sig);
1126 4 + body
1127 }
1128
1129 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; }
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 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 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 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}