1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use crate::{Error, Result};
use core::convert::TryFrom;
use der::{
asn1::{Any, UIntBytes},
Decodable, Encodable, Message,
};
#[cfg(feature = "alloc")]
use crate::RsaPublicKeyDocument;
#[cfg(feature = "pem")]
use {
crate::{pem, LineEnding},
alloc::string::String,
};
#[cfg(feature = "pem")]
pub(crate) const PEM_TYPE_LABEL: &str = "RSA PUBLIC KEY";
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct RsaPublicKey<'a> {
pub modulus: UIntBytes<'a>,
pub public_exponent: UIntBytes<'a>,
}
impl<'a> RsaPublicKey<'a> {
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_der(self) -> RsaPublicKeyDocument {
self.into()
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
pub fn to_pem(self) -> Result<String> {
self.to_pem_with_le(LineEnding::default())
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
pub fn to_pem_with_le(self, line_ending: LineEnding) -> Result<String> {
Ok(pem::encode_string(
PEM_TYPE_LABEL,
line_ending,
self.to_der().as_ref(),
)?)
}
}
impl<'a> TryFrom<&'a [u8]> for RsaPublicKey<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Ok(Self::from_der(bytes)?)
}
}
impl<'a> TryFrom<Any<'a>> for RsaPublicKey<'a> {
type Error = der::Error;
fn try_from(any: Any<'a>) -> der::Result<RsaPublicKey<'a>> {
any.sequence(|decoder| {
Ok(Self {
modulus: decoder.decode()?,
public_exponent: decoder.decode()?,
})
})
}
}
impl<'a> Message<'a> for RsaPublicKey<'a> {
fn fields<F, T>(&self, f: F) -> der::Result<T>
where
F: FnOnce(&[&dyn Encodable]) -> der::Result<T>,
{
f(&[&self.modulus, &self.public_exponent])
}
}