1mod 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 #[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 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 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 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
105pub struct Oaep<D, MGD = D> {
117 pub digest: D,
119
120 pub mgf_digest: MGD,
122
123 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 #[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 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 #[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 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#[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
301fn 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#[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#[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 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}