1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#![deny(missing_docs)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc, clippy::must_use_candidate)]

//! `rsa_export` allows you to export your RSA key, generated via the [rsa crate](https://crates.io/crates/rsa), with PKCS#1 or PKCS#8 encoding  
//!
//! **Note**: Multi-prime keys are not supported
//!
//! The keys can also be exported into the PEM format by enabling the feature `pem`
//!
//! Example:  
//!
//! ```rust
//! use rsa::RSAPrivateKey;
//! use rand::rngs::OsRng;
//!
//! let mut rng = OsRng;
//! let key = RSAPrivateKey::new(&mut rng, 2048).unwrap();
//! let private_key = rsa_export::RsaKey::new(key);
//! let public_key = private_key.public_key();
//!
//! let pkcs1_encoded_private = private_key.as_pkcs1().unwrap();
//! let pkcs1_encoded_public = public_key.as_pkcs1().unwrap();
//!
//! let pkcs8_encoded_private = private_key.as_pkcs8().unwrap();
//! let pkcs8_encoded_public = public_key.as_pkcs8().unwrap();
//! ```
//!
//! Encode PKCS#1 or PKCS#8 encoded keys into the PEM format
//!
//! ```rust
//! use rsa::RSAPrivateKey;
//! use rand::rngs::OsRng;
//!
//! let mut rng = OsRng;
//! let key = RSAPrivateKey::new(&mut rng, 2048).unwrap();
//! let private_key = rsa_export::RsaKey::new(key);
//! let public_key = private_key.public_key();
//!
//! let pkcs1_encoded_private_pem = private_key.as_pkcs1_pem().unwrap();
//! let pkcs1_encoded_public_pem = public_key.as_pkcs1_pem().unwrap();
//!
//! let pkcs8_encoded_private_pem = private_key.as_pkcs8_pem().unwrap();
//! let pkcs8_encoded_public_pem = public_key.as_pkcs8_pem().unwrap();
//! ```
//!
//! Encode PKCS#1 or PKCS#8 encoded keys into the PEM format with a custom line ending
//!
//! ```rust
//! use rsa::RSAPrivateKey;
//! use rsa_export::LineEnding;
//! use rand::rngs::OsRng;
//!
//! let mut rng = OsRng;
//! let key = RSAPrivateKey::new(&mut rng, 2048).unwrap();
//! let mut private_key = rsa_export::RsaKey::new(key);
//!
//! private_key.set_line_ending(LineEnding::CRLF);
//!
//! let public_key = private_key.public_key();
//!
//! let pkcs1_encoded_private_pem = private_key.as_pkcs1_pem().unwrap();
//! let pkcs1_encoded_public_pem = public_key.as_pkcs1_pem().unwrap();
//!
//! let pkcs8_encoded_private_pem = private_key.as_pkcs8_pem().unwrap();
//! let pkcs8_encoded_public_pem = public_key.as_pkcs8_pem().unwrap();
//! ```
//!

#[cfg(feature = "pem")]
extern crate pem as pem_crate;

use {
    crate::error::Error,
    num_bigint_dig::ToBigInt,
    rsa::{RSAPrivateKey, RSAPublicKey},
};

fn rsa_oid() -> simple_asn1::OID {
    use simple_asn1::{BigUint, OID};

    simple_asn1::oid!(1, 2, 840, 113_549, 1, 1, 1)
}

fn to_bigint(biguint: &rsa::BigUint) -> simple_asn1::BigInt {
    simple_asn1::BigInt::from_signed_bytes_le(
        biguint.to_bigint().unwrap().to_signed_bytes_le().as_slice(),
    )
}

/// Wrapper struct for the RSA key
pub struct RsaKey<T: Encode> {
    key: T,

    #[cfg(feature = "pem")]
    line_ending: LineEnding,
}

impl<T: Encode> RsaKey<T> {
    /// Create a new wrapper, wrapping around the given key
    pub fn new(key: T) -> Self {
        Self {
            key,

            #[cfg(feature = "pem")]
            line_ending: LineEnding::LF,
        }
    }

