Skip to main content

pkcs1/
private_key.rs

1//! PKCS#1 RSA Private Keys.
2
3#[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
25/// PKCS#1 RSA Private Keys as defined in [RFC 8017 Appendix 1.2].
26///
27/// Borrows its integer data from the input. Decode DER using [`der::Decode::from_der`]
28/// or [`TryFrom<&[u8]>`].
29pub type RsaPrivateKeyRef<'a> = RsaPrivateKey<UintRef<'a>>;
30
31/// PKCS#1 RSA Private Keys as defined in [RFC 8017 Appendix 1.2].
32///
33/// Owns its integer data. Use [`DecodeRsaPrivateKey`] and [`EncodeRsaPrivateKey`]
34/// for DER decoding and encoding, or PEM when the `pem` feature is enabled.
35#[cfg(feature = "alloc")]
36pub type RsaPrivateKeyOwned = RsaPrivateKey<Uint>;
37
38/// PKCS#1 RSA Private Keys as defined in [RFC 8017 Appendix 1.2].
39///
40/// ASN.1 structure containing a serialized RSA private key:
41///
42/// ```text
43/// RSAPrivateKey ::= SEQUENCE {
44///     version           Version,
45///     modulus           INTEGER,  -- n
46///     publicExponent    INTEGER,  -- e
47///     privateExponent   INTEGER,  -- d
48///     prime1            INTEGER,  -- p
49///     prime2            INTEGER,  -- q
50///     exponent1         INTEGER,  -- d mod (p-1)
51///     exponent2         INTEGER,  -- d mod (q-1)
52///     coefficient       INTEGER,  -- (inverse of q) mod p
53///     otherPrimeInfos   OtherPrimeInfos OPTIONAL
54/// }
55///
56/// OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
57/// ```
58///
59/// Note: the `version` field is selected automatically based on the absence or
60/// presence of the `other_prime_infos` field.
61///
62/// [RFC 8017 Appendix 1.2]: https://www.rfc-editor.org/info/rfc8017#appendix-A.1.2
63#[derive(Clone)]
64pub struct RsaPrivateKey<U> {
65    /// `n`: RSA modulus.
66    pub modulus: U,
67
68    /// `e`: RSA public exponent.
69    pub public_exponent: U,
70
71    /// `d`: RSA private exponent.
72    pub private_exponent: U,
73
74    /// `p`: first prime factor of `n`.
75    pub prime1: U,
76
77    /// `q`: Second prime factor of `n`.
78    pub prime2: U,
79
80    /// First exponent: `d mod (p-1)`.
81    pub exponent1: U,
82
83    /// Second exponent: `d mod (q-1)`.
84    pub exponent2: U,
85
86    /// CRT coefficient: `(inverse of q) mod p`.
87    pub coefficient: U,
88
89    /// Additional primes `r_3`, ..., `r_u`, in order, if this is a multi-prime
90    /// RSA key (i.e. `version` is `multi`).
91    pub other_prime_infos: Option<OtherPrimeInfos<U>>,
92}
93
94impl<U> RsaPrivateKey<U>
95where
96    U: AsUintRef,
97{
98    /// Get the public key that corresponds to this [`RsaPrivateKey`].
99    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    /// Get the [`Version`] for this key.
109    ///
110    /// Determined by the presence or absence of the
111    /// [`RsaPrivateKey::other_prime_infos`] field.
112    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        // Ensure version is set correctly for two-prime vs multi-prime key.
143        if version.is_multi() != result.other_prime_infos.is_some() {
144            return Err(reader.error(der::ErrorKind::Value { tag: Tag::Integer }));
145        }
146
147        // `OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo`
148        // (without `alloc`, `OtherPrimeInfos` never decodes, so there is nothing to check)
149        #[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    /// Decode a PKCS#1 RSA private key from ASN.1 DER-encoded bytes.
229    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/// Placeholder struct for `OtherPrimeInfos` in the no-`alloc` case.
288///
289/// This type is unconstructable by design, but supports the same traits.
290#[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        // Placeholder decoder that always returns an error.
303        // Uses `Tag::Integer` to signal an unsupported version.
304        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        // Placeholder decoder that always returns an error.
312        // Uses `Tag::Integer` to signal an unsupported version.
313        Err(der::ErrorKind::Value { tag: Tag::Integer }.into())
314    }
315
316    fn encode_value(&self, _writer: &mut impl Writer) -> der::Result<()> {
317        // Placeholder decoder that always returns an error.
318        // Uses `Tag::Integer` to signal an unsupported version.
319        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/// Additional RSA prime info in a multi-prime RSA key.
329#[cfg(feature = "alloc")]
330pub type OtherPrimeInfos<U> = Vec<OtherPrimeInfo<U>>;