feat: pgp decrypt

This commit is contained in:
2021-07-18 10:56:48 +08:00
parent 1d1e0ada87
commit 24449711e9
11 changed files with 131 additions and 14 deletions

61
src/pgpcarddecrypt.rs Normal file
View File

@@ -0,0 +1,61 @@
use clap::{ArgMatches, SubCommand, App, Arg};
use crate::cmd::{Command, CommandError};
use openpgp_card::DecryptMe;
use std::collections::BTreeMap;
pub struct CommandImpl;
impl Command for CommandImpl {
fn name(&self) -> &str { "pgp-card-decrypt" }
fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("OpenPGP Card List subcommand")
.arg(Arg::with_name("pass").short("p").long("pass").takes_value(true).default_value("123456").help("OpenPGP card password"))
.arg(Arg::with_name("cipher").short("c").long("cipher").takes_value(true).help("Cipher text HEX"))
.arg(Arg::with_name("cipher-base64").short("b").long("cipher-base64").takes_value(true).help("Cipher text base64"))
.arg(Arg::with_name("json").long("json").help("JSON output"))
}
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let json_output = sub_arg_matches.is_present("json");
if json_output {
rust_util::util_msg::set_logger_std_out(false);
}
let pass = sub_arg_matches.value_of("pass");
let pass = match pass {
Some(p) => p,
None => return simple_error!("Pass must be assigned"),
};
let cipher = sub_arg_matches.value_of("cipher");
let cipher_base64 = sub_arg_matches.value_of("cipher-base64");
let mut json = BTreeMap::<&'_ str, String>::new();
let cipher_bytes = if let Some(cipher) = cipher {
opt_result!(hex::decode(cipher), "Decode cipher failed: {}")
} else if let Some(cipher_base64) = cipher_base64 {
opt_result!(base64::decode(cipher_base64), "Decode cipher-base64 failed: {}")
} else {
return simple_error!("cipher or cipher-base64 must assign one");
};
let user = crate::pgpcardutil::get_card_user_sw1_82(pass)?;
let text = user.decrypt(DecryptMe::RSA(&cipher_bytes))?;
success!("Clear text HEX: {}", hex::encode(&text));
success!("Clear text base64: {}", base64::encode(&text));
success!("Clear text UTF-8: {}", String::from_utf8_lossy(&text));
if json_output {
json.insert("cipher_hex", hex::encode(&cipher_bytes));
json.insert("cipher_base64", base64::encode(&cipher_bytes));
json.insert("text_hex", hex::encode(&text));
json.insert("text_utf8", String::from_utf8_lossy(&text).to_string());
}
if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap());
}
Ok(())
}
}