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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::{
    errors::{Error, Result},
    key::PublicKeyParts,
    parse::rsa_oid,
    PublicKey, RSAPrivateKey, RSAPublicKey,
};
use num_bigint::{BigUint, ModInverse, ToBigInt};
use num_traits::Zero;
#[cfg(feature = "pem")]
use pem::{EncodeConfig, LineEnding};
use simple_asn1::{to_der, ASN1Block, BigInt};
use std::prelude::v1::*;
use std::{format, vec};

const BYTE_BIT_SIZE: usize = 8;
#[cfg(feature = "pem")]
const DEFAULT_ENCODING_CONFIG: EncodeConfig = EncodeConfig {
    line_ending: LineEnding::LF,
};

#[cfg(feature = "pem")]
/// Trait for encoding the private key in the PEM format
///
/// Important: Encoding multi prime keys isn't supported. See [RustCrypto/RSA#66](https://github.com/RustCrypto/RSA/issues/66) for more info
pub trait PrivateKeyPemEncoding: PrivateKeyEncoding {
    const PKCS1_HEADER: &'static str;
    const PKCS8_HEADER: &'static str = "PRIVATE KEY";

    /// Converts a Private key into `PKCS1` encoded bytes in pem format.
    ///
    /// Encodes the key with the header:
    /// `-----BEGIN <name> PRIVATE KEY-----`
    ///
    /// # Example
    ///
    /// ```
    /// use rsa::{RSAPrivateKey, PrivateKeyPemEncoding};
    /// use rand::rngs::OsRng;
    ///
    /// let mut rng = OsRng;
    /// let bits = 2048;
    /// let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    ///
    /// let _ = private_key.to_pem_pkcs1();
    /// ```
    fn to_pem_pkcs1(&self) -> Result<String> {
        self.to_pem_pkcs1_with_config(DEFAULT_ENCODING_CONFIG)
    }

    /// Converts a Private key into `PKCS1` encoded bytes in pem format with encoding config.
    ///
    /// # Example
    /// ```
    /// # use rsa::{RSAPrivateKey, PrivateKeyPemEncoding};
    /// # use rand::rngs::OsRng;
    /// use pem::{EncodeConfig, LineEnding};
    /// # let mut rng = OsRng;
    /// # let bits = 2048;
    /// # let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    ///
    /// let _ = private_key.to_pem_pkcs1_with_config(EncodeConfig {
    ///     line_ending: LineEnding::CRLF,
    /// });
    /// ```
    fn to_pem_pkcs1_with_config(&self, config: EncodeConfig) -> Result<String> {
        let pem = pem::Pem {
            tag: String::from(Self::PKCS1_HEADER),
            contents: self.to_pkcs1()?,
        };
        Ok(pem::encode_config(&pem, config))
    }

    /// Converts a Private key into `PKCS8` encoded bytes in pem format.
    ///
    /// Encodes the key with the header:
    /// `-----BEGIN PRIVATE KEY-----`
    ///
    /// # Example
    ///
    /// ```
    /// use rsa::{RSAPrivateKey, PrivateKeyPemEncoding};
    /// use rand::rngs::OsRng;
    ///
    /// let mut rng = OsRng;
    /// let bits = 2048;
    /// let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    ///
    /// let _ = private_key.to_pem_pkcs8();
    /// ```
    fn to_pem_pkcs8(&self) -> Result<String> {
        self.to_pem_pkcs8_with_config(DEFAULT_ENCODING_CONFIG)
    }

    /// Converts a Private key into `PKCS8` encoded bytes in pem format with encoding config.
    ///
    /// # Example
    /// ```
    /// # use rsa::{RSAPrivateKey, PrivateKeyPemEncoding};
    /// # use rand::rngs::OsRng;
    /// use pem::{EncodeConfig, LineEnding};
    /// # let mut rng = OsRng;
    /// # let bits = 2048;
    /// # let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    ///
    /// let _ = private_key.to_pem_pkcs8_with_config(EncodeConfig {
    ///     line_ending: LineEnding::CRLF,
    /// });
    /// ```
    fn to_pem_pkcs8_with_config(&self, config: EncodeConfig) -> Result<String> {
        let pem = pem::Pem {
            tag: String::from(Self::PKCS8_HEADER),
            contents: self.to_pkcs8()?,
        };
        Ok(pem::encode_config(&pem, config))
    }
}

