use crate::{Error, MPInt, Result};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
#[cfg(feature = "rsa")]
use {
crate::private::RsaKeypair,
rsa::{pkcs1v15, PublicKeyParts},
sha2::{digest::const_oid::AssociatedOid, Digest},
};
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct RsaPublicKey {
pub e: MPInt,
pub n: MPInt,
}
impl RsaPublicKey {
#[cfg(feature = "rsa")]
pub(crate) const MIN_KEY_SIZE: usize = RsaKeypair::MIN_KEY_SIZE;
}
impl Decode for RsaPublicKey {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let e = MPInt::decode(reader)?;
let n = MPInt::decode(reader)?;
Ok(Self { e, n })
}
}
impl Encode for RsaPublicKey {
type Error = Error;
fn encoded_len(&self) -> Result<usize> {
Ok([self.e.encoded_len()?, self.n.encoded_len()?].checked_sum()?)
}
fn encode(&self, writer: &mut impl Writer) -> Result<()> {
self.e.encode(writer)?;
self.n.encode(writer)
}
}
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
impl TryFrom<RsaPublicKey> for rsa::RsaPublicKey {
type Error = Error;
fn try_from(key: RsaPublicKey) -> Result<rsa::RsaPublicKey> {
rsa::RsaPublicKey::try_from(&key)
}
}
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
impl TryFrom<&RsaPublicKey> for rsa::RsaPublicKey {
type Error = Error;
fn try_from(key: &RsaPublicKey) -> Result<rsa::RsaPublicKey> {
let ret = rsa::RsaPublicKey::new(
rsa::BigUint::try_from(&key.n)?,
rsa::BigUint::try_from(&key.e)?,
)
.map_err(|_| Error::Crypto)?;
if ret.size().saturating_mul(8) >= RsaPublicKey::MIN_KEY_SIZE {
Ok(ret)
} else {
Err(Error::Crypto)
}
}
}
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
impl TryFrom<rsa::RsaPublicKey> for RsaPublicKey {
type Error = Error;
fn try_from(key: rsa::RsaPublicKey) -> Result<RsaPublicKey> {
RsaPublicKey::try_from(&key)
}
}
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
impl TryFrom<&rsa::RsaPublicKey> for RsaPublicKey {
type Error = Error;
fn try_from(key: &rsa::RsaPublicKey) -> Result<RsaPublicKey> {
Ok(RsaPublicKey {
e: key.e().try_into()?,
n: key.n().try_into()?,
})
}
}
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
impl<D> TryFrom<&RsaPublicKey> for pkcs1v15::VerifyingKey<D>
where
D: Digest + AssociatedOid,
{
type Error = Error;
fn try_from(key: &RsaPublicKey) -> Result<pkcs1v15::VerifyingKey<D>> {
Ok(pkcs1v15::VerifyingKey::new_with_prefix(key.try_into()?))
}
}