feat: v1.2.2, optimize codes

This commit is contained in:
2023-12-09 20:33:18 +08:00
parent 9b735f8e48
commit af7bf60869
9 changed files with 41 additions and 58 deletions

2
Cargo.lock generated
View File

@@ -1700,7 +1700,7 @@ dependencies = [
[[package]]
name = "tiny-encrypt"
version = "1.2.1"
version = "1.2.2"
dependencies = [
"aes-gcm-stream",
"base64",

View File

@@ -1,6 +1,6 @@
[package]
name = "tiny-encrypt"
version = "1.2.1"
version = "1.2.2"
edition = "2021"
license = "MIT"
description = "A simple and tiny file encrypt tool"

View File

@@ -41,13 +41,13 @@ use crate::wrap_key::WrapKey;
pub struct CmdDecrypt {
/// Files need to be decrypted
pub paths: Vec<PathBuf>,
/// PIN
/// PGP or PIV PIN
#[arg(long, short = 'p')]
pub pin: Option<String>,
/// KeyID
#[arg(long, short = 'k')]
pub key_id: Option<String>,
/// Slot
/// PIV slot
#[arg(long, short = 's')]
pub slot: Option<String>,
/// Remove source file
@@ -68,7 +68,7 @@ pub struct CmdDecrypt {
/// Edit file
#[arg(long, short = 'E')]
pub edit_file: bool,
// Readonly
/// Readonly mode
#[arg(long)]
pub readonly: bool,
/// Digest algorithm (sha1, sha256[default], sha384, sha512 ...)

View File

@@ -52,8 +52,8 @@ pub struct CmdEncrypt {
/// Remove source file
#[arg(long, short = 'R')]
pub remove_file: bool,
/// Create file
#[arg(long)]
/// Create file (create a empty encrypted file)
#[arg(long, short = 'a')]
pub create: bool,
/// Disable compress meta
#[arg(long)]
@@ -285,7 +285,7 @@ fn encrypt_envelops(cryptor: Cryptor, key: &[u8], envelops: &[&TinyEncryptConfig
fn encrypt_envelop_ecdh(cryptor: Cryptor, key: &[u8], envelop: &TinyEncryptConfigEnvelop) -> XResult<TinyEncryptEnvelop> {
let public_key_point_hex = &envelop.public_part;
let (shared_secret, ephemeral_spki) = util_p256::compute_shared_secret(public_key_point_hex)?;
let (shared_secret, ephemeral_spki) = util_p256::compute_p256_shared_secret(public_key_point_hex)?;
let enc_type = match cryptor {
Cryptor::Aes256Gcm => ENC_AES256_GCM_P256,
Cryptor::ChaCha20Poly1305 => ENC_CHACHA20_POLY1305_P256,

View File

@@ -18,19 +18,19 @@ use crate::util_enc_file;
#[derive(Debug, Args)]
pub struct CmdExecEnv {
/// PIN
/// PGP or PIV PIN
#[arg(long, short = 'p')]
pub pin: Option<String>,
/// KeyID
#[arg(long, short = 'k')]
pub key_id: Option<String>,
/// Slot
/// PIV slot
#[arg(long, short = 's')]
pub slot: Option<String>,
// Tiny encrypt file name
/// Tiny encrypt file name
pub file_name: String,
// Arguments
pub arguments: Vec<String>,
/// Command and arguments
pub command_arguments: Vec<String>,
}
impl Drop for CmdExecEnv {
@@ -43,7 +43,7 @@ pub fn exec_env(cmd_exec_env: CmdExecEnv) -> XResult<()> {
util_msg::set_logger_std_out(false);
debugging!("Cmd exec env: {:?}", cmd_exec_env);
let config = TinyEncryptConfig::load(TINY_ENC_CONFIG_FILE).ok();
if cmd_exec_env.arguments.is_empty() {
if cmd_exec_env.command_arguments.is_empty() {
return simple_error!("No commands assigned.");
}
@@ -75,7 +75,7 @@ pub fn exec_env(cmd_exec_env: CmdExecEnv) -> XResult<()> {
let decrypted_content = decrypt_limited_content_to_vec(&mut file_in, &meta, cryptor, &key_nonce)?;
let exit_code = if let Some(output) = decrypted_content {
debugging!("Outputs: {}", output);
let arguments = &cmd_exec_env.arguments;
let arguments = &cmd_exec_env.command_arguments;
let envs = parse_output_to_env(&output);
let mut command = Command::new(&arguments[0]);

View File

@@ -9,14 +9,14 @@ use crate::util_keychainkey;
use crate::util_keychainstatic;
#[derive(Debug, Args)]
pub struct CmdKeychainKey {
pub struct CmdInitKeychain {
/// Secure Enclave
#[arg(long, short = 'S')]
pub secure_enclave: bool,
// /// Keychain name, or default
// #[arg(long, short = 'c')]
// pub keychain_name: Option<String>,
/// Service name, or tiny-encrypt
/// Service name, or default: tiny-encrypt
#[arg(long, short = 's')]
pub server_name: Option<String>,
/// Key name
@@ -27,19 +27,19 @@ pub struct CmdKeychainKey {
#[allow(dead_code)]
const DEFAULT_SERVICE_NAME: &str = "tiny-encrypt";
pub fn keychain_key(cmd_keychain_key: CmdKeychainKey) -> XResult<()> {
if cmd_keychain_key.secure_enclave {
pub fn keychain_key(cmd_init_keychain: CmdInitKeychain) -> XResult<()> {
if cmd_init_keychain.secure_enclave {
#[cfg(feature = "secure-enclave")]
return keychain_key_se(cmd_keychain_key);
return keychain_key_se(cmd_init_keychain);
#[cfg(not(feature = "secure-enclave"))]
return simple_error!("Feature secure-enclave is not built");
} else {
keychain_key_static(cmd_keychain_key)
keychain_key_static(cmd_init_keychain)
}
}
#[cfg(feature = "secure-enclave")]
pub fn keychain_key_se(cmd_keychain_key: CmdKeychainKey) -> XResult<()> {
pub fn keychain_key_se(cmd_init_keychain: CmdInitKeychain) -> XResult<()> {
if !util_keychainkey::is_support_se() {
return simple_error!("Secure enclave is not supported.");
}
@@ -49,7 +49,7 @@ pub fn keychain_key_se(cmd_keychain_key: CmdKeychainKey) -> XResult<()> {
let config_envelop = TinyEncryptConfigEnvelop {
r#type: TinyEncryptEnvelopType::KeyP256,
sid: cmd_keychain_key.key_name.clone(),
sid: cmd_init_keychain.key_name.clone(),
kid: format!("keychain:02{}", &public_key_compressed_hex),
desc: Some("Keychain Secure Enclave".to_string()),
args: Some(vec![
@@ -63,10 +63,10 @@ pub fn keychain_key_se(cmd_keychain_key: CmdKeychainKey) -> XResult<()> {
Ok(())
}
pub fn keychain_key_static(cmd_keychain_key: CmdKeychainKey) -> XResult<()> {
let service_name = cmd_keychain_key.server_name.as_deref().unwrap_or(DEFAULT_SERVICE_NAME);
pub fn keychain_key_static(cmd_init_keychain: CmdInitKeychain) -> XResult<()> {
let service_name = cmd_init_keychain.server_name.as_deref().unwrap_or(DEFAULT_SERVICE_NAME);
let sec_keychain = opt_result!(SecKeychain::default(), "Get keychain failed: {}");
let key_name = opt_value_result!(&cmd_keychain_key.key_name, "Key name is required.");
let key_name = opt_value_result!(&cmd_init_keychain.key_name, "Key name is required.");
if sec_keychain.find_generic_password(service_name, key_name).is_ok() {
return simple_error!("Static x25519 exists: {}.{}", service_name, &key_name);
}

View File

@@ -20,9 +20,9 @@ pub use cmd_info::CmdInfo;
pub use cmd_info::info;
pub use cmd_info::info_single;
#[cfg(feature = "macos")]
pub use cmd_initkeychainkey::CmdKeychainKey;
pub use cmd_initkeychain::CmdInitKeychain;
#[cfg(feature = "macos")]
pub use cmd_initkeychainkey::keychain_key;
pub use cmd_initkeychain::keychain_key;
pub use cmd_version::CmdVersion;
pub use cmd_version::version;
@@ -56,7 +56,7 @@ mod cmd_decrypt;
mod cmd_encrypt;
mod cmd_directdecrypt;
#[cfg(feature = "macos")]
mod cmd_initkeychainkey;
mod cmd_initkeychain;
#[cfg(feature = "macos")]
mod util_keychainstatic;
#[cfg(feature = "decrypt")]

View File

@@ -9,7 +9,7 @@ use tiny_encrypt::CmdDecrypt;
#[cfg(feature = "decrypt")]
use tiny_encrypt::CmdExecEnv;
#[cfg(feature = "macos")]
use tiny_encrypt::CmdKeychainKey;
use tiny_encrypt::CmdInitKeychain;
#[derive(Debug, Parser)]
#[command(name = "tiny-encrypt-rs")]
@@ -31,21 +31,21 @@ enum Commands {
/// Direct decrypt file(s)
#[command(arg_required_else_help = true)]
DirectDecrypt(CmdDirectDecrypt),
/// Show file info
/// Show tiny encrypt file info
#[command(arg_required_else_help = true, short_flag = 'I')]
Info(CmdInfo),
#[cfg(feature = "macos")]
/// Keychain Key [pending implementation]
#[command(arg_required_else_help = true, short_flag = 'k')]
KeychainKey(CmdKeychainKey),
/// Init Keychain (Secure Enclave or Static)
#[command(arg_required_else_help = true, short_flag = 'K')]
InitKeychain(CmdInitKeychain),
#[cfg(feature = "decrypt")]
/// Execute env
/// Execute environment
#[command(arg_required_else_help = true, short_flag = 'X')]
ExecEnv(CmdExecEnv),
/// Show version
#[command(short_flag = 'v')]
Version(CmdVersion),
/// Show Config
/// Show configuration
#[command(short_flag = 'c')]
Config(CmdConfig),
}
@@ -59,7 +59,7 @@ fn main() -> XResult<()> {
Commands::DirectDecrypt(cmd_direct_decrypt) => tiny_encrypt::direct_decrypt(cmd_direct_decrypt),
Commands::Info(cmd_info) => tiny_encrypt::info(cmd_info),
#[cfg(feature = "macos")]
Commands::KeychainKey(cmd_keychain_key) => tiny_encrypt::keychain_key(cmd_keychain_key),
Commands::InitKeychain(cmd_keychain_key) => tiny_encrypt::keychain_key(cmd_keychain_key),
#[cfg(feature = "decrypt")]
Commands::ExecEnv(cmd_exec_env) => tiny_encrypt::exec_env(cmd_exec_env),
Commands::Version(cmd_version) => tiny_encrypt::version(cmd_version),

View File

@@ -1,28 +1,11 @@
use p256::{EncodedPoint, PublicKey};
use p256::ecdh::EphemeralSecret;
use p256::elliptic_curve::sec1::FromEncodedPoint;
use p256::pkcs8::EncodePublicKey;
use rand::rngs::OsRng;
use rust_util::{opt_result, XResult};
use p256::pkcs8::EncodePublicKey;
use p256::{EncodedPoint, PublicKey};
use p256::elliptic_curve::sec1::FromEncodedPoint;
// use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
// #[derive(Debug)]
// pub struct EphemeralKeyBytes(EncodedPoint);
//
// impl EphemeralKeyBytes {
// pub fn from_public_key(epk: &PublicKey) -> Self {
// EphemeralKeyBytes(epk.to_encoded_point(true))
// }
//
// pub fn decompress(&self) -> EncodedPoint {
// // EphemeralKeyBytes is a valid compressed encoding by construction.
// let p = PublicKey::from_encoded_point(&self.0).unwrap();
// p.to_encoded_point(false)
// }
// }
pub fn compute_shared_secret(public_key_point_hex: &str) -> XResult<(Vec<u8>, Vec<u8>)> {
pub fn compute_p256_shared_secret(public_key_point_hex: &str) -> XResult<(Vec<u8>, Vec<u8>)> {
let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}");
let encoded_point = opt_result!(EncodedPoint::from_bytes(public_key_point_bytes), "Parse public key point failed: {}");
let public_key = PublicKey::from_encoded_point(&encoded_point).unwrap();