#[cfg(feature = "pem")]
impl PrivateKeyPemEncoding for RSAPrivateKey {
    const PKCS1_HEADER: &'static str = "RSA PRIVATE KEY";
}

#[cfg(feature = "pem")]
pub trait PublicKeyPemEncoding: PublicKeyEncoding {
    const PKCS1_HEADER: &'static str;
    const PKCS8_HEADER: &'static str = "PUBLIC KEY";

    /// Converts a Public key into `PKCS1` encoded bytes in pem format.
    ///
    /// Encodes the key with the header:
    /// `-----BEGIN <name> PUBLIC KEY-----`
    ///
    /// # Example
    ///
    /// ```
    /// use rsa::{RSAPrivateKey, RSAPublicKey, PublicKeyPemEncoding};
    /// use rand::rngs::OsRng;
    ///
    /// let mut rng = OsRng;
    /// let bits = 2048;
    /// let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    /// let public_key = RSAPublicKey::from(&private_key);
    ///
    /// let _ = public_key.to_pem_pkcs1();
    /// ```
    fn to_pem_pkcs1(&self) -> Result<String> {
        self.to_pem_pkcs1_with_config(DEFAULT_ENCODING_CONFIG)
    }

    /// Converts a Public key into `PKCS1` encoded bytes in pem format with encoding config.
    ///
    /// # Example
    /// ```
    /// use rsa::{RSAPrivateKey, RSAPublicKey, PublicKeyPemEncoding};
    /// # use rand::rngs::OsRng;
    /// use pem::{EncodeConfig, LineEnding};
    /// # let mut rng = OsRng;
    /// # let bits = 2048;
    /// # let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    /// # let public_key = RSAPublicKey::from(&private_key);
    ///
    /// let _ = public_key.to_pem_pkcs1_with_config(EncodeConfig {
    ///     line_ending: LineEnding::CRLF,
    /// });
    /// ```
    fn to_pem_pkcs1_with_config(&self, config: EncodeConfig) -> Result<String> {
        let pem = pem::Pem {
            tag: String::from(Self::PKCS1_HEADER),
            contents: self.to_pkcs1()?,
        };
        Ok(pem::encode_config(&pem, config))
    }

    /// Converts a Public key into `PKCS8` encoded bytes in pem format.
    ///
    /// Encodes the key with the header:
    /// `-----BEGIN PUBLIC KEY-----`
    ///
    /// # Example
    ///
    /// ```
    /// use rsa::{RSAPrivateKey, RSAPublicKey, PublicKeyPemEncoding};
    /// use rand::rngs::OsRng;
    ///
    /// let mut rng = OsRng;
    /// let bits = 2048;
    /// let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    /// let public_key = RSAPublicKey::from(&private_key);
    ///
    /// let _ = public_key.to_pem_pkcs8();
    /// ```
    fn to_pem_pkcs8(&self) -> Result<String> {
        self.to_pem_pkcs8_with_config(DEFAULT_ENCODING_CONFIG)
    }

    /// Converts a Public key into `PKCS8` encoded bytes in pem format with encoding config.
    ///
    /// # Example
    /// ```
    /// use rsa::{RSAPrivateKey, RSAPublicKey, PublicKeyPemEncoding};
    /// # use rand::rngs::OsRng;
    /// use pem::{EncodeConfig, LineEnding};
    /// # let mut rng = OsRng;
    /// # let bits = 2048;
    /// # let private_key = RSAPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
    /// # let public_key = RSAPublicKey::from(&private_key);
    ///
    /// let _ = public_key.to_pem_pkcs8_with_config(EncodeConfig {
    ///     line_ending: LineEnding::CRLF,
    /// });
    /// ```
    fn to_pem_pkcs8_with_config(&self, config: EncodeConfig) -> Result<String> {
        let pem = pem::Pem {
            tag: String::from(Self::PKCS8_HEADER),
            contents: self.to_pkcs8()?,
        };
        Ok(pem::encode_config(&pem, config))
    }
}

