rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
/*
 *
 *    Copyright (c) 2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

//! X.509 DER certificate parsing utilities for extracting Matter-specific data in
//! DAC, PAI, and PAA certificates.
//!
//! This module parses DER-encoded X.509 certificates with Matter specific constraints
//! as defined in the Matter specification 6.2.2.3.
//!
//! It extracts fields needed for Matter device attestation verification: Subject Key
//! Identifier (SKID), Authority Key Identifier (AKID), public key, Matter Vendor ID,
//! Matter Product ID, and validity periods.

use crate::cert::x509::{
    key_usage_der, parse_hex_u16, time_to_unix_secs, AlgorithmIdentifier, AttributeTypeAndValue,
    AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectPublicKeyInfo, Validity,
    OID_AUTHORITY_KEY_ID, OID_BASIC_CONSTRAINTS, OID_ECDSA_WITH_SHA256, OID_EC_PUBLIC_KEY,
    OID_KEY_USAGE, OID_PRIME256V1, OID_SUBJECT_KEY_ID, P256_PUBLIC_KEY_LEN,
};
use crate::error::{Error, ErrorCode};

use der::asn1::{AnyRef, BitStringRef, ObjectIdentifier, OctetStringRef, UintRef};
use der::{
    Decode, DecodeValue, EncodeValue, FixedTag, Header, Reader, Sequence, SliceReader, Tag,
    TagNumber, Tagged,
};

/// Type alias for DAC (Device Attestation Certificate)
pub type DacCert<'a> = X509Cert<'a, DacExtensions<'a>>;

/// Type alias for PAI (Product Attestation Intermediate) Certificate
pub type PaiCert<'a> = X509Cert<'a, PaiExtensions<'a>>;

/// Type alias for PAA (Product Attestation Authority) Certificate
pub type PaaCert<'a> = X509Cert<'a, PaaExtensions<'a>>;

/// OID 1.3.6.1.4.1.37244.2.1 — Matter Vendor ID
const OID_MATTER_VENDOR_ID: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.6.1.4.1.37244.2.1");
/// OID 1.3.6.1.4.1.37244.2.2 — Matter Product ID
const OID_MATTER_PRODUCT_ID: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.6.1.4.1.37244.2.2");

/// Name ::= SEQUENCE OF RelativeDistinguishedName
///
/// Stores both the raw DER-encoded bytes and parsed Matter-specific attributes.
/// The raw bytes are used for exact byte-for-byte DN comparison as required by
/// the Matter specification.
///
/// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4
struct Name<'a> {
    /// Raw DER-encoded bytes of the Name
    raw_bytes: &'a [u8],
    /// Parsed Matter-specific attributes
    attrs: MatterDnAttrs,
}

impl<'a> der::FixedTag for Name<'a> {
    const TAG: Tag = Tag::Sequence;
}
impl<'a> DecodeValue<'a> for Name<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        // Read the entire SEQUENCE content (the RDNSequence) as a byte slice
        let raw_bytes = reader.read_slice(header.length)?;

        // Parse the Matter-specific attributes from the RDNSequence
        let attrs = MatterDnAttrs::parse(raw_bytes)?;

        Ok(Self { raw_bytes, attrs })
    }
}

/// Parsed Matter-specific attributes from an RDNSequence (Subject or Issuer DN).
///
/// Only extracts Vendor ID and Product ID.
/// Other standard DN attributes are ignored.
#[derive(Debug, Clone, Default)]
pub struct MatterDnAttrs {
    /// Matter Vendor ID (OID 1.3.6.1.4.1.37244.2.1)
    vendor_id: Option<u16>,
    /// Matter Product ID (OID 1.3.6.1.4.1.37244.2.2)
    product_id: Option<u16>,
}

impl MatterDnAttrs {
    /// Parse Matter vendor and producs ID attributes from an RDNSequence
    fn parse(rdn_bytes: &[u8]) -> der::Result<Self> {
        let mut vendor_id = None;
        let mut product_id = None;

        // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
        // RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
        let mut outer = SliceReader::new(rdn_bytes)?;

        while !outer.is_finished() {
            // Each RDN is a SET
            let rdn_set = AnyRef::decode(&mut outer)?;
            let mut set_reader = SliceReader::new(rdn_set.value())?;

            while !set_reader.is_finished() {
                let atv = AttributeTypeAndValue::decode(&mut set_reader)?;

                if atv.oid == OID_MATTER_VENDOR_ID {
                    let value = atv.value;
                    vendor_id = Some(
                        parse_hex_u16(value.value())
                            .map_err(|_| der::ErrorKind::Value { tag: value.tag() })?,
                    );
                } else if atv.oid == OID_MATTER_PRODUCT_ID {
                    let value = atv.value;
                    product_id = Some(
                        parse_hex_u16(value.value())
                            .map_err(|_| der::ErrorKind::Value { tag: value.tag() })?,
                    );
                }
            }
        }

        Ok(Self {
            vendor_id,
            product_id,
        })
    }
}

/// A parsed extension with its critical flag and typed value.
struct ParsedExtension<T> {
    critical: bool,
    value: T,
}

/// Helper structure to hold parsed extension fields during decoding
struct ParsedExtensionFields<'a> {
    basic_constraints: Option<ParsedExtension<BasicConstraints>>,
    key_usage: Option<ParsedExtension<KeyUsage>>,
    subject_key_id: Option<ParsedExtension<OctetStringRef<'a>>>,
    authority_key_id: Option<ParsedExtension<AuthorityKeyIdentifier<'a>>>,
}

impl<'a> ParsedExtensionFields<'a> {
    /// Parse X.509 extensions from a reader
    fn parse<R: Reader<'a>>(reader: &mut R) -> der::Result<Self> {
        let mut basic_constraints: Option<ParsedExtension<BasicConstraints>> = None;
        let mut key_usage: Option<ParsedExtension<KeyUsage>> = None;
        let mut subject_key_id: Option<ParsedExtension<OctetStringRef<'a>>> = None;
        let mut authority_key_id: Option<ParsedExtension<AuthorityKeyIdentifier<'a>>> = None;

        // Iterate through SEQUENCE OF Extension
        while !reader.is_finished() {
            // Each Extension is a SEQUENCE, so we decode it to get its contents
            let ext_any = AnyRef::decode(reader)?;
            let mut ext_reader = SliceReader::new(ext_any.value())?;

            // extnID OBJECT IDENTIFIER
            let extn_id = ObjectIdentifier::decode(&mut ext_reader)?;

            // critical BOOLEAN DEFAULT FALSE
            let critical = if !ext_reader.is_finished() && ext_reader.peek_tag()? == Tag::Boolean {
                bool::decode(&mut ext_reader)?
            } else {
                false
            };

            // extnValue OCTET STRING
            let extn_value = OctetStringRef::decode(&mut ext_reader)?;
            let value_bytes = extn_value.as_bytes();

            if extn_id == OID_BASIC_CONSTRAINTS {
                let bc = BasicConstraints::from_der(value_bytes)?;
                basic_constraints = Some(ParsedExtension {
                    critical,
                    value: bc,
                });
            } else if extn_id == OID_KEY_USAGE {
                let bs = BitStringRef::from_der(value_bytes)?;
                key_usage = Some(ParsedExtension {
                    critical,
                    value: bs.into(),
                });
            } else if extn_id == OID_SUBJECT_KEY_ID {
                let skid = OctetStringRef::from_der(value_bytes)?;
                subject_key_id = Some(ParsedExtension {
                    critical,
                    value: skid,
                });
            } else if extn_id == OID_AUTHORITY_KEY_ID {
                let akid = AuthorityKeyIdentifier::from_der(value_bytes)?;
                authority_key_id = Some(ParsedExtension {
                    critical,
                    value: akid,
                });
            } else {
                // RFC 5280 Section 4.2 states that a certificate-using system MUST reject
                // the certificate if it encounters a critical extension it does not recognize
                // or a critical extension that contains information that it cannot process.
                //
                // Matter spec allows other non-critical extensions from RFC 5280 that don't
                // violate size limitations, but all unrecognized critical extensions must be rejected.
                if critical {
                    return Err(der::ErrorKind::Failed.into());
                }
                // Non-critical unknown extensions are ignored
            }
        }

        Ok(Self {
            basic_constraints,
            key_usage,
            subject_key_id,
            authority_key_id,
        })
    }
}

/// Trait for certificate types (DAC, PAI, PAA).
///
/// Each certificate type has different requirements (Matter Spec).
/// Implementations must:
/// - Parse extensions from DER-encoded data
/// - Validate requirements during parsing (fail if invalid)
/// - Provide access to Subject Key Identifier and Authority Key Identifier
/// - Validate issuer and subject fields
pub trait CertType<'a>: DecodeValue<'a> + der::FixedTag + der::EncodeValue {
    /// Get subject key identifier if present for this certificate type
    fn subject_key_id(&self) -> Option<&'a [u8]>;

    /// Get authority key identifier if present for this certificate type
    /// Note: PAA certificates do not have AKID (self-signed)
    fn authority_key_id(&self) -> Option<&'a [u8]>;

    /// Validate issuer and subject fields according to certificate type requirements.
    /// Called after decoding the extensions to validate the DN constraints.
    ///
    /// According to the Matter specification, issuer and subject fields must match
    /// exactly for self-signed certificates (PAA).
    fn validate_issuer_subject(
        issuer_attrs: &MatterDnAttrs,
        subject_attrs: &MatterDnAttrs,
        issuer_raw: &[u8],
        subject_raw: &[u8],
    ) -> der::Result<()>;
}

/// DAC (Device Attestation Certificate) Extensions
///
/// A DAC SHALL have (Matter Spec):
/// - Basic Constraints: critical=TRUE, cA=FALSE
/// - Key Usage: critical=TRUE, only digitalSignature bit set
/// - Authority Key Identifier: present
/// - Subject Key Identifier: present
#[allow(unused)]
pub struct DacExtensions<'a> {
    basic_constraints: ParsedExtension<BasicConstraints>,
    key_usage: ParsedExtension<KeyUsage>,
    subject_key_id: ParsedExtension<OctetStringRef<'a>>,
    authority_key_id: ParsedExtension<AuthorityKeyIdentifier<'a>>,
}

// DAC Extensions parsing with validation
impl<'a> DecodeValue<'a> for DacExtensions<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            // Parse all extension fields
            let fields = ParsedExtensionFields::parse(reader)?;

            // Validate DAC requirements: all fields must be present
            let basic_constraints = fields.basic_constraints.ok_or(der::ErrorKind::Failed)?;
            let key_usage = fields.key_usage.ok_or(der::ErrorKind::Failed)?;
            let subject_key_id = fields.subject_key_id.ok_or(der::ErrorKind::Failed)?;
            let authority_key_id = fields.authority_key_id.ok_or(der::ErrorKind::Failed)?;

            // Basic Constraints: SHALL be critical and cA SHALL be FALSE
            if !basic_constraints.critical {
                return Err(der::ErrorKind::Failed.into());
            }
            if basic_constraints.value.ca {
                return Err(der::ErrorKind::Failed.into());
            }

            // Key Usage: SHALL be critical, SHALL only have digitalSignature bit set
            if !key_usage.critical {
                return Err(der::ErrorKind::Failed.into());
            }
            if !key_usage.value.digital_signature() {
                return Err(der::ErrorKind::Failed.into());
            }
            // Only digitalSignature bit should be set (no other bits)
            if !key_usage
                .value
                .has_only_bits(key_usage_der::DIGITAL_SIGNATURE)
            {
                return Err(der::ErrorKind::Failed.into());
            }

            Ok(Self {
                basic_constraints,
                key_usage,
                subject_key_id,
                authority_key_id,
            })
        })
    }
}

impl<'a> der::FixedTag for DacExtensions<'a> {
    const TAG: Tag = Tag::Sequence;
}

// Dummy EncodeValue implementation
// Required by der verision 0.7 for use with #[derive(Sequence)] on structs that contain Extensions.
// TODO Remove when upgrading to der 0.8+ which separates Encode/Decode traits.
impl<'a> der::EncodeValue for DacExtensions<'a> {
    fn value_len(&self) -> der::Result<der::Length> {
        // This should never be called since we only parse certificates, never create them
        unimplemented!("DacExtensions encoding is not supported")
    }

    fn encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()> {
        // This should never be called since we only parse certificates, never create them
        unimplemented!("DacExtensions encoding is not supported")
    }
}

impl<'a> CertType<'a> for DacExtensions<'a> {
    fn subject_key_id(&self) -> Option<&'a [u8]> {
        Some(self.subject_key_id.value.as_bytes())
    }

    fn authority_key_id(&self) -> Option<&'a [u8]> {
        Some(self.authority_key_id.value.key_identifier.as_bytes())
    }

    fn validate_issuer_subject(
        issuer_attrs: &MatterDnAttrs,
        subject_attrs: &MatterDnAttrs,
        _issuer_raw: &[u8],
        _subject_raw: &[u8],
    ) -> der::Result<()> {
        // DAC requirements (Matter Spec):
        // Issuer:
        // - SHALL have exactly one VendorID value present
        // - SHALL have exactly zero or one ProductID value present
        let issuer_vid = issuer_attrs.vendor_id.ok_or(der::ErrorKind::Failed)?;
        // ProductID is optional in issuer (zero or one)

        // Subject:
        // - SHALL have exactly one VendorID value present
        // - SHALL have exactly one ProductID value present
        let subject_vid = subject_attrs.vendor_id.ok_or(der::ErrorKind::Failed)?;
        let _subject_pid = subject_attrs.product_id.ok_or(der::ErrorKind::Failed)?;

        // The VendorID in issuer SHALL match the VendorID in subject
        if issuer_vid != subject_vid {
            return Err(der::ErrorKind::Failed.into());
        }

        // If ProductID was present in issuer, it SHALL match the ProductID in subject
        if let Some(issuer_pid) = issuer_attrs.product_id {
            if let Some(subject_pid) = subject_attrs.product_id {
                if issuer_pid != subject_pid {
                    return Err(der::ErrorKind::Failed.into());
                }
            }
        }

        Ok(())
    }
}

/// PAI (Product Attestation Intermediate) Certificate Extensions
///
/// A PAI SHALL have (Matter Spec):
/// - Basic Constraints: critical=TRUE, cA=TRUE, pathLen=0
/// - Key Usage: critical=TRUE, keyCertSign and cRLSign bits set, digitalSignature MAY be set
/// - Authority Key Identifier: present
/// - Subject Key Identifier: present
#[allow(unused)]
pub struct PaiExtensions<'a> {
    basic_constraints: ParsedExtension<BasicConstraints>,
    key_usage: ParsedExtension<KeyUsage>,
    subject_key_id: ParsedExtension<OctetStringRef<'a>>,
    authority_key_id: ParsedExtension<AuthorityKeyIdentifier<'a>>,
}

// PAI Extensions parsing with validation
impl<'a> DecodeValue<'a> for PaiExtensions<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            // Parse all extension fields
            let fields = ParsedExtensionFields::parse(reader)?;

            // Validate PAI requirements: all fields must be present
            let basic_constraints = fields.basic_constraints.ok_or(der::ErrorKind::Failed)?;
            let key_usage = fields.key_usage.ok_or(der::ErrorKind::Failed)?;
            let subject_key_id = fields.subject_key_id.ok_or(der::ErrorKind::Failed)?;
            let authority_key_id = fields.authority_key_id.ok_or(der::ErrorKind::Failed)?;

            // Basic Constraints: SHALL be critical, cA SHALL be TRUE, pathLen SHALL be 0
            if !basic_constraints.critical {
                return Err(der::ErrorKind::Failed.into());
            }
            if !basic_constraints.value.ca {
                return Err(der::ErrorKind::Failed.into());
            }
            // pathLen must be present and equal to 0
            if basic_constraints.value.path_len_constraint != Some(0) {
                return Err(der::ErrorKind::Failed.into());
            }

            // Key Usage: SHALL be critical
            if !key_usage.critical {
                return Err(der::ErrorKind::Failed.into());
            }
            // Both keyCertSign and cRLSign SHALL be set
            if !key_usage.value.key_cert_sign() || !key_usage.value.crl_sign() {
                return Err(der::ErrorKind::Failed.into());
            }
            // digitalSignature MAY be set, but no other bits should be set
            let allowed_bits = key_usage_der::KEY_CERT_SIGN
                | key_usage_der::CRL_SIGN
                | key_usage_der::DIGITAL_SIGNATURE;
            if (key_usage.value.bits & !allowed_bits) != 0 {
                return Err(der::ErrorKind::Failed.into());
            }

            Ok(Self {
                basic_constraints,
                key_usage,
                subject_key_id,
                authority_key_id,
            })
        })
    }
}

impl<'a> der::FixedTag for PaiExtensions<'a> {
    const TAG: Tag = Tag::Sequence;
}

// TODO Remove when upgrading to der 0.8+ which separates Encode/Decode traits.
impl<'a> der::EncodeValue for PaiExtensions<'a> {
    fn value_len(&self) -> der::Result<der::Length> {
        unimplemented!("PaiExtensions encoding is not supported")
    }

    fn encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()> {
        unimplemented!("PaiExtensions encoding is not supported")
    }
}

impl<'a> CertType<'a> for PaiExtensions<'a> {
    fn subject_key_id(&self) -> Option<&'a [u8]> {
        Some(self.subject_key_id.value.as_bytes())
    }

    fn authority_key_id(&self) -> Option<&'a [u8]> {
        Some(self.authority_key_id.value.key_identifier.as_bytes())
    }

    fn validate_issuer_subject(
        issuer_attrs: &MatterDnAttrs,
        subject_attrs: &MatterDnAttrs,
        _issuer_raw: &[u8],
        _subject_raw: &[u8],
    ) -> der::Result<()> {
        // PAI requirements (Matter Spec):
        // Issuer:
        // - SHALL have exactly zero or one VendorID value present
        // (VendorID is optional in issuer)

        // Subject:
        // - SHALL have exactly one VendorID value present
        // - SHALL have exactly zero or one ProductID value present
        let subject_vid = subject_attrs.vendor_id.ok_or(der::ErrorKind::Failed)?;
        // ProductID is optional in subject (zero or one)

        // If VendorID was present in issuer, it SHALL match the VendorID in subject
        if let Some(issuer_vid) = issuer_attrs.vendor_id {
            if issuer_vid != subject_vid {
                return Err(der::ErrorKind::Failed.into());
            }
        }

        Ok(())
    }
}

/// PAA (Product Attestation Authority) Certificate Extensions
///
/// A PAA SHALL have (Matter Spec):
/// - Basic Constraints: critical=TRUE, cA=TRUE, pathLen MAY be present and if so must be 1
/// - Key Usage: critical=TRUE, keyCertSign and cRLSign bits set, digitalSignature MAY be set
/// - Subject Key Identifier: present
/// - Authority Key Identifier: NOT required (self-signed), but may be present
#[allow(unused)]
pub struct PaaExtensions<'a> {
    basic_constraints: ParsedExtension<BasicConstraints>,
    key_usage: ParsedExtension<KeyUsage>,
    subject_key_id: ParsedExtension<OctetStringRef<'a>>,
    authority_key_id: Option<ParsedExtension<AuthorityKeyIdentifier<'a>>>,
}

// PAA Extensions parsing with validation
impl<'a> DecodeValue<'a> for PaaExtensions<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            // Parse all extension fields
            let fields = ParsedExtensionFields::parse(reader)?;

            // Validate PAA requirements
            let basic_constraints = fields.basic_constraints.ok_or(der::ErrorKind::Failed)?;
            let key_usage = fields.key_usage.ok_or(der::ErrorKind::Failed)?;
            let subject_key_id = fields.subject_key_id.ok_or(der::ErrorKind::Failed)?;

            // AKID is optional for PAA
            let authority_key_id = fields.authority_key_id;

            // Basic Constraints: SHALL be critical, cA SHALL be TRUE
            if !basic_constraints.critical || !basic_constraints.value.ca {
                return Err(der::ErrorKind::Failed.into());
            }

            // pathLen MAY be present, and if present it SHALL be 1
            if let Some(path_len) = basic_constraints.value.path_len_constraint {
                if path_len != 1 {
                    return Err(der::ErrorKind::Failed.into());
                }
            }

            // Key Usage: SHALL be critical
            if !key_usage.critical {
                return Err(der::ErrorKind::Failed.into());
            }
            // Both keyCertSign and cRLSign SHALL be set
            if !key_usage.value.key_cert_sign() || !key_usage.value.crl_sign() {
                return Err(der::ErrorKind::Failed.into());
            }
            // digitalSignature MAY be set, but no other bits should be set
            let allowed_bits = key_usage_der::KEY_CERT_SIGN
                | key_usage_der::CRL_SIGN
                | key_usage_der::DIGITAL_SIGNATURE;
            if (key_usage.value.bits & !allowed_bits) != 0 {
                return Err(der::ErrorKind::Failed.into());
            }

            Ok(Self {
                basic_constraints,
                key_usage,
                subject_key_id,
                authority_key_id,
            })
        })
    }
}

impl<'a> FixedTag for PaaExtensions<'a> {
    const TAG: Tag = Tag::Sequence;
}

// TODO Remove when upgrading to der 0.8+ which separates Encode/Decode traits.
impl<'a> EncodeValue for PaaExtensions<'a> {
    fn value_len(&self) -> der::Result<der::Length> {
        unimplemented!("PaaExtensions encoding is not supported")
    }

    fn encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()> {
        unimplemented!("PaaExtensions encoding is not supported")
    }
}

impl<'a> CertType<'a> for PaaExtensions<'a> {
    fn subject_key_id(&self) -> Option<&'a [u8]> {
        Some(self.subject_key_id.value.as_bytes())
    }

    fn authority_key_id(&self) -> Option<&'a [u8]> {
        // PAA certificates do not require AKID, but may have it
        self.authority_key_id
            .as_ref()
            .map(|ext| ext.value.key_identifier.as_bytes())
    }

    fn validate_issuer_subject(
        issuer_attrs: &MatterDnAttrs,
        subject_attrs: &MatterDnAttrs,
        issuer_raw: &[u8],
        subject_raw: &[u8],
    ) -> der::Result<()> {
        // PAA requirements (Matter Spec):
        // Issuer:
        // - SHALL have exactly zero or one VendorID value present
        // Subject:
        // - SHALL have exactly zero or one VendorID value present
        // - A ProductID value SHALL NOT be present in either subject or issuer

        // ProductID SHALL NOT be present in issuer or subject
        if issuer_attrs.product_id.is_some() || subject_attrs.product_id.is_some() {
            return Err(der::ErrorKind::Failed.into());
        }

        // For self-signed PAA certificates, issuer and subject SHALL match exactly
        // byte-for-byte as per Matter specification
        if issuer_raw != subject_raw {
            return Err(der::ErrorKind::Failed.into());
        }

        Ok(())
    }
}

/// TBSCertificate (To Be Signed Certificate)
///
/// Generic over extension type E to support DAC, PAI, and PAA certificates.
///
/// TBSCertificate ::= SEQUENCE {
///   version [0] EXPLICIT INTEGER DEFAULT v1,
///   serialNumber INTEGER,
///   signature AlgorithmIdentifier,
///   issuer Name,
///   validity Validity,
///   subject Name,
///   subjectPublicKeyInfo SubjectPublicKeyInfo,
///   extensions [3] EXPLICIT Extensions
/// }
#[allow(unused)]
struct TbsCertificate<'a, E: CertType<'a>> {
    /// Version number (0=v1, 1=v2, 2=v3).
    version: UintRef<'a>,
    /// Raw bytes of the serial number INTEGER value.
    serial_number: AnyRef<'a>,
    /// Signature algorithm.
    signature: AlgorithmIdentifier<'a>,
    /// Issuer Name with parsed Matter attributes.
    issuer: Name<'a>,
    /// Validity period.
    validity: Validity,
    /// Subject Name with parsed Matter attributes.
    subject: Name<'a>,
    /// Subject public key info.
    subject_public_key_info: SubjectPublicKeyInfo<'a>,
    /// Extensions field. Always present for Matter certificates (context tag [3]).
    extensions: E,
}

impl<'a, E: CertType<'a>> DecodeValue<'a> for TbsCertificate<'a, E> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            let version = reader
                .context_specific::<UintRef<'a>>(TagNumber::new(0), der::TagMode::Explicit)?
                .ok_or(der::ErrorKind::Failed)?;

            // Validate that version is 2 (v3 certificate)
            let version_value = version.as_bytes();
            if version_value.len() != 1 || version_value[0] != 2 {
                return Err(der::ErrorKind::Failed.into());
            }

            let serial_number = AnyRef::decode(reader)?;
            let signature = AlgorithmIdentifier::decode(reader)?;

            // Validate that signature algorithm is ECDSA with SHA256
            if signature.algorithm != OID_ECDSA_WITH_SHA256 {
                return Err(der::ErrorKind::Failed.into());
            }

            let issuer = Name::decode(reader)?;
            let validity = Validity::decode(reader)?;
            let subject = Name::decode(reader)?;
            let subject_public_key_info = SubjectPublicKeyInfo::decode(reader)?;

            // Validate that subjectPublicKeyInfo algorithm is ecPublicKey with prime256v1 curve
            let spki_algo = &subject_public_key_info.algorithm;
            if spki_algo.algorithm != OID_EC_PUBLIC_KEY {
                return Err(der::ErrorKind::Failed.into());
            }

            // SPK is P-256 which is 65-byte uncompressed (0x04 || X || Y).
            if subject_public_key_info.subject_public_key.raw_bytes().len() != P256_PUBLIC_KEY_LEN {
                return Err(der::ErrorKind::Failed.into());
            }

            // The parameters field must contain the named curve OID for prime256v1
            // ECParameters ::= CHOICE { namedCurve OBJECT IDENTIFIER, ... }
            // For Matter certs, only namedCurve is used, so we decode directly as an OID
            // https://www.rfc-editor.org/rfc/rfc5480#section-2.1.1
            let params = spki_algo.parameters.ok_or(der::ErrorKind::Failed)?;
            let curve_oid: ObjectIdentifier = params.try_into()?;

            if curve_oid != OID_PRIME256V1 {
                return Err(der::ErrorKind::Failed.into());
            }

            // Decode extensions [3] EXPLICIT
            let extensions = reader
                .context_specific::<E>(TagNumber::new(3), der::TagMode::Explicit)?
                .ok_or(der::ErrorKind::Failed)?;

            // Validate issuer and subject fields according to certificate type requirements
            E::validate_issuer_subject(
                &issuer.attrs,
                &subject.attrs,
                issuer.raw_bytes,
                subject.raw_bytes,
            )?;

            Ok(Self {
                version,
                serial_number,
                signature,
                issuer,
                validity,
                subject,
                subject_public_key_info,
                extensions,
            })
        })
    }
}

impl<'a, E: CertType<'a>> der::FixedTag for TbsCertificate<'a, E> {
    const TAG: Tag = Tag::Sequence;
}

// TODO Remove when upgrading to der 0.8+ which separates Encode/Decode traits.
impl<'a, E: CertType<'a>> EncodeValue for TbsCertificate<'a, E> {
    fn value_len(&self) -> der::Result<der::Length> {
        unimplemented!("PaaExtensions encoding is not supported")
    }

    fn encode_value(&self, _writer: &mut impl der::Writer) -> der::Result<()> {
        unimplemented!("PaaExtensions encoding is not supported")
    }
}

/// Top-level Certificate structure.
///
/// Generic over extension type E to support DAC, PAI, and PAA certificates.
///
/// Certificate ::= SEQUENCE {
///   tbsCertificate     TBSCertificate,
///   signatureAlgorithm AlgorithmIdentifier,
///   signatureValue     BIT STRING
/// }
#[allow(unused)]
#[derive(Sequence)]
struct Certificate<'a, E: CertType<'a>> {
    tbs_certificate: TbsCertificate<'a, E>,
    signature_algorithm: AlgorithmIdentifier<'a>,
    signature_value: BitStringRef<'a>,
}

/// A parsed DER-encoded X.509 certificate.
///
/// Generic over extension type E to support DAC, PAI, and PAA certificates.
/// Use the type aliases `DacCert`, `PaiCert`, and `PaaCert` for convenience.
///
/// Validates the incoming bytes are correctly DER-encoded x509 certificates
/// with the appropriate extensions for the certificate type.
///
/// # Example
///
/// ```ignore
/// let cert = DacCert::new(der_bytes)?;
/// let skid = cert.subject_key_id()?;
/// let pubkey = cert.public_key()?;
/// let vid = cert.vendor_id()?;
/// ```
pub struct X509Cert<'a, E: CertType<'a>> {
    cert: Certificate<'a, E>,
}

impl<'a, E: CertType<'a>> X509Cert<'a, E> {
    /// Create a new `X509Cert` from DER-encoded certificate bytes.
    ///
    /// Validates that the certificate parses correctly and has the required
    /// extensions for the certificate type E.
    pub fn new(data: &'a [u8]) -> Result<Self, Error> {
        let cert = Certificate::from_der(data).map_err(|_| ErrorCode::InvalidData)?;

        Ok(Self { cert })
    }

    /// Extract the Subject Key Identifier extension value.
    ///
    /// The extnValue of the SubjectKeyIdentifier extension is an
    /// OCTET STRING containing the 20-byte key identifier.
    pub fn subject_key_id(&self) -> Result<&'a [u8], Error> {
        self.cert
            .tbs_certificate
            .extensions
            .subject_key_id()
            .ok_or(Error::from(ErrorCode::NotFound))
    }

    /// Extract the Authority Key Identifier extension value.
    ///
    /// The extnValue contains a SEQUENCE with a context-specific `[0]`
    /// field holding the 20-byte key identifier.
    ///
    /// Note: This will return NotFound for PAA certificates (which are self-signed
    /// and do not have an Authority Key Identifier).
    pub fn authority_key_id(&self) -> Result<&'a [u8], Error> {
        self.cert
            .tbs_certificate
            .extensions
            .authority_key_id()
            .ok_or(Error::from(ErrorCode::NotFound))
    }

    /// Extract the subject public key bytes.
    ///
    /// Returns the raw bytes of the BIT STRING value from SubjectPublicKeyInfo,
    /// excluding the unused-bits prefix byte. For P-256 this is the 65-byte
    /// uncompressed point (0x04 || X || Y).
    pub fn public_key(&self) -> Result<&'a [u8], Error> {
        let spki_bytes = &self
            .cert
            .tbs_certificate
            .subject_public_key_info
            .subject_public_key
            .raw_bytes();

        Ok(spki_bytes)
    }

    /// Extract the Matter Vendor ID from the Subject DN.
    ///
    /// Returns `ErrorCode::NotFound` if not present in the Subject DN.
    pub fn vendor_id(&self) -> Result<u16, Error> {
        self.cert
            .tbs_certificate
            .subject
            .attrs
            .vendor_id
            .ok_or(Error::from(ErrorCode::NotFound))
    }

    /// Extract the Matter Product ID from the Subject DN.
    ///
    /// Returns `ErrorCode::NotFound` if not present in the Subject DN.
    pub fn product_id(&self) -> Result<u16, Error> {
        self.cert
            .tbs_certificate
            .subject
            .attrs
            .product_id
            .ok_or(Error::from(ErrorCode::NotFound))
    }

    /// Extract the NotBefore time as Unix epoch seconds.
    ///
    /// Parses UTCTime ("YYMMDDHHMMSSZ") or GeneralizedTime ("YYYYMMDDHHMMSSZ")
    /// from the validity field of the tbsCertificate.
    pub fn not_before_unix(&self) -> Result<u64, Error> {
        time_to_unix_secs(&self.cert.tbs_certificate.validity.not_before)
    }

    /// Extract the NotAfter time as Unix epoch seconds.
    ///
    /// Parses UTCTime or GeneralizedTime. For GeneralizedTime
    /// "99991231235959Z", returns `u64::MAX` to indicate no expiry.
    pub fn not_after_unix(&self) -> Result<u64, Error> {
        time_to_unix_secs(&self.cert.tbs_certificate.validity.not_after)
    }

    /// Check if the certificate is valid at the given Unix epoch time (seconds).
    ///
    /// Returns `true` if `not_before <= now_unix_secs <= not_after`.
    /// A `not_after` of `u64::MAX` (from "99991231235959Z") is always
    /// considered valid (no expiry).
    pub fn is_valid_at(&self, now_unix_secs: u64) -> Result<bool, Error> {
        let not_before = self.not_before_unix()?;
        let not_after = self.not_after_unix()?;

        Ok(now_unix_secs >= not_before && now_unix_secs <= not_after)
    }
}

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

    // Matter Development PAA certificate (self-signed, no VID/PID)
    // From connectedhomeip/credentials/development/attestation/Chip-Development-PAA-Cert.der
    const PAA_DER: &[u8] = &[
        0x30, 0x82, 0x01, 0xa0, 0x30, 0x82, 0x01, 0x46, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08,
        0x57, 0xd3, 0xa2, 0xd0, 0x1e, 0x31, 0x81, 0x90, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48,
        0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x21, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04,
        0x03, 0x0c, 0x16, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x65, 0x6c,
        0x6f, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x50, 0x41, 0x41, 0x30, 0x20, 0x17, 0x0d, 0x32,
        0x31, 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39,
        0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30,
        0x21, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x4d, 0x61, 0x74,
        0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, 0x65, 0x6e, 0x74,
        0x20, 0x50, 0x41, 0x41, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d,
        0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
        0x04, 0x1b, 0x0f, 0x25, 0x94, 0x2e, 0x3d, 0x92, 0xab, 0xd6, 0x70, 0x4c, 0x1a, 0x27, 0x81,
        0xa0, 0x38, 0xec, 0x53, 0x21, 0x2c, 0x4d, 0xab, 0x58, 0xb0, 0xbe, 0x3c, 0x40, 0xbd, 0xfb,
        0x49, 0x23, 0x23, 0x42, 0x1c, 0x79, 0xdc, 0xc7, 0xad, 0x70, 0x18, 0x10, 0x07, 0x12, 0x0d,
        0xc8, 0x6f, 0x0a, 0x89, 0x25, 0x3d, 0x89, 0x93, 0xeb, 0x37, 0xab, 0x65, 0x2e, 0xf8, 0xdb,
        0x13, 0x75, 0xe5, 0xb1, 0x45, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d,
        0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x01, 0x30,
        0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06,
        0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xfa, 0x92, 0xcf, 0x09,
        0x5e, 0xfa, 0x42, 0xe1, 0x14, 0x30, 0x65, 0x16, 0x32, 0xfe, 0xfe, 0x1b, 0x2c, 0x77, 0xa7,
        0xc8, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xfa,
        0x92, 0xcf, 0x09, 0x5e, 0xfa, 0x42, 0xe1, 0x14, 0x30, 0x65, 0x16, 0x32, 0xfe, 0xfe, 0x1b,
        0x2c, 0x77, 0xa7, 0xc8, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03,
        0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x50, 0xa7, 0x90, 0x33, 0x64, 0xb6, 0x53,
        0xff, 0x0e, 0xa4, 0x63, 0xdc, 0x68, 0x4a, 0x86, 0xdd, 0x25, 0xc7, 0x31, 0xa3, 0x9e, 0xfe,
        0xb3, 0xc2, 0x0c, 0xd2, 0xde, 0xd1, 0xb6, 0x60, 0x7e, 0x2f, 0x02, 0x21, 0x00, 0xaf, 0xd4,
        0xed, 0x4b, 0x6a, 0x99, 0xe5, 0xf8, 0xc5, 0x52, 0x1d, 0x70, 0x1e, 0xbc, 0xf9, 0xfd, 0x53,
        0xb9, 0x39, 0x4f, 0xd8, 0x0f, 0xc5, 0x99, 0x92, 0xff, 0x3e, 0x5b, 0xbb, 0xb6, 0x0a, 0x35,
    ];

    // Matter Development PAI certificate (VID=FFF1, no PID)
    // From connectedhomeip/credentials/development/attestation/Matter-Development-PAI-FFF1-noPID-Cert.der
    const PAI_DER: &[u8] = &[
        0x30, 0x82, 0x01, 0xcb, 0x30, 0x82, 0x01, 0x71, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08,
        0x56, 0xad, 0x82, 0x22, 0xad, 0x94, 0x5b, 0x64, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48,
        0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x30, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04,
        0x03, 0x0c, 0x0f, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20,
        0x50, 0x41, 0x41, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82,
        0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x30, 0x20, 0x17, 0x0d, 0x32,
        0x32, 0x30, 0x32, 0x30, 0x35, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x39,
        0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30,
        0x3d, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74,
        0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x20, 0x50, 0x41, 0x49, 0x20, 0x30, 0x78, 0x46,
        0x46, 0x46, 0x31, 0x20, 0x6e, 0x6f, 0x20, 0x50, 0x49, 0x44, 0x31, 0x14, 0x30, 0x12, 0x06,
        0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46,
        0x46, 0x31, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
        0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x41,
        0x9a, 0x93, 0x15, 0xc2, 0x17, 0x3e, 0x0c, 0x8c, 0x87, 0x6d, 0x03, 0xcc, 0xfc, 0x94, 0x48,
        0x52, 0x64, 0x7f, 0x7f, 0xec, 0x5e, 0x50, 0x82, 0xf4, 0x05, 0x99, 0x28, 0xec, 0xa8, 0x94,
        0xc5, 0x94, 0x15, 0x13, 0x09, 0xac, 0x63, 0x1e, 0x4c, 0xb0, 0x33, 0x92, 0xaf, 0x68, 0x4b,
        0x0b, 0xaf, 0xb7, 0xe6, 0x5b, 0x3b, 0x81, 0x62, 0xc2, 0xf5, 0x2b, 0xf9, 0x31, 0xb8, 0xe7,
        0x7a, 0xaa, 0x82, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01,
        0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06,
        0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x1d,
        0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x63, 0x54, 0x0e, 0x47, 0xf6, 0x4b,
        0x1c, 0x38, 0xd1, 0x38, 0x84, 0xa4, 0x62, 0xd1, 0x6c, 0x19, 0x5d, 0x8f, 0xfb, 0x3c, 0x30,
        0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x6a, 0xfd, 0x22,
        0x77, 0x1f, 0x51, 0x1f, 0xec, 0xbf, 0x16, 0x41, 0x97, 0x67, 0x10, 0xdc, 0xdc, 0x31, 0xa1,
        0x71, 0x7e, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03,
        0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0xb2, 0xef, 0x27, 0xf4, 0x9a, 0xe9, 0xb5, 0x0f,
        0xb9, 0x1e, 0xea, 0xc9, 0x4c, 0x4d, 0x0b, 0xdb, 0xb8, 0xd7, 0x92, 0x9c, 0x6c, 0xb8, 0x8f,
        0xac, 0xe5, 0x29, 0x36, 0x8d, 0x12, 0x05, 0x4c, 0x0c, 0x02, 0x20, 0x65, 0x5d, 0xc9, 0x2b,
        0x86, 0xbd, 0x90, 0x98, 0x82, 0xa6, 0xc6, 0x21, 0x77, 0xb8, 0x25, 0xd7, 0xd0, 0x5e, 0xdb,
        0xe7, 0xc2, 0x2f, 0x9f, 0xea, 0x71, 0x22, 0x0e, 0x7e, 0xa7, 0x03, 0xf8, 0x91,
    ];

    // Matter Development DAC certificate (VID=FFF1, PID=8000)
    // From connectedhomeip/credentials/development/attestation/Matter-Development-DAC-FFF1-8000-Cert.der
    const DAC_DER: &[u8] = &[
        0x30, 0x82, 0x01, 0xe9, 0x30, 0x82, 0x01, 0x8e, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08,
        0x23, 0x8a, 0x64, 0x7b, 0xbc, 0x4c, 0x30, 0xdd, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48,
        0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x3d, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04,
        0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x20, 0x50,
        0x41, 0x49, 0x20, 0x30, 0x78, 0x46, 0x46, 0x46, 0x31, 0x20, 0x6e, 0x6f, 0x20, 0x50, 0x49,
        0x44, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c,
        0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x32, 0x30,
        0x32, 0x30, 0x35, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39,
        0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x53, 0x31,
        0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74, 0x74, 0x65,
        0x72, 0x20, 0x44, 0x65, 0x76, 0x20, 0x44, 0x41, 0x43, 0x20, 0x30, 0x78, 0x46, 0x46, 0x46,
        0x31, 0x2f, 0x30, 0x78, 0x38, 0x30, 0x30, 0x30, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b,
        0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31,
        0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02,
        0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x30, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
        0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07,
        0x03, 0x42, 0x00, 0x04, 0x62, 0xdb, 0x16, 0xba, 0xde, 0xa3, 0x26, 0xa6, 0xdb, 0x84, 0x81,
        0x4a, 0x06, 0x3f, 0xc6, 0xc7, 0xe9, 0xe2, 0xb1, 0x01, 0xb7, 0x21, 0x64, 0x8e, 0xba, 0x4e,
        0x5a, 0xc8, 0x40, 0xf5, 0xda, 0x30, 0x1e, 0xe6, 0x18, 0x12, 0x4e, 0xb4, 0x18, 0x0e, 0x2f,
        0xc3, 0xa2, 0x04, 0x7a, 0x56, 0x4b, 0xa9, 0xbc, 0xfa, 0x0b, 0xf7, 0x1f, 0x60, 0xce, 0x89,
        0x30, 0xf1, 0xe7, 0xf6, 0x6e, 0xc8, 0xd7, 0x28, 0xa3, 0x60, 0x30, 0x5e, 0x30, 0x0c, 0x06,
        0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0e, 0x06, 0x03,
        0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x07, 0x80, 0x30, 0x1d, 0x06,
        0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xbc, 0xf7, 0xb0, 0x07, 0x49, 0x70, 0x63,
        0x60, 0x6a, 0x26, 0xbe, 0x4e, 0x08, 0x7c, 0x59, 0x56, 0x87, 0x74, 0x5a, 0x5a, 0x30, 0x1f,
        0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x63, 0x54, 0x0e, 0x47,
        0xf6, 0x4b, 0x1c, 0x38, 0xd1, 0x38, 0x84, 0xa4, 0x62, 0xd1, 0x6c, 0x19, 0x5d, 0x8f, 0xfb,
        0x3c, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x49,
        0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0x97, 0x97, 0x11, 0xec, 0x9e, 0x76, 0x18, 0xce, 0x41,
        0x80, 0x11, 0x32, 0xc2, 0x50, 0xdb, 0x70, 0x76, 0x74, 0x63, 0x0c, 0xd5, 0x8c, 0x12, 0xc6,
        0xe2, 0x31, 0x5f, 0x08, 0xd0, 0x1e, 0xe1, 0x78, 0x02, 0x21, 0x00, 0xec, 0xfc, 0x13, 0x06,
        0xbd, 0x2a, 0x13, 0x3d, 0x12, 0x2a, 0x27, 0x86, 0x10, 0xea, 0x3d, 0xca, 0x47, 0xf0, 0x5c,
        0x7a, 0x8b, 0x80, 0x5f, 0xa7, 0x1c, 0x6f, 0xf4, 0x15, 0x38, 0xa8, 0x64, 0xc8,
    ];

    #[test]
    fn test_paa_skid() {
        let cert = PaaCert::new(PAA_DER).unwrap();
        let skid = cert.subject_key_id().unwrap();
        assert_eq!(
            skid,
            &[
                0xFA, 0x92, 0xCF, 0x09, 0x5E, 0xFA, 0x42, 0xE1, 0x14, 0x30, 0x65, 0x16, 0x32, 0xFE,
                0xFE, 0x1B, 0x2C, 0x77, 0xA7, 0xC8
            ]
        );
    }

    #[test]
    fn test_paa_self_signed_akid_equals_skid() {
        // PAA certificates may have AKID (for self-signed certs, AKID should equal SKID)
        let cert = PaaCert::new(PAA_DER).unwrap();
        let skid = cert.subject_key_id().unwrap();
        let akid = cert.authority_key_id().unwrap();
        assert_eq!(skid, akid);
    }

    #[test]
    fn test_pai_skid() {
        let cert = PaiCert::new(PAI_DER).unwrap();
        let skid = cert.subject_key_id().unwrap();
        assert_eq!(
            skid,
            &[
                0x63, 0x54, 0x0E, 0x47, 0xF6, 0x4B, 0x1C, 0x38, 0xD1, 0x38, 0x84, 0xA4, 0x62, 0xD1,
                0x6C, 0x19, 0x5D, 0x8F, 0xFB, 0x3C
            ]
        );
    }

    #[test]
    fn test_dac_skid() {
        let cert = DacCert::new(DAC_DER).unwrap();
        let skid = cert.subject_key_id().unwrap();
        assert_eq!(
            skid,
            &[
                0xBC, 0xF7, 0xB0, 0x07, 0x49, 0x70, 0x63, 0x60, 0x6A, 0x26, 0xBE, 0x4E, 0x08, 0x7C,
                0x59, 0x56, 0x87, 0x74, 0x5A, 0x5A
            ]
        );
    }

    #[test]
    fn test_dac_akid_matches_pai_skid() {
        let dac = DacCert::new(DAC_DER).unwrap();
        let pai = PaiCert::new(PAI_DER).unwrap();
        assert_eq!(
            dac.authority_key_id().unwrap(),
            pai.subject_key_id().unwrap()
        );
    }

    #[test]
    fn test_paa_public_key() {
        let cert = PaaCert::new(PAA_DER).unwrap();
        let pk = cert.public_key().unwrap();
        assert_eq!(pk.len(), 65);
        assert_eq!(pk[0], 0x04); // uncompressed point marker
        assert_eq!(
            pk,
            &[
                0x04, 0x1b, 0x0f, 0x25, 0x94, 0x2e, 0x3d, 0x92, 0xab, 0xd6, 0x70, 0x4c, 0x1a, 0x27,
                0x81, 0xa0, 0x38, 0xec, 0x53, 0x21, 0x2c, 0x4d, 0xab, 0x58, 0xb0, 0xbe, 0x3c, 0x40,
                0xbd, 0xfb, 0x49, 0x23, 0x23, 0x42, 0x1c, 0x79, 0xdc, 0xc7, 0xad, 0x70, 0x18, 0x10,
                0x07, 0x12, 0x0d, 0xc8, 0x6f, 0x0a, 0x89, 0x25, 0x3d, 0x89, 0x93, 0xeb, 0x37, 0xab,
                0x65, 0x2e, 0xf8, 0xdb, 0x13, 0x75, 0xe5, 0xb1, 0x45,
            ]
        );
    }

    #[test]
    fn test_dac_public_key() {
        let cert = DacCert::new(DAC_DER).unwrap();
        let pk = cert.public_key().unwrap();
        assert_eq!(pk.len(), 65);
        assert_eq!(pk[0], 0x04);
        assert_eq!(
            pk,
            &[
                0x04, 0x62, 0xdb, 0x16, 0xba, 0xde, 0xa3, 0x26, 0xa6, 0xdb, 0x84, 0x81, 0x4a, 0x06,
                0x3f, 0xc6, 0xc7, 0xe9, 0xe2, 0xb1, 0x01, 0xb7, 0x21, 0x64, 0x8e, 0xba, 0x4e, 0x5a,
                0xc8, 0x40, 0xf5, 0xda, 0x30, 0x1e, 0xe6, 0x18, 0x12, 0x4e, 0xb4, 0x18, 0x0e, 0x2f,
                0xc3, 0xa2, 0x04, 0x7a, 0x56, 0x4b, 0xa9, 0xbc, 0xfa, 0x0b, 0xf7, 0x1f, 0x60, 0xce,
                0x89, 0x30, 0xf1, 0xe7, 0xf6, 0x6e, 0xc8, 0xd7, 0x28,
            ]
        );
    }

    #[test]
    fn test_dac_vendor_id() {
        let cert = DacCert::new(DAC_DER).unwrap();
        assert_eq!(cert.vendor_id().unwrap(), 0xFFF1);
    }

    #[test]
    fn test_dac_product_id() {
        let cert = DacCert::new(DAC_DER).unwrap();
        assert_eq!(cert.product_id().unwrap(), 0x8000);
    }

    #[test]
    fn test_pai_vendor_id() {
        let cert = PaiCert::new(PAI_DER).unwrap();
        assert_eq!(cert.vendor_id().unwrap(), 0xFFF1);
    }

    #[test]
    fn test_pai_no_product_id() {
        let cert = PaiCert::new(PAI_DER).unwrap();
        assert_eq!(
            cert.product_id().map_err(|e| e.code()),
            Err(ErrorCode::NotFound)
        );
    }

    #[test]
    fn test_paa_no_vendor_id() {
        let cert = PaaCert::new(PAA_DER).unwrap();
        assert_eq!(
            cert.vendor_id().map_err(|e| e.code()),
            Err(ErrorCode::NotFound)
        );
    }

    #[test]
    fn test_paa_no_product_id() {
        let cert = PaaCert::new(PAA_DER).unwrap();
        assert_eq!(
            cert.product_id().map_err(|e| e.code()),
            Err(ErrorCode::NotFound)
        );
    }

    #[test]
    fn test_dac_not_before() {
        let cert = DacCert::new(DAC_DER).unwrap();
        let nb = cert.not_before_unix().unwrap();
        // 2022-02-05 00:00:00 UTC = 1644019200
        assert_eq!(nb, 1644019200);
    }

    #[test]
    fn test_dac_not_after_no_expiry() {
        let cert = DacCert::new(DAC_DER).unwrap();
        let na = cert.not_after_unix().unwrap();
        // 99991231235959Z => u64::MAX (no expiry)
        assert_eq!(na, u64::MAX);
    }

    #[test]
    fn test_paa_not_before() {
        let cert = PaaCert::new(PAA_DER).unwrap();
        let nb = cert.not_before_unix().unwrap();
        // 2021-06-28 14:23:43 UTC = 1624890223
        assert_eq!(nb, 1624890223);
    }

    #[test]
    fn test_dac_is_valid_at() {
        let cert = DacCert::new(DAC_DER).unwrap();
        // A time well after NotBefore (2023-11-14)
        assert!(cert.is_valid_at(1700000000).unwrap());
        // A time before NotBefore (2021-09-13)
        assert!(!cert.is_valid_at(1600000000).unwrap());
    }

    #[test]
    fn test_invalid_empty_input() {
        assert!(DacCert::new(&[]).is_err());
    }

    #[test]
    fn test_invalid_not_sequence() {
        assert!(DacCert::new(&[0x01, 0x02, 0x03]).is_err());
    }

    #[test]
    fn test_invalid_empty_sequence() {
        assert!(DacCert::new(&[0x30, 0x00]).is_err());
    }

    #[test]
    fn test_tbs_field_version_error_when_absent() {
        let mut der = PAA_DER.to_vec();
        let version_field_len: usize = 5;
        let version_start: usize = 8;

        // remove version field length from DER length
        der[3] -= version_field_len as u8;
        // remove version field length from tbs certificate length
        der[7] -= version_field_len as u8;
        // remove version field from the certificate
        der.drain(version_start..version_start + version_field_len);

        assert!(PaaCert::new(&der).is_err());
    }

    #[test]
    fn test_version_must_be_v3() {
        let mut der = PAA_DER.to_vec();

        // Change version from v3 (2) to v2 (1)
        der[12] = 1;
        // Matter certificate versions must be v3
        assert!(PaaCert::new(&der).is_err());
    }

    #[test]
    fn test_parse_hex_u16() {
        assert_eq!(parse_hex_u16(b"FFF1").unwrap(), 0xFFF1);
        assert_eq!(parse_hex_u16(b"8000").unwrap(), 0x8000);
        assert_eq!(parse_hex_u16(b"0000").unwrap(), 0x0000);
        assert_eq!(parse_hex_u16(b"FFFF").unwrap(), 0xFFFF);
        assert_eq!(parse_hex_u16(b"abcd").unwrap(), 0xABCD);
        assert!(parse_hex_u16(b"FFF").is_err()); // too short
        assert!(parse_hex_u16(b"FFFFF").is_err()); // too long
        assert!(parse_hex_u16(b"GHIJ").is_err()); // invalid chars
    }

    #[test]
    fn test_keyusage_from_bitstring_1_byte_with_unused() {
        // Represents only bit 0 set, with bits 1-7 as padding
        let bs_bytes = &[0x81u8];
        let bs = BitStringRef::new(7, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        // Should only have digitalSignature (0x8000)
        assert_eq!(
            ku.bits, 0x8000,
            "Expected only bit 0 (digitalSignature) set"
        );
        assert!(ku.digital_signature());
        assert!(ku.has_only_bits(key_usage_der::DIGITAL_SIGNATURE));
    }

    #[test]
    fn test_keyusage_from_bitstring_1_byte_no_unused() {
        // All 8 bits are valid, only bit 0 is set
        let bs_bytes = &[0x80u8];
        let bs = BitStringRef::new(0, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        assert_eq!(ku.bits, 0x8000);
        assert!(ku.digital_signature());
        assert!(ku.has_only_bits(key_usage_der::DIGITAL_SIGNATURE));
    }

    #[test]
    fn test_keyusage_from_bitstring_2_bytes_with_unused() {
        // Bits 0 and 8 are valid, bits 9-15 are padding
        let bs_bytes = &[0x80u8, 0x80u8];
        let bs = BitStringRef::new(7, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        // Should have digitalSignature (0x8000) and decipherOnly (0x0080)
        assert_eq!(ku.bits, 0x8080);
        assert!(ku.digital_signature());
    }

    #[test]
    fn test_keyusage_from_bitstring_2_bytes_no_unused() {
        // Only bit 5 (keyCertSign) is set
        let bs_bytes = &[0x04u8, 0x00u8];
        let bs = BitStringRef::new(0, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        assert_eq!(ku.bits, 0x0400);
        assert!(ku.key_cert_sign());
        assert!(ku.has_only_bits(key_usage_der::KEY_CERT_SIGN));
    }

    #[test]
    fn test_keyusage_rejects_oversized_bitstring() {
        // 3-byte bitstring (malformed, KeyUsage max is 9 bits, so 2 bytes)
        let bs_bytes = &[0x80u8, 0x00u8, 0xFFu8];
        let bs = BitStringRef::new(0, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        assert_eq!(ku.bits, 0, "Oversized bitstring should be rejected");
        assert!(!ku.digital_signature());
    }

    #[test]
    fn test_keyusage_1_byte_with_padding() {
        // Only bit 0 should be valid; bits 1-7 should be masked off
        let bs_bytes = &[0xFFu8];
        let bs = BitStringRef::new(7, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        // Should mask to only bit 0
        assert_eq!(ku.bits, 0x8000, "Should mask off unused padding bits");
        assert!(ku.has_only_bits(key_usage_der::DIGITAL_SIGNATURE));
    }

    #[test]
    fn test_keyusage_2_bytes_with_padding() {
        // Bits 0-8 are valid (bit 0 and 8 set), bits 9-15 should be masked
        let bs_bytes = &[0x80u8, 0xFFu8];
        let bs = BitStringRef::new(7, bs_bytes).unwrap();
        let ku = KeyUsage::from(bs);

        // Should have bits 0 and 8, with bits 9-15 masked off
        assert_eq!(
            ku.bits, 0x8080,
            "Should mask off unused padding bits in last byte"
        );
    }
}