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
//! Read and Write PEM files from RSA types
//!
//! This library will be useless after the next release of the RSA crate, which should have this
//! functionality baked in.
//!
//! ### Examples
//! ```rust
//! use rsa_pem::KeyExt;
//! use rsa::RSAPrivateKey;
//! #
//! # let mut rng = rand::thread_rng();
//! # let private_key = RSAPrivateKey::new(&mut rng, 2048).unwrap();
//!
//! let pkcs8_string = private_key.to_pem_pkcs8().unwrap();
//! let private_key = RSAPrivateKey::from_pem_pkcs8(&pkcs8_string).unwrap();
//! ```
use num_bigint_dig::{BigInt, BigUint, Sign};
use thiserror::Error;

mod private;
mod public;

const RSA_OID: [u64; 7] = [1, 2, 840, 113549, 1, 1, 1];

/// Extensions to keys for formatting and reading PKCS1 and PKCS8 PEM strings
pub trait KeyExt {
    /// Write a PKCS8 pem string
    fn to_pem_pkcs8(&self) -> Result<String, KeyError>;

    /// Read a PKCS8 pem string
    fn from_pem_pkcs8(pem: &str) -> Result<Self, KeyError>
    where
        Self: Sized;

    /// Write a PKCS1 pem string
    fn to_pem_pkcs1(&self) -> Result<String, KeyError>;

    /// Read a PKCS1 pem string
    fn from_pem_pkcs1(pem: &str) -> Result<Self, KeyError>
    where
        Self: Sized;
}

/// Errors produced when serializing or deserializing keys
#[derive(Clone, Debug, Error)]
pub enum KeyError {
    /// The PEM wrapper has the wrong name
    #[error("Invalid key kind supplied")]
    Kind,

    /// The file isn't PEM encoded
    #[error("Key not PEM-formatted")]
    Pem,

    /// Parsing the DER bytes failed
    #[error("Error parsing key, {}", .0)]
    Parse(#[from] yasna::ASN1Error),

    /// The private key's fields don't make sense
    #[error("Constructed key is invalid")]
    Validate,

    /// Failed to serialize to DER bytes
    #[error("Could not serialize key")]
    Serialize,
}

fn to_dig(biguint: &num_bigint::BigUint) -> num_bigint_dig::BigUint {
    BigUint::from_bytes_be(&biguint.to_bytes_be())
}

fn from_dig(biguint: &BigUint) -> num_bigint::BigUint {
    num_bigint::BigUint::from_bytes_be(&biguint.to_bytes_be())
}

fn int_from_dig(bigint: &BigInt) -> num_bigint::BigInt {
    let (sign, bytes) = bigint.to_bytes_be();
    num_bigint::BigInt::from_bytes_be(sign_from_dig(sign), &bytes)
}

fn sign_from_dig(sign: Sign) -> num_bigint::Sign {
    match sign {
        Sign::Minus => num_bigint::Sign::Minus,
        Sign::NoSign => num_bigint::Sign::NoSign,
        Sign::Plus => num_bigint::Sign::Plus,
    }
}

#[cfg(test)]
mod tests {
    use crate::KeyExt;
    use rsa::{hash::Hashes, padding::PaddingScheme, PublicKey, RSAPrivateKey, RSAPublicKey};
    use sha2::{Digest, Sha256};

    static SIGNING_STRING: &[u8] = b"Hewwo, Mr Obama";
    static HASH: Option<&Hashes> = Some(&Hashes::SHA2_256);
    static PADDING: PaddingScheme = PaddingScheme::PKCS1v15;

    #[test]
    fn priv_can_complete_cycle_pkcs1() {
        let mut rng = rand::thread_rng();
        let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
        let hashed = Sha256::digest(SIGNING_STRING);
        let sig = rsa.sign(PADDING, HASH, &hashed).unwrap();

        let string = rsa.to_pem_pkcs1().unwrap();

        let res = RSAPrivateKey::from_pem_pkcs1(&string);

        let pubkey = res.unwrap().to_public_key();
        pubkey.verify(PADDING, HASH, &hashed, &sig).unwrap();
    }

    #[test]
    fn pub_can_complete_cycle_pkcs1() {
        let mut rng = rand::thread_rng();
        let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
        let hashed = Sha256::digest(SIGNING_STRING);
        let sig = rsa.sign(PADDING, HASH, &hashed).unwrap();

        let rsa = rsa.to_public_key();
        let string = rsa.to_pem_pkcs1().unwrap();

        let res = RSAPublicKey::from_pem_pkcs1(&string);

        let pubkey = res.unwrap();
        pubkey.verify(PADDING, HASH, &hashed, &sig).unwrap();
    }

    #[test]
    fn priv_can_complete_cycle_pkcs8() {
        let mut rng = rand::thread_rng();
        let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
        let hashed = Sha256::digest(SIGNING_STRING);
        let sig = rsa.sign(PADDING, HASH, &hashed).unwrap();

        let string = rsa.to_pem_pkcs8().unwrap();

        let res = RSAPrivateKey::from_pem_pkcs8(&string);

        let pubkey = res.unwrap().to_public_key();
        pubkey.verify(PADDING, HASH, &hashed, &sig).unwrap();
    }

    #[test]
    fn pub_can_complete_cycle_pkcs8() {
        let mut rng = rand::thread_rng();
        let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
        let hashed = Sha256::digest(SIGNING_STRING);
        let sig = rsa.sign(PADDING, HASH, &hashed).unwrap();

        let rsa = rsa.to_public_key();
        let string = rsa.to_pem_pkcs8().unwrap();

        let res = RSAPublicKey::from_pem_pkcs8(&string);

        let pubkey = res.unwrap();
        pubkey.verify(PADDING, HASH, &hashed, &sig).unwrap();
    }
}