#[cfg(feature = "pem")]
impl PublicKeyPemEncoding for RSAPublicKey {
    const PKCS1_HEADER: &'static str = "RSA PUBLIC KEY";
}

fn to_bigint(value: &crate::BigUint) -> simple_asn1::BigInt {
    // TODO can be switched if simple_asn1 BigInt type is updated
    // This is not very clean because of the exports available from simple_asn1
    simple_asn1::BigInt::from_signed_bytes_le(&value.to_bigint().unwrap().to_signed_bytes_le())
}

/// Trait for encoding the private key in the PKCS#1/PKCS#8 format
///
/// Important: Encoding multi prime keys isn't supported. See [RustCrypto/RSA#66](https://github.com/RustCrypto/RSA/issues/66) for more info
pub trait PrivateKeyEncoding {
    /// Encodes a Private key to into `PKCS1` bytes.
    ///
    /// This data will be `base64` encoded which would be used
    /// following a `-----BEGIN <name> PRIVATE KEY-----` header.
    ///
    /// <https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem>
    fn to_pkcs1(&self) -> Result<Vec<u8>>;

    /// Encodes a Private key to into `PKCS8` bytes.
    ///
    /// This data will be `base64` encoded which would be used
    /// following a `-----BEGIN PRIVATE KEY-----` header.
    ///
    /// <https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem>
    fn to_pkcs8(&self) -> Result<Vec<u8>>;
}

impl PrivateKeyEncoding for RSAPrivateKey {
    fn to_pkcs1(&self) -> Result<Vec<u8>> {
        // Check if the key is multi prime
        if self.primes.len() > 2 {
            return Err(Error::EncodeError {
                reason: "multi prime key encoding isn't supported. see RustCrypto/RSA#66".into(),
            });
        }

        // Version 0 = "regular" (two prime) key
        // Version 1 = multi prime key
        let version = ASN1Block::Integer(0, to_bigint(&BigUint::zero()));
        let n = ASN1Block::Integer(0, to_bigint(&self.n()));
        let e = ASN1Block::Integer(0, to_bigint(&self.e()));
        let d = ASN1Block::Integer(0, to_bigint(&self.d));
        let mut blocks = vec![version, n, e, d];

        // Encode primes
        blocks.extend(
            self.primes
                .iter()
                .take(2)
                .map(|p| ASN1Block::Integer(0, to_bigint(p))),
        );
        // Encode exponents
        blocks.extend(self.primes.iter().take(2).map(|p| {
            let exponent = &self.d % (p - 1u8);
            ASN1Block::Integer(0, to_bigint(&exponent))
        }));
        // Encode coefficient
        let coefficient =
            (&self.primes[1])
                .mod_inverse(&self.primes[0])
                .ok_or(Error::EncodeError {
                    reason: "mod inverse failed".into(),
                })?;
        blocks.push(ASN1Block::Integer(
            0,
            BigInt::from_signed_bytes_le(&coefficient.to_signed_bytes_le()),
        ));

        to_der(&ASN1Block::Sequence(0, blocks)).map_err(|e| Error::EncodeError {
            reason: format!("failed to encode ASN.1 sequence of blocks: {}", e),
        })
    }

    fn to_pkcs8(&self) -> Result<Vec<u8>> {
        let version = ASN1Block::Integer(0, to_bigint(&BigUint::zero()));
        let oid = ASN1Block::ObjectIdentifier(0, rsa_oid());
        let alg = ASN1Block::Sequence(0, vec![oid, ASN1Block::Null(0)]);
        let octet_string = ASN1Block::OctetString(0, self.to_pkcs1()?);
        let blocks = vec![version, alg, octet_string];

        to_der(&ASN1Block::Sequence(0, blocks)).map_err(|e| Error::EncodeError {
            reason: format!("failed to encode ASN.1 sequence of blocks: {}", e),
        })
    }
}

