crypt_guard 3.0.1

CryptGuard is a post-quantum cryptography framework with NIST FIPS 203/204/205 (ML-KEM, ML-DSA, SLH-DSA) plus legacy Kyber/Falcon/Dilithium, combined with AES and XChaCha20.
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
//! Hub module: `Kyber<P, K, D, C>` four-axis typestate, KEM variant traits, and cipher markers.
//!
//! # Responsibility scope
//! This module is the renamed internal path of the hub (was `src/core/kyber/`).
//! It owns the generic `Kyber<ProcessStatus, KyberSize, ContentStatus, AlgorithmParam>`
//! struct, the content-gated encrypt/decrypt capability traits (Phase 3),
//! and the legacy `KyberFunctions` trait (preserved for the legacy-pqclean path).
//!
//! Phase 3 adds:
//! - [`EncryptData`] / [`EncryptText`] / [`EncryptFile`] — implemented only for
//!   the matching `Kyber<Encryption, _, ContentStatus, _>`
//! - [`DecryptData`] / [`DecryptText`] / [`DecryptFile`] — implemented only for
//!   the matching `Kyber<Decryption, _, ContentStatus, _>`
//! - `MlKem512`, `MlKem768`, `MlKem1024` as primary size markers (backed by the
//!   new `KemBackend` trait); `Kyber512/768/1024` are deprecated aliases.
//!
//! The actual per-cipher capability impls live in `cipher_impls.rs`, wired once
//! over the `SymmetricCipher` abstraction (see [`cipher_impls`]).
//!
//! # Key types exported
//! - [`Kyber`] — four-axis typestate struct
//! - [`KyberFunctions`] — legacy encrypt/decrypt trait (legacy-pqclean path)
//! - [`EncryptData`] / [`EncryptText`] / [`EncryptFile`] — Phase 3 encrypt-only traits
//! - [`DecryptData`] / [`DecryptText`] / [`DecryptFile`] — Phase 3 decrypt-only traits
//! - [`KyberSizeVariant`] / [`KyberVariant`] — size-dispatch trait and enum
//! - [`Kyber512`], [`Kyber768`], [`Kyber1024`] — deprecated legacy size markers
//! - [`MlKem512`], [`MlKem768`], [`MlKem1024`] — FIPS primary size markers
//!
//! # Concurrency
//! `Kyber<P,K,D,C>` holds only `Vec<u8>` key material and `PhantomData`; all
//! methods are `&self` or `&mut self`. No shared state.
//!
//! # Feature gate
//! The `key_controler` sub-module is gated behind `legacy-pqclean`.
//! The `cipher_impls` module is compiled unconditionally (the ml-kem path works
//! without legacy-pqclean).
//!
//! # Examples
//! ```text
//! use crypt_guard::core::hub::{Kyber, MlKem768, EncryptData};
//! use crypt_guard::markers::{Encryption, Data};
//! // Kyber<Encryption, MlKem768, Data, _> implements EncryptData.
//! // Kyber<Decryption, MlKem768, Data, _> does NOT implement EncryptData — compile error.
//! ```

// Phase 3 cipher impls generated by impl_kyber_cipher!
pub mod cipher_impls;
pub mod macros;

use crate::error::CryptError;
use crate::protocol::Envelope;
use std::{marker::PhantomData, path::PathBuf};
use zeroize::Zeroize;

// Re-export all shared ZST markers from the thin markers shim.
pub use crate::markers::{
    AesCtr, AesGcmSiv, AesXts, Data, Decryption, Encryption, Files, Message, XChaCha20,
    XChaCha20Poly1305, AES,
};

// ── Legacy KyberFunctions trait ────────────────────────────────────────────────

