Skip to main content

rsa/algorithms/pkcs1v15/
implicit_rejection.rs

1//! Deterministic fallback derivation from [draft-irtf-cfrg-rsa-guidance-10 §7.1–7.2].
2//!
3//! These helpers implement step 3 of §7.2. The caller is then expected to perform decoding and
4//! message selection without exposing padding validity or the alternative length.
5//!
6//! [draft-irtf-cfrg-rsa-guidance-10 §7.1–7.2]: https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-7.1
7
8use super::selection::select_al;
9use crate::{
10    algorithms::pad::i2osp_zeroizing,
11    errors::{Error, Result},
12};
13use alloc::vec::Vec;
14use crypto_bigint::BoxedUint;
15use digest::Digest;
16use hmac::{Hmac, KeyInit, Mac};
17use sha2::Sha256;
18use zeroize::Zeroizing;
19
20/// Key derivation key for one private key and ciphertext.
21pub(crate) struct KeyDerivationKey(Zeroizing<[u8; 32]>);
22
23impl KeyDerivationKey {
24    /// Computes `HMAC-SHA256(SHA256(I2OSP(d, k)), ciphertext)`.
25    ///
26    /// The caller must establish that d fits in k octets and that its storage precision is public.
27    ///
28    /// Use the supplied private exponent, not a reconstructed equivalent exponent. The ciphertext
29    /// must have passed the public length check.
30    pub(crate) fn derive(d: &BoxedUint, k: usize, ciphertext: &[u8]) -> Result<Self> {
31        if k < 11 || ciphertext.len() != k {
32            return Err(Error::Decryption);
33        }
34
35        // Step 3.1.1: D = I2OSP(d, k).
36        let d = i2osp_zeroizing(d.clone(), k);
37
38        // Step 3.1.2: DH = SHA256(D).
39        let dh: Zeroizing<[u8; 32]> = Zeroizing::new(Sha256::digest(&*d).into());
40
41        // Step 3.1.3: KDK = HMAC(DH, C, SHA256).
42        let mut mac = Hmac::<Sha256>::new_from_slice(dh.as_ref()).map_err(|_| Error::Internal)?;
43        mac.update(ciphertext);
44        Ok(Self(Zeroizing::new(mac.finalize().into_bytes().into())))
45    }
46
47    /// Derives the full alternative message and its candidate suffix length.
48    ///
49    /// Both the length and message remain secret until the caller selects the final result together
50    /// with the real plaintext. Do not slice at this candidate length  or expose it separately
51    /// before that selection.
52    pub(crate) fn alternative_message(&self, k: usize) -> Result<(Zeroizing<Vec<u8>>, u16)> {
53        let max_message_len = k
54            .checked_sub(11)
55            .and_then(|len| u16::try_from(len).ok())
56            .ok_or(Error::Decryption)?;
57
58        // Step 3.2.1: CL = IRPRF(KDK, "length", 256).
59        let cl = self.irprf(b"length", 256)?;
60
61        // Step 3.2.2: AM = IRPRF(KDK, "message", k).
62        let am = self.irprf(b"message", k)?;
63
64        // Step 3.3: AL is the last admissible candidate, or zero.
65        let al = select_al(&cl, max_message_len);
66        Ok((am, al))
67    }
68
69    /// Computes the `IRPRF` from `draft-irtf-cfrg-rsa-guidance-10` §7.1, returning a zeroizing
70    /// output buffer.
71    fn irprf(&self, label: &[u8], length: usize) -> Result<Zeroizing<Vec<u8>>> {
72        let bit_length = length
73            .checked_mul(8)
74            .and_then(|bits| u16::try_from(bits).ok())
75            .ok_or(Error::Decryption)?
76            .to_be_bytes();
77
78        let mut output = Zeroizing::new(vec![0u8; length]);
79        for (i, chunk) in (0u16..).zip(output.chunks_mut(32)) {
80            let mut mac =
81                Hmac::<Sha256>::new_from_slice(self.0.as_ref()).map_err(|_| Error::Internal)?;
82            mac.update(&i.to_be_bytes());
83            mac.update(label);
84            mac.update(&bit_length);
85            let block: Zeroizing<[u8; 32]> = Zeroizing::new(mac.finalize().into_bytes().into());
86            chunk.copy_from_slice(&block[..chunk.len()]);
87        }
88        Ok(output)
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn length_mask_boundary() {
98        // Reproduces the k - 10 mask bug from #702 using real IRPRF output.
99        let mut key = [0u8; 32];
100        key[31] = 2;
101        let kdk = KeyDerivationKey(Zeroizing::new(key));
102        assert_eq!(kdk.alternative_message(138).unwrap().1, 105);
103        assert_eq!(kdk.alternative_message(266).unwrap().1, 233);
104    }
105
106    #[test]
107    fn public_length_errors() {
108        let d = BoxedUint::from(1u64);
109        assert!(KeyDerivationKey::derive(&d, 10, &[0; 10]).is_err());
110        assert!(KeyDerivationKey::derive(&d, 11, &[0; 10]).is_err());
111        assert!(KeyDerivationKey::derive(&d, 11, &[0; 12]).is_err());
112        let kdk = KeyDerivationKey::derive(&d, 11, &[0; 11]).unwrap();
113        assert!(kdk.alternative_message(10).is_err());
114        assert_eq!(kdk.alternative_message(11).unwrap().1, 0);
115        assert!(kdk.irprf(b"message", 0).unwrap().is_empty());
116        assert_eq!(kdk.irprf(b"message", 8191).unwrap().len(), 8191);
117        assert!(kdk.irprf(b"message", 8192).is_err());
118        assert!(kdk.irprf(b"message", usize::MAX).is_err());
119    }
120
121    #[cfg(feature = "encoding")]
122    mod vectors {
123        use super::*;
124        use crate::{
125            PrivateKey,
126            algorithms::{pad::os2ip, pkcs1v15::eme_pkcs1v15_decode, rsa::rsa_decrypt_and_check},
127            pkcs1v15::{DecryptingKey, Pkcs1v15Encrypt},
128            traits::{Decryptor, PaddingScheme, PublicKeyParts, RandomizedDecryptor},
129        };
130        use alloc::{collections::BTreeMap, string::String};
131        use pkcs8::DecodePrivateKey;
132        use rand::rngs::ChaCha8Rng;
133        use rand_core::SeedableRng;
134        use serde::Deserialize;
135
136        #[derive(Deserialize)]
137        struct Section {
138            key_pem: String,
139            cases: Vec<Case>,
140        }
141
142        #[derive(Deserialize)]
143        struct Case {
144            id: String,
145            valid: bool,
146            ciphertext_hex: String,
147            expect: Expected,
148        }
149
150        #[derive(Deserialize)]
151        struct Expected {
152            #[serde(default)]
153            empty: bool,
154            ascii: Option<String>,
155            hex: Option<String>,
156        }
157
158        macro_rules! fixture {
159            ($name:literal) => {
160                include_str!(concat!(
161                    env!("CARGO_MANIFEST_DIR"),
162                    "/tests/examples/pkcs1v15_cfrg_rsa_guidance/",
163                    $name
164                ))
165            };
166        }
167
168        #[rstest::rstest]
169        #[case("B.1")]
170        #[case("B.2")]
171        #[case("B.3")]
172        #[case("B.4")]
173        fn draft_10_vectors(#[case] section: &str) {
174            let data: BTreeMap<String, Section> =
175                serde_json::from_str(fixture!("test_cases.json")).unwrap();
176            let section = &data[section];
177            let pem = match section.key_pem.as_str() {
178                "k2048.pem" => fixture!("k2048.pem"),
179                "k2049.pem" => fixture!("k2049.pem"),
180                "k3072.pem" => fixture!("k3072.pem"),
181                "k4096.pem" => fixture!("k4096.pem"),
182                _ => panic!("unknown key fixture"),
183            };
184            let key = PrivateKey::from_pkcs8_pem(pem).unwrap();
185            let k = key.size();
186            let typed_key = DecryptingKey::new(key.clone());
187            let mut rng = ChaCha8Rng::from_seed([42; 32]);
188            assert_eq!(section.cases.len(), 12);
189
190            for case in &section.cases {
191                let ciphertext = hex::decode(&case.ciphertext_hex).unwrap();
192                assert_eq!(ciphertext.len(), k, "{}", case.id);
193                let c = os2ip(&ciphertext, key.n_bits_precision()).unwrap();
194                let m = rsa_decrypt_and_check::<ChaCha8Rng>(&key, None, &c).unwrap();
195                let em = i2osp_zeroizing(m, k);
196                let (check, _) = eme_pkcs1v15_decode(&em, k);
197                assert_eq!(!check.to_bool(), case.valid, "{}", case.id);
198
199                let expected = if case.expect.empty {
200                    Vec::new()
201                } else if let Some(ascii) = &case.expect.ascii {
202                    ascii.as_bytes().to_vec()
203                } else {
204                    hex::decode(case.expect.hex.as_ref().unwrap()).unwrap()
205                };
206
207                // Exercise the actual scheme and both public APIs. Different blinding randomness
208                // and repeated calls must not change synthetic plaintext.
209                let outputs = [
210                    Pkcs1v15Encrypt
211                        .decrypt::<ChaCha8Rng>(None, &key, &ciphertext)
212                        .unwrap(),
213                    key.decrypt(Pkcs1v15Encrypt, &ciphertext).unwrap(),
214                    key.decrypt_blinded(&mut rng, Pkcs1v15Encrypt, &ciphertext)
215                        .unwrap(),
216                    typed_key.decrypt(&ciphertext).unwrap(),
217                    typed_key.decrypt_with_rng(&mut rng, &ciphertext).unwrap(),
218                ];
219                for got in outputs {
220                    assert_eq!(got, expected, "{}", case.id);
221                }
222            }
223        }
224    }
225}