Skip to main content

pkcs1/
public_key.rs

1//! PKCS#1 RSA Public Keys.
2
3use crate::{Error, Result};
4use der::{
5    Decode, DecodeValue, Encode, EncodeValue, Header, Length, Reader, Sequence, Writer,
6    asn1::UintRef,
7};
8
9#[cfg(feature = "alloc")]
10use der::Document;
11
12#[cfg(feature = "pem")]
13use der::pem::PemLabel;
14
15/// PKCS#1 RSA Public Keys as defined in [RFC 8017 Appendix 1.1].
16///
17/// ASN.1 structure containing a serialized RSA public key:
18///
19/// ```text
20/// RSAPublicKey ::= SEQUENCE {
21///     modulus           INTEGER,  -- n
22///     publicExponent    INTEGER   -- e
23/// }
24/// ```
25///
26/// [RFC 8017 Appendix 1.1]: https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.1.1
27#[derive(Copy, Clone, Debug, Eq, PartialEq)]
28pub struct RsaPublicKey<'a> {
29    /// `n`: RSA modulus
30    pub modulus: UintRef<'a>,
31
32    /// `e`: RSA public exponent
33    pub public_exponent: UintRef<'a>,
34}
35
36impl<'a> DecodeValue<'a> for RsaPublicKey<'a> {
37    type Error = der::Error;
38    fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
39        Ok(Self {
40            modulus: reader.decode()?,
41            public_exponent: reader.decode()?,
42        })
43    }
44}
45
46impl EncodeValue for RsaPublicKey<'_> {
47    fn value_len(&self) -> der::Result<Length> {
48        self.modulus.encoded_len()? + self.public_exponent.encoded_len()?
49    }
50
51    fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
52        self.modulus.encode(writer)?;
53        self.public_exponent.encode(writer)?;
54        Ok(())
55    }
56}
57
58impl<'a> Sequence<'a> for RsaPublicKey<'a> {}
59
60impl<'a> TryFrom<&'a [u8]> for RsaPublicKey<'a> {
61    type Error = Error;
62
63    fn try_from(bytes: &'a [u8]) -> Result<Self> {
64        Ok(Self::from_der(bytes)?)
65    }
66}
67
68#[cfg(feature = "alloc")]
69impl TryFrom<RsaPublicKey<'_>> for Document {
70    type Error = Error;
71
72    fn try_from(spki: RsaPublicKey<'_>) -> Result<Document> {
73        Self::try_from(&spki)
74    }
75}
76
77#[cfg(feature = "alloc")]
78impl TryFrom<&RsaPublicKey<'_>> for Document {
79    type Error = Error;
80
81    fn try_from(spki: &RsaPublicKey<'_>) -> Result<Document> {
82        Ok(Self::encode_msg(spki)?)
83    }
84}
85
86#[cfg(feature = "pem")]
87impl PemLabel for RsaPublicKey<'_> {
88    const PEM_LABEL: &'static str = "RSA PUBLIC KEY";
89}