/// Legacy encrypt/decrypt trait used by the `legacy-pqclean` path.
///
/// # Description
/// The six impls for this trait live in `src/legacy/kyber_crypto/`. They dispatch
/// KEM through the pqcrypto-backed `KeyControlVariant`. This trait is preserved for
/// source compatibility; new code should use `EncryptFunctions` / `DecryptFunctions`.
pub trait KyberFunctions {
    /// Encrypts a file at a given path with a passphrase, returning the encrypted data and nonce.
    fn encrypt_file(
        &mut self,
        path: PathBuf,
        passphrase: &str,
    ) -> Result<(Vec<u8>, Vec<u8>), CryptError>;
    /// Encrypts a message with a passphrase, returning the encrypted data and nonce.
    fn encrypt_msg(
        &mut self,
        message: &str,
        passphrase: &str,
    ) -> Result<(Vec<u8>, Vec<u8>), CryptError>;
    /// Encrypts data with a passphrase, returning the encrypted data and nonce.
    fn encrypt_data(
        &mut self,
        data: Vec<u8>,
        passphrase: &str,
    ) -> Result<(Vec<u8>, Vec<u8>), CryptError>;
    /// Decrypts a file at a given path with a passphrase and ciphertext, returning the decrypted data.
    fn decrypt_file(
        &self,
        path: PathBuf,
        passphrase: &str,
        ciphertext: Vec<u8>,
    ) -> Result<Vec<u8>, CryptError>;
    /// Decrypts a message with a passphrase and ciphertext, returning the decrypted data.
    fn decrypt_msg(
        &self,
        message: Vec<u8>,
        passphrase: &str,
        ciphertext: Vec<u8>,
    ) -> Result<Vec<u8>, CryptError>;
    /// Decrypts data with a passphrase and ciphertext, returning the decrypted data.
    fn decrypt_data(
        &self,
        data: Vec<u8>,
        passphrase: &str,
        ciphertext: Vec<u8>,
    ) -> Result<Vec<u8>, CryptError>;
}

// ── Phase 3: content-gated capability traits ──────────────────────────────────
//
// The four-axis typestate is now genuinely enforced on the content axis: each
// capability trait is implemented ONLY for the matching `ContentStatus` marker, so
// the available methods follow the marker. Calling `encrypt_file` on a
// `Kyber<_, _, Message, _>` is a compile error (`E0599`), not a silent runtime path.
//
//   Encryption + Data    => EncryptData::encrypt_data
//   Encryption + Message => EncryptText::encrypt_msg
//   Encryption + Files   => EncryptFile::encrypt_file
//   Decryption + Data    => DecryptData::decrypt_data
//   Decryption + Message => DecryptText::decrypt_msg
//   Decryption + Files   => DecryptFile::decrypt_file
//
// Every method returns / consumes an authenticated [`Envelope`]; the nonce lives
// inside the envelope and is bound into the AEAD associated data — callers never
// handle it separately.

/// Encrypt arbitrary bytes into an authenticated [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Encryption, K, Data, C>`. The content (`Data`) and
/// process (`Encryption`) markers are both enforced: this method does not exist on
/// `Message`/`Files` instances or on any `Decryption` instance.
///
/// # Errors
/// - [`CryptError::EncapsulationError`]: KEM encapsulation failed.
/// - [`CryptError::EncryptionFailed`]: symmetric encryption failed.
///
/// # Examples
/// ```text
/// use crypt_guard::core::hub::{Kyber, MlKem768, EncryptData};
/// use crypt_guard::markers::{Encryption, Data, XChaCha20Poly1305};
/// let mut enc = Kyber::<Encryption, MlKem768, Data, XChaCha20Poly1305>::new(pk, None).unwrap();
/// let envelope = enc.encrypt_data(b"bytes", "passphrase").unwrap();
/// ```
pub trait EncryptData {
    /// Encrypt `data` and return an authenticated envelope.
    ///
    /// # Arguments
    /// - `data` (`&[u8]`): plaintext bytes.
    /// - `passphrase` (`&str`): reserved for password-bound key schedules; unused on the AEAD path.
    ///
    /// # Returns
    /// `Ok(Envelope)` with the header, KEM ciphertext, nonce, and ciphertext.
    fn encrypt_data(&mut self, data: &[u8], passphrase: &str) -> Result<Envelope, CryptError>;
}

/// Encrypt a UTF-8 string message into an authenticated [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Encryption, K, Message, C>`.
///
/// # Errors
/// See [`EncryptData::encrypt_data`].
pub trait EncryptText {
    /// Encrypt `message` and return an authenticated envelope.
    ///
    /// # Arguments
    /// - `message` (`&str`): plaintext message.
    /// - `passphrase` (`&str`): reserved for password-bound key schedules.
    fn encrypt_msg(&mut self, message: &str, passphrase: &str) -> Result<Envelope, CryptError>;
}

