Skip to main content

kyberlib/
key_import.rs

1// Copyright © 2026 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Importing typed keys from bytes with the FIPS 203 input checks, so a
5//! decoder (for example `kyberlib-pkcs8`) rejects a bad key at import
6//! rather than at first use: `validate()` on encapsulation keys (§7.2)
7//! and `MlKem768DecapKey::try_from_slice` (§7.3; ML-KEM-512 and -1024
8//! define theirs in `ml_kem.rs`).
9
10use crate::error::KyberLibError;
11use crate::input_check::{coefficients_reduced, dk_hash_check};
12use crate::ml_kem::{
13    MlKem1024EncapKey, MlKem512EncapKey, MlKem768, MlKem768DecapKey,
14    MlKem768EncapKey,
15};
16use crate::params::KYBER_SECRET_KEY_BYTES;
17
18/// Length of the public seed `rho` that ends every encapsulation key.
19const RHO_BYTES: usize = 32;
20
21macro_rules! impl_validate {
22    ($($ek:ty),*) => {$(
23        impl $ek {
24            /// Runs the FIPS 203 §7.2 encapsulation-key check: every
25            /// encoded 12-bit coefficient must be below q = 3329. The
26            /// length (type) check is enforced by the type itself.
27            ///
28            /// [`Self::encapsulate`] runs the same check; call this to
29            /// reject a key when it is imported.
30            ///
31            /// # Errors
32            ///
33            /// [`KyberLibError::InvalidKey`] if a coefficient is not
34            /// reduced modulo q.
35            pub fn validate(&self) -> Result<(), KyberLibError> {
36                let bytes = self.as_bytes();
37                if coefficients_reduced(&bytes[..bytes.len() - RHO_BYTES]) {
38                    Ok(())
39                } else {
40                    Err(KyberLibError::InvalidKey)
41                }
42            }
43        }
44    )*};
45}
46
47impl_validate!(MlKem512EncapKey, MlKem768EncapKey, MlKem1024EncapKey);
48
49impl MlKem768DecapKey {
50    /// Construct from a borrowed slice, validating the length and the
51    /// FIPS 203 §7.3 hash check (the stored `H(ek)` must match the
52    /// embedded encapsulation key).
53    ///
54    /// # Errors
55    ///
56    /// [`KyberLibError::InvalidLength`] on length mismatch;
57    /// [`KyberLibError::InvalidKey`] if the hash check fails.
58    pub fn try_from_slice(bytes: &[u8]) -> Result<Self, KyberLibError> {
59        let buf: [u8; KYBER_SECRET_KEY_BYTES] = bytes
60            .try_into()
61            .map_err(|_| KyberLibError::InvalidLength)?;
62        if !dk_hash_check::<MlKem768>(&buf) {
63            return Err(KyberLibError::InvalidKey);
64        }
65        Ok(Self(buf))
66    }
67}