1use 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#[derive(Debug, Clone)]
20pub struct PublicKey {
21 pub(crate) n: NonZero<BoxedUint>,
23
24 pub(crate) e: BoxedUint,
29
30 pub(crate) n_params: BoxedMontyParams,
32}
33
34impl PublicKey {
35 pub const MIN_SIZE: usize = 1024;
37
38 pub const MAX_SIZE: usize = 8192;
40
41 pub const MIN_PUB_EXPONENT: u64 = 2;
43
44 pub const MAX_PUB_EXPONENT: u64 = (1 << 33) - 1;
61
62 #[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 #[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 #[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 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 #[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 #[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 state.write(b"PublicKey");
183 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#[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#[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#[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 Ok(())
268}