Skip to main content

rsa/
public_key.rs

1//! RSA public key type.
2
3use crate::traits::{PaddingScheme, PublicKeyParts, SignatureScheme};
4use crate::{Error, PrivateKey, Result};
5use alloc::vec::Vec;
6use core::hash::{Hash, Hasher};
7use core::ops::RangeInclusive;
8use crypto_bigint::modular::BoxedMontyParams;
9use crypto_bigint::{BoxedUint, Integer, NonZero, Odd};
10use rand_core::TryCryptoRng;
11
12#[cfg(feature = "serde")]
13use {
14    serdect::serde::{Deserialize, Serialize, de, ser},
15    spki::{DecodePublicKey, EncodePublicKey},
16};
17
18/// Represents the public part of an RSA key.
19#[derive(Debug, Clone)]
20pub struct PublicKey {
21    /// Modulus: product of prime numbers `p` and `q`
22    pub(crate) n: NonZero<BoxedUint>,
23
24    /// Public exponent: power to which a plaintext message is raised in
25    /// order to encrypt it.
26    ///
27    /// The recommended value is `0x10001` (`65537`).
28    pub(crate) e: BoxedUint,
29
30    /// `n` represented as its Montgomery parameters.
31    pub(crate) n_params: BoxedMontyParams,
32}
33
34impl PublicKey {
35    /// Default minimum size of the modulus `n` in bits.
36    pub const MIN_SIZE: usize = 1024;
37
38    /// Default maximum size of the modulus `n` in bits.
39    pub const MAX_SIZE: usize = 8192;
40
41    /// Minimum value of the public exponent `e`.
42    pub const MIN_PUB_EXPONENT: u64 = 2;
43
44    /// Maximum value of the public exponent `e`.
45    ///
46    /// Very large public exponents are a potential denial-of-service vector (a.k.a. "RSADoS")
47    /// because they increase the amount of work required for e.g. signature verification. See:
48    ///
49    /// <https://www.imperialviolet.org/2012/03/17/rsados.html>
50    ///
51    /// The particular constant below has been chosen to align with *ring* where this value was
52    /// selected based on the history of this particular issue, API compatibility concerns, and
53    /// benchmark-driven evaluation. See RustCrypto/RSA#155.
54    ///
55    /// If for some reason you have a legitimate reason to use keys with public exponents larger
56    /// than this value, use the special APIs:
57    ///
58    /// - [`PublicKey::new_unchecked`]
59    /// - [`PrivateKey::from_components_with_large_exponent`]
60    pub const MAX_PUB_EXPONENT: u64 = (1 << 33) - 1;
61
62    /// Encrypt the given message.
63    #[allow(clippy::missing_errors_doc, reason = "TODO")]
64    pub fn encrypt<R: TryCryptoRng + ?Sized, P: PaddingScheme>(
65        &self,
66        rng: &mut R,
67        padding: P,
68        msg: &[u8],
69    ) -> Result<Vec<u8>> {
70        padding.encrypt(rng, self, msg)
71    }
72
73    /// Verify a signed message.
74    ///
75    /// `hashed` must be the result of hashing the input using the hashing function
76    /// passed in through `hash`.
77    ///
78    /// If the message is valid `Ok(())` is returned, otherwise an `Err` indicating failure.
79    #[allow(clippy::missing_errors_doc, reason = "TODO")]
80    pub fn verify<S: SignatureScheme>(&self, scheme: S, hashed: &[u8], sig: &[u8]) -> Result<()> {
81        scheme.verify(self, hashed, sig)
82    }
83
84    /// Create a new public key from its components.
85    ///
86    /// Accepts modulus sizes from [`Self::MIN_SIZE`] to [`Self::MAX_SIZE`], inclusive.
87    /// Use [`Self::new_with_size_limits`] to explicitly allow other sizes.
88    #[allow(clippy::missing_errors_doc, reason = "TODO")]
89    pub fn new(n: BoxedUint, e: BoxedUint) -> Result<Self> {
90        Self::new_with_size_limits(n, e, Self::MIN_SIZE..=Self::MAX_SIZE)
91    }
92
93    /// Create a new public key with explicit, inclusive modulus size limits in bits.
94    ///
95    /// All other public-key checks still apply. Allowing a smaller minimum can admit insecure
96    /// keys and is intended for testing or compatibility with legacy systems.
97    ///
98    /// For encoded keys outside the default limits, decode the components with the `pkcs1`
99    /// crate and pass them to this constructor explicitly.
100    ///
101    /// # Errors
102    /// Returns [`Error::InvalidArguments`] for an empty range, [`Error::ModulusTooSmall`] or
103    /// [`Error::ModulusTooLarge`] for a modulus outside the range, or an error if the modulus
104    /// or public exponent is invalid.
105    pub fn new_with_size_limits(
106        n: BoxedUint,
107        e: BoxedUint,
108        size_range_bits: RangeInclusive<usize>,
109    ) -> Result<Self> {
110        if size_range_bits.is_empty() {
111            return Err(Error::InvalidArguments);
112        }
113
114        if (n.bit_width_vartime() as usize) < *size_range_bits.start() {
115            return Err(Error::ModulusTooSmall);
116        }
117
118        check_public_with_max_size(&n, &e, Some(*size_range_bits.end()))?;
119
120        let n_odd = Odd::new(n.clone())
121            .into_option()
122            .ok_or(Error::InvalidModulus)?;
123        let n_params = BoxedMontyParams::new(n_odd);
124        let n = NonZero::new(n).expect("checked above");
125
126        Ok(Self { n, e, n_params })
127    }
128
129    /// Create a new public key with the default minimum modulus size and a custom maximum.
130    #[deprecated(since = "0.10.0", note = "please use `new_with_size_limits` instead")]
131    #[allow(clippy::missing_errors_doc, reason = "TODO")]
132    pub fn new_with_max_size(n: BoxedUint, e: BoxedUint, max_size: usize) -> Result<Self> {
133        Self::new_with_size_limits(n, e, Self::MIN_SIZE..=max_size)
134    }
135
136    /// Create a new public key, bypassing checks around the modulus and public
137    /// exponent size.
138    ///
139    /// This method is not recommended, and only intended for unusual use cases.
140    /// Most applications should use [`PublicKey::new`] or
141    /// [`PublicKey::new_with_size_limits`] instead.
142    #[must_use]
143    pub fn new_unchecked(n: BoxedUint, e: BoxedUint) -> Self {
144        let n_odd = Odd::new(n.clone()).expect("n must be odd");
145        let n_params = BoxedMontyParams::new(n_odd);
146        let n = NonZero::new(n).expect("odd numbers are non zero");
147
148        Self { n, e, n_params }
149    }
150}
151
152impl Eq for PublicKey {}
153impl PartialEq for PublicKey {
154    #[inline]
155    fn eq(&self, other: &PublicKey) -> bool {
156        self.n == other.n && self.e == other.e
157    }
158}
159
160impl From<PrivateKey> for PublicKey {
161    fn from(private_key: PrivateKey) -> Self {
162        (&private_key).into()
163    }
164}
165
166impl From<&PrivateKey> for PublicKey {
167    fn from(private_key: &PrivateKey) -> Self {
168        let n = PublicKeyParts::n(private_key);
169        let e = PublicKeyParts::e(private_key);
170        let n_params = PublicKeyParts::n_params(private_key);
171        PublicKey {
172            n: n.clone(),
173            e: e.clone(),
174            n_params: n_params.clone(),
175        }
176    }
177}
178
179impl Hash for PublicKey {
180    fn hash<H: Hasher>(&self, state: &mut H) {
181        // Domain separator for RSA private keys
182        state.write(b"PublicKey");
183        // TODO(tarcieri): to match the `PartialEq` impl we should strip leading zeros
184        Hash::hash(&self.n.as_limbs(), state);
185        Hash::hash(&self.e.as_limbs(), state);
186    }
187}
188
189impl PublicKeyParts for PublicKey {
190    fn n(&self) -> &NonZero<BoxedUint> {
191        &self.n
192    }
193
194    fn e(&self) -> &BoxedUint {
195        &self.e
196    }
197
198    fn n_params(&self) -> &BoxedMontyParams {
199        &self.n_params
200    }
201}
202
203#[cfg(feature = "serde")]
204impl Serialize for PublicKey {
205    fn serialize<S>(&self, serializer: S) -> core::prelude::v1::Result<S::Ok, S::Error>
206    where
207        S: serde::Serializer,
208    {
209        let der = self.to_public_key_der().map_err(ser::Error::custom)?;
210        serdect::slice::serialize_hex_lower_or_bin(&der, serializer)
211    }
212}
213
214#[cfg(feature = "serde")]
215impl<'de> Deserialize<'de> for PublicKey {
216    fn deserialize<D>(deserializer: D) -> core::prelude::v1::Result<Self, D::Error>
217    where
218        D: serde::Deserializer<'de>,
219    {
220        let der_bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
221        Self::from_public_key_der(&der_bytes).map_err(de::Error::custom)
222    }
223}
224
225/// Check that the public key is well formed and has an exponent within acceptable bounds.
226#[inline]
227pub(crate) fn check_public(public_key: &impl PublicKeyParts) -> Result<()> {
228    check_public_with_max_size(public_key.n(), public_key.e(), None)
229}
230
231/// Check that the public key is well formed and has an exponent within acceptable bounds.
232#[inline]
233fn check_public_with_max_size(n: &BoxedUint, e: &BoxedUint, max_size: Option<usize>) -> Result<()> {
234    if let Some(max_size) = max_size {
235        if n.bit_width_vartime() as usize > max_size {
236            return Err(Error::ModulusTooLarge);
237        }
238    }
239
240    check_public_skip_exponent_size(n, e)?;
241
242    if e < &BoxedUint::from(PublicKey::MIN_PUB_EXPONENT) {
243        return Err(Error::PublicExponentTooSmall);
244    }
245
246    if e > &BoxedUint::from(PublicKey::MAX_PUB_EXPONENT) {
247        return Err(Error::PublicExponentTooLarge);
248    }
249
250    Ok(())
251}
252
253/// Check that the public key is well formed, skipping exponent size bounds checks.
254///
255/// This is used internally by both public validation functions and hazmat APIs.
256#[inline]
257pub(crate) fn check_public_skip_exponent_size(n: &BoxedUint, e: &BoxedUint) -> Result<()> {
258    if e >= n || n.is_even().into() || n.is_zero().into() {
259        return Err(Error::InvalidModulus);
260    }
261
262    if e.is_even().into() {
263        return Err(Error::InvalidExponent);
264    }
265
266    // Skip exponent size bounds checks
267    Ok(())
268}