Skip to main content

quantaegis_core/
ct.rs

1//! Constant-time primitives for branchless cryptographic operations.
2//!
3//! All functions in this module are designed to avoid secret-dependent control flow and
4//! secret-dependent memory accesses. Values pass through [`core::hint::black_box`] to inhibit
5//! LLVM optimizations that might otherwise reintroduce branches.
6//!
7//! How far this is verified (release-assembly audit, `dudect` timing tests) is tracked in
8//! [SECURITY.md](https://github.com/PyRin-c/quantaegis/blob/main/SECURITY.md#evidence-for-the-current-stage).
9
10use core::hint::black_box;
11use core::ops::{BitAnd, BitOr, BitXor, Not};
12
13/// A constant-time boolean represented internally as `0u8` (false) or `1u8` (true).
14#[derive(Copy, Clone, Debug)]
15pub struct Choice(u8);
16
17impl Choice {
18    /// Constant-time `false` (`0`).
19    pub const FALSE: Self = Self(0);
20
21    /// Constant-time `true` (`1`).
22    pub const TRUE: Self = Self(1);
23
24    /// Constructs a [`Choice`] from a `u8` whose value MUST be `0` or `1`.
25    ///
26    /// Any non-zero input is normalized to `1` in constant time.
27    #[inline]
28    pub fn from_u8_nonzero(v: u8) -> Self {
29        // If v != 0, then (v | v.wrapping_neg()) has bit 7 set.
30        let nonzero = (v | v.wrapping_neg()) >> 7;
31        Self(black_box(nonzero))
32    }
33
34    /// Returns the raw `0` or `1` representation.
35    #[inline]
36    pub fn unwrap_u8(self) -> u8 {
37        black_box(self.0)
38    }
39
40    /// Converts to a standard `bool`.
41    ///
42    /// **Caution**: Branching on the returned `bool` when the `Choice` depends on secret data
43    /// leaks timing information. Only convert at explicit non-secret boundaries (e.g., public
44    /// verification results or tests).
45    #[inline]
46    pub fn into_bool(self) -> bool {
47        self.unwrap_u8() == 1
48    }
49
50    /// Expands `0` -> `0x00` and `1` -> `0xFF` in constant time.
51    #[inline]
52    pub(crate) fn mask_u8(self) -> u8 {
53        0u8.wrapping_sub(self.unwrap_u8())
54    }
55
56    /// Expands `0` -> `0x0000` and `1` -> `0xFFFF` in constant time.
57    #[inline]
58    pub(crate) fn mask_u16(self) -> u16 {
59        0u16.wrapping_sub(u16::from(self.unwrap_u8()))
60    }
61}
62
63impl BitAnd for Choice {
64    type Output = Self;
65
66    #[inline]
67    fn bitand(self, rhs: Self) -> Self::Output {
68        Self(black_box(self.unwrap_u8() & rhs.unwrap_u8()))
69    }
70}
71
72impl BitOr for Choice {
73    type Output = Self;
74
75    #[inline]
76    fn bitor(self, rhs: Self) -> Self::Output {
77        Self(black_box(self.unwrap_u8() | rhs.unwrap_u8()))
78    }
79}
80
81impl BitXor for Choice {
82    type Output = Self;
83
84    #[inline]
85    fn bitxor(self, rhs: Self) -> Self::Output {
86        Self(black_box(self.unwrap_u8() ^ rhs.unwrap_u8()))
87    }
88}
89
90impl Not for Choice {
91    type Output = Self;
92
93    #[inline]
94    fn not(self) -> Self::Output {
95        Self(black_box(1u8 ^ self.unwrap_u8()))
96    }
97}
98
99/// Constant-time equality for two `u8` values.
100#[inline]
101pub fn ct_eq_u8(a: u8, b: u8) -> Choice {
102    let diff = a ^ b;
103    !Choice::from_u8_nonzero(diff)
104}
105
106/// Constant-time equality for two byte slices.
107///
108/// Returns [`Choice::FALSE`] immediately if slice lengths differ (slice length is assumed to be
109/// public metadata, e.g., fixed ciphertext size). When lengths are equal, every byte is inspected
110/// without short-circuiting.
111#[inline]
112pub fn ct_eq_slice(a: &[u8], b: &[u8]) -> Choice {
113    if a.len() != b.len() {
114        return Choice::FALSE;
115    }
116
117    let mut acc: u8 = 0;
118    for (&x, &y) in a.iter().zip(b.iter()) {
119        acc |= x ^ y;
120    }
121    !Choice::from_u8_nonzero(acc)
122}
123
124/// Constant-time selection between two `u8` values: returns `if_true` when `choice` is true,
125/// otherwise `if_false`.
126#[inline]
127pub fn ct_select_u8(if_false: u8, if_true: u8, choice: Choice) -> u8 {
128    let mask = choice.mask_u8();
129    if_false ^ (mask & (if_false ^ if_true))
130}
131
132/// Constant-time selection between two `u16` values.
133#[inline]
134pub fn ct_select_u16(if_false: u16, if_true: u16, choice: Choice) -> u16 {
135    let mask = choice.mask_u16();
136    if_false ^ (mask & (if_false ^ if_true))
137}
138
139/// Constant-time selection between two `i16` values (used in lattice polynomial arithmetic).
140#[inline]
141pub fn ct_select_i16(if_false: i16, if_true: i16, choice: Choice) -> i16 {
142    let mask = i16::from_ne_bytes(choice.mask_u16().to_ne_bytes());
143    if_false ^ (mask & (if_false ^ if_true))
144}
145
146/// Constant-time selection of fixed-size byte arrays directly into `out`.
147///
148/// Used directly in ML-KEM implicit rejection (`FIPS 203, Algorithm 18`) to choose between the
149/// real shared secret `K'` and the rejection key `K_bar` without branching or creating an
150/// intermediate stack copy of the selected secret.
151#[inline]
152pub fn ct_select_array_into<const N: usize>(
153    if_false: &[u8; N],
154    if_true: &[u8; N],
155    choice: Choice,
156    out: &mut [u8; N],
157) {
158    let mask = choice.mask_u8();
159    for i in 0..N {
160        out[i] = if_false[i] ^ (mask & (if_false[i] ^ if_true[i]));
161    }
162}
163
164/// Constant-time selection of fixed-size byte arrays, returning the selected array.
165///
166/// Used directly in ML-KEM implicit rejection (`FIPS 203, Algorithm 18`) to choose between the
167/// real shared secret `K'` and the rejection key `K_bar` without branching.
168#[inline]
169pub fn ct_select_array<const N: usize>(
170    if_false: &[u8; N],
171    if_true: &[u8; N],
172    choice: Choice,
173) -> [u8; N] {
174    let mut out = [0u8; N];
175    ct_select_array_into(if_false, if_true, choice, &mut out);
176    out
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn choice_normalization_and_logic() {
185        assert!(!Choice::from_u8_nonzero(0).into_bool());
186        for v in 1..=u8::MAX {
187            assert!(Choice::from_u8_nonzero(v).into_bool());
188        }
189        assert!((Choice::TRUE & Choice::TRUE).into_bool());
190        assert!(!(Choice::TRUE & Choice::FALSE).into_bool());
191        assert!((Choice::TRUE | Choice::FALSE).into_bool());
192        assert!((Choice::TRUE ^ Choice::FALSE).into_bool());
193        assert!(!(Choice::TRUE ^ Choice::TRUE).into_bool());
194        assert!((!Choice::FALSE).into_bool());
195        assert!(!(!Choice::TRUE).into_bool());
196    }
197
198    #[test]
199    fn constant_time_slice_equality() {
200        let a = [0x12u8, 0x34, 0x56, 0x78];
201        let b = [0x12u8, 0x34, 0x56, 0x78];
202        let c = [0x12u8, 0x34, 0x56, 0x79];
203        let short = [0x12u8, 0x34];
204
205        assert!(ct_eq_slice(&a, &b).into_bool());
206        assert!(!ct_eq_slice(&a, &c).into_bool());
207        assert!(!ct_eq_slice(&a, &short).into_bool());
208    }
209
210    #[test]
211    fn constant_time_selection() {
212        assert_eq!(ct_select_u8(0xAA, 0x55, Choice::FALSE), 0xAA);
213        assert_eq!(ct_select_u8(0xAA, 0x55, Choice::TRUE), 0x55);
214        assert_eq!(ct_select_u16(0x1234, 0xABCD, Choice::FALSE), 0x1234);
215        assert_eq!(ct_select_u16(0x1234, 0xABCD, Choice::TRUE), 0xABCD);
216        assert_eq!(ct_select_i16(-1234, 3328, Choice::FALSE), -1234);
217        assert_eq!(ct_select_i16(-1234, 3328, Choice::TRUE), 3328);
218
219        let k_bar = [0x11u8; 32];
220        let k_prime = [0x99u8; 32];
221        assert_eq!(ct_select_array(&k_bar, &k_prime, Choice::FALSE), k_bar);
222        assert_eq!(ct_select_array(&k_bar, &k_prime, Choice::TRUE), k_prime);
223    }
224}