pub trait PublicKeyEncoding: PublicKey {
    /// Encodes a Public key to into `PKCS1` bytes.
    ///
    /// This data will be `base64` encoded which would be used
    /// following a `-----BEGIN <name> PUBLIC KEY-----` header.
    ///
    /// <https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem>
    fn to_pkcs1(&self) -> Result<Vec<u8>> {
        let n = ASN1Block::Integer(0, to_bigint(&self.n()));
        let e = ASN1Block::Integer(0, to_bigint(&self.e()));
        let blocks = vec![n, e];

        to_der(&ASN1Block::Sequence(0, blocks)).map_err(|e| Error::EncodeError {
            reason: format!("failed to encode ASN.1 sequence of blocks: {}", e),
        })
    }
    /// Encodes a Public key to into `PKCS8` bytes.
    ///
    /// This data will be `base64` encoded which would be used
    /// following a `-----BEGIN PUBLIC KEY-----` header.
    ///
    /// <https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem>
    fn to_pkcs8(&self) -> Result<Vec<u8>> {
        let oid = ASN1Block::ObjectIdentifier(0, rsa_oid());
        let alg = ASN1Block::Sequence(0, vec![oid, ASN1Block::Null(0)]);

        let bz = self.to_pkcs1()?;
        let octet_string = ASN1Block::BitString(0, bz.len() * BYTE_BIT_SIZE, bz);
        let blocks = vec![alg, octet_string];

        to_der(&ASN1Block::Sequence(0, blocks)).map_err(|e| Error::EncodeError {
            reason: format!("failed to encode ASN.1 sequence of blocks: {}", e),
        })
    }
}

impl PublicKeyEncoding for RSAPublicKey {}

#[cfg(all(test, feature = "pem"))]
mod tests {
    use super::{EncodeConfig, LineEnding, PrivateKeyPemEncoding, PublicKeyPemEncoding};
    use crate::{RSAPrivateKey, RSAPublicKey};
    use rand::thread_rng;
    use rand::SeedableRng;
    use rand_xorshift::XorShiftRng;
    use std::convert::TryFrom;

