Skip to main content

pkcs1/
traits.rs

1//! Traits for parsing objects from PKCS#1 encoded documents
2
3use crate::Result;
4
5#[cfg(feature = "alloc")]
6use der::{Document, SecretDocument};
7
8#[cfg(feature = "pem")]
9use {
10    crate::LineEnding,
11    alloc::string::String,
12    der::{pem::PemLabel, zeroize::Zeroizing},
13};
14
15#[cfg(feature = "std")]
16use std::path::Path;
17
18#[cfg(all(feature = "alloc", feature = "pem"))]
19use crate::{RsaPrivateKeyRef, RsaPublicKeyRef};
20
21#[cfg(doc)]
22use crate::{RsaPrivateKey, RsaPublicKey};
23
24/// Decode an owned type from a PKCS#1-encoded [`RsaPrivateKey`].
25///
26/// Implemented for `RsaPrivateKeyOwned` with the `alloc` feature enabled, and
27/// usable by RSA implementations for their own key types. For borrowed decoding
28/// into [`crate::RsaPrivateKeyRef`], use [`der::Decode`] instead.
29pub trait DecodeRsaPrivateKey: Sized {
30    /// Deserialize PKCS#1 private key from ASN.1 DER-encoded data
31    /// (binary format).
32    fn from_pkcs1_der(bytes: &[u8]) -> Result<Self>;
33
34    /// Deserialize PKCS#1-encoded private key from PEM.
35    ///
36    /// Keys in this format begin with the following:
37    ///
38    /// ```text
39    /// -----BEGIN RSA PRIVATE KEY-----
40    /// ```
41    #[cfg(feature = "pem")]
42    fn from_pkcs1_pem(s: &str) -> Result<Self> {
43        let (label, doc) = SecretDocument::from_pem(s)?;
44        RsaPrivateKeyRef::validate_pem_label(label)?;
45        Self::from_pkcs1_der(doc.as_bytes())
46    }
47
48    /// Load PKCS#1 private key from an ASN.1 DER-encoded file on the local
49    /// filesystem (binary format).
50    #[cfg(feature = "std")]
51    fn read_pkcs1_der_file(path: impl AsRef<Path>) -> Result<Self> {
52        Self::from_pkcs1_der(SecretDocument::read_der_file(path)?.as_bytes())
53    }
54
55    /// Load PKCS#1 private key from a PEM-encoded file on the local filesystem.
56    #[cfg(all(feature = "pem", feature = "std"))]
57    fn read_pkcs1_pem_file(path: impl AsRef<Path>) -> Result<Self> {
58        let (label, doc) = SecretDocument::read_pem_file(path)?;
59        RsaPrivateKeyRef::validate_pem_label(&label)?;
60        Self::from_pkcs1_der(doc.as_bytes())
61    }
62}
63
64/// Decode an owned type from a PKCS#1-encoded [`RsaPublicKey`].
65///
66/// Implemented for `RsaPublicKeyOwned` with the `alloc` feature enabled, and
67/// usable by RSA implementations for their own key types. For borrowed decoding
68/// into [`crate::RsaPublicKeyRef`], use [`der::Decode`] instead.
69pub trait DecodeRsaPublicKey: Sized {
70    /// Deserialize object from ASN.1 DER-encoded [`RsaPublicKey`]
71    /// (binary format).
72    fn from_pkcs1_der(bytes: &[u8]) -> Result<Self>;
73
74    /// Deserialize PEM-encoded [`RsaPublicKey`].
75    ///
76    /// Keys in this format begin with the following:
77    ///
78    /// ```text
79    /// -----BEGIN RSA PUBLIC KEY-----
80    /// ```
81    #[cfg(feature = "pem")]
82    fn from_pkcs1_pem(s: &str) -> Result<Self> {
83        let (label, doc) = Document::from_pem(s)?;
84        RsaPublicKeyRef::validate_pem_label(label)?;
85        Self::from_pkcs1_der(doc.as_bytes())
86    }
87
88    /// Load [`RsaPublicKey`] from an ASN.1 DER-encoded file on the local
89    /// filesystem (binary format).
90    #[cfg(feature = "std")]
91    fn read_pkcs1_der_file(path: impl AsRef<Path>) -> Result<Self> {
92        let doc = Document::read_der_file(path)?;
93        Self::from_pkcs1_der(doc.as_bytes())
94    }
95
96    /// Load [`RsaPublicKey`] from a PEM-encoded file on the local filesystem.
97    #[cfg(all(feature = "pem", feature = "std"))]
98    fn read_pkcs1_pem_file(path: impl AsRef<Path>) -> Result<Self> {
99        let (label, doc) = Document::read_pem_file(path)?;
100        RsaPublicKeyRef::validate_pem_label(&label)?;
101        Self::from_pkcs1_der(doc.as_bytes())
102    }
103}
104
105/// Serialize a [`RsaPrivateKey`] to a PKCS#1 encoded document.
106#[cfg(feature = "alloc")]
107pub trait EncodeRsaPrivateKey {
108    /// Serialize a [`SecretDocument`] containing a PKCS#1-encoded private key.
109    fn to_pkcs1_der(&self) -> Result<SecretDocument>;
110
111    /// Serialize this private key as PEM-encoded PKCS#1 with the given [`LineEnding`].
112    #[cfg(feature = "pem")]
113    fn to_pkcs1_pem(&self, line_ending: LineEnding) -> Result<Zeroizing<String>> {
114        let doc = self.to_pkcs1_der()?;
115        Ok(doc.to_pem(RsaPrivateKeyRef::PEM_LABEL, line_ending)?)
116    }
117
118    /// Write ASN.1 DER-encoded PKCS#1 private key to the given path.
119    #[cfg(feature = "std")]
120    fn write_pkcs1_der_file(&self, path: impl AsRef<Path>) -> Result<()> {
121        Ok(self.to_pkcs1_der()?.write_der_file(path)?)
122    }
123
124    /// Write ASN.1 PEM-encoded PKCS#1 private key to the given path.
125    #[cfg(all(feature = "pem", feature = "std"))]
126    fn write_pkcs1_pem_file(&self, path: impl AsRef<Path>, line_ending: LineEnding) -> Result<()> {
127        let doc = self.to_pkcs1_der()?;
128        Ok(doc.write_pem_file(path, RsaPrivateKeyRef::PEM_LABEL, line_ending)?)
129    }
130}
131
132/// Serialize a [`RsaPublicKey`] to a PKCS#1-encoded document.
133#[cfg(feature = "alloc")]
134pub trait EncodeRsaPublicKey {
135    /// Serialize a [`Document`] containing a PKCS#1-encoded public key.
136    fn to_pkcs1_der(&self) -> Result<Document>;
137
138    /// Serialize this public key as PEM-encoded PKCS#1 with the given line ending.
139    #[cfg(feature = "pem")]
140    fn to_pkcs1_pem(&self, line_ending: LineEnding) -> Result<String> {
141        let doc = self.to_pkcs1_der()?;
142        Ok(doc.to_pem(RsaPublicKeyRef::PEM_LABEL, line_ending)?)
143    }
144
145    /// Write ASN.1 DER-encoded public key to the given path.
146    #[cfg(feature = "std")]
147    fn write_pkcs1_der_file(&self, path: impl AsRef<Path>) -> Result<()> {
148        Ok(self.to_pkcs1_der()?.write_der_file(path)?)
149    }
150
151    /// Write ASN.1 PEM-encoded public key to the given path.
152    #[cfg(all(feature = "pem", feature = "std"))]
153    fn write_pkcs1_pem_file(&self, path: impl AsRef<Path>, line_ending: LineEnding) -> Result<()> {
154        let doc = self.to_pkcs1_der()?;
155        Ok(doc.write_pem_file(path, RsaPublicKeyRef::PEM_LABEL, line_ending)?)
156    }
157}