/// Encrypt the contents of a file into an authenticated [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Encryption, K, Files, C>`.
///
/// # Errors
/// - [`CryptError::FileNotFound`]: the source file does not exist.
/// - Plus the errors of [`EncryptData::encrypt_data`].
pub trait EncryptFile {
    /// Read `path`, encrypt its contents, and return an authenticated envelope.
    ///
    /// # Arguments
    /// - `path` (`PathBuf`): path to the source file.
    /// - `passphrase` (`&str`): reserved for password-bound key schedules.
    fn encrypt_file(&mut self, path: PathBuf, passphrase: &str) -> Result<Envelope, CryptError>;
}

/// Decrypt the byte ciphertext carried by an [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Decryption, K, Data, C>`. The nonce is read from the
/// envelope; the caller does not supply it.
///
/// # Errors
/// - [`CryptError::DecapsulationError`]: KEM decapsulation failed.
/// - [`CryptError::AuthenticationFailed`]: AEAD tag or HMAC mismatch.
/// - [`CryptError::DecryptionFailed`]: symmetric decryption failed.
///
/// # Examples
/// ```text
/// use crypt_guard::core::hub::{Kyber, MlKem768, DecryptData};
/// use crypt_guard::markers::{Decryption, Data, XChaCha20Poly1305};
/// let dec = Kyber::<Decryption, MlKem768, Data, XChaCha20Poly1305>::new(sk, None).unwrap();
/// let plaintext = dec.decrypt_data(&envelope.ciphertext, "passphrase", &envelope).unwrap();
/// ```
pub trait DecryptData {
    /// Decrypt and authenticate the envelope ciphertext.
    ///
    /// # Arguments
    /// - `data` (`&[u8]`): the ciphertext bytes (typically `envelope.ciphertext`).
    /// - `passphrase` (`&str`): reserved for password-bound key schedules.
    /// - `envelope` (`&Envelope`): the authenticated envelope.
    fn decrypt_data(
        &self,
        data: &[u8],
        passphrase: &str,
        envelope: &Envelope,
    ) -> Result<Vec<u8>, CryptError>;
}

/// Decrypt the message ciphertext carried by an [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Decryption, K, Message, C>`.
///
/// # Errors
/// See [`DecryptData::decrypt_data`].
pub trait DecryptText {
    /// Decrypt and authenticate the envelope ciphertext (message variant).
    ///
    /// # Arguments
    /// - `message` (`&[u8]`): the ciphertext bytes.
    /// - `passphrase` (`&str`): reserved for password-bound key schedules.
    /// - `envelope` (`&Envelope`): the authenticated envelope.
    fn decrypt_msg(
        &self,
        message: &[u8],
        passphrase: &str,
        envelope: &Envelope,
    ) -> Result<Vec<u8>, CryptError>;
}

/// Decrypt the file ciphertext carried by an [`Envelope`].
///
/// # Description
/// Implemented only for `Kyber<Decryption, K, Files, C>`.
///
/// # Errors
/// - [`CryptError::FileNotFound`]: the encrypted file does not exist.
/// - Plus the errors of [`DecryptData::decrypt_data`].
pub trait DecryptFile {
    /// Decrypt and authenticate the envelope ciphertext (file variant).
    ///
    /// # Arguments
    /// - `path` (`PathBuf`): path to the encrypted file (presence is required).
    /// - `passphrase` (`&str`): reserved for password-bound key schedules.
    /// - `envelope` (`&Envelope`): the authenticated envelope.
    fn decrypt_file(
        &self,
        path: PathBuf,
        passphrase: &str,
        envelope: &Envelope,
    ) -> Result<Vec<u8>, CryptError>;
}

// ── KyberSize trait & variant enum ────────────────────────────────────────────

/// Runtime identifier for the KEM size parameter.
///
/// # Description
/// Returned by [`KyberSizeVariant::variant`]. Used by legacy dispatch code to
/// select the correct `KeyControlVariant` arm. The new FIPS path uses
/// [`KyberSizeVariant::kem_id`] instead.
pub enum KyberVariant {
    /// Corresponds to ML-KEM-512 / Kyber-512.
    Kyber512,
    /// Corresponds to ML-KEM-768 / Kyber-768.
    Kyber768,
    /// Corresponds to ML-KEM-1024 / Kyber-1024.
    Kyber1024,
}

