use std::collections::BTreeMap; use clap::{ArgMatches, SubCommand, App, Arg}; use openpgp_card::DecryptMe; use rust_util::util_clap::{Command, CommandError}; 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 Decrypt 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_opt = sub_arg_matches.value_of("pass"); let pass = opt_value_result!(pass_opt, "Pass must be assigned"); if pass.len() < 6 { return simple_error!("Pass length:{}, must >= 6!", pass.len()); } let cipher = sub_arg_matches.value_of("cipher"); let cipher_base64 = sub_arg_matches.value_of("cipher-base64"); 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 { let mut json = BTreeMap::<&'_ str, String>::new(); 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_base64", base64::encode(&text)); json.insert("text_utf8", String::from_utf8_lossy(&text).to_string()); println!("{}", serde_json::to_string_pretty(&json).unwrap()); } Ok(None) } }