feat: add rand, update decrypt

This commit is contained in:
2023-09-09 17:54:20 +08:00
parent bc55d84978
commit c1dd71abc2
4 changed files with 23 additions and 12 deletions

View File

@@ -1,7 +1,8 @@
use std::path::PathBuf;
use clap::Args;
use rust_util::{debugging, simple_error, XResult};
use rand::random;
use rust_util::{debugging, failure, simple_error, success, XResult};
use crate::config::{TinyEncryptConfig, TinyEncryptConfigEnvelop};
use crate::spec::{TinyEncryptEnvelop, TinyEncryptEnvelopType};
@@ -13,6 +14,8 @@ pub struct CmdEncrypt {
pub paths: Vec<PathBuf>,
// Comment
pub comment: Option<String>,
// Comment
pub encrypted_comment: Option<String>,
// Encryption profile
pub profile: Option<String>,
}
@@ -20,16 +23,23 @@ pub struct CmdEncrypt {
pub fn encrypt(cmd_encrypt: CmdEncrypt) -> XResult<()> {
let config = TinyEncryptConfig::load(TINY_ENC_CONFIG_FILE)?;
let envelops = config.find_envelops(&cmd_encrypt.profile);
if envelops.is_empty() {
return simple_error!("Cannot find any valid envelops");
}
if envelops.is_empty() { return simple_error!("Cannot find any valid envelops"); }
let (key, nonce) = make_key_and_nonce();
debugging!("Cmd encrypt: {:?}", cmd_encrypt);
for path in &cmd_encrypt.paths {
match encrypt_single(path, &envelops) {
Ok(_) => success!("Encrypt {} succeed", path.to_str().unwrap_or("N/A")),
Err(e) => failure!("Encrypt {} failed: {}", path.to_str().unwrap_or("N/A"), e),
}
}
Ok(())
}
fn encrypt_single(path: &PathBuf, envelops: &[&TinyEncryptConfigEnvelop]) -> XResult<()> {
let (key, nonce) = make_key256_and_nonce();
let envelops = encrypt_envelops(&key, &envelops)?;
debugging!("Envelops: {:?}", envelops);
println!("Cmd encrypt: {:?}", cmd_encrypt);
Ok(())
}
@@ -68,10 +78,8 @@ fn encrypt_envelop_pgp(key: &[u8], envelop: &TinyEncryptConfigEnvelop) -> XResul
})
}
fn make_key_and_nonce() -> (Vec<u8>, Vec<u8>) {
// TODO use random
let key = [0u8; 32];
let nonce = [0u8; 12];
fn make_key256_and_nonce() -> (Vec<u8>, Vec<u8>) {
let key: [u8; 32] = random();
let nonce: [u8; 12] = random();
(key.into(), nonce.into())
}