kyberlib/api.rs
1// Copyright © 2024 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Legacy free-function KEM API.
5//!
6//! Three top-level functions cover the ML-KEM-768 key encapsulation
7//! mechanism end-to-end:
8//!
9//! - [`keypair`] — generate a fresh (public, secret) keypair.
10//! - [`encapsulate`] — encapsulate a 32-byte shared secret against a
11//! public key.
12//! - [`decapsulate`] — recover the shared secret from a ciphertext +
13//! secret key.
14//!
15//! The legacy [`Keypair`] struct bundles the two halves. Prefer the
16//! [v0.0.7 typed-state API](crate::ml_kem) for new code — it
17//! prevents accidental mixing of `EncapsulationKey` / `DecapsulationKey`
18//! at the type level and redacts secret material in `Debug` output.
19//!
20//! # Example
21//!
22//! ```
23//! # fn main() -> Result<(), kyberlib::KyberLibError> {
24//! use kyberlib::{keypair, encapsulate, decapsulate};
25//!
26//! let mut rng = rand::thread_rng();
27//! let bob = keypair(&mut rng)?;
28//! let (ct, ss_a) = encapsulate(&bob.public, &mut rng)?;
29//! let ss_b = decapsulate(&ct, &bob.secret)?;
30//! assert_eq!(ss_a, ss_b);
31//! # Ok(()) }
32//! ```
33
34use core::fmt;
35
36use crate::{
37 error::KyberLibError, kem::*, params::*, CryptoRng, RngCore,
38};
39use zeroize::{Zeroize, ZeroizeOnDrop};
40
41/// Result of encapsulating a public key which includes the ciphertext and shared secret
42pub type Encapsulated = Result<
43 (
44 [u8; KYBER_CIPHERTEXT_BYTES],
45 [u8; KYBER_SHARED_SECRET_BYTES],
46 ),
47 KyberLibError,
48>;
49/// Decapsulated ciphertext
50pub type Decapsulated =
51 Result<[u8; KYBER_SHARED_SECRET_BYTES], KyberLibError>;
52/// Kyber public key
53pub type PublicKey = [u8; KYBER_PUBLIC_KEY_BYTES];
54/// Kyber secret key
55pub type SecretKey = [u8; KYBER_SECRET_KEY_BYTES];
56/// Kyber Shared Secret
57pub type SharedSecret = [u8; KYBER_SHARED_SECRET_BYTES];
58
59/// Generate a key pair for Kyber encryption with a provided RNG.
60///
61/// This function generates a key pair consisting of a public key and a secret key for Kyber encryption.
62///
63/// # Arguments
64///
65/// * `rng` - The random number generator implementing the `RngCore` and `CryptoRng` traits.
66///
67/// # Errors
68///
69/// Returns a `KyberLibError` if an error occurs during key pair generation.
70///
71/// ### Example
72/// ```
73/// # use kyberlib::*;
74/// # fn main() -> Result<(), KyberLibError> {
75/// let mut rng = rand::thread_rng();
76/// let keys = keypair(&mut rng)?;
77/// # Ok(())}
78/// ```
79pub fn keypair<R>(rng: &mut R) -> Result<Keypair, KyberLibError>
80where
81 R: RngCore + CryptoRng,
82{
83 let mut public = [0u8; KYBER_PUBLIC_KEY_BYTES];
84 let mut secret = [0u8; KYBER_SECRET_KEY_BYTES];
85 generate_key_pair(&mut public, &mut secret, rng, None)?;
86 let keys = Keypair { public, secret };
87 secret.zeroize();
88 Ok(keys)
89}
90
91/// Verify that given secret and public key matches and put them in
92/// the KeyPair structure after zeroize them if asked.
93/// ### Example
94/// ```
95/// # use kyberlib::*;
96/// # fn main() -> Result<(), KyberLibError> {
97/// let mut rng = rand::thread_rng();
98/// let keys = keypair(&mut rng)?;
99/// let mut public = keys.public;
100/// let mut secret = keys.secret;
101/// let _ = keypairfrom(&mut public, &mut secret, &mut rng)?;
102/// # Ok(())}
103/// ```
104pub fn keypairfrom<R>(
105 public: &mut [u8; KYBER_PUBLIC_KEY_BYTES],
106 secret: &mut [u8; KYBER_SECRET_KEY_BYTES],
107 rng: &mut R,
108) -> Result<Keypair, KyberLibError>
109where
110 R: RngCore + CryptoRng,
111{
112 //Try to encapsulate and decapsulate to verify secret key matches public key
113 let (ciphertext, shared_secret) = encapsulate(public, rng)?;
114 let expected_shared_secret = decapsulate(&ciphertext, secret)?;
115 //If it does match, return a KeyPair
116 if expected_shared_secret == shared_secret {
117 let public2 = *public;
118 let secret2 = *secret;
119 let key = Keypair {
120 public: public2,
121 secret: secret2,
122 };
123 // Zeroize only the caller-supplied secret slice. Public keys are
124 // not sensitive (and zeroizing them would surprise callers who
125 // expect their input buffers to be preserved). The in-struct
126 // `secret2` is moved into `key`, which zeroizes via `ZeroizeOnDrop`.
127 secret.zeroize();
128 Ok(key)
129 } else {
130 //Else return an error
131 Err(KyberLibError::InvalidKey)
132 }
133}
134
135/// Encapsulates a public key and returns the ciphertext to send and the shared secret.
136///
137/// This function encapsulates a public key and returns the ciphertext and the shared secret.
138///
139/// # Arguments
140///
141/// * `pk` - The public key as a slice of bytes.
142/// * `rng` - The random number generator implementing the `RngCore` and `CryptoRng` traits.
143///
144/// # Errors
145///
146/// Returns [`KyberLibError::InvalidInput`] if `pk` has the wrong length, or
147/// [`KyberLibError::InvalidKey`] if it fails the FIPS 203 §7.2 modulus check.
148///
149/// ### Example
150/// ```
151/// # use kyberlib::*;
152/// # fn main() -> Result<(), KyberLibError> {
153/// let mut rng = rand::thread_rng();
154/// let keys = keypair(&mut rng)?;
155/// let (ciphertext, shared_secret) = encapsulate(&keys.public, &mut rng)?;
156/// # Ok(())}
157/// ```
158pub fn encapsulate<R>(pk: &[u8], rng: &mut R) -> Encapsulated
159where
160 R: CryptoRng + RngCore,
161{
162 if pk.len() != KYBER_PUBLIC_KEY_BYTES {
163 return Err(KyberLibError::InvalidInput);
164 }
165 let mut ct = [0u8; KYBER_CIPHERTEXT_BYTES];
166 let mut ss = [0u8; KYBER_SHARED_SECRET_BYTES];
167 encrypt_message(&mut ct, &mut ss, pk, rng, None)?;
168 Ok((ct, ss))
169}
170
171/// Decapsulates ciphertext with a secret key.
172///
173/// This function decapsulates ciphertext with a secret key and returns the shared secret.
174///
175/// # Arguments
176///
177/// * `ct` - The ciphertext as a slice of bytes.
178/// * `sk` - The secret key as a slice of bytes.
179///
180/// # Errors
181///
182/// Returns a `KyberLibError` if the input sizes are incorrect or if decapsulation fails.
183///
184/// ### Example
185/// ```
186/// # use kyberlib::*;
187/// # fn main() -> Result<(), KyberLibError> {
188/// let mut rng = rand::thread_rng();
189/// let keys = keypair(&mut rng)?;
190/// let (ct, ss1) = encapsulate(&keys.public, &mut rng)?;
191/// let ss2 = decapsulate(&ct, keys.expose_secret())?;
192/// assert_eq!(ss1, ss2);
193/// # Ok(())}
194/// ```
195pub fn decapsulate(ct: &[u8], sk: &[u8]) -> Decapsulated {
196 if ct.len() != KYBER_CIPHERTEXT_BYTES
197 || sk.len() != KYBER_SECRET_KEY_BYTES
198 {
199 return Err(KyberLibError::InvalidInput);
200 }
201 let mut ss = [0u8; KYBER_SHARED_SECRET_BYTES];
202 decrypt_message(&mut ss, ct, sk);
203 Ok(ss)
204}
205
206/// A public/secret keypair for use with Kyber.
207///
208/// Byte lengths of the keys are determined by the security level chosen.
209///
210/// # Deprecation
211///
212/// **Soft-deprecated since v0.0.7** in favour of the typed
213/// [`MlKem768EncapKey`](crate::MlKem768EncapKey) /
214/// [`MlKem768DecapKey`](crate::MlKem768DecapKey) split exposed via
215/// the [`KemCore`](crate::KemCore) trait. The blob form exposes the
216/// secret half through a public field; the typed split prevents that
217/// while keeping the legacy byte arrays accessible via
218/// `.as_bytes()` for serialization.
219///
220/// New code should use [`MlKem768::generate`](crate::MlKem768) and
221/// the typed API. This struct will be removed in a future release.
222///
223/// # Secret handling (legacy)
224///
225/// `Keypair` does not derive [`Copy`] (since v0.0.7) and derives
226/// [`Zeroize`] / [`ZeroizeOnDrop`] unconditionally — the `zeroize`
227/// Cargo feature is a no-op opt-out retained for one release.
228///
229/// `Debug` redacts the secret key and prints only the two lengths,
230/// matching [`MlKem768DecapKey`](crate::MlKem768DecapKey):
231/// `Keypair { public: [1184 bytes; not secret], secret: [REDACTED 2400 bytes] }`
232/// for ML-KEM-768.
233// Note: deliberately NOT `#[non_exhaustive]`. The struct is
234// soft-deprecated in favour of the typed `MlKem768EncapKey` /
235// `MlKem768DecapKey` split (see the type-level docs above); locking
236// the literal-constructor would only break existing call sites
237// without buying us safety, since the new typed API is where the
238// `#[non_exhaustive]` rigour lives.
239// non-exhaustive-guard: exempt (soft-deprecated; literals stay valid until removal)
240#[derive(Clone, Eq, PartialEq, Zeroize, ZeroizeOnDrop)]
241pub struct Keypair {
242 /// The public key.
243 pub public: PublicKey,
244 /// The secret key.
245 pub secret: SecretKey,
246}
247
248impl fmt::Debug for Keypair {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.debug_struct("Keypair")
251 .field(
252 "public",
253 &format_args!(
254 "[{} bytes; not secret]",
255 KYBER_PUBLIC_KEY_BYTES
256 ),
257 )
258 .field(
259 "secret",
260 &format_args!(
261 "[REDACTED {} bytes]",
262 KYBER_SECRET_KEY_BYTES
263 ),
264 )
265 .finish()
266 }
267}
268
269impl Keypair {
270 /// Securely generates a new keypair.
271 ///
272 /// This function generates a new Kyber key pair and returns it as a `Keypair` struct.
273 ///
274 /// # Arguments
275 ///
276 /// * `rng` - The random number generator implementing the `RngCore` and `CryptoRng` traits.
277 ///
278 /// ### Example
279 /// ```
280 /// # use kyberlib::*;
281 /// # fn main() -> Result<(), KyberLibError> {
282 /// let mut rng = rand::thread_rng();
283 /// let keys = Keypair::generate(&mut rng)?;
284 /// # let empty_keys = Keypair{
285 /// public: [0u8; KYBER_PUBLIC_KEY_BYTES], secret: [0u8; KYBER_SECRET_KEY_BYTES]
286 /// };
287 /// # assert!(empty_keys != keys);
288 /// # Ok(()) }
289 /// ```
290 pub fn generate<R: CryptoRng + RngCore>(
291 rng: &mut R,
292 ) -> Result<Keypair, KyberLibError> {
293 keypair(rng)
294 }
295
296 /// Explicitly exposes the secret key
297 ///```
298 /// use kyberlib::*;
299 ///
300 /// let mut rng = rand::thread_rng();
301 /// let keys = Keypair::generate(&mut rng);
302 /// let binding = keys.expect("Exposed secret key");
303 /// let secret = binding.expose_secret();
304 /// assert!(secret.len() == KYBER_SECRET_KEY_BYTES);
305 /// assert!(secret.len() != 0);
306 /// ```
307 pub fn expose_secret(&self) -> &SecretKey {
308 &self.secret
309 }
310
311 /// Imports a keypair from existing public and secret key arrays.
312 ///
313 /// This function imports a keypair from existing public and secret key
314 /// arrays and returns it as a `Keypair` struct.
315 ///
316 /// # Arguments
317 ///
318 /// * `public` - A mutable reference to a `[u8; KYBER_PUBLIC_KEY_BYTES]` array representing the public key.
319 /// * `secret` - A mutable reference to a `[u8; KYBER_SECRET_KEY_BYTES]` array representing the secret key.
320 /// * `rng` - The random number generator implementing the `RngCore` and `CryptoRng` traits.
321 ///
322 /// # Secret hygiene
323 ///
324 /// On success, the caller-supplied `secret` buffer is zeroized in place
325 /// (since v0.0.7). Subsequent calls with the same `secret` buffer will
326 /// therefore return [`KyberLibError::InvalidKey`]; this is intentional —
327 /// the secret has only one valid home, the returned [`Keypair`]. If you
328 /// genuinely need a copy, use [`Keypair::clone`] on the returned value.
329 ///
330 /// # Example
331 ///
332 /// ```
333 /// # use kyberlib::*;
334 /// # fn main() -> Result<(), KyberLibError> {
335 /// let mut rng = rand::thread_rng();
336 /// let keys = keypair(&mut rng)?;
337 /// let mut public_key = keys.public;
338 /// let mut secret_key = keys.secret;
339 /// let imported = Keypair::import(&mut public_key, &mut secret_key, &mut rng)?;
340 /// // `secret_key` has been zeroized in place; `imported.secret` is the
341 /// // only remaining copy and will be zeroized when `imported` is dropped.
342 /// # let _ = imported;
343 /// # Ok(()) }
344 /// ```
345 pub fn import<R: CryptoRng + RngCore>(
346 public: &mut [u8; KYBER_PUBLIC_KEY_BYTES],
347 secret: &mut [u8; KYBER_SECRET_KEY_BYTES],
348 rng: &mut R,
349 ) -> Result<Keypair, KyberLibError> {
350 keypairfrom(public, secret, rng)
351 }
352}
353
354struct DummyRng {}
355
356impl CryptoRng for DummyRng {}
357
358impl RngCore for DummyRng {
359 fn next_u32(&mut self) -> u32 {
360 panic!()
361 }
362
363 fn next_u64(&mut self) -> u64 {
364 panic!()
365 }
366
367 fn try_fill_bytes(
368 &mut self,
369 _dest: &mut [u8],
370 ) -> Result<(), rand_core::Error> {
371 panic!()
372 }
373
374 fn fill_bytes(&mut self, _dest: &mut [u8]) {
375 panic!()
376 }
377}
378
379/// Deterministically derive a keypair from a seed as specified in draft-schwabe-cfrg-kyber.
380///
381/// This function deterministically derives a key pair from a seed and returns it as a `Keypair` struct.
382///
383/// # Arguments
384///
385/// * `seed` - The seed as a slice of bytes.
386///
387/// # Errors
388///
389/// Returns a `KyberLibError` if the seed length is incorrect.
390pub fn derive(seed: &[u8]) -> Result<Keypair, KyberLibError> {
391 let mut public = [0u8; KYBER_PUBLIC_KEY_BYTES];
392 let mut secret = [0u8; KYBER_SECRET_KEY_BYTES];
393 let mut _rng = DummyRng {};
394 if seed.len() != 64 {
395 return Err(KyberLibError::InvalidInput);
396 }
397 generate_key_pair(
398 &mut public,
399 &mut secret,
400 &mut _rng,
401 Some((&seed[..32], &seed[32..])),
402 )?;
403 Ok(Keypair { public, secret })
404}
405
406/// Extracts a public key from a private key.
407///
408/// This function extracts the public key from a private key.
409///
410/// # Arguments
411///
412/// * `sk` - The secret key as a slice of bytes.
413///
414/// # Returns
415///
416/// Returns the public key as a `PublicKey`.
417pub fn public(sk: &[u8]) -> PublicKey {
418 let mut pk = [0u8; KYBER_INDCPA_PUBLIC_KEY_BYTES];
419 pk.copy_from_slice(
420 &sk[KYBER_INDCPA_SECRET_KEY_BYTES
421 ..KYBER_INDCPA_SECRET_KEY_BYTES
422 + KYBER_INDCPA_PUBLIC_KEY_BYTES],
423 );
424 pk
425}