kyberlib/ml_kem_sized.rs
1// Copyright © 2026 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! The ML-KEM-512 and ML-KEM-1024 key and ciphertext wrappers, generated
5//! by one macro. Split out of `ml_kem.rs` to keep that file within the
6//! size ceiling; the types are re-exported from `crate::ml_kem`.
7
8use super::{MlKem1024, MlKem512};
9use crate::error::KyberLibError;
10use core::fmt;
11use zeroize::{Zeroize, ZeroizeOnDrop};
12
13// ---------------------------------------------------------------- ML-KEM-512 + 1024 typed wrappers
14
15macro_rules! sized_wrapper_types {
16 ($p:ident, $ek:ident, $dk:ident, $ct:ident, $pk_bytes:expr, $sk_bytes:expr, $ct_bytes:expr) => {
17 /// Public encapsulation key.
18 #[derive(Clone, Copy, Eq, PartialEq)]
19 #[non_exhaustive]
20 pub struct $ek(pub(crate) [u8; $pk_bytes]);
21
22 impl $ek {
23 /// Construct from raw bytes.
24 pub fn from_bytes(bytes: [u8; $pk_bytes]) -> Self {
25 Self(bytes)
26 }
27 /// Construct from a borrowed slice, validating the length.
28 ///
29 /// # Errors
30 ///
31 /// [`KyberLibError::InvalidLength`] on length mismatch.
32 pub fn try_from_slice(
33 bytes: &[u8],
34 ) -> Result<Self, KyberLibError> {
35 if bytes.len() != $pk_bytes {
36 return Err(KyberLibError::InvalidLength);
37 }
38 let mut buf = [0u8; $pk_bytes];
39 buf.copy_from_slice(bytes);
40 Ok(Self(buf))
41 }
42 /// Borrow as raw bytes.
43 pub fn as_bytes(&self) -> &[u8; $pk_bytes] {
44 &self.0
45 }
46 }
47
48 impl fmt::Debug for $ek {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 f.debug_tuple(stringify!($ek))
51 .field(&format_args!(
52 "[{} bytes; not secret]",
53 $pk_bytes
54 ))
55 .finish()
56 }
57 }
58
59 /// Secret decapsulation key. Zeroized on drop.
60 #[derive(Clone, Zeroize, ZeroizeOnDrop, Eq, PartialEq)]
61 #[non_exhaustive]
62 pub struct $dk(pub(crate) [u8; $sk_bytes]);
63
64 impl $dk {
65 /// Construct from raw bytes.
66 pub fn from_bytes(bytes: [u8; $sk_bytes]) -> Self {
67 Self(bytes)
68 }
69 /// Construct from a borrowed slice, validating the length
70 /// and the FIPS 203 §7.3 hash check (the stored `H(ek)`
71 /// must match the embedded encapsulation key).
72 ///
73 /// # Errors
74 ///
75 /// [`KyberLibError::InvalidLength`] on length mismatch;
76 /// [`KyberLibError::InvalidKey`] if the hash check fails.
77 pub fn try_from_slice(
78 bytes: &[u8],
79 ) -> Result<Self, KyberLibError> {
80 if bytes.len() != $sk_bytes {
81 return Err(KyberLibError::InvalidLength);
82 }
83 if !crate::input_check::dk_hash_check::<$p>(bytes) {
84 return Err(KyberLibError::InvalidKey);
85 }
86 let mut buf = [0u8; $sk_bytes];
87 buf.copy_from_slice(bytes);
88 Ok(Self(buf))
89 }
90 /// Borrow as raw bytes. Sparingly — the secret state is
91 /// exposed.
92 pub fn as_bytes(&self) -> &[u8; $sk_bytes] {
93 &self.0
94 }
95 }
96
97 impl fmt::Debug for $dk {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 f.write_str(concat!(
100 stringify!($dk),
101 "([REDACTED ",
102 stringify!($sk_bytes),
103 " bytes])"
104 ))
105 }
106 }
107
108 /// Ciphertext.
109 #[derive(Clone, Copy, Eq, PartialEq)]
110 #[non_exhaustive]
111 pub struct $ct(pub(crate) [u8; $ct_bytes]);
112
113 impl $ct {
114 /// Construct from raw bytes.
115 pub fn from_bytes(bytes: [u8; $ct_bytes]) -> Self {
116 Self(bytes)
117 }
118 /// Construct from a borrowed slice, validating the length.
119 ///
120 /// # Errors
121 ///
122 /// [`KyberLibError::InvalidLength`] on length mismatch.
123 pub fn try_from_slice(
124 bytes: &[u8],
125 ) -> Result<Self, KyberLibError> {
126 if bytes.len() != $ct_bytes {
127 return Err(KyberLibError::InvalidLength);
128 }
129 let mut buf = [0u8; $ct_bytes];
130 buf.copy_from_slice(bytes);
131 Ok(Self(buf))
132 }
133 /// Borrow as raw bytes.
134 pub fn as_bytes(&self) -> &[u8; $ct_bytes] {
135 &self.0
136 }
137 }
138
139 impl fmt::Debug for $ct {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f.debug_tuple(stringify!($ct))
142 .field(&format_args!(
143 "[{} bytes; opaque]",
144 $ct_bytes
145 ))
146 .finish()
147 }
148 }
149 };
150}
151
152sized_wrapper_types!(
153 MlKem512,
154 MlKem512EncapKey,
155 MlKem512DecapKey,
156 MlKem512Ciphertext,
157 800,
158 1632,
159 768
160);
161sized_wrapper_types!(
162 MlKem1024,
163 MlKem1024EncapKey,
164 MlKem1024DecapKey,
165 MlKem1024Ciphertext,
166 1568,
167 3168,
168 1568
169);