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, Encode)]
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 Eq for RsaPrivateKey {}
112impl PartialEq for RsaPrivateKey {
113 fn eq(&self, other: &Self) -> bool {
114 self.ct_eq(other).into()
115 }
116}
117
118#[derive(Clone)]
120pub struct RsaKeypair {
121 public: RsaPublicKey,
123
124 private: RsaPrivateKey,
126}
127
128impl RsaKeypair {
129 #[cfg(feature = "rsa")]
131 #[expect(clippy::missing_errors_doc, reason = "TODO")]
132 pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
133 rsa::PrivateKey::new(rng, bit_size)?.try_into()
134 }
135
136 pub fn new(public: RsaPublicKey, private: RsaPrivateKey) -> Result<Self> {
141 Ok(Self { public, private })
143 }
144
145 #[must_use]
147 pub fn key_size(&self) -> u32 {
148 self.public.key_size()
149 }
150
151 #[must_use]
153 pub fn public(&self) -> &RsaPublicKey {
154 &self.public
155 }
156
157 #[must_use]
159 pub fn private(&self) -> &RsaPrivateKey {
160 &self.private
161 }
162}
163
164impl CtEq for RsaKeypair {
165 fn ct_eq(&self, other: &Self) -> Choice {
166 Choice::from(u8::from(self.public == other.public)) & self.private.ct_eq(&other.private)
167 }
168}
169
170impl Debug for RsaKeypair {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.debug_struct("RsaKeypair")
173 .field("public", &self.public)
174 .finish_non_exhaustive()
175 }
176}
177
178impl Decode for RsaKeypair {
179 type Error = Error;
180
181 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
182 let n = Mpint::decode(reader)?;
183 let e = Mpint::decode(reader)?;
184 let public = RsaPublicKey::new(e, n)?;
185 let private = RsaPrivateKey::decode(reader)?;
186 Self::new(public, private)
187 }
188}
189
190impl Encode for RsaKeypair {
191 fn encoded_len(&self) -> encoding::Result<usize> {
192 [
193 self.public.n().encoded_len()?,
194 self.public.e().encoded_len()?,
195 self.private.encoded_len()?,
196 ]
197 .checked_sum()
198 }
199
200 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
201 self.public.n().encode(writer)?;
202 self.public.e().encode(writer)?;
203 self.private.encode(writer)
204 }
205}
206
207impl Eq for RsaKeypair {}
208impl PartialEq for RsaKeypair {
209 fn eq(&self, other: &Self) -> bool {
210 self.ct_eq(other).into()
211 }
212}
213
214impl From<RsaKeypair> for RsaPublicKey {
215 fn from(keypair: RsaKeypair) -> RsaPublicKey {
216 keypair.public
217 }
218}
219
220impl From<&RsaKeypair> for RsaPublicKey {
221 fn from(keypair: &RsaKeypair) -> RsaPublicKey {
222 keypair.public.clone()
223 }
224}
225
226#[cfg(feature = "rsa")]
227impl TryFrom<RsaKeypair> for rsa::PrivateKey {
228 type Error = Error;
229
230 fn try_from(key: RsaKeypair) -> Result<rsa::PrivateKey> {
231 rsa::PrivateKey::try_from(&key)
232 }
233}
234
235#[cfg(feature = "rsa")]
236impl TryFrom<&RsaKeypair> for rsa::PrivateKey {
237 type Error = Error;
238
239 fn try_from(key: &RsaKeypair) -> Result<rsa::PrivateKey> {
240 let ret = rsa::PrivateKey::from_components(
241 Uint::from(key.public.n()),
242 Uint::from(key.public.e()),
243 Uint::from(&key.private.d),
244 vec![Uint::from(&key.private.p), Uint::from(&key.private.q)],
245 )?;
246
247 Ok(ret)
248 }
249}
250
251#[cfg(feature = "rsa")]
252impl TryFrom<rsa::PrivateKey> for RsaKeypair {
253 type Error = Error;
254
255 fn try_from(key: rsa::PrivateKey) -> Result<RsaKeypair> {
256 RsaKeypair::try_from(&key)
257 }
258}
259
260#[cfg(feature = "rsa")]
261impl TryFrom<&rsa::PrivateKey> for RsaKeypair {
262 type Error = Error;
263
264 fn try_from(key: &rsa::PrivateKey) -> Result<RsaKeypair> {
265 if key.primes().len() > 2 {
267 return Err(Error::Crypto);
268 }
269
270 let public = RsaPublicKey::try_from(key.to_public_key())?;
271
272 let p = &key.primes()[0];
273 let q = &key.primes()[1];
274 let iqmp = key.crt_coefficient().ok_or(Error::Crypto)?;
275
276 let private = RsaPrivateKey {
277 d: key.d().try_into()?,
278 iqmp: iqmp.try_into()?,
279 p: p.as_ref().try_into()?,
280 q: q.as_ref().try_into()?,
281 };
282
283 Ok(RsaKeypair { public, private })
284 }
285}
286
287#[cfg(feature = "rsa")]
288impl<D> TryFrom<&RsaKeypair> for pkcs1v15::SigningKey<D>
289where
290 D: Digest + AssociatedOid,
291{
292 type Error = Error;
293
294 fn try_from(keypair: &RsaKeypair) -> Result<pkcs1v15::SigningKey<D>> {
295 Ok(pkcs1v15::SigningKey::new(keypair.try_into()?))
296 }
297}