Skip to main content

ssh_key/public/
rsa.rs

1//! Rivest–Shamir–Adleman (RSA) public keys.
2
3use crate::{Error, Mpint, Result};
4use core::hash::{Hash, Hasher};
5use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
6
7#[cfg(feature = "rsa")]
8use {
9    encoding::Uint,
10    rsa::{pkcs1v15, traits::PublicKeyParts},
11    sha2::{Digest, digest::const_oid::AssociatedOid},
12};
13
14/// RSA public key.
15///
16/// Described in [RFC4253 § 6.6](https://datatracker.ietf.org/doc/html/rfc4253#section-6.6).
17#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
18pub struct RsaPublicKey {
19    /// RSA public exponent.
20    e: Mpint,
21
22    /// RSA modulus.
23    n: Mpint,
24
25    /// Length of this key in bits.
26    bits: u32,
27}
28
29impl RsaPublicKey {
30    /// Create a new [`RsaPublicKey`] with the given components:
31    ///
32    /// - `e`: RSA public exponent.
33    /// - `n`: RSA modulus.
34    ///
35    /// # Errors
36    /// Returns [`Error::FormatEncoding`] if either component is zero.
37    pub fn new(e: Mpint, n: Mpint) -> Result<Self> {
38        if e.is_zero() || n.is_zero() {
39            return Err(Error::FormatEncoding);
40        }
41
42        let bits = u32::try_from(n.as_bytes().len() * 8).map_err(|_| Error::FormatEncoding)?;
43
44        Ok(Self { e, n, bits })
45    }
46
47    /// Get the RSA public exponent.
48    #[must_use]
49    pub fn e(&self) -> &Mpint {
50        &self.e
51    }
52
53    /// Get the RSA modulus.
54    #[must_use]
55    pub fn n(&self) -> &Mpint {
56        &self.n
57    }
58
59    /// Get the size of the RSA modulus in bits.
60    #[must_use]
61    pub fn key_size(&self) -> u32 {
62        self.bits
63    }
64}
65
66impl Decode for RsaPublicKey {
67    type Error = Error;
68
69    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
70        let e = Mpint::decode(reader)?;
71        let n = Mpint::decode(reader)?;
72        Self::new(e, n)
73    }
74}
75
76impl Encode for RsaPublicKey {
77    fn encoded_len(&self) -> encoding::Result<usize> {
78        [self.e.encoded_len()?, self.n.encoded_len()?].checked_sum()
79    }
80
81    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
82        self.e.encode(writer)?;
83        self.n.encode(writer)
84    }
85}
86
87impl Hash for RsaPublicKey {
88    #[inline]
89    fn hash<H: Hasher>(&self, state: &mut H) {
90        self.e.as_bytes().hash(state);
91        self.n.as_bytes().hash(state);
92    }
93}
94
95#[cfg(feature = "rsa")]
96impl TryFrom<RsaPublicKey> for rsa::PublicKey {
97    type Error = Error;
98
99    fn try_from(key: RsaPublicKey) -> Result<rsa::PublicKey> {
100        rsa::PublicKey::try_from(&key)
101    }
102}
103
104#[cfg(feature = "rsa")]
105impl TryFrom<&RsaPublicKey> for rsa::PublicKey {
106    type Error = Error;
107
108    fn try_from(key: &RsaPublicKey) -> Result<rsa::PublicKey> {
109        let n = Uint::from(&key.n);
110        let e = Uint::from(&key.e);
111        let ret = rsa::PublicKey::new(n, e).map_err(|_| Error::Crypto)?;
112
113        Ok(ret)
114    }
115}
116
117#[cfg(feature = "rsa")]
118impl TryFrom<rsa::PublicKey> for RsaPublicKey {
119    type Error = Error;
120
121    fn try_from(key: rsa::PublicKey) -> Result<RsaPublicKey> {
122        RsaPublicKey::try_from(&key)
123    }
124}
125
126#[cfg(feature = "rsa")]
127impl TryFrom<&rsa::PublicKey> for RsaPublicKey {
128    type Error = Error;
129
130    fn try_from(key: &rsa::PublicKey) -> Result<RsaPublicKey> {
131        RsaPublicKey::new(key.e().try_into()?, key.n().as_ref().try_into()?)
132    }
133}
134
135#[cfg(feature = "rsa")]
136impl<D> TryFrom<&RsaPublicKey> for pkcs1v15::VerifyingKey<D>
137where
138    D: Digest + AssociatedOid,
139{
140    type Error = Error;
141
142    fn try_from(key: &RsaPublicKey) -> Result<pkcs1v15::VerifyingKey<D>> {
143        Ok(pkcs1v15::VerifyingKey::new(key.try_into()?))
144    }
145}