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
#[macro_use]
extern crate lazy_static;
use failure::Fail;
use std::sync::RwLock;
mod decrypt;
mod encrypt;
pub mod prelude;
#[cfg(test)]
mod test;

pub use self::{decrypt::decode_ekey, encrypt::encode_ekey};

pub type Result<T> = std::result::Result<T, failure::Error>;

pub trait Encrypted {
    fn ekey(&self) -> Result<String>;
}

pub trait Decrypted {
    fn dkey(&self, ekey: &str) -> Result<u64>;
}

#[derive(Default)]
pub struct Config {
    secret_key: Option<String>,
    secret_key_bytes: Vec<u8>,
}

lazy_static! {
    pub(crate) static ref CONFIG: RwLock<Config> = RwLock::new(Config::default());
}

pub fn init_encrypt_conf(secret_key: &str) {
    let mut conf = CONFIG.write().unwrap();
    conf.secret_key = Some(secret_key.to_string());
    conf.secret_key_bytes = secret_key.as_bytes().to_owned();
}

#[derive(Fail, Debug)]
pub enum Error {
    #[fail(display = "Encryption error: {:?}", _0)]
    Encrypt(crypto::symmetriccipher::SymmetricCipherError),

    #[fail(display = "Decryption error: {:?}", _0)]
    Decrypt(crypto::symmetriccipher::SymmetricCipherError),

    #[fail(display = "Invalid input")]
    InvalidInput,

    #[fail(display = "CRC mismatch")]
    CRCMismatch,

    #[fail(display = "SecretKey is none in encrypt config, initialize config first")]
    SecretKeyNotFound,
}