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
/*
 *
 *    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.
 */

use rand_core::RngCore;

use crate::cert::CertRef;
use crate::crypto::{
    self, canon, Aead, AeadNonceRef, CanonAeadKey, CanonAeadKeyRef, CanonPkcPublicKey,
    CanonPkcPublicKeyRef, CanonPkcSharedSecret, CanonPkcSignature, CanonPkcSignatureRef, Crypto,
    CryptoSensitive, Digest, Hash, HashRef, Kdf, PublicKey, SecretKey, SigningSecretKey,
    AEAD_CANON_KEY_LEN, AEAD_KEY_ZEROED, AEAD_TAG_LEN, AEAD_TAG_ZEROED, HASH_LEN, HASH_ZEROED,
    PKC_CANON_PUBLIC_KEY_LEN, PKC_PUBLIC_KEY_ZEROED, PKC_SHARED_SECRET_ZEROED,
};
use crate::dm::clusters::time_sync::UtcTime;
use crate::error::{Error, ErrorCode};
use crate::fabric::Fabric;
use crate::tlv::{Optional, TLVElement, TLVTag, TLVWrite};
use crate::utils::init::{init, Init};
use crate::utils::storage::WriteBuf;

pub const CASE_RANDOM_LEN: usize = 32;

pub const CASE_RESUMPTION_ID_LEN: usize = 16;

pub const CASE_SESSION_KEYS_LEN: usize = AEAD_CANON_KEY_LEN * 3;

// TBEData2_Nonce per spec: "NCASE_Sigma2N"
const SIGMA2_NONCE: AeadNonceRef = AeadNonceRef::new(&[
    0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x32, 0x4e,
]);

// TBEData3_Nonce per spec: "NCASE_Sigma3N"
const SIGMA3_NONCE: AeadNonceRef = AeadNonceRef::new(&[
    0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x33, 0x4e,
]);

canon!(
    CASE_RANDOM_LEN,
    CASE_RANDOM_ZEROED,
    CaseRandom,
    CaseRandomRef
);
canon!(
    CASE_RESUMPTION_ID_LEN,
    CASE_RESUMPTION_ID_ZEROED,
    CaseResumptionId,
    CaseResumptionIdRef
);
canon!(
    CASE_SESSION_KEYS_LEN,
    CASE_SESSION_KEYS_ZEROED,
    CaseSessionKeys,
    CaseSessionKeysRef
);

/// The CASE protocol handler type used during the CASE handshake
pub struct CaseP<'a, C: Crypto + 'a> {
    /// The peer's session ID
    peer_sessid: u16,
    /// The local session ID
    local_sessid: u16,
    /// The local fabric index for this session
    local_fabric_idx: u8,
    /// The ECDH Shared Secret
    shared_secret: CanonPkcSharedSecret,
    /// Our ephemeral public key
    our_pub_key: CanonPkcPublicKey,
    /// The peer's ephemeral public key
    peer_pub_key: CanonPkcPublicKey,
    /// The Transcript Hash
    tt: Optional<C::Hash<'a>>,
}