/// Trait implemented by KEM size marker types.
///
/// # Description
/// Every KEM size marker (both legacy `Kyber512/768/1024` and new `MlKem512/768/1024`)
/// implements this trait. It provides a runtime enum for legacy dispatch and a
/// [`crate::kem::backend::KemId`] for envelope headers.
pub trait KyberSizeVariant {
    /// Returns the runtime KEM size variant (for legacy dispatch).
    fn variant() -> KyberVariant;
    /// Returns the KEM algorithm identifier for envelope headers.
    fn kem_id() -> crate::kem::backend::KemId;
}

// ── Legacy size markers ────────────────────────────────────────────────────────

/// Legacy KEM size marker: Kyber-512.
///
/// Deprecated in favour of [`MlKem512`].
#[deprecated(note = "Use MlKem512 (FIPS 203)")]
pub struct Kyber512;

/// Legacy KEM size marker: Kyber-768.
///
/// Deprecated in favour of [`MlKem768`].
#[deprecated(note = "Use MlKem768 (FIPS 203)")]
pub struct Kyber768;

/// Legacy KEM size marker: Kyber-1024.
///
/// Deprecated in favour of [`MlKem1024`].
#[deprecated(note = "Use MlKem1024 (FIPS 203)")]
pub struct Kyber1024;

#[allow(deprecated)]
impl KyberSizeVariant for Kyber512 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber512
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem512
    }
}

#[allow(deprecated)]
impl KyberSizeVariant for Kyber768 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber768
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem768
    }
}

#[allow(deprecated)]
impl KyberSizeVariant for Kyber1024 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber1024
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem1024
    }
}

// ── FIPS primary size markers ──────────────────────────────────────────────────

/// Primary KEM size marker: ML-KEM-512 (FIPS 203, security category 1).
///
/// # Description
/// Use this marker instead of the deprecated `Kyber512`.
pub struct MlKem512;

/// Primary KEM size marker: ML-KEM-768 (FIPS 203, security category 3 — recommended).
///
/// # Description
/// Use this marker instead of the deprecated `Kyber768`.
pub struct MlKem768;

/// Primary KEM size marker: ML-KEM-1024 (FIPS 203, security category 5).
///
/// # Description
/// Use this marker instead of the deprecated `Kyber1024`.
pub struct MlKem1024;

impl KyberSizeVariant for MlKem512 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber512
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem512
    }
}

impl KyberSizeVariant for MlKem768 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber768
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem768
    }
}

impl KyberSizeVariant for MlKem1024 {
    fn variant() -> KyberVariant {
        KyberVariant::Kyber1024
    }
    fn kem_id() -> crate::kem::backend::KemId {
        crate::kem::backend::KemId::MlKem1024
    }
}

// ── KyberData ─────────────────────────────────────────────────────────────────

/// Internal state bag holding the key bytes and optional nonce for a `Kyber` instance.
///
/// # Description
/// Holds the public or secret key bytes (depending on the `ProcessStatus` axis) and an
/// optional hex-encoded nonce for nonce-bearing ciphers. The nonce is stored here only
/// so that the legacy `KyberFunctions` path can retrieve it via `get_nonce()`; the new
/// Phase 3 path stores the nonce inside the [`Envelope`] instead.
#[derive(PartialEq, Debug, Clone)]
pub struct KyberData {
    /// Key bytes (public key for encryption, secret key for decryption).
    key: Vec<u8>,
    /// Hex-encoded nonce string; empty if not set.
    nonce: String,
}

impl KyberData {
    /// Returns the key bytes.
    pub fn key(&self) -> Result<Vec<u8>, CryptError> {
        Ok(self.key.to_vec())
    }

    /// Borrow the key bytes without creating a second key buffer.
    ///
    /// This is crate-internal so terminal decrypt sessions can hand the
    /// caller-provided secret key directly to the KEM operation. The public
    /// [`Self::key`] accessor remains cloning for source compatibility.
    pub(crate) fn key_bytes(&self) -> &[u8] {
        &self.key
    }

