1use crate::{Error, Result};
4use der::{asn1::UIntRef, Decode, DecodeValue, Encode, Header, Reader, Sequence};
5
6#[cfg(feature = "alloc")]
7use der::Document;
8
9#[cfg(feature = "pem")]
10use der::pem::PemLabel;
11
12#[derive(Copy, Clone, Debug, Eq, PartialEq)]
25pub struct RsaPublicKey<'a> {
26 pub modulus: UIntRef<'a>,
28
29 pub public_exponent: UIntRef<'a>,
31}
32
33impl<'a> DecodeValue<'a> for RsaPublicKey<'a> {
34 fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
35 reader.read_nested(header.length, |reader| {
36 Ok(Self {
37 modulus: reader.decode()?,
38 public_exponent: reader.decode()?,
39 })
40 })
41 }
42}
43
44impl<'a> Sequence<'a> for RsaPublicKey<'a> {
45 fn fields<F, T>(&self, f: F) -> der::Result<T>
46 where
47 F: FnOnce(&[&dyn Encode]) -> der::Result<T>,
48 {
49 f(&[&self.modulus, &self.public_exponent])
50 }
51}
52
53impl<'a> TryFrom<&'a [u8]> for RsaPublicKey<'a> {
54 type Error = Error;
55
56 fn try_from(bytes: &'a [u8]) -> Result<Self> {
57 Ok(Self::from_der(bytes)?)
58 }
59}
60
61#[cfg(feature = "alloc")]
62#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
63impl TryFrom<RsaPublicKey<'_>> for Document {
64 type Error = Error;
65
66 fn try_from(spki: RsaPublicKey<'_>) -> Result<Document> {
67 Self::try_from(&spki)
68 }
69}
70
71#[cfg(feature = "alloc")]
72#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
73impl TryFrom<&RsaPublicKey<'_>> for Document {
74 type Error = Error;
75
76 fn try_from(spki: &RsaPublicKey<'_>) -> Result<Document> {
77 Ok(Self::encode_msg(spki)?)
78 }
79}
80
81#[cfg(feature = "pem")]
82#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
83impl PemLabel for RsaPublicKey<'_> {
84 const PEM_LABEL: &'static str = "RSA PUBLIC KEY";
85}