diff --git a/src/cli/algotest.rs b/src/cli/algotest.rs index 1ea4139..0a13119 100644 --- a/src/cli/algotest.rs +++ b/src/cli/algotest.rs @@ -143,7 +143,7 @@ pub fn run(path: &str, bundle_size: usize, chunker: ChunkerType, compression: Op if encrypt { println!(); - let (public, secret) = gen_keypair(); + let (public, secret) = Crypto::gen_keypair(); let mut crypto = Crypto::dummy(); crypto.add_secret_key(public, secret); let encryption = (EncryptionMethod::Sodium, public[..].to_vec().into()); diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 4c3058d..c547bec 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -281,7 +281,7 @@ pub fn run() -> Result<(), ErrorCode> { hash: hash }, remote_path), "create repository", ErrorCode::CreateRepository); if encryption { - let (public, secret) = gen_keypair(); + let (public, secret) = Crypto::gen_keypair(); info!("Created the following key pair"); println!("public: {}", to_hex(&public[..])); println!("secret: {}", to_hex(&secret[..])); @@ -589,7 +589,7 @@ pub fn run() -> Result<(), ErrorCode> { } }, Arguments::GenKey{file} => { - let (public, secret) = gen_keypair(); + let (public, secret) = Crypto::gen_keypair(); info!("Created the following key pair"); println!("public: {}", to_hex(&public[..])); println!("secret: {}", to_hex(&secret[..])); @@ -603,7 +603,7 @@ pub fn run() -> Result<(), ErrorCode> { checked!(Crypto::load_keypair_from_file(file), "load key pair", ErrorCode::LoadKey) } else { info!("Created the following key pair"); - let (public, secret) = gen_keypair(); + let (public, secret) = Crypto::gen_keypair(); println!("public: {}", to_hex(&public[..])); println!("secret: {}", to_hex(&secret[..])); (public, secret) diff --git a/src/util/encryption.rs b/src/util/encryption.rs index d350ab9..64b3849 100644 --- a/src/util/encryption.rs +++ b/src/util/encryption.rs @@ -2,16 +2,29 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::io; use std::fs::{self, File}; +use std::sync::{Once, ONCE_INIT}; use serde_yaml; use serde::bytes::ByteBuf; +use sodiumoxide; use sodiumoxide::crypto::sealedbox; -pub use sodiumoxide::crypto::box_::{SecretKey, PublicKey, gen_keypair}; +use sodiumoxide::crypto::box_; +pub use sodiumoxide::crypto::box_::{SecretKey, PublicKey}; use ::util::*; +static INIT: Once = ONCE_INIT; + +fn sodium_init() { + INIT.call_once(|| { + if !sodiumoxide::init() { + panic!("Failed to initialize sodiumoxide"); + } + }); +} + quick_error!{ #[derive(Debug)] pub enum EncryptionError { @@ -108,10 +121,12 @@ pub struct Crypto { impl Crypto { #[inline] pub fn dummy() -> Self { + sodium_init(); Crypto { path: PathBuf::new(), keys: HashMap::new() } } pub fn open>(path: P) -> Result { + sodium_init(); let path = path.as_ref().to_owned(); let mut keys: HashMap = HashMap::default(); for entry in try!(fs::read_dir(&path)) { @@ -190,4 +205,10 @@ impl Crypto { } } } + + #[inline] + pub fn gen_keypair() -> (PublicKey, SecretKey) { + sodium_init(); + box_::gen_keypair() + } }