    /// Get the key which the wrapper is wrapping around
    pub fn into_inner(self) -> T {
        self.key
    }

    /// Encode the key in the PKCS#1 format
    pub fn as_pkcs1(&self) -> Result<Vec<u8>, Error> {
        self.key.encode_pkcs1()
    }

    /// Encode the key in the PKCS#8 format
    pub fn as_pkcs8(&self) -> Result<Vec<u8>, Error> {
        self.key.encode_pkcs8()
    }
}

#[cfg(feature = "pem")]
impl<T: Encode> RsaKey<T> {
    /// Set the line ending for the PEM keys (default: unix-style)
    pub fn set_line_ending(&mut self, line_ending: LineEnding) {
        self.line_ending = line_ending;
    }

    /// Encode the key in the PKCS#1 format inside a PEM block (unix-style line ending)
    pub fn as_pkcs1_pem(&self) -> Result<String, Error> {
        let pkcs1_key = self.as_pkcs1()?;

        Ok(pem::encode(
            pem::EncodingScheme::PKCS1,
            self.key.key_type(),
            self.line_ending,
            pkcs1_key,
        ))
    }

    /// Encode the key in the PKCS#8 format inside a PEM block (unix-style line ending)
    pub fn as_pkcs8_pem(&self) -> Result<String, Error> {
        let pkcs8_key = self.as_pkcs8()?;

        Ok(pem::encode(
            pem::EncodingScheme::PKCS8,
            self.key.key_type(),
            self.line_ending,
            pkcs8_key,
        ))
    }
}

impl RsaKey<RSAPrivateKey> {
    /// Convenience function to create the public key version
    pub fn public_key(&self) -> RsaKey<RSAPublicKey> {
        RsaKey {
            key: self.key.to_public_key(),

            #[cfg(feature = "pem")]
            line_ending: self.line_ending,
        }
    }
}

/// Trait to reduce copy-pasted code for the PKCS#1 and PKCS#8 encoding  
pub trait Encode: sealed::Sealed {
    #[cfg(feature = "pem")]
    /// Get the key type
    fn key_type(&self) -> pem::KeyType;

    /// Encode in the PKCS#1 format
    fn encode_pkcs1(&self) -> Result<Vec<u8>, Error>;
    /// Encode in the PKCS#8 format
    fn encode_pkcs8(&self) -> Result<Vec<u8>, Error>;
}

impl Encode for RSAPrivateKey {
    #[cfg(feature = "pem")]
    fn key_type(&self) -> pem::KeyType {
        pem::KeyType::Private
    }

    fn encode_pkcs1(&self) -> Result<Vec<u8>, Error> {
        pkcs1::private_key(self)
    }

    fn encode_pkcs8(&self) -> Result<Vec<u8>, Error> {
        pkcs8::private_key(self)
    }
}

impl Encode for RSAPublicKey {
    #[cfg(feature = "pem")]
    fn key_type(&self) -> pem::KeyType {
        pem::KeyType::Public
    }

    fn encode_pkcs1(&self) -> Result<Vec<u8>, Error> {
        pkcs1::public_key(self)
    }

    fn encode_pkcs8(&self) -> Result<Vec<u8>, Error> {
        pkcs8::public_key(self)
    }
}

#[cfg(feature = "pem")]
pub use pem_crate::LineEnding;

mod sealed {
    pub trait Sealed {}

    impl Sealed for rsa::RSAPrivateKey {}
    impl Sealed for rsa::RSAPublicKey {}
}

/// Error type
pub mod error;

/// Encode a public/private key with PKCS#1
mod pkcs1;
/// Encode a public/private key with PKCS#8
mod pkcs8;

#[cfg(feature = "pem")]
/// Encode a public/private key encoded with PKCS#1 or PKCS#8 into the PEM format
mod pem;

#[cfg(test)]
mod test;