Skip to main content

rsa/
oaep.rs

1//! Encryption and Decryption using [OAEP padding](https://datatracker.ietf.org/doc/html/rfc8017#section-7.1).
2//!
3//! # Usage
4//!
5//! See [code example in the toplevel rustdoc](../index.html#oaep-encryption).
6
7mod decrypting_key;
8mod encrypting_key;
9
10pub use self::{decrypting_key::DecryptingKey, encrypting_key::EncryptingKey};
11
12use alloc::boxed::Box;
13use alloc::vec::Vec;
14use core::fmt;
15
16use digest::{Digest, FixedOutputReset};
17use rand_core::TryCryptoRng;
18
19use crate::algorithms::oaep::*;
20use crate::algorithms::pad::{i2osp, i2osp_zeroizing, os2ip, os2ip_zeroizing};
21use crate::algorithms::rsa::{rsa_decrypt_and_check, rsa_encrypt};
22use crate::errors::{Error, Result};
23use crate::traits::{PaddingScheme, PublicKeyParts};
24use crate::{PrivateKey, PublicKey, public_key};
25
26#[cfg(feature = "getrandom")]
27use crypto_common::getrandom::SysRng;
28
29impl PublicKey {
30    /// Encrypt `plaintext` using OAEP and the operating system RNG.
31    ///
32    /// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
33    /// digest or a nonempty label, use [`EncryptingKey`].
34    ///
35    /// # Errors
36    /// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
37    #[cfg(feature = "getrandom")]
38    pub fn oaep_encrypt<D>(&self, plaintext: &[u8]) -> Result<Vec<u8>>
39    where
40        D: Digest + FixedOutputReset,
41    {
42        self.oaep_encrypt_with_rng::<D, _>(&mut SysRng, plaintext)
43    }
44
45    /// Encrypt `plaintext` using OAEP and the provided RNG.
46    ///
47    /// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
48    /// digest or a nonempty label, use [`EncryptingKey`].
49    ///
50    /// # Errors
51    /// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
52    pub fn oaep_encrypt_with_rng<D, R>(&self, rng: &mut R, plaintext: &[u8]) -> Result<Vec<u8>>
53    where
54        D: Digest + FixedOutputReset,
55        R: TryCryptoRng + ?Sized,
56    {
57        encrypt_digest::<_, D, D>(rng, self, plaintext, None)
58    }
59}
60
61impl PrivateKey {
62    /// Decrypt `ciphertext` using OAEP.
63    ///
64    /// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
65    /// digest or a nonempty label, use [`DecryptingKey`].
66    ///
67    /// Uses the operating system RNG for blinding when `getrandom` is enabled.
68    /// Otherwise, this operation is unblinded; use [`Self::oaep_decrypt_with_rng`]
69    /// to provide blinding randomness.
70    ///
71    /// # Errors
72    /// Returns an error if the key or ciphertext is invalid or the private operation
73    /// fails, including RNG failures.
74    pub fn oaep_decrypt<D>(&self, ciphertext: &[u8]) -> Result<Vec<u8>>
75    where
76        D: Digest + FixedOutputReset,
77    {
78        #[cfg(feature = "getrandom")]
79        {
80            self.oaep_decrypt_with_rng::<D, _>(&mut SysRng, ciphertext)
81        }
82        #[cfg(not(feature = "getrandom"))]
83        {
84            decrypt_digest::<crate::dummy_rng::DummyRng, D, D>(None, self, ciphertext, None)
85        }
86    }
87
88    /// Decrypt `ciphertext` using OAEP, using the provided RNG for blinding.
89    ///
90    /// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
91    /// digest or a nonempty label, use [`DecryptingKey`].
92    ///
93    /// # Errors
94    /// Returns an error if the key or ciphertext is invalid or the private operation
95    /// fails, including RNG failures.
96    pub fn oaep_decrypt_with_rng<D, R>(&self, rng: &mut R, ciphertext: &[u8]) -> Result<Vec<u8>>
97    where
98        D: Digest + FixedOutputReset,
99        R: TryCryptoRng + ?Sized,
100    {
101        decrypt_digest::<_, D, D>(Some(rng), self, ciphertext, None)
102    }
103}
104
105/// Encryption and Decryption using [OAEP padding](https://datatracker.ietf.org/doc/html/rfc8017#section-7.1).
106///
107/// - `digest` is used to hash the label. The maximum possible plaintext length is `m = k - 2 * h_len - 2`,
108///   where `k` is the size of the RSA modulus.
109/// - `mgf_digest` specifies the hash function that is used in the [MGF1](https://datatracker.ietf.org/doc/html/rfc8017#appendix-B.2).
110/// - `label` is optional data that can be associated with the message.
111///
112/// The two hash functions can, but don't need to be the same.
113///
114/// A prominent example is the [`AndroidKeyStore`](https://developer.android.com/guide/topics/security/cryptography#oaep-mgf1-digest).
115/// It uses SHA-1 for `mgf_digest` and a user-chosen SHA flavour for `digest`.
116pub struct Oaep<D, MGD = D> {
117    /// Digest type to use.
118    pub digest: D,
119
120    /// Digest to use for Mask Generation Function (MGF).
121    pub mgf_digest: MGD,
122
123    /// Optional label.
124    pub label: Option<Box<[u8]>>,
125}
126
127impl<D> Default for Oaep<D>
128where
129    D: Digest + FixedOutputReset,
130{
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl<D> Oaep<D>
137where
138    D: Digest + FixedOutputReset,
139{
140    /// Create a new OAEP `PaddingScheme`, using `T` as the hash function for both the default (empty) label and for MGF1.
141    ///
142    /// # Example
143    /// ```
144    /// use sha1::Sha1;
145    /// use sha2::Sha256;
146    /// use rsa::{PublicKey, Oaep};
147    /// use base64ct::{Base64, Encoding};
148    /// use crypto_bigint::BoxedUint;
149    ///
150    /// let n_bytes = Base64::decode_vec("seAOhmYFAjH6NOaB54dboqw86uPXV/oK9ayJGV4mVClbvsDBJmF3bVkOaVMp9ogcFJTFFSy5g2HsTZIfHyuQVUJADb+BeRnkYrYhRvNJOKj2pcDbkxYe9XGMx8pIvxkDFnIpusb3gUsuzMUAU5qIstjwQKzuD51c6uJi0HAtQkr6Wmlt34SX7xkD/MfRuTu9uqmHmkiiJaCDHB2reYTPguetSWfuvp1qBJDNgSsp7BjwYANWldyrmZ8cLXEXYMUG5vtsWMxUzl8ertEr6kbnGM0OJghNuEtittW/dfTPvk683R1jj0hNaMzvHK8xYldUlLuwmWCYIIvpHBaA/w+FwQ==").unwrap();
151    /// let e_bytes = Base64::decode_vec("AQAB").unwrap();
152    /// let n = BoxedUint::from_be_slice(&n_bytes, 2048).unwrap();
153    /// let e = BoxedUint::from_be_slice(&e_bytes, 32).unwrap();
154    ///
155    /// let mut rng = rand::rng();
156    /// let key = PublicKey::new(n, e).unwrap();
157    /// let padding = Oaep::<Sha256>::new();
158    /// let encrypted_data = key.encrypt(&mut rng, padding, b"secret").unwrap();
159    /// ```
160    #[must_use]
161    pub fn new() -> Self {
162        Self {
163            digest: D::new(),
164            mgf_digest: D::new(),
165            label: None,
166        }
167    }
168
169    /// Create a new OAEP `PaddingScheme` with an associated `label`, using `T` as the hash function for both the label and for MGF1.
170    pub fn new_with_label<S: Into<Box<[u8]>>>(label: S) -> Self {
171        Self {
172            digest: D::new(),
173            mgf_digest: D::new(),
174            label: Some(label.into()),
175        }
176    }
177}
178
179impl<D, MGD> Oaep<D, MGD>
180where
181    D: Digest + FixedOutputReset,
182    MGD: Digest + FixedOutputReset,
183{
184    /// Create a new OAEP `PaddingScheme`, using `T` as the hash function for the default (empty) label, and `U` as the hash function for MGF1.
185    /// If a label is needed use `PaddingScheme::new_oaep_with_label` or `PaddingScheme::new_oaep_with_mgf_hash_with_label`.
186    ///
187    /// # Example
188    /// ```
189    /// use sha1::Sha1;
190    /// use sha2::Sha256;
191    /// use rsa::{PublicKey, Oaep};
192    /// use base64ct::{Base64, Encoding};
193    /// use crypto_bigint::BoxedUint;
194    ///
195    /// let n_bytes = Base64::decode_vec("seAOhmYFAjH6NOaB54dboqw86uPXV/oK9ayJGV4mVClbvsDBJmF3bVkOaVMp9ogcFJTFFSy5g2HsTZIfHyuQVUJADb+BeRnkYrYhRvNJOKj2pcDbkxYe9XGMx8pIvxkDFnIpusb3gUsuzMUAU5qIstjwQKzuD51c6uJi0HAtQkr6Wmlt34SX7xkD/MfRuTu9uqmHmkiiJaCDHB2reYTPguetSWfuvp1qBJDNgSsp7BjwYANWldyrmZ8cLXEXYMUG5vtsWMxUzl8ertEr6kbnGM0OJghNuEtittW/dfTPvk683R1jj0hNaMzvHK8xYldUlLuwmWCYIIvpHBaA/w+FwQ==").unwrap();
196    /// let e_bytes = Base64::decode_vec("AQAB").unwrap();
197    /// let n = BoxedUint::from_be_slice(&n_bytes, 2048).unwrap();
198    /// let e = BoxedUint::from_be_slice(&e_bytes, 32).unwrap();
199    ///
200    /// let mut rng = rand::rng();
201    /// let key = PublicKey::new(n, e).unwrap();
202    /// let padding = Oaep::<Sha256, Sha1>::new_with_mgf_hash();
203    /// let encrypted_data = key.encrypt(&mut rng, padding, b"secret").unwrap();
204    /// ```
205    #[must_use]
206    pub fn new_with_mgf_hash() -> Self {
207        Self {
208            digest: D::new(),
209            mgf_digest: MGD::new(),
210            label: None,
211        }
212    }
213
214    /// Create a new OAEP `PaddingScheme` with an associated `label`, using `T` as the hash function for the label, and `U` as the hash function for MGF1.
215    pub fn new_with_mgf_hash_and_label<S: Into<Box<[u8]>>>(label: S) -> Self {
216        Self {
217            digest: D::new(),
218            mgf_digest: MGD::new(),
219            label: Some(label.into()),
220        }
221    }
222}
223
224impl<D, MGD> PaddingScheme for Oaep<D, MGD>
225where
226    D: Digest + FixedOutputReset,
227    MGD: Digest + FixedOutputReset,
228{
229    fn decrypt<Rng: TryCryptoRng + ?Sized>(
230        mut self,
231        rng: Option<&mut Rng>,
232        priv_key: &PrivateKey,
233        ciphertext: &[u8],
234    ) -> Result<Vec<u8>> {
235        decrypt(
236            rng,
237            priv_key,
238            ciphertext,
239            &mut self.digest,
240            &mut self.mgf_digest,
241            self.label,
242        )
243    }
244
245    fn encrypt<Rng: TryCryptoRng + ?Sized>(
246        mut self,
247        rng: &mut Rng,
248        pub_key: &PublicKey,
249        msg: &[u8],
250    ) -> Result<Vec<u8>> {
251        encrypt(
252            rng,
253            pub_key,
254            msg,
255            &mut self.digest,
256            &mut self.mgf_digest,
257            self.label,
258        )
259    }
260}
261
262impl<D, MGD> fmt::Debug for Oaep<D, MGD> {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        f.debug_struct("OAEP")
265            .field("digest", &"...")
266            .field("mgf_digest", &"...")
267            .field("label", &self.label)
268            .finish()
269    }
270}
271
272/// Encrypts the given message with RSA and the padding scheme from
273/// [PKCS#1 OAEP].
274///
275/// The message must be no longer than the length of the public modulus minus
276/// `2 + (2 * hash.size())`.
277///
278/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
279#[inline]
280fn encrypt<R, D, MGD>(
281    rng: &mut R,
282    pub_key: &PublicKey,
283    msg: &[u8],
284    digest: &mut D,
285    mgf_digest: &mut MGD,
286    label: Option<Box<[u8]>>,
287) -> Result<Vec<u8>>
288where
289    R: TryCryptoRng + ?Sized,
290    D: Digest + FixedOutputReset,
291    MGD: Digest + FixedOutputReset,
292{
293    public_key::check_public(pub_key)?;
294
295    let em = oaep_encrypt(rng, msg, digest, mgf_digest, label, pub_key.size())?;
296
297    let int = os2ip_zeroizing(em, pub_key.n_bits_precision())?;
298    Ok(i2osp(rsa_encrypt(pub_key, &int)?, pub_key.size()))
299}
300
301/// Encrypts the given message with RSA and the padding scheme from
302/// [PKCS#1 OAEP].
303///
304/// The message must be no longer than the length of the public modulus minus
305/// `2 + (2 * hash.size())`.
306///
307/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
308fn encrypt_digest<R, D, MGD>(
309    rng: &mut R,
310    pub_key: &PublicKey,
311    msg: &[u8],
312    label: Option<Box<[u8]>>,
313) -> Result<Vec<u8>>
314where
315    R: TryCryptoRng + ?Sized,
316    D: Digest,
317    MGD: Digest + FixedOutputReset,
318{
319    public_key::check_public(pub_key)?;
320
321    let em = oaep_encrypt_digest::<_, D, MGD>(rng, msg, label, pub_key.size())?;
322
323    let int = os2ip_zeroizing(em, pub_key.n_bits_precision())?;
324    Ok(i2osp(rsa_encrypt(pub_key, &int)?, pub_key.size()))
325}
326
327/// Decrypts a plaintext using RSA and the padding scheme from [PKCS#1 OAEP].
328///
329/// If an `rng` is passed, it uses RSA blinding to avoid timing side-channel attacks.
330///
331/// Note that whether this function returns an error or not discloses secret
332/// information. If an attacker can cause this function to run repeatedly and
333/// learn whether each instance returned an error then they can decrypt and
334/// forge signatures as if they had the private key.
335///
336/// See `decrypt_session_key` for a way of solving this problem.
337///
338/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
339#[inline]
340fn decrypt<R, D, MGD>(
341    rng: Option<&mut R>,
342    priv_key: &PrivateKey,
343    ciphertext: &[u8],
344    digest: &mut D,
345    mgf_digest: &mut MGD,
346    label: Option<Box<[u8]>>,
347) -> Result<Vec<u8>>
348where
349    R: TryCryptoRng + ?Sized,
350    D: Digest + FixedOutputReset,
351    MGD: Digest + FixedOutputReset,
352{
353    if ciphertext.len() != priv_key.size() {
354        return Err(Error::Decryption);
355    }
356
357    let ciphertext = os2ip(ciphertext, priv_key.n_bits_precision())?;
358
359    let em = rsa_decrypt_and_check(priv_key, rng, &ciphertext)?;
360    let mut em = i2osp_zeroizing(em, priv_key.size());
361
362    oaep_decrypt(&mut em, digest, mgf_digest, label, priv_key.size())
363}
364
365/// Decrypts a plaintext using RSA and the padding scheme from [PKCS#1 OAEP].
366///
367/// If an `rng` is passed, it uses RSA blinding to avoid timing side-channel attacks.
368///
369/// Note that whether this function returns an error or not discloses secret
370/// information. If an attacker can cause this function to run repeatedly and
371/// learn whether each instance returned an error then they can decrypt and
372/// forge signatures as if they had the private key.
373///
374/// See `decrypt_session_key` for a way of solving this problem.
375///
376/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
377#[inline]
378fn decrypt_digest<R, D, MGD>(
379    rng: Option<&mut R>,
380    priv_key: &PrivateKey,
381    ciphertext: &[u8],
382    label: Option<Box<[u8]>>,
383) -> Result<Vec<u8>>
384where
385    R: TryCryptoRng + ?Sized,
386    D: Digest,
387    MGD: Digest + FixedOutputReset,
388{
389    public_key::check_public(priv_key)?;
390
391    if ciphertext.len() != priv_key.size() {
392        return Err(Error::Decryption);
393    }
394
395    let ciphertext = os2ip(ciphertext, priv_key.n_bits_precision())?;
396    let em = rsa_decrypt_and_check(priv_key, rng, &ciphertext)?;
397    let mut em = i2osp_zeroizing(em, priv_key.size());
398
399    oaep_decrypt_digest::<D, MGD>(&mut em, label, priv_key.size())
400}
401
402#[cfg(test)]
403mod tests {
404    use crate::oaep::{DecryptingKey, EncryptingKey, Oaep};
405    use crate::traits::PublicKeyParts;
406    use crate::traits::{Decryptor, RandomizedDecryptor, RandomizedEncryptor};
407    use crate::{PrivateKey, PublicKey};
408
409    use alloc::boxed::Box;
410    use crypto_bigint::BoxedUint;
411    use digest::{Digest, FixedOutputReset};
412    use rand::rngs::ChaCha8Rng;
413    use rand_core::{Rng, SeedableRng};
414    use sha1::Sha1;
415    use sha2::{Sha224, Sha256, Sha384, Sha512};
416    use sha3::{Sha3_256, Sha3_384, Sha3_512};
417
418    fn get_private_key() -> PrivateKey {
419        // -----BEGIN RSA PRIVATE KEY-----
420        // MIIEpAIBAAKCAQEA05e4TZikwmE47RtpWoEG6tkdVTvwYEG2LT/cUKBB4iK49FKW
421        // icG4LF5xVU9d1p+i9LYVjPDb61eBGg/DJ+HyjnT+dNO8Fmweq9wbi1e5NMqL5bAL
422        // TymXW8yZrK9BW1m7KKZ4K7QaLDwpdrPBjbre9i8AxrsiZkAJUJbAzGDSL+fvmH11
423        // xqgbENlr8pICivEQ3HzBu8Q9Iq2rN5oM1dgHjMeA/1zWIJ3qNMkiz3hPdxfkKNdb
424        // WuyP8w5fAUFRB2bi4KuNRzyE6HELK5gifD2wlTN600UvGeK5v7zN2BSKv2d2+lUn
425        // debnWVbkUimuWpxGlJurHmIvDkj1ZSSoTtNIOwIDAQABAoIBAQDE5wxokWLJTGYI
426        // KBkbUrTYOSEV30hqmtvoMeRY1zlYMg3Bt1VFbpNwHpcC12+wuS+Q4B0f4kgVMoH+
427        // eaqXY6kvrmnY1+zRRN4p+hNb0U+Vc+NJ5FAx47dpgvWDADgmxVLomjl8Gga9IWNI
428        // hjDZLowrtkPXq+9wDaldaFyUFImkb1S1MW9itdLDp/G70TTLNzU6RGg/3J2V02RY
429        // 3iL2xEBX/nSgpDbEMI9z9NpC81xHrBanE41IOvyR5B3DoRJzguDA9RGbAiG0/GOd
430        // a5w4F3pt6bUm69iMONeYLAf5ig79h31Qiq4nW5RpFcAuLhEG0XXXTsZ3f16A0SwF
431        // PZx74eNBAoGBAPgnu/OkGHfHzFmuv0LtSynDLe/LjtloY9WwkKBaiTDdYkohydz5
432        // g4Vo/foN9luEYqXyrJE9bFb5dVMr2OePsHvUBcqZpIS89Z8Bm73cs5M/K85wYwC0
433        // 97EQEgxd+QGBWQZ8NdowYaVshjWlK1QnOzEnG0MR8Hld9gIeY1XhpC5hAoGBANpI
434        // F84Aid028q3mo/9BDHPsNL8bT2vaOEMb/t4RzvH39u+nDl+AY6Ox9uFylv+xX+76
435        // CRKgMluNH9ZaVZ5xe1uWHsNFBy4OxSA9A0QdKa9NZAVKBFB0EM8dp457YRnZCexm
436        // 5q1iW/mVsnmks8W+fYlc18W5xMSX/ecwkW/NtOQbAoGAHabpz4AhKFbodSLrWbzv
437        // CUt4NroVFKdjnoodjfujfwJFF2SYMV5jN9LG3lVCxca43ulzc1tqka33Nfv8TBcg
438        // WHuKQZ5ASVgm5VwU1wgDMSoQOve07MWy/yZTccTc1zA0ihDXgn3bfR/NnaVh2wlh
439        // CkuI92eyW1494hztc7qlmqECgYEA1zenyOQ9ChDIW/ABGIahaZamNxsNRrDFMl3j
440        // AD+cxHSRU59qC32CQH8ShRy/huHzTaPX2DZ9EEln76fnrS4Ey7uLH0rrFl1XvT6K
441        // /timJgLvMEvXTx/xBtUdRN2fUqXtI9odbSyCtOYFL+zVl44HJq2UzY4pVRDrNcxs
442        // SUkQJqsCgYBSaNfPBzR5rrstLtTdZrjImRW1LRQeDEky9WsMDtCTYUGJTsTSfVO8
443        // hkU82MpbRVBFIYx+GWIJwcZRcC7OCQoV48vMJllxMAAjqG/p00rVJ+nvA7et/nNu
444        // BoB0er/UmDm4Ly/97EO9A0PKMOE5YbMq9s3t3RlWcsdrU7dvw+p2+A==
445        // -----END RSA PRIVATE KEY-----
446
447        PrivateKey::from_components(
448            BoxedUint::from_be_hex("d397b84d98a4c26138ed1b695a8106ead91d553bf06041b62d3fdc50a041e222b8f4529689c1b82c5e71554f5dd69fa2f4b6158cf0dbeb57811a0fc327e1f28e74fe74d3bc166c1eabdc1b8b57b934ca8be5b00b4f29975bcc99acaf415b59bb28a6782bb41a2c3c2976b3c18dbadef62f00c6bb226640095096c0cc60d22fe7ef987d75c6a81b10d96bf292028af110dc7cc1bbc43d22adab379a0cd5d8078cc780ff5cd6209dea34c922cf784f7717e428d75b5aec8ff30e5f0141510766e2e0ab8d473c84e8710b2b98227c3db095337ad3452f19e2b9bfbccdd8148abf6776fa552775e6e75956e45229ae5a9c46949bab1e622f0e48f56524a84ed3483b", 2048).unwrap(),
449            BoxedUint::from(65_537u64),
450            BoxedUint::from_be_hex("c4e70c689162c94c660828191b52b4d8392115df486a9adbe831e458d73958320dc1b755456e93701e9702d76fb0b92f90e01d1fe248153281fe79aa9763a92fae69d8d7ecd144de29fa135bd14f9573e349e45031e3b76982f583003826c552e89a397c1a06bd2163488630d92e8c2bb643d7abef700da95d685c941489a46f54b5316f62b5d2c3a7f1bbd134cb37353a44683fdc9d95d36458de22f6c44057fe74a0a436c4308f73f4da42f35c47ac16a7138d483afc91e41dc3a1127382e0c0f5119b0221b4fc639d6b9c38177a6de9b526ebd88c38d7982c07f98a0efd877d508aae275b946915c02e2e1106d175d74ec6777f5e80d12c053d9c7be1e341", 2048).unwrap(),
451            vec![
452                BoxedUint::from_be_hex("f827bbf3a41877c7cc59aebf42ed4b29c32defcb8ed96863d5b090a05a8930dd624a21c9dcf9838568fdfa0df65b8462a5f2ac913d6c56f975532bd8e78fb07bd405ca99a484bcf59f019bbddcb3933f2bce706300b4f7b110120c5df9018159067c35da3061a56c8635a52b54273b31271b4311f0795df6021e6355e1a42e61", 1024).unwrap(),
453                BoxedUint::from_be_hex("da4817ce0089dd36f2ade6a3ff410c73ec34bf1b4f6bda38431bfede11cef1f7f6efa70e5f8063a3b1f6e17296ffb15feefa0912a0325b8d1fd65a559e717b5b961ec345072e0ec5203d03441d29af4d64054a04507410cf1da78e7b6119d909ec66e6ad625bf995b279a4b3c5be7d895cd7c5b9c4c497fde730916fcdb4e41b", 1024).unwrap()
454            ],
455        ).unwrap()
456    }
457
458    #[test]
459    fn test_encrypt_decrypt_oaep() {
460        let priv_key = get_private_key();
461        do_test_encrypt_decrypt_oaep::<Sha1>(&priv_key);
462        do_test_encrypt_decrypt_oaep::<Sha224>(&priv_key);
463        do_test_encrypt_decrypt_oaep::<Sha256>(&priv_key);
464        do_test_encrypt_decrypt_oaep::<Sha384>(&priv_key);
465        do_test_encrypt_decrypt_oaep::<Sha512>(&priv_key);
466        do_test_encrypt_decrypt_oaep::<Sha3_256>(&priv_key);
467        do_test_encrypt_decrypt_oaep::<Sha3_384>(&priv_key);
468        do_test_encrypt_decrypt_oaep::<Sha3_512>(&priv_key);
469
470        do_test_oaep_with_different_hashes::<Sha1, Sha1>(&priv_key);
471        do_test_oaep_with_different_hashes::<Sha224, Sha1>(&priv_key);
472        do_test_oaep_with_different_hashes::<Sha256, Sha1>(&priv_key);
473        do_test_oaep_with_different_hashes::<Sha384, Sha1>(&priv_key);
474        do_test_oaep_with_different_hashes::<Sha512, Sha1>(&priv_key);
475        do_test_oaep_with_different_hashes::<Sha3_256, Sha1>(&priv_key);
476        do_test_oaep_with_different_hashes::<Sha3_384, Sha1>(&priv_key);
477        do_test_oaep_with_different_hashes::<Sha3_512, Sha1>(&priv_key);
478    }
479
480    fn get_label(rng: &mut ChaCha8Rng) -> Option<Box<[u8]>> {
481        let mut buf = [0u8; 32];
482        rng.fill_bytes(&mut buf);
483
484        if rng.next_u32() % 2 == 0 {
485            Some(buf.into())
486        } else {
487            None
488        }
489    }
490
491    fn do_test_encrypt_decrypt_oaep<D: Digest + FixedOutputReset>(prk: &PrivateKey) {
492        let mut rng = ChaCha8Rng::from_seed([42; 32]);
493
494        let k = prk.size();
495
496        for i in 1..8 {
497            let mut input = vec![0u8; i * 8];
498            rng.fill_bytes(&mut input);
499
500            if input.len() > k - 11 {
501                input = input[0..k - 11].to_vec();
502            }
503            let label = get_label(&mut rng);
504
505            let pub_key: PublicKey = prk.into();
506
507            let ciphertext = if let Some(ref label) = label {
508                let padding = Oaep::<D>::new_with_label(label.clone());
509                pub_key.encrypt(&mut rng, padding, &input).unwrap()
510            } else {
511                let padding = Oaep::<D>::new();
512                pub_key.encrypt(&mut rng, padding, &input).unwrap()
513            };
514
515            assert_ne!(input, ciphertext);
516            let blind: bool = rng.next_u32() < (1 << 31);
517
518            let padding = if let Some(label) = label {
519                Oaep::<D>::new_with_label::<Box<[u8]>>(label)
520            } else {
521                Oaep::<D>::new()
522            };
523
524            let plaintext = if blind {
525                prk.decrypt(padding, &ciphertext).unwrap()
526            } else {
527                prk.decrypt_blinded(&mut rng, padding, &ciphertext).unwrap()
528            };
529
530            assert_eq!(input, plaintext);
531        }
532    }
533
534    fn do_test_oaep_with_different_hashes<
535        D: Digest + FixedOutputReset,
536        U: Digest + FixedOutputReset,
537    >(
538        prk: &PrivateKey,
539    ) {
540        let mut rng = ChaCha8Rng::from_seed([42; 32]);
541
542        let k = prk.size();
543
544        for i in 1..8 {
545            let mut input = vec![0u8; i * 8];
546            rng.fill_bytes(&mut input);
547
548            if input.len() > k - 11 {
549                input = input[0..k - 11].to_vec();
550            }
551            let label = get_label(&mut rng);
552
553            let pub_key: PublicKey = prk.into();
554
555            let ciphertext = if let Some(ref label) = label {
556                let padding = Oaep::<D, U>::new_with_mgf_hash_and_label::<_>(label.clone());
557                pub_key.encrypt(&mut rng, padding, &input).unwrap()
558            } else {
559                let padding = Oaep::<D, U>::new_with_mgf_hash();
560                pub_key.encrypt(&mut rng, padding, &input).unwrap()
561            };
562
563            assert_ne!(input, ciphertext);
564            let blind: bool = rng.next_u32() < (1 << 31);
565
566            let padding = if let Some(label) = label {
567                Oaep::<D, U>::new_with_mgf_hash_and_label::<_>(label)
568            } else {
569                Oaep::<D, U>::new_with_mgf_hash()
570            };
571
572            let plaintext = if blind {
573                prk.decrypt(padding, &ciphertext).unwrap()
574            } else {
575                prk.decrypt_blinded(&mut rng, padding, &ciphertext).unwrap()
576            };
577
578            assert_eq!(input, plaintext);
579        }
580    }
581
582    #[test]
583    fn test_decrypt_oaep_invalid_hash() {
584        let mut rng = ChaCha8Rng::from_seed([42; 32]);
585        let priv_key = get_private_key();
586        let pub_key: PublicKey = (&priv_key).into();
587        let ciphertext = pub_key
588            .encrypt(&mut rng, Oaep::<Sha1>::new(), "a_plain_text".as_bytes())
589            .unwrap();
590        assert!(
591            priv_key
592                .decrypt_blinded(
593                    &mut rng,
594                    Oaep::<Sha1>::new_with_label::<_>("label".as_bytes()),
595                    &ciphertext,
596                )
597                .is_err(),
598            "decrypt should have failed on hash verification"
599        );
600    }
601
602    #[test]
603    fn test_encrypt_decrypt_oaep_traits() {
604        let priv_key = get_private_key();
605        do_test_encrypt_decrypt_oaep_traits::<Sha1>(&priv_key);
606        do_test_encrypt_decrypt_oaep_traits::<Sha224>(&priv_key);
607        do_test_encrypt_decrypt_oaep_traits::<Sha256>(&priv_key);
608        do_test_encrypt_decrypt_oaep_traits::<Sha384>(&priv_key);
609        do_test_encrypt_decrypt_oaep_traits::<Sha512>(&priv_key);
610        do_test_encrypt_decrypt_oaep_traits::<Sha3_256>(&priv_key);
611        do_test_encrypt_decrypt_oaep_traits::<Sha3_384>(&priv_key);
612        do_test_encrypt_decrypt_oaep_traits::<Sha3_512>(&priv_key);
613
614        do_test_oaep_with_different_hashes_traits::<Sha1, Sha1>(&priv_key);
615        do_test_oaep_with_different_hashes_traits::<Sha224, Sha1>(&priv_key);
616        do_test_oaep_with_different_hashes_traits::<Sha256, Sha1>(&priv_key);
617        do_test_oaep_with_different_hashes_traits::<Sha384, Sha1>(&priv_key);
618        do_test_oaep_with_different_hashes_traits::<Sha512, Sha1>(&priv_key);
619        do_test_oaep_with_different_hashes_traits::<Sha3_256, Sha1>(&priv_key);
620        do_test_oaep_with_different_hashes_traits::<Sha3_384, Sha1>(&priv_key);
621        do_test_oaep_with_different_hashes_traits::<Sha3_512, Sha1>(&priv_key);
622    }
623
624    fn do_test_encrypt_decrypt_oaep_traits<D: Digest + FixedOutputReset>(prk: &PrivateKey) {
625        do_test_oaep_with_different_hashes_traits::<D, D>(prk);
626    }
627
628    fn do_test_oaep_with_different_hashes_traits<D: Digest, MGD: Digest + FixedOutputReset>(
629        prk: &PrivateKey,
630    ) {
631        let mut rng = ChaCha8Rng::from_seed([42; 32]);
632
633        let k = prk.size();
634
635        for i in 1..8 {
636            let mut input = vec![0u8; i * 8];
637            rng.fill_bytes(&mut input);
638
639            if input.len() > k - 11 {
640                input = input[0..k - 11].to_vec();
641            }
642            let label = get_label(&mut rng);
643
644            let pub_key: PublicKey = prk.into();
645
646            let ciphertext = if let Some(ref label) = label {
647                let encrypting_key =
648                    EncryptingKey::<D, MGD>::new_with_label(pub_key, label.clone());
649                encrypting_key.encrypt_with_rng(&mut rng, &input).unwrap()
650            } else {
651                let encrypting_key = EncryptingKey::<D, MGD>::new(pub_key);
652                encrypting_key.encrypt_with_rng(&mut rng, &input).unwrap()
653            };
654
655            assert_ne!(input, ciphertext);
656            let blind: bool = rng.next_u32() < (1 << 31);
657
658            let decrypting_key = if let Some(ref label) = label {
659                DecryptingKey::<D, MGD>::new_with_label(prk.clone(), label.clone())
660            } else {
661                DecryptingKey::<D, MGD>::new(prk.clone())
662            };
663
664            let plaintext = if blind {
665                decrypting_key.decrypt(&ciphertext).unwrap()
666            } else {
667                decrypting_key
668                    .decrypt_with_rng(&mut rng, &ciphertext)
669                    .unwrap()
670            };
671
672            assert_eq!(input, plaintext);
673        }
674    }
675
676    #[test]
677    fn test_decrypt_oaep_invalid_hash_traits() {
678        let mut rng = ChaCha8Rng::from_seed([42; 32]);
679        let priv_key = get_private_key();
680        let pub_key: PublicKey = (&priv_key).into();
681        let encrypting_key = EncryptingKey::<Sha1>::new(pub_key);
682        let decrypting_key = DecryptingKey::<Sha1>::new_with_label(priv_key, "label".as_bytes());
683        let ciphertext = encrypting_key
684            .encrypt_with_rng(&mut rng, "a_plain_text".as_bytes())
685            .unwrap();
686        assert!(
687            decrypting_key
688                .decrypt_with_rng(&mut rng, &ciphertext)
689                .is_err(),
690            "decrypt should have failed on hash verification"
691        );
692    }
693}