Skip to main content

kyberlib/
symmetric.rs

1// Copyright © 2024 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Symmetric primitives — SHAKE-128/256 (default) or AES-256-CTR +
5//! SHA-2 (under the deprecated `90s` feature).
6//!
7//! These primitives back FIPS 203 ML-KEM's PRF/XOF/KDF surface. The
8//! module re-exports types for both backends under a uniform name so
9//! the active backend is selected at compile time via the `90s`
10//! Cargo feature. Default (no `90s`) → SHAKE; with `90s` → AES + SHA-2.
11//!
12//! End users typically don't reach into this module directly — it's
13//! exposed for backend selection inside the KEM machinery.
14
15#![allow(dead_code)]
16
17use core::fmt;
18
19#[cfg(feature = "90s")]
20use crate::aes256ctr::*;
21#[cfg(not(feature = "90s"))]
22use crate::{fips202::*, params::*};
23#[cfg(feature = "90s")]
24use sha2::{Digest, Sha256, Sha512};
25
26#[cfg(feature = "90s-fixslice")]
27use aes::cipher::{KeyIvInit, StreamCipher};
28#[cfg(feature = "90s-fixslice")]
29type Aes256Ctr = ctr::Ctr32BE<aes::Aes256>;
30
31/// Block size for AES256CTR in bytes.
32#[cfg(feature = "90s")]
33pub const AES256CTR_BLOCKBYTES: usize = 64;
34
35/// Block size for AES256CTR in bytes.
36#[cfg(not(feature = "90s"))]
37pub const AES256CTR_BLOCKBYTES: usize = 64;
38
39/// Block size for XOF (Extendable Output Function) in bytes.
40#[cfg(feature = "90s")]
41pub const XOF_BLOCKBYTES: usize = AES256CTR_BLOCKBYTES;
42
43/// Block size for XOF (Extendable Output Function) in bytes.
44#[cfg(not(feature = "90s"))]
45pub const XOF_BLOCKBYTES: usize = SHAKE128_RATE;
46
47/// Type alias for the XOF (Extendable Output Function) state.
48#[cfg(not(feature = "90s"))]
49pub type XofState = KeccakState;
50
51/// Type alias for the XOF (Extendable Output Function) state in 90s mode.
52#[cfg(feature = "90s")]
53pub type XofState = Aes256CtrCtx;
54
55/// Keccak state for absorbing data
56///
57/// The lanes hold data derived from whatever was absorbed, which may be
58/// a seed or key, so `Debug` redacts them and shows only `pos`.
59#[derive(Copy, Clone, Default)]
60#[non_exhaustive]
61pub struct KeccakState {
62    /// State array for Keccak
63    pub s: [u64; 25],
64    /// Position in the state array
65    pub pos: usize,
66}
67
68impl fmt::Debug for KeccakState {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("KeccakState")
71            .field("s", &format_args!("[REDACTED {} bytes]", 25 * 8))
72            .field("pos", &self.pos)
73            .finish()
74    }
75}
76
77impl KeccakState {
78    /// Creates a new KeccakState
79    pub fn new() -> Self {
80        KeccakState {
81            s: [0u64; 25],
82            pos: 0usize,
83        }
84    }
85
86    /// Resets the KeccakState
87    pub fn reset(&mut self) {
88        self.s = [0u64; 25];
89        self.pos = 0;
90    }
91}
92
93/// Computes SHA3-256 hash
94#[cfg(not(feature = "90s"))]
95pub fn hash_h(out: &mut [u8], input: &[u8], inlen: usize) {
96    sha3_256(out, input, inlen);
97}
98
99/// Computes SHA2-256 hash in 90s mode
100#[cfg(feature = "90s")]
101pub fn hash_h(out: &mut [u8], input: &[u8], inlen: usize) {
102    let mut hasher = Sha256::new();
103    hasher.update(&input[..inlen]);
104    let digest = hasher.finalize();
105    out[..digest.len()].copy_from_slice(&digest);
106}
107
108/// Computes SHA3-512 hash
109#[cfg(not(feature = "90s"))]
110pub fn hash_g(out: &mut [u8], input: &[u8], inlen: usize) {
111    sha3_512(out, input, inlen);
112}
113
114/// Computes SHA2-512 hash in 90s mode
115#[cfg(feature = "90s")]
116pub fn hash_g(out: &mut [u8], input: &[u8], inlen: usize) {
117    let mut hasher = Sha512::new();
118    hasher.update(&input[..inlen]);
119    let digest = hasher.finalize();
120    out[..digest.len()].copy_from_slice(&digest);
121}
122
123/// Absorbs input data into the XOF state in non-90s mode
124#[cfg(not(feature = "90s"))]
125pub fn xof_absorb(state: &mut XofState, input: &[u8], x: u8, y: u8) {
126    kyber_shake128_absorb(state, input, x, y);
127}
128
129/// Absorbs input data into the XOF state in 90s mode
130#[cfg(feature = "90s")]
131pub fn xof_absorb(state: &mut XofState, input: &[u8], x: u8, y: u8) {
132    let mut nonce = [0u8; 12];
133    nonce[0] = x;
134    nonce[1] = y;
135    aes256ctr_init(state, input, nonce);
136}
137
138/// Squeezes XOF data into output in non-90s mode
139#[cfg(not(feature = "90s"))]
140pub fn xof_squeezeblocks(
141    out: &mut [u8],
142    outblocks: usize,
143    state: &mut XofState,
144) {
145    kyber_shake128_squeezeblocks(out, outblocks, state);
146}
147
148/// Squeezes XOF data into output in 90s mode
149#[cfg(feature = "90s")]
150pub fn xof_squeezeblocks(
151    out: &mut [u8],
152    outblocks: usize,
153    state: &mut XofState,
154) {
155    aes256ctr_squeezeblocks(out, outblocks, state);
156}
157
158/// Pseudo-random function (PRF) in non-90s mode
159#[cfg(not(feature = "90s"))]
160pub fn prf(out: &mut [u8], outbytes: usize, key: &[u8], nonce: u8) {
161    shake256_prf(out, outbytes, key, nonce);
162}
163
164/// Pseudo-random function (PRF) in 90s mode
165#[cfg(feature = "90s")]
166pub fn prf(out: &mut [u8], _outbytes: usize, key: &[u8], nonce: u8) {
167    #[cfg(feature = "90s-fixslice")]
168    {
169        // RustCrypto fixslice
170        let mut expnonce = [0u8; 16];
171        expnonce[0] = nonce;
172        let mut cipher = Aes256Ctr::new_from_slices(key, &expnonce)
173            .expect("AES-256 key is 32 bytes and the CTR IV is 16");
174        cipher.apply_keystream(out)
175    }
176    #[cfg(not(feature = "90s-fixslice"))]
177    // Pornin bitslice
178    aes256ctr_prf(out, _outbytes, &key, nonce);
179}
180
181/// Key derivation function (KDF) in non-90s mode
182#[cfg(not(feature = "90s"))]
183pub fn kdf(out: &mut [u8], input: &[u8], inlen: usize) {
184    shake256(out, KYBER_SHARED_SECRET_BYTES, input, inlen);
185}
186
187/// Key derivation function (KDF) in 90s mode
188#[cfg(feature = "90s")]
189pub fn kdf(out: &mut [u8], input: &[u8], inlen: usize) {
190    let mut hasher = Sha256::new();
191    hasher.update(&input[..inlen]);
192    let digest = hasher.finalize();
193    out[..digest.len()].copy_from_slice(&digest);
194}
195
196/// Absorb step of the SHAKE128 specialized for the Kyber context
197#[cfg(not(feature = "90s"))]
198pub fn kyber_shake128_absorb(
199    s: &mut KeccakState,
200    input: &[u8],
201    x: u8,
202    y: u8,
203) {
204    let mut extseed = [0u8; KYBER_SYM_BYTES + 2];
205    extseed[..KYBER_SYM_BYTES].copy_from_slice(input);
206    extseed[KYBER_SYM_BYTES] = x;
207    extseed[KYBER_SYM_BYTES + 1] = y;
208    shake128_absorb_once(s, &extseed, KYBER_SYM_BYTES + 2);
209}
210
211/// Squeeze step of SHAKE128 XOF in non-90s mode
212#[cfg(not(feature = "90s"))]
213pub fn kyber_shake128_squeezeblocks(
214    output: &mut [u8],
215    nblocks: usize,
216    s: &mut KeccakState,
217) {
218    shake128_squeezeblocks(output, nblocks, s);
219}
220
221/// Usage of SHAKE256 as a PRF in non-90s mode
222#[cfg(not(feature = "90s"))]
223pub fn shake256_prf(
224    output: &mut [u8],
225    outlen: usize,
226    key: &[u8],
227    nonce: u8,
228) {
229    let mut extkey = [0u8; KYBER_SYM_BYTES + 1];
230    extkey[..KYBER_SYM_BYTES].copy_from_slice(key);
231    extkey[KYBER_SYM_BYTES] = nonce;
232    shake256(output, outlen, &extkey, KYBER_SYM_BYTES + 1);
233}