    #[test]
    fn priv_pem_encoding_pkcs8() {
        const PKCS8_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----\nMFQCAQAwDQYJKoZIhvcNAQEBBQAEQDA+AgEAAgkAkbIIzU1MDAMCAwEAAQIJAIwM\nfAIR0ioBAgUAwQEBAQIFAMFACQMCAwMEAQIEAd9X9wIFALtFdt8=\n-----END PRIVATE KEY-----\n";
        let mut rng = XorShiftRng::from_seed([1; 16]);
        let key = RSAPrivateKey::new(&mut rng, 64).expect("failed to generate key");
        let pem_str = key
            .to_pem_pkcs8()
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS8_PRIVATE_KEY);
    }
    #[test]
    fn priv_pem_encoding_pkcs1() {
        const PKCS1_PRIVATE_KEY: &str = "-----BEGIN RSA PRIVATE KEY-----\nMD4CAQACCQCRsgjNTUwMAwIDAQABAgkAjAx8AhHSKgECBQDBAQEBAgUAwUAJAwID\nAwQBAgQB31f3AgUAu0V23w==\n-----END RSA PRIVATE KEY-----\n";
        let mut rng = XorShiftRng::from_seed([1; 16]);
        let key = RSAPrivateKey::new(&mut rng, 64).expect("failed to generate key");
        let pem_str = key
            .to_pem_pkcs1()
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS1_PRIVATE_KEY);
    }

    #[test]
    fn pub_pem_encoding_pkcs8() {
        const PKCS8_PUBLIC_KEY: &str = "-----BEGIN PUBLIC KEY-----\nMCQwDQYJKoZIhvcNAQEBBQADEwAwEAIJAJGyCM1NTAwDAgMBAAE=\n-----END PUBLIC KEY-----\n";
        let mut rng = XorShiftRng::from_seed([1; 16]);
        let key = RSAPrivateKey::new(&mut rng, 64)
            .expect("failed to generate key")
            .to_public_key();
        let pem_str = key
            .to_pem_pkcs8()
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS8_PUBLIC_KEY);
    }

    #[test]
    fn pub_pem_encoding_pkcs1() {
        const PKCS1_PUBLIC_KEY: &str = "-----BEGIN RSA PUBLIC KEY-----\nMBACCQCRsgjNTUwMAwIDAQAB\n-----END RSA PUBLIC KEY-----\n";

        let mut rng = XorShiftRng::from_seed([1; 16]);
        let key = RSAPrivateKey::new(&mut rng, 64)
            .expect("failed to generate key")
            .to_public_key();
        let pem_str = key
            .to_pem_pkcs1()
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS1_PUBLIC_KEY);
    }

    #[test]
    fn symmetric_private_key_encoding_pkcs1() {
        let mut rng = thread_rng();
        let key = RSAPrivateKey::new(&mut rng, 128).unwrap();
        let pem2 = pem::parse(key.to_pem_pkcs1().unwrap()).expect("pem::parse failed");
        let key2 = RSAPrivateKey::try_from(pem2).expect("RSAPrivateKey::try_from failed");
        assert_eq!(key, key2);
    }

    #[test]
    fn symmetric_private_key_encoding_pkcs8() {
        let mut rng = thread_rng();
        let key = RSAPrivateKey::new(&mut rng, 128).unwrap();
        let pem2 = pem::parse(key.to_pem_pkcs8().unwrap()).expect("pem::parse failed");
        let key2 = RSAPrivateKey::try_from(pem2).expect("RSAPrivateKey::try_from failed");
        assert_eq!(key, key2);
    }

    #[test]
    fn symmetric_public_key_encoding_pkcs1() {
        let mut rng = thread_rng();
        let key = RSAPrivateKey::new(&mut rng, 128).unwrap().to_public_key();
        let pem2 = pem::parse(key.to_pem_pkcs1().unwrap()).expect("pem::parse failed");
        let key2 = RSAPublicKey::try_from(pem2).expect("RSAPublicKey::try_from failed");
        assert_eq!(key, key2);
    }

    #[test]
    fn symmetric_public_key_encoding_pkcs8() {
        let mut rng = thread_rng();
        let key = RSAPrivateKey::new(&mut rng, 128).unwrap().to_public_key();
        let pem2 = pem::parse(key.to_pem_pkcs8().unwrap()).expect("pem::parse failed");
        let key2 = RSAPublicKey::try_from(pem2).expect("RSAPublicKey::try_from failed");
        assert_eq!(key, key2);
    }

    #[test]
    fn pem_encoding_config() {
        const PKCS8_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----\r\nMFQCAQAwDQYJKoZIhvcNAQEBBQAEQDA+AgEAAgkAkbIIzU1MDAMCAwEAAQIJAIwM\r\nfAIR0ioBAgUAwQEBAQIFAMFACQMCAwMEAQIEAd9X9wIFALtFdt8=\r\n-----END PRIVATE KEY-----\r\n";
        const PKCS8_PUBLIC_KEY: &str = "-----BEGIN PUBLIC KEY-----\r\nMCQwDQYJKoZIhvcNAQEBBQADEwAwEAIJAJGyCM1NTAwDAgMBAAE=\r\n-----END PUBLIC KEY-----\r\n";
        let mut rng = XorShiftRng::from_seed([1; 16]);
        let key = RSAPrivateKey::new(&mut rng, 64).expect("failed to generate key");
        let pub_key = key.to_public_key();
        let pem_str = key
            .to_pem_pkcs8_with_config(EncodeConfig {
                line_ending: LineEnding::CRLF,
            })
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS8_PRIVATE_KEY);
        let pem_str = pub_key
            .to_pem_pkcs8_with_config(EncodeConfig {
                line_ending: LineEnding::CRLF,
            })
            .expect("failed to encode private key to pem string");
        assert_eq!(pem_str, PKCS8_PUBLIC_KEY);
    }
}