1#[cfg(feature = "alloc")]
4pub(crate) mod other_prime_info;
5
6use crate::{Error, Result, RsaPublicKeyRef, Version};
7use core::fmt;
8use der::{
9 Decode, DecodeValue, Encode, EncodeValue, Header, Length, Reader, Sequence, Tag, Writer,
10 asn1::{AsUintRef, OctetStringRef, UintRef},
11};
12
13#[cfg(feature = "alloc")]
14use {self::other_prime_info::OtherPrimeInfo, alloc::vec::Vec, der::SecretDocument};
15
16#[cfg(feature = "alloc")]
17use {
18 crate::{DecodeRsaPrivateKey, EncodeRsaPrivateKey},
19 der::asn1::Uint,
20};
21
22#[cfg(feature = "pem")]
23use der::pem::PemLabel;
24
25pub type RsaPrivateKeyRef<'a> = RsaPrivateKey<UintRef<'a>>;
30
31#[cfg(feature = "alloc")]
36pub type RsaPrivateKeyOwned = RsaPrivateKey<Uint>;
37
38#[derive(Clone)]
64pub struct RsaPrivateKey<U> {
65 pub modulus: U,
67
68 pub public_exponent: U,
70
71 pub private_exponent: U,
73
74 pub prime1: U,
76
77 pub prime2: U,
79
80 pub exponent1: U,
82
83 pub exponent2: U,
85
86 pub coefficient: U,
88
89 pub other_prime_infos: Option<OtherPrimeInfos<U>>,
92}
93
94impl<U> RsaPrivateKey<U>
95where
96 U: AsUintRef,
97{
98 pub fn public_key<'a>(&'a self) -> RsaPublicKeyRef<'a> {
100 RsaPublicKeyRef {
101 modulus: self.modulus.as_uint_ref(),
102 public_exponent: self.public_exponent.as_uint_ref(),
103 }
104 }
105}
106
107impl<U> RsaPrivateKey<U> {
108 pub fn version(&self) -> Version {
113 if self.other_prime_infos.is_some() {
114 Version::Multi
115 } else {
116 Version::TwoPrime
117 }
118 }
119}
120
121impl<'a, U> DecodeValue<'a> for RsaPrivateKey<U>
122where
123 U: Decode<'a, Error = der::Error>,
124{
125 type Error = der::Error;
126
127 fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
128 let version = Version::decode(reader)?;
129
130 let result = Self {
131 modulus: reader.decode()?,
132 public_exponent: reader.decode()?,
133 private_exponent: reader.decode()?,
134 prime1: reader.decode()?,
135 prime2: reader.decode()?,
136 exponent1: reader.decode()?,
137 exponent2: reader.decode()?,
138 coefficient: reader.decode()?,
139 other_prime_infos: reader.decode()?,
140 };
141
142 if version.is_multi() != result.other_prime_infos.is_some() {
144 return Err(reader.error(der::ErrorKind::Value { tag: Tag::Integer }));
145 }
146
147 #[cfg(feature = "alloc")]
150 if result
151 .other_prime_infos
152 .as_ref()
153 .is_some_and(|infos| infos.is_empty())
154 {
155 return Err(reader.error(der::ErrorKind::Value { tag: Tag::Sequence }));
156 }
157
158 Ok(result)
159 }
160}
161
162impl<U> EncodeValue for RsaPrivateKey<U>
163where
164 U: Encode,
165{
166 fn value_len(&self) -> der::Result<Length> {
167 self.version().encoded_len()?
168 + self.modulus.encoded_len()?
169 + self.public_exponent.encoded_len()?
170 + self.private_exponent.encoded_len()?
171 + self.prime1.encoded_len()?
172 + self.prime2.encoded_len()?
173 + self.exponent1.encoded_len()?
174 + self.exponent2.encoded_len()?
175 + self.coefficient.encoded_len()?
176 + self.other_prime_infos.encoded_len()?
177 }
178
179 fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
180 self.version().encode(writer)?;
181 self.modulus.encode(writer)?;
182 self.public_exponent.encode(writer)?;
183 self.private_exponent.encode(writer)?;
184 self.prime1.encode(writer)?;
185 self.prime2.encode(writer)?;
186 self.exponent1.encode(writer)?;
187 self.exponent2.encode(writer)?;
188 self.coefficient.encode(writer)?;
189 self.other_prime_infos.encode(writer)?;
190 Ok(())
191 }
192}
193
194impl<U> Sequence<'_> for RsaPrivateKey<U> {}
195
196#[cfg(feature = "alloc")]
197impl DecodeRsaPrivateKey for RsaPrivateKeyOwned {
198 fn from_pkcs1_der(bytes: &[u8]) -> Result<Self> {
199 Ok(Self::from_der(bytes)?)
200 }
201}
202
203#[cfg(feature = "alloc")]
204impl<U> EncodeRsaPrivateKey for RsaPrivateKey<U>
205where
206 U: Encode,
207{
208 fn to_pkcs1_der(&self) -> Result<SecretDocument> {
209 self.try_into()
210 }
211}
212
213impl<'a, U> From<&'a RsaPrivateKey<U>> for RsaPublicKeyRef<'a>
214where
215 U: AsUintRef,
216{
217 fn from(private_key: &'a RsaPrivateKey<U>) -> RsaPublicKeyRef<'a> {
218 private_key.public_key()
219 }
220}
221
222impl<'a, U> TryFrom<&'a [u8]> for RsaPrivateKey<U>
223where
224 U: Decode<'a, Error = der::Error>,
225{
226 type Error = Error;
227
228 fn try_from(bytes: &'a [u8]) -> Result<Self> {
230 Ok(Self::from_der(bytes)?)
231 }
232}
233
234impl<'a, U> TryFrom<&'a OctetStringRef> for RsaPrivateKey<U>
235where
236 U: Decode<'a, Error = der::Error>,
237{
238 type Error = Error;
239
240 fn try_from(bytes: &'a OctetStringRef) -> Result<Self> {
241 Ok(Self::from_der(bytes.as_bytes())?)
242 }
243}
244
245impl<U> fmt::Debug for RsaPrivateKey<U>
246where
247 U: fmt::Debug,
248{
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.debug_struct("RsaPrivateKey")
251 .field("version", &self.version())
252 .field("modulus", &self.modulus)
253 .field("public_exponent", &self.public_exponent)
254 .finish_non_exhaustive()
255 }
256}
257
258#[cfg(feature = "alloc")]
259impl<U> TryFrom<RsaPrivateKey<U>> for SecretDocument
260where
261 U: Encode,
262{
263 type Error = Error;
264
265 fn try_from(private_key: RsaPrivateKey<U>) -> Result<SecretDocument> {
266 SecretDocument::try_from(&private_key)
267 }
268}
269
270#[cfg(feature = "alloc")]
271impl<U> TryFrom<&RsaPrivateKey<U>> for SecretDocument
272where
273 U: Encode,
274{
275 type Error = Error;
276
277 fn try_from(private_key: &RsaPrivateKey<U>) -> Result<SecretDocument> {
278 Ok(Self::encode_msg(private_key)?)
279 }
280}
281
282#[cfg(feature = "pem")]
283impl<U> PemLabel for RsaPrivateKey<U> {
284 const PEM_LABEL: &'static str = "RSA PRIVATE KEY";
285}
286
287#[cfg(not(feature = "alloc"))]
291#[derive(Clone)]
292#[non_exhaustive]
293pub struct OtherPrimeInfos<U> {
294 _marker: core::marker::PhantomData<U>,
295}
296
297#[cfg(not(feature = "alloc"))]
298impl<'a, U> DecodeValue<'a> for OtherPrimeInfos<U> {
299 type Error = der::Error;
300
301 fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
302 Err(reader.error(der::ErrorKind::Value { tag: Tag::Integer }))
305 }
306}
307
308#[cfg(not(feature = "alloc"))]
309impl<U> EncodeValue for OtherPrimeInfos<U> {
310 fn value_len(&self) -> der::Result<Length> {
311 Err(der::ErrorKind::Value { tag: Tag::Integer }.into())
314 }
315
316 fn encode_value(&self, _writer: &mut impl Writer) -> der::Result<()> {
317 Err(der::ErrorKind::Value { tag: Tag::Integer }.into())
320 }
321}
322
323#[cfg(not(feature = "alloc"))]
324impl<U> der::FixedTag for OtherPrimeInfos<U> {
325 const TAG: Tag = Tag::Sequence;
326}
327
328#[cfg(feature = "alloc")]
330pub type OtherPrimeInfos<U> = Vec<OtherPrimeInfo<U>>;