rsa/oaep/
encrypting_key.rs

1use super::encrypt_digest;
2use crate::{traits::RandomizedEncryptor, Result, RsaPublicKey};
3use alloc::{
4    string::{String, ToString},
5    vec::Vec,
6};
7use core::marker::PhantomData;
8use digest::{Digest, FixedOutputReset};
9use rand_core::CryptoRngCore;
10
11/// Encryption key for PKCS#1 v1.5 encryption as described in [RFC8017 § 7.1].
12///
13/// [RFC8017 § 7.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
14#[derive(Debug, Clone)]
15pub struct EncryptingKey<D, MGD = D>
16where
17    D: Digest,
18    MGD: Digest + FixedOutputReset,
19{
20    inner: RsaPublicKey,
21    label: Option<String>,
22    phantom: PhantomData<D>,
23    mg_phantom: PhantomData<MGD>,
24}
25
26impl<D, MGD> EncryptingKey<D, MGD>
27where
28    D: Digest,
29    MGD: Digest + FixedOutputReset,
30{
31    /// Create a new verifying key from an RSA public key.
32    pub fn new(key: RsaPublicKey) -> Self {
33        Self {
34            inner: key,
35            label: None,
36            phantom: Default::default(),
37            mg_phantom: Default::default(),
38        }
39    }
40
41    /// Create a new verifying key from an RSA public key using provided label
42    pub fn new_with_label<S: AsRef<str>>(key: RsaPublicKey, label: S) -> Self {
43        Self {
44            inner: key,
45            label: Some(label.as_ref().to_string()),
46            phantom: Default::default(),
47            mg_phantom: Default::default(),
48        }
49    }
50}
51
52impl<D, MGD> RandomizedEncryptor for EncryptingKey<D, MGD>
53where
54    D: Digest,
55    MGD: Digest + FixedOutputReset,
56{
57    fn encrypt_with_rng<R: CryptoRngCore + ?Sized>(
58        &self,
59        rng: &mut R,
60        msg: &[u8],
61    ) -> Result<Vec<u8>> {
62        encrypt_digest::<_, D, MGD>(rng, &self.inner, msg, self.label.as_ref().cloned())
63    }
64}