Skip to main content

rsa/algorithms/pkcs1v15/
selection.rs

1//! Side-channel-free decoding and selection for `draft-irtf-cfrg-rsa-guidance-10` ยง7.2.
2
3use crypto_bigint::{Choice, CtAssign, CtEq, CtGt, CtSelect};
4
5/// Step 3.3: select AL from the 128 big-endian candidate lengths CL.
6///
7/// `max_message_len` is the public bound k - 11, not k - 10.
8pub(crate) fn select_al(cl: &[u8], max_message_len: u16) -> u16 {
9    debug_assert_eq!(cl.len(), 256);
10    let mut mask = max_message_len;
11    mask |= mask >> 1;
12    mask |= mask >> 2;
13    mask |= mask >> 4;
14    mask |= mask >> 8;
15
16    // Zero the high bits, then keep the last admissible candidate (or zero).
17    cl.chunks_exact(2).fold(0u16, |al, bytes| {
18        let candidate = u16::from_be_bytes([bytes[0], bytes[1]]) & mask;
19        al.ct_select(&candidate, !candidate.ct_gt(&max_message_len))
20    })
21}
22
23/// Step 4: EME-PKCS1-v1_5 decoding, returning `(check, L)`.
24///
25/// `check` is set if any padding check fails. L is the length following the first zero separator,
26/// or zero if no separator exists. Both remain secret.
27///
28/// The caller must establish the public bounds `11 <= k <= u32::MAX` and `em.len() == k`.
29#[inline]
30#[allow(
31    clippy::cast_possible_truncation,
32    reason = "k fits in u32 by the public precondition"
33)]
34pub(crate) fn eme_pkcs1v15_decode(em: &[u8], k: usize) -> (Choice, u32) {
35    debug_assert!(k >= 11);
36    debug_assert_eq!(em.len(), k);
37    debug_assert!(u32::try_from(k).is_ok());
38
39    // EM = 0x00 || 0x02 || PS || 0x00 || M.
40    let mut check = !em[0].ct_eq(&0u8) | !em[1].ct_eq(&2u8);
41    let mut looking_for_separator = Choice::TRUE;
42    let mut separator = 0u32;
43    for (i, octet) in em.iter().enumerate().skip(2) {
44        let is_zero = octet.ct_eq(&0u8);
45        separator.ct_assign(&(i as u32), looking_for_separator & is_zero);
46        looking_for_separator &= !is_zero;
47    }
48
49    // Always check for a separator and at least eight nonzero PS octets.
50    check |= looking_for_separator | !separator.ct_gt(&9);
51    let l = 0u32.ct_select(&(k as u32 - separator - 1), !looking_for_separator);
52    (check, l)
53}
54
55/// Step 5: select the last AL octets of AM if check is set, otherwise the last L of EM.
56///
57/// Select the entire encoded buffer in place before exposing the final length. Both EM and AM are
58/// read at every offset, independently of check, AL, and L. The caller may then expose the returned
59/// length and copy that suffix of EM.
60///
61/// The buffers must have the same public length `k`; AL and L must be at most `k`.
62#[inline]
63pub(crate) fn select_message(em: &mut [u8], am: &[u8], al: u16, l: u32, check: Choice) -> u32 {
64    debug_assert_eq!(em.len(), am.len());
65    let length = l.ct_select(&u32::from(al), check);
66    for (em_octet, am_octet) in em.iter_mut().zip(am) {
67        em_octet.ct_assign(am_octet, check);
68    }
69    length
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn last_admissible_length() {
78        let mut cl = [0xff; 256];
79        cl[..2].copy_from_slice(&5u16.to_be_bytes());
80        cl[252..254].copy_from_slice(&20u16.to_be_bytes());
81        assert_eq!(select_al(&cl, 20), 20);
82        cl[..2].fill(0xff);
83        cl[252..254].fill(0xff);
84        assert_eq!(select_al(&cl, 20), 0);
85        assert_eq!(select_al(&cl, 0), 0);
86    }
87
88    #[test]
89    fn every_separator_and_header() {
90        const K: usize = 32;
91        let am = [0xa5; K];
92        // Includes missing separator, PS lengths 0..7, empty and maximum messages, and later zeros
93        // which must not change the first separator's meaning.
94        for header in [[0, 2], [1, 2], [0, 1], [1, 1], [0, 0]] {
95            for separator in 2..=K {
96                for later_zero in [false, true] {
97                    let mut original = [0x42; K];
98                    original[..2].copy_from_slice(&header);
99                    if separator < K {
100                        original[separator] = 0;
101                        if later_zero {
102                            original[K - 1] = 0;
103                        }
104                    }
105                    let (check, l) = eme_pkcs1v15_decode(&original, K);
106                    let invalid = header != [0, 2] || !(10..K).contains(&separator);
107                    let expected_l = if separator < K { K - separator - 1 } else { 0 };
108                    assert_eq!(check.to_bool(), invalid);
109                    assert_eq!(l as usize, expected_l);
110                    for al in [0, 1, 21] {
111                        let mut em = original;
112                        let length = select_message(&mut em, &am, al, l, check) as usize;
113                        let expected = if invalid {
114                            &am[K - usize::from(al)..]
115                        } else {
116                            &original[K - expected_l..]
117                        };
118                        assert_eq!(&em[K - length..], expected);
119                    }
120                }
121            }
122        }
123    }
124
125    #[test]
126    fn minimum_modulus_length() {
127        let em = [0, 2, 1, 2, 3, 4, 5, 6, 7, 8, 0];
128        let (check, l) = eme_pkcs1v15_decode(&em, em.len());
129        assert!(!check.to_bool());
130        assert_eq!(l, 0);
131    }
132}