1use crate::{Error, Mpint, Result, public::RsaPublicKey};
4use core::fmt::{self, Debug};
5use ctutils::{Choice, CtEq};
6use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
7use zeroize::Zeroize;
8
9#[cfg(feature = "rsa")]
10use {
11 encoding::Uint,
12 rand_core::CryptoRng,
13 rsa::{pkcs1v15, traits::PrivateKeyParts},
14 sha2::{Digest, digest::const_oid::AssociatedOid},
15};
16
17#[derive(Clone)]
19pub struct RsaPrivateKey {
20 d: Mpint,
22
23 iqmp: Mpint,
25
26 p: Mpint,
28
29 q: Mpint,
31}
32
33impl RsaPrivateKey {
34 pub fn new(d: Mpint, iqmp: Mpint, p: Mpint, q: Mpint) -> Result<Self> {
44 if d.is_zero() || iqmp.is_zero() || p.is_zero() || q.is_zero() {
45 return Err(Error::FormatEncoding);
46 }
47 Ok(Self { d, iqmp, p, q })
48 }
49
50 #[must_use]
52 pub fn d(&self) -> &Mpint {
53 &self.d
54 }
55
56 #[must_use]
58 pub fn iqmp(&self) -> &Mpint {
59 &self.iqmp
60 }
61
62 #[must_use]
64 pub fn p(&self) -> &Mpint {
65 &self.p
66 }
67
68 #[must_use]
70 pub fn q(&self) -> &Mpint {
71 &self.q
72 }
73}
74
75impl CtEq for RsaPrivateKey {
76 fn ct_eq(&self, other: &Self) -> Choice {
77 self.d.ct_eq(&other.d)
78 & self.iqmp.ct_eq(&other.iqmp)
79 & self.p.ct_eq(&other.p)
80 & self.q.ct_eq(&other.q)
81 }
82}
83
84impl Debug for RsaPrivateKey {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 f.debug_struct("RsaPrivateKey").finish_non_exhaustive()
87 }
88}
89
90impl Drop for RsaPrivateKey {
91 fn drop(&mut self) {
92 self.d.zeroize();
93 self.iqmp.zeroize();
94 self.p.zeroize();
95 self.q.zeroize();
96 }
97}
98
99impl Decode for RsaPrivateKey {
100 type Error = Error;
101
102 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
103 let d = Mpint::decode(reader)?;
104 let iqmp = Mpint::decode(reader)?;
105 let p = Mpint::decode(reader)?;
106 let q = Mpint::decode(reader)?;
107 Self::new(d, iqmp, p, q)
108 }
109}
110
111impl Encode for RsaPrivateKey {
112 fn encoded_len(&self) -> encoding::Result<usize> {
113 [
114 self.d.encoded_len()?,
115 self.iqmp.encoded_len()?,
116 self.p.encoded_len()?,
117 self.q.encoded_len()?,
118 ]
119 .checked_sum()
120 }
121
122 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
123 self.d.encode(writer)?;
124 self.iqmp.encode(writer)?;
125 self.p.encode(writer)?;
126 self.q.encode(writer)?;
127 Ok(())
128 }
129}
130
131impl Eq for RsaPrivateKey {}
132impl PartialEq for RsaPrivateKey {
133 fn eq(&self, other: &Self) -> bool {
134 self.ct_eq(other).into()
135 }
136}
137
138#[derive(Clone)]
140pub struct RsaKeypair {
141 public: RsaPublicKey,
143
144 private: RsaPrivateKey,
146}
147
148impl RsaKeypair {
149 #[cfg(feature = "rsa")]
151 #[expect(clippy::missing_errors_doc, reason = "TODO")]
152 pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
153 rsa::PrivateKey::new(rng, bit_size)?.try_into()
154 }
155
156 pub fn new(public: RsaPublicKey, private: RsaPrivateKey) -> Result<Self> {
161 Ok(Self { public, private })
163 }
164
165 #[must_use]
167 pub fn key_size(&self) -> u32 {
168 self.public.key_size()
169 }
170
171 #[must_use]
173 pub fn public(&self) -> &RsaPublicKey {
174 &self.public
175 }
176
177 #[must_use]
179 pub fn private(&self) -> &RsaPrivateKey {
180 &self.private
181 }
182}
183
184impl CtEq for RsaKeypair {
185 fn ct_eq(&self, other: &Self) -> Choice {
186 Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
187 }
188}
189
190impl Debug for RsaKeypair {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.debug_struct("RsaKeypair")
193 .field("public", &self.public)
194 .finish_non_exhaustive()
195 }
196}
197
198impl Decode for RsaKeypair {
199 type Error = Error;
200
201 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
202 let n = Mpint::decode(reader)?;
203 let e = Mpint::decode(reader)?;
204 let public = RsaPublicKey::new(e, n)?;
205 let private = RsaPrivateKey::decode(reader)?;
206 Self::new(public, private)
207 }
208}
209
210impl Encode for RsaKeypair {
211 fn encoded_len(&self) -> encoding::Result<usize> {
212 [
213 self.public.n().encoded_len()?,
214 self.public.e().encoded_len()?,
215 self.private.encoded_len()?,
216 ]
217 .checked_sum()
218 }
219
220 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
221 self.public.n().encode(writer)?;
222 self.public.e().encode(writer)?;
223 self.private.encode(writer)
224 }
225}
226
227impl Eq for RsaKeypair {}
228impl PartialEq for RsaKeypair {
229 fn eq(&self, other: &Self) -> bool {
230 self.ct_eq(other).into()
231 }
232}
233
234impl From<RsaKeypair> for RsaPublicKey {
235 fn from(keypair: RsaKeypair) -> RsaPublicKey {
236 keypair.public
237 }
238}
239
240impl From<&RsaKeypair> for RsaPublicKey {
241 fn from(keypair: &RsaKeypair) -> RsaPublicKey {
242 keypair.public.clone()
243 }
244}
245
246#[cfg(feature = "rsa")]
247impl TryFrom<RsaKeypair> for rsa::PrivateKey {
248 type Error = Error;
249
250 fn try_from(key: RsaKeypair) -> Result<rsa::PrivateKey> {
251 rsa::PrivateKey::try_from(&key)
252 }
253}
254
255#[cfg(feature = "rsa")]
256impl TryFrom<&RsaKeypair> for rsa::PrivateKey {
257 type Error = Error;
258
259 fn try_from(key: &RsaKeypair) -> Result<rsa::PrivateKey> {
260 let ret = rsa::PrivateKey::from_components(
261 Uint::from(key.public.n()),
262 Uint::from(key.public.e()),
263 Uint::from(&key.private.d),
264 vec![Uint::from(&key.private.p), Uint::from(&key.private.q)],
265 )?;
266
267 Ok(ret)
268 }
269}
270
271#[cfg(feature = "rsa")]
272impl TryFrom<rsa::PrivateKey> for RsaKeypair {
273 type Error = Error;
274
275 fn try_from(key: rsa::PrivateKey) -> Result<RsaKeypair> {
276 RsaKeypair::try_from(&key)
277 }
278}
279
280#[cfg(feature = "rsa")]
281impl TryFrom<&rsa::PrivateKey> for RsaKeypair {
282 type Error = Error;
283
284 fn try_from(key: &rsa::PrivateKey) -> Result<RsaKeypair> {
285 if key.primes().len() > 2 {
287 return Err(Error::Crypto);
288 }
289
290 let public = RsaPublicKey::try_from(key.to_public_key())?;
291
292 let p = &key.primes()[0];
293 let q = &key.primes()[1];
294 let iqmp = key.crt_coefficient().ok_or(Error::Crypto)?;
295
296 let private = RsaPrivateKey {
297 d: key.d().try_into()?,
298 iqmp: iqmp.try_into()?,
299 p: p.as_ref().try_into()?,
300 q: q.as_ref().try_into()?,
301 };
302
303 Ok(RsaKeypair { public, private })
304 }
305}
306
307#[cfg(feature = "rsa")]
308impl<D> TryFrom<&RsaKeypair> for pkcs1v15::SigningKey<D>
309where
310 D: Digest + AssociatedOid,
311{
312 type Error = Error;
313
314 fn try_from(keypair: &RsaKeypair) -> Result<pkcs1v15::SigningKey<D>> {
315 Ok(pkcs1v15::SigningKey::new(keypair.try_into()?))
316 }
317}