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
/*
 * 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.
 */

//! # Importer
//!
//! The importer module is used to import keys from files.
//!
//! The file passed to the importer must be JSON that matches the expected structure.
//!
//! Currently RSA and EC (SECP256K1) keys can be imported.
//!
//! ## Examples
//! This example will use an RSA key as an example but other keys should
//! use the same process. Examples will be provided if this is not the case.
//! Alternative functions will be listed at the end of the example.
//! ```
//! # use activeledger::key::import;
//! let rsa_key_path = "/path/to/key.json";
//!
//! # let rsa_key_path = "./testfiles/rsa.json";
//!
//! let rsa = import::import_rsa(&rsa_key_path).unwrap();
//! ```
//! The other functions for key importing are:
//!
//! ```
//! # use activeledger::key::import;
//! # let ec_key_path = "./testfiles/ec.json";
//! import::import_ec(ec_key_path).unwrap();
//! ```
//!
//! ## File Structure
//! The file you import should have the following structure, otherwise the import will fail.
//! ```JSON
//! {
//!     "name":"",
//!     "type":"",
//!     "pem": {
//!        "private": "",
//!        "public":""
//!     }
//! }
//! ```

extern crate serde_json;

use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::str;

use crate::key::Pkcs8pem;

use super::error::{KeyError, KeyResult};
use super::EllipticCurve;
use super::RSA;

struct ImportData {
    name: String,
    pkcs8pem: Pkcs8pem,
}

/// Import an RSA key from the specified file.
///
/// The document must be a JSON file of the expected structure else importing will fail.
/// An template of the structure is provided below if you are importing a file not exported
/// from this SDK.
///
/// # Example
/// ```
/// use activeledger::key::import;
///
/// let rsa_key_path = "/path/to/key.json";
/// # let rsa_key_path = "./testfiles/rsa.json";
/// let rsa = import::import_rsa(&rsa_key_path).unwrap();
/// ```
///
/// ## File Structure
/// The file you import should have the following structure, otherwise the import will fail.
/// ```JSON
/// {
///     "name":"",
///     "type":"",
///     "pem": {
///        "private": "",
///        "public":""
///     }
/// }
/// ```
pub fn import_rsa(path: &str) -> KeyResult<RSA> {
    let rsa_data = import(path, "\"rsa\"")?;

    Ok(RSA::create_from_pem(&rsa_data.name, &rsa_data.pkcs8pem))
}

/// Import an EC (SECP256K1) key from the specified file.
///
/// The document must be a JSON file of the expected structure else importing will fail.
/// An template of the structure is provided below if you are importing a file not exported
/// from this SDK.
///
/// # Example
/// ```
/// use activeledger::key::import;
/// let ec_key_path = "/path/to/key.json";
/// # let ec_key_path = "./testfiles/ec.json";
///
/// let ec = import::import_ec(&ec_key_path).unwrap();
/// ```
///
/// ## File Structure
/// The file you import should have the following structure, otherwise the import will fail.
/// ```JSON
/// {
///     "name":"",
///     "type":"",
///     "pem": {
///        "private": "",
///        "public":""
///     }
/// }
/// ```
pub fn import_ec(path: &str) -> KeyResult<EllipticCurve> {
    let ec_data = import(path, "\"ec\"")?;

    Ok(EllipticCurve::create_from_pem(
        &ec_data.name,
        &ec_data.pkcs8pem,
    ))
}

/// Handle opening the file and returning the contents as JSON
fn import(path: &str, expected_type: &str) -> KeyResult<ImportData> {
    let path = Path::new(path);

    let mut file = match File::open(&path) {
        Ok(file) => file,
        Err(_) => return Err(KeyError::ImportError(4000)),
    };

    let mut contents = String::new();

    match file.read_to_string(&mut contents) {
        Ok(_) => (),
        Err(_) => return Err(KeyError::ImportError(4001)),
    };

    let data_obj: serde_json::Value = match serde_json::from_str(&contents) {
        Ok(json) => json,
        Err(_) => return Err(KeyError::ImportError(4001)),
    };

    let name = match data_obj["name"].as_str() {
        Some(data) => data,
        None => return Err(KeyError::ImportError(4001)),
    };

    let pem_public = match data_obj["pem"]["public"].as_str() {
        Some(data) => data,
        None => return Err(KeyError::ImportError(4001)),
    };

    let pem_private = match data_obj["pem"]["private"].as_str() {
        Some(data) => data,
        None => return Err(KeyError::ImportError(4001)),
    };

    if data_obj["type"].to_string() != expected_type {
        return Err(KeyError::ImportError(4002));
    }

    let pkcs8pem = Pkcs8pem {
        public: pem_public.to_string(),
        private: pem_private.to_string(),
    };

    Ok(ImportData {
        name: name.to_string(),
        pkcs8pem,
    })
}

#[cfg(test)]
mod tests {
    use crate::key::import;

    #[test]
    fn import_rsa() {
        import::import_rsa("./testfiles/rsa.json").unwrap();
    }

    #[test]
    fn import_ec() {
        import::import_ec("./testfiles/ec.json").unwrap();
    }
}