1use super::signature::{RsaEncoding, RsaPadding};
6use super::{encoding, RsaParameters};
7#[cfg(feature = "fips")]
8use crate::aws_lc::RSA;
9use crate::aws_lc::{
10 EVP_PKEY_CTX_set_rsa_keygen_bits, EVP_PKEY_assign_RSA, EVP_PKEY_new, RSA_new, RSA_set0_key,
11 RSA_size, EVP_PKEY, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
12};
13#[cfg(feature = "ring-io")]
14use crate::aws_lc::{RSA_get0_e, RSA_get0_n};
15use crate::encoding::{AsDer, Pkcs8V1Der, PublicKeyX509Der};
16use crate::error::{KeyRejected, Unspecified};
17#[cfg(feature = "ring-io")]
18use crate::io;
19#[cfg(feature = "ring-io")]
20use crate::ptr::ConstPointer;
21use crate::ptr::{DetachableLcPtr, LcPtr};
22use crate::rsa::PublicEncryptingKey;
23use crate::sealed::Sealed;
24use crate::{hex, rand};
25#[cfg(feature = "fips")]
26use aws_lc::RSA_check_fips;
27use core::fmt::{self, Debug, Formatter};
28use core::ptr::null_mut;
29
30use std::os::raw::c_int;
33
34use crate::pkcs8::Version;
35use crate::rsa::encoding::{rfc5280, rfc8017};
36use crate::rsa::signature::configure_rsa_pkcs1_pss_padding;
37#[cfg(feature = "ring-io")]
38use untrusted::Input;
39use zeroize::Zeroize;
40
41#[allow(clippy::module_name_repetitions)]
43#[non_exhaustive]
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum KeySize {
46 Rsa2048,
48
49 Rsa3072,
51
52 Rsa4096,
54
55 Rsa8192,
57}
58
59#[allow(clippy::len_without_is_empty)]
60impl KeySize {
61 #[inline]
63 #[must_use]
64 pub fn len(self) -> usize {
65 match self {
66 Self::Rsa2048 => 256,
67 Self::Rsa3072 => 384,
68 Self::Rsa4096 => 512,
69 Self::Rsa8192 => 1024,
70 }
71 }
72
73 #[inline]
75 pub(super) fn bits(self) -> i32 {
76 match self {
77 Self::Rsa2048 => 2048,
78 Self::Rsa3072 => 3072,
79 Self::Rsa4096 => 4096,
80 Self::Rsa8192 => 8192,
81 }
82 }
83}
84
85#[allow(clippy::module_name_repetitions)]
87pub struct KeyPair {
88 pub(super) evp_pkey: LcPtr<EVP_PKEY>,
95 pub(super) serialized_public_key: PublicKey,
96}
97
98impl Sealed for KeyPair {}
99unsafe impl Send for KeyPair {}
100unsafe impl Sync for KeyPair {}
101
102impl KeyPair {
103 fn new(evp_pkey: LcPtr<EVP_PKEY>) -> Result<Self, KeyRejected> {
104 KeyPair::validate_private_key(&evp_pkey)?;
105 let serialized_public_key = PublicKey::new(&evp_pkey)?;
106 Ok(KeyPair {
107 evp_pkey,
108 serialized_public_key,
109 })
110 }
111
112 pub fn generate(size: KeySize) -> Result<Self, Unspecified> {
123 let private_key = generate_rsa_key(size.bits())?;
124 Ok(Self::new(private_key)?)
125 }
126
127 #[cfg(feature = "fips")]
135 #[deprecated]
136 pub fn generate_fips(size: KeySize) -> Result<Self, Unspecified> {
137 Self::generate(size)
138 }
139
140 pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
156 let key = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(pkcs8, EVP_PKEY_RSA)?;
157 Self::new(key)
158 }
159
160 pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
165 let key = encoding::rfc8017::decode_private_key_der(input)?;
166 Self::new(key)
167 }
168
169 #[cfg(feature = "fips")]
171 #[must_use]
172 pub fn is_valid_fips_key(&self) -> bool {
173 is_valid_fips_key(&self.evp_pkey)
174 }
175
176 fn validate_private_key(key: &LcPtr<EVP_PKEY>) -> Result<(), KeyRejected> {
177 if !is_rsa_key(key) {
178 return Err(KeyRejected::unspecified());
179 }
180 match key.key_size_bits() {
181 2048..=8192 => Ok(()),
182 _ => Err(KeyRejected::unspecified()),
183 }
184 }
185
186 pub fn sign(
208 &self,
209 padding_alg: &'static dyn RsaEncoding,
210 _rng: &dyn rand::SecureRandom,
211 msg: &[u8],
212 signature: &mut [u8],
213 ) -> Result<(), Unspecified> {
214 let encoding = padding_alg.encoding();
215 let padding_fn = if let RsaPadding::RSA_PKCS1_PSS_PADDING = encoding.padding() {
216 Some(configure_rsa_pkcs1_pss_padding)
217 } else {
218 None
219 };
220
221 let sig_bytes = self
222 .evp_pkey
223 .sign(msg, Some(encoding.digest_algorithm()), padding_fn)?;
224
225 signature.copy_from_slice(&sig_bytes);
226 Ok(())
227 }
228
229 #[must_use]
233 pub fn public_modulus_len(&self) -> usize {
234 match self.evp_pkey.get_rsa() {
236 Ok(rsa) => {
237 unsafe { RSA_size(*rsa) as usize }
239 }
240 Err(_) => unreachable!(),
241 }
242 }
243}
244
245impl Debug for KeyPair {
246 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
247 f.write_str(&format!(
248 "RsaKeyPair {{ public_key: {:?} }}",
249 self.serialized_public_key
250 ))
251 }
252}
253
254impl crate::signature::KeyPair for KeyPair {
255 type PublicKey = PublicKey;
256
257 fn public_key(&self) -> &Self::PublicKey {
258 &self.serialized_public_key
259 }
260}
261
262impl AsDer<Pkcs8V1Der<'static>> for KeyPair {
263 fn as_der(&self) -> Result<Pkcs8V1Der<'static>, Unspecified> {
264 Ok(Pkcs8V1Der::new(
265 self.evp_pkey.marshal_rfc5208_private_key(Version::V1)?,
266 ))
267 }
268}
269
270#[derive(Clone)]
272#[allow(clippy::module_name_repetitions)]
273pub struct PublicKey {
274 key: Box<[u8]>,
275 #[cfg(feature = "ring-io")]
276 modulus: Box<[u8]>,
277 #[cfg(feature = "ring-io")]
278 exponent: Box<[u8]>,
279}
280
281impl Drop for PublicKey {
282 fn drop(&mut self) {
283 self.key.zeroize();
284 #[cfg(feature = "ring-io")]
285 self.modulus.zeroize();
286 #[cfg(feature = "ring-io")]
287 self.exponent.zeroize();
288 }
289}
290
291impl PublicKey {
292 pub(super) fn new(evp_pkey: &LcPtr<EVP_PKEY>) -> Result<Self, KeyRejected> {
293 let key = encoding::rfc8017::encode_public_key_der(evp_pkey)?;
294 #[cfg(feature = "ring-io")]
295 {
296 let pubkey = evp_pkey.get_rsa()?;
297 let modulus = ConstPointer::new(unsafe { RSA_get0_n(*pubkey) })?;
298 let modulus = modulus.to_be_bytes().into_boxed_slice();
299 let exponent = ConstPointer::new(unsafe { RSA_get0_e(*pubkey) })?;
300 let exponent = exponent.to_be_bytes().into_boxed_slice();
301 Ok(PublicKey {
302 key,
303 modulus,
304 exponent,
305 })
306 }
307
308 #[cfg(not(feature = "ring-io"))]
309 Ok(PublicKey { key })
310 }
311
312 pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
316 PublicKey::new(
319 &rfc8017::decode_public_key_der(input).or(rfc5280::decode_public_key_der(input))?,
320 )
321 }
322}
323
324impl Debug for PublicKey {
325 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
326 f.write_str(&format!(
327 "RsaPublicKey(\"{}\")",
328 hex::encode(self.key.as_ref())
329 ))
330 }
331}
332
333impl AsRef<[u8]> for PublicKey {
334 fn as_ref(&self) -> &[u8] {
336 self.key.as_ref()
337 }
338}
339
340impl AsDer<PublicKeyX509Der<'static>> for PublicKey {
341 fn as_der(&self) -> Result<PublicKeyX509Der<'static>, Unspecified> {
342 let evp_pkey = rfc8017::decode_public_key_der(self.as_ref())?;
344 rfc5280::encode_public_key_der(&evp_pkey)
345 }
346}
347
348#[cfg(feature = "ring-io")]
349impl PublicKey {
350 #[must_use]
352 pub fn modulus(&self) -> io::Positive<'_> {
353 io::Positive::new_non_empty_without_leading_zeros(Input::from(self.modulus.as_ref()))
354 }
355
356 #[must_use]
358 pub fn exponent(&self) -> io::Positive<'_> {
359 io::Positive::new_non_empty_without_leading_zeros(Input::from(self.exponent.as_ref()))
360 }
361
362 #[must_use]
364 pub fn modulus_len(&self) -> usize {
365 self.modulus.len()
366 }
367}
368
369#[allow(clippy::module_name_repetitions)]
378#[derive(Clone)]
379pub struct PublicKeyComponents<B>
380where
381 B: AsRef<[u8]> + Debug,
382{
383 pub n: B,
385 pub e: B,
387}
388
389impl<B: AsRef<[u8]> + Debug> Debug for PublicKeyComponents<B> {
390 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
391 f.debug_struct("RsaPublicKeyComponents")
392 .field("n", &self.n)
393 .field("e", &self.e)
394 .finish()
395 }
396}
397
398impl<B: Copy + AsRef<[u8]> + Debug> Copy for PublicKeyComponents<B> {}
399
400impl<B> PublicKeyComponents<B>
401where
402 B: AsRef<[u8]> + Debug,
403{
404 #[inline]
405 fn build_rsa(&self) -> Result<LcPtr<EVP_PKEY>, ()> {
406 let n_bytes = self.n.as_ref();
407 if n_bytes.is_empty() || n_bytes[0] == 0u8 {
408 return Err(());
409 }
410 let n_bn = DetachableLcPtr::try_from(n_bytes)?;
411
412 let e_bytes = self.e.as_ref();
413 if e_bytes.is_empty() || e_bytes[0] == 0u8 {
414 return Err(());
415 }
416 let e_bn = DetachableLcPtr::try_from(e_bytes)?;
417
418 let rsa = DetachableLcPtr::new(unsafe { RSA_new() })?;
419 if 1 != unsafe { RSA_set0_key(*rsa, *n_bn, *e_bn, null_mut()) } {
420 return Err(());
421 }
422 n_bn.detach();
423 e_bn.detach();
424
425 let mut pkey = LcPtr::new(unsafe { EVP_PKEY_new() })?;
426 if 1 != unsafe { EVP_PKEY_assign_RSA(*pkey.as_mut(), *rsa) } {
427 return Err(());
428 }
429 rsa.detach();
430
431 Ok(pkey)
432 }
433
434 pub fn verify(
442 &self,
443 params: &RsaParameters,
444 message: &[u8],
445 signature: &[u8],
446 ) -> Result<(), Unspecified> {
447 let rsa = self.build_rsa()?;
448 super::signature::verify_rsa_signature(
449 params.digest_algorithm(),
450 params.padding(),
451 &rsa,
452 message,
453 signature,
454 params.bit_size_range(),
455 )
456 }
457}
458
459#[cfg(feature = "ring-io")]
460impl From<&PublicKey> for PublicKeyComponents<Vec<u8>> {
461 fn from(public_key: &PublicKey) -> Self {
462 PublicKeyComponents {
463 n: public_key.modulus.to_vec(),
464 e: public_key.exponent.to_vec(),
465 }
466 }
467}
468
469impl<B> TryInto<PublicEncryptingKey> for PublicKeyComponents<B>
470where
471 B: AsRef<[u8]> + Debug,
472{
473 type Error = Unspecified;
474
475 fn try_into(self) -> Result<PublicEncryptingKey, Self::Error> {
480 let rsa = self.build_rsa()?;
481 PublicEncryptingKey::new(rsa)
482 }
483}
484
485pub(super) fn generate_rsa_key(size: c_int) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
486 let params_fn = |ctx| {
487 if 1 == unsafe { EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, size) } {
488 Ok(())
489 } else {
490 Err(())
491 }
492 };
493
494 LcPtr::<EVP_PKEY>::generate(EVP_PKEY_RSA, Some(params_fn))
495}
496
497#[cfg(feature = "fips")]
498#[must_use]
499pub(super) fn is_valid_fips_key(key: &LcPtr<EVP_PKEY>) -> bool {
500 let rsa_key = key.get_rsa().expect("RSA EVP_PKEY");
502
503 1 == unsafe { RSA_check_fips(*rsa_key as *mut RSA) }
504}
505
506pub(super) fn is_rsa_key(key: &LcPtr<EVP_PKEY>) -> bool {
507 let id = key.id();
508 id == EVP_PKEY_RSA || id == EVP_PKEY_RSA_PSS
509}