feat: pendig simple encrypt/decrypt

This commit is contained in:
2024-11-16 21:59:36 +08:00
parent d6e1f96207
commit 6a07360dc1
3 changed files with 86 additions and 1 deletions

View File

@@ -0,0 +1,78 @@
use crate::config::TinyEncryptConfig;
use crate::consts::TINY_ENC_CONFIG_FILE;
use clap::Args;
use rust_util::{debugging, failure, iff, information, opt_result, simple_error, success, util_size, warning, XResult};
use serde::Serialize;
use std::process::exit;
#[derive(Debug, Args)]
pub struct CmdSimpleEncrypt {
/// Encryption profile (use default when --key-filter is assigned)
#[arg(long, short = 'p')]
pub profile: Option<String>,
/// Encryption key filter (key_id or type:TYPE(e.g. ecdh, pgp, ecdh-p384, pgp-ed25519), multiple joined by ',', ALL for all)
#[arg(long, short = 'k')]
pub key_filter: Option<String>,
}
#[derive(Serialize)]
pub struct CmdResult {
pub code: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
}
impl CmdResult {
pub fn fail(code: i32, message: &str) -> Self {
Self {
code,
message: Some(message.to_string()),
result: None,
}
}
pub fn success(result: &str) -> Self {
Self {
code: 0,
message: None,
result: Some(result.to_string()),
}
}
pub fn print_exit(&self) {
let result = serde_json::to_string_pretty(self).unwrap();
println!("{}", result);
exit(self.code);
}
}
pub fn simple_encrypt(cmd_encrypt: CmdSimpleEncrypt) -> XResult<()> {
if let Err(inner_result_error) = inner_simple_encrypt(cmd_encrypt) {
CmdResult::fail(-1, &format!("{}", inner_result_error)).print_exit();
}
Ok(())
}
pub fn inner_simple_encrypt(cmd_encrypt: CmdSimpleEncrypt) -> XResult<()> {
let config = TinyEncryptConfig::load(TINY_ENC_CONFIG_FILE)?;
debugging!("Found tiny encrypt config: {:?}", config);
let envelops = config.find_envelops(&cmd_encrypt.profile, &cmd_encrypt.key_filter)?;
if envelops.is_empty() { return simple_error!("Cannot find any valid envelops"); }
debugging!("Found envelops: {:?}", envelops);
let envelop_tkids: Vec<_> = envelops.iter()
.map(|e| format!("{}:{}", e.r#type.get_name(), e.kid))
.collect();
debugging!("Matched {} envelop(s): \n- {}", envelops.len(), envelop_tkids.join("\n- "));
if envelop_tkids.is_empty() {
return simple_error!("no matched envelops found");
}
// TODO ...
Ok(())
}