impl<'a, C: Crypto + 'a> CaseP<'a, C> {
    /// Create a new `CaseSession` instance
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            peer_sessid: 0,
            local_sessid: 0,
            local_fabric_idx: 0,
            shared_secret: PKC_SHARED_SECRET_ZEROED,
            our_pub_key: PKC_PUBLIC_KEY_ZEROED,
            peer_pub_key: PKC_PUBLIC_KEY_ZEROED,
            tt: Optional::none(),
        }
    }

    /// Return an in-place initializer for `CaseSession`
    pub fn init() -> impl Init<Self> {
        init!(Self {
            peer_sessid: 0,
            local_sessid: 0,
            local_fabric_idx: 0,
            shared_secret <- CanonPkcSharedSecret::init(),
            our_pub_key <- CanonPkcPublicKey::init(),
            peer_pub_key <- CanonPkcPublicKey::init(),
            tt <- Optional::init_none(),
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn start(
        &mut self,
        crypto: &'a C,
        peer_sessid: u16,
        local_sessid: u16,
        local_fabric_idx: u8,
        peer_pub_key: CanonPkcPublicKeyRef<'_>,
        request: &[u8],
        our_random_out: &mut CaseRandom,
        resumption_id_out: &mut CaseResumptionId,
        tt_hash_out: &mut Hash,
    ) -> Result<(), Error> {
        self.peer_sessid = peer_sessid;
        self.local_sessid = local_sessid;
        self.local_fabric_idx = local_fabric_idx;

        self.peer_pub_key.load(peer_pub_key);

        let peer_pub_key = crypto.pub_key(peer_pub_key)?;

        // Create an ephemeral EC secret key
        let secret_key = crypto.generate_secret_key()?;

        secret_key.pub_key()?.write_canon(&mut self.our_pub_key)?;

        // Derive the Shared Secret
        secret_key.derive_shared_secret(&peer_pub_key, &mut self.shared_secret)?;
        //        println!("Derived secret: {:x?} len: {}", secret, len);

        let mut rand = crypto.rand()?;

        rand.fill_bytes(our_random_out.access_mut());
        rand.fill_bytes(resumption_id_out.access_mut());

        self.tt = Optional::some(crypto.hash()?);
        self.update_tt(request)?;

        self.current_tt_hash(tt_hash_out)?;

        Ok(())
    }

    /// Initialize the CASE initiator state for Sigma1.
    ///
    /// Generates ephemeral keypair, initiator random, and destination ID.
    /// Returns the ephemeral secret key — caller (`CaseInitiator`) retains it
    /// for ECDH during `process_sigma2`, matching the PASE pattern where
    /// initiator-specific state lives on `PaseInitiator`, not on `Spake2P`.
    ///
    /// The transcript hash is initialized but left empty; the caller is responsible
    /// for feeding the serialized Sigma1 TLV bytes via `update_tt`.
    pub fn start_initiator(
        &mut self,
        crypto: &'a C,
        fabric: &Fabric,
        peer_node_id: u64,
        local_sessid: u16,
        initiator_random_out: &mut CaseRandom,
        destination_id_out: &mut Hash,
    ) -> Result<C::SecretKey<'a>, Error> {
        self.local_sessid = local_sessid;
        self.local_fabric_idx = fabric.fab_idx().get();

        // Create an ephemeral EC secret key
        let secret_key = crypto.generate_secret_key()?;
        secret_key.pub_key()?.write_canon(&mut self.our_pub_key)?;

        // Generate initiator random
        let mut rand = crypto.rand()?;
        rand.fill_bytes(initiator_random_out.access_mut());

        // Compute the destination ID for the peer node
        fabric.compute_dest_id(
            crypto,
            initiator_random_out.access(),
            peer_node_id,
            destination_id_out,
        )?;

        // Initialize transcript hash; caller feeds Sigma1 TLV bytes in via update_tt
        self.tt = Optional::some(crypto.hash()?);

        Ok(secret_key)
    }

    /// Decrypt the Sigma2 TBE payload.
    ///
    /// Performs ECDH, derives S2K, updates the transcript hash with raw Sigma2,
    /// and decrypts TBE2 in-place. Symmetric with `sigma3_decrypt`.
    #[allow(clippy::too_many_arguments)]
    pub fn sigma2_decrypt(
        &mut self,
        crypto: &'a C,
        fabric: &Fabric,
        secret_key: &C::SecretKey<'a>,
        raw_sigma2_payload: &[u8],
        peer_random: CaseRandomRef<'_>,
        peer_sessid: u16,
        peer_eph_pub_key: CanonPkcPublicKeyRef<'_>,
        encrypted2: &mut [u8],
    ) -> Result<usize, Error> {
        self.peer_sessid = peer_sessid;
        self.peer_pub_key.load(peer_eph_pub_key);

        // ECDH: derive shared secret using the initiator's retained secret key
        let peer_pub_key_obj = crypto.pub_key(peer_eph_pub_key)?;
        secret_key.derive_shared_secret(&peer_pub_key_obj, &mut self.shared_secret)?;

        // Get transcript hash (Sigma1 only at this point)
        let mut tt_hash = HASH_ZEROED;
        self.current_tt_hash(&mut tt_hash)?;

        // Derive S2K
        let mut sigma2_key = AEAD_KEY_ZEROED;
        self.compute_sigma2_key(
            crypto,
            fabric.ipk().op_key(),
            peer_random,
            peer_eph_pub_key,
            tt_hash.reference(),
            &mut sigma2_key,
        )?;

        // Add raw Sigma2 to transcript hash
        self.update_tt(raw_sigma2_payload)?;

        // Decrypt TBE2
        let encrypted_len = encrypted2.len();
        let mut cypher = crypto.aead()?;
        cypher.decrypt_in_place(sigma2_key.reference(), SIGMA2_NONCE, &[], encrypted2)?;

        Ok(encrypted_len - crypto::AEAD_TAG_LEN)
    }

    pub fn local_fabric_idx(&self) -> u8 {
        self.local_fabric_idx
    }

    pub fn peer_sessid(&self) -> u16 {
        self.peer_sessid
    }

    pub fn local_sessid(&self) -> u16 {
        self.local_sessid
    }

    pub fn our_pub_key(&self) -> CanonPkcPublicKeyRef<'_> {
        self.our_pub_key.reference()
    }

    pub fn update_tt(&mut self, data: &[u8]) -> Result<(), Error> {
        unwrap!(self.tt.as_opt_mut()).update(data)
    }

    pub fn current_tt_hash(&mut self, out: &mut Hash) -> Result<(), Error> {
        unwrap!(self.tt.as_opt_mut()).finish_current(out)
    }

    /// Get the Sigma2 encrypted data
    ///
    /// # Arguments
    /// - `fabric` - The local fabric
    /// - `our_random` - Our random value
    /// - `our_hash` - Our transcript hash
    /// - `signature` - Our signature
    /// - `resumption_id` - The resumption ID
    /// - `out` - The output buffer to write the encrypted data to
    ///
    /// # Returns
    /// - `Ok(usize)` - The length of the encrypted data written to `out`
    /// - `Err(Error)` - If an error occurred during the process
    #[allow(clippy::too_many_arguments)]
    pub fn sigma2_encrypt(
        &self,
        crypto: &C,
        fabric: &Fabric,
        our_random: CaseRandomRef<'_>,
        our_hash: HashRef<'_>,
        signature: CanonPkcSignatureRef<'_>,
        resumption_id: CaseResumptionIdRef<'_>,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        let mut sigma2_key = AEAD_KEY_ZEROED;
        self.compute_sigma2_key(
            crypto,
            fabric.ipk().op_key(),
            our_random,
            self.our_pub_key.reference(),
            our_hash,
            &mut sigma2_key,
        )?;

        let mut tw = WriteBuf::new(out);

        tw.start_struct(&TLVTag::Anonymous)?;
        tw.str(&TLVTag::Context(1), fabric.noc())?;
        if !fabric.icac().is_empty() {
            tw.str(&TLVTag::Context(2), fabric.icac())?
        };
        tw.str(&TLVTag::Context(3), signature.access())?;
        tw.str(&TLVTag::Context(4), resumption_id.access())?;
        tw.end_container()?;

        //println!("TBE is {:x?}", write_buf.as_borrow_slice());
        //        let nonce = GenericArray::from_slice(&nonce);
        //        type AesCcm = Ccm<Aes128, U16, U13>;
        //        let cipher = AesCcm::new(GenericArray::from_slice(key));

        tw.append(AEAD_TAG_ZEROED.access())?;
        let cipher_text = tw.as_mut_slice();

        let mut cypher = crypto.aead()?;

        cypher.encrypt_in_place(
            sigma2_key.reference(),
            SIGMA2_NONCE,
            &[],
            cipher_text,
            cipher_text.len() - AEAD_TAG_LEN,
        )?;

        Ok(tw.as_slice().len())
    }

    /// Get the Sigma2 signature
    ///
    /// # Arguments
    /// - `fabric` - The local fabric
    /// - `tmp_buf` - A temporary buffer for constructing the signature
    /// - `signature` - The output buffer to write the signature to
    ///
    /// # Returns
    /// - `Ok(())` - If the signature was successfully generated
    /// - `Err(Error)` - If an error occurred during the process
    pub fn compute_sigma2_signature(
        &self,
        crypto: &C,
        fabric: &Fabric,
        tmp_buf: &mut [u8],
        signature: &mut CanonPkcSignature,
    ) -> Result<(), Error> {
        let mut tw = WriteBuf::new(tmp_buf);

        tw.start_struct(&TLVTag::Anonymous)?;
        tw.str(&TLVTag::Context(1), fabric.noc())?;
        if !fabric.icac().is_empty() {
            tw.str(&TLVTag::Context(2), fabric.icac())?;
        }
        tw.str(&TLVTag::Context(3), self.our_pub_key.access())?;
        tw.str(&TLVTag::Context(4), self.peer_pub_key.access())?;
        tw.end_container()?;
        //println!("TBS is {:x?}", write_buf.as_borrow_slice());

        let fabric_secret = crypto.secret_key(fabric.secret_key())?;
        fabric_secret.sign(tw.as_slice(), signature)?;

        Ok(())
    }

    /// Get the Sigma2 key
    ///
    /// # Arguments
    /// - `ipk` - The IPK
    /// - `responder_random` - The responder's random value
    /// - `responder_eph_pub_key` - The responder's ephemeral public key
    /// - `tt_hash` - The transcript hash
    /// - `key` - The output buffer to write the Sigma2 key to
    ///
    /// # Returns
    /// - `Ok(())` - If the Sigma2 key was successfully derived
    /// - `Err(Error)` - If an error occurred during the process
    fn compute_sigma2_key(
        &self,
        crypto: &C,
        ipk: CanonAeadKeyRef<'_>,
        responder_random: CaseRandomRef<'_>,
        responder_eph_pub_key: CanonPkcPublicKeyRef<'_>,
        tt_hash: HashRef<'_>,
        key: &mut CanonAeadKey,
    ) -> Result<(), Error> {
        const S2K_INFO: [u8; 6] = [0x53, 0x69, 0x67, 0x6d, 0x61, 0x32];

        let mut salt = CryptoSensitive::<
            { AEAD_CANON_KEY_LEN + 32 + PKC_CANON_PUBLIC_KEY_LEN + HASH_LEN },
        >::new();

        let salt_access: &mut [u8] = salt.access_mut();
        salt_access[..AEAD_CANON_KEY_LEN].copy_from_slice(ipk.access());
        salt_access[AEAD_CANON_KEY_LEN..][..32].copy_from_slice(responder_random.access());
        salt_access[AEAD_CANON_KEY_LEN..][32..][..PKC_CANON_PUBLIC_KEY_LEN]
            .copy_from_slice(responder_eph_pub_key.access());
        salt_access[AEAD_CANON_KEY_LEN..][32..][PKC_CANON_PUBLIC_KEY_LEN..]
            .copy_from_slice(tt_hash.access());

        crypto
            .kdf()?
            .expand(
                salt.access(),
                self.shared_secret.reference(),
                &S2K_INFO,
                key,
            )
            .map_err(|_x| ErrorCode::InvalidData)?;
        //        println!("Sigma2Key: key: {:x?}", key);

        Ok(())
    }

    /// Validate the certificate chain
    ///
    /// # Arguments
    /// - `crypto` - The crypto provider
    /// - `time` - The current UTC time for validating certificate validity periods
    /// - `fabric` - The local fabric
    /// - `noc` - The Node Operational Certificate
    /// - `icac` - The Intermediate Certificate Authority Certificate (optional)
    /// - `tmp_buf` - A temporary buffer for certificate validation
    ///
    /// # Returns
    /// - `Ok(())` - If the certificate chain is valid
    /// - `Err(Error)` - If the certificate chain is invalid
    pub fn validate_certs(
        &self,
        crypto: &C,
        time: UtcTime,
        fabric: &Fabric,
        noc: &CertRef,
        icac: Option<&CertRef>,
        tmp_buf: &mut [u8],
    ) -> Result<(), Error> {
        let mut verifier = noc.verify_chain_start(crypto, time);

        if fabric.fabric_id() != noc.get_fabric_id()? {
            Err(ErrorCode::Invalid)?;
        }

        if let Some(icac) = icac {
            // If ICAC is present handle it
            if let Ok(fid) = icac.get_fabric_id() {
                if fid != fabric.fabric_id() {
                    Err(ErrorCode::Invalid)?;
                }
            }

            verifier = verifier.add_cert(icac, tmp_buf)?;
        }

        verifier
            .add_cert(&CertRef::new(TLVElement::new(fabric.root_ca())), tmp_buf)?
            .finalise(tmp_buf)?;

        Ok(())
    }

    /// Validate the Sigma3 signature
    ///
    /// # Arguments
    /// - `noc` - The Node Operational Certificate as raw bytes
    /// - `icac` - The Intermediate Certificate Authority Certificate as raw bytes (optional)
    /// - `noc_cert` - The Node Operational Certificate reference
    /// - `signature` - The signature to validate
    /// - `tmp_buf` - A temporary buffer for signature validation
    ///
    /// # Returns
    /// - `Ok(())` - If the signature is valid
    /// - `Err(Error)` - If the signature is invalid
    pub fn validate_peer_tbs_signature(
        &self,
        crypto: &C,
        noc: &[u8],
        icac: Option<&[u8]>,
        noc_cert: &CertRef,
        signature: CanonPkcSignatureRef<'_>,
        tmp_buf: &mut [u8],
    ) -> Result<(), Error> {
        let mut tw = WriteBuf::new(tmp_buf);

        tw.start_struct(&TLVTag::Anonymous)?;
        tw.str(&TLVTag::Context(1), noc)?;
        if let Some(icac) = icac {
            tw.str(&TLVTag::Context(2), icac)?;
        }
        tw.str(&TLVTag::Context(3), self.peer_pub_key.access())?;
        tw.str(&TLVTag::Context(4), self.our_pub_key.access())?;
        tw.end_container()?;

        let pub_key = crypto.pub_key(CanonPkcPublicKeyRef::try_new(noc_cert.pubkey()?)?)?;
        if !pub_key.verify(tw.as_slice(), signature)? {
            Err(ErrorCode::Invalid)?;
        }

        Ok(())
    }

    /// Get the session keys
    ///
    /// # Arguments
    /// - `ipk` - The IPK
    /// - `key` - The output buffer to write the session keys to
    ///
    /// # Returns
    /// - `Ok(())` - If the session keys were successfully derived
    /// - `Err(Error)` - If an error occurred during the process
    pub fn compute_session_keys(
        &mut self,
        crypto: &C,
        ipk: CanonAeadKeyRef<'_>,
        keys: &mut CaseSessionKeys,
    ) -> Result<(), Error> {
        const SEKEYS_INFO: [u8; 11] = [
            0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x73,
        ];

        let mut tt_hash = HASH_ZEROED;
        self.current_tt_hash(&mut tt_hash)?;

        let mut salt = CryptoSensitive::<{ AEAD_CANON_KEY_LEN + HASH_LEN }>::new();

        let salt_access: &mut [u8] = salt.access_mut();
        salt_access[..AEAD_CANON_KEY_LEN].copy_from_slice(ipk.access());
        salt_access[AEAD_CANON_KEY_LEN..].copy_from_slice(tt_hash.access());

        //        println!("Session Key: salt: {:x?}, len: {}", salt, salt.len());

        crypto
            .kdf()?
            .expand(
                salt.access(),
                self.shared_secret.reference(),
                &SEKEYS_INFO,
                keys,
            )
            .map_err(|_x| ErrorCode::InvalidData)?;
        //        println!("Session Key: key: {:x?}", key);

        Ok(())
    }

    /// Compute the Sigma3 TBSData3 and sign it with the fabric's operational secret key.
    ///
    /// TBSData3 structure (TLV):
    /// - Tag 1: initiator NOC
    /// - Tag 2: initiator ICAC (optional — omitted if empty)
    /// - Tag 3: initiator ephemeral public key (sender)
    /// - Tag 4: responder ephemeral public key (receiver)
    ///
    /// # Arguments
    /// - `crypto` - The crypto provider
    /// - `fabric` - The local fabric
    /// - `tmp_buf` - A temporary buffer for constructing the TBS data
    /// - `signature` - The output buffer to write the signature to
    ///
    /// # Returns
    /// - `Ok(())` - If the signature was successfully generated
    /// - `Err(Error)` - If an error occurred during the process
    pub fn compute_sigma3_signature(
        &self,
        crypto: &C,
        fabric: &Fabric,
        tmp_buf: &mut [u8],
        signature: &mut CanonPkcSignature,
    ) -> Result<(), Error> {
        let mut tw = WriteBuf::new(tmp_buf);

        tw.start_struct(&TLVTag::Anonymous)?;
        tw.str(&TLVTag::Context(1), fabric.noc())?;
        if !fabric.icac().is_empty() {
            tw.str(&TLVTag::Context(2), fabric.icac())?;
        }
        tw.str(&TLVTag::Context(3), self.our_pub_key.access())?;
        tw.str(&TLVTag::Context(4), self.peer_pub_key.access())?;
        tw.end_container()?;

        let fabric_secret = crypto.secret_key(fabric.secret_key())?;
        fabric_secret.sign(tw.as_slice(), signature)?;

        Ok(())
    }

    /// Encrypt the Sigma3 TBE3 payload with S3K.
    ///
    /// Builds the TBE3 plaintext (NOC + ICAC + signature), appends an AEAD tag slot,
    /// and encrypts in-place. Returns the total ciphertext length (plaintext + tag).
    ///
    /// TBE3 plaintext structure (TLV):
    /// - Tag 1: initiator NOC
    /// - Tag 2: initiator ICAC (optional — omitted if empty)
    /// - Tag 3: signature
    ///
    /// # Arguments
    /// - `crypto` - The crypto provider
    /// - `fabric` - The local fabric
    /// - `signature` - The Sigma3 signature
    /// - `out` - The output buffer to write the encrypted data to
    ///
    /// # Returns
    /// - `Ok(usize)` - The length of the encrypted data written to `out`
    /// - `Err(Error)` - If an error occurred during the process
    pub fn sigma3_encrypt(
        &mut self,
        crypto: &C,
        fabric: &Fabric,
        signature: CanonPkcSignatureRef<'_>,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        let mut sigma3_key = AEAD_KEY_ZEROED;
        self.compute_sigma3_key(crypto, fabric.ipk().op_key(), &mut sigma3_key)?;

        let mut tw = WriteBuf::new(out);

        tw.start_struct(&TLVTag::Anonymous)?;
        tw.str(&TLVTag::Context(1), fabric.noc())?;
        if !fabric.icac().is_empty() {
            tw.str(&TLVTag::Context(2), fabric.icac())?;
        }
        tw.str(&TLVTag::Context(3), signature.access())?;
        tw.end_container()?;

        tw.append(AEAD_TAG_ZEROED.access())?;
        let cipher_text = tw.as_mut_slice();

        let mut cypher = crypto.aead()?;

        cypher.encrypt_in_place(
            sigma3_key.reference(),
            SIGMA3_NONCE,
            &[],
            cipher_text,
            cipher_text.len() - AEAD_TAG_LEN,
        )?;

        Ok(tw.as_slice().len())
    }

    /// Get the Sigma3 decrypted data
    ///
    /// # Arguments
    /// - `ipk` - The IPK
    /// - `encrypted` - The encrypted data to decrypt
    ///
    /// # Returns
    /// - `Ok(usize)` - The length of the decrypted data
    /// - `Err(Error)` - If an error occurred during the process
    pub fn sigma3_decrypt(
        &mut self,
        crypto: &C,
        ipk: CanonAeadKeyRef<'_>,
        encrypted: &mut [u8],
    ) -> Result<usize, Error> {
        let mut sigma3_key = AEAD_KEY_ZEROED;
        self.compute_sigma3_key(crypto, ipk, &mut sigma3_key)?;
        // println!("Sigma3 Key: {:x?}", sigma3_key);

        let encrypted_len = encrypted.len();

        let mut cypher = crypto.aead()?;

        cypher.decrypt_in_place(sigma3_key.reference(), SIGMA3_NONCE, &[], encrypted)?;
        Ok(encrypted_len - crypto::AEAD_TAG_LEN)
    }

    /// Get the Sigma3 key
    ///
    /// # Arguments
    /// - `ipk` - The IPK
    /// - `key` - The output buffer to write the Sigma3 key to
    ///
    /// # Returns
    /// - `Ok(())` - If the Sigma3 key was successfully derived
    /// - `Err(Error)` - If an error occurred during the process
    fn compute_sigma3_key(
        &mut self,
        crypto: &C,
        ipk: CanonAeadKeyRef<'_>,
        key: &mut CanonAeadKey,
    ) -> Result<(), Error> {
        const S3K_INFO: [u8; 6] = [0x53, 0x69, 0x67, 0x6d, 0x61, 0x33];

        let mut tt_hash = HASH_ZEROED;
        self.current_tt_hash(&mut tt_hash)?;

        let mut salt = CryptoSensitive::<{ AEAD_CANON_KEY_LEN + HASH_LEN }>::new();

        let salt_access: &mut [u8] = salt.access_mut();
        salt_access[..AEAD_CANON_KEY_LEN].copy_from_slice(ipk.access());
        salt_access[AEAD_CANON_KEY_LEN..].copy_from_slice(tt_hash.access());

        //        println!("Sigma3Key: salt: {:x?}, len: {}", salt, salt.len());

        crypto
            .kdf()?
            .expand(
                salt.access(),
                self.shared_secret.reference(),
                &S3K_INFO,
                key,
            )
            .map_err(|_x| ErrorCode::InvalidData)?;
        //        println!("Sigma3Key: key: {:x?}", key);

        Ok(())
    }
}