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
/*
 * MIT License (MIT)
 * Copyright (c) 2019 Activeledger
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

//! # RSA Key
//!
//! This module is used to generate or injest an RSA key,
//! used to sign transactions.
//!
//! ## Examples
//! ### Create a new key
//! ```
//! # use activeledger::key::RSA;
//! let rsa_key = RSA::new("keyname").unwrap();
//! ```
//!
//! ### Use an existing PEM to create a key object
//! ```
//! # use activeledger::key::RSA;
//! # use activeledger::key::Pkcs8pem;
//! # let pem = Pkcs8pem::new("", "");
//! // The PEM must be of type Pkcs8pem
//! let rsa_key = RSA::create_from_pem("keyname", &pem);
//! ```
//!
//! ### Sign data
//! ```
//! # use activeledger::key::RSA;
//! let rsa_key = RSA::new("keyname").unwrap();
//!
//! let signature = rsa_key.sign("<Data to sign>").unwrap();
//! ```
//!
//! ### Verify signed data
//! ```
//! # use activeledger::key::RSA;
//! let rsa_key = RSA::new("keyname").unwrap();
//!
//! let signature = rsa_key.sign("<Data to sign>").unwrap();
//!
//! let verification_result = rsa_key.verify("<Data to sign>", &signature).unwrap();
//! ```
//!
//! ### Get a stringified version of the keys PEM
//! ```
//! # use activeledger::key::RSA;
//! let rsa_key = RSA::new("keyname").unwrap();
//!
//! // Get a Pkcs8pem object containing the public private pems as strings
//! let pem = rsa_key.get_pem();
//! ```

extern crate openssl;

use std::str;

use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa as openssl_rsa;

use crate::key::Pkcs8pem;

use super::{KeyError, KeyResult};

#[path = "int_def.rs"]
mod int_def;
use int_def::{Pkcs8pemBytes, Signing};

#[derive(Clone)]
pub struct RSA {
    pub name: String,
    pkcs8pem: Pkcs8pemBytes,
}

// Public functions
impl RSA {
    /// Generate a new RSA key
    ///
    /// # Example
    /// ```
    /// # use activeledger::key::RSA;
    /// let rsa_key = RSA::new("Key name").unwrap();
    /// ```
    pub fn new(name: &str) -> KeyResult<RSA> {
        let pkcs8pem = match RSA::generate() {
            Ok(pem) => pem,
            Err(error) => return Err(error),
        };

        Ok(RSA {
            name: String::from(name),
            pkcs8pem,
        })
    }

    /// Create a new key using a given PEM
    ///
    /// # Example
    /// ```
    /// # use activeledger::key::RSA;
    /// # use activeledger::key::Pkcs8pem;
    /// # let pem = Pkcs8pem::new("", "");
    /// let rsa_key = RSA::create_from_pem("NAME", &pem);
    /// ```
    pub fn create_from_pem(name: &str, pem: &Pkcs8pem) -> RSA {
        // Use the given pem to recreate a keypair
        let pkcs8pem = Pkcs8pemBytes::new(
            pem.private.to_string().as_bytes(),
            pem.public.to_string().as_bytes(),
        );

        RSA {
            name: String::from(name),
            pkcs8pem,
        }
    }

    /// Sign the given data
    ///
    /// # Example
    /// ```
    /// # use activeledger::key::RSA;
    /// let rsa = RSA::new("keyname").unwrap();
    ///
    /// let signature = rsa.sign("Data to sign").unwrap();
    /// ```
    pub fn sign(&self, data: &str) -> KeyResult<String> {
        let keypair = self.get_keypair()?;

        let signature = Signing::sign(&keypair, &data)?;

        Ok(signature)
    }

    /// Verify a signature against some data
    ///
    /// # Example
    /// ```
    /// # use activeledger::key::RSA;
    /// let rsa = RSA::new("keyname").unwrap();
    ///
    /// let data_to_sign = String::from("Data to sign");
    /// let signature: String = rsa.sign(&data_to_sign).unwrap();
    ///
    /// let verify: bool = rsa.verify(&data_to_sign, &signature).unwrap();
    /// ```
    pub fn verify(&self, data: &str, signature: &str) -> KeyResult<bool> {
        let keypair = self.get_keypair()?;

        let verification = Signing::verify(&keypair, &data, &signature)?;

        Ok(verification)
    }

    /// Get a keys PEM as string values
    ///
    /// # Example
    /// ```
    /// # use activeledger::key::RSA;
    /// # use activeledger::key::Pkcs8pem;
    /// let rsa = RSA::new("keyname").unwrap();
    ///
    /// let pem: Pkcs8pem = rsa.get_pem().unwrap();
    /// ```
    pub fn get_pem(&self) -> KeyResult<Pkcs8pem> {
        let private_pem = match str::from_utf8(&self.pkcs8pem.private) {
            Ok(pem) => pem,
            Err(_) => return Err(KeyError::StringifyError(3000)),
        };

        let public_pem = match str::from_utf8(&self.pkcs8pem.public) {
            Ok(pem) => pem,
            Err(_) => return Err(KeyError::StringifyError(3001)),
        };

        Ok(Pkcs8pem {
            private: private_pem.to_string(),
            public: public_pem.to_string(),
        })
    }
}

// Private functions

impl RSA {
    /// Generate the PEM of the RSA keypair
    fn generate() -> KeyResult<Pkcs8pemBytes> {
        // Generate the keypair with openssl
        let rsa = match openssl_rsa::generate(2048) {
            Ok(rsa) => rsa,
            Err(_) => return Err(KeyError::GenerationError(1004)),
        };

        // Get the private key PEM
        let private = match rsa.private_key_to_pem() {
            Ok(bytes) => bytes,
            Err(_) => return Err(KeyError::GenerationError(1005)),
        };

        // Get the public key PEM
        let public = match rsa.public_key_to_pem() {
            Ok(bytes) => bytes,
            Err(_) => return Err(KeyError::GenerationError(1006)),
        };

        Ok(Pkcs8pemBytes::new(&private, &public))
    }

    /// Get the PEM keypair in their byte form
    fn get_keypair(&self) -> KeyResult<PKey<Private>> {
        // Generate private key from pem
        let keypair = match openssl_rsa::private_key_from_pem(&self.pkcs8pem.private) {
            Ok(keypair) => keypair,
            Err(_) => return Err(KeyError::SigningError(2007)),
        };

        // Handle the public key
        let keypair = match PKey::from_rsa(keypair) {
            Ok(keypair) => keypair,
            Err(_) => return Err(KeyError::SigningError(2008)),
        };

        Ok(keypair)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rsa_gen() {
        use std::time::Instant;
        let start = Instant::now();
        let key = RSA::new("Test").unwrap();
        let duration = start.elapsed();

        let start2 = Instant::now();
        let pem = key.get_pem().unwrap();
        let duration_of_pem_stringification = start2.elapsed();
        let overall_duration = start.elapsed();

        println!(
            "Private PEM: \n{}\n Public PEM: \n{}\n",
            pem.private, pem.public
        );
        println!("RSA Generation time: {:?}", duration);
        println!(
            "RSA PEM stringification time: {:?}",
            duration_of_pem_stringification
        );
        println!("RSA Overall time: {:?}", overall_duration);
    }

    #[test]
    fn rsa_sign() {
        let sig_data = String::from("I am test data");

        let key = RSA::new("Test").unwrap();

        let signature = key.sign(&sig_data).unwrap();
        println!("Sig {}", signature);

        println!(
            "Verification: {:?}",
            key.verify(&sig_data, &signature).unwrap()
        );

        assert!(key.verify(&sig_data, &signature).unwrap());
    }
}