1use crate::{Error, Result};
4use der::{
5 Decode, DecodeValue, Encode, EncodeValue, FixedTag, Header, Length, Reader, Sequence, Writer,
6 asn1::UintRef,
7};
8
9#[cfg(feature = "alloc")]
10use {
11 crate::{DecodeRsaPublicKey, EncodeRsaPublicKey},
12 der::{Document, asn1::Uint},
13};
14
15#[cfg(feature = "pem")]
16use der::pem::PemLabel;
17
18pub type RsaPublicKeyRef<'a> = RsaPublicKey<UintRef<'a>>;
23
24#[cfg(feature = "alloc")]
29pub type RsaPublicKeyOwned = RsaPublicKey<Uint>;
30
31#[derive(Copy, Clone, Debug, Eq, PartialEq)]
44pub struct RsaPublicKey<U> {
45 pub modulus: U,
47
48 pub public_exponent: U,
50}
51
52impl<'a, U> DecodeValue<'a> for RsaPublicKey<U>
53where
54 U: DecodeValue<'a, Error = der::Error> + FixedTag + 'a,
55{
56 type Error = der::Error;
57 fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
58 Ok(Self {
59 modulus: reader.decode()?,
60 public_exponent: reader.decode()?,
61 })
62 }
63}
64
65impl<U> EncodeValue for RsaPublicKey<U>
66where
67 U: EncodeValue + FixedTag,
68{
69 fn value_len(&self) -> der::Result<Length> {
70 self.modulus.encoded_len()? + self.public_exponent.encoded_len()?
71 }
72
73 fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
74 self.modulus.encode(writer)?;
75 self.public_exponent.encode(writer)?;
76 Ok(())
77 }
78}
79
80impl<'a, U> Sequence<'a> for RsaPublicKey<U> {}
81
82#[cfg(feature = "alloc")]
83impl DecodeRsaPublicKey for RsaPublicKeyOwned {
84 fn from_pkcs1_der(bytes: &[u8]) -> Result<Self> {
85 Ok(Self::from_der(bytes)?)
86 }
87}
88
89#[cfg(feature = "alloc")]
90impl<U> EncodeRsaPublicKey for RsaPublicKey<U>
91where
92 U: EncodeValue + FixedTag,
93{
94 fn to_pkcs1_der(&self) -> Result<Document> {
95 self.try_into()
96 }
97}
98
99impl<'a, U> TryFrom<&'a [u8]> for RsaPublicKey<U>
100where
101 RsaPublicKey<U>: Decode<'a>,
102 Error: From<<RsaPublicKey<U> as Decode<'a>>::Error>,
103{
104 type Error = Error;
105
106 fn try_from(bytes: &'a [u8]) -> Result<Self> {
108 Ok(Self::from_der(bytes)?)
109 }
110}
111
112#[cfg(feature = "alloc")]
113impl<U> TryFrom<RsaPublicKey<U>> for Document
114where
115 RsaPublicKey<U>: EncodeValue,
116{
117 type Error = Error;
118
119 fn try_from(spki: RsaPublicKey<U>) -> Result<Document> {
120 Self::try_from(&spki)
121 }
122}
123
124#[cfg(feature = "alloc")]
125impl<U> TryFrom<&RsaPublicKey<U>> for Document
126where
127 RsaPublicKey<U>: EncodeValue,
128{
129 type Error = Error;
130
131 fn try_from(spki: &RsaPublicKey<U>) -> Result<Document> {
132 Ok(Self::encode_msg(spki)?)
133 }
134}
135
136#[cfg(feature = "pem")]
137impl<U> PemLabel for RsaPublicKey<U> {
138 const PEM_LABEL: &'static str = "RSA PUBLIC KEY";
139}