Skip to content

Commit 91dfea3

Browse files
committed
Migrate away from Path towards PathBuf, see rust-lang/rust#23286
1 parent 8d655c5 commit 91dfea3

File tree

4 files changed

+50
-51
lines changed

4 files changed

+50
-51
lines changed

src/bin.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ fn retrieve_private_key(sk: Option<PathBuf>, generate: bool) -> Result<Vec<u8>,
7474
let seckey_path = sk;
7575

7676
if generate && seckey_path.is_none() {
77-
let skey = keys::generate_private_key();
77+
let skey = keys::generate_private_key()?;
7878
log::info!("Generating Private Key: {:02x?}", skey.iter().format(""));
7979
Ok(skey)
8080
}
@@ -95,7 +95,7 @@ fn retrieve_private_key(sk: Option<PathBuf>, generate: bool) -> Result<Vec<u8>,
9595
}),
9696
};
9797

98-
get_private_key(&path, callback)
98+
get_private_key(path.to_owned(), callback)
9999
}
100100
}
101101

@@ -111,7 +111,7 @@ fn build_recipients(recipient_pk: &[PathBuf], sk: &[u8]) -> Result<HashSet<Keys>
111111
Ok(Keys {
112112
method: 0,
113113
privkey: sk.to_vec(),
114-
recipient_pubkey: get_public_key(Path::new(pk))?,
114+
recipient_pubkey: get_public_key(PathBuf::from(pk))?,
115115
})
116116
})
117117
.collect()
@@ -138,7 +138,7 @@ fn run_encrypt(sk: Option<PathBuf>, recipient_pk: &[PathBuf], range: Option<Stri
138138

139139
fn run_decrypt(sk: Option<PathBuf>, sender_pk: Option<PathBuf>, range: Option<String>) -> Result<(), Crypt4GHError> {
140140
let sender_pubkey = match sender_pk {
141-
Some(path) => Some(keys::get_public_key(&path)?),
141+
Some(path) => Some(keys::get_public_key(path)?),
142142
None => None,
143143
};
144144

@@ -193,13 +193,13 @@ fn run_reencrypt(sk: Option<PathBuf>, recipient_pk: &[PathBuf], trim: bool) -> R
193193
crypt4gh::reencrypt(&keys, &recipient_keys, &mut io::stdin(), &mut io::stdout(), trim)
194194
}
195195

196-
fn run_keygen(sk: &Path, pk: &Path, comment: Option<String>, nocrypt: bool, force: bool) -> Result<(), Crypt4GHError> {
196+
fn run_keygen(sk: PathBuf, pk: PathBuf, comment: Option<String>, nocrypt: bool, force: bool) -> Result<(), Crypt4GHError> {
197197
// Prepare key files
198198

199199
let seckey = sk;
200-
let pubkey = &pk;
200+
let pubkey = pk;
201201

202-
for key in &[seckey, pubkey] {
202+
for key in &[seckey, pubkey.to_owned()] {
203203
// If key exists and it is a file
204204
if key.is_file() {
205205
// Force overwrite?
@@ -221,6 +221,7 @@ fn run_keygen(sk: &Path, pk: &Path, comment: Option<String>, nocrypt: bool, forc
221221
// Comment
222222
let comment = comment;
223223
let do_crypt = !nocrypt;
224+
224225
let passphrase_callback = move || {
225226
if do_crypt {
226227
prompt_password(format!("Passphrase for {}: ", seckey.display()))
@@ -263,7 +264,7 @@ fn run() -> Result<(), Crypt4GHError> {
263264
comment,
264265
nocrypt,
265266
force,
266-
} => run_keygen(&sk, &pk, comment, nocrypt, force)?,
267+
} => run_keygen(sk, pk, comment, nocrypt, force)?,
267268
}
268269

269270
Ok(())

src/error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub enum Crypt4GHError {
2828
#[error("Invalid key format")]
2929
InvalidKeyFormat,
3030
#[error("Invalid PEM file length. The file ({0:?}) is not 3 lines long")]
31-
InvalidPEMFormatLength(&'static Path),
31+
InvalidPEMFormatLength(PathBuf),
3232
#[error("Invalid PEM file header or footer: -----BEGIN or -----END")]
3333
InvalidPEMHeaderOrFooter,
3434
#[error("Invalid SSH key format")]

src/keys.rs

Lines changed: 39 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,11 @@
22
#![warn(rustdoc::missing_doc_code_examples)]
33

44
use aes::cipher::{StreamCipher, generic_array::GenericArray};
5-
use rand::{SeedableRng, Rng};
6-
use rand_chacha;
75

86
use std::collections::HashMap;
97
use std::fs::File;
108
use std::io::{BufRead, BufReader, Cursor, Read, Write, BufWriter};
11-
use std::path::Path;
12-
use std::sync::Arc;
9+
use std::path::PathBuf;
1310

1411
use base64::engine::general_purpose;
1512
use base64::Engine;
@@ -57,9 +54,8 @@ lazy_static! {
5754
.collect();
5855
}
5956

60-
fn read_lines<P>(filename: P) -> Result<Vec<String>, Crypt4GHError>
57+
fn read_lines(filename: &PathBuf) -> Result<Vec<String>, Crypt4GHError>
6158
where
62-
P: AsRef<Path>,
6359
{
6460
let file = File::open(filename)?;
6561
Ok(BufReader::new(file)
@@ -68,13 +64,14 @@ where
6864
.collect())
6965
}
7066

71-
fn load_from_pem(filepath: &'static Path) -> Result<Vec<u8>, Crypt4GHError> {
67+
fn load_from_pem(filepath: &PathBuf) -> Result<Vec<u8>, Crypt4GHError> {
7268
// Read lines
73-
let lines = read_lines(filepath).map_err(|e| Crypt4GHError::ReadLinesError(filepath.into(), e.into()))?;
69+
let lines = read_lines(&filepath)
70+
.map_err(|e| Crypt4GHError::ReadLinesError(filepath.to_owned(), Box::new(e)))?;
7471

7572
// Check format
7673
if lines.len() < 3 {
77-
return Err(Crypt4GHError::InvalidPEMFormatLength(filepath));
74+
return Err(Crypt4GHError::InvalidPEMFormatLength(filepath.into()));
7875
}
7976

8077
if lines.first().unwrap().starts_with("-----BEGIN ") ||
@@ -83,7 +80,7 @@ fn load_from_pem(filepath: &'static Path) -> Result<Vec<u8>, Crypt4GHError> {
8380
}
8481

8582
// Decode with base64
86-
general_purpose::STANDARD.decode(&lines[1..lines.len() - 1].join("")).map_err(|e| Crypt4GHError::BadBase64Error(e.into()))
83+
general_purpose::STANDARD.decode(&lines[1..lines.len() - 1].join("")).map_err(move |e| Crypt4GHError::BadBase64Error(e.into()))
8784
}
8885

8986
fn decode_string_ssh(stream: &mut impl BufRead) -> Result<Vec<u8>, Crypt4GHError> {
@@ -124,9 +121,10 @@ fn derive_key(
124121
match alg {
125122
"scrypt" => {
126123
// TODO: Review last param of ScryptParams (length of what, exactly?) carefully.
124+
// TODO: Why is the output not used?
127125
// Added "dklen" for now since it seemed fitting, but needs proper review.
128126
let params = scrypt::Params::new(14, 8, 1, dklen);
129-
scrypt::scrypt(
127+
let _ = scrypt::scrypt(
130128
passphrase.as_bytes(),
131129
&salt.unwrap_or_else(|| {
132130
log::warn!("Using default salt = [0_u8; 8]");
@@ -137,7 +135,7 @@ fn derive_key(
137135
);
138136
},
139137
"bcrypt" => {
140-
bcrypt_pbkdf::bcrypt_pbkdf(
138+
let _ = bcrypt_pbkdf::bcrypt_pbkdf(
141139
passphrase.as_bytes(),
142140
&salt.unwrap_or_else(|| {
143141
log::warn!("Using default salt = [0_u8; 8]");
@@ -335,7 +333,8 @@ fn decipher(ciphername: &str, data: &[u8], private_ciphertext: &[u8]) -> Result<
335333
assert!((private_ciphertext.len() % block_size(ciphername)?) == 0);
336334

337335
// Decipher
338-
match ciphername {
336+
// TODO: Why is this match not used? Was it used upstream?
337+
let _ = match ciphername {
339338
"aes128-ctr" => {
340339
type Aes128Ctr = ctr::Ctr128LE<aes::Aes128>;
341340
let iv_ga = GenericArray::from_slice(iv);
@@ -425,41 +424,40 @@ fn get_skpk_from_decrypted_private_blob(blob: &[u8]) -> Result<([u8; 32], [u8; 3
425424
/// or if the key is not one of the two supported formats. Returns the decode key.
426425
/// If the key is encrypted, the `callback` should return the passphrase of the key.
427426
pub fn get_private_key(
428-
key_path: &Path,
427+
key_path: PathBuf,
429428
callback: impl Fn() -> Result<String, Crypt4GHError>,
430429
) -> Result<Vec<u8>, Crypt4GHError> {
431-
todo!();
432-
// let data = load_from_pem(key_path)?;
433-
434-
// if data.starts_with(C4GH_MAGIC_WORD) {
435-
// log::info!("Loading a Crypt4GH private key");
436-
// let mut stream = BufReader::new(data.as_slice());
437-
// stream
438-
// .read_exact(&mut [0_u8; C4GH_MAGIC_WORD.len()])
439-
// .map_err(|e| Crypt4GHError::ReadMagicWord(e.into()))?;
440-
// parse_c4gh_private_key(stream, callback)
441-
// }
442-
// else if data.starts_with(SSH_MAGIC_WORD) {
443-
// log::info!("Loading an OpenSSH private key");
444-
// let mut stream = BufReader::new(data.as_slice());
445-
// stream
446-
// .read_exact(&mut [0_u8; SSH_MAGIC_WORD.len()])
447-
// .map_err(|e| Crypt4GHError::ReadMagicWord(e.into()))?;
448-
// let (seckey, pubkey) = parse_ssh_private_key(stream, callback)?;
449-
// Ok(vec![seckey, pubkey].concat())
450-
// }
451-
// else {
452-
// Err(Crypt4GHError::InvalidKeyFormat)
453-
// }
430+
let data = load_from_pem(&key_path)?;
431+
432+
if data.starts_with(C4GH_MAGIC_WORD) {
433+
log::info!("Loading a Crypt4GH private key");
434+
let mut stream = BufReader::new(data.as_slice());
435+
stream
436+
.read_exact(&mut [0_u8; C4GH_MAGIC_WORD.len()])
437+
.map_err(|e| Crypt4GHError::ReadMagicWord(e.into()))?;
438+
parse_c4gh_private_key(stream, callback)
439+
}
440+
else if data.starts_with(SSH_MAGIC_WORD) {
441+
log::info!("Loading an OpenSSH private key");
442+
let mut stream = BufReader::new(data.as_slice());
443+
stream
444+
.read_exact(&mut [0_u8; SSH_MAGIC_WORD.len()])
445+
.map_err(|e| Crypt4GHError::ReadMagicWord(e.into()))?;
446+
let (seckey, pubkey) = parse_ssh_private_key(stream, callback)?;
447+
Ok(vec![seckey, pubkey].concat())
448+
}
449+
else {
450+
Err(Crypt4GHError::InvalidKeyFormat)
451+
}
454452
}
455453

456454
/// Reads and decodes the public key stored in `key_path`.
457455
///
458456
/// It supports `Crypt4GH` and OpenSSH public keys. Fails if it can not read the file
459457
/// or if the key is not one of the two supported formats. Returns the decoded key.
460-
pub fn get_public_key(key_path: &Path) -> Result<Vec<u8>, Crypt4GHError> {
458+
pub fn get_public_key(key_path: PathBuf) -> Result<Vec<u8>, Crypt4GHError> {
461459
// Read lines from public key file
462-
match read_lines(key_path) {
460+
match read_lines(&key_path) {
463461
Ok(lines_vec) => {
464462
// Empty key
465463
if lines_vec.is_empty() {
@@ -537,8 +535,8 @@ pub fn generate_private_key() -> Result<Vec<u8>, Crypt4GHError> {
537535
/// The passphrase callback should return a string that will be used to encode the keys. You can add
538536
/// an optional comment at the end of the keys.
539537
pub fn generate_keys(
540-
seckey: &Path,
541-
pubkey: &Path,
538+
seckey: PathBuf,
539+
pubkey: PathBuf,
542540
passphrase_callback: impl Fn() -> Result<String, Crypt4GHError>,
543541
comment: Option<String>,
544542
) -> Result<(), Crypt4GHError> {

tests/edit_list_gen.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::io::Write;
55
use std::path::Path;
66

77
use rand::Rng;
8-
use sodiumoxide::crypto::aead::chacha20poly1305_ietf;
8+
//use sodiumoxide::crypto::aead::chacha20poly1305_ietf;
99

1010
pub fn generate(sk: &str, recipient_pk: &str, input: &str, outfile: &mut File, passphrase: &str) {
1111
let mut rng = rand::thread_rng();

0 commit comments

Comments
 (0)