    /// Clear the key bytes held by a terminal decrypt session.
    ///
    /// This is intentionally crate-internal: a generic `Kyber` can also hold
    /// a public encapsulation key, whose public API and semantics remain
    /// unchanged.
    pub(crate) fn zeroize_key(&mut self) {
        self.key.zeroize();
    }
    /// Returns the nonce string.
    pub fn nonce(&self) -> Result<&str, CryptError> {
        Ok(&self.nonce)
    }
    /// Sets the nonce string.
    pub fn set_nonce(&mut self, nonce: String) -> Result<(), CryptError> {
        self.nonce = nonce;
        Ok(())
    }
    /// Sets the key bytes.
    pub fn set_key(&mut self, key: Vec<u8>) -> Result<(), CryptError> {
        self.key = key;
        Ok(())
    }
}

// ── Kyber<P, K, D, C> ─────────────────────────────────────────────────────────

/// Four-axis typestate struct for KEM + symmetric encryption operations.
///
/// # Description
/// The four type parameters encode:
/// - `ProcessStatus` — `Encryption` or `Decryption` (controls which trait is implemented)
/// - `KyberSize` — KEM size marker (`MlKem512/768/1024` or deprecated `Kyber512/768/1024`)
/// - `ContentStatus` — content kind (`Files`, `Message`, `Data`)
/// - `AlgorithmParam` — symmetric cipher marker
///
/// # Concurrency
/// Each instance holds only owned `Vec<u8>` key material; no shared state.
///
/// # Examples
/// ```text
/// use crypt_guard::core::hub::{Kyber, MlKem768};
/// use crypt_guard::markers::{Encryption, Data, XChaCha20Poly1305};
/// let pk = vec![0u8; 1184]; // placeholder
/// let enc = Kyber::<Encryption, MlKem768, Data, XChaCha20Poly1305>::new(pk, None).unwrap();
/// ```
pub struct Kyber<
    ProcessStatus = Encryption,
    KyberSize = MlKem1024,
    ContentStatus = Files,
    AlgorithmParam = AES,
> where
    KyberSize: KyberSizeVariant,
{
    pub(crate) kyber_data: KyberData,
    /// HMAC output size in bits (256 or 512).
    hmac_size: usize,
    content_state: PhantomData<ContentStatus>,
    kyber_state: PhantomData<KyberSize>,
    algorithm_state: PhantomData<AlgorithmParam>,
    process_state: PhantomData<ProcessStatus>,
}

impl<ProcessStatus, KyberSize: KyberSizeVariant, ContentStatus, AlgorithmParam>
    Kyber<ProcessStatus, KyberSize, ContentStatus, AlgorithmParam>
{
    /// Construct a new `Kyber` instance with key bytes and an optional hex-encoded nonce.
    ///
    /// # Arguments
    /// - `key` (`Vec<u8>`): public key (encryption) or secret key (decryption).
    /// - `nonce` (`Option<String>`): hex-encoded nonce for nonce-bearing ciphers; `None`
    ///   if not applicable (AES-CBC self-embeds its IV; AEAD modes auto-generate).
    ///
    /// # Returns
    /// `Ok(Kyber<...>)`.
    pub fn new(key: Vec<u8>, nonce: Option<String>) -> Result<Self, CryptError> {
        let nonce = nonce.unwrap_or_default();
        Ok(Self {
            kyber_data: KyberData { key, nonce },
            hmac_size: 512,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        })
    }

    /// Returns the key bytes.
    pub fn get_key(&self) -> Result<Vec<u8>, CryptError> {
        self.kyber_data.key()
    }

    /// Clear this instance's owned key bytes.
    ///
    /// Only the decrypt-session owner calls this internal operation after the
    /// KEM operation completes; public-key `Kyber` instances are not changed.
    pub(crate) fn zeroize_key(&mut self) {
        self.kyber_data.zeroize_key();
    }

    /// Returns the hex-encoded nonce string.
    ///
    /// # Description
    /// Returns the nonce set by the encrypt path via `set_nonce`. On the Phase 3
    /// path the nonce lives inside the `Envelope`; this getter is preserved for
    /// the legacy path and for source compatibility.
    pub fn get_nonce(&self) -> Result<&str, CryptError> {
        self.kyber_data.nonce()
    }

    /// Switch HMAC output to SHA-256 (default is SHA-512).
    pub fn hmac_sha256(&mut self) -> Result<(), CryptError> {
        self.hmac_size = 256;
        Ok(())
    }
}

// ── Size-switch methods ───────────────────────────────────────────────────────
// Keep source compatibility: users can call `.kyber768()` etc. on an existing instance.

macro_rules! impl_size_switch {
    ($from:ty => $to:ty, $method:ident, $to_phantom:ty) => {
        // The Kyber512/768/1024 size markers are deprecated in favour of MlKem*,
        // but the legacy size-switch methods are kept for source compatibility.
        #[allow(deprecated)]
        impl<ProcessStatus, ContentStatus, AlgorithmParam>
            Kyber<ProcessStatus, $from, ContentStatus, AlgorithmParam>
        {
            /// Switch to a different KEM size marker.
            pub fn $method(self) -> Kyber<ProcessStatus, $to, ContentStatus, AlgorithmParam> {
                Kyber {
                    kyber_data: self.kyber_data,
                    hmac_size: self.hmac_size,
                    content_state: PhantomData,
                    kyber_state: PhantomData::<$to_phantom>,
                    algorithm_state: PhantomData,
                    process_state: PhantomData,
                }
            }
        }
    };
}

impl_size_switch!(Kyber1024 => Kyber768,  kyber768,  Kyber768);
impl_size_switch!(Kyber1024 => Kyber512,  kyber512,  Kyber512);
impl_size_switch!(Kyber768  => Kyber1024, kyber1024, Kyber1024);
impl_size_switch!(Kyber768  => Kyber512,  kyber512,  Kyber512);
impl_size_switch!(Kyber512  => Kyber1024, kyber1024, Kyber1024);
impl_size_switch!(Kyber512  => Kyber768,  kyber768,  Kyber768);

impl_size_switch!(MlKem1024 => MlKem768,  ml_kem768,  MlKem768);
impl_size_switch!(MlKem1024 => MlKem512,  ml_kem512,  MlKem512);
impl_size_switch!(MlKem768  => MlKem1024, ml_kem1024, MlKem1024);
impl_size_switch!(MlKem768  => MlKem512,  ml_kem512,  MlKem512);
impl_size_switch!(MlKem512  => MlKem1024, ml_kem1024, MlKem1024);
impl_size_switch!(MlKem512  => MlKem768,  ml_kem768,  MlKem768);

// ── Algorithm-switch methods (all sizes) ─────────────────────────────────────

macro_rules! impl_alg_switch {
    ($from:ty, $to:ty, $method:ident) => {
        impl<ProcessStatus, KyberSize: KyberSizeVariant, ContentStatus>
            Kyber<ProcessStatus, KyberSize, ContentStatus, $from>
        {
            /// Switch to a different symmetric cipher.
            pub fn $method(self) -> Kyber<ProcessStatus, KyberSize, ContentStatus, $to> {
                Kyber {
                    kyber_data: self.kyber_data,
                    hmac_size: self.hmac_size,
                    content_state: PhantomData,
                    kyber_state: PhantomData,
                    algorithm_state: PhantomData,
                    process_state: PhantomData,
                }
            }
        }
    };
}

impl_alg_switch!(AES, XChaCha20, xchacha20);
impl_alg_switch!(AES, AesGcmSiv, aes_gcm_siv);
impl_alg_switch!(AES, AesCtr, aes_ctr);
impl_alg_switch!(AES, AesXts, aes_xts);
impl_alg_switch!(AES, XChaCha20Poly1305, xchacha20poly1305);
impl_alg_switch!(XChaCha20, AES, aes);
impl_alg_switch!(XChaCha20, AesGcmSiv, aes_gcm_siv);
impl_alg_switch!(XChaCha20, AesCtr, aes_ctr);
impl_alg_switch!(XChaCha20, AesXts, aes_xts);
impl_alg_switch!(XChaCha20, XChaCha20Poly1305, xchacha20poly1305);
impl_alg_switch!(XChaCha20Poly1305, AES, aes);
impl_alg_switch!(XChaCha20Poly1305, AesGcmSiv, aes_gcm_siv);
impl_alg_switch!(XChaCha20Poly1305, AesCtr, aes_ctr);
impl_alg_switch!(XChaCha20Poly1305, AesXts, aes_xts);
impl_alg_switch!(XChaCha20Poly1305, XChaCha20, xchacha20);
impl_alg_switch!(AesGcmSiv, AES, aes);
impl_alg_switch!(AesGcmSiv, XChaCha20, xchacha20);
impl_alg_switch!(AesGcmSiv, XChaCha20Poly1305, xchacha20poly1305);
impl_alg_switch!(AesGcmSiv, AesCtr, aes_ctr);
impl_alg_switch!(AesGcmSiv, AesXts, aes_xts);
impl_alg_switch!(AesCtr, AES, aes);
impl_alg_switch!(AesCtr, XChaCha20, xchacha20);
impl_alg_switch!(AesCtr, AesGcmSiv, aes_gcm_siv);
impl_alg_switch!(AesCtr, AesXts, aes_xts);
impl_alg_switch!(AesCtr, XChaCha20Poly1305, xchacha20poly1305);
impl_alg_switch!(AesXts, AES, aes);
impl_alg_switch!(AesXts, XChaCha20, xchacha20);
impl_alg_switch!(AesXts, XChaCha20Poly1305, xchacha20poly1305);
impl_alg_switch!(AesXts, AesGcmSiv, aes_gcm_siv);
impl_alg_switch!(AesXts, AesCtr, aes_ctr);

// ── Content-switch methods ────────────────────────────────────────────────────

impl<ProcessStatus, KyberSize: KyberSizeVariant, AlgorithmParam>
    Kyber<ProcessStatus, KyberSize, Files, AlgorithmParam>
{
    /// Switch to `Message` content type.
    pub fn message(self) -> Kyber<ProcessStatus, KyberSize, Message, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Switch to `Data` content type.
    pub fn data(self) -> Kyber<ProcessStatus, KyberSize, Data, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Returns `true` (this is a file instance).
    pub fn is_file(self) -> bool {
        true
    }
    /// Returns `false`.
    pub fn is_message(self) -> bool {
        false
    }
    /// Returns `false`.
    pub fn is_data(self) -> bool {
        false
    }
}

impl<ProcessStatus, KyberSize: KyberSizeVariant, AlgorithmParam>
    Kyber<ProcessStatus, KyberSize, Message, AlgorithmParam>
{
    /// Switch to `Files` content type.
    pub fn file(self) -> Kyber<ProcessStatus, KyberSize, Files, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Switch to `Data` content type.
    pub fn data(self) -> Kyber<ProcessStatus, KyberSize, Data, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Returns `false`.
    pub fn is_file(self) -> bool {
        false
    }
    /// Returns `true` (this is a message instance).
    pub fn is_message(self) -> bool {
        true
    }
    /// Returns `false`.
    pub fn is_data(self) -> bool {
        false
    }
}

impl<ProcessStatus, KyberSize: KyberSizeVariant, AlgorithmParam>
    Kyber<ProcessStatus, KyberSize, Data, AlgorithmParam>
{
    /// Switch to `Files` content type.
    pub fn file(self) -> Kyber<ProcessStatus, KyberSize, Files, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Switch to `Message` content type.
    pub fn message(self) -> Kyber<ProcessStatus, KyberSize, Message, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
    /// Returns `false`.
    pub fn is_file(self) -> bool {
        false
    }
    /// Returns `false`.
    pub fn is_message(self) -> bool {
        false
    }
    /// Returns `true` (this is a data instance).
    pub fn is_data(self) -> bool {
        true
    }
}

// ── Process-switch methods ────────────────────────────────────────────────────

impl<KyberSize: KyberSizeVariant, ContentStatus, AlgorithmParam>
    Kyber<Encryption, KyberSize, ContentStatus, AlgorithmParam>
{
    /// Switch to the decryption process state.
    pub fn decryption(self) -> Kyber<Decryption, KyberSize, Message, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
}

impl<KyberSize: KyberSizeVariant, ContentStatus, AlgorithmParam>
    Kyber<Decryption, KyberSize, ContentStatus, AlgorithmParam>
{
    /// Switch to the encryption process state.
    pub fn encryption(self) -> Kyber<Encryption, KyberSize, Files, AlgorithmParam> {
        Kyber {
            kyber_data: self.kyber_data,
            hmac_size: self.hmac_size,
            content_state: PhantomData,
            kyber_state: PhantomData,
            algorithm_state: PhantomData,
            process_state: PhantomData